Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

wezterm/bugabinga/session_storage.nu

Raw
# Only ciphertext is written to disk; plaintext travels in memory/argv.
def storage-root [] {
    if $nu.os-info.name == 'windows' {
        let base = $env.LOCALAPPDATA? | default ''
        if $base == '' { error make {msg: 'LOCALAPPDATA is missing; cannot locate session storage.'} }
        $base | path join wezterm
    } else {
        let configured = $env.XDG_STATE_HOME? | default ''
        let base = if $configured == '' { $nu.home-path | path join '.local' 'state' } else { $configured }
        $base | path join wezterm
    }
}

def executable [name: string] {
    let found = (which $name)
    if ($found | is-empty) { error make {msg: $'Session save/restore unavailable: ($name) not found in PATH.'} }
    $found | first | get path
}

def checked [result: record, message: string] {
    if $result.exit_code != 0 {
        error make {msg: $'($message) ($result.stderr | str trim)'}
    }
    $result.stdout
}

def protect-directory [root: path] {
    mkdir $root
    if $nu.os-info.name == 'windows' {
        let user = (^whoami | str trim)
        checked (^icacls $root /inheritance:r /grant:r ($user + ':(OI)(CI)F') | complete) 'Cannot restrict session directory permissions.' | ignore
    } else {
        checked (^chmod 700 $root | complete) 'Cannot restrict session directory permissions.' | ignore
    }
}

# Buffers are fetched over the owning GUI socket, not passed in command argv.
def capture-text [node: record] {
    if $node.direction? != null {
        $node | update first { capture-text $node.first } | update second { capture-text $node.second }
    } else if $node.text_source? != null {
        if ($env.WEZTERM_UNIX_SOCKET? | default '') == '' {
            error make {msg: 'Cannot capture history: owning WezTerm socket is unavailable.'}
        }
        let wezterm = (executable wezterm)
        let source = $node.text_source
        let text = (checked (^$wezterm cli --no-auto-start get-text --pane-id $source.pane_id --start-line (0 - $source.rows) | complete) 'Cannot capture pane history.')
        let plain = ($text | str replace --all "\r\n" "\n" | str replace --all --regex '[\x00-\x08\x0B-\x1F\x7F-\x9F]' '')
        $node | reject text_source | insert text $plain
    } else {
        $node
    }
}

def main [operation: string, payload: string = '', --root: path] {
    let age = (executable age)
    let root = if $root == null { storage-root } else { $root }
    let key = ($root | path join session-key.txt)
    let directory = ($root | path join sessions)
    let slot = ($directory | path join last.json.age)
    let previous = ($directory | path join previous.json.age)

    if $operation == 'load' {
        if not ($key | path exists) { error make {msg: $'Session key missing: ($key). Restore the original key; no replacement was generated.'} }
        if not ($slot | path exists) { error make {msg: $'No saved session: ($slot). Use Session → Save first.'} }
        checked (^$age --decrypt --identity $key $slot | complete) 'Session decryption failed.'
    } else if $operation == 'save' {
        # Conservative transport bound: Windows command lines have a 32K UTF-16 limit.
        if ($payload | encode utf-8 | bytes length) > 8192 { error make {msg: 'Session exceeds the 8 KiB snapshot limit; existing save was not changed.'} }
        let snapshot = ($payload | from json)
        # Layout metadata is bounded; captured buffers themselves have no 8 KiB cap.
        let plaintext = if ($snapshot.tabs? | describe) =~ '^list|^table' {
            $snapshot | update tabs { $snapshot.tabs | each {|tab| $tab | update tree { capture-text $tab.tree } } } | to json --raw
        } else { $payload }
        if not ($key | path exists) and (($slot | path exists) or ($previous | path exists)) {
            error make {msg: $'Session key missing: ($key). Existing snapshots preserved; restore the original key.'}
        }
        protect-directory $root
        mkdir $directory
        if not ($key | path exists) {
            let keygen = (executable age-keygen)
            checked (^$keygen --output $key | complete) 'Session key generation failed.' | ignore
            if $nu.os-info.name != 'windows' { ^chmod 600 $key }
        }
        # Encrypt to our own identity, without exposing the private key in argv.
        let pending = ($directory | path join $'.(random uuid).age')
        try {
            checked ($plaintext | ^$age --encrypt --identity $key --output $pending | complete) 'Session encryption failed.' | ignore
            if ($slot | path exists) { cp --force $slot $previous }
            mv --force $pending $slot
        } catch {|err|
            if ($pending | path exists) { rm $pending }
            error make $err
        }
        {path: $slot} | to json --raw
    } else {
        error make {msg: $'Unknown session operation: ($operation)'}
    }
}