ai-remote 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/cli.mjs +8065 -0
  2. package/dist/index.js +6 -6
  3. package/dist/protocols/index.js +2 -2
  4. package/dist/protocols/rdp/caps.js +1 -1
  5. package/dist/protocols/rdp/cert.js +1 -1
  6. package/dist/protocols/rdp/client.js +18 -16
  7. package/dist/protocols/rdp/client.js.map +2 -2
  8. package/dist/protocols/rdp/cliprdr.js +1 -1
  9. package/dist/protocols/rdp/credssp.js +2 -2
  10. package/dist/protocols/rdp/display.js +2 -2
  11. package/dist/protocols/rdp/gcc.js +2 -2
  12. package/dist/protocols/rdp/mcs.js +2 -2
  13. package/dist/protocols/rdp/ntlm.js +2 -2
  14. package/dist/protocols/rdp/pdu.js +1 -1
  15. package/dist/protocols/rdp/rail.js +1 -1
  16. package/dist/protocols/rdp/sec.js +3 -3
  17. package/dist/protocols/rdp/session.js +3 -3
  18. package/dist/protocols/rdp/tls.js +3 -3
  19. package/dist/protocols/rdp/vchannel.js +1 -1
  20. package/dist/protocols/rdp/x224.js +1 -1
  21. package/dist/protocols/ssh/kex.js +1 -1
  22. package/dist/protocols/ssh/session.js +4 -3
  23. package/dist/protocols/ssh/session.js.map +2 -2
  24. package/dist/protocols/ssh/transport.js +8 -6
  25. package/dist/protocols/ssh/transport.js.map +2 -2
  26. package/dist/protocols/vnc/session.js +3 -3
  27. package/dist/shared/connection.js +1 -1
  28. package/dist/shared/hosts.js +1 -1
  29. package/package.json +13 -3
  30. package/src/cli/cli.ts +451 -0
  31. package/src/cli/daemon.ts +291 -0
  32. package/src/cli/framebuffer.ts +115 -0
  33. package/src/cli/generated/viewer-bundle.ts +5 -0
  34. package/src/cli/ipc.ts +78 -0
  35. package/src/cli/paths.ts +28 -0
  36. package/src/cli/png.ts +106 -0
  37. package/src/cli/session.ts +263 -0
  38. package/src/cli/shell.ts +171 -0
  39. package/src/cli/transport.ts +86 -0
  40. package/src/cli/viewer-client/assets.d.ts +4 -0
  41. package/src/cli/viewer-client/main.ts +300 -0
  42. package/src/cli/viewer-page.ts +102 -0
  43. package/src/cli/viewer.ts +269 -0
  44. package/src/cli/wsserver.ts +144 -0
  45. package/src/protocols/rdp/client.ts +9 -1
  46. package/src/protocols/ssh/session.ts +1 -0
  47. package/src/protocols/ssh/transport.ts +15 -2
@@ -1,4 +1,4 @@
1
- import { SshReader, SshWriter, concatBytes, padStart, toBase64, toBase64Url } from "./wire";
1
+ import { SshReader, SshWriter, concatBytes, padStart, toBase64, toBase64Url } from "./wire.js";
2
2
  const subtle = globalThis.crypto?.subtle;
