prvng_core/nulib/lib_provisioning/utils/script-compression.nu

85 lines
2.8 KiB
Text
Raw Normal View History

# Script compression utilities for secure transmission
# Compresses template path, variables, and script as a complete auditable unit
# Compress complete workflow data (template + vars + script)
export def compress-workflow [template_path: string, template_vars: record, script: string]: nothing -> record {
# Create temporary directory
let timestamp_hash = ((date now | format date "%Y%m%d_%H%M%S") | hash sha256 | str substring 0..8)
let temp_dir = $"/tmp/workflow_($timestamp_hash)"
^mkdir -p $temp_dir
# 1. Compress template_vars (JSON)
let vars_file = ($temp_dir + "/vars.json")
let vars_json = ($template_vars | to json)
$vars_json | save -f $vars_file
let vars_original_size = ($vars_json | str length)
# 2. Compress script
let script_file = ($temp_dir + "/script.sh")
$script | save -f $script_file
let script_original_size = ($script | str length)
# 3. Create manifest with template_path
let manifest_file = ($temp_dir + "/manifest.json")
{
template_path: $template_path
timestamp: ((date now) | format date "%Y-%m-%d %H:%M:%S UTC")
} | to json | save -f $manifest_file
# 4. Combine all into single archive
let total_original = ($vars_original_size + $script_original_size)
let archive_file = ($temp_dir + "/workflow.tar.gz")
^tar -czf $archive_file -C $temp_dir manifest.json vars.json script.sh
# 5. Encode to base64
let tar_content = (open -r $archive_file)
let compressed_data = ($tar_content | ^base64)
# Get compressed size using base64 encoded output (approximation)
let compressed_size = ($compressed_data | str length)
# Calculate ratio
let compression_ratio = ($compressed_size / $total_original)
# Cleanup
^rm -rf $temp_dir
{
template_path: $template_path
script_compressed: $compressed_data
script_encoding: "tar+gzip+base64"
original_size: $total_original
compressed_size: $compressed_size
compression_ratio: $compression_ratio
}
}
# Decompress workflow (for verification/testing)
export def decompress-workflow [script_compressed: string]: nothing -> record {
let timestamp_hash = ((date now | format date "%Y%m%d_%H%M%S") | hash sha256 | str substring 0..8)
let temp_dir = $"/tmp/workflow_decompress_($timestamp_hash)"
^mkdir -p $temp_dir
# Decode from base64
let decoded = (echo $script_compressed | ^base64 -d)
# Extract tar.gz
echo $decoded | ^tar -xzf - -C $temp_dir
# Read files
let manifest = (open ($temp_dir + "/manifest.json"))
let vars = (open ($temp_dir + "/vars.json"))
let script = (open -r ($temp_dir + "/script.sh"))
# Cleanup
^rm -rf $temp_dir
{
template_path: $manifest.template_path
template_vars: $vars
script: $script
timestamp: $manifest.timestamp
}
}