import { randomBytes, createCipheriv, createDecipheriv, createHash, } from "node:crypto"; import { mkdir, readFile, writeFile, chmod, rename, rm, realpath, } from "node:fs/promises"; import path from "node:path"; // ssh2 is CommonJS: Node's ESM loader cannot see `utils` as a named export (see test/bundle.test.ts). import ssh2 from "ssh2"; const { utils } = ssh2; import type { HostCredentialInput, HostCredentialMetadata, } from "@shellbook/core"; import { SerialQueue, httpError } from "../workspace"; const writes = new SerialQueue(); export type StoredCredential = { input: Exclude; metadata: HostCredentialMetadata; }; export class CredentialStore { constructor( private dir: string, private workspaceDir?: string, ) {} private file(name: string) { return path.join( this.dir, "ssh-credentials", createHash("sha256").update(name).digest("hex") + ".json", ); } private key() { return writes.run(path.join(this.dir, "ssh-credentials.key"), () => this.loadKey(), ); } private async loadKey() { await mkdir(this.dir, { recursive: true, mode: 0o700 }); if (this.workspaceDir) { const workspace = await realpath(this.workspaceDir); const relative = path.relative(workspace, await realpath(this.dir)); if ( !relative || (!relative.startsWith(".." + path.sep) && relative !== ".." && !path.isAbsolute(relative)) ) { throw httpError( 400, "SSH credential data directory must be outside the workspace", ); } } const file = path.join(this.dir, "ssh-credentials.key"); try { await writeFile(file, randomBytes(32), { flag: "wx", mode: 0o600 }); } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; } await chmod(file, 0o600); const key = await readFile(file); if (key.length !== 32) throw new Error("Invalid credential encryption key"); return key; } async get(name: string): Promise { let bytes: Buffer; try { bytes = await readFile(this.file(name)); } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return; throw new Error("Cannot read SSH credential"); } try { const decipher = createDecipheriv( "aes-256-gcm", await this.key(), bytes.subarray(0, 12), ); decipher.setAAD(Buffer.from(name)); decipher.setAuthTag(bytes.subarray(12, 28)); return JSON.parse( Buffer.concat([ decipher.update(bytes.subarray(28)), decipher.final(), ]).toString(), ) as StoredCredential; } catch { throw new Error("Cannot decrypt SSH credential"); } } async set(name: string, value: unknown): Promise { const input = value as HostCredentialInput; if (!input || typeof input !== "object") throw httpError(400, "Invalid credential"); let safe: StoredCredential["input"]; const metadata: HostCredentialMetadata = { type: input.type, setAt: new Date().toISOString(), }; if (input.type === "shellbook") { await this.delete(name); return { type: "shellbook" }; } if (input.type === "password") { if ( typeof input.password !== "string" || !input.password || input.password.length > 16384 || input.password.includes("\0") ) throw httpError(400, "Invalid password"); safe = { type: "password", password: input.password }; } else if (input.type === "privateKey") { if ( typeof input.privateKey !== "string" || input.privateKey.length > 65536 || (input.passphrase !== undefined && (typeof input.passphrase !== "string" || input.passphrase.length > 16384)) ) throw httpError(400, "Invalid private key"); const parsed = utils.parseKey(input.privateKey, input.passphrase); if ( parsed instanceof Error || Array.isArray(parsed) || !parsed.isPrivateKey() ) throw httpError(400, "Invalid private key or passphrase"); metadata.fingerprint = "SHA256:" + createHash("sha256") .update(parsed.getPublicSSH()) .digest("base64") .replace(/=+$/, ""); safe = { type: "privateKey", privateKey: input.privateKey, ...(input.passphrase !== undefined ? { passphrase: input.passphrase } : {}), }; } else throw httpError(400, "Unsupported SSH authentication type"); return writes.run(this.file(name), async () => { const key = await this.key(); const iv = randomBytes(12); const cipher = createCipheriv("aes-256-gcm", key, iv); cipher.setAAD(Buffer.from(name)); const encrypted = Buffer.concat([ cipher.update(JSON.stringify({ input: safe, metadata })), cipher.final(), ]); await mkdir(path.dirname(this.file(name)), { recursive: true, mode: 0o700, }); const temp = this.file(name) + "." + randomBytes(8).toString("hex"); try { await writeFile( temp, Buffer.concat([iv, cipher.getAuthTag(), encrypted]), { mode: 0o600, flag: "wx" }, ); await rename(temp, this.file(name)); } finally { await rm(temp, { force: true }); } return metadata; }); } async delete(name: string) { await writes.run(this.file(name), () => rm(this.file(name), { force: true }), ); } } export function credentialSecrets(stored?: StoredCredential): string[] { if (!stored) return []; return stored.input.type === "password" ? [stored.input.password] : [ stored.input.privateKey, ...stored.input.privateKey .split(/\r?\n/) .filter((line) => line && !line.startsWith("-----")), stored.input.passphrase ?? "", ]; }