3
3
  const KEX_ALGORITHMS = {
4
4
  "curve25519-sha256": { type: "x25519", hash: "SHA-256" },
@@ -1,6 +1,6 @@
1
- import { MSG, EXTENDED_DATA_STDERR } from "./messages";
2
- import { SshReader, SshWriter, decodeUtf8, encodeUtf8, toBase64 } from "./wire";
3
- import { SshTransport } from "./transport";
1
+ import { MSG, EXTENDED_DATA_STDERR } from "./messages.js";
2
+ import { SshReader, SshWriter, decodeUtf8, encodeUtf8, toBase64 } from "./wire.js";
3
+ import { SshTransport } from "./transport.js";
4
4
  const DEFAULT_PORT = 22;
5
5
  const SERVICE = "ssh-connection";
6
6
  const TERMINAL_TYPE = "xterm-256color";
@@ -110,6 +110,7 @@ class SshSession extends EventTarget {
110
110
  this.waiters = /* @__PURE__ */ new Map();
111
111
  this.transport = new SshTransport(url, {
112
112
  verifyHost: options.verifyHost || (async () => true),
113
+ openTransport: options.openTransport || null,
113
114
  log: (step, detail) => console.info(`[SSH] ${step}`, detail)
114
115
  });
115
116
  this.transport.addEventListener("packet", (event) => {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/protocols/ssh/session.ts"],
4
- "sourcesContent": ["// An SSH session: authentication, one interactive shell channel, and the\n// events a terminal needs to render it.\n//\n// The transport below this owns the cryptography. This module owns the\n// conversation: proving who the user is, asking for a pseudo-terminal, and\n// moving bytes between the shell and the screen.\n\nimport { MSG, EXTENDED_DATA_STDERR } from './messages';\nimport { SshReader, SshWriter, decodeUtf8, encodeUtf8, toBase64 } from './wire';\nimport { SshTransport } from './transport';\n\nexport const DEFAULT_PORT = 22;\n\nconst SERVICE = 'ssh-connection';\nconst TERMINAL_TYPE = 'xterm-256color';\n\n// A shell is not a bulk transfer, so a modest window costs nothing and is\n// topped up long before it runs out.\nconst INITIAL_WINDOW = 2 * 1024 * 1024;\nconst MAX_PACKET = 32 * 1024;\nconst WINDOW_REFILL_THRESHOLD = INITIAL_WINDOW / 2;\n\n/** Terminal modes: only the terminator, so the host keeps its own defaults. */\nconst PTY_MODES = new Uint8Array([0]);\n\n/**\n * How patient `runCommand` is, in three different senses.\n *\n * A single deadline cannot tell \"the shell ignored me\" apart from \"the\n * installer is three minutes into a download\", and a short one turns every\n * real piece of work -- a package install, a build, a large copy -- into a\n * false failure that also leaves the command running on the far side.\n *\n * So the wait is judged by what the shell is doing. It has START_MS to\n * acknowledge the command at all; after that it may take as long as it likes\n * as long as it keeps printing, and only silence longer than IDLE_MS, or a run\n * longer than MAX_MS, is treated as stuck.\n */\nexport const COMMAND_START_MS = 20_000;\nexport const COMMAND_IDLE_MS = 5 * 60_000;\nexport const COMMAND_MAX_MS = 60 * 60_000;\n\n/** Nothing for the terminal to draw, while the framing is being hidden. */\nconst NO_BYTES = new Uint8Array(0);\n\n/**\n * One shell word holding `value` literally.\n *\n * Single quotes suspend every kind of expansion the shell has, so the only\n * character that needs handling is the closing quote itself: the string is left\n * for a moment, an escaped quote is added, and it starts again.\n */\nfunction singleQuote(value) {\n return `'${String(value).replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * The shell a machine answers with, guessed from its prompt.\n *\n * Windows OpenSSH hands out cmd.exe by default, and a POSIX-framed command\n * there does not fail loudly -- it prints `'printf' is not recognized` and\n * leaves the caller waiting for markers that will never come.\n */\nfunction shellFromPrompt(text: string) {\n const tail = text.slice(-400);\n if (/(?:^|\\n)PS [A-Za-z]:\\\\[^\\n]*>\\s*$/.test(tail)) return 'powershell';\n if (/(?:^|\\n)[^\\n]*[A-Za-z]:\\\\[^\\n]*>\\s*$/.test(tail)) return 'cmd';\n return '';\n}\n\n/** A shell saying it has never heard of the command that frames the output. */\nconst FRAMING_REJECTED = /is not recognized as an internal or external command|command not found|not recognized as the name of a cmdlet|CommandNotFoundException/i;\n\n/**\n * The one line that runs `command` and marks where its output starts and ends.\n *\n * Each shell gets its own, because none of the three agree on how to print a\n * string, run a command and read back its exit status.\n */\nexport function frameCommand(family, command: string, id) {\n if (family === 'cmd') {\n // `&` chains unconditionally, and the delayed-expansion problem is dodged\n // by reading ERRORLEVEL through `call`, which re-expands its arguments.\n return `echo.&echo CCB${id}&${command}&call echo.CCE${id} %^ERRORLEVEL%\\r`;\n }\n\n if (family === 'powershell') {\n // A base64 payload keeps a trailing comment, newline or semicolon from\n // swallowing the closing marker. Dot-sourcing the resulting script block\n // also keeps Set-Location and environment changes in this same shell.\n //\n // $LASTEXITCODE is read before $?, because the two answer different\n // questions and only the first one is about the command. $? says whether\n // the dot-source raised an error record, and launching a program that goes\n // on to fail is not an error record: a failing `git`, `msiexec` or nested\n // `powershell.exe` leaves $? True and its own status in $LASTEXITCODE, so\n // asking $? first reports a failed command as exit 0. $LASTEXITCODE is\n // cleared just above, so a non-null value can only have come from a\n // program this command ran, and $? still decides for a payload that ended\n // in a cmdlet and never set it.\n const encoded = toBase64(encodeUtf8(command));\n return `Write-Output \"\"; Write-Output (\"CCB\" + \"${id}\"); `\n + `$__ccCode = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}')); `\n + `$global:LASTEXITCODE = $null; . ([ScriptBlock]::Create($__ccCode)); $__ccOk = $?; `\n + `$__cc = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($__ccOk) { 0 } else { 1 }; `\n + `Write-Output (\"CCE\" + \"${id} \" + $__cc)\\r`;\n }\n\n // `printf '%s%s'` joins the marker inside the shell; `__cc` holds the status\n // so the command's own exit code survives the second printf.\n //\n // It all goes on one line, because an interactive shell echoes each line as\n // it reads it: a second line would be echoed after the command had already\n // printed, landing inside the captured output rather than in front of the\n // opening marker where it can be discarded.\n //\n // The command travels through `eval` as a single quoted word rather than\n // being spliced between the semicolons directly. Spliced in, three ordinary\n // commands break the framing: one ending in `&` puts `&` next to `;`, which\n // is a syntax error; one ending in a newline leaves a bare `;`, likewise; and\n // one ending in `# a comment` swallows the closing marker, so the call only\n // returns when it times out. Inside `eval` the command is a string, so none\n // of it can reach the outer line. `eval` runs in this same shell, so the\n // working directory, the environment and `$?` all still behave as if the\n // user had typed it.\n return `printf '\\\\n%s%s\\\\n' 'CCB' '${id}'; eval ${singleQuote(command)}; `\n + `__cc=$?; printf '\\\\n%s%s %s\\\\n' 'CCE' '${id}' \"$__cc\"\\r`;\n}\n\n/**\n * Plain text from a shell transcript. An interactive shell dresses its output\n * with colour, cursor moves and title changes, none of which mean anything to\n * a model reading the result.\n */\nfunction stripTerminalCodes(text: string) {\n return text\n // OSC sequences (window titles, and iTerm/VS Code shell integration)\n .replace(/\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)/g, '')\n // CSI sequences: colour, cursor movement, erase\n .replace(/\\u001b\\[[0-9;?]*[ -/]*[@-~]/g, '')\n // remaining two-character escapes\n .replace(/\\u001b[@-Z\\\\-_]/g, '')\n // carriage returns a terminal would have overwritten in place\n .replace(/\\r\\n/g, '\\n')\n .replace(/\\r/g, '');\n}\n\n/**\n * The same bytes, minus the scaffolding around a tool command.\n *\n * An interactive shell echoes whatever is typed into it, and what\n * `frameCommand` types is a `printf`-and-`eval` line -- or, in PowerShell, a\n * base64 blob. Left alone it buries the command's own output in the\n * scrollback the user is trying to read. The joined markers are safe to cut\n * on for the same reason `runCommand` finds them: the echoed line contains\n * their halves, never the joined marker itself.\n *\n * Only display is filtered. `detail.bytes` stays exactly what the host sent,\n * because that is what `runCommand` reads the result out of.\n */\nfunction filterDisplay(session, bytes: Uint8Array) {\n const filter = session.displayFilter;\n if (!filter) return bytes;\n\n filter.pending += decodeUtf8(bytes);\n let shown = '';\n\n if (filter.stage === 'before') {\n const at = filter.pending.indexOf(filter.begin);\n if (at === -1) return NO_BYTES; // still inside the echoed wrapper\n filter.pending = filter.pending.slice(at + filter.begin.length).replace(/^\\r?\\n/, '');\n filter.stage = 'inside';\n }\n\n if (filter.stage === 'inside') {\n const at = filter.pending.indexOf(filter.end);\n if (at === -1) {\n shown = filter.pending;\n filter.pending = '';\n return shown ? encodeUtf8(shown) : NO_BYTES;\n }\n shown = filter.pending.slice(0, at);\n filter.pending = filter.pending.slice(at);\n filter.stage = 'closing';\n }\n\n // The closing marker carries the exit status on its own line. Drop that\n // line and hand back everything after it: the prompt the shell draws next\n // belongs to the user again.\n const newline = filter.pending.indexOf('\\n');\n if (newline !== -1) {\n shown += filter.pending.slice(newline + 1);\n session.displayFilter = null;\n }\n return shown ? encodeUtf8(shown) : NO_BYTES;\n}\n\n/**\n * Stop filtering, showing anything held back on the way out.\n *\n * Text held before the opening marker is normally the echoed wrapper, but if\n * the command never started it is the shell explaining why -- the one case\n * where the held text is the whole answer, so it must not be swallowed.\n */\nfunction releaseDisplayFilter(session) {\n const filter = session.displayFilter;\n session.displayFilter = null;\n if (!filter || filter.stage !== 'before' || !filter.pending) return;\n session.dispatchEvent(new CustomEvent('data', {\n detail: { bytes: NO_BYTES, display: encodeUtf8(filter.pending), isStderr: false },\n }));\n}\n\nexport class SshSession extends EventTarget {\n /**\n * @param {string} url gateway WebSocket URL\n * @param {object} options\n * @param {string} options.username\n * @param {string} [options.password]\n * @param {'powershell'} [options.preferredShell]\n * @param {(info: object) => Promise<boolean>} [options.verifyHost]\n * @param {(prompt: object) => Promise<string>} [options.requestInput]\n */\n constructor(url: string, options = {}) {\n super();\n\n this.options = options;\n this.username = options.username || '';\n this.password = options.password || '';\n this.requestInput = options.requestInput || (async () => '');\n this.columns = options.columns || 80;\n this.rows = options.rows || 24;\n\n this.channelId = 0;\n this.remoteChannelId = null;\n this.remoteWindow = 0;\n this.remoteMaxPacket = MAX_PACKET;\n this.localWindow = INITIAL_WINDOW;\n this.pendingWrites = [];\n this.shellOpen = false;\n this.commandInFlight = false;\n /** Set while a tool command runs, to keep its framing off the screen. */\n this.displayFilter = null;\n /** True only after the requested interactive shell is ready for commands. */\n this.readySignaled = false;\n this.powerShellAttempted = false;\n this.powerShellTimer = null;\n /** '', 'posix', 'cmd' or 'powershell'; learned from the prompt. */\n this.shellFamily = '';\n this.promptTail = '';\n this.exitStatus = null;\n this.authMethods = [];\n this.closed = false;\n this.waiters = new Map();\n\n this.transport = new SshTransport(url, {\n verifyHost: options.verifyHost || (async () => true),\n log: (step: number, detail) => console.info(`[SSH] ${step}`, detail),\n });\n\n this.transport.addEventListener('packet', (event) => {\n this.#handlePacket(event.detail.type, event.detail.payload);\n });\n this.transport.addEventListener('greeting', (event) => {\n for (const line of event.detail.lines) this.#emitBanner(`${line}\\r\\n`);\n });\n this.transport.addEventListener('banner', (event) => this.#emitBanner(event.detail.text));\n this.transport.addEventListener('keys', (event) => {\n this.fingerprint = event.detail.fingerprint;\n this.#status('secured', `Host key ${event.detail.fingerprint} verified.`);\n this.dispatchEvent(new CustomEvent('secure', { detail: event.detail }));\n if (event.detail.firstTime) void this.#authenticate();\n });\n this.transport.addEventListener('hostdisconnect', (event) => {\n this.lastMessage = event.detail.reason;\n });\n this.transport.addEventListener('error', (event) => {\n this.lastMessage = event.detail.message;\n this.dispatchEvent(new CustomEvent('error', { detail: event.detail }));\n });\n this.transport.addEventListener('close', (event) => {\n if (this.closed) return;\n this.closed = true;\n clearTimeout(this.powerShellTimer);\n this.#abandonWaiters(event.detail.message || 'The SSH connection closed.');\n this.dispatchEvent(new CustomEvent('close', {\n detail: {\n ...event.detail,\n message: event.detail.message || this.lastMessage || '',\n exitStatus: this.exitStatus,\n },\n }));\n });\n }\n\n connect() {\n this.#status('connecting', 'Opening the SSH transport\u2026');\n this.transport.connect();\n }\n\n disconnect() {\n if (this.closed) return;\n clearTimeout(this.powerShellTimer);\n if (this.shellOpen && this.remoteChannelId !== null) {\n this.transport.send(new SshWriter(8).u8(MSG.CHANNEL_CLOSE).u32(this.remoteChannelId).take());\n }\n this.transport.disconnect('Closed by the user');\n }\n\n /** Send keystrokes, or anything else the terminal produces, to the shell. */\n write(data: Uint8Array) {\n const bytes = typeof data === 'string' ? encodeUtf8(data) : data;\n if (!bytes.length) return;\n this.pendingWrites.push(bytes);\n this.#flushWrites();\n }\n\n /**\n * Run one command in this shell and return what it printed.\n *\n * Deliberately the *same* shell the user is looking at, not a second channel:\n * a command the assistant runs inherits the working directory, the\n * environment and the login the user already has, and it appears in their\n * terminal as it happens. An agent acting on a machine invisibly is worse\n * than an agent that is slower to read.\n *\n * The output is framed by markers rather than measured, because an\n * interactive shell echoes its input and prints a prompt around it. The\n * markers are assembled by the shell from two pieces, so the echoed command\n * line -- which contains the pieces but not the joined marker -- never looks\n * like the real boundary.\n *\n * A `command` event brackets the run so the terminal can label it, and the\n * three deadlines above decide when a command is stuck rather than slow.\n */\n runCommand(command: string, {\n startMs = COMMAND_START_MS,\n idleMs = COMMAND_IDLE_MS,\n maxMs = COMMAND_MAX_MS,\n } = {}) {\n const text = String(command || '').trim();\n if (!text) return Promise.reject(new Error('No command was given.'));\n if (!this.shellOpen || this.closed) {\n return Promise.reject(new Error('The SSH shell is not open.'));\n }\n if (this.readySignaled === false) {\n return Promise.reject(new Error('The SSH shell is still starting.'));\n }\n if (this.commandInFlight) {\n return Promise.reject(new Error('Another command is still running in this shell.'));\n }\n\n const id = Array.from(crypto.getRandomValues(new Uint8Array(6)))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n const begin = `CCB${id}`;\n const end = `CCE${id}`;\n // What the prompt showed, or POSIX until something says otherwise.\n const family = this.shellFamily || 'posix';\n\n this.commandInFlight = true;\n const startedAt = Date.now();\n\n // The wrapper is machinery, not something the user asked to read, so the\n // terminal is shown the command's own output instead of the line that\n // frames it. The announcement below is what marks it in the scrollback.\n this.displayFilter = { begin, end, stage: 'before', pending: '' };\n this.dispatchEvent(new CustomEvent('command', {\n detail: { phase: 'start', id, command: text },\n }));\n\n return new Promise((resolve, reject) => {\n let transcript = '';\n let started = false;\n let startTimer = null;\n let idleTimer = null;\n let maxTimer = null;\n\n const finish = (settle) => {\n clearTimeout(startTimer);\n clearTimeout(idleTimer);\n clearTimeout(maxTimer);\n this.removeEventListener('data', onData);\n this.removeEventListener('close', onClose);\n this.commandInFlight = false;\n releaseDisplayFilter(this);\n settle();\n };\n\n /** End the call, and tell the terminal how it went. */\n const done = (result) => finish(() => {\n this.dispatchEvent(new CustomEvent('command', {\n detail: {\n phase: 'end',\n id,\n command: text,\n exitStatus: result.exitStatus,\n timedOut: result.timedOut,\n started: result.started !== false,\n reason: result.reason,\n durationMs: result.durationMs,\n },\n }));\n resolve(result);\n });\n\n const fail = (error) => finish(() => {\n this.dispatchEvent(new CustomEvent('command', {\n detail: {\n phase: 'end',\n id,\n command: text,\n exitStatus: null,\n timedOut: false,\n started,\n durationMs: Date.now() - startedAt,\n error: error.message,\n },\n }));\n reject(error);\n });\n\n /**\n * What the command has printed so far. Without the opening marker the\n * shell never started it, so the transcript is its echo of the wrapper\n * -- noise, not output.\n */\n const partialOutput = () => {\n const at = transcript.indexOf(begin);\n return at === -1\n ? ''\n : stripTerminalCodes(transcript.slice(at + begin.length)).replace(/^\\r?\\n/, '').replace(/\\s+$/, '');\n };\n\n /** Interrupt whatever is still running, so the shell is usable again. */\n const giveUp = (reason) => {\n this.write('\\u0003');\n done({\n output: partialOutput(),\n exitStatus: null,\n timedOut: true,\n started,\n reason,\n durationMs: Date.now() - startedAt,\n });\n };\n\n const onData = (event) => {\n transcript += decodeUtf8(event.detail.bytes);\n\n if (!started && transcript.indexOf(begin) !== -1) {\n started = true;\n clearTimeout(startTimer);\n startTimer = null;\n }\n // A command that is still printing is still working, however long it\n // has been at it, so every chunk buys another idle window.\n if (started) {\n clearTimeout(idleTimer);\n idleTimer = setTimeout(() => giveUp('idle'), idleMs);\n }\n\n const endAt = transcript.indexOf(`${end} `);\n if (endAt === -1) {\n // The shell has rejected the wrapper itself, so the closing marker is\n // never coming. Say so now instead of holding the caller until the\n // deadline with a transcript of the wrapper it could not read.\n if (!started && FRAMING_REJECTED.test(stripTerminalCodes(transcript))) {\n const guessed = shellFromPrompt(stripTerminalCodes(transcript)) || 'cmd';\n const wrongGuess = family !== guessed;\n // Learn from it, so the next command is framed the shell's way.\n this.shellFamily = guessed;\n fail(new Error(\n wrongGuess\n ? `This shell is ${guessed === 'powershell' ? 'PowerShell' : 'Windows cmd'}, not a POSIX shell, `\n + 'and it rejected the wrapper used to capture output. The shell has been noted; '\n + 'run the command again and it will be framed correctly.'\n : `The shell rejected the wrapper used to capture output: ${\n stripTerminalCodes(transcript).split('\\n').filter(Boolean).pop() || 'no detail'\n }`\n ));\n }\n return;\n }\n\n const tail = transcript.slice(endAt);\n const status = parseInt(tail.slice(end.length + 1).trim(), 10);\n // Everything the shell printed between the two markers, with the\n // marker lines themselves and any terminal control codes removed.\n const beginAt = transcript.indexOf(begin);\n const body = beginAt === -1\n ? transcript.slice(0, endAt)\n : transcript.slice(beginAt + begin.length, endAt);\n\n done({\n output: stripTerminalCodes(body).replace(/^\\r?\\n/, '').replace(/\\s+$/, ''),\n exitStatus: Number.isInteger(status) ? status : null,\n timedOut: false,\n started: true,\n durationMs: Date.now() - startedAt,\n });\n };\n\n const onClose = () => fail(new Error('The SSH session closed while the command was running.'));\n\n this.addEventListener('data', onData);\n this.addEventListener('close', onClose);\n\n // Three deadlines, none of which is \"how long may this command take\".\n startTimer = setTimeout(() => giveUp('start'), startMs);\n idleTimer = setTimeout(() => giveUp('idle'), idleMs);\n maxTimer = setTimeout(() => giveUp('max'), maxMs);\n\n this.write(frameCommand(family, text, id));\n });\n }\n\n /** Tell the shell its window changed, so full-screen programs redraw. */\n resize(columns: number, rows: number) {\n const nextColumns = Math.max(1, Math.floor(columns));\n const nextRows = Math.max(1, Math.floor(rows));\n if (nextColumns === this.columns && nextRows === this.rows) return;\n\n this.columns = nextColumns;\n this.rows = nextRows;\n if (!this.shellOpen || this.remoteChannelId === null) return;\n\n this.transport.send(new SshWriter(64)\n .u8(MSG.CHANNEL_REQUEST).u32(this.remoteChannelId).string('window-change').boolean(false)\n .u32(nextColumns).u32(nextRows).u32(0).u32(0)\n .take());\n }\n\n // --- plumbing ------------------------------------------------------------\n\n #status(phase, message: string) {\n this.dispatchEvent(new CustomEvent('status', { detail: { phase, message } }));\n }\n\n #emitBanner(text: string) {\n if (text) this.dispatchEvent(new CustomEvent('banner', { detail: { text } }));\n }\n\n /** Wait for one of a few message types: the handshakes read linearly that way. */\n #expect(...types) {\n return new Promise((resolve, reject) => {\n for (const type of types) this.waiters.set(type, { resolve, reject });\n });\n }\n\n #settle(type, payload: Uint8Array) {\n const waiter = this.waiters.get(type);\n if (!waiter) return false;\n this.waiters.clear();\n waiter.resolve({ type, payload });\n return true;\n }\n\n /** A closed transport must not leave a handshake waiting forever. */\n #abandonWaiters(message: string) {\n if (this.waiters.size === 0) return;\n const pending = [...new Set(this.waiters.values())];\n this.waiters.clear();\n for (const waiter of pending) waiter.reject(new Error(message));\n }\n\n #handlePacket(type, payload: Uint8Array) {\n if (this.#settle(type, payload)) return;\n\n switch (type) {\n case MSG.USERAUTH_BANNER:\n this.#emitBanner(new SshReader(payload, 1).string().replaceAll('\\n', '\\r\\n'));\n return;\n case MSG.CHANNEL_DATA: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n this.#consume(reader.stringBytes());\n return;\n }\n case MSG.CHANNEL_EXTENDED_DATA: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n const dataType = reader.u32();\n const bytes = reader.stringBytes();\n this.#consume(bytes, dataType === EXTENDED_DATA_STDERR);\n return;\n }\n case MSG.CHANNEL_WINDOW_ADJUST: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n this.remoteWindow += reader.u32();\n this.#flushWrites();\n return;\n }\n case MSG.CHANNEL_REQUEST: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n const request = reader.string();\n const wantReply = reader.boolean();\n if (request === 'exit-status') this.exitStatus = reader.u32();\n if (request === 'exit-signal') this.exitSignal = reader.string();\n if (wantReply && this.remoteChannelId !== null) {\n this.transport.send(new SshWriter(8).u8(MSG.CHANNEL_SUCCESS).u32(this.remoteChannelId).take());\n }\n return;\n }\n case MSG.CHANNEL_EOF:\n return;\n case MSG.CHANNEL_CLOSE:\n this.shellOpen = false;\n this.#status('closed', 'The remote shell ended.');\n this.transport.disconnect('Shell closed');\n return;\n default:\n return;\n }\n }\n\n /**\n * Watch the prompt for which shell this machine answers with, so the first\n * command is framed correctly rather than discovering it by failing.\n */\n #noteShellFamily(bytes: Uint8Array) {\n this.promptTail = (this.promptTail + stripTerminalCodes(decodeUtf8(bytes))).slice(-400);\n const family = shellFromPrompt(this.promptTail);\n if (!family) return;\n\n if (family === 'cmd' && !this.powerShellAttempted) {\n this.#startPowerShell();\n return;\n }\n\n // While PowerShell is starting, the old cmd prompt may still be the last\n // prompt in the transcript. Wait for PowerShell's own prompt rather than\n // briefly advertising cmd as ready and racing an AI tool call into it.\n if (family === 'cmd' && this.powerShellAttempted && !this.readySignaled) return;\n\n this.shellFamily = family;\n if (family === 'powershell' && !this.readySignaled) {\n this.#markReady('Connected \u00B7 PowerShell');\n }\n }\n\n /** Replace Windows OpenSSH's usual cmd.exe with an interactive PowerShell. */\n #startPowerShell() {\n if (this.powerShellAttempted || !this.shellOpen) return;\n this.powerShellAttempted = true;\n this.readySignaled = false;\n this.shellFamily = '';\n this.#status('opening', 'Starting PowerShell\u2026');\n this.write('powershell.exe -NoLogo\\r');\n\n // A customized prompt may not begin with \"PS\". Keep the terminal usable\n // in that case; the command was already sent and PowerShell is still the\n // overwhelmingly likely interpreter after this short settling period.\n this.powerShellTimer = setTimeout(() => {\n if (this.readySignaled || this.closed) return;\n this.shellFamily = 'powershell';\n this.#markReady('Connected \u00B7 PowerShell');\n }, 2_000);\n }\n\n #markReady(message = 'Connected.') {\n clearTimeout(this.powerShellTimer);\n this.powerShellTimer = null;\n this.readySignaled = true;\n this.#status('ready', message);\n this.dispatchEvent(new CustomEvent('ready', {\n detail: { fingerprint: this.fingerprint, shellFamily: this.shellFamily || 'posix' },\n }));\n }\n\n /** Shell output, with the receive window topped up before it runs dry. */\n #consume(bytes: Uint8Array, isStderr = false) {\n if (!bytes.length) return;\n this.#noteShellFamily(bytes);\n this.dispatchEvent(new CustomEvent('data', {\n detail: { bytes, display: filterDisplay(this, bytes), isStderr },\n }));\n\n this.localWindow -= bytes.length;\n if (this.localWindow > WINDOW_REFILL_THRESHOLD || this.remoteChannelId === null) return;\n\n const increment = INITIAL_WINDOW - this.localWindow;\n this.localWindow = INITIAL_WINDOW;\n this.transport.send(new SshWriter(16)\n .u8(MSG.CHANNEL_WINDOW_ADJUST).u32(this.remoteChannelId).u32(increment).take());\n }\n\n #flushWrites() {\n if (!this.shellOpen || this.remoteChannelId === null) return;\n\n while (this.pendingWrites.length > 0) {\n const next = this.pendingWrites[0];\n const room = Math.min(this.remoteWindow, this.remoteMaxPacket - 64);\n if (room <= 0) return;\n\n const chunk = next.length <= room ? next : next.subarray(0, room);\n if (chunk.length === next.length) this.pendingWrites.shift();\n else this.pendingWrites[0] = next.subarray(chunk.length);\n\n this.remoteWindow -= chunk.length;\n this.transport.send(new SshWriter(chunk.length + 16)\n .u8(MSG.CHANNEL_DATA).u32(this.remoteChannelId).string(chunk).take());\n }\n }\n\n // --- authentication ------------------------------------------------------\n\n async #authenticate() {\n try {\n this.#status('authenticating', `Authenticating as ${this.username}\u2026`);\n this.transport.send(new SshWriter(32).u8(MSG.SERVICE_REQUEST).string('ssh-userauth').take());\n await this.#expect(MSG.SERVICE_ACCEPT);\n\n // \"none\" is how a client learns which methods a host will accept, and a\n // host with no authentication at all answers it with success.\n if (await this.#tryNone()) return void await this.#openShell();\n\n if (this.authMethods.includes('password') && this.password) {\n if (await this.#tryPassword(this.password)) return void await this.#openShell();\n }\n\n if (this.authMethods.includes('keyboard-interactive')) {\n if (await this.#tryKeyboardInteractive()) return void await this.#openShell();\n\n // The stored password was not what the host wanted -- a one-time code,\n // or simply the wrong one. Ask, the way the command-line client does.\n if (this.authMethods.includes('keyboard-interactive')) {\n if (await this.#tryKeyboardInteractive({ usePassword: false })) {\n return void await this.#openShell();\n }\n }\n }\n\n // A host that only advertises password auth still needs an answer when\n // the panel was opened without one.\n if (this.authMethods.includes('password')) {\n const typed = await this.requestInput({\n prompt: `${this.username}@${this.options.hostLabel || 'host'}'s password: `,\n echo: false,\n });\n if (typed && await this.#tryPassword(typed)) return void await this.#openShell();\n }\n\n throw new Error(this.authMethods.length\n ? `SSH: authentication failed. The host accepts ${this.authMethods.join(', ')}.`\n : 'SSH: the host rejected the connection before any authentication method was offered.');\n } catch (error) {\n if (!this.closed) this.transport.fail(error);\n }\n }\n\n async #tryNone() {\n this.transport.send(new SshWriter(64)\n .u8(MSG.USERAUTH_REQUEST).string(this.username).string(SERVICE).string('none').take());\n return this.#authResult();\n }\n\n async #tryPassword(password: string) {\n this.transport.send(new SshWriter(128)\n .u8(MSG.USERAUTH_REQUEST).string(this.username).string(SERVICE).string('password')\n .boolean(false).string(password)\n .take());\n return this.#authResult();\n }\n\n /**\n * keyboard-interactive is how most Linux hosts actually ask for a password,\n * and the only way a one-time code can be entered. Prompts are answered from\n * the password when one is obviously being asked for, and by the user\n * otherwise.\n */\n async #tryKeyboardInteractive({ usePassword = true } = {}) {\n this.transport.send(new SshWriter(96)\n .u8(MSG.USERAUTH_REQUEST).string(this.username).string(SERVICE).string('keyboard-interactive')\n .string('').string('')\n .take());\n\n let usedPassword = !usePassword;\n while (true) {\n const { type, payload } = await this.#expect(\n MSG.USERAUTH_SUCCESS, MSG.USERAUTH_FAILURE, MSG.USERAUTH_INFO_REQUEST\n );\n if (type === MSG.USERAUTH_SUCCESS) return true;\n if (type === MSG.USERAUTH_FAILURE) {\n this.#readFailure(payload);\n return false;\n }\n\n const reader = new SshReader(payload, 1);\n const name = reader.string();\n const instruction = reader.string();\n reader.string(); // language\n const promptCount = reader.u32();\n\n if (name) this.#emitBanner(`${name.replaceAll('\\n', '\\r\\n')}\\r\\n`);\n if (instruction) this.#emitBanner(`${instruction.replaceAll('\\n', '\\r\\n')}\\r\\n`);\n\n const answers = [];\n for (let index = 0; index < promptCount; index++) {\n const prompt = reader.string();\n const echo = reader.boolean();\n const looksLikePassword = !echo && /pass(word|phrase)/i.test(prompt);\n\n if (looksLikePassword && this.password && !usedPassword) {\n usedPassword = true;\n answers.push(this.password);\n continue;\n }\n answers.push(await this.requestInput({ prompt, echo }));\n }\n\n const response = new SshWriter(256).u8(MSG.USERAUTH_INFO_RESPONSE).u32(answers.length);\n for (const answer of answers) response.string(answer);\n this.transport.send(response.take());\n }\n }\n\n async #authResult() {\n const { type, payload } = await this.#expect(MSG.USERAUTH_SUCCESS, MSG.USERAUTH_FAILURE);\n if (type === MSG.USERAUTH_SUCCESS) return true;\n this.#readFailure(payload);\n return false;\n }\n\n #readFailure(payload: Uint8Array) {\n const reader = new SshReader(payload, 1);\n this.authMethods = reader.nameList();\n const partial = reader.boolean();\n if (partial) this.#emitBanner('\\r\\nOne factor accepted; the host wants another.\\r\\n');\n }\n\n // --- the shell -----------------------------------------------------------\n\n async #openShell() {\n this.#status('opening', 'Starting the remote shell\u2026');\n\n this.transport.send(new SshWriter(64)\n .u8(MSG.CHANNEL_OPEN).string('session').u32(this.channelId).u32(INITIAL_WINDOW).u32(MAX_PACKET)\n .take());\n\n const opened = await this.#expect(MSG.CHANNEL_OPEN_CONFIRMATION, MSG.CHANNEL_OPEN_FAILURE);\n if (opened.type === MSG.CHANNEL_OPEN_FAILURE) {\n const reader = new SshReader(opened.payload, 1);\n reader.u32();\n reader.u32();\n throw new Error(`SSH: the host refused to open a session channel (${reader.string()}).`);\n }\n\n const reader = new SshReader(opened.payload, 1);\n reader.u32(); // our channel id, echoed back\n this.remoteChannelId = reader.u32();\n this.remoteWindow = reader.u32();\n this.remoteMaxPacket = Math.max(1024, Math.min(reader.u32(), MAX_PACKET));\n\n this.transport.send(new SshWriter(128)\n .u8(MSG.CHANNEL_REQUEST).u32(this.remoteChannelId).string('pty-req').boolean(true)\n .string(TERMINAL_TYPE).u32(this.columns).u32(this.rows).u32(0).u32(0).string(PTY_MODES)\n .take());\n const pty = await this.#expect(MSG.CHANNEL_SUCCESS, MSG.CHANNEL_FAILURE);\n if (pty.type === MSG.CHANNEL_FAILURE) {\n throw new Error('SSH: the host refused a pseudo-terminal, so there is no interactive shell to show.');\n }\n\n this.transport.send(new SshWriter(32)\n .u8(MSG.CHANNEL_REQUEST).u32(this.remoteChannelId).string('shell').boolean(true).take());\n const shell = await this.#expect(MSG.CHANNEL_SUCCESS, MSG.CHANNEL_FAILURE);\n if (shell.type === MSG.CHANNEL_FAILURE) {\n throw new Error('SSH: the host refused to start a shell for this account.');\n }\n\n this.shellOpen = true;\n this.#flushWrites();\n if (this.options.preferredShell === 'powershell') this.#startPowerShell();\n else this.#markReady();\n }\n}\n"],
5
- "mappings": "AAOA,SAAS,KAAK,4BAA4B;AAC1C,SAAS,WAAW,WAAW,YAAY,YAAY,gBAAgB;AACvE,SAAS,oBAAoB;AAEtB,MAAM,eAAe;AAE5B,MAAM,UAAU;AAChB,MAAM,gBAAgB;AAItB,MAAM,iBAAiB,IAAI,OAAO;AAClC,MAAM,aAAa,KAAK;AACxB,MAAM,0BAA0B,iBAAiB;AAGjD,MAAM,YAAY,IAAI,WAAW,CAAC,CAAC,CAAC;AAe7B,MAAM,mBAAmB;AACzB,MAAM,kBAAkB,IAAI;AAC5B,MAAM,iBAAiB,KAAK;AAGnC,MAAM,WAAW,IAAI,WAAW,CAAC;AASjC,SAAS,YAAY,OAAO;AAC1B,SAAO,IAAI,OAAO,KAAK,EAAE,QAAQ,MAAM,OAAO,CAAC;AACjD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AAClB,QAAI,KAAK,QAAQ,mBAAmB,aAAc,MAAK,iBAAiB;AAAA,QACnE,MAAK,WAAW;AAAA,EACvB;AACF;",
4
+ "sourcesContent": ["// An SSH session: authentication, one interactive shell channel, and the\n// events a terminal needs to render it.\n//\n// The transport below this owns the cryptography. This module owns the\n// conversation: proving who the user is, asking for a pseudo-terminal, and\n// moving bytes between the shell and the screen.\n\nimport { MSG, EXTENDED_DATA_STDERR } from './messages';\nimport { SshReader, SshWriter, decodeUtf8, encodeUtf8, toBase64 } from './wire';\nimport { SshTransport } from './transport';\n\nexport const DEFAULT_PORT = 22;\n\nconst SERVICE = 'ssh-connection';\nconst TERMINAL_TYPE = 'xterm-256color';\n\n// A shell is not a bulk transfer, so a modest window costs nothing and is\n// topped up long before it runs out.\nconst INITIAL_WINDOW = 2 * 1024 * 1024;\nconst MAX_PACKET = 32 * 1024;\nconst WINDOW_REFILL_THRESHOLD = INITIAL_WINDOW / 2;\n\n/** Terminal modes: only the terminator, so the host keeps its own defaults. */\nconst PTY_MODES = new Uint8Array([0]);\n\n/**\n * How patient `runCommand` is, in three different senses.\n *\n * A single deadline cannot tell \"the shell ignored me\" apart from \"the\n * installer is three minutes into a download\", and a short one turns every\n * real piece of work -- a package install, a build, a large copy -- into a\n * false failure that also leaves the command running on the far side.\n *\n * So the wait is judged by what the shell is doing. It has START_MS to\n * acknowledge the command at all; after that it may take as long as it likes\n * as long as it keeps printing, and only silence longer than IDLE_MS, or a run\n * longer than MAX_MS, is treated as stuck.\n */\nexport const COMMAND_START_MS = 20_000;\nexport const COMMAND_IDLE_MS = 5 * 60_000;\nexport const COMMAND_MAX_MS = 60 * 60_000;\n\n/** Nothing for the terminal to draw, while the framing is being hidden. */\nconst NO_BYTES = new Uint8Array(0);\n\n/**\n * One shell word holding `value` literally.\n *\n * Single quotes suspend every kind of expansion the shell has, so the only\n * character that needs handling is the closing quote itself: the string is left\n * for a moment, an escaped quote is added, and it starts again.\n */\nfunction singleQuote(value) {\n return `'${String(value).replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * The shell a machine answers with, guessed from its prompt.\n *\n * Windows OpenSSH hands out cmd.exe by default, and a POSIX-framed command\n * there does not fail loudly -- it prints `'printf' is not recognized` and\n * leaves the caller waiting for markers that will never come.\n */\nfunction shellFromPrompt(text: string) {\n const tail = text.slice(-400);\n if (/(?:^|\\n)PS [A-Za-z]:\\\\[^\\n]*>\\s*$/.test(tail)) return 'powershell';\n if (/(?:^|\\n)[^\\n]*[A-Za-z]:\\\\[^\\n]*>\\s*$/.test(tail)) return 'cmd';\n return '';\n}\n\n/** A shell saying it has never heard of the command that frames the output. */\nconst FRAMING_REJECTED = /is not recognized as an internal or external command|command not found|not recognized as the name of a cmdlet|CommandNotFoundException/i;\n\n/**\n * The one line that runs `command` and marks where its output starts and ends.\n *\n * Each shell gets its own, because none of the three agree on how to print a\n * string, run a command and read back its exit status.\n */\nexport function frameCommand(family, command: string, id) {\n if (family === 'cmd') {\n // `&` chains unconditionally, and the delayed-expansion problem is dodged\n // by reading ERRORLEVEL through `call`, which re-expands its arguments.\n return `echo.&echo CCB${id}&${command}&call echo.CCE${id} %^ERRORLEVEL%\\r`;\n }\n\n if (family === 'powershell') {\n // A base64 payload keeps a trailing comment, newline or semicolon from\n // swallowing the closing marker. Dot-sourcing the resulting script block\n // also keeps Set-Location and environment changes in this same shell.\n //\n // $LASTEXITCODE is read before $?, because the two answer different\n // questions and only the first one is about the command. $? says whether\n // the dot-source raised an error record, and launching a program that goes\n // on to fail is not an error record: a failing `git`, `msiexec` or nested\n // `powershell.exe` leaves $? True and its own status in $LASTEXITCODE, so\n // asking $? first reports a failed command as exit 0. $LASTEXITCODE is\n // cleared just above, so a non-null value can only have come from a\n // program this command ran, and $? still decides for a payload that ended\n // in a cmdlet and never set it.\n const encoded = toBase64(encodeUtf8(command));\n return `Write-Output \"\"; Write-Output (\"CCB\" + \"${id}\"); `\n + `$__ccCode = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}')); `\n + `$global:LASTEXITCODE = $null; . ([ScriptBlock]::Create($__ccCode)); $__ccOk = $?; `\n + `$__cc = if ($LASTEXITCODE -ne $null) { $LASTEXITCODE } elseif ($__ccOk) { 0 } else { 1 }; `\n + `Write-Output (\"CCE\" + \"${id} \" + $__cc)\\r`;\n }\n\n // `printf '%s%s'` joins the marker inside the shell; `__cc` holds the status\n // so the command's own exit code survives the second printf.\n //\n // It all goes on one line, because an interactive shell echoes each line as\n // it reads it: a second line would be echoed after the command had already\n // printed, landing inside the captured output rather than in front of the\n // opening marker where it can be discarded.\n //\n // The command travels through `eval` as a single quoted word rather than\n // being spliced between the semicolons directly. Spliced in, three ordinary\n // commands break the framing: one ending in `&` puts `&` next to `;`, which\n // is a syntax error; one ending in a newline leaves a bare `;`, likewise; and\n // one ending in `# a comment` swallows the closing marker, so the call only\n // returns when it times out. Inside `eval` the command is a string, so none\n // of it can reach the outer line. `eval` runs in this same shell, so the\n // working directory, the environment and `$?` all still behave as if the\n // user had typed it.\n return `printf '\\\\n%s%s\\\\n' 'CCB' '${id}'; eval ${singleQuote(command)}; `\n + `__cc=$?; printf '\\\\n%s%s %s\\\\n' 'CCE' '${id}' \"$__cc\"\\r`;\n}\n\n/**\n * Plain text from a shell transcript. An interactive shell dresses its output\n * with colour, cursor moves and title changes, none of which mean anything to\n * a model reading the result.\n */\nfunction stripTerminalCodes(text: string) {\n return text\n // OSC sequences (window titles, and iTerm/VS Code shell integration)\n .replace(/\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)/g, '')\n // CSI sequences: colour, cursor movement, erase\n .replace(/\\u001b\\[[0-9;?]*[ -/]*[@-~]/g, '')\n // remaining two-character escapes\n .replace(/\\u001b[@-Z\\\\-_]/g, '')\n // carriage returns a terminal would have overwritten in place\n .replace(/\\r\\n/g, '\\n')\n .replace(/\\r/g, '');\n}\n\n/**\n * The same bytes, minus the scaffolding around a tool command.\n *\n * An interactive shell echoes whatever is typed into it, and what\n * `frameCommand` types is a `printf`-and-`eval` line -- or, in PowerShell, a\n * base64 blob. Left alone it buries the command's own output in the\n * scrollback the user is trying to read. The joined markers are safe to cut\n * on for the same reason `runCommand` finds them: the echoed line contains\n * their halves, never the joined marker itself.\n *\n * Only display is filtered. `detail.bytes` stays exactly what the host sent,\n * because that is what `runCommand` reads the result out of.\n */\nfunction filterDisplay(session, bytes: Uint8Array) {\n const filter = session.displayFilter;\n if (!filter) return bytes;\n\n filter.pending += decodeUtf8(bytes);\n let shown = '';\n\n if (filter.stage === 'before') {\n const at = filter.pending.indexOf(filter.begin);\n if (at === -1) return NO_BYTES; // still inside the echoed wrapper\n filter.pending = filter.pending.slice(at + filter.begin.length).replace(/^\\r?\\n/, '');\n filter.stage = 'inside';\n }\n\n if (filter.stage === 'inside') {\n const at = filter.pending.indexOf(filter.end);\n if (at === -1) {\n shown = filter.pending;\n filter.pending = '';\n return shown ? encodeUtf8(shown) : NO_BYTES;\n }\n shown = filter.pending.slice(0, at);\n filter.pending = filter.pending.slice(at);\n filter.stage = 'closing';\n }\n\n // The closing marker carries the exit status on its own line. Drop that\n // line and hand back everything after it: the prompt the shell draws next\n // belongs to the user again.\n const newline = filter.pending.indexOf('\\n');\n if (newline !== -1) {\n shown += filter.pending.slice(newline + 1);\n session.displayFilter = null;\n }\n return shown ? encodeUtf8(shown) : NO_BYTES;\n}\n\n/**\n * Stop filtering, showing anything held back on the way out.\n *\n * Text held before the opening marker is normally the echoed wrapper, but if\n * the command never started it is the shell explaining why -- the one case\n * where the held text is the whole answer, so it must not be swallowed.\n */\nfunction releaseDisplayFilter(session) {\n const filter = session.displayFilter;\n session.displayFilter = null;\n if (!filter || filter.stage !== 'before' || !filter.pending) return;\n session.dispatchEvent(new CustomEvent('data', {\n detail: { bytes: NO_BYTES, display: encodeUtf8(filter.pending), isStderr: false },\n }));\n}\n\nexport class SshSession extends EventTarget {\n /**\n * @param {string} url gateway WebSocket URL\n * @param {object} options\n * @param {string} options.username\n * @param {string} [options.password]\n * @param {'powershell'} [options.preferredShell]\n * @param {(info: object) => Promise<boolean>} [options.verifyHost]\n * @param {(prompt: object) => Promise<string>} [options.requestInput]\n */\n constructor(url: string, options = {}) {\n super();\n\n this.options = options;\n this.username = options.username || '';\n this.password = options.password || '';\n this.requestInput = options.requestInput || (async () => '');\n this.columns = options.columns || 80;\n this.rows = options.rows || 24;\n\n this.channelId = 0;\n this.remoteChannelId = null;\n this.remoteWindow = 0;\n this.remoteMaxPacket = MAX_PACKET;\n this.localWindow = INITIAL_WINDOW;\n this.pendingWrites = [];\n this.shellOpen = false;\n this.commandInFlight = false;\n /** Set while a tool command runs, to keep its framing off the screen. */\n this.displayFilter = null;\n /** True only after the requested interactive shell is ready for commands. */\n this.readySignaled = false;\n this.powerShellAttempted = false;\n this.powerShellTimer = null;\n /** '', 'posix', 'cmd' or 'powershell'; learned from the prompt. */\n this.shellFamily = '';\n this.promptTail = '';\n this.exitStatus = null;\n this.authMethods = [];\n this.closed = false;\n this.waiters = new Map();\n\n this.transport = new SshTransport(url, {\n verifyHost: options.verifyHost || (async () => true),\n openTransport: options.openTransport || null,\n log: (step: number, detail) => console.info(`[SSH] ${step}`, detail),\n });\n\n this.transport.addEventListener('packet', (event) => {\n this.#handlePacket(event.detail.type, event.detail.payload);\n });\n this.transport.addEventListener('greeting', (event) => {\n for (const line of event.detail.lines) this.#emitBanner(`${line}\\r\\n`);\n });\n this.transport.addEventListener('banner', (event) => this.#emitBanner(event.detail.text));\n this.transport.addEventListener('keys', (event) => {\n this.fingerprint = event.detail.fingerprint;\n this.#status('secured', `Host key ${event.detail.fingerprint} verified.`);\n this.dispatchEvent(new CustomEvent('secure', { detail: event.detail }));\n if (event.detail.firstTime) void this.#authenticate();\n });\n this.transport.addEventListener('hostdisconnect', (event) => {\n this.lastMessage = event.detail.reason;\n });\n this.transport.addEventListener('error', (event) => {\n this.lastMessage = event.detail.message;\n this.dispatchEvent(new CustomEvent('error', { detail: event.detail }));\n });\n this.transport.addEventListener('close', (event) => {\n if (this.closed) return;\n this.closed = true;\n clearTimeout(this.powerShellTimer);\n this.#abandonWaiters(event.detail.message || 'The SSH connection closed.');\n this.dispatchEvent(new CustomEvent('close', {\n detail: {\n ...event.detail,\n message: event.detail.message || this.lastMessage || '',\n exitStatus: this.exitStatus,\n },\n }));\n });\n }\n\n connect() {\n this.#status('connecting', 'Opening the SSH transport\u2026');\n this.transport.connect();\n }\n\n disconnect() {\n if (this.closed) return;\n clearTimeout(this.powerShellTimer);\n if (this.shellOpen && this.remoteChannelId !== null) {\n this.transport.send(new SshWriter(8).u8(MSG.CHANNEL_CLOSE).u32(this.remoteChannelId).take());\n }\n this.transport.disconnect('Closed by the user');\n }\n\n /** Send keystrokes, or anything else the terminal produces, to the shell. */\n write(data: Uint8Array) {\n const bytes = typeof data === 'string' ? encodeUtf8(data) : data;\n if (!bytes.length) return;\n this.pendingWrites.push(bytes);\n this.#flushWrites();\n }\n\n /**\n * Run one command in this shell and return what it printed.\n *\n * Deliberately the *same* shell the user is looking at, not a second channel:\n * a command the assistant runs inherits the working directory, the\n * environment and the login the user already has, and it appears in their\n * terminal as it happens. An agent acting on a machine invisibly is worse\n * than an agent that is slower to read.\n *\n * The output is framed by markers rather than measured, because an\n * interactive shell echoes its input and prints a prompt around it. The\n * markers are assembled by the shell from two pieces, so the echoed command\n * line -- which contains the pieces but not the joined marker -- never looks\n * like the real boundary.\n *\n * A `command` event brackets the run so the terminal can label it, and the\n * three deadlines above decide when a command is stuck rather than slow.\n */\n runCommand(command: string, {\n startMs = COMMAND_START_MS,\n idleMs = COMMAND_IDLE_MS,\n maxMs = COMMAND_MAX_MS,\n } = {}) {\n const text = String(command || '').trim();\n if (!text) return Promise.reject(new Error('No command was given.'));\n if (!this.shellOpen || this.closed) {\n return Promise.reject(new Error('The SSH shell is not open.'));\n }\n if (this.readySignaled === false) {\n return Promise.reject(new Error('The SSH shell is still starting.'));\n }\n if (this.commandInFlight) {\n return Promise.reject(new Error('Another command is still running in this shell.'));\n }\n\n const id = Array.from(crypto.getRandomValues(new Uint8Array(6)))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n const begin = `CCB${id}`;\n const end = `CCE${id}`;\n // What the prompt showed, or POSIX until something says otherwise.\n const family = this.shellFamily || 'posix';\n\n this.commandInFlight = true;\n const startedAt = Date.now();\n\n // The wrapper is machinery, not something the user asked to read, so the\n // terminal is shown the command's own output instead of the line that\n // frames it. The announcement below is what marks it in the scrollback.\n this.displayFilter = { begin, end, stage: 'before', pending: '' };\n this.dispatchEvent(new CustomEvent('command', {\n detail: { phase: 'start', id, command: text },\n }));\n\n return new Promise((resolve, reject) => {\n let transcript = '';\n let started = false;\n let startTimer = null;\n let idleTimer = null;\n let maxTimer = null;\n\n const finish = (settle) => {\n clearTimeout(startTimer);\n clearTimeout(idleTimer);\n clearTimeout(maxTimer);\n this.removeEventListener('data', onData);\n this.removeEventListener('close', onClose);\n this.commandInFlight = false;\n releaseDisplayFilter(this);\n settle();\n };\n\n /** End the call, and tell the terminal how it went. */\n const done = (result) => finish(() => {\n this.dispatchEvent(new CustomEvent('command', {\n detail: {\n phase: 'end',\n id,\n command: text,\n exitStatus: result.exitStatus,\n timedOut: result.timedOut,\n started: result.started !== false,\n reason: result.reason,\n durationMs: result.durationMs,\n },\n }));\n resolve(result);\n });\n\n const fail = (error) => finish(() => {\n this.dispatchEvent(new CustomEvent('command', {\n detail: {\n phase: 'end',\n id,\n command: text,\n exitStatus: null,\n timedOut: false,\n started,\n durationMs: Date.now() - startedAt,\n error: error.message,\n },\n }));\n reject(error);\n });\n\n /**\n * What the command has printed so far. Without the opening marker the\n * shell never started it, so the transcript is its echo of the wrapper\n * -- noise, not output.\n */\n const partialOutput = () => {\n const at = transcript.indexOf(begin);\n return at === -1\n ? ''\n : stripTerminalCodes(transcript.slice(at + begin.length)).replace(/^\\r?\\n/, '').replace(/\\s+$/, '');\n };\n\n /** Interrupt whatever is still running, so the shell is usable again. */\n const giveUp = (reason) => {\n this.write('\\u0003');\n done({\n output: partialOutput(),\n exitStatus: null,\n timedOut: true,\n started,\n reason,\n durationMs: Date.now() - startedAt,\n });\n };\n\n const onData = (event) => {\n transcript += decodeUtf8(event.detail.bytes);\n\n if (!started && transcript.indexOf(begin) !== -1) {\n started = true;\n clearTimeout(startTimer);\n startTimer = null;\n }\n // A command that is still printing is still working, however long it\n // has been at it, so every chunk buys another idle window.\n if (started) {\n clearTimeout(idleTimer);\n idleTimer = setTimeout(() => giveUp('idle'), idleMs);\n }\n\n const endAt = transcript.indexOf(`${end} `);\n if (endAt === -1) {\n // The shell has rejected the wrapper itself, so the closing marker is\n // never coming. Say so now instead of holding the caller until the\n // deadline with a transcript of the wrapper it could not read.\n if (!started && FRAMING_REJECTED.test(stripTerminalCodes(transcript))) {\n const guessed = shellFromPrompt(stripTerminalCodes(transcript)) || 'cmd';\n const wrongGuess = family !== guessed;\n // Learn from it, so the next command is framed the shell's way.\n this.shellFamily = guessed;\n fail(new Error(\n wrongGuess\n ? `This shell is ${guessed === 'powershell' ? 'PowerShell' : 'Windows cmd'}, not a POSIX shell, `\n + 'and it rejected the wrapper used to capture output. The shell has been noted; '\n + 'run the command again and it will be framed correctly.'\n : `The shell rejected the wrapper used to capture output: ${\n stripTerminalCodes(transcript).split('\\n').filter(Boolean).pop() || 'no detail'\n }`\n ));\n }\n return;\n }\n\n const tail = transcript.slice(endAt);\n const status = parseInt(tail.slice(end.length + 1).trim(), 10);\n // Everything the shell printed between the two markers, with the\n // marker lines themselves and any terminal control codes removed.\n const beginAt = transcript.indexOf(begin);\n const body = beginAt === -1\n ? transcript.slice(0, endAt)\n : transcript.slice(beginAt + begin.length, endAt);\n\n done({\n output: stripTerminalCodes(body).replace(/^\\r?\\n/, '').replace(/\\s+$/, ''),\n exitStatus: Number.isInteger(status) ? status : null,\n timedOut: false,\n started: true,\n durationMs: Date.now() - startedAt,\n });\n };\n\n const onClose = () => fail(new Error('The SSH session closed while the command was running.'));\n\n this.addEventListener('data', onData);\n this.addEventListener('close', onClose);\n\n // Three deadlines, none of which is \"how long may this command take\".\n startTimer = setTimeout(() => giveUp('start'), startMs);\n idleTimer = setTimeout(() => giveUp('idle'), idleMs);\n maxTimer = setTimeout(() => giveUp('max'), maxMs);\n\n this.write(frameCommand(family, text, id));\n });\n }\n\n /** Tell the shell its window changed, so full-screen programs redraw. */\n resize(columns: number, rows: number) {\n const nextColumns = Math.max(1, Math.floor(columns));\n const nextRows = Math.max(1, Math.floor(rows));\n if (nextColumns === this.columns && nextRows === this.rows) return;\n\n this.columns = nextColumns;\n this.rows = nextRows;\n if (!this.shellOpen || this.remoteChannelId === null) return;\n\n this.transport.send(new SshWriter(64)\n .u8(MSG.CHANNEL_REQUEST).u32(this.remoteChannelId).string('window-change').boolean(false)\n .u32(nextColumns).u32(nextRows).u32(0).u32(0)\n .take());\n }\n\n // --- plumbing ------------------------------------------------------------\n\n #status(phase, message: string) {\n this.dispatchEvent(new CustomEvent('status', { detail: { phase, message } }));\n }\n\n #emitBanner(text: string) {\n if (text) this.dispatchEvent(new CustomEvent('banner', { detail: { text } }));\n }\n\n /** Wait for one of a few message types: the handshakes read linearly that way. */\n #expect(...types) {\n return new Promise((resolve, reject) => {\n for (const type of types) this.waiters.set(type, { resolve, reject });\n });\n }\n\n #settle(type, payload: Uint8Array) {\n const waiter = this.waiters.get(type);\n if (!waiter) return false;\n this.waiters.clear();\n waiter.resolve({ type, payload });\n return true;\n }\n\n /** A closed transport must not leave a handshake waiting forever. */\n #abandonWaiters(message: string) {\n if (this.waiters.size === 0) return;\n const pending = [...new Set(this.waiters.values())];\n this.waiters.clear();\n for (const waiter of pending) waiter.reject(new Error(message));\n }\n\n #handlePacket(type, payload: Uint8Array) {\n if (this.#settle(type, payload)) return;\n\n switch (type) {\n case MSG.USERAUTH_BANNER:\n this.#emitBanner(new SshReader(payload, 1).string().replaceAll('\\n', '\\r\\n'));\n return;\n case MSG.CHANNEL_DATA: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n this.#consume(reader.stringBytes());\n return;\n }\n case MSG.CHANNEL_EXTENDED_DATA: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n const dataType = reader.u32();\n const bytes = reader.stringBytes();\n this.#consume(bytes, dataType === EXTENDED_DATA_STDERR);\n return;\n }\n case MSG.CHANNEL_WINDOW_ADJUST: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n this.remoteWindow += reader.u32();\n this.#flushWrites();\n return;\n }\n case MSG.CHANNEL_REQUEST: {\n const reader = new SshReader(payload, 1);\n reader.u32();\n const request = reader.string();\n const wantReply = reader.boolean();\n if (request === 'exit-status') this.exitStatus = reader.u32();\n if (request === 'exit-signal') this.exitSignal = reader.string();\n if (wantReply && this.remoteChannelId !== null) {\n this.transport.send(new SshWriter(8).u8(MSG.CHANNEL_SUCCESS).u32(this.remoteChannelId).take());\n }\n return;\n }\n case MSG.CHANNEL_EOF:\n return;\n case MSG.CHANNEL_CLOSE:\n this.shellOpen = false;\n this.#status('closed', 'The remote shell ended.');\n this.transport.disconnect('Shell closed');\n return;\n default:\n return;\n }\n }\n\n /**\n * Watch the prompt for which shell this machine answers with, so the first\n * command is framed correctly rather than discovering it by failing.\n */\n #noteShellFamily(bytes: Uint8Array) {\n this.promptTail = (this.promptTail + stripTerminalCodes(decodeUtf8(bytes))).slice(-400);\n const family = shellFromPrompt(this.promptTail);\n if (!family) return;\n\n if (family === 'cmd' && !this.powerShellAttempted) {\n this.#startPowerShell();\n return;\n }\n\n // While PowerShell is starting, the old cmd prompt may still be the last\n // prompt in the transcript. Wait for PowerShell's own prompt rather than\n // briefly advertising cmd as ready and racing an AI tool call into it.\n if (family === 'cmd' && this.powerShellAttempted && !this.readySignaled) return;\n\n this.shellFamily = family;\n if (family === 'powershell' && !this.readySignaled) {\n this.#markReady('Connected \u00B7 PowerShell');\n }\n }\n\n /** Replace Windows OpenSSH's usual cmd.exe with an interactive PowerShell. */\n #startPowerShell() {\n if (this.powerShellAttempted || !this.shellOpen) return;\n this.powerShellAttempted = true;\n this.readySignaled = false;\n this.shellFamily = '';\n this.#status('opening', 'Starting PowerShell\u2026');\n this.write('powershell.exe -NoLogo\\r');\n\n // A customized prompt may not begin with \"PS\". Keep the terminal usable\n // in that case; the command was already sent and PowerShell is still the\n // overwhelmingly likely interpreter after this short settling period.\n this.powerShellTimer = setTimeout(() => {\n if (this.readySignaled || this.closed) return;\n this.shellFamily = 'powershell';\n this.#markReady('Connected \u00B7 PowerShell');\n }, 2_000);\n }\n\n #markReady(message = 'Connected.') {\n clearTimeout(this.powerShellTimer);\n this.powerShellTimer = null;\n this.readySignaled = true;\n this.#status('ready', message);\n this.dispatchEvent(new CustomEvent('ready', {\n detail: { fingerprint: this.fingerprint, shellFamily: this.shellFamily || 'posix' },\n }));\n }\n\n /** Shell output, with the receive window topped up before it runs dry. */\n #consume(bytes: Uint8Array, isStderr = false) {\n if (!bytes.length) return;\n this.#noteShellFamily(bytes);\n this.dispatchEvent(new CustomEvent('data', {\n detail: { bytes, display: filterDisplay(this, bytes), isStderr },\n }));\n\n this.localWindow -= bytes.length;\n if (this.localWindow > WINDOW_REFILL_THRESHOLD || this.remoteChannelId === null) return;\n\n const increment = INITIAL_WINDOW - this.localWindow;\n this.localWindow = INITIAL_WINDOW;\n this.transport.send(new SshWriter(16)\n .u8(MSG.CHANNEL_WINDOW_ADJUST).u32(this.remoteChannelId).u32(increment).take());\n }\n\n #flushWrites() {\n if (!this.shellOpen || this.remoteChannelId === null) return;\n\n while (this.pendingWrites.length > 0) {\n const next = this.pendingWrites[0];\n const room = Math.min(this.remoteWindow, this.remoteMaxPacket - 64);\n if (room <= 0) return;\n\n const chunk = next.length <= room ? next : next.subarray(0, room);\n if (chunk.length === next.length) this.pendingWrites.shift();\n else this.pendingWrites[0] = next.subarray(chunk.length);\n\n this.remoteWindow -= chunk.length;\n this.transport.send(new SshWriter(chunk.length + 16)\n .u8(MSG.CHANNEL_DATA).u32(this.remoteChannelId).string(chunk).take());\n }\n }\n\n // --- authentication ------------------------------------------------------\n\n async #authenticate() {\n try {\n this.#status('authenticating', `Authenticating as ${this.username}\u2026`);\n this.transport.send(new SshWriter(32).u8(MSG.SERVICE_REQUEST).string('ssh-userauth').take());\n await this.#expect(MSG.SERVICE_ACCEPT);\n\n // \"none\" is how a client learns which methods a host will accept, and a\n // host with no authentication at all answers it with success.\n if (await this.#tryNone()) return void await this.#openShell();\n\n if (this.authMethods.includes('password') && this.password) {\n if (await this.#tryPassword(this.password)) return void await this.#openShell();\n }\n\n if (this.authMethods.includes('keyboard-interactive')) {\n if (await this.#tryKeyboardInteractive()) return void await this.#openShell();\n\n // The stored password was not what the host wanted -- a one-time code,\n // or simply the wrong one. Ask, the way the command-line client does.\n if (this.authMethods.includes('keyboard-interactive')) {\n if (await this.#tryKeyboardInteractive({ usePassword: false })) {\n return void await this.#openShell();\n }\n }\n }\n\n // A host that only advertises password auth still needs an answer when\n // the panel was opened without one.\n if (this.authMethods.includes('password')) {\n const typed = await this.requestInput({\n prompt: `${this.username}@${this.options.hostLabel || 'host'}'s password: `,\n echo: false,\n });\n if (typed && await this.#tryPassword(typed)) return void await this.#openShell();\n }\n\n throw new Error(this.authMethods.length\n ? `SSH: authentication failed. The host accepts ${this.authMethods.join(', ')}.`\n : 'SSH: the host rejected the connection before any authentication method was offered.');\n } catch (error) {\n if (!this.closed) this.transport.fail(error);\n }\n }\n\n async #tryNone() {\n this.transport.send(new SshWriter(64)\n .u8(MSG.USERAUTH_REQUEST).string(this.username).string(SERVICE).string('none').take());\n return this.#authResult();\n }\n\n async #tryPassword(password: string) {\n this.transport.send(new SshWriter(128)\n .u8(MSG.USERAUTH_REQUEST).string(this.username).string(SERVICE).string('password')\n .boolean(false).string(password)\n .take());\n return this.#authResult();\n }\n\n /**\n * keyboard-interactive is how most Linux hosts actually ask for a password,\n * and the only way a one-time code can be entered. Prompts are answered from\n * the password when one is obviously being asked for, and by the user\n * otherwise.\n */\n async #tryKeyboardInteractive({ usePassword = true } = {}) {\n this.transport.send(new SshWriter(96)\n .u8(MSG.USERAUTH_REQUEST).string(this.username).string(SERVICE).string('keyboard-interactive')\n .string('').string('')\n .take());\n\n let usedPassword = !usePassword;\n while (true) {\n const { type, payload } = await this.#expect(\n MSG.USERAUTH_SUCCESS, MSG.USERAUTH_FAILURE, MSG.USERAUTH_INFO_REQUEST\n );\n if (type === MSG.USERAUTH_SUCCESS) return true;\n if (type === MSG.USERAUTH_FAILURE) {\n this.#readFailure(payload);\n return false;\n }\n\n const reader = new SshReader(payload, 1);\n const name = reader.string();\n const instruction = reader.string();\n reader.string(); // language\n const promptCount = reader.u32();\n\n if (name) this.#emitBanner(`${name.replaceAll('\\n', '\\r\\n')}\\r\\n`);\n if (instruction) this.#emitBanner(`${instruction.replaceAll('\\n', '\\r\\n')}\\r\\n`);\n\n const answers = [];\n for (let index = 0; index < promptCount; index++) {\n const prompt = reader.string();\n const echo = reader.boolean();\n const looksLikePassword = !echo && /pass(word|phrase)/i.test(prompt);\n\n if (looksLikePassword && this.password && !usedPassword) {\n usedPassword = true;\n answers.push(this.password);\n continue;\n }\n answers.push(await this.requestInput({ prompt, echo }));\n }\n\n const response = new SshWriter(256).u8(MSG.USERAUTH_INFO_RESPONSE).u32(answers.length);\n for (const answer of answers) response.string(answer);\n this.transport.send(response.take());\n }\n }\n\n async #authResult() {\n const { type, payload } = await this.#expect(MSG.USERAUTH_SUCCESS, MSG.USERAUTH_FAILURE);\n if (type === MSG.USERAUTH_SUCCESS) return true;\n this.#readFailure(payload);\n return false;\n }\n\n #readFailure(payload: Uint8Array) {\n const reader = new SshReader(payload, 1);\n this.authMethods = reader.nameList();\n const partial = reader.boolean();\n if (partial) this.#emitBanner('\\r\\nOne factor accepted; the host wants another.\\r\\n');\n }\n\n // --- the shell -----------------------------------------------------------\n\n async #openShell() {\n this.#status('opening', 'Starting the remote shell\u2026');\n\n this.transport.send(new SshWriter(64)\n .u8(MSG.CHANNEL_OPEN).string('session').u32(this.channelId).u32(INITIAL_WINDOW).u32(MAX_PACKET)\n .take());\n\n const opened = await this.#expect(MSG.CHANNEL_OPEN_CONFIRMATION, MSG.CHANNEL_OPEN_FAILURE);\n if (opened.type === MSG.CHANNEL_OPEN_FAILURE) {\n const reader = new SshReader(opened.payload, 1);\n reader.u32();\n reader.u32();\n throw new Error(`SSH: the host refused to open a session channel (${reader.string()}).`);\n }\n\n const reader = new SshReader(opened.payload, 1);\n reader.u32(); // our channel id, echoed back\n this.remoteChannelId = reader.u32();\n this.remoteWindow = reader.u32();\n this.remoteMaxPacket = Math.max(1024, Math.min(reader.u32(), MAX_PACKET));\n\n this.transport.send(new SshWriter(128)\n .u8(MSG.CHANNEL_REQUEST).u32(this.remoteChannelId).string('pty-req').boolean(true)\n .string(TERMINAL_TYPE).u32(this.columns).u32(this.rows).u32(0).u32(0).string(PTY_MODES)\n .take());\n const pty = await this.#expect(MSG.CHANNEL_SUCCESS, MSG.CHANNEL_FAILURE);\n if (pty.type === MSG.CHANNEL_FAILURE) {\n throw new Error('SSH: the host refused a pseudo-terminal, so there is no interactive shell to show.');\n }\n\n this.transport.send(new SshWriter(32)\n .u8(MSG.CHANNEL_REQUEST).u32(this.remoteChannelId).string('shell').boolean(true).take());\n const shell = await this.#expect(MSG.CHANNEL_SUCCESS, MSG.CHANNEL_FAILURE);\n if (shell.type === MSG.CHANNEL_FAILURE) {\n throw new Error('SSH: the host refused to start a shell for this account.');\n }\n\n this.shellOpen = true;\n this.#flushWrites();\n if (this.options.preferredShell === 'powershell') this.#startPowerShell();\n else this.#markReady();\n }\n}\n"],
5
+ "mappings": "AAOA,SAAS,KAAK,4BAA4B;AAC1C,SAAS,WAAW,WAAW,YAAY,YAAY,gBAAgB;AACvE,SAAS,oBAAoB;AAEtB,MAAM,eAAe;AAE5B,MAAM,UAAU;AAChB,MAAM,gBAAgB;AAItB,MAAM,iBAAiB,IAAI,OAAO;AAClC,MAAM,aAAa,KAAK;AACxB,MAAM,0BAA0B,iBAAiB;AAGjD,MAAM,YAAY,IAAI,WAAW,CAAC,CAAC,CA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,EAAE,OAAO,OAAO,EAAE,QAAQ,IAAI,EAAE,KAAK,CAAC;AACzF,UAAM,QAAQ,MAAM,KAAK,QAAQ,IAAI,iBAAiB,IAAI,eAAe;AACzE,QAAI,MAAM,SAAS,IAAI,iBAAiB;AACtC,YAAM,IAAI,MAAM,0DAA0D;AAAA,IAC5E;AAEA,SAAK,YAAY;AACjB,SAAK,aAAa;AAClB,QAAI,KAAK,QAAQ,mBAAmB,aAAc,MAAK,iBAAiB;AAAA,QACnE,MAAK,WAAW;AAAA,EACvB;AACF;",
6
6
  "names": ["reader"]
7
7
  }
@@ -1,10 +1,10 @@
1
- import { MSG, DISCONNECT_REASON } from "./messages";
1
+ import { MSG, DISCONNECT_REASON } from "./messages.js";
2
2
  import {
3
3
  SshReader,
4
4
  SshWriter,
5
5
  concatBytes,
6
6
  encodeUtf8
7
- } from "./wire";
7
+ } from "./wire.js";
8
8
  import {
9
9
  createKexClient,
10
10
  deriveKey,
@@ -13,12 +13,12 @@ import {
13
13
  hostKeyType,
14
14
  negotiableAlgorithms,
15
15
  verifyHostKeySignature
16
- } from "./kex";
16
+ } from "./kex.js";
17
17
  import {
18
18
  GATEWAY_KEEPALIVE_SIGNAL,
19
19
  GATEWAY_READY_SIGNAL,
20
20
  KEEPALIVE_INTERVAL_MS
21
- } from "../../shared/signals";
21
+ } from "../../shared/signals.js";
22
22
  const CLIENT_VERSION = "SSH-2.0-CloudflareGateway_1.0";
23
23
  const CIPHERS = {
24
24
  "aes256-gcm@openssh.com": { keyLength: 32 },
@@ -66,6 +66,7 @@ class SshTransport extends EventTarget {
66
66
  verifyHost;
67
67
  log;
68
68
  socket;
69
+ openTransport;
69
70
  closed;
70
71
  buffer;
71
72
  serverVersion;
@@ -91,12 +92,13 @@ class SshTransport extends EventTarget {
91
92
  * @param {(info: object) => Promise<boolean>} options.verifyHost decides
92
93
  * whether an unknown or changed host key may be used.
93
94
  */
94
- constructor(url, { verifyHost, log } = {}) {
95
+ constructor(url, { verifyHost, log, openTransport } = {}) {
95
96
  super();
96
97
  this.url = url;
97
98
  this.verifyHost = verifyHost || (() => true);
98
99
  this.log = log || (() => {
99
100
  });
101
+ this.openTransport = openTransport || null;
100
102
  this.socket = null;
101
103
  this.closed = false;
102
104
  this.buffer = new Uint8Array(0);
@@ -115,7 +117,7 @@ class SshTransport extends EventTarget {
115
117
  }
116
118
  // --- connection ----------------------------------------------------------
117
119
  connect() {
118
- this.socket = new WebSocket(this.url);
120
+ this.socket = this.openTransport ? this.openTransport(this.url) : new WebSocket(this.url);
119
121
  this.socket.binaryType = "arraybuffer";
120
122
  this.socket.addEventListener("open", () => {
121
123
  this.socket.send(GATEWAY_READY_SIGNAL);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/protocols/ssh/transport.ts"],
4
- "sourcesContent": ["// The SSH transport layer (RFC 4253): version exchange, the binary packet\n// protocol, key exchange, and the AES-GCM cipher that protects everything\n// after it.\n//\n// Like the RDP client, this runs entirely in the browser. The gateway's\n// /ssh-ws endpoint is a byte relay and never sees a decrypted packet or a\n// password; the keys derived here exist only in this tab.\n\nimport { MSG, DISCONNECT_REASON } from './messages';\nimport {\n SshReader,\n SshWriter,\n concatBytes,\n encodeUtf8,\n} from './wire';\nimport {\n createKexClient,\n deriveKey,\n exchangeHash,\n hostKeyFingerprint,\n hostKeyType,\n negotiableAlgorithms,\n verifyHostKeySignature,\n} from './kex';\nimport {\n GATEWAY_KEEPALIVE_SIGNAL,\n GATEWAY_READY_SIGNAL,\n KEEPALIVE_INTERVAL_MS,\n} from '../../shared/signals';\n\nexport const CLIENT_VERSION = 'SSH-2.0-CloudflareGateway_1.0';\n\n/** Only AEAD ciphers are offered, so the MAC list is never actually used. */\nconst CIPHERS = {\n 'aes256-gcm@openssh.com': { keyLength: 32 },\n 'aes128-gcm@openssh.com': { keyLength: 16 },\n};\nconst CIPHER_NAMES = Object.keys(CIPHERS);\nconst MAC_NAMES = ['hmac-sha2-256', 'hmac-sha2-512'];\nconst COMPRESSION_NAMES = ['none'];\n\nconst GCM_BLOCK = 16;\nconst GCM_TAG_BYTES = 16;\nconst GCM_IV_BYTES = 12;\nconst PLAIN_BLOCK = 8;\nconst MIN_PADDING = 4;\nconst MAX_PACKET_BYTES = 262_144;\nconst VERSION_LINE_LIMIT = 8_192;\n\nconst subtle = globalThis.crypto?.subtle;\n\n/** Pick the first client preference the host also offered (RFC 4253 7.1). */\nexport function negotiate(clientNames, serverNames) {\n return clientNames.find((name: string) => serverNames.includes(name)) || null;\n}\n\n/** An AES-GCM direction: one key, and an invocation counter that never repeats. */\nclass GcmCipher {\n key: CryptoKey;\n fixed: Uint8Array;\n counter: Uint8Array;\n\n constructor(key: CryptoKey, iv: Uint8Array) {\n this.key = key;\n this.fixed = iv.slice(0, 4);\n this.counter = iv.slice(4, 12);\n }\n\n static async create(keyBytes: Uint8Array, iv: Uint8Array) {\n const key = await subtle.importKey('raw', keyBytes as unknown as BufferSource, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);\n return new GcmCipher(key, iv);\n }\n\n /** The 12-byte nonce for this packet, then step the 64-bit counter. */\n nextIv() {\n const iv = concatBytes(this.fixed, this.counter);\n for (let index = this.counter.length - 1; index >= 0; index--) {\n this.counter[index] = (this.counter[index] + 1) & 0xff;\n if (this.counter[index] !== 0) break;\n }\n return iv;\n }\n}\n\nexport class SshTransport extends EventTarget {\n url: string;\n verifyHost: (info: any) => Promise<boolean> | boolean;\n log: (...args: any[]) => void;\n socket: WebSocket | null;\n closed: boolean;\n buffer: Uint8Array;\n serverVersion: string;\n greeting: string[];\n sendSequence: number;\n receiveSequence: number;\n outgoing: any;\n incoming: any;\n sessionId: Uint8Array | null;\n kex: any;\n kexQueue: Uint8Array[];\n keepaliveTimer: any;\n bytesSent: number;\n bytesReceived: number;\n encryptChain?: Promise<void>;\n newKeysBarrier?: Promise<void> | null;\n releaseNewKeys?: (() => void) | null;\n pendingServerKexInit?: Uint8Array | null;\n established?: boolean;\n\n /**\n * @param {string} url gateway WebSocket URL\n * @param {object} options\n * @param {(info: object) => Promise<boolean>} options.verifyHost decides\n * whether an unknown or changed host key may be used.\n */\n constructor(url: string, { verifyHost, log }: { verifyHost?: (info: any) => Promise<boolean> | boolean; log?: (...args: any[]) => void } = {}) {\n super();\n\n this.url = url;\n this.verifyHost = verifyHost || (() => true);\n this.log = log || (() => {});\n\n this.socket = null;\n this.closed = false;\n this.buffer = new Uint8Array(0);\n this.serverVersion = '';\n this.greeting = [];\n\n this.sendSequence = 0;\n this.receiveSequence = 0;\n this.outgoing = null;\n this.incoming = null;\n this.sessionId = null;\n\n this.kex = null;\n this.kexQueue = [];\n this.keepaliveTimer = null;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n }\n\n // --- connection ----------------------------------------------------------\n\n connect() {\n this.socket = new WebSocket(this.url);\n this.socket.binaryType = 'arraybuffer';\n\n this.socket.addEventListener('open', () => {\n // The relay holds the host's first bytes until the browser says it is\n // listening, exactly as the RDP client does.\n this.socket.send(GATEWAY_READY_SIGNAL);\n this.#write(encodeUtf8(`${CLIENT_VERSION}\\r\\n`));\n this.keepaliveTimer = setInterval(() => {\n if (this.socket?.readyState !== WebSocket.OPEN) return;\n\n // Keeps the browser-to-gateway WebSocket alive. The gateway absorbs\n // this frame, so it never reaches the host.\n this.socket.send(GATEWAY_KEEPALIVE_SIGNAL);\n\n // Which leaves the TCP leg silent whenever nobody is typing, and an\n // idle TCP connection through a tunnel is a TCP connection about to be\n // dropped. This is the request OpenSSH itself uses to keep one warm:\n // servers answer it with a failure, which is a perfectly good answer --\n // the point is the bytes, not the reply.\n if (this.sessionId) {\n try {\n this.#sendPacket(new SshWriter(64)\n .u8(MSG.GLOBAL_REQUEST)\n .string('keepalive@openssh.com')\n .u8(1)\n .take());\n } catch {\n // A keepalive is not worth breaking a working session over.\n }\n }\n }, KEEPALIVE_INTERVAL_MS);\n });\n\n this.socket.addEventListener('message', (event) => {\n if (typeof event.data === 'string') return; // gateway control frame\n this.#receive(new Uint8Array(event.data));\n });\n\n this.socket.addEventListener('close', (event) => {\n this.#finish({\n clean: event.code === 1000,\n code: event.code,\n message: event.reason || (\n event.code === 1006\n ? 'The gateway rejected or could not reach this SSH target. Confirm that SSH is published for this host.'\n : ''\n ),\n });\n });\n\n // A failed WebSocket upgrade emits `error` immediately followed by\n // `close`. The error event has no HTTP status or response body, while a\n // relay that connected successfully can put the useful TCP failure in the\n // close reason. Waiting for `close` preserves that explanation instead of\n // replacing it with an opaque generic error.\n this.socket.addEventListener('error', () => {\n this.log('The SSH gateway WebSocket reported a transport error; waiting for its close reason.');\n });\n }\n\n disconnect(message = 'Client disconnected') {\n if (this.closed) return;\n try {\n const payload = new SshWriter(64)\n .u8(MSG.DISCONNECT).u32(11).string(message).string('')\n .take();\n this.#sendPacket(payload);\n } catch {}\n // The packet may still be encrypting, and closing the socket under it\n // would drop the goodbye the host is waiting for.\n const socket = this.socket;\n void Promise.resolve(this.encryptChain).finally(() => {\n try { socket?.close(1000, 'Client disconnected'); } catch {}\n });\n this.#finish({ clean: true, code: 1000, message: '' });\n }\n\n #finish(detail) {\n if (this.closed) return;\n this.closed = true;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n this.dispatchEvent(new CustomEvent('close', { detail }));\n }\n\n fail(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n if (this.closed) return;\n this.dispatchEvent(new CustomEvent('error', { detail: { message } }));\n this.#finish({ clean: false, code: 4000, message });\n try { this.socket?.close(4000, message.slice(0, 100)); } catch {}\n }\n\n #write(bytes: Uint8Array) {\n if (this.socket?.readyState !== WebSocket.OPEN) return;\n this.bytesSent += bytes.length;\n this.socket.send(bytes);\n }\n\n // --- framing -------------------------------------------------------------\n\n #receive(chunk: Uint8Array) {\n this.bytesReceived += chunk.length;\n this.buffer = this.buffer.length ? concatBytes(this.buffer, chunk) : chunk;\n\n // Decryption is asynchronous, so the reader is a single chain rather than\n // a loop: two overlapping drains could deliver packets out of order, and\n // an out-of-order packet is a broken session.\n this.drainChain = (this.drainChain || Promise.resolve())\n .then(() => this.#drain())\n .catch((error: unknown) => this.fail(error));\n }\n\n async #drain() {\n if (this.closed) return;\n if (!this.serverVersion && !this.#readVersion()) return;\n\n while (!this.closed) {\n // The host's NEWKEYS is the last packet under the old cipher. Nothing\n // after it can be read until the new one is installed.\n if (this.newKeysBarrier) {\n const barrier = this.newKeysBarrier;\n this.newKeysBarrier = null;\n await barrier;\n continue;\n }\n\n if (!this.incoming) {\n const payload = this.#readPlainPacket();\n if (!payload) return;\n this.#dispatchPacket(payload);\n continue;\n }\n\n const frame = this.#takeEncryptedFrame();\n if (!frame) return;\n this.#dispatchPacket(await this.#decrypt(frame));\n }\n }\n\n /**\n * The host may print any number of lines before its version line, and RFC\n * 4253 says to show them: this is where a \"banned by fail2ban\" notice or a\n * legal banner arrives.\n */\n #readVersion() {\n while (true) {\n const newline = this.buffer.indexOf(0x0a);\n if (newline === -1) {\n if (this.buffer.length > VERSION_LINE_LIMIT) {\n throw new Error('SSH: the host sent no version line.');\n }\n return false;\n }\n\n let end = newline;\n if (end > 0 && this.buffer[end - 1] === 0x0d) end--;\n const line = new TextDecoder().decode(this.buffer.subarray(0, end));\n this.buffer = this.buffer.subarray(newline + 1);\n\n if (!line.startsWith('SSH-')) {\n if (line.trim()) this.greeting.push(line);\n continue;\n }\n if (!line.startsWith('SSH-2.0-') && !line.startsWith('SSH-1.99-')) {\n throw new Error(`SSH: this host speaks ${line.split('-').slice(0, 2).join('-')}, which is too old.`);\n }\n\n this.serverVersion = line;\n this.log('version', { server: line, greeting: this.greeting });\n this.dispatchEvent(new CustomEvent('greeting', { detail: { lines: this.greeting.slice() } }));\n void this.#startKex();\n return true;\n }\n }\n\n /** A packet from before the keys exist. Returns null when more bytes are due. */\n #readPlainPacket() {\n if (this.buffer.length < 5) return null;\n const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n const packetLength = view.getUint32(0, false);\n if (packetLength < 8 || packetLength > MAX_PACKET_BYTES) {\n throw new Error('SSH: the host sent a packet of an impossible size.');\n }\n if (this.buffer.length < 4 + packetLength) return null;\n\n const paddingLength = this.buffer[4];\n if (paddingLength + 1 > packetLength) throw new Error('SSH: a packet claimed more padding than it had.');\n const payload = this.buffer.slice(5, 4 + packetLength - paddingLength);\n this.buffer = this.buffer.subarray(4 + packetLength);\n this.receiveSequence = (this.receiveSequence + 1) >>> 0;\n return payload;\n }\n\n /**\n * With AES-GCM the length is authenticated but not encrypted, so the frame\n * can be measured before anything is decrypted (RFC 5647).\n */\n #takeEncryptedFrame() {\n if (this.buffer.length < 4) return null;\n const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n const packetLength = view.getUint32(0, false);\n if (packetLength < GCM_BLOCK || packetLength % GCM_BLOCK !== 0 || packetLength > MAX_PACKET_BYTES) {\n throw new Error('SSH: the host sent a packet of an impossible size.');\n }\n\n const total = 4 + packetLength + GCM_TAG_BYTES;\n if (this.buffer.length < total) return null;\n\n const frame = this.buffer.slice(0, total);\n this.buffer = this.buffer.subarray(total);\n return frame;\n }\n\n async #decrypt(frame: Uint8Array) {\n let plain;\n try {\n plain = new Uint8Array(await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: this.incoming.nextIv(),\n additionalData: frame.subarray(0, 4),\n tagLength: GCM_TAG_BYTES * 8,\n },\n this.incoming.key,\n frame.subarray(4)\n ));\n } catch {\n throw new Error('SSH: a packet failed its integrity check, so the session was dropped.');\n }\n\n const paddingLength = plain[0];\n if (paddingLength + 1 > plain.length) throw new Error('SSH: a packet claimed more padding than it had.');\n this.receiveSequence = (this.receiveSequence + 1) >>> 0;\n return plain.slice(1, plain.length - paddingLength);\n }\n\n #dispatchPacket(payload: Uint8Array) {\n if (payload.length === 0) return;\n const type = payload[0];\n\n switch (type) {\n case MSG.DISCONNECT: {\n const reader = new SshReader(payload, 1);\n const code = reader.u32();\n const description = reader.string();\n const reason = description || DISCONNECT_REASON[code] || `reason ${code}`;\n this.dispatchEvent(new CustomEvent('hostdisconnect', { detail: { code, reason } }));\n this.#finish({ clean: code === 11, code: 1000, message: reason });\n try { this.socket?.close(1000, 'Host disconnected'); } catch {}\n return;\n }\n case MSG.IGNORE:\n case MSG.UNIMPLEMENTED:\n case MSG.EXT_INFO:\n return;\n case MSG.DEBUG: {\n const reader = new SshReader(payload, 1);\n const alwaysDisplay = reader.boolean();\n const message = reader.string();\n this.log('debug', { message, alwaysDisplay });\n if (alwaysDisplay) {\n this.dispatchEvent(new CustomEvent('banner', { detail: { text: `${message}\\r\\n` } }));\n }\n return;\n }\n case MSG.KEXINIT:\n void this.#onKexInit(payload);\n return;\n case MSG.NEWKEYS:\n this.#onNewKeys();\n return;\n case MSG.GLOBAL_REQUEST: {\n const reader = new SshReader(payload, 1);\n reader.string();\n if (reader.boolean()) this.#sendPacket(new Uint8Array([MSG.REQUEST_FAILURE]));\n return;\n }\n // The answer to the keepalive global request. Either one means the host\n // is still there, which is the whole point of having asked.\n case MSG.REQUEST_SUCCESS:\n case MSG.REQUEST_FAILURE:\n return;\n default:\n break;\n }\n\n // A key exchange packet can only be answered by the exchange that is\n // running, and everything else belongs to the layers above.\n if (this.kex && type >= 30 && type <= 49) {\n this.#deliverKexPacket(payload);\n return;\n }\n this.dispatchEvent(new CustomEvent('packet', { detail: { type, payload } }));\n }\n\n // --- sending -------------------------------------------------------------\n\n /** Application packets wait while a key exchange is in flight (RFC 4253 7.1). */\n send(payload: Uint8Array) {\n if (this.closed) return false;\n if (this.kex?.running) {\n this.kexQueue.push(payload);\n return true;\n }\n this.#sendPacket(payload);\n return true;\n }\n\n #sendPacket(payload: Uint8Array) {\n if (this.closed || this.socket?.readyState !== WebSocket.OPEN) return;\n if (!this.outgoing) {\n this.#write(framePlain(payload));\n this.sendSequence = (this.sendSequence + 1) >>> 0;\n return;\n }\n void this.#encrypt(payload);\n }\n\n async #encrypt(payload: Uint8Array) {\n // Packets must reach the host in the order they were built, and encryption\n // is asynchronous, so each one waits for the one before it.\n const previous = this.encryptChain || Promise.resolve();\n this.encryptChain = previous.then(async () => {\n if (this.closed || !this.outgoing) return;\n\n const paddingLength = gcmPaddingLength(payload.length);\n const plain = new Uint8Array(1 + payload.length + paddingLength);\n plain[0] = paddingLength;\n plain.set(payload, 1);\n crypto.getRandomValues(plain.subarray(1 + payload.length));\n\n const header = new SshWriter(4).u32(plain.length).take();\n const sealed = new Uint8Array(await subtle.encrypt(\n { name: 'AES-GCM', iv: this.outgoing.nextIv(), additionalData: header, tagLength: GCM_TAG_BYTES * 8 },\n this.outgoing.key,\n plain\n ));\n\n this.#write(concatBytes(header, sealed));\n this.sendSequence = (this.sendSequence + 1) >>> 0;\n }).catch((error: unknown) => this.fail(error));\n\n return this.encryptChain;\n }\n\n // --- key exchange --------------------------------------------------------\n\n async #startKex() {\n if (this.kex?.running) return;\n\n // Claimed before the first await: the host's own KEXINIT is usually already\n // on the wire, and two exchanges starting at once would send two of ours.\n this.kex = { running: true, clientKexInit: null, pending: null, inbox: [] };\n\n try {\n const offer = await negotiableAlgorithms();\n const clientKexInit = buildKexInit(offer);\n this.kex.clientKexInit = clientKexInit;\n this.#sendPacket(clientKexInit);\n\n const serverKexInit = this.pendingServerKexInit || await this.#nextKexPacket(MSG.KEXINIT);\n this.pendingServerKexInit = null;\n await this.#runKex(offer, clientKexInit, serverKexInit);\n } catch (error) {\n this.fail(error);\n }\n }\n\n /** The host may ask for new keys at any point in a session. */\n async #onKexInit(payload: Uint8Array) {\n if (this.kex?.running) {\n this.#deliverKexPacket(payload);\n return;\n }\n\n this.log('rekey', { reason: 'the host asked for new keys' });\n this.pendingServerKexInit = payload;\n await this.#startKex();\n }\n\n /**\n * Key exchange packets can arrive before the step that wants them: the host\n * sends its reply and NEWKEYS back to back, while this side is still\n * deriving a secret or waiting for the user to accept a host key. They are\n * queued rather than dropped.\n */\n #deliverKexPacket(payload: Uint8Array) {\n if (!this.kex) return;\n if (this.kex.pending) {\n const pending = this.kex.pending;\n this.kex.pending = null;\n pending(payload);\n return;\n }\n this.kex.inbox.push(payload);\n }\n\n #nextKexPacket(expectedType) {\n return new Promise((resolve, reject) => {\n const check = (payload: Uint8Array) => {\n if (expectedType !== undefined && payload[0] !== expectedType) {\n reject(new Error(`SSH: expected message ${expectedType} during key exchange but got ${payload[0]}.`));\n return;\n }\n resolve(payload);\n };\n\n const queued = this.kex.inbox.shift();\n if (queued) {\n check(queued);\n return;\n }\n this.kex.pending = (payload: Uint8Array) => {\n this.kex.pending = null;\n check(payload);\n };\n });\n }\n\n async #runKex(offer, clientKexInit: Uint8Array, serverKexInit: Uint8Array) {\n const server = parseKexInit(serverKexInit);\n const kexAlgorithm = negotiate(offer.kex, server.kex);\n const hostKeyAlgorithm = negotiate(offer.hostKey, server.hostKey);\n const cipherToServer = negotiate(CIPHER_NAMES, server.cipherClientToServer);\n const cipherToClient = negotiate(CIPHER_NAMES, server.cipherServerToClient);\n\n if (!kexAlgorithm) throw new Error(`SSH: no shared key exchange method. The host offers ${server.kex.join(', ')}.`);\n if (!hostKeyAlgorithm) throw new Error(`SSH: no host key type this browser can verify. The host offers ${server.hostKey.join(', ')}.`);\n if (!cipherToServer || !cipherToClient) {\n throw new Error(`SSH: the host does not offer AES-GCM, which is the only cipher this client can use. It offers ${server.cipherServerToClient.join(', ')}.`);\n }\n\n this.log('negotiated', {\n kex: kexAlgorithm,\n hostKey: hostKeyAlgorithm,\n cipher: cipherToClient,\n rekey: Boolean(this.sessionId),\n });\n\n const client = await createKexClient(kexAlgorithm);\n this.#sendPacket(new SshWriter(128).u8(MSG.KEX_ECDH_INIT).string(client.publicKey).take());\n\n const reply = new SshReader(await this.#nextKexPacket(MSG.KEX_ECDH_REPLY), 1);\n const hostKeyBlob = reply.stringBytes();\n const serverPublicKey = reply.stringBytes();\n const signatureBlob = reply.stringBytes();\n\n const sharedSecret = await client.sharedSecret(serverPublicKey);\n const hash = await exchangeHash({\n hash: client.hash,\n clientVersion: CLIENT_VERSION,\n serverVersion: this.serverVersion,\n clientKexInit,\n serverKexInit,\n hostKeyBlob,\n clientPublicKey: client.publicKey,\n serverPublicKey,\n sharedSecret,\n });\n\n const signatureValid = await verifyHostKeySignature({\n algorithm: hostKeyAlgorithm,\n keyBlob: hostKeyBlob,\n signatureBlob,\n exchangeHash: hash,\n });\n if (!signatureValid) {\n throw new Error('SSH: the host key signature is invalid, so this is not the machine it claims to be.');\n }\n\n const fingerprint = await hostKeyFingerprint(hostKeyBlob);\n if (!this.sessionId) {\n // Trust is decided once per connection, against the key that has just\n // proved it owns this exchange.\n const accepted = await this.verifyHost({\n fingerprint,\n keyType: hostKeyType(hostKeyBlob),\n algorithm: hostKeyAlgorithm,\n });\n if (!accepted) throw new Error('SSH: the host key was not accepted, so the connection was stopped.');\n this.sessionId = hash;\n }\n\n this.#sendPacket(new Uint8Array([MSG.NEWKEYS]));\n await this.#nextKexPacket(MSG.NEWKEYS);\n\n const parameters = {\n hash: client.hash,\n sharedSecret,\n exchangeHash: hash,\n sessionId: this.sessionId,\n };\n const [ivToServer, ivToClient, keyToServer, keyToClient] = await Promise.all([\n deriveKey({ ...parameters, letter: 'A', length: GCM_IV_BYTES }),\n deriveKey({ ...parameters, letter: 'B', length: GCM_IV_BYTES }),\n deriveKey({ ...parameters, letter: 'C', length: CIPHERS[cipherToServer].keyLength }),\n deriveKey({ ...parameters, letter: 'D', length: CIPHERS[cipherToClient].keyLength }),\n ]);\n\n this.outgoing = await GcmCipher.create(keyToServer, ivToServer);\n this.incoming = await GcmCipher.create(keyToClient, ivToClient);\n this.kex.running = false;\n\n // Both ciphers exist now, so the reader may go on.\n this.releaseNewKeys?.();\n this.releaseNewKeys = null;\n\n const queued = this.kexQueue;\n this.kexQueue = [];\n for (const payload of queued) this.#sendPacket(payload);\n\n const firstTime = !this.established;\n this.established = true;\n this.dispatchEvent(new CustomEvent('keys', {\n detail: { fingerprint, kexAlgorithm, hostKeyAlgorithm, cipher: cipherToClient, firstTime },\n }));\n }\n\n #onNewKeys() {\n if (!this.kex) return;\n\n // Hold the reader here: the host's very next packet is already encrypted\n // with keys this side has not derived yet.\n this.newKeysBarrier = new Promise((resolve) => { this.releaseNewKeys = resolve; });\n this.#deliverKexPacket(new Uint8Array([MSG.NEWKEYS]));\n }\n}\n\n/** Padding for a GCM packet: only the encrypted part is block aligned. */\nexport function gcmPaddingLength(payloadLength) {\n const unpadded = 1 + payloadLength;\n let padding = GCM_BLOCK - (unpadded % GCM_BLOCK);\n while (padding < MIN_PADDING) padding += GCM_BLOCK;\n return padding;\n}\n\n/** A packet before any keys exist: the whole thing is block aligned. */\nexport function framePlain(payload: Uint8Array) {\n const unpadded = 5 + payload.length;\n let padding = PLAIN_BLOCK - (unpadded % PLAIN_BLOCK);\n if (padding < MIN_PADDING) padding += PLAIN_BLOCK;\n\n const writer = new SshWriter(unpadded + padding);\n writer.u32(1 + payload.length + padding);\n writer.u8(padding);\n writer.raw(payload);\n const frame = writer.take();\n const filler = new Uint8Array(padding);\n crypto.getRandomValues(filler);\n return concatBytes(frame, filler);\n}\n\nexport function buildKexInit(offer) {\n const cookie = new Uint8Array(16);\n crypto.getRandomValues(cookie);\n\n const writer = new SshWriter(512);\n writer.u8(MSG.KEXINIT).raw(cookie);\n writer.nameList(offer.kex);\n writer.nameList(offer.hostKey);\n writer.nameList(CIPHER_NAMES); // client to server\n writer.nameList(CIPHER_NAMES); // server to client\n writer.nameList(MAC_NAMES);\n writer.nameList(MAC_NAMES);\n writer.nameList(COMPRESSION_NAMES);\n writer.nameList(COMPRESSION_NAMES);\n writer.nameList([]); // languages\n writer.nameList([]);\n writer.boolean(false); // no guessed key exchange packet\n writer.u32(0); // reserved\n return writer.take();\n}\n\nexport function parseKexInit(payload: Uint8Array) {\n const reader = new SshReader(payload, 17); // message number and cookie\n return {\n kex: reader.nameList(),\n hostKey: reader.nameList(),\n cipherClientToServer: reader.nameList(),\n cipherServerToClient: reader.nameList(),\n macClientToServer: reader.nameList(),\n macServerToClient: reader.nameList(),\n compressionClientToServer: reader.n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SAAS,iBAAiB;AACjC,SAAO,SAAS,CAAC,CAAC;AAClB,SAAO,SAAS,CAAC,CAAC;AAClB,SAAO,QAAQ,KAAK;AACpB,SAAO,IAAI,CAAC;AACZ,SAAO,OAAO,KAAK;AACrB;AAEO,SAAS,aAAa,SAAqB;AAChD,QAAM,SAAS,IAAI,UAAU,SAAS,EAAE;AACxC,SAAO;AAAA,IACL,KAAK,OAAO,SAAS;AAAA,IACrB,SAAS,OAAO,SAAS;AAAA,IACzB,sBAAsB,OAAO,SAAS;AAAA,IACtC,sBAAsB,OAAO,SAAS;AAAA,IACtC,mBAAmB,OAAO,SAAS;AAAA,IACnC,mBAAmB,OAAO,SAAS;AAAA,IACnC,2BAA2B,OAAO,SAAS;AAAA,IAC3C,2BAA2B,OAAO,SAAS;AAAA,EAC7C;AACF;",
4
+ "sourcesContent": ["// The SSH transport layer (RFC 4253): version exchange, the binary packet\n// protocol, key exchange, and the AES-GCM cipher that protects everything\n// after it.\n//\n// Like the RDP client, this runs entirely in the browser. The gateway's\n// /ssh-ws endpoint is a byte relay and never sees a decrypted packet or a\n// password; the keys derived here exist only in this tab.\n\nimport { MSG, DISCONNECT_REASON } from './messages';\nimport {\n SshReader,\n SshWriter,\n concatBytes,\n encodeUtf8,\n} from './wire';\nimport {\n createKexClient,\n deriveKey,\n exchangeHash,\n hostKeyFingerprint,\n hostKeyType,\n negotiableAlgorithms,\n verifyHostKeySignature,\n} from './kex';\nimport {\n GATEWAY_KEEPALIVE_SIGNAL,\n GATEWAY_READY_SIGNAL,\n KEEPALIVE_INTERVAL_MS,\n} from '../../shared/signals';\n\nexport const CLIENT_VERSION = 'SSH-2.0-CloudflareGateway_1.0';\n\n/** Only AEAD ciphers are offered, so the MAC list is never actually used. */\nconst CIPHERS = {\n 'aes256-gcm@openssh.com': { keyLength: 32 },\n 'aes128-gcm@openssh.com': { keyLength: 16 },\n};\nconst CIPHER_NAMES = Object.keys(CIPHERS);\nconst MAC_NAMES = ['hmac-sha2-256', 'hmac-sha2-512'];\nconst COMPRESSION_NAMES = ['none'];\n\nconst GCM_BLOCK = 16;\nconst GCM_TAG_BYTES = 16;\nconst GCM_IV_BYTES = 12;\nconst PLAIN_BLOCK = 8;\nconst MIN_PADDING = 4;\nconst MAX_PACKET_BYTES = 262_144;\nconst VERSION_LINE_LIMIT = 8_192;\n\nconst subtle = globalThis.crypto?.subtle;\n\n/** Pick the first client preference the host also offered (RFC 4253 7.1). */\nexport function negotiate(clientNames, serverNames) {\n return clientNames.find((name: string) => serverNames.includes(name)) || null;\n}\n\n/** An AES-GCM direction: one key, and an invocation counter that never repeats. */\nclass GcmCipher {\n key: CryptoKey;\n fixed: Uint8Array;\n counter: Uint8Array;\n\n constructor(key: CryptoKey, iv: Uint8Array) {\n this.key = key;\n this.fixed = iv.slice(0, 4);\n this.counter = iv.slice(4, 12);\n }\n\n static async create(keyBytes: Uint8Array, iv: Uint8Array) {\n const key = await subtle.importKey('raw', keyBytes as unknown as BufferSource, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);\n return new GcmCipher(key, iv);\n }\n\n /** The 12-byte nonce for this packet, then step the 64-bit counter. */\n nextIv() {\n const iv = concatBytes(this.fixed, this.counter);\n for (let index = this.counter.length - 1; index >= 0; index--) {\n this.counter[index] = (this.counter[index] + 1) & 0xff;\n if (this.counter[index] !== 0) break;\n }\n return iv;\n }\n}\n\nexport class SshTransport extends EventTarget {\n url: string;\n verifyHost: (info: any) => Promise<boolean> | boolean;\n log: (...args: any[]) => void;\n socket: WebSocket | null;\n openTransport: ((url: string) => any) | null;\n closed: boolean;\n buffer: Uint8Array;\n serverVersion: string;\n greeting: string[];\n sendSequence: number;\n receiveSequence: number;\n outgoing: any;\n incoming: any;\n sessionId: Uint8Array | null;\n kex: any;\n kexQueue: Uint8Array[];\n keepaliveTimer: any;\n bytesSent: number;\n bytesReceived: number;\n encryptChain?: Promise<void>;\n newKeysBarrier?: Promise<void> | null;\n releaseNewKeys?: (() => void) | null;\n pendingServerKexInit?: Uint8Array | null;\n established?: boolean;\n\n /**\n * @param {string} url gateway WebSocket URL\n * @param {object} options\n * @param {(info: object) => Promise<boolean>} options.verifyHost decides\n * whether an unknown or changed host key may be used.\n */\n constructor(\n url: string,\n { verifyHost, log, openTransport }: {\n verifyHost?: (info: any) => Promise<boolean> | boolean;\n log?: (...args: any[]) => void;\n /** Returns a WebSocket-shaped transport for `url`; default is a real one. */\n openTransport?: ((url: string) => any) | null;\n } = {}\n ) {\n super();\n\n this.url = url;\n this.verifyHost = verifyHost || (() => true);\n this.log = log || (() => {});\n this.openTransport = openTransport || null;\n\n this.socket = null;\n this.closed = false;\n this.buffer = new Uint8Array(0);\n this.serverVersion = '';\n this.greeting = [];\n\n this.sendSequence = 0;\n this.receiveSequence = 0;\n this.outgoing = null;\n this.incoming = null;\n this.sessionId = null;\n\n this.kex = null;\n this.kexQueue = [];\n this.keepaliveTimer = null;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n }\n\n // --- connection ----------------------------------------------------------\n\n connect() {\n // Injected so this client can run anywhere: a WebSocket to the gateway in\n // a browser, a TCP socket straight at the host in the CLI. The key\n // exchange and everything above it is identical either way.\n this.socket = this.openTransport ? this.openTransport(this.url) : new WebSocket(this.url);\n this.socket.binaryType = 'arraybuffer';\n\n this.socket.addEventListener('open', () => {\n // The relay holds the host's first bytes until the browser says it is\n // listening, exactly as the RDP client does.\n this.socket.send(GATEWAY_READY_SIGNAL);\n this.#write(encodeUtf8(`${CLIENT_VERSION}\\r\\n`));\n this.keepaliveTimer = setInterval(() => {\n if (this.socket?.readyState !== WebSocket.OPEN) return;\n\n // Keeps the browser-to-gateway WebSocket alive. The gateway absorbs\n // this frame, so it never reaches the host.\n this.socket.send(GATEWAY_KEEPALIVE_SIGNAL);\n\n // Which leaves the TCP leg silent whenever nobody is typing, and an\n // idle TCP connection through a tunnel is a TCP connection about to be\n // dropped. This is the request OpenSSH itself uses to keep one warm:\n // servers answer it with a failure, which is a perfectly good answer --\n // the point is the bytes, not the reply.\n if (this.sessionId) {\n try {\n this.#sendPacket(new SshWriter(64)\n .u8(MSG.GLOBAL_REQUEST)\n .string('keepalive@openssh.com')\n .u8(1)\n .take());\n } catch {\n // A keepalive is not worth breaking a working session over.\n }\n }\n }, KEEPALIVE_INTERVAL_MS);\n });\n\n this.socket.addEventListener('message', (event) => {\n if (typeof event.data === 'string') return; // gateway control frame\n this.#receive(new Uint8Array(event.data));\n });\n\n this.socket.addEventListener('close', (event) => {\n this.#finish({\n clean: event.code === 1000,\n code: event.code,\n message: event.reason || (\n event.code === 1006\n ? 'The gateway rejected or could not reach this SSH target. Confirm that SSH is published for this host.'\n : ''\n ),\n });\n });\n\n // A failed WebSocket upgrade emits `error` immediately followed by\n // `close`. The error event has no HTTP status or response body, while a\n // relay that connected successfully can put the useful TCP failure in the\n // close reason. Waiting for `close` preserves that explanation instead of\n // replacing it with an opaque generic error.\n this.socket.addEventListener('error', () => {\n this.log('The SSH gateway WebSocket reported a transport error; waiting for its close reason.');\n });\n }\n\n disconnect(message = 'Client disconnected') {\n if (this.closed) return;\n try {\n const payload = new SshWriter(64)\n .u8(MSG.DISCONNECT).u32(11).string(message).string('')\n .take();\n this.#sendPacket(payload);\n } catch {}\n // The packet may still be encrypting, and closing the socket under it\n // would drop the goodbye the host is waiting for.\n const socket = this.socket;\n void Promise.resolve(this.encryptChain).finally(() => {\n try { socket?.close(1000, 'Client disconnected'); } catch {}\n });\n this.#finish({ clean: true, code: 1000, message: '' });\n }\n\n #finish(detail) {\n if (this.closed) return;\n this.closed = true;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n this.dispatchEvent(new CustomEvent('close', { detail }));\n }\n\n fail(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n if (this.closed) return;\n this.dispatchEvent(new CustomEvent('error', { detail: { message } }));\n this.#finish({ clean: false, code: 4000, message });\n try { this.socket?.close(4000, message.slice(0, 100)); } catch {}\n }\n\n #write(bytes: Uint8Array) {\n if (this.socket?.readyState !== WebSocket.OPEN) return;\n this.bytesSent += bytes.length;\n this.socket.send(bytes);\n }\n\n // --- framing -------------------------------------------------------------\n\n #receive(chunk: Uint8Array) {\n this.bytesReceived += chunk.length;\n this.buffer = this.buffer.length ? concatBytes(this.buffer, chunk) : chunk;\n\n // Decryption is asynchronous, so the reader is a single chain rather than\n // a loop: two overlapping drains could deliver packets out of order, and\n // an out-of-order packet is a broken session.\n this.drainChain = (this.drainChain || Promise.resolve())\n .then(() => this.#drain())\n .catch((error: unknown) => this.fail(error));\n }\n\n async #drain() {\n if (this.closed) return;\n if (!this.serverVersion && !this.#readVersion()) return;\n\n while (!this.closed) {\n // The host's NEWKEYS is the last packet under the old cipher. Nothing\n // after it can be read until the new one is installed.\n if (this.newKeysBarrier) {\n const barrier = this.newKeysBarrier;\n this.newKeysBarrier = null;\n await barrier;\n continue;\n }\n\n if (!this.incoming) {\n const payload = this.#readPlainPacket();\n if (!payload) return;\n this.#dispatchPacket(payload);\n continue;\n }\n\n const frame = this.#takeEncryptedFrame();\n if (!frame) return;\n this.#dispatchPacket(await this.#decrypt(frame));\n }\n }\n\n /**\n * The host may print any number of lines before its version line, and RFC\n * 4253 says to show them: this is where a \"banned by fail2ban\" notice or a\n * legal banner arrives.\n */\n #readVersion() {\n while (true) {\n const newline = this.buffer.indexOf(0x0a);\n if (newline === -1) {\n if (this.buffer.length > VERSION_LINE_LIMIT) {\n throw new Error('SSH: the host sent no version line.');\n }\n return false;\n }\n\n let end = newline;\n if (end > 0 && this.buffer[end - 1] === 0x0d) end--;\n const line = new TextDecoder().decode(this.buffer.subarray(0, end));\n this.buffer = this.buffer.subarray(newline + 1);\n\n if (!line.startsWith('SSH-')) {\n if (line.trim()) this.greeting.push(line);\n continue;\n }\n if (!line.startsWith('SSH-2.0-') && !line.startsWith('SSH-1.99-')) {\n throw new Error(`SSH: this host speaks ${line.split('-').slice(0, 2).join('-')}, which is too old.`);\n }\n\n this.serverVersion = line;\n this.log('version', { server: line, greeting: this.greeting });\n this.dispatchEvent(new CustomEvent('greeting', { detail: { lines: this.greeting.slice() } }));\n void this.#startKex();\n return true;\n }\n }\n\n /** A packet from before the keys exist. Returns null when more bytes are due. */\n #readPlainPacket() {\n if (this.buffer.length < 5) return null;\n const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n const packetLength = view.getUint32(0, false);\n if (packetLength < 8 || packetLength > MAX_PACKET_BYTES) {\n throw new Error('SSH: the host sent a packet of an impossible size.');\n }\n if (this.buffer.length < 4 + packetLength) return null;\n\n const paddingLength = this.buffer[4];\n if (paddingLength + 1 > packetLength) throw new Error('SSH: a packet claimed more padding than it had.');\n const payload = this.buffer.slice(5, 4 + packetLength - paddingLength);\n this.buffer = this.buffer.subarray(4 + packetLength);\n this.receiveSequence = (this.receiveSequence + 1) >>> 0;\n return payload;\n }\n\n /**\n * With AES-GCM the length is authenticated but not encrypted, so the frame\n * can be measured before anything is decrypted (RFC 5647).\n */\n #takeEncryptedFrame() {\n if (this.buffer.length < 4) return null;\n const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n const packetLength = view.getUint32(0, false);\n if (packetLength < GCM_BLOCK || packetLength % GCM_BLOCK !== 0 || packetLength > MAX_PACKET_BYTES) {\n throw new Error('SSH: the host sent a packet of an impossible size.');\n }\n\n const total = 4 + packetLength + GCM_TAG_BYTES;\n if (this.buffer.length < total) return null;\n\n const frame = this.buffer.slice(0, total);\n this.buffer = this.buffer.subarray(total);\n return frame;\n }\n\n async #decrypt(frame: Uint8Array) {\n let plain;\n try {\n plain = new Uint8Array(await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: this.incoming.nextIv(),\n additionalData: frame.subarray(0, 4),\n tagLength: GCM_TAG_BYTES * 8,\n },\n this.incoming.key,\n frame.subarray(4)\n ));\n } catch {\n throw new Error('SSH: a packet failed its integrity check, so the session was dropped.');\n }\n\n const paddingLength = plain[0];\n if (paddingLength + 1 > plain.length) throw new Error('SSH: a packet claimed more padding than it had.');\n this.receiveSequence = (this.receiveSequence + 1) >>> 0;\n return plain.slice(1, plain.length - paddingLength);\n }\n\n #dispatchPacket(payload: Uint8Array) {\n if (payload.length === 0) return;\n const type = payload[0];\n\n switch (type) {\n case MSG.DISCONNECT: {\n const reader = new SshReader(payload, 1);\n const code = reader.u32();\n const description = reader.string();\n const reason = description || DISCONNECT_REASON[code] || `reason ${code}`;\n this.dispatchEvent(new CustomEvent('hostdisconnect', { detail: { code, reason } }));\n this.#finish({ clean: code === 11, code: 1000, message: reason });\n try { this.socket?.close(1000, 'Host disconnected'); } catch {}\n return;\n }\n case MSG.IGNORE:\n case MSG.UNIMPLEMENTED:\n case MSG.EXT_INFO:\n return;\n case MSG.DEBUG: {\n const reader = new SshReader(payload, 1);\n const alwaysDisplay = reader.boolean();\n const message = reader.string();\n this.log('debug', { message, alwaysDisplay });\n if (alwaysDisplay) {\n this.dispatchEvent(new CustomEvent('banner', { detail: { text: `${message}\\r\\n` } }));\n }\n return;\n }\n case MSG.KEXINIT:\n void this.#onKexInit(payload);\n return;\n case MSG.NEWKEYS:\n this.#onNewKeys();\n return;\n case MSG.GLOBAL_REQUEST: {\n const reader = new SshReader(payload, 1);\n reader.string();\n if (reader.boolean()) this.#sendPacket(new Uint8Array([MSG.REQUEST_FAILURE]));\n return;\n }\n // The answer to the keepalive global request. Either one means the host\n // is still there, which is the whole point of having asked.\n case MSG.REQUEST_SUCCESS:\n case MSG.REQUEST_FAILURE:\n return;\n default:\n break;\n }\n\n // A key exchange packet can only be answered by the exchange that is\n // running, and everything else belongs to the layers above.\n if (this.kex && type >= 30 && type <= 49) {\n this.#deliverKexPacket(payload);\n return;\n }\n this.dispatchEvent(new CustomEvent('packet', { detail: { type, payload } }));\n }\n\n // --- sending -------------------------------------------------------------\n\n /** Application packets wait while a key exchange is in flight (RFC 4253 7.1). */\n send(payload: Uint8Array) {\n if (this.closed) return false;\n if (this.kex?.running) {\n this.kexQueue.push(payload);\n return true;\n }\n this.#sendPacket(payload);\n return true;\n }\n\n #sendPacket(payload: Uint8Array) {\n if (this.closed || this.socket?.readyState !== WebSocket.OPEN) return;\n if (!this.outgoing) {\n this.#write(framePlain(payload));\n this.sendSequence = (this.sendSequence + 1) >>> 0;\n return;\n }\n void this.#encrypt(payload);\n }\n\n async #encrypt(payload: Uint8Array) {\n // Packets must reach the host in the order they were built, and encryption\n // is asynchronous, so each one waits for the one before it.\n const previous = this.encryptChain || Promise.resolve();\n this.encryptChain = previous.then(async () => {\n if (this.closed || !this.outgoing) return;\n\n const paddingLength = gcmPaddingLength(payload.length);\n const plain = new Uint8Array(1 + payload.length + paddingLength);\n plain[0] = paddingLength;\n plain.set(payload, 1);\n crypto.getRandomValues(plain.subarray(1 + payload.length));\n\n const header = new SshWriter(4).u32(plain.length).take();\n const sealed = new Uint8Array(await subtle.encrypt(\n { name: 'AES-GCM', iv: this.outgoing.nextIv(), additionalData: header, tagLength: GCM_TAG_BYTES * 8 },\n this.outgoing.key,\n plain\n ));\n\n this.#write(concatBytes(header, sealed));\n this.sendSequence = (this.sendSequence + 1) >>> 0;\n }).catch((error: unknown) => this.fail(error));\n\n return this.encryptChain;\n }\n\n // --- key exchange --------------------------------------------------------\n\n async #startKex() {\n if (this.kex?.running) return;\n\n // Claimed before the first await: the host's own KEXINIT is usually already\n // on the wire, and two exchanges starting at once would send two of ours.\n this.kex = { running: true, clientKexInit: null, pending: null, inbox: [] };\n\n try {\n const offer = await negotiableAlgorithms();\n const clientKexInit = buildKexInit(offer);\n this.kex.clientKexInit = clientKexInit;\n this.#sendPacket(clientKexInit);\n\n const serverKexInit = this.pendingServerKexInit || await this.#nextKexPacket(MSG.KEXINIT);\n this.pendingServerKexInit = null;\n await this.#runKex(offer, clientKexInit, serverKexInit);\n } catch (error) {\n this.fail(error);\n }\n }\n\n /** The host may ask for new keys at any point in a session. */\n async #onKexInit(payload: Uint8Array) {\n if (this.kex?.running) {\n this.#deliverKexPacket(payload);\n return;\n }\n\n this.log('rekey', { reason: 'the host asked for new keys' });\n this.pendingServerKexInit = payload;\n await this.#startKex();\n }\n\n /**\n * Key exchange packets can arrive before the step that wants them: the host\n * sends its reply and NEWKEYS back to back, while this side is still\n * deriving a secret or waiting for the user to accept a host key. They are\n * queued rather than dropped.\n */\n #deliverKexPacket(payload: Uint8Array) {\n if (!this.kex) return;\n if (this.kex.pending) {\n const pending = this.kex.pending;\n this.kex.pending = null;\n pending(payload);\n return;\n }\n this.kex.inbox.push(payload);\n }\n\n #nextKexPacket(expectedType) {\n return new Promise((resolve, reject) => {\n const check = (payload: Uint8Array) => {\n if (expectedType !== undefined && payload[0] !== expectedType) {\n reject(new Error(`SSH: expected message ${expectedType} during key exchange but got ${payload[0]}.`));\n return;\n }\n resolve(payload);\n };\n\n const queued = this.kex.inbox.shift();\n if (queued) {\n check(queued);\n return;\n }\n this.kex.pending = (payload: Uint8Array) => {\n this.kex.pending = null;\n check(payload);\n };\n });\n }\n\n async #runKex(offer, clientKexInit: Uint8Array, serverKexInit: Uint8Array) {\n const server = parseKexInit(serverKexInit);\n const kexAlgorithm = negotiate(offer.kex, server.kex);\n const hostKeyAlgorithm = negotiate(offer.hostKey, server.hostKey);\n const cipherToServer = negotiate(CIPHER_NAMES, server.cipherClientToServer);\n const cipherToClient = negotiate(CIPHER_NAMES, server.cipherServerToClient);\n\n if (!kexAlgorithm) throw new Error(`SSH: no shared key exchange method. The host offers ${server.kex.join(', ')}.`);\n if (!hostKeyAlgorithm) throw new Error(`SSH: no host key type this browser can verify. The host offers ${server.hostKey.join(', ')}.`);\n if (!cipherToServer || !cipherToClient) {\n throw new Error(`SSH: the host does not offer AES-GCM, which is the only cipher this client can use. It offers ${server.cipherServerToClient.join(', ')}.`);\n }\n\n this.log('negotiated', {\n kex: kexAlgorithm,\n hostKey: hostKeyAlgorithm,\n cipher: cipherToClient,\n rekey: Boolean(this.sessionId),\n });\n\n const client = await createKexClient(kexAlgorithm);\n this.#sendPacket(new SshWriter(128).u8(MSG.KEX_ECDH_INIT).string(client.publicKey).take());\n\n const reply = new SshReader(await this.#nextKexPacket(MSG.KEX_ECDH_REPLY), 1);\n const hostKeyBlob = reply.stringBytes();\n const serverPublicKey = reply.stringBytes();\n const signatureBlob = reply.stringBytes();\n\n const sharedSecret = await client.sharedSecret(serverPublicKey);\n const hash = await exchangeHash({\n hash: client.hash,\n clientVersion: CLIENT_VERSION,\n serverVersion: this.serverVersion,\n clientKexInit,\n serverKexInit,\n hostKeyBlob,\n clientPublicKey: client.publicKey,\n serverPublicKey,\n sharedSecret,\n });\n\n const signatureValid = await verifyHostKeySignature({\n algorithm: hostKeyAlgorithm,\n keyBlob: hostKeyBlob,\n signatureBlob,\n exchangeHash: hash,\n });\n if (!signatureValid) {\n throw new Error('SSH: the host key signature is invalid, so this is not the machine it claims to be.');\n }\n\n const fingerprint = await hostKeyFingerprint(hostKeyBlob);\n if (!this.sessionId) {\n // Trust is decided once per connection, against the key that has just\n // proved it owns this exchange.\n const accepted = await this.verifyHost({\n fingerprint,\n keyType: hostKeyType(hostKeyBlob),\n algorithm: hostKeyAlgorithm,\n });\n if (!accepted) throw new Error('SSH: the host key was not accepted, so the connection was stopped.');\n this.sessionId = hash;\n }\n\n this.#sendPacket(new Uint8Array([MSG.NEWKEYS]));\n await this.#nextKexPacket(MSG.NEWKEYS);\n\n const parameters = {\n hash: client.hash,\n sharedSecret,\n exchangeHash: hash,\n sessionId: this.sessionId,\n };\n const [ivToServer, ivToClient, keyToServer, keyToClient] = await Promise.all([\n deriveKey({ ...parameters, letter: 'A', length: GCM_IV_BYTES }),\n deriveKey({ ...parameters, letter: 'B', length: GCM_IV_BYTES }),\n deriveKey({ ...parameters, letter: 'C', length: CIPHERS[cipherToServer].keyLength }),\n deriveKey({ ...parameters, letter: 'D', length: CIPHERS[cipherToClient].keyLength }),\n ]);\n\n this.outgoing = await GcmCipher.create(keyToServer, ivToServer);\n this.incoming = await GcmCipher.create(keyToClient, ivToClient);\n this.kex.running = false;\n\n // Both ciphers exist now, so the reader may go on.\n this.releaseNewKeys?.();\n this.releaseNewKeys = null;\n\n const queued = this.kexQueue;\n this.kexQueue = [];\n for (const payload of queued) this.#sendPacket(payload);\n\n const firstTime = !this.established;\n this.established = true;\n this.dispatchEvent(new CustomEvent('keys', {\n detail: { fingerprint, kexAlgorithm, hostKeyAlgorithm, cipher: cipherToClient, firstTime },\n }));\n }\n\n #onNewKeys() {\n if (!this.kex) return;\n\n // Hold the reader here: the host's very next packet is already encrypted\n // with keys this side has not derived yet.\n this.newKeysBarrier = new Promise((resolve) => { this.releaseNewKeys = resolve; });\n this.#deliverKexPacket(new Uint8Array([MSG.NEWKEYS]));\n }\n}\n\n/** Padding for a GCM packet: only the encrypted part is block aligned. */\nexport function gcmPaddingLength(payloadLength) {\n const unpadded = 1 + payloadLength;\n let padding = GCM_BLOCK - (unpadded % GCM_BLOCK);\n while (padding < MIN_PADDING) padding += GCM_BLOCK;\n return padding;\n}\n\n/** A packet before any keys exist: the whole thing is block aligned. */\nexport function framePlain(payload: Uint8Array) {\n const unpadded = 5 + payload.length;\n let padding = PLAIN_BLOCK - (unpadded % PLAIN_BLOCK);\n if (padding < MIN_PADDING) padding += PLAIN_BLOCK;\n\n const writer = new SshWriter(unpadded + padding);\n writer.u32(1 + payload.length + padding);\n writer.u8(padding);\n writer.raw(payload);\n const frame = writer.take();\n const filler = new Uint8Array(padding);\n crypto.getRandomValues(filler);\n return concatBytes(frame, filler);\n}\n\nexport function buildKexInit(offer) {\n const cookie = new Uint8Array(16);\n crypto.getRandomValues(cookie);\n\n const writer = new SshWriter(512);\n writer.u8(MSG.KEXINIT).raw(cookie);\n writer.nameList(offer.kex);\n writer.nameList(offer.hostKey);\n writer.nameList(CIPHER_NAMES); // client to server\n writer.nameList(CIPHER_NAMES); // server to client\n writer.nameList(MAC_NAMES);\n writer.nameList(MAC_NAMES);\n writer.nameList(COMPRESSION_NAMES);\n writer.nameList(COMPRESSION_NAMES);\n writer.nameList([]); // languages\n writer.nameList([]);\n writer.boolean(false); // no guessed key exchange packet\n writer.u32(0); // reserved\n return writer.take();\n}\n\nexport function parseKexInit(payload: Uint8Array) {\n const reader = new SshReader(payload, 17); // message number and cookie\n return {\n kex: reader.nameList(),\n hostKey: reader.nameList(),\n cipherClientToServer: reader.nameList(),\n cipherServerToClient: reader.nameList(),\n macClientToServer: reader.nameList(),\n macServerToClient: reader.nameList(),\n compressionClientToServer: reader.nameList(),\n compressionServerToClient: reader.nameList(),\n };\n}\n"],
5
+ "mappings": "AAQA,SAAS,KAAK,yBAAyB;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,iBAAiB;AAG9B,MAAM,UAAU;AAAA,EACd,0BAA0B,EAAE,WAAW,GAAG;AAAA,EAC1C,0BAA0B,EAAE,WAAW,GAAG;AAC5C;AACA,MAAM,eAAe,OAAO,KAAK,OAAO;AACxC,MAAM,YAAY,CAAC,iBAAiB,eAAe;AACnD,MAAM,oBAAoB,CAAC,MAAM;AAEjC,MAAM,YAAY;AAClB,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAE3B,MAAM,SAAS,WAAW,QAAQ;AAG3B,SAAS,UAAU,aAAa,aAAa;AAClD,SAAO,YAAY,KAAK,CAAC,SAAiB,YAAY,SAAS,IAAI,CAAC,KAAK;AAC3E;AAGA,MAAM,UAAU;AAAA,EACd;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,KAAgB,IAAgB;AAC1C,SAAK,MAAM;AACX,SAAK,QAAQ,GAAG,MAAM,GAAG,CAAC;AAC1B,SAAK,UAAU,GAAG,MAAM,GAAG,EAAE;AAAA,EAC/B;AAAA,E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,IAAI,WAAW,EAAE;AAChC,SAAO,gBAAgB,MAAM;AAE7B,QAAM,SAAS,IAAI,UAAU,GAAG;AAChC,SAAO,GAAG,IAAI,OAAO,EAAE,IAAI,MAAM;AACjC,SAAO,SAAS,MAAM,GAAG;AACzB,SAAO,SAAS,MAAM,OAAO;AAC7B,SAAO,SAAS,YAAY;AAC5B,SAAO,SAAS,YAAY;AAC5B,SAAO,SAAS,SAAS;AACzB,SAAO,SAAS,SAAS;AACzB,SAAO,SAAS,iBAAiB;AACjC,SAAO,SAAS,iBAAiB;AACjC,SAAO,SAAS,CAAC,CAAC;AAClB,SAAO,SAAS,CAAC,CAAC;AAClB,SAAO,QAAQ,KAAK;AACpB,SAAO,IAAI,CAAC;AACZ,SAAO,OAAO,KAAK;AACrB;AAEO,SAAS,aAAa,SAAqB;AAChD,QAAM,SAAS,IAAI,UAAU,SAAS,EAAE;AACxC,SAAO;AAAA,IACL,KAAK,OAAO,SAAS;AAAA,IACrB,SAAS,OAAO,SAAS;AAAA,IACzB,sBAAsB,OAAO,SAAS;AAAA,IACtC,sBAAsB,OAAO,SAAS;AAAA,IACtC,mBAAmB,OAAO,SAAS;AAAA,IACnC,mBAAmB,OAAO,SAAS;AAAA,IACnC,2BAA2B,OAAO,SAAS;AAAA,IAC3C,2BAA2B,OAAO,SAAS;AAAA,EAC7C;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,11 +1,11 @@
1
1
  import RFB from "@novnc/novnc";
2
- import { DEFAULT_PORTS } from "../../shared/protocol";
2
+ import { DEFAULT_PORTS } from "../../shared/protocol.js";
3
3
  import {
4
4
  GATEWAY_KEEPALIVE_SIGNAL,
5
5
  GATEWAY_READY_SIGNAL,
6
6
  KEEPALIVE_INTERVAL_MS
7
- } from "../../shared/signals";
8
- import { vncWheelMasks } from "./input";
7
+ } from "../../shared/signals.js";
8
+ import { vncWheelMasks } from "./input.js";
9
9
  const DIALOG = {
10
10
  usernameLabel: "Username",
11
11
  usernamePlaceholder: "macOS username (optional)",
@@ -3,7 +3,7 @@ import {
3
3
  toPort,
4
4
  toRdpSecurity,
5
5
  toRemoteProtocol
6
- } from "./protocol";
6
+ } from "./protocol.js";
7
7
  const DEFAULT_DISPLAY_SETTINGS = {
8
8
  quality: 6,
9
9
  compression: 2,
@@ -4,7 +4,7 @@ import {
4
4
  isRdpSecurity,
5
5
  toPort,
6
6
  toRemoteProtocol
7
- } from "./protocol";
7
+ } from "./protocol.js";
8
8
  function normalizeRemoteApp(value) {
9
9
  if (typeof value === "string" && value.trim()) return { program: value.trim() };
10
10
  if (!value || typeof value !== "object") return void 0;