From 45254207918d89567812d01c11f4f0e5a3adc6ee Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:38:51 +0000 Subject: [PATCH 1/6] Add customer-protected secrets, wrapped versions and vault unwrap Co-authored-by: Ninad Sinha --- src/customer-key.ts | 508 ++++++++++++++++++++++++++++ src/index.ts | 10 + src/sandbox/process.ts | 11 +- src/sandbox/secret-references.ts | 143 +++++++- src/secrets-envelope.ts | 3 +- src/services/credentials.ts | 16 +- src/services/sandboxes.ts | 10 +- src/services/secrets.ts | 235 ++++++++++++- src/services/vaults.ts | 49 ++- src/types/credential.ts | 25 +- src/types/index.ts | 22 +- src/types/sandbox.ts | 56 ++- src/types/secret.ts | 93 +++++ src/types/session.ts | 14 +- src/types/vault.ts | 46 ++- tests/unit/credentials-fill.test.ts | 28 ++ tests/unit/customer-secrets.test.ts | 503 +++++++++++++++++++++++++++ tests/unit/sandbox-secrets.test.ts | 105 ++++++ 18 files changed, 1806 insertions(+), 71 deletions(-) create mode 100644 src/customer-key.ts create mode 100644 tests/unit/customer-secrets.test.ts diff --git a/src/customer-key.ts b/src/customer-key.ts new file mode 100644 index 0000000..0e6b134 --- /dev/null +++ b/src/customer-key.ts @@ -0,0 +1,508 @@ +import crypto from "crypto"; +import { HyperbrowserError } from "./error"; +import type { WrappedSecretVersion } from "./types/secret"; + +/** + * How a customer key wraps an envelope (JWE key management). RSA keys use + * `RSA-OAEP-256`; EC and X25519/X448 keys use `ECDH-ES+A256KW` unless + * `ECDH-ES` is chosen. Content is always encrypted with A256GCM. + */ +export type CustomerKeyAlgorithm = "RSA-OAEP-256" | "ECDH-ES" | "ECDH-ES+A256KW"; + +/** + * The customer's own key for customer-protected secrets. Each version's + * envelope, already encrypted to the platform, is wrapped with this key + * before upload, so nothing the platform stores can be decrypted without it. + * Each use of the secret passes the envelope unwrapped with this key. + * + * `createCustomerKey` builds one from a local key. Implement this interface + * to keep the private key elsewhere, such as in a KMS or HSM. + */ +export interface CustomerKey { + /** + * The key's ID, written as the `kid` of every envelope it wraps: 1-256 + * printable ASCII characters. + */ + readonly kid: string; + /** + * Wrap an inner envelope as a compact JWE (RSA-OAEP-256, ECDH-ES or + * ECDH-ES+A256KW with A256GCM) whose protected header holds exactly `alg`, + * `enc`, `kid` and `ctx` (plus `epk`, and optionally `apu` and `apv`, with + * ECDH-ES), with `ctx` set to `encryptionContext`. + */ + wrap(innerEnvelope: string, encryptionContext: string): string | Promise; + /** Decrypt an envelope this key wrapped and return the inner envelope. */ + unwrap(wrappedEnvelope: string): string | Promise; +} + +/** + * A key as `createCustomerKey` takes it: a `KeyObject`, a PEM (or DER + * `Buffer`) private or public key, or a JWK. A public key can only wrap. + */ +export type CustomerKeyInput = crypto.KeyObject | string | Buffer | crypto.JsonWebKey; + +export interface CustomerKeyOptions { + /** Defaults to the JWK's `kid`, or else the key's RFC 7638 thumbprint. */ + kid?: string; + /** For EC and X25519/X448 keys; defaults to `ECDH-ES+A256KW`. */ + algorithm?: CustomerKeyAlgorithm; +} + +const ENC = "A256GCM"; +const IV_BYTES = 12; +const TAG_BYTES = 16; +const CEK_BYTES = 32; +/** The server's limits: an inner envelope of 64 KiB, an RSA encrypted key of 256 bytes. */ +const MAX_INNER_ENVELOPE_LENGTH = 64 * 1024; +const MIN_RSA_BITS = 2048; +const MAX_KID_LENGTH = 256; +const KID_PATTERN = /^[\x20-\x7E]+$/; +const AES_KW_IV = Buffer.from("A6A6A6A6A6A6A6A6", "hex"); +const EC_CURVES: Record = { + prime256v1: "P-256", + secp384r1: "P-384", + secp521r1: "P-521", +}; + +const keyError = (message: string, code = "invalid_customer_key"): HyperbrowserError => + new HyperbrowserError(message, { code, retryable: false }); + +const unwrapFailed = (message: string): HyperbrowserError => + keyError(message, "customer_key_unwrap_failed"); + +const base64Url = (data: Buffer | Uint8Array): string => Buffer.from(data).toString("base64url"); + +const decodeSegment = (segment: string, what: string): Buffer => { + const decoded = /^[A-Za-z0-9_-]*$/.test(segment) ? Buffer.from(segment, "base64url") : null; + if (!decoded || decoded.toString("base64url") !== segment) { + throw unwrapFailed(`Wrapped envelope ${what} is not canonical base64url`); + } + return decoded; +}; + +const uint32 = (value: number): Buffer => { + const buffer = Buffer.alloc(4); + buffer.writeUInt32BE(value); + return buffer; +}; + +const lengthPrefixed = (data: Buffer): Buffer => Buffer.concat([uint32(data.length), data]); + +/** RFC 7518 ยง4.6.2 Concat KDF with SHA-256, for one 256-bit key. */ +const concatKdf = (sharedSecret: Buffer, algorithmId: string, apu: Buffer, apv: Buffer): Buffer => + crypto + .createHash("sha256") + .update( + Buffer.concat([ + uint32(1), + sharedSecret, + lengthPrefixed(Buffer.from(algorithmId, "ascii")), + lengthPrefixed(apu), + lengthPrefixed(apv), + uint32(CEK_BYTES * 8), + ]) + ) + .digest(); + +/** The members of a public JWK that RFC 7638 thumbprints (and `epk` headers) hold. */ +const publicMembers = (jwk: crypto.JsonWebKey): Record => { + switch (jwk.kty) { + case "RSA": + return { e: jwk.e as string, kty: "RSA", n: jwk.n as string }; + case "EC": + return { crv: jwk.crv as string, kty: "EC", x: jwk.x as string, y: jwk.y as string }; + default: + return { crv: jwk.crv as string, kty: jwk.kty as string, x: jwk.x as string }; + } +}; + +/** The RFC 7638 SHA-256 thumbprint of a public key. */ +const thumbprint = (publicKey: crypto.KeyObject): string => + base64Url( + crypto + .createHash("sha256") + .update(JSON.stringify(publicMembers(publicKey.export({ format: "jwk" })))) + .digest() + ); + +const isJwk = (input: unknown): input is crypto.JsonWebKey => + !!input && + typeof input === "object" && + !Buffer.isBuffer(input) && + !(input instanceof crypto.KeyObject) && + typeof (input as crypto.JsonWebKey).kty === "string"; + +const loadKeys = ( + input: CustomerKeyInput +): { publicKey: crypto.KeyObject; privateKey?: crypto.KeyObject; jwkKid?: string } => { + if (input instanceof crypto.KeyObject) { + if (input.type === "private") { + return { publicKey: crypto.createPublicKey(input), privateKey: input }; + } + if (input.type === "public") { + return { publicKey: input }; + } + throw keyError("A customer key must be an asymmetric key, not a secret key"); + } + if (isJwk(input)) { + const jwkKid = typeof input.kid === "string" ? input.kid : undefined; + try { + if (typeof input.d === "string") { + const privateKey = crypto.createPrivateKey({ key: input, format: "jwk" }); + return { publicKey: crypto.createPublicKey(privateKey), privateKey, jwkKid }; + } + return { publicKey: crypto.createPublicKey({ key: input, format: "jwk" }), jwkKid }; + } catch (cause) { + throw new HyperbrowserError("The customer key JWK could not be read", { + code: "invalid_customer_key", + cause, + }); + } + } + if (typeof input === "string" || Buffer.isBuffer(input)) { + try { + const privateKey = crypto.createPrivateKey(input); + return { publicKey: crypto.createPublicKey(privateKey), privateKey }; + } catch { + try { + return { publicKey: crypto.createPublicKey(input) }; + } catch (cause) { + throw new HyperbrowserError("The customer key is not a PEM or DER key", { + code: "invalid_customer_key", + cause, + }); + } + } + } + throw keyError("A customer key must be a KeyObject, a PEM or DER key, or a JWK"); +}; + +/** Throws unless `kid` is a key ID the API stores: 1-256 printable ASCII characters. */ +export const assertCustomerKeyId = (kid: unknown): string => { + if (typeof kid !== "string" || kid.length > MAX_KID_LENGTH || !KID_PATTERN.test(kid)) { + throw keyError(`A customer key's kid must be 1-${MAX_KID_LENGTH} printable ASCII characters`); + } + return kid; +}; + +type KeyKind = { type: "rsa" } | { type: "ec"; curve: string } | { type: "x25519" | "x448" }; + +const keyKind = (publicKey: crypto.KeyObject): KeyKind => { + const type = publicKey.asymmetricKeyType; + if (type === "rsa") { + const bits = publicKey.asymmetricKeyDetails?.modulusLength ?? 0; + if (bits < MIN_RSA_BITS) { + throw keyError(`RSA customer keys must be at least ${MIN_RSA_BITS} bits`); + } + return { type }; + } + if (type === "ec") { + const curve = publicKey.asymmetricKeyDetails?.namedCurve ?? ""; + if (!EC_CURVES[curve]) { + throw keyError("EC customer keys must be on P-256, P-384 or P-521"); + } + return { type, curve }; + } + if (type === "x25519" || type === "x448") { + return { type }; + } + throw keyError("A customer key must be RSA, EC (P-256, P-384, P-521), X25519 or X448"); +}; + +/** A customer key held in this process. */ +class LocalCustomerKey implements CustomerKey { + readonly kid: string; + private readonly kind: KeyKind; + private readonly algorithm: CustomerKeyAlgorithm; + + constructor( + private readonly publicKey: crypto.KeyObject, + private readonly privateKey: crypto.KeyObject | undefined, + options: CustomerKeyOptions & { jwkKid?: string } + ) { + this.kind = keyKind(publicKey); + const algorithm = + options.algorithm ?? (this.kind.type === "rsa" ? "RSA-OAEP-256" : "ECDH-ES+A256KW"); + if ((algorithm === "RSA-OAEP-256") !== (this.kind.type === "rsa")) { + throw keyError( + this.kind.type === "rsa" + ? "RSA customer keys wrap with RSA-OAEP-256" + : "EC and X25519/X448 customer keys wrap with ECDH-ES or ECDH-ES+A256KW" + ); + } + if (!["RSA-OAEP-256", "ECDH-ES", "ECDH-ES+A256KW"].includes(algorithm)) { + throw keyError(`Unsupported customer key algorithm ${String(algorithm)}`); + } + this.algorithm = algorithm; + this.kid = assertCustomerKeyId(options.kid ?? options.jwkKid ?? thumbprint(publicKey)); + } + + /** Whether this key can unwrap, that is, holds its private key. */ + get canUnwrap(): boolean { + return this.privateKey !== undefined; + } + + wrap(innerEnvelope: string, encryptionContext: string): string { + if (typeof innerEnvelope !== "string" || innerEnvelope.length === 0) { + throw keyError("The envelope to wrap must be a non-empty string", "invalid_request"); + } + if (innerEnvelope.length > MAX_INNER_ENVELOPE_LENGTH) { + throw keyError("The envelope to wrap is larger than 64 KiB", "invalid_request"); + } + if (typeof encryptionContext !== "string" || encryptionContext.length === 0) { + throw keyError("An encryption context is required to wrap an envelope", "invalid_request"); + } + const header: Record = { + alg: this.algorithm, + enc: ENC, + kid: this.kid, + ctx: encryptionContext, + }; + let cek: Buffer; + let encryptedKey = Buffer.alloc(0); + if (this.kind.type === "rsa") { + cek = crypto.randomBytes(CEK_BYTES); + encryptedKey = crypto.publicEncrypt( + { + key: this.publicKey, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + oaepHash: "sha256", + }, + cek + ); + } else { + const ephemeral = + this.kind.type === "ec" + ? crypto.generateKeyPairSync("ec", { namedCurve: this.kind.curve }) + : crypto.generateKeyPairSync(this.kind.type as "x25519"); + header.epk = publicMembers(ephemeral.publicKey.export({ format: "jwk" })); + const shared = crypto.diffieHellman({ + privateKey: ephemeral.privateKey, + publicKey: this.publicKey, + }); + const derived = concatKdf( + shared, + this.algorithm === "ECDH-ES" ? ENC : this.algorithm, + Buffer.alloc(0), + Buffer.alloc(0) + ); + shared.fill(0); + if (this.algorithm === "ECDH-ES") { + cek = derived; + } else { + cek = crypto.randomBytes(CEK_BYTES); + const wrapper = crypto.createCipheriv("id-aes256-wrap", derived, AES_KW_IV); + encryptedKey = Buffer.concat([wrapper.update(cek), wrapper.final()]); + derived.fill(0); + } + } + try { + const protectedHeader = base64Url(Buffer.from(JSON.stringify(header), "utf8")); + const iv = crypto.randomBytes(IV_BYTES); + const cipher = crypto.createCipheriv("aes-256-gcm", cek, iv); + cipher.setAAD(Buffer.from(protectedHeader, "ascii")); + const ciphertext = Buffer.concat([cipher.update(innerEnvelope, "utf8"), cipher.final()]); + return [ + protectedHeader, + base64Url(encryptedKey), + base64Url(iv), + base64Url(ciphertext), + base64Url(cipher.getAuthTag()), + ].join("."); + } finally { + cek.fill(0); + } + } + + unwrap(wrappedEnvelope: string): string { + if (!this.privateKey) { + throw keyError( + `Customer key ${this.kid} has no private key, so it can wrap but not unwrap`, + "customer_key_private_key_required" + ); + } + if (typeof wrappedEnvelope !== "string") { + throw unwrapFailed("The wrapped envelope must be a string"); + } + const segments = wrappedEnvelope.split("."); + if (segments.length !== 5) { + throw unwrapFailed("The wrapped envelope must have five segments"); + } + const [headerSegment, keySegment, ivSegment, ciphertextSegment, tagSegment] = segments; + let header: Record; + try { + header = JSON.parse(decodeSegment(headerSegment, "header").toString("utf8")); + } catch (error) { + if (error instanceof HyperbrowserError) throw error; + throw unwrapFailed("The wrapped envelope header is not JSON"); + } + if (!header || typeof header !== "object" || Array.isArray(header)) { + throw unwrapFailed("The wrapped envelope header is not a JSON object"); + } + if (header.kid !== this.kid) { + throw keyError( + `The envelope was wrapped with key ${JSON.stringify(header.kid)}, not ${JSON.stringify(this.kid)}`, + "customer_key_mismatch" + ); + } + if (header.enc !== ENC) { + throw unwrapFailed(`Unsupported wrapped envelope encryption ${String(header.enc)}`); + } + const alg = header.alg; + const encryptedKey = decodeSegment(keySegment, "encrypted key"); + const iv = decodeSegment(ivSegment, "IV"); + const ciphertext = decodeSegment(ciphertextSegment, "ciphertext"); + const tag = decodeSegment(tagSegment, "tag"); + if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) { + throw unwrapFailed("The wrapped envelope IV or tag has the wrong length"); + } + + let cek: Buffer; + try { + if (alg === "RSA-OAEP-256" && this.kind.type === "rsa") { + cek = crypto.privateDecrypt( + { + key: this.privateKey, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + oaepHash: "sha256", + }, + encryptedKey + ); + } else if ((alg === "ECDH-ES" || alg === "ECDH-ES+A256KW") && this.kind.type !== "rsa") { + const optional = (name: "apu" | "apv") => + header[name] === undefined ? Buffer.alloc(0) : decodeSegment(String(header[name]), name); + const epk = crypto.createPublicKey({ + key: header.epk as crypto.JsonWebKey, + format: "jwk", + }); + const shared = crypto.diffieHellman({ privateKey: this.privateKey, publicKey: epk }); + const derived = concatKdf( + shared, + alg === "ECDH-ES" ? ENC : alg, + optional("apu"), + optional("apv") + ); + shared.fill(0); + if (alg === "ECDH-ES") { + cek = derived; + } else { + const unwrapper = crypto.createDecipheriv("id-aes256-wrap", derived, AES_KW_IV); + cek = Buffer.concat([unwrapper.update(encryptedKey), unwrapper.final()]); + derived.fill(0); + } + } else { + throw unwrapFailed( + `Customer key ${this.kid} can't unwrap an envelope wrapped with ${String(alg)}` + ); + } + } catch (error) { + if (error instanceof HyperbrowserError) throw error; + throw new HyperbrowserError("The wrapped envelope's key could not be decrypted", { + code: "customer_key_unwrap_failed", + cause: error, + }); + } + try { + if (cek.length !== CEK_BYTES) { + throw unwrapFailed("The wrapped envelope's content key has the wrong length"); + } + const decipher = crypto.createDecipheriv("aes-256-gcm", cek, iv); + decipher.setAAD(Buffer.from(headerSegment, "ascii")); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8"); + } catch (error) { + if (error instanceof HyperbrowserError) throw error; + throw new HyperbrowserError("The wrapped envelope could not be decrypted", { + code: "customer_key_unwrap_failed", + cause: error, + }); + } finally { + cek.fill(0); + } + } +} + +/** + * A customer key from a local key: RSA (at least 2048 bits), EC (P-256, + * P-384 or P-521), X25519 or X448. With only the public key it can wrap + * (upload versions) but not unwrap (use them). + * + * The key ID defaults to the JWK's `kid`, or else the RFC 7638 thumbprint of + * the public key, so the same key always gets the same ID. + */ +export const createCustomerKey = ( + key: CustomerKeyInput, + options: CustomerKeyOptions = {} +): CustomerKey & { readonly canUnwrap: boolean } => { + const { publicKey, privateKey, jwkKid } = loadKeys(key); + return new LocalCustomerKey(publicKey, privateKey, { ...options, jwkKid }); +}; + +/** + * Identifies an inner envelope as the API does: the unpadded base64url + * SHA-256 of its compact form. + */ +export const secretEnvelopeDigest = (envelope: string): string => + crypto.createHash("sha256").update(envelope, "utf8").digest("base64url"); + +/** @internal Checks that `key` looks like a CustomerKey before anything is sent. */ +export const assertCustomerKey = (key: unknown, what = "customerKey"): CustomerKey => { + const candidate = key as CustomerKey | null | undefined; + if ( + !candidate || + typeof candidate !== "object" || + typeof candidate.wrap !== "function" || + typeof candidate.unwrap !== "function" + ) { + throw new HyperbrowserError( + `${what} must be a customer key, such as one from createCustomerKey()`, + { code: "invalid_request", retryable: false } + ); + } + assertCustomerKeyId(candidate.kid); + return candidate; +}; + +/** + * @internal Unwrap a wrapped version with the key among `keys` that wrapped + * it, and check the result is the inner envelope the version holds. + */ +export const unwrapVersion = async ( + wrapped: Pick, + keys: CustomerKey | readonly CustomerKey[], + label: string +): Promise => { + const key = customerKeyFor(keys, wrapped.outerKid, label); + const inner = await key.unwrap(wrapped.envelope); + if (typeof inner !== "string" || secretEnvelopeDigest(inner) !== wrapped.innerDigest) { + throw new HyperbrowserError( + `${label} unwrapped to an envelope that doesn't match its innerDigest; it may have been uploaded with the wrong digest`, + { code: "customer_key_unwrap_failed", retryable: false } + ); + } + return inner; +}; + +/** @internal The key among `keys` that wrapped an envelope with this `kid`. */ +export const customerKeyFor = ( + keys: CustomerKey | readonly CustomerKey[], + kid: string, + label: string +): CustomerKey => { + const list = (Array.isArray(keys) ? keys : [keys]) as readonly CustomerKey[]; + if (list.length === 0) { + throw new HyperbrowserError("Pass at least one customer key", { + code: "invalid_request", + retryable: false, + }); + } + list.forEach((key, index) => assertCustomerKey(key, `customerKey[${index}]`)); + const key = list.find((candidate) => candidate.kid === kid); + if (!key) { + throw new HyperbrowserError( + `${label} was wrapped with customer key ${JSON.stringify(kid)}, which none of the keys given has`, + { code: "customer_key_mismatch", retryable: false } + ); + } + return key; +}; diff --git a/src/index.ts b/src/index.ts index b8d510a..7f3e88b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,14 @@ export type { ImageBuildSource, } from "./image-builds"; import { HyperbrowserClient, HyperbrowserError } from "./client"; +import { createCustomerKey, secretEnvelopeDigest } from "./customer-key"; +export { createCustomerKey, secretEnvelopeDigest }; +export type { + CustomerKey, + CustomerKeyAlgorithm, + CustomerKeyInput, + CustomerKeyOptions, +} from "./customer-key"; // Export HyperbrowserClient as Hyperbrowser for named imports export const Hyperbrowser = HyperbrowserClient; @@ -37,5 +45,7 @@ if (typeof module !== "undefined" && module.exports) { module.exports.imageBuildName = imageBuildName; module.exports.dockerImageDigest = dockerImageDigest; module.exports.DockerCommandError = DockerCommandError; + module.exports.createCustomerKey = createCustomerKey; + module.exports.secretEnvelopeDigest = secretEnvelopeDigest; module.exports.default = HyperbrowserClient; } diff --git a/src/sandbox/process.ts b/src/sandbox/process.ts index 02c4eee..c1da0e4 100644 --- a/src/sandbox/process.ts +++ b/src/sandbox/process.ts @@ -10,9 +10,12 @@ import { } from "./process-output"; import { assertNoEnvSecretOverlap, + serializeOnePassword, serializeSecretReferences, + serializeVaultSource, WireOnePassword, WireSecretReference, + WireVaultSource, } from "./secret-references"; import { SandboxExecParams, @@ -61,8 +64,8 @@ export interface SecretProcessStartPayload { timeoutMs?: number; runAs?: string; secrets?: Record; - /** A vault name; `secrets` is merged over its entries. */ - vault?: string; + /** A vault, by name or with unwrapped entries; `secrets` is merged over its entries. */ + vault?: WireVaultSource; /** 1Password fields; their variables can't come from any other source. */ onePassword?: WireOnePassword; } @@ -744,8 +747,8 @@ export class SandboxProcessesApi { throw new HyperbrowserError("Starting a process with secrets requires a sandbox handle"); } const secrets = serializeSecretReferences(params.secrets); - const vault = params.vault; - const onePassword = params.onePassword; + const vault = serializeVaultSource(params.vault); + const onePassword = serializeOnePassword(params.onePassword); // A clash between env and the vault's variables is reported by the API. if (secrets !== undefined) assertNoEnvSecretOverlap(params.env, secrets); const timeoutMs = secretProcessTimeoutMs(params); diff --git a/src/sandbox/secret-references.ts b/src/sandbox/secret-references.ts index 2300599..f89461e 100644 --- a/src/sandbox/secret-references.ts +++ b/src/sandbox/secret-references.ts @@ -1,5 +1,5 @@ import { HyperbrowserError } from "../error"; -import { SandboxSecrets } from "../types/sandbox"; +import { SandboxOnePassword, SandboxSecrets, SandboxVaultSource } from "../types/sandbox"; const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; /** The longest environment variable name the API stores. */ @@ -9,6 +9,8 @@ export const SECRET_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/; /** The largest version number the API stores. */ export const MAX_SECRET_VERSION = 2_147_483_647; const MAX_SECRETS = 32; +/** The longest unwrapped envelope the API takes. */ +const MAX_UNWRAPPED_LENGTH = 64 * 1024; /** An environment variable name the API accepts for a secret or a vault entry. */ export const isSecretEnvName = (name: unknown): name is string => typeof name === "string" && @@ -16,14 +18,68 @@ export const isSecretEnvName = (name: unknown): name is string => ENV_NAME_PATTERN.test(name) && name !== "__proto__"; +const isVersionNumber = (version: unknown): version is number => + Number.isSafeInteger(version) && + (version as number) >= 1 && + (version as number) <= MAX_SECRET_VERSION; + +const isUnwrappedEnvelope = (unwrapped: unknown): unwrapped is string => + typeof unwrapped === "string" && + unwrapped.length >= 1 && + unwrapped.length <= MAX_UNWRAPPED_LENGTH; + export interface WireSecretReference { name: string; version?: number | "latest"; + unwrapped?: string; +} + +export interface WireVaultReference { + name: string; + unwrapped: Record; +} + +/** A vault as the API takes it: its name, or its name with unwrapped entries. */ +export type WireVaultSource = string | WireVaultReference; + +export interface WireOnePassword extends Omit { + token: string | WireSecretReference; } +/** Check one secret reference and convert it to the API's `{ name, version?, unwrapped? }`. */ +const serializeSecretReference = (reference: unknown, label: string): WireSecretReference => { + const { name, version, unwrapped } = ( + typeof reference === "string" ? { name: reference } : (reference ?? {}) + ) as { name?: unknown; version?: unknown; unwrapped?: unknown }; + if (typeof name !== "string" || !SECRET_NAME_PATTERN.test(name)) { + throw new HyperbrowserError(`Invalid secret name for ${label}: ${String(name)}`); + } + if (version !== undefined && version !== "latest" && !isVersionNumber(version)) { + throw new HyperbrowserError( + `Secret version for ${label} must be an integer from 1 to ${MAX_SECRET_VERSION} or "latest"` + ); + } + if (unwrapped === undefined) { + return version === undefined ? { name } : { name, version: version as number | "latest" }; + } + if (!isUnwrappedEnvelope(unwrapped)) { + throw new HyperbrowserError( + `The unwrapped envelope for ${label} must be a string of 1 to ${MAX_UNWRAPPED_LENGTH} characters` + ); + } + // An unwrapped envelope is one version's value; "latest" could move on. + if (typeof version !== "number") { + throw new HyperbrowserError( + `Pin the version of ${label} to the version you unwrapped when passing "unwrapped"`, + { code: "invalid_request" } + ); + } + return { name, version, unwrapped }; +}; + /** * Check secret references locally and convert them to the API's - * `{ name, version? }` shape. Returns undefined when there are none. + * `{ name, version?, unwrapped? }` shape. Returns undefined when there are none. */ export const serializeSecretReferences = ( secrets: SandboxSecrets | undefined @@ -46,27 +102,80 @@ export const serializeSecretReferences = ( if (!isSecretEnvName(env)) { throw new HyperbrowserError(`Invalid environment variable name for a secret: ${env}`); } - const { name, version } = - typeof reference === "string" ? { name: reference, version: undefined } : (reference ?? {}); - if (typeof name !== "string" || !SECRET_NAME_PATTERN.test(name)) { - throw new HyperbrowserError(`Invalid secret name for ${env}: ${String(name)}`); + wire[env] = serializeSecretReference(reference, env); + } + return wire; +}; + +/** + * Check a vault source and convert it to the API's shape: a name is passed + * as is, and a `VaultReference` keeps only its name and unwrapped entries. + */ +export const serializeVaultSource = ( + vault: SandboxVaultSource | undefined +): WireVaultSource | undefined => { + if (vault === undefined || typeof vault === "string") { + return vault; + } + if (!vault || typeof vault !== "object" || Array.isArray(vault)) { + throw new HyperbrowserError( + "vault must be a vault's name or the reference vaults.unwrap() returns" + ); + } + const { name, unwrapped } = vault; + if (typeof name !== "string" || !SECRET_NAME_PATTERN.test(name)) { + throw new HyperbrowserError(`Invalid vault name: ${String(name)}`); + } + if (!unwrapped || typeof unwrapped !== "object" || Array.isArray(unwrapped)) { + throw new HyperbrowserError( + `vault.unwrapped must map vault ${name}'s variables to { version, unwrapped }` + ); + } + const entries = Object.entries(unwrapped); + if (entries.length > MAX_SECRETS) { + throw new HyperbrowserError(`At most ${MAX_SECRETS} unwrapped vault entries are allowed`); + } + const wire: WireVaultReference["unwrapped"] = {}; + for (const [env, entry] of entries) { + if (!isSecretEnvName(env)) { + throw new HyperbrowserError(`Invalid environment variable name in vault ${name}: ${env}`); + } + const { version, unwrapped: envelope } = (entry ?? {}) as { + version?: unknown; + unwrapped?: unknown; + }; + if (!isVersionNumber(version)) { + throw new HyperbrowserError( + `The version of vault ${name}'s ${env} must be the integer it was unwrapped from` + ); } - if ( - version !== undefined && - version !== "latest" && - (!Number.isSafeInteger(version) || - (version as number) < 1 || - (version as number) > MAX_SECRET_VERSION) - ) { + if (!isUnwrappedEnvelope(envelope)) { throw new HyperbrowserError( - `Secret version for ${env} must be an integer from 1 to ${MAX_SECRET_VERSION} or "latest"` + `The unwrapped envelope of vault ${name}'s ${env} must be a string of 1 to ${MAX_UNWRAPPED_LENGTH} characters` ); } - wire[env] = version === undefined ? { name } : { name, version }; + wire[env] = { version, unwrapped: envelope }; } - return wire; + return { name, unwrapped: wire }; }; +/** + * Check a 1Password source's token, the one member that can be a secret + * reference; the API checks the rest. + */ +export const serializeOnePasswordToken = ( + token: SandboxOnePassword["token"] +): WireOnePassword["token"] => + typeof token === "string" ? token : serializeSecretReference(token, "the 1Password token"); + +/** Serialize a 1Password source, checking its token. */ +export const serializeOnePassword = ( + onePassword: SandboxOnePassword | undefined +): WireOnePassword | undefined => + onePassword === undefined || onePassword === null || typeof onePassword !== "object" + ? onePassword + : { ...onePassword, token: serializeOnePasswordToken(onePassword.token) }; + /** An environment variable must come from either `env` or `secrets`, not both. */ export const assertNoEnvSecretOverlap = ( env: Record | undefined, @@ -81,5 +190,3 @@ export const assertNoEnvSecretOverlap = ( ); } }; - -export type { SandboxOnePassword as WireOnePassword } from "../types/sandbox"; diff --git a/src/secrets-envelope.ts b/src/secrets-envelope.ts index c247822..367b5df 100644 --- a/src/secrets-envelope.ts +++ b/src/secrets-envelope.ts @@ -65,7 +65,8 @@ const rsaThumbprint = (n: Buffer, e: Buffer): string => /** Encrypts values to a verified secrets public key. */ export class SecretsSealer { private constructor( - private readonly kid: string, + /** The platform key's ID, which every envelope it seals names. */ + readonly kid: string, private readonly publicKey: crypto.KeyObject ) {} diff --git a/src/services/credentials.ts b/src/services/credentials.ts index 0fc34b6..aab48c5 100644 --- a/src/services/credentials.ts +++ b/src/services/credentials.ts @@ -1,4 +1,5 @@ import { invalidRequest } from "../error"; +import { serializeOnePasswordToken } from "../sandbox/secret-references"; import { isPlainObject } from "../secrets-envelope"; import { CredentialFillResult, FillCredentialParams } from "../types/credential"; import { BaseService } from "./base"; @@ -19,7 +20,11 @@ export class CredentialsService extends BaseService { * `op_token` secret must have been attached at session creation as * `{ onePassword: name }`, and the request's `allowedOrigins` are the * origins the values may be typed on. Each field's result carries the - * `reference` read, and there is no top-level `version`. + * `reference` read, and there is no top-level `version`. A + * customer-protected token is passed as `secrets.unwrap()` returns it. + * + * A `vault` fill needs the vault attached to the session; it fills the + * entries as they are now. Customer-protected secrets can't be filled. * * API errors are `HyperbrowserError`s whose `details` is the error body; the * server's own details are in `details.details`, such as `details.details.pages` @@ -38,11 +43,18 @@ export class CredentialsService extends BaseService { } // Preserve request members so the API can reject unknown or conflicting options. const { frameUrl, ...body } = params; + const onePassword = isPlainObject(body.onePassword) + ? { ...body.onePassword, token: serializeOnePasswordToken(body.onePassword.token) } + : body.onePassword; return this.request( `/session/${encodeURIComponent(sessionId)}/credentials/fill`, { method: "POST", - body: JSON.stringify({ ...body, frame: frameUrl == null ? undefined : { url: frameUrl } }), + body: JSON.stringify({ + ...body, + onePassword, + frame: frameUrl == null ? undefined : { url: frameUrl }, + }), timeout: Math.max(this.timeout, MIN_FILL_TIMEOUT_MS), } ); diff --git a/src/services/sandboxes.ts b/src/services/sandboxes.ts index 1e86446..7d23166 100644 --- a/src/services/sandboxes.ts +++ b/src/services/sandboxes.ts @@ -9,7 +9,11 @@ import { SecretProcessStartPayload, SecretProcessStartResponse, } from "../sandbox/process"; -import { serializeSecretReferences } from "../sandbox/secret-references"; +import { + serializeOnePassword, + serializeSecretReferences, + serializeVaultSource, +} from "../sandbox/secret-references"; import { SandboxTerminalApi } from "../sandbox/terminal"; import { buildDockerImageFromDockerfile, @@ -155,8 +159,8 @@ const serializeCreateSandboxParams = (params: CreateSandboxParams): Record `/secrets/${encodeURIComponent(id)}`; +const isCustomerProtected = (secret: Secret): boolean => secret.protection === "customer"; + +/** Throws unless `version` is a version number, or `"latest"` where allowed. */ +const assertVersion = (version: unknown, allowLatest: boolean): void => { + if (allowLatest && version === "latest") return; + if ( + !Number.isSafeInteger(version) || + (version as number) < 1 || + (version as number) > MAX_SECRET_VERSION + ) { + throw new HyperbrowserError( + `version must be an integer from 1 to ${MAX_SECRET_VERSION}${allowLatest ? ' or "latest"' : ""}` + ); + } +}; + const rethrow = (error: unknown, message: string): never => { if (error instanceof HyperbrowserError) { throw error; @@ -36,6 +64,11 @@ const rethrow = (error: unknown, message: string): never => { * Secrets are encrypted locally to the platform's public key; the API only * ever receives envelopes, and values are never returned. * + * A customer-protected secret's versions are also wrapped locally with your + * own key (`createCustomerKey()`, or your own `CustomerKey`), so the platform + * stores nothing it can open alone. Each use passes the reference `unwrap()` + * returns. + * * Methods that take `secret` accept its ID or its exact name. A UUID-shaped * argument is tried as an ID first and then as a name, since names may look * like UUIDs. @@ -83,7 +116,8 @@ export class SecretsService extends BaseService { * empty secret behind. */ async create(params: CreateSecretParams): Promise { - const { name, description, type, allowedOrigins, value } = params ?? ({} as CreateSecretParams); + const { name, description, type, allowedOrigins, value, customerKey } = + params ?? ({} as CreateSecretParams); if (typeof name !== "string" || !SECRET_NAME_PATTERN.test(name)) { throw new HyperbrowserError( "Secret name must be 1-128 letters, digits, '_' or '-', starting with a letter or digit" @@ -92,6 +126,21 @@ export class SecretsService extends BaseService { if (type !== undefined && (typeof type !== "string" || !type)) { throw invalidRequest('type must be "secret", "totp" or "op_token"'); } + const protection = params.protection ?? (customerKey !== undefined ? "customer" : undefined); + if (protection !== undefined && protection !== "platform" && protection !== "customer") { + throw invalidRequest('protection must be "platform" or "customer"'); + } + if (customerKey !== undefined) { + if (protection !== "customer") { + throw invalidRequest('customerKey is only for secrets with protection "customer"'); + } + assertCustomerKey(customerKey); + } + if (protection === "customer" && value !== undefined && customerKey === undefined) { + throw invalidRequest( + "A customer-protected secret's value is wrapped with your own key: pass customerKey" + ); + } const plaintext = value === undefined ? undefined : secretPlaintext(type ?? "secret", value); const sealer = plaintext === undefined ? undefined : SecretsSealer.fromPublicKey(await this.getPublicKey()); @@ -101,7 +150,7 @@ export class SecretsService extends BaseService { try { secret = await this.request("/secrets", { method: "POST", - body: JSON.stringify({ name, description, type, metadata }), + body: JSON.stringify({ name, description, type, metadata, protection }), }); } catch (error) { return rethrow(error, `Failed to create secret ${name}`); @@ -111,7 +160,7 @@ export class SecretsService extends BaseService { } try { - const version = await this.uploadVersion(secret, sealer, plaintext); + const version = await this.uploadVersion(secret, sealer, plaintext, customerKey); return { ...secret, latestVersion: version.version }; } catch (error) { // Retrying create would fail with "name taken"; the value has to be @@ -168,18 +217,162 @@ export class SecretsService extends BaseService { * value is checked against the rules of the secret's type, such as a TOTP * seed's format, before it is sealed. */ - async addVersion(secret: string, value: SecretValue): Promise { + async addVersion( + secret: string, + value: SecretValue, + options: AddSecretVersionOptions = {} + ): Promise { secretValueBytes(value); + const { customerKey } = options ?? {}; + if (customerKey !== undefined) assertCustomerKey(customerKey); const sealer = SecretsSealer.fromPublicKey(await this.getPublicKey()); try { const resolved = await this.resolve(secret); + const customer = isCustomerProtected(resolved); + if (customer && customerKey === undefined) { + throw invalidRequest( + `Secret ${resolved.name} is customer-protected: pass customerKey to wrap the value with` + ); + } + if (!customer && customerKey !== undefined) { + throw invalidRequest( + `Secret ${resolved.name} is not customer-protected, so its versions aren't wrapped: omit customerKey` + ); + } const plaintext = secretPlaintext(resolved.type ?? "secret", value); - return await this.uploadVersion(resolved, sealer, plaintext); + return await this.uploadVersion(resolved, sealer, plaintext, customerKey); } catch (error) { return rethrow(error, `Failed to add a version to secret ${secret}`); } } + /** + * A customer-protected version's wrapped envelope, for unwrapping with + * your own key. Most callers want `unwrap()`, which also unwraps it. + */ + async getWrappedVersion( + secret: string, + version: number | "latest" = "latest" + ): Promise { + assertVersion(version, true); + try { + const { id } = await this.resolve(secret); + return await this.fetchWrapped(id, version); + } catch (error) { + return rethrow(error, `Failed to get the wrapped version of secret ${secret}`); + } + } + + /** + * Unwrap a customer-protected version locally with your own key, giving + * the reference each use passes: as a sandbox's or process's `secrets` + * entry, or as a 1Password `token`. It is pinned to the version unwrapped. + * The unwrapped envelope is checked against the digest stored with the + * version, and only the platform can open it. + * + * `customerKey` may be several keys, such as during a rotation; the one + * whose `kid` wrapped the version is used. + */ + async unwrap( + secret: string, + customerKey: CustomerKey | readonly CustomerKey[], + options: UnwrapSecretOptions = {} + ): Promise { + const version = options?.version ?? "latest"; + assertVersion(version, true); + try { + const resolved = await this.resolve(secret); + const wrapped = await this.fetchWrapped(resolved.id, version); + const unwrapped = await unwrapVersion( + wrapped, + customerKey, + `Version ${wrapped.version} of secret ${resolved.name}` + ); + return { name: resolved.name, version: wrapped.version, unwrapped }; + } catch (error) { + return rethrow(error, `Failed to unwrap secret ${secret}`); + } + } + + /** + * Rewrap a customer-protected secret's versions with a new key, for + * rotating your own key. Each version is unwrapped with `from` and wrapped + * with `to` locally; the value never changes and the platform never sees + * it. Returns the versions rewrapped. + */ + async rewrap(secret: string, params: RewrapSecretParams): Promise { + const { from, to, versions } = params ?? ({} as RewrapSecretParams); + assertCustomerKey(to, "to"); + if (versions !== undefined) { + if (!Array.isArray(versions)) + throw invalidRequest("versions must be an array of version numbers"); + versions.forEach((version) => assertVersion(version, false)); + } + try { + const detail = await this.resolveDetail(secret); + if (!isCustomerProtected(detail)) { + throw invalidRequest(`Secret ${detail.name} is not customer-protected; it has no wrapping`); + } + const wanted = + versions ?? + detail.versions.filter(({ outerKid }) => outerKid !== to.kid).map(({ version }) => version); + const rewrapped: WrappedSecretVersion[] = []; + for (const version of wanted) { + const wrapped = await this.fetchWrapped(detail.id, version); + const label = `Version ${version} of secret ${detail.name}`; + const inner = await unwrapVersion(wrapped, from, label); + const envelope = await to.wrap(inner, detail.encryptionContext); + rewrapped.push( + await this.request( + `${secretPath(detail.id)}/versions/${version}/wrapping`, + { + method: "PUT", + body: JSON.stringify({ envelope, innerDigest: wrapped.innerDigest }), + } + ) + ); + } + return rewrapped; + } catch (error) { + return rethrow(error, `Failed to rewrap secret ${secret}`); + } + } + + /** + * Replace a customer-protected version's outer envelope with one you + * wrapped yourself. `innerDigest` must match the version's: only the + * wrapping changes, never the value. `rewrap()` does this for you. + */ + async replaceVersionWrapping( + secret: string, + version: number, + params: ReplaceSecretVersionWrappingParams + ): Promise { + assertVersion(version, false); + const { envelope, innerDigest } = params ?? ({} as ReplaceSecretVersionWrappingParams); + if (typeof envelope !== "string" || !envelope) { + throw invalidRequest("envelope must be the wrapped envelope"); + } + if (typeof innerDigest !== "string" || !innerDigest) { + throw invalidRequest("innerDigest must be the version's innerDigest"); + } + try { + const { id } = await this.resolve(secret); + return await this.request( + `${secretPath(id)}/versions/${version}/wrapping`, + { + method: "PUT", + body: JSON.stringify({ envelope, innerDigest }), + } + ); + } catch (error) { + return rethrow( + error, + `Failed to replace the wrapping of version ${version} of secret ${secret}` + ); + } + } + /** * Replace the origins a secret may be filled into in browser sessions, or * clear them with `null` (it then can't be filled until origins are set @@ -206,9 +399,7 @@ export class SecretsService extends BaseService { /** Delete one stored version. The latest version cannot be deleted. */ async deleteVersion(secret: string, version: number): Promise { - if (!Number.isSafeInteger(version) || version < 1 || version > MAX_SECRET_VERSION) { - throw new HyperbrowserError(`version must be an integer from 1 to ${MAX_SECRET_VERSION}`); - } + assertVersion(version, false); try { const { id } = await this.resolve(secret); return await this.request( @@ -222,14 +413,36 @@ export class SecretsService extends BaseService { } } - /** Sealed to the context the API returned for the secret; never one built here. */ - private uploadVersion(secret: Secret, sealer: SecretsSealer, plaintext: Buffer) { + /** + * Sealed to the context the API returned for the secret; never one built + * here. With a customer key, the sealed envelope is wrapped to the same + * context and the API keeps only the wrapped one and the inner digest. + */ + private async uploadVersion( + secret: Secret, + sealer: SecretsSealer, + plaintext: Buffer, + customerKey?: CustomerKey + ) { + const inner = sealer.seal(secret.encryptionContext, plaintext); + const body = + customerKey === undefined + ? { envelope: inner } + : { + envelope: await customerKey.wrap(inner, secret.encryptionContext), + innerDigest: secretEnvelopeDigest(inner), + innerKid: sealer.kid, + }; return this.request(`${secretPath(secret.id)}/versions`, { method: "POST", - body: JSON.stringify({ envelope: sealer.seal(secret.encryptionContext, plaintext) }), + body: JSON.stringify(body), }); } + private fetchWrapped(id: string, version: number | "latest") { + return this.request(`${secretPath(id)}/versions/${version}/wrapped`); + } + private async resolve(secret: string): Promise { return (await this.lookup(secret)).secret; } diff --git a/src/services/vaults.ts b/src/services/vaults.ts index 78f7369..3f1343d 100644 --- a/src/services/vaults.ts +++ b/src/services/vaults.ts @@ -1,3 +1,4 @@ +import { CustomerKey, unwrapVersion } from "../customer-key"; import { HyperbrowserError, invalidRequest } from "../error"; import { CreateVaultParams, @@ -6,6 +7,8 @@ import { VaultDeleteResult, VaultListParams, VaultListResponse, + VaultReference, + WrappedVault, } from "../types/vault"; import { BaseService } from "./base"; @@ -18,7 +21,13 @@ const vaultPath = (id: string): string => `/vaults/${encodeURIComponent(id)}`; * Vaults name a set of environment variables whose values come from stored * secrets. Pass one as `vault` to a sandbox process * or sandbox create, or attach it to a browser session with - * `credentials: [{ vault }]` and fill its entries by name. + * `credentials: [{ vault }]` and fill its entries by name. A session + * attaches the vault by reference, so each fill uses its entries as they are + * then. + * + * Entries may be customer-protected secrets. Each sandbox or process use then + * passes the vault as `unwrap()` returns it, with those entries' envelopes + * unwrapped with your own key. * * Methods that take `vault` accept its ID or its exact name. A UUID-shaped * argument is tried as an ID first and then as a name. @@ -62,6 +71,44 @@ export class VaultsService extends BaseService { return await this.request(vaultPath(id), { method: "DELETE" }); } + /** + * The wrapped envelopes of a vault's customer-protected entries, each at + * the version its entry resolves to now. Most callers want `unwrap()`. + */ + async getWrapped(vault: string): Promise { + const { id } = await this.resolve(vault); + return await this.request(`${vaultPath(id)}/wrapped`); + } + + /** + * Unwrap a vault's customer-protected entries locally with your own key, + * giving the reference to pass as a sandbox's or process's `vault`. Each + * envelope is checked against the digest stored with its version. A vault + * with no customer-protected entries needs none and can be passed by name. + * + * `customerKey` may be several keys; each entry uses the one whose `kid` + * wrapped it. If an entry changes after this, uses fail with + * `SECRET_VAULT_CHANGED`: unwrap the vault again. + */ + async unwrap( + vault: string, + customerKey: CustomerKey | readonly CustomerKey[] + ): Promise { + const wrapped = await this.getWrapped(vault); + const unwrapped: VaultReference["unwrapped"] = {}; + for (const [env, entry] of Object.entries(wrapped.entries ?? {})) { + unwrapped[env] = { + version: entry.version, + unwrapped: await unwrapVersion( + entry, + customerKey, + `Entry ${env} of vault ${wrapped.name} (version ${entry.version} of secret ${entry.name})` + ), + }; + } + return { name: wrapped.name, unwrapped }; + } + private async resolve(key: string): Promise { if (typeof key !== "string" || !key.trim()) { throw invalidRequest("A vault ID or name is required"); diff --git a/src/types/credential.ts b/src/types/credential.ts index 74f146c..6b1be58 100644 --- a/src/types/credential.ts +++ b/src/types/credential.ts @@ -1,14 +1,25 @@ +import type { SandboxStoredSecretReference } from "./sandbox"; + /** A secret attached to a browser session, which fill may type into its pages. */ export interface SessionCredential { id: string; name: string; } +/** + * A vault attached to a browser session by reference: each fill uses its + * entries as they are at that moment. + */ +export interface SessionVault { + id: string; + name: string; +} + /** * What to attach to a browser session at creation: a secret by name (or - * `{ secret }`), `{ vault }` for the secrets a vault's entries name, or - * `{ onePassword }` for an `op_token` secret that fills may read 1Password - * fields with. + * `{ secret }`), `{ vault }` for a vault by reference (each fill reads its + * entries as they are then), or `{ onePassword }` for an `op_token` secret + * that fills may read 1Password fields with. */ export type SessionCredentialSource = | string @@ -49,8 +60,12 @@ export interface CredentialFillField { * the request names the origins it may be typed on. */ export interface CredentialFillOnePassword { - /** The `op_token` secret attached to the session, by name; its latest version is used. */ - token: string; + /** + * The `op_token` secret attached to the session: its name (its latest + * version is used), or a reference pinning a version. A + * customer-protected token is passed as `secrets.unwrap()` returns it. + */ + token: string | SandboxStoredSecretReference; /** The 1Password vault's name or ID. */ vault: string; /** diff --git a/src/types/index.ts b/src/types/index.ts index 5e2b110..f011472 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -179,7 +179,9 @@ export { SandboxVolumeMountType, SandboxVolumeMount, SandboxSecretReference, + SandboxStoredSecretReference, SandboxSecrets, + SandboxVaultSource, SandboxResolvedSecret, SandboxStoredSecretBinding, SandboxOnePasswordBinding, @@ -279,6 +281,7 @@ export { export { SecretValue, SecretType, + SecretProtection, SecretBrowserMetadata, SecretMetadata, UpdateSecretMetadata, @@ -293,10 +296,21 @@ export { SecretListResponse, SecretDeleteResult, SecretVersionDeleteResult, + WrappedSecretVersion, + UnwrappedSecretReference, + UnwrapSecretOptions, + AddSecretVersionOptions, + ReplaceSecretVersionWrappingParams, + RewrapSecretParams, } from "./secret"; +export { SessionCredential, SessionCredentialSource, SessionVault } from "./credential"; +export type { + CustomerKey, + CustomerKeyAlgorithm, + CustomerKeyInput, + CustomerKeyOptions, +} from "../customer-key"; export { - SessionCredential, - SessionCredentialSource, CredentialFillField, CredentialFillRef, CredentialFillOnePassword, @@ -315,6 +329,10 @@ export { VaultListParams, VaultListResponse, VaultDeleteResult, + WrappedVault, + WrappedVaultEntry, + VaultUnwrappedEntry, + VaultReference, } from "./vault"; export { CreateProfileParams, diff --git a/src/types/sandbox.ts b/src/types/sandbox.ts index 786335c..f84de40 100644 --- a/src/types/sandbox.ts +++ b/src/types/sandbox.ts @@ -2,6 +2,7 @@ import type { Blob } from "buffer"; import type { ReadableStream } from "node:stream/web"; import { SessionRegion } from "./constants"; import { SessionLaunchState, SessionStatus } from "./session"; +import type { VaultReference } from "./vault"; export type SandboxStatus = SessionStatus; @@ -81,28 +82,47 @@ export interface SandboxDetail extends Sandbox { export type SandboxVolumeMountType = "rw" | "ro"; +/** + * A stored secret by name, optionally pinned to a version. A + * customer-protected secret also carries `unwrapped`, the envelope the + * customer unwrapped, and must pin the version it came from; + * `secrets.unwrap()` returns one ready to pass. + */ +export interface SandboxStoredSecretReference { + name: string; + version?: number | "latest"; + /** Customer-protected secrets only: the version's unwrapped inner envelope. */ + unwrapped?: string; +} + /** * A stored secret to deliver as an environment variable: its name, or * `{ name, version }` to pin a version. The latest version is used otherwise. */ -export type SandboxSecretReference = - | string - | { - name: string; - version?: number | "latest"; - }; +export type SandboxSecretReference = string | SandboxStoredSecretReference; /** Environment variable name to secret, at most 32 per process or sandbox. */ export type SandboxSecrets = Record; +/** + * A vault whose entries become environment variables: its name, or, when it + * has customer-protected entries, the `VaultReference` from + * `vaults.unwrap()` with their unwrapped envelopes. + */ +export type SandboxVaultSource = string | VaultReference; + /** * Fields of one 1Password vault to deliver as environment variables, read * with a service account token kept as an `op_token` secret when the process * starts. Nothing about it is stored. */ export interface SandboxOnePassword { - /** The name of the `op_token` secret; its latest version is used. */ - token: string; + /** + * The `op_token` secret: its name (its latest version is used), or a + * reference pinning a version. A customer-protected token is passed as + * `secrets.unwrap()` returns it. + */ + token: string | SandboxStoredSecretReference; /** The 1Password vault's name or ID. */ vault: string; /** @@ -205,11 +225,12 @@ export type CreateSandboxParams = */ secrets?: SandboxSecrets; /** - * A vault, by name, whose entries become the startup command's - * environment variables; `secrets` is merged over it and wins on a - * clash. Same requirements as `secrets`. + * A vault whose entries become the startup command's environment + * variables; `secrets` is merged over it and wins on a clash. Same + * requirements as `secrets`. Pass a vault with customer-protected + * entries as `vaults.unwrap()` returns it. */ - vault?: string; + vault?: SandboxVaultSource; /** 1Password fields for the startup command. Same requirements as `secrets`. */ onePassword?: SandboxOnePassword; }); @@ -601,12 +622,13 @@ export interface SandboxExecParams { */ secrets?: SandboxSecrets; /** - * A vault, by name, whose entries become environment variables of this - * process, delivered like `secrets`. `secrets` is merged over it and wins - * on a clash; `env` can't set a variable either of them sets. Together - * they hold at most 32 variables. + * A vault whose entries become environment variables of this process, + * delivered like `secrets`. `secrets` is merged over it and wins on a + * clash; `env` can't set a variable either of them sets. Together they hold + * at most 32 variables. Pass a vault with customer-protected entries as + * `vaults.unwrap()` returns it. */ - vault?: string; + vault?: SandboxVaultSource; /** * Fields of a 1Password vault, read with an `op_token` secret when the * process starts and delivered like `secrets`. A variable set here can't diff --git a/src/types/secret.ts b/src/types/secret.ts index fa48de6..074bf8b 100644 --- a/src/types/secret.ts +++ b/src/types/secret.ts @@ -1,6 +1,20 @@ +import type { CustomerKey } from "../customer-key"; + /** A secret value: a UTF-8 string or its raw bytes, used byte-for-byte. */ export type SecretValue = string | Uint8Array; +/** + * Who can open a secret's values, fixed at creation: + * - `"platform"`: each version is encrypted to the platform's key. + * - `"customer"`: each version is also wrapped with the customer's own key + * (see `CustomerKey`), so the platform stores nothing it can decrypt + * alone. Each use passes the envelope the customer unwrapped, pinned to + * its version; see `secrets.unwrap()` and `vaults.unwrap()`. + * Customer-protected secrets can't be filled into browser pages + * themselves, though an `op_token` one can sign 1Password fills. + */ +export type SecretProtection = "platform" | "customer"; + /** * What a secret's value is, fixed at creation: * - `"secret"`: an opaque value. It can be a sandbox environment variable, @@ -51,6 +65,11 @@ export interface Secret { */ type: string; metadata: SecretMetadata; + /** + * A `SecretProtection`, typed as a string for values added later. Absent + * from API versions before customer protection, which means `"platform"`. + */ + protection?: string; /** Bound into every envelope for this secret; the SDK uses it when encrypting. */ encryptionContext: string; /** Null until a value is stored. */ @@ -61,10 +80,74 @@ export interface Secret { export interface SecretVersion { version: number; + /** The platform key the (inner) envelope was encrypted to. */ kid: string; + /** The customer key that wrapped this version; customer-protected secrets only. */ + outerKid?: string; + /** + * When this version stops working because its platform key is retired. + * After then, uses fail with `SECRET_KEY_RETIRED`; add a new version and use + * that instead. + */ + retiresAt?: string | null; createdAt: string; } +/** A customer-protected version as the API stores it, for the customer to unwrap. */ +export interface WrappedSecretVersion { + version: number; + /** The platform key the inner envelope is encrypted to. */ + kid: string; + retiresAt: string | null; + /** The customer key that wrapped it. */ + outerKid: string; + /** Unpadded base64url SHA-256 of the inner envelope. */ + innerDigest: string; + /** The outer envelope, which only the customer key can open. */ + envelope: string; +} + +/** + * A customer-protected secret ready to use: pass it as a sandbox or process + * `secrets` entry, or as a 1Password `token`. It is the version's inner + * envelope, which only the platform can open, but anyone holding it can use + * that version, so treat it like the secret itself. + */ +export interface UnwrappedSecretReference { + name: string; + version: number; + unwrapped: string; +} + +export interface UnwrapSecretOptions { + /** Defaults to the latest version. */ + version?: number | "latest"; +} + +export interface AddSecretVersionOptions { + /** Required for customer-protected secrets, which it wraps the value with; not allowed otherwise. */ + customerKey?: CustomerKey; +} + +/** A new outer envelope for a version, wrapping the same inner envelope. */ +export interface ReplaceSecretVersionWrappingParams { + envelope: string; + /** Must match the version's `innerDigest`: rewrapping can't change the value. */ + innerDigest: string; +} + +export interface RewrapSecretParams { + /** The key (or keys, picked by `kid`) the versions are wrapped with now. */ + from: CustomerKey | readonly CustomerKey[]; + /** The key to wrap them with instead. */ + to: CustomerKey; + /** + * Versions to rewrap. Defaults to every version not already wrapped with + * `to`, so an interrupted rotation can be run again. + */ + versions?: number[]; +} + export interface SecretDetail extends Secret { versions: SecretVersion[]; } @@ -96,6 +179,16 @@ export interface CreateSecretParams { * `["https://github.com"]`; 1-20 entries. Not for `"op_token"` secrets. */ allowedOrigins?: string[]; + /** + * Defaults to `"customer"` when `customerKey` is given and `"platform"` + * otherwise. Fixed at creation. + */ + protection?: SecretProtection; + /** + * The customer's own key, which wraps every version of a + * customer-protected secret. Required to store `value` in one. + */ + customerKey?: CustomerKey; } /** diff --git a/src/types/session.ts b/src/types/session.ts index 91526b5..2568f6d 100644 --- a/src/types/session.ts +++ b/src/types/session.ts @@ -10,7 +10,7 @@ import { SessionRegion, State, } from "./constants"; -import { SessionCredential, SessionCredentialSource } from "./credential"; +import { SessionCredential, SessionCredentialSource, SessionVault } from "./credential"; export type SessionStatus = "active" | "closed" | "close-error" | "error"; export type BrowserMemorySize = "small" | "medium" | "large"; @@ -94,6 +94,8 @@ export interface SessionDetail extends Session { token: string; /** The secrets attached at creation, when any were requested. */ credentials?: SessionCredential[]; + /** The vaults attached at creation, by reference, when credentials were requested. */ + vaults?: SessionVault[]; } export interface SessionGetParams { @@ -270,13 +272,13 @@ export interface CreateSessionParams { startFromSnapshot?: StartSessionFromSnapshotParams; /** * Secrets that `sessions.credentials.fill` may type into pages, at most 20: - * a secret's name (or `{ secret: name }`), `{ vault: name }` for the - * secrets a vault's entries name when the session is created, or + * a secret's name (or `{ secret: name }`), `{ vault: name }` for a vault + * by reference, whose entries each fill reads as they are then, or * `{ onePassword: name }` for an `op_token` secret whose 1Password fields * fills may read. - * Secrets need allowed origins to be filled. They can only be attached at - * creation; the session runs on Firecracker with Chrome's password manager - * off. + * Secrets need allowed origins to be filled, and customer-protected ones + * can't be filled. They can only be attached at creation; the session runs + * on Firecracker with Chrome's password manager off. */ credentials?: SessionCredentialSource[]; } diff --git a/src/types/vault.ts b/src/types/vault.ts index 73470c4..f27a8e1 100644 --- a/src/types/vault.ts +++ b/src/types/vault.ts @@ -1,3 +1,5 @@ +import type { WrappedSecretVersion } from "./secret"; + /** An entry of a vault: a stored secret. */ export interface VaultEntry { /** The secret's name. */ @@ -5,6 +7,45 @@ export interface VaultEntry { secretId: string; /** A pinned version, or null to follow the secret's latest version. */ version: number | null; + /** + * The secret's `SecretProtection`. With `"customer"`, each use of the vault + * passes this entry's unwrapped envelope (see `vaults.unwrap()`). Absent + * from API versions before customer protection. + */ + protection?: string; +} + +/** A customer-protected entry's wrapped envelope, at the version the entry resolves to now. */ +export interface WrappedVaultEntry extends WrappedSecretVersion { + /** The secret's name. */ + name: string; + secretId: string; +} + +export interface WrappedVault { + id: string; + name: string; + /** Customer-protected entries only, by environment variable. */ + entries: Record; +} + +/** The envelope the customer unwrapped for one entry, and the version it is from. */ +export interface VaultUnwrappedEntry { + version: number; + unwrapped: string; +} + +/** + * A vault with the envelopes of its customer-protected entries, as + * `vaults.unwrap()` returns it: pass it as a sandbox's or process's `vault`. + * The envelopes match the entries as they were unwrapped; if an entry changes + * since, uses fail with `SECRET_VAULT_CHANGED` and the vault must be + * unwrapped again. Anyone holding it can use those versions. + */ +export interface VaultReference { + name: string; + /** Environment variable name to unwrapped envelope; at most 32. */ + unwrapped: Record; } /** Named environment variables whose values come from stored secrets. A vault holds no values itself. */ @@ -18,7 +59,10 @@ export interface Vault { updatedAt: string; } -/** A stored secret, following its latest version unless one is pinned. */ +/** + * A stored secret, following its latest version unless one is pinned. It may + * be customer-protected; entries never hold unwrapped envelopes. + */ export interface VaultEntryParams { /** The secret's name. */ name: string; diff --git a/tests/unit/credentials-fill.test.ts b/tests/unit/credentials-fill.test.ts index 88d3e70..cc65242 100644 --- a/tests/unit/credentials-fill.test.ts +++ b/tests/unit/credentials-fill.test.ts @@ -94,6 +94,16 @@ describe("sessions", () => { >(); }); + test("the session lists the vaults attached on create", async () => { + const vaults = [{ id: "v1", name: "github-login" }]; + fetchMock.mockResolvedValue(respond({ id: "session", vaults })); + const session = await client().sessions.create({ credentials: [{ vault: "github-login" }] }); + expect(session.vaults).toEqual(vaults); + expectTypeOf().toEqualTypeOf< + { id: string; name: string }[] | undefined + >(); + }); + test("a vault fill posts the entries with a timeout above the server's", async () => { fetchMock.mockResolvedValue(respond(filled)); const result = await client(1000).sessions.credentials.fill(SESSION, { @@ -271,6 +281,24 @@ describe("1Password fills", () => { expectTypeOf(result.version).toEqualTypeOf(); }); + test("a customer-protected op_token is sent as an unwrapped reference", async () => { + fetchMock.mockResolvedValue(respond(opResult)); + const token = { name: "op-token", version: 2, unwrapped: "a.b.c.d.e" }; + await client().sessions.credentials.fill(SESSION, { + onePassword: { ...onePassword, token }, + fields: refFields, + }); + expect(lastRequest().body.onePassword).toEqual({ ...onePassword, token }); + + await expect( + client().sessions.credentials.fill(SESSION, { + onePassword: { ...onePassword, token: { name: "op-token", unwrapped: "a.b.c.d.e" } }, + fields: refFields, + }) + ).rejects.toMatchObject({ code: "invalid_request" }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + test("local and wildcard origins, and a 512-byte reference, are accepted", async () => { fetchMock.mockImplementation(async () => respond(opResult)); await client().sessions.credentials.fill(SESSION, { diff --git a/tests/unit/customer-secrets.test.ts b/tests/unit/customer-secrets.test.ts new file mode 100644 index 0000000..76b957a --- /dev/null +++ b/tests/unit/customer-secrets.test.ts @@ -0,0 +1,503 @@ +import crypto from "crypto"; +import { describe, expect, expectTypeOf, test, vi } from "vitest"; +import { HyperbrowserError } from "../../src/client"; +import { createCustomerKey, CustomerKey, secretEnvelopeDigest } from "../../src/customer-key"; +import { SecretsSealer } from "../../src/secrets-envelope"; +import { SecretsService } from "../../src/services/secrets"; +import { VaultsService } from "../../src/services/vaults"; +import type { + SandboxSecretReference, + SandboxVaultSource, + SecretsPublicKey, + UnwrappedSecretReference, + VaultReference, + WrappedSecretVersion, +} from "../../src/types"; + +const ID = "6f1d3c1e-5b8a-4e6f-9a51-0c2b7f3d9e10"; +const VAULT_ID = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; +const CONTEXT = `hb-secret-v1:team-1:${ID}`; + +const platformKey = crypto.generateKeyPairSync("rsa", { modulusLength: 3072 }); +const platformPublicKey: SecretsPublicKey = (() => { + const jwk = platformKey.publicKey.export({ format: "jwk" }) as { n: string; e: string }; + const kid = crypto + .createHash("sha256") + .update(`{"e":"${jwk.e}","kty":"RSA","n":"${jwk.n}"}`) + .digest("base64url"); + return { kid, alg: "RSA-OAEP-256", enc: "A256GCM", jwk: { kty: "RSA", n: jwk.n, e: jwk.e } }; +})(); + +/** Opens an inner envelope with the platform key, as vm-service would. */ +const openInner = (envelope: string) => { + const [protectedHeader, encryptedKey, iv, ciphertext, tag] = envelope.split("."); + const cek = crypto.privateDecrypt( + { + key: platformKey.privateKey, + padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, + oaepHash: "sha256", + }, + Buffer.from(encryptedKey, "base64url") + ); + const decipher = crypto.createDecipheriv("aes-256-gcm", cek, Buffer.from(iv, "base64url")); + decipher.setAAD(Buffer.from(protectedHeader, "ascii")); + decipher.setAuthTag(Buffer.from(tag, "base64url")); + return { + header: JSON.parse(Buffer.from(protectedHeader, "base64url").toString()), + value: Buffer.concat([ + decipher.update(Buffer.from(ciphertext, "base64url")), + decipher.final(), + ]).toString(), + }; +}; + +const headerOf = (envelope: string) => + JSON.parse(Buffer.from(envelope.split(".")[0], "base64url").toString()); + +const rsaKey = createCustomerKey( + crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey +); +const ecKey = createCustomerKey( + crypto.generateKeyPairSync("ec", { namedCurve: "P-256" }).privateKey +); + +const secret = (overrides: Record = {}) => ({ + id: ID, + name: "db-password", + description: "", + type: "secret", + metadata: {}, + protection: "customer", + encryptionContext: CONTEXT, + latestVersion: null, + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", + ...overrides, +}); + +/** Routes `request(path, init, params)` calls to `handler(method, path, body, params)`. */ +const mockService = ( + service: T, + handler: (method: string, path: string, body: any, params: any) => unknown +) => { + const requestSpy = vi + .spyOn(service as any, "request") + .mockImplementation(async (path: any, init: any, params: any) => { + const result = handler( + init?.method ?? "GET", + path, + init?.body ? JSON.parse(init.body) : undefined, + params + ); + if (result instanceof Error) throw result; + return result; + }); + const calls = () => + requestSpy.mock.calls.map(([path, init]: any[]) => `${init?.method ?? "GET"} ${path}`); + const bodies = () => + requestSpy.mock.calls.map(([, init]: any[]) => + init?.body ? JSON.parse(init.body) : undefined + ); + return { service, requestSpy, calls, bodies }; +}; + +const secrets = () => new SecretsService("test-key", "https://api.example.com", 30_000); + +/** A stored customer-protected version: `value` sealed to the platform and wrapped with `key`. */ +const storedVersion = ( + value: string, + key: CustomerKey, + version = 1 +): WrappedSecretVersion & { inner: string } => { + const sealer = SecretsSealer.fromPublicKey(platformPublicKey); + const inner = sealer.seal(CONTEXT, value); + return { + version, + kid: platformPublicKey.kid, + retiresAt: null, + outerKid: key.kid, + innerDigest: secretEnvelopeDigest(inner), + envelope: key.wrap(inner, CONTEXT) as string, + inner, + }; +}; + +describe("customer keys", () => { + test("secretEnvelopeDigest is the base64url SHA-256 of the envelope", () => { + expect(secretEnvelopeDigest("a.b.c.d.e")).toBe( + crypto.createHash("sha256").update("a.b.c.d.e").digest("base64url") + ); + expect(secretEnvelopeDigest("a.b.c.d.e")).toHaveLength(43); + }); + + test.each([ + ["RSA", () => crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }), "RSA-OAEP-256"], + ["P-384", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-384" }), "ECDH-ES+A256KW"], + ["P-521", () => crypto.generateKeyPairSync("ec", { namedCurve: "P-521" }), "ECDH-ES+A256KW"], + ["X25519", () => crypto.generateKeyPairSync("x25519"), "ECDH-ES+A256KW"], + ["X448", () => crypto.generateKeyPairSync("x448"), "ECDH-ES+A256KW"], + ])("%s keys wrap to the secret's context and unwrap", (_label, generate, alg) => { + const { privateKey } = generate(); + const key = createCustomerKey(privateKey); + const inner = "header.key.iv.ciphertext.tag"; + const wrapped = key.wrap(inner, CONTEXT) as string; + const header = headerOf(wrapped); + expect(header).toMatchObject({ alg, enc: "A256GCM", kid: key.kid, ctx: CONTEXT }); + expect(Object.keys(header).sort()).toEqual( + alg === "RSA-OAEP-256" ? ["alg", "ctx", "enc", "kid"] : ["alg", "ctx", "enc", "epk", "kid"] + ); + expect(key.unwrap(wrapped)).toBe(inner); + }); + + test("direct ECDH-ES leaves the encrypted key empty", () => { + const key = createCustomerKey(crypto.generateKeyPairSync("x25519").privateKey, { + algorithm: "ECDH-ES", + }); + const wrapped = key.wrap("a.b.c.d.e", CONTEXT) as string; + expect(wrapped.split(".")[1]).toBe(""); + expect(headerOf(wrapped).alg).toBe("ECDH-ES"); + expect(key.unwrap(wrapped)).toBe("a.b.c.d.e"); + }); + + test("the kid is the RFC 7638 thumbprint unless the JWK or options name one", () => { + const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" }); + const jwk = publicKey.export({ format: "jwk" }); + const thumbprint = crypto + .createHash("sha256") + .update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y })) + .digest("base64url"); + expect(createCustomerKey(privateKey).kid).toBe(thumbprint); + expect(createCustomerKey(publicKey).kid).toBe(thumbprint); + expect(createCustomerKey(publicKey.export({ type: "spki", format: "pem" })).kid).toBe( + thumbprint + ); + expect(createCustomerKey({ ...jwk, kid: "team-key-2026" }).kid).toBe("team-key-2026"); + expect(createCustomerKey(privateKey, { kid: "kms/key-1" }).kid).toBe("kms/key-1"); + }); + + test("PEM and JWK private keys unwrap; public keys only wrap", () => { + const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }); + const fromPem = createCustomerKey(privateKey.export({ type: "pkcs8", format: "pem" })); + const fromJwk = createCustomerKey(privateKey.export({ format: "jwk" })); + const publicOnly = createCustomerKey(publicKey); + expect(fromPem.canUnwrap && fromJwk.canUnwrap).toBe(true); + expect(publicOnly.canUnwrap).toBe(false); + const wrapped = publicOnly.wrap("a.b.c.d.e", CONTEXT) as string; + expect(fromPem.unwrap(wrapped)).toBe("a.b.c.d.e"); + expect(fromJwk.unwrap(wrapped)).toBe("a.b.c.d.e"); + expect(() => publicOnly.unwrap(wrapped)).toThrow( + expect.objectContaining({ code: "customer_key_private_key_required" }) + ); + }); + + test("keys the API would refuse are rejected", () => { + const small = crypto.generateKeyPairSync("rsa", { modulusLength: 1024 }).privateKey; + const k256 = crypto.generateKeyPairSync("ec", { namedCurve: "secp256k1" }).privateKey; + const ed = crypto.generateKeyPairSync("ed25519").privateKey; + for (const key of [small, k256, ed]) { + expect(() => createCustomerKey(key)).toThrow( + expect.objectContaining({ code: "invalid_customer_key" }) + ); + } + expect(() => createCustomerKey(crypto.createSecretKey(Buffer.alloc(32)))).toThrow(/asymmetric/); + expect(() => createCustomerKey("not a key")).toThrow(/PEM or DER/); + expect(() => createCustomerKey(rsaKeyObject(), { algorithm: "ECDH-ES" })).toThrow( + /RSA-OAEP-256/ + ); + expect(() => createCustomerKey(rsaKeyObject(), { kid: "caf\u00e9" })).toThrow( + /printable ASCII/ + ); + expect(() => createCustomerKey(rsaKeyObject(), { kid: "x".repeat(257) })).toThrow(/1-256/); + }); + + test("unwrapping names a key mismatch and refuses a tampered envelope", () => { + const wrapped = rsaKey.wrap("a.b.c.d.e", CONTEXT) as string; + expect(() => ecKey.unwrap(wrapped)).toThrow( + expect.objectContaining({ code: "customer_key_mismatch" }) + ); + const segments = wrapped.split("."); + const tag = Buffer.from(segments[4], "base64url"); + tag[0] ^= 1; + segments[4] = tag.toString("base64url"); + expect(() => rsaKey.unwrap(segments.join("."))).toThrow( + expect.objectContaining({ code: "customer_key_unwrap_failed" }) + ); + expect(() => rsaKey.unwrap("a.b.c")).toThrow(/five segments/); + }); +}); + +function rsaKeyObject() { + return crypto.generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey; +} + +describe("customer-protected secrets", () => { + test("create wraps the first value with the customer key", async () => { + const { service, calls, bodies } = mockService(secrets(), (method, path) => { + if (path === "/secrets/public-key") return platformPublicKey; + if (method === "POST" && path === "/secrets") return secret(); + if (method === "POST" && path === `/secrets/${ID}/versions`) { + return { version: 1, kid: platformPublicKey.kid, outerKid: rsaKey.kid, retiresAt: null }; + } + throw new Error(`unexpected ${method} ${path}`); + }); + + const created = await service.create({ + name: "db-password", + value: "hunter2", + customerKey: rsaKey, + }); + + expect(created.latestVersion).toBe(1); + expect(calls()).toEqual([ + "GET /secrets/public-key", + "POST /secrets", + `POST /secrets/${ID}/versions`, + ]); + expect(bodies()[1]).toEqual({ name: "db-password", protection: "customer" }); + const upload = bodies()[2]; + expect(Object.keys(upload).sort()).toEqual(["envelope", "innerDigest", "innerKid"]); + expect(upload.innerKid).toBe(platformPublicKey.kid); + expect(headerOf(upload.envelope)).toMatchObject({ kid: rsaKey.kid, ctx: CONTEXT }); + const inner = rsaKey.unwrap(upload.envelope) as string; + expect(secretEnvelopeDigest(inner)).toBe(upload.innerDigest); + expect(openInner(inner)).toMatchObject({ + header: { kid: platformPublicKey.kid, ctx: CONTEXT }, + value: "hunter2", + }); + }); + + test("create sends protection without a value, and checks keys before any request", async () => { + const { service, calls, bodies } = mockService(secrets(), () => secret()); + await service.create({ name: "db-password", protection: "customer" }); + expect(bodies()).toEqual([{ name: "db-password", protection: "customer" }]); + + for (const params of [ + { name: "db-password", protection: "customer" as const, value: "v" }, + { name: "db-password", protection: "platform" as const, customerKey: rsaKey }, + { name: "db-password", customerKey: {} as CustomerKey }, + { name: "db-password", protection: "vendor" as any }, + ]) { + await expect(service.create(params)).rejects.toMatchObject({ code: "invalid_request" }); + } + expect(calls()).toEqual(["POST /secrets"]); + }); + + test("addVersion wraps for customer-protected secrets and refuses a mismatched key option", async () => { + let protection = "customer"; + const { service, calls, bodies } = mockService(secrets(), (method, path) => { + if (path === "/secrets/public-key") return platformPublicKey; + if (path === `/secrets/${ID}`) return { ...secret({ protection }), versions: [] }; + if (method === "POST") return { version: 2, kid: platformPublicKey.kid, outerKid: ecKey.kid }; + throw new Error(`unexpected ${method} ${path}`); + }); + + await service.addVersion(ID, "hunter3", { customerKey: ecKey }); + const upload = bodies()[2]; + expect(openInner(ecKey.unwrap(upload.envelope) as string).value).toBe("hunter3"); + expect(upload.innerDigest).toBe(secretEnvelopeDigest(ecKey.unwrap(upload.envelope) as string)); + + await expect(service.addVersion(ID, "v")).rejects.toThrow( + /customer-protected: pass customerKey/ + ); + protection = "platform"; + await expect(service.addVersion(ID, "v", { customerKey: ecKey })).rejects.toThrow( + /not customer-protected/ + ); + expect(calls().filter((call) => call.startsWith("POST"))).toHaveLength(1); + }); + + test("unwrap returns a pinned reference whose envelope matches the stored digest", async () => { + const stored = storedVersion("hunter2", rsaKey, 4); + const { service, calls } = mockService(secrets(), (_method, path) => { + if (path === `/secrets/${ID}`) return { ...secret({ latestVersion: 4 }), versions: [] }; + if (path === `/secrets/${ID}/versions/latest/wrapped`) return stored; + if (path === `/secrets/${ID}/versions/4/wrapped`) return stored; + throw new Error(`unexpected ${path}`); + }); + + const reference = await service.unwrap(ID, [ecKey, rsaKey]); + expectTypeOf(reference).toEqualTypeOf(); + expectTypeOf(reference).toMatchTypeOf(); + expect(reference).toEqual({ name: "db-password", version: 4, unwrapped: stored.inner }); + await service.unwrap(ID, rsaKey, { version: 4 }); + expect(calls()).toEqual([ + `GET /secrets/${ID}`, + `GET /secrets/${ID}/versions/latest/wrapped`, + `GET /secrets/${ID}`, + `GET /secrets/${ID}/versions/4/wrapped`, + ]); + }); + + test("unwrap refuses a key that didn't wrap the version, and a digest mismatch", async () => { + let stored: WrappedSecretVersion = storedVersion("hunter2", rsaKey); + const { service } = mockService(secrets(), (_method, path) => + path.endsWith("/wrapped") ? stored : { ...secret(), versions: [] } + ); + await expect(service.unwrap(ID, ecKey)).rejects.toMatchObject({ + code: "customer_key_mismatch", + }); + stored = { ...stored, innerDigest: secretEnvelopeDigest("something else") }; + await expect(service.unwrap(ID, rsaKey)).rejects.toThrow(/doesn't match its innerDigest/); + await expect(service.unwrap(ID, [])).rejects.toThrow(/at least one customer key/); + }); + + test("getWrappedVersion fetches a version's outer envelope", async () => { + const stored = storedVersion("hunter2", rsaKey, 2); + const { service, calls } = mockService(secrets(), (_method, path) => + path.endsWith("/wrapped") ? stored : { ...secret(), versions: [] } + ); + await expect(service.getWrappedVersion(ID, 2)).resolves.toEqual(stored); + await expect(service.getWrappedVersion(ID, 0)).rejects.toThrow(/version must be/); + expect(calls()).toEqual([`GET /secrets/${ID}`, `GET /secrets/${ID}/versions/2/wrapped`]); + }); + + test("rewrap moves every version not yet on the new key, keeping the inner envelope", async () => { + const v1 = storedVersion("one", rsaKey, 1); + const v2 = storedVersion("two", rsaKey, 2); + const v3 = storedVersion("three", ecKey, 3); + const byVersion: Record = { + 1: v1, + 2: v2, + 3: v3, + }; + const { service, calls, bodies } = mockService(secrets(), (method, path, body) => { + if (path === `/secrets/${ID}`) { + return { + ...secret({ latestVersion: 3 }), + versions: [v3, v2, v1].map(({ version, kid, outerKid }) => ({ version, kid, outerKid })), + }; + } + const match = /\/versions\/(\d+)\/(wrapped|wrapping)$/.exec(path)!; + const stored = byVersion[Number(match[1])]; + if (method === "GET") return stored; + return { ...stored, envelope: body.envelope, outerKid: headerOf(body.envelope).kid }; + }); + + const rewrapped = await service.rewrap(ID, { from: rsaKey, to: ecKey }); + + expect(calls()).toEqual([ + `GET /secrets/${ID}`, + `GET /secrets/${ID}/versions/2/wrapped`, + `PUT /secrets/${ID}/versions/2/wrapping`, + `GET /secrets/${ID}/versions/1/wrapped`, + `PUT /secrets/${ID}/versions/1/wrapping`, + ]); + expect(rewrapped.map(({ version, outerKid }) => [version, outerKid])).toEqual([ + [2, ecKey.kid], + [1, ecKey.kid], + ]); + const puts = bodies().filter((body) => body !== undefined); + expect(puts[0].innerDigest).toBe(v2.innerDigest); + expect(ecKey.unwrap(puts[0].envelope)).toBe(v2.inner); + expect(headerOf(puts[1].envelope).ctx).toBe(CONTEXT); + expect(ecKey.unwrap(puts[1].envelope)).toBe(v1.inner); + }); + + test("rewrap refuses platform secrets, and replaceVersionWrapping sends the envelope as given", async () => { + const { service, calls, bodies } = mockService(secrets(), (method, path) => { + if (path === `/secrets/${ID}`) return { ...secret({ protection: "platform" }), versions: [] }; + if (method === "PUT") return storedVersion("x", ecKey, 5); + throw new Error(`unexpected ${path}`); + }); + await expect(service.rewrap(ID, { from: rsaKey, to: ecKey })).rejects.toThrow( + /not customer-protected/ + ); + await service.replaceVersionWrapping(ID, 5, { envelope: "outer", innerDigest: "digest" }); + expect(calls()).toEqual([ + `GET /secrets/${ID}`, + `GET /secrets/${ID}`, + `PUT /secrets/${ID}/versions/5/wrapping`, + ]); + expect(bodies()[2]).toEqual({ envelope: "outer", innerDigest: "digest" }); + await expect( + service.replaceVersionWrapping(ID, 5, { envelope: "", innerDigest: "digest" }) + ).rejects.toMatchObject({ code: "invalid_request" }); + }); + + test("version details keep outerKid and retiresAt", async () => { + const versions = [ + { + version: 2, + kid: "p", + outerKid: rsaKey.kid, + retiresAt: "2027-01-01T00:00:00.000Z", + createdAt: "x", + }, + ]; + const { service } = mockService(secrets(), () => ({ ...secret(), versions })); + const detail = await service.get(ID); + expect(detail.protection).toBe("customer"); + expect(detail.versions).toEqual(versions); + }); +}); + +describe("customer-protected vaults", () => { + const vaults = () => new VaultsService("test-key", "https://api.example.com", 30_000); + const vault = { + id: VAULT_ID, + name: "app-env", + description: "", + entries: { + DB_PASSWORD: { name: "db-password", secretId: ID, version: null, protection: "customer" }, + API_KEY: { name: "api-key", secretId: "s2", version: 3, protection: "platform" }, + }, + createdAt: "x", + updatedAt: "x", + }; + + test("unwrap returns the vault reference sandboxes and processes take", async () => { + const stored = storedVersion("hunter2", ecKey, 7); + const { service, calls } = mockService(vaults(), (_method, path) => { + if (path === `/vaults/${VAULT_ID}`) return vault; + if (path === `/vaults/${VAULT_ID}/wrapped`) { + return { + id: VAULT_ID, + name: "app-env", + entries: { DB_PASSWORD: { ...stored, name: "db-password", secretId: ID } }, + }; + } + throw new Error(`unexpected ${path}`); + }); + + const reference = await service.unwrap(VAULT_ID, [rsaKey, ecKey]); + + expectTypeOf(reference).toEqualTypeOf(); + expectTypeOf(reference).toMatchTypeOf(); + expect(reference).toEqual({ + name: "app-env", + unwrapped: { DB_PASSWORD: { version: 7, unwrapped: stored.inner } }, + }); + expect(calls()).toEqual([`GET /vaults/${VAULT_ID}`, `GET /vaults/${VAULT_ID}/wrapped`]); + }); + + test("unwrap names the entry whose key is missing", async () => { + const stored = storedVersion("hunter2", ecKey, 7); + const { service } = mockService(vaults(), (_method, path) => + path.endsWith("/wrapped") + ? { + id: VAULT_ID, + name: "app-env", + entries: { DB_PASSWORD: { ...stored, name: "db-password", secretId: ID } }, + } + : vault + ); + const error = await service.unwrap(VAULT_ID, rsaKey).catch((e) => e); + expect(error).toBeInstanceOf(HyperbrowserError); + expect(error).toMatchObject({ code: "customer_key_mismatch" }); + expect(error.message).toContain("Entry DB_PASSWORD of vault app-env"); + }); + + test("a vault with no customer-protected entries unwraps to an empty reference", async () => { + const { service, calls } = mockService(vaults(), (_method, path) => { + if (path === "/vaults") return { vaults: [vault], total: 1, page: 1, limit: 100 }; + if (path === `/vaults/${VAULT_ID}/wrapped`) + return { id: VAULT_ID, name: "app-env", entries: {} }; + throw new Error(`unexpected ${path}`); + }); + await expect(service.unwrap("app-env", rsaKey)).resolves.toEqual({ + name: "app-env", + unwrapped: {}, + }); + expect(calls()).toEqual(["GET /vaults", `GET /vaults/${VAULT_ID}/wrapped`]); + }); +}); diff --git a/tests/unit/sandbox-secrets.test.ts b/tests/unit/sandbox-secrets.test.ts index 043e19d..1fd5ec7 100644 --- a/tests/unit/sandbox-secrets.test.ts +++ b/tests/unit/sandbox-secrets.test.ts @@ -666,6 +666,111 @@ describe("1Password in sandboxes", () => { }); }); +describe("customer-protected secrets in sandboxes", () => { + const unwrapped = "eyJhbGciOiJSU0EtT0FFUC0yNTYifQ.key.iv.ciphertext.tag"; + const vault = { + name: "app-env", + unwrapped: { DB_PASSWORD: { version: 7, unwrapped } }, + }; + const tokenReference = { name: "op-token", version: 2, unwrapped }; + const onePassword = { + token: tokenReference, + vault: "Engineering", + fields: { DB_PASS: { item: "Postgres", field: "password" } }, + }; + + test("image launches send unwrapped references, vault references and 1Password tokens", async () => { + const service = new SandboxesService("test-key", "https://api.example.com", 30_000); + const requestSpy = vi.spyOn(service as any, "request").mockResolvedValue(wireDetail); + + await service.create({ + imageName: "node", + secrets: { API_KEY: { name: "provider-key", version: 4, unwrapped } }, + vault: { ...vault, extra: "dropped" } as typeof vault, + onePassword, + }); + + const body = JSON.parse((requestSpy.mock.calls[0][1] as any).body); + expect(body).toMatchObject({ + secrets: { API_KEY: { name: "provider-key", version: 4, unwrapped } }, + vault, + onePassword, + }); + expect(body.vault).not.toHaveProperty("extra"); + }); + + test("process start sends the same shapes through the control API", async () => { + const start = starter(); + const api = new SandboxProcessesApi(runtime({}).transport, start); + await api.start("node app.js", { + secrets: { API_KEY: { name: "provider-key", version: 4, unwrapped } }, + vault, + onePassword, + }); + expect(start.start.mock.calls[0][0]).toEqual({ + command: "node app.js", + secrets: { API_KEY: { name: "provider-key", version: 4, unwrapped } }, + vault, + onePassword, + }); + }); + + test.each([ + [{ secrets: { A: { name: "x", unwrapped } } }, /Pin the version of A/], + [{ secrets: { A: { name: "x", version: "latest", unwrapped } } }, /Pin the version of A/], + [{ secrets: { A: { name: "x", version: 1, unwrapped: "" } } }, /unwrapped envelope for A/], + [{ secrets: { A: { name: "x", version: 1, unwrapped: "x".repeat(65537) } } }, /1 to 65536/], + [{ vault: { name: "app env", unwrapped: {} } }, /Invalid vault name/], + [{ vault: { name: "app-env" } }, /vault.unwrapped must map/], + [{ vault: ["app-env"] }, /vault must be a vault's name/], + [ + { vault: { name: "app-env", unwrapped: { "1A": { version: 1, unwrapped } } } }, + /Invalid environment variable name in vault/, + ], + [ + { vault: { name: "app-env", unwrapped: { A: { version: "latest", unwrapped } } } }, + /must be the integer/, + ], + [ + { vault: { name: "app-env", unwrapped: { A: { version: 1 } } } }, + /unwrapped envelope of vault app-env's A/, + ], + [ + { onePassword: { ...onePassword, token: { name: "op-token", unwrapped } } }, + /Pin the version of the 1Password token/, + ], + [ + { onePassword: { ...onePassword, token: { name: "op token" } } }, + /Invalid secret name for the 1Password token/, + ], + ])("bad customer references are rejected before any request: %j", async (params, message) => { + const service = new SandboxesService("test-key", "https://api.example.com", 30_000); + const requestSpy = vi.spyOn(service as any, "request").mockResolvedValue(wireDetail); + await expect(service.create({ imageName: "node", ...(params as any) })).rejects.toThrow( + message + ); + const start = starter(); + await expect( + new SandboxProcessesApi(runtime({}).transport, start).start("x", params as any) + ).rejects.toThrow(message); + expect(requestSpy).not.toHaveBeenCalled(); + expect(start.start).not.toHaveBeenCalled(); + }); + + test("at most 32 unwrapped vault entries are sent", async () => { + const service = new SandboxesService("test-key", "https://api.example.com", 30_000); + vi.spyOn(service as any, "request").mockResolvedValue(wireDetail); + const entries = (count: number) => + Object.fromEntries( + Array.from({ length: count }, (_, i) => [`E${i}`, { version: 1, unwrapped }]) + ); + await service.create({ imageName: "node", vault: { name: "app-env", unwrapped: entries(32) } }); + await expect( + service.create({ imageName: "node", vault: { name: "app-env", unwrapped: entries(33) } }) + ).rejects.toThrow(/At most 32 unwrapped vault entries/); + }); +}); + describe("control API error fields", () => { class TestService extends BaseService { post(path: string) { From 7446b4d81b7d86f1686a0e3c3849f85dfd283727 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:38:51 +0000 Subject: [PATCH 2/6] Document customer-protected secrets Co-authored-by: Ninad Sinha --- README.md | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/README.md b/README.md index 915e05a..8c5831f 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,82 @@ console.log(result.fields); - `CredentialFillTool` can't fill from 1Password; call `sessions.credentials.fill` directly (see [Use with LLM SDKs](#use-with-llm-sdks)). +### Customer-protected secrets + +A secret created with `protection: "customer"` is also wrapped with your own +key, so the platform stores nothing it can open alone. Each version is sealed +to the platform key as usual, then wrapped locally with your key. To use one, +unwrap it locally and pass the result. Only the platform can open the +unwrapped envelope, and it checks that the envelope belongs to the version +you pinned. + +```typescript +import { createCustomerKey } from "@hyperbrowser/sdk"; + +// RSA (2048 bits or more), EC P-256/P-384/P-521, X25519 or X448: a KeyObject, +// PEM/DER or a JWK. A public key can wrap; unwrapping needs the private key. +const customerKey = createCustomerKey(process.env.HB_CUSTOMER_KEY_PEM!); + +await client.secrets.create({ name: "db-pass", value: "hunter2", customerKey }); +await client.secrets.addVersion("db-pass", "hunter3", { customerKey }); + +// A reference pinned to the version unwrapped: { name, version, unwrapped }. +const dbPass = await client.secrets.unwrap("db-pass", customerKey); +const sandbox = await client.sandboxes.create({ + imageName: "my-image", + secrets: { DB_PASS: dbPass }, +}); +await sandbox.exec("node migrate.js", { secrets: { DB_PASS: dbPass } }); + +// A vault's customer-protected entries, unwrapped together. Its other entries +// are delivered as usual. +const appEnv = await client.vaults.unwrap("app-env", customerKey); +await sandbox.processes.start("node worker.js", { vault: appEnv }); + +// A customer-protected op_token, for sandboxes and 1Password fills. +const token = await client.secrets.unwrap("op-token", customerKey); +await sandbox.exec("node app.js", { + onePassword: { token, vault: "Engineering", fields: { DB_PASS: { item: "Postgres", field: "password" } } }, +}); +``` + +- `protection` is `"platform"` (the default) or `"customer"`, and is fixed when + the secret is created. Passing `customerKey` to `create` implies + `"customer"`. Creating one without a value gives an empty secret; add its + first version with `addVersion(secret, value, { customerKey })`. +- The key's `kid` is its RFC 7638 thumbprint unless the JWK has a `kid` or you + pass `createCustomerKey(key, { kid })`. RSA keys wrap with `RSA-OAEP-256`. + EC and OKP keys default to `ECDH-ES+A256KW`; pass `{ algorithm: "ECDH-ES" }` + for direct key agreement. To keep the private key in a KMS or HSM, implement + `CustomerKey` yourself: `kid`, `wrap(innerEnvelope, encryptionContext)` and + `unwrap(wrappedEnvelope)` produce and open a compact JWE with protected + header `{ alg, enc: "A256GCM", kid, ctx }`. `ctx` must be the secret's + `encryptionContext`. Either method may return a promise. +- `unwrap(secret, keys, { version })` unwraps the latest version by default. + `vaults.unwrap(vault, keys)` unwraps the versions the vault's entries + resolve to now. Both take several keys, such as during a rotation, and use + the one whose `kid` wrapped each version (`customer_key_mismatch` if none + did). The unwrapped envelope is checked against the version's `innerDigest` + locally, and again by the API. +- An unwrapped reference must pin a number, never `"latest"`. A vault reference + is refused with `SECRET_VAULT_CHANGED` when an entry was repointed or moved + to a newer version since it was unwrapped; unwrap it again. +- Customer-protected secrets can't be typed into browser pages, including as + vault entries in a fill (`SECRET_REQUIRES_CUSTOMER_UNWRAP`). A + customer-protected `op_token` can still sign 1Password fills: pass the + unwrapped reference as `onePassword.token`. +- Rotate your key with `rewrap(secret, { from, to })`. It unwraps each version + still wrapped with another key and rewraps it with `to`, all locally; the + value and the version numbers don't change. It skips versions already + wrapped with `to`, so an interrupted rotation resumes where it stopped. + `getWrappedVersion` and `replaceVersionWrapping` are the single-version + steps, for wrapping done elsewhere. +- Version details include `outerKid`, the customer key that wrapped them, and + `retiresAt`. A version whose platform key is retired is refused with + `SECRET_KEY_RETIRED`: add a new version. +- Fetching wrapped versions needs `secrets.use`, and rewrapping needs + `secrets.manage`. Signed-in users must be team owners or admins. + ### Errors API errors are `HyperbrowserError`s with `statusCode`, `code` and `retryable` @@ -367,6 +443,12 @@ own `details` holds the specifics (such as `error.details.details.origin`). | `SECRET_ONEPASSWORD_AUTH_FAILED` | 1Password refused the token, or the token is malformed or signs in somewhere other than `1password.com`, `.ca` or `.eu` (or their subdomains). | | `SECRET_ONEPASSWORD_RATE_LIMITED`, `SECRET_ONEPASSWORD_FAILED` | Retryable. | | `SECRET_SOURCES_INVALID` | Bad `vault`/`onePassword`/`secrets`/`env` combination, such as a `onePassword` variable also set by the vault, more than 32 variables, or a vault with no entries. | +| `SECRET_REQUIRES_CUSTOMER_UNWRAP` | A customer-protected secret was used without its unwrapped envelope, unwrapped with `"latest"` instead of a pinned version, or used where it can't be (a fill). | +| `SECRET_PROTECTION_MISMATCH` | An unwrapped envelope for a secret that isn't customer-protected, or a version uploaded in the other protection's form. | +| `SECRET_DIGEST_MISMATCH` | The unwrapped envelope (or a rewrap's `innerDigest`) doesn't match the version. | +| `SECRET_VERSION_DUPLICATE` | Another version already holds this inner envelope; rewrap that version instead. | +| `SECRET_VAULT_CHANGED` | A vault entry resolves to another secret or version than the one unwrapped; unwrap the vault again. | +| `SECRET_KEY_RETIRED` | The version was sealed to a retired platform key; add a new version. | | `VAULT_NOT_FOUND`, `VAULT_ENTRY_NOT_FOUND` | | | `VAULT_NAME_TAKEN`, `VAULT_LIMIT_REACHED`, `VAULT_ENTRY_LIMIT_REACHED` | | | `SECRETS_FEATURE_DISABLED` | The team doesn't have secrets enabled. | From 72da9b2f8b1f1e78db4b85ad05a7028e0403bbc4 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:38:52 +0000 Subject: [PATCH 3/6] Set the version to 1.5.0 Co-authored-by: Ninad Sinha --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9fb1ebb..9b76fee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hyperbrowser/sdk", - "version": "1.4.1", + "version": "1.5.0", "description": "Node SDK for Hyperbrowser API", "author": "", "repository": { From 45d0a243fcfda8620c0ebe3839e82b9b777b3ddd Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:44:28 +0000 Subject: [PATCH 4/6] Document that sessions attach vaults by reference Co-authored-by: Ninad Sinha --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8c5831f..6e83f68 100644 --- a/README.md +++ b/README.md @@ -154,10 +154,11 @@ try { ``` - `credentials` takes up to 20 items: a secret's name (or `{ secret }`), - `{ vault }` for the secrets a stored vault names when the session is created, - or `{ onePassword }` for an `op_token` secret (see - [Fill from 1Password](#fill-from-1password)); the API validates names and limits. - `session.credentials` lists the attached secrets as `{ id, name }`. Fill a + `{ vault }` for a stored vault, or `{ onePassword }` for an `op_token` secret + (see [Fill from 1Password](#fill-from-1password)); the API validates names + and limits. A vault is attached by reference, so each fill uses the secrets + its entries name at that moment. `session.credentials` lists the attached + secrets as `{ id, name }`, and `session.vaults` the vaults. Fill a single secret with `{ credential: "github-password", fields: [{ selector }] }`; with `vault`, each field names its entry in `field`. - Each input reports an `outcome`: `filled`, `not_found` (no input matched), @@ -423,7 +424,7 @@ own `details` holds the specifics (such as `error.details.details.origin`). | Code | Meaning | |---|---| -| `CREDENTIAL_NOT_ATTACHED` | The secret, vault or 1Password token wasn't attached to the session, or a vault entry was repointed since. | +| `CREDENTIAL_NOT_ATTACHED` | The secret, vault or 1Password token wasn't attached to the session, directly or as an entry of an attached vault. | | `CREDENTIAL_ORIGIN_NOT_ALLOWED` | The page isn't on the secret's allowed origins (for 1Password, the request's); nothing was typed. | | `CREDENTIAL_NOT_READY` | The secret has no allowed origins or no value. | | `CREDENTIAL_PAGE_NOT_FOUND`, `CREDENTIAL_FRAME_NOT_FOUND` | No tab or iframe matched. | From 3b276faa14d86c5c8ac825c745d7116e70fd4786 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:54:03 +0000 Subject: [PATCH 5/6] Check customer keys against the shared interop fixture Co-authored-by: Ninad Sinha --- tests/fixtures/customer_key_interop.json | 80 ++++++++++++++++++++++++ tests/unit/customer-secrets.test.ts | 31 ++++++++- 2 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 tests/fixtures/customer_key_interop.json diff --git a/tests/fixtures/customer_key_interop.json b/tests/fixtures/customer_key_interop.json new file mode 100644 index 0000000..0f0c742 --- /dev/null +++ b/tests/fixtures/customer_key_interop.json @@ -0,0 +1,80 @@ +{ + "about": "Throwaway test keys. Envelopes wrapped by the Node and Python SDKs; each SDK must unwrap both.", + "context": "hb-secret-v1:team_fixture:6f1d3c1e-5b8a-4e6f-9a51-0c2b7f3d9e10", + "inner": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoicGxhdGZvcm0ifQ.a2V5.aXY.Y2lwaGVydGV4dA.dGFn", + "innerDigest": "DoW8NO1f4rVoq5sMs8mrBlvpXHo-U7jdfXilx_HzvyI", + "keys": [ + { + "label": "rsa-2048", + "algorithm": "RSA-OAEP-256", + "jwk": { + "kty": "RSA", + "n": "p2kQEhw9dp076z8aM5TR4TAa_XkDIw-Xw2GO-GWOFFgEIsL1VIwtdhuQRhWdGvd6LrmLlCRs6kz3RxJPTpJ8wAb-wrbxK9cLmJ-UJMdR4QYkdN8s9UqaB4ceJUnQU6DcJ1FWrjLkPyMKMGgfFGonvS_Jeqo7zayQiJELajkELtZpgpDsywrZbSVZvv0iYP5bpjZpYjTdsxrEVc4Np5L2R0rqeMvyS5Eu4R9Ib09ZDIqX_5s0YWRmHHsAKcXmN-iJFVKz9vKOWkE5iVwVmrghaUEdABBLlANbSWbtg53F3dEJrhVziz4VQHbv5YkyLza3XunWc18b2aqSIa-didQh4Q", + "e": "AQAB", + "d": "HCkAGwvFCv7H5Xpn3eVaqJZ-88Q3Ut58mNEAS6hJjgKAL5i7y80ImKVqT1-zXaXjV5i-cdzutTrdHYdm78CUW3jRwc8kIku6F6JAOS-OBlwSJdakqV4zKrD_0SXpdSfJ4JM-EW9eFYC_ZgUdtUFmDdzL92ZLSP2OEmrTkLqmiXoheOaHgvInk8bV2qsZdqvrLxzj5GojbIVb_5-CzmJrn1o4i6WfGpIQ1gECRHW84uxmY11Lcxq1Tt5Xr4G9EwEB5NB9vaUc1znkefQO_mMPp4_37zORAZotLZiekHonHU8WE5oEkYrAuzHPKvqnPtd7cCQV_4P3DrBLTnv5BLwoQQ", + "p": "6hq-G3iWJuDLrCDOLViAHCLJ2K21RUkQMTw2K2FAS4G4N1AI10Awo__orogJ4KR6ozjuicTXvRt7eq_GNIc0ucGvNeOBzYBhy0nFuALNleGtpQsHJxwYfdrN0qRPiNjsXwPohl8hi0joJD9sh6o93NymMeZPzxvAColEmE0rF58", + "q": "txFv-Znw7F9t49Roc7ENn9xox6okAuUxY8wLAkbx1LdRfqJNcfu-pu4sv6zAbFDPdhT8k_ABgQZ8lSG4zo-twFRTjJwbDXnbEmKvy4QtGTdUUPagXBTTHSicicFhAuIx3v3F0QmSo9ZuOtFbCQuA-YrSLTLpnssfDt549xn8Vn8", + "dp": "McQ1nclowiMPqSvgKKujsFeE6VckLfJ2SsEuEtK9xE9zRe7xsjCnJnYElPW-g87zczdrHkaGRmFNQquTSx9jCgouoRoYQgOExp6MNa4C3lX3gBp0DtBeNIMLNjhP4BudRCWkjMw0aVO6ZdpFzCFYvVb6zajUVobjsFm2B1qASqk", + "dq": "AzQ37HtoPwrQhotCJLw1i9W0s8HjjXVrbt60Vp7dPqbSs0-t4U_Rn2RNvjEM0Rh8-QkW_pPVwudVKNsFPABBvzr6l1xoEM1QKzs07m_qxiU0wZH_bn0i0MDUNIkA5KcGzmtMmgL74Qgwt7DQUhE0eamXUhkxA4l0irMUFOcMhos", + "qi": "lPBPvjwZzYq-fQWVb1Kb-RPcr5VVbJD6Lm_u2OL4ahkMJa3tFdoNormISDKYzpJ8c2wv_xpO980o2pVwgd9IcSM2dkqbm1vaduUjToA3PACOZLv14BuogjQThNlaczt3YC_CzC5JiX9m-PECfFH94zUkLwwNAurbCeZtRlK2ag4" + }, + "kid": "_FBIIs2D_wVdLliJ93PRe2Da0Ul_aqRXza6VHroBiIU", + "wrappedByNode": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiX0ZCSUlzMkRfd1ZkTGxpSjkzUFJlMkRhMFVsX2FxUlh6YTZWSHJvQmlJVSIsImN0eCI6ImhiLXNlY3JldC12MTp0ZWFtX2ZpeHR1cmU6NmYxZDNjMWUtNWI4YS00ZTZmLTlhNTEtMGMyYjdmM2Q5ZTEwIn0.EkMxha80QvplqXUQ0_C5y_ZJQGAzizYBeDg6-kg2R2UB0JPS0TDPkuGzVLehmUSWk4JaAv_wmIAvAIlGePldqZ1h3UVV9m190Q5-5eiZyLLfgs1Sk4ccUbWNwIvafC8KfcAtFmfF-NLlCxaE4zL2HAqGv_RkKufHRskgfD2bf2kM-8rt9yBL5zj9gk1PFkSxgsJTtk1Fcp7OKfrkK4vctNmVIFbvPyEZrs-frEJM3NJAHyAQJP28-6bzDmSTYdRmxRc-d5uuGZ5-VW5WkVjJg5oyvyGQm_YVpBhi67Rfrddif0gNGCahtbac4B8GJOEp6MdoSSdAphIXAMzoF0X2LQ.29_WDLi3SKkpMg-f.-c3Ol2gyxb4j32ztbpchiZGjYrE18vLgEffkwHGbHVDROjHJERu7IRzl0YZgnmapfesqKg8A0nv6W_9RoSGEGe4z3_oFp_fGh4MWZwsXV5qUvai1D8xP00VzScysU7TkpTDen5ipvA.RvO5OqZO5yfyID83M0dUcA", + "wrappedByPython": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiX0ZCSUlzMkRfd1ZkTGxpSjkzUFJlMkRhMFVsX2FxUlh6YTZWSHJvQmlJVSIsImN0eCI6ImhiLXNlY3JldC12MTp0ZWFtX2ZpeHR1cmU6NmYxZDNjMWUtNWI4YS00ZTZmLTlhNTEtMGMyYjdmM2Q5ZTEwIn0.gYBYMs-xdCmCdbMjMFqgxb3_kSuqfD6XwOUaL4Dqx5CNd_CGPELiKXl4nvDBDHiX59-_QF6c2WSgV-YTdXM1Il_mlRpNxOXKH06tAMGrNL_lf264JeJLT1pMO70ww13yud3Dr12EzEeSJwyM78o_aw8gZFt1oO8-OSfaGPlVE_PFt-OxRd1svu5kKleqyWLVJsoKfKzp2MTwry7AQyECdggiaZ7mrWHyEyvEGeCXMDtwGmqkFEA4L6TmdnEMTisVooYD2DqP3IkBjIJsjuAQyV0QUM5sM8Ol89a4nCVrkK3pHEV4ZLW5vIFc0SBH3miTF9UO8620q1TEuz1C5Natyg.NvN09cM9LkzeChW_.tqofTXuHuJ79Pmbc_8I2RFXR9OzMjOqbDykelb9M-3Qdk_vyBNurrMOSY8CjPt0rMlj6NB-hbuuMHPsTQf8MmK8RGFuIYiAcpe4HTKYaDYIZbY-u8r1BRxTLlxmuUwM-Tkmqc1jlAg.2XXEiA1Kqz1FvVbbOwTs4A" + }, + { + "label": "p-256", + "algorithm": "ECDH-ES+A256KW", + "jwk": { + "kty": "EC", + "x": "Zr2qtLIXe3AeGL7HmhVPsFD9EYUQfkqE4WcGMZlpUnc", + "y": "_2jmh34p1jmuI-S6N8aca7KtirrPwJjq4h_jRux2QOg", + "crv": "P-256", + "d": "p5ZqhGq8alcsDcgq_zIi_B9ExkF_1suosznWw3iLjCM" + }, + "kid": "4ttAqrEVmQ3gzrQXH9vYpX1V-MxiuMWBs_CYd64dBkY", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiI0dHRBcXJFVm1RM2d6clFYSDl2WXBYMVYtTXhpdU1XQnNfQ1lkNjRkQmtZIiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiUC0yNTYiLCJrdHkiOiJFQyIsIngiOiJNMTZvczU1LVpzcy01Skx6cHh6WmNHZE5ua2NGUTlpTVBkd29xRVpHSnJvIiwieSI6IlQyclJPRldvQnB6T2R3M2NxQUtRb3VXTnBsbmQtLUtuMkhwMWV6M3d3QjQifX0.EEV9pLdbb8-mTpcIjKnLNezz8Kbi_cn8_AeD9tX2JOWkAoxkLz3JVQ.LA_2FnRQTyrLhlkw.GQZbrdURYFJU4UmzFOz81RpDD5gCfFkkmyneGbkgZfzGbu6pJnbF9b7h7aQjX3LY9itnZ-KdPaAu4CYVoiK4cNUxuvhlBT5VRVbosA2YfYzxswSCPbqq5gPowJ_NrvMIIHga7OPpug._ISWNu1ZXorq8lkOJHh5_Q", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiI0dHRBcXJFVm1RM2d6clFYSDl2WXBYMVYtTXhpdU1XQnNfQ1lkNjRkQmtZIiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiUC0yNTYiLCJrdHkiOiJFQyIsIngiOiJLbkdvc2ppeDUwZnBsUlN3bXBhWC1ENEtLZzlPeThpRndPTUFQbVdJc0pRIiwieSI6IkdPT3hKb1RsU2Jaa0Q3X0lHRzhXZDFXWTlBSllwNklXTXp2UkthdF9TWjAifX0.4O3TphALVVj_f6G0_wwIsOsiRnKhZZoCTnJ9jbB3CN1UralrLwnRnw.9RV3HqOsSzUC6VU9.FNb9SU6PwuE4zmu2dZGE2Uk4tYYieeW7m9Prr44dKt_RDD03KAb1VOsp1PZaP1CEanmIeOBnPKv4KR7obozgMGs5_YgyXKetAYprqUD6WYw3gk2xupqhNBEJDmix_7_byxV5KnXcHg.5gNOeffAiSwhB7x4_ABJRg" + }, + { + "label": "p-521", + "algorithm": "ECDH-ES", + "jwk": { + "kty": "EC", + "x": "AHobEvicT4YKcVb_A-IAm3zFz9_InDY37yh_THSqQaARHLjAH9XgPd29oBGr3kOWncm4-E5BQ0iEcG7aKS7D-dwY", + "y": "ADB02ULFoCBdxqw4BpM3htPKEwynxvsWTFyAfNWmMCNoph7PStG8t9MK8OHmhG1yrNLTTELdox_QyUHCJx70rBw_", + "crv": "P-521", + "d": "AUYKj_0wfctv6AFU6EsH00rM69kaYgmIa_XtiOZZUBbm56K1RqaYWNUEccUI1U36n4LUhCZzUHDeXFT4DfbChgVx" + }, + "kid": "UIFrQul50aGcwaugYz50xcza4YZ6VOH3BBDypCL3454", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6IlVJRnJRdWw1MGFHY3dhdWdZejUweGN6YTRZWjZWT0gzQkJEeXBDTDM0NTQiLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJQLTUyMSIsImt0eSI6IkVDIiwieCI6IkFHYUpCZi04MC1MaWp6UDdvYWl6eUpZaVEwb0VaWlhyQ19JeFBjRG5LTGo2QVFJekRTWFNyb0wzamJlVS1sOEd5bElMX3RGUmU0QmxnTDZJYlhOZFdvN2UiLCJ5IjoiQUFHcC1obFhmY1o0MXpvU2dKaDIxcXBmVUN4SU5qYmE5eWVtU2VxZmVEQ2tjeHpHUXM5V0YtbEJ4QlphX0xkQUhtLXVaZDdUWG5zOHBzOUU2TzkxNVp3RCJ9fQ..BXEgBGzV9uKnB8X2.OfKKiTQLgVqIQ4v40R__Tz0Yk-wb7EOWG7OOg4Z88zWrWwAfi_YMktn24tJ-Eg5WD64x9fx9rUCwcX8o0t0SzuIbLEW8bGVVVlr5niPsZoaCYDLpQ156litd3r0Hf2gnFoQdeOPcww._1vT9N9rkXxKYjmxcn8dmw", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6IlVJRnJRdWw1MGFHY3dhdWdZejUweGN6YTRZWjZWT0gzQkJEeXBDTDM0NTQiLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJQLTUyMSIsImt0eSI6IkVDIiwieCI6IkFOZlBCUHRUUmo5RW5jNmdXUVc4SGZDQmFvRnZqNGVnVDhaVjRad0Nyc2pFVWc2c25LX2FYQTFkTXR4NTQ3MWoxQWU0ZWQwU1NaSlo3WmtwVGpQTjhxOHUiLCJ5IjoiQUZlMXZSTVhCWHRPSmVUTmpzR1RaN05tV0d2eWpvaVNsSHEyMTBJT0RLbGRWRThzUVBFWFJ3dmhLQmVvbEkxTi1qc3VlSmtVUXlheHgxVGFBODhBaG1rRyJ9fQ..JuMmlFpA1DyD_4_l.M0TbQp146nJRVIJQZ0sKqEsRpF4FYevWfYyS_Z2DTHsLs5GIsYEKJ4PUvYHBIHuJ1D7UrE4-otqYLGcQJW-uT_-OqSa6BIVlNAqBjTMnVVeUUBu3XV9xqDb68d7Xpj9MfrAw-zC7MA.fIF6VPqxhJCrA5MjPQ459w" + }, + { + "label": "x25519", + "algorithm": "ECDH-ES+A256KW", + "jwk": { + "crv": "X25519", + "d": "UIVv3o0M6-jv_pLf77pnaSR1HPXSMLe0k5UcYpukMVs", + "x": "cLzaeMuTZwtFbGJodc98KKvv7ShLfCB-yoav0HQaIQQ", + "kty": "OKP" + }, + "kid": "shputQF0o-yH6jz5npiZHcFvPB8oyC4fPBU8y8udGn8", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiJzaHB1dFFGMG8teUg2ano1bnBpWkhjRnZQQjhveUM0ZlBCVTh5OHVkR244IiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiWDI1NTE5Iiwia3R5IjoiT0tQIiwieCI6IkFma3g1VklfX2RicGdOY29feF9VTVVDMV8tUzVwU2NkRnJGZndZSlRCMWcifX0.VEcsB_DKjDKzudxxwyKNWpfGQmOnhmr8R22o-sIbQRV6U2AEXKd9aA.zeGhRuiZKphU5CmR.WpK2y2paHyLDYaHKdaI1k9KW4j4Wwc2TTRx9_bf1J0EKu7_u7QJhJeEWuAmIudZ05s2HIGAR6g48hgS56Qwxj-lYzjIlGqqzULeXw5mBp2yUyX99uFEFC_FUzpbKniSte66G3CD7ug.ta9TOCb_0A9SUVjKzCufLA", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiJzaHB1dFFGMG8teUg2ano1bnBpWkhjRnZQQjhveUM0ZlBCVTh5OHVkR244IiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiWDI1NTE5Iiwia3R5IjoiT0tQIiwieCI6IkFsZFlhdGJHU1ZVTXlEdHpiLVlvamRvMUZ1Mk90c09fQXQ4QkRoWUpTQkEifX0.evwJ-ewF8MS_PVouBBDMi10iHyi-Tg60z7O5kZPK47nbGzo1EWTblA.Mj3l-XzynRSue44w.4kZc9WY0vX8hACPwvVQvq0bFfQ9lxuNvE8Z366Z0r9IOPaFGxxuPmIojZAFCJ4LKYkAIuiMtH2AfydsnguGbrq8kcEgLyrLrowsG9viqpFm6U3Q6UWGAVlpED6OFqGm9EF168iwjew.QJ0baAoToXU4pz7tJZ2BRg" + }, + { + "label": "x448", + "algorithm": "ECDH-ES", + "jwk": { + "crv": "X448", + "d": "GJ0gpEJEC-COQUPfcl6UAuVDDrdQaxSwL43RtDh49v4_c_a0hSCCgmXpUce83PQbj9q-axJajbw", + "x": "pCb-B4PIc_VaYouhZTnXuA8YkBMvbdgP0QJ_b_JtCO6IV_hVO_2q9l5GNfDJXTLx8550xkd3X0A", + "kty": "OKP" + }, + "kid": "lxvyEWaOabx7FJbA5vbCwhvLMARQUlf8fq0lDCIkw7w", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6Imx4dnlFV2FPYWJ4N0ZKYkE1dmJDd2h2TE1BUlFVbGY4ZnEwbERDSWt3N3ciLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJYNDQ4Iiwia3R5IjoiT0tQIiwieCI6IktPT0lXS2tSQzVuQ1hXcWZ2Qzc3UzVhODRhaTB4Q1JibkZfVTI0WnZ6VWFmX3JIM2RDRHAwRUk5VXNvQ1lhWDl3M0w0alhvVUtCZyJ9fQ..SLdO9ul1cGuZ5CLx.TN3Hp5fEf4L33_blTzP8PUnf4ABBoFXPw-IThcA5fzUVTsNEfIjfIjbonNejuEPOBtkbrfs06oN1xljqoBllmV6bMsgQ4uFSMtMmLET49xz5h-PB-hkqzOKP-tSt2iy7sytGyVGqaQ.YmyQ3TgrHcCGRdOufvdbpg", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6Imx4dnlFV2FPYWJ4N0ZKYkE1dmJDd2h2TE1BUlFVbGY4ZnEwbERDSWt3N3ciLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJYNDQ4Iiwia3R5IjoiT0tQIiwieCI6ImRELXAtdDl0S0JQRC1aVkcwRlRVTEFXcjAxbU5PNnNQOWhYdE00MWVweVRycTZweEVLY0J3MjBkLW5Ha3kxdFBPbWxwV1NiVGV5NCJ9fQ..kWMdqtLyWFgWwsph.xdQOXYPg1zODw0BVVzQCNhxDBBdvjrK3LzJabgIuzUVTIJV_xMzI3ua-E65XZpNfElLmIqwaSldamDaI41TR_K8yT0BdtN_gR_fTyG2dJM29pohSK0sPZmuSMnAdpFopxQ8EdMcPMw.zI1rPy3AuMP0Uh-VHqsR0A" + } + ] +} diff --git a/tests/unit/customer-secrets.test.ts b/tests/unit/customer-secrets.test.ts index 76b957a..24e8754 100644 --- a/tests/unit/customer-secrets.test.ts +++ b/tests/unit/customer-secrets.test.ts @@ -1,7 +1,14 @@ import crypto from "crypto"; +import { readFileSync } from "fs"; +import path from "path"; import { describe, expect, expectTypeOf, test, vi } from "vitest"; import { HyperbrowserError } from "../../src/client"; -import { createCustomerKey, CustomerKey, secretEnvelopeDigest } from "../../src/customer-key"; +import { + createCustomerKey, + CustomerKey, + CustomerKeyAlgorithm, + secretEnvelopeDigest, +} from "../../src/customer-key"; import { SecretsSealer } from "../../src/secrets-envelope"; import { SecretsService } from "../../src/services/secrets"; import { VaultsService } from "../../src/services/vaults"; @@ -501,3 +508,25 @@ describe("customer-protected vaults", () => { expect(calls()).toEqual(["GET /vaults", `GET /vaults/${VAULT_ID}/wrapped`]); }); }); + +describe("customer key interop fixture", () => { + const fixture: typeof import("../fixtures/customer_key_interop.json") = JSON.parse( + readFileSync(path.join(__dirname, "../fixtures/customer_key_interop.json"), "utf8") + ); + + test("the inner envelope digest matches", () => { + expect(secretEnvelopeDigest(fixture.inner)).toBe(fixture.innerDigest); + }); + + test.each(fixture.keys)("$label unwraps what both SDKs wrapped", async (item) => { + const key = createCustomerKey(item.jwk as crypto.JsonWebKey, { + algorithm: item.algorithm as CustomerKeyAlgorithm, + }); + expect(key.kid).toBe(item.kid); + for (const wrapped of [item.wrappedByNode, item.wrappedByPython]) { + const header = JSON.parse(Buffer.from(wrapped.split(".")[0], "base64url").toString()); + expect(header).toMatchObject({ alg: item.algorithm, kid: item.kid, ctx: fixture.context }); + expect(await key.unwrap(wrapped)).toBe(fixture.inner); + } + }); +}); From bd9fb549afd0d65fa1246f528e5a9b13d7a09b98 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 21:54:46 +0000 Subject: [PATCH 6/6] Share the wrapping request and 1Password serializer, trim repeated docs Co-authored-by: Ninad Sinha --- src/sandbox/secret-references.ts | 24 ++++++++++++------------ src/services/credentials.ts | 6 ++---- src/services/secrets.ts | 23 +++++++++-------------- src/types/credential.ts | 6 +----- src/types/sandbox.ts | 12 +++--------- src/types/secret.ts | 11 +++-------- src/types/vault.ts | 8 +++----- 7 files changed, 33 insertions(+), 57 deletions(-) diff --git a/src/sandbox/secret-references.ts b/src/sandbox/secret-references.ts index f89461e..f677644 100644 --- a/src/sandbox/secret-references.ts +++ b/src/sandbox/secret-references.ts @@ -1,4 +1,5 @@ import { HyperbrowserError } from "../error"; +import { isPlainObject } from "../secrets-envelope"; import { SandboxOnePassword, SandboxSecrets, SandboxVaultSource } from "../types/sandbox"; const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; @@ -163,18 +164,17 @@ export const serializeVaultSource = ( * Check a 1Password source's token, the one member that can be a secret * reference; the API checks the rest. */ -export const serializeOnePasswordToken = ( - token: SandboxOnePassword["token"] -): WireOnePassword["token"] => - typeof token === "string" ? token : serializeSecretReference(token, "the 1Password token"); - -/** Serialize a 1Password source, checking its token. */ -export const serializeOnePassword = ( - onePassword: SandboxOnePassword | undefined -): WireOnePassword | undefined => - onePassword === undefined || onePassword === null || typeof onePassword !== "object" - ? onePassword - : { ...onePassword, token: serializeOnePasswordToken(onePassword.token) }; +export const serializeOnePassword = >( + onePassword: T | undefined +): (Omit & Pick) | undefined => { + if (!isPlainObject(onePassword)) return onePassword; + const { token } = onePassword; + return { + ...onePassword, + token: + typeof token === "string" ? token : serializeSecretReference(token, "the 1Password token"), + }; +}; /** An environment variable must come from either `env` or `secrets`, not both. */ export const assertNoEnvSecretOverlap = ( diff --git a/src/services/credentials.ts b/src/services/credentials.ts index aab48c5..a13c1ea 100644 --- a/src/services/credentials.ts +++ b/src/services/credentials.ts @@ -1,5 +1,5 @@ import { invalidRequest } from "../error"; -import { serializeOnePasswordToken } from "../sandbox/secret-references"; +import { serializeOnePassword } from "../sandbox/secret-references"; import { isPlainObject } from "../secrets-envelope"; import { CredentialFillResult, FillCredentialParams } from "../types/credential"; import { BaseService } from "./base"; @@ -43,9 +43,7 @@ export class CredentialsService extends BaseService { } // Preserve request members so the API can reject unknown or conflicting options. const { frameUrl, ...body } = params; - const onePassword = isPlainObject(body.onePassword) - ? { ...body.onePassword, token: serializeOnePasswordToken(body.onePassword.token) } - : body.onePassword; + const onePassword = serializeOnePassword(body.onePassword); return this.request( `/session/${encodeURIComponent(sessionId)}/credentials/fill`, { diff --git a/src/services/secrets.ts b/src/services/secrets.ts index 74aa6fa..15f13f2 100644 --- a/src/services/secrets.ts +++ b/src/services/secrets.ts @@ -323,13 +323,7 @@ export class SecretsService extends BaseService { const inner = await unwrapVersion(wrapped, from, label); const envelope = await to.wrap(inner, detail.encryptionContext); rewrapped.push( - await this.request( - `${secretPath(detail.id)}/versions/${version}/wrapping`, - { - method: "PUT", - body: JSON.stringify({ envelope, innerDigest: wrapped.innerDigest }), - } - ) + await this.putWrapping(detail.id, version, { envelope, innerDigest: wrapped.innerDigest }) ); } return rewrapped; @@ -358,13 +352,7 @@ export class SecretsService extends BaseService { } try { const { id } = await this.resolve(secret); - return await this.request( - `${secretPath(id)}/versions/${version}/wrapping`, - { - method: "PUT", - body: JSON.stringify({ envelope, innerDigest }), - } - ); + return await this.putWrapping(id, version, { envelope, innerDigest }); } catch (error) { return rethrow( error, @@ -443,6 +431,13 @@ export class SecretsService extends BaseService { return this.request(`${secretPath(id)}/versions/${version}/wrapped`); } + private putWrapping(id: string, version: number, body: ReplaceSecretVersionWrappingParams) { + return this.request(`${secretPath(id)}/versions/${version}/wrapping`, { + method: "PUT", + body: JSON.stringify(body), + }); + } + private async resolve(secret: string): Promise { return (await this.lookup(secret)).secret; } diff --git a/src/types/credential.ts b/src/types/credential.ts index 6b1be58..a19862e 100644 --- a/src/types/credential.ts +++ b/src/types/credential.ts @@ -60,11 +60,7 @@ export interface CredentialFillField { * the request names the origins it may be typed on. */ export interface CredentialFillOnePassword { - /** - * The `op_token` secret attached to the session: its name (its latest - * version is used), or a reference pinning a version. A - * customer-protected token is passed as `secrets.unwrap()` returns it. - */ + /** The `op_token` secret attached to the session: its name (its latest version is used), or a reference. */ token: string | SandboxStoredSecretReference; /** The 1Password vault's name or ID. */ vault: string; diff --git a/src/types/sandbox.ts b/src/types/sandbox.ts index f84de40..82a747f 100644 --- a/src/types/sandbox.ts +++ b/src/types/sandbox.ts @@ -117,11 +117,7 @@ export type SandboxVaultSource = string | VaultReference; * starts. Nothing about it is stored. */ export interface SandboxOnePassword { - /** - * The `op_token` secret: its name (its latest version is used), or a - * reference pinning a version. A customer-protected token is passed as - * `secrets.unwrap()` returns it. - */ + /** The `op_token` secret: its name (its latest version is used), or a reference. */ token: string | SandboxStoredSecretReference; /** The 1Password vault's name or ID. */ vault: string; @@ -227,8 +223,7 @@ export type CreateSandboxParams = /** * A vault whose entries become the startup command's environment * variables; `secrets` is merged over it and wins on a clash. Same - * requirements as `secrets`. Pass a vault with customer-protected - * entries as `vaults.unwrap()` returns it. + * requirements as `secrets`. */ vault?: SandboxVaultSource; /** 1Password fields for the startup command. Same requirements as `secrets`. */ @@ -625,8 +620,7 @@ export interface SandboxExecParams { * A vault whose entries become environment variables of this process, * delivered like `secrets`. `secrets` is merged over it and wins on a * clash; `env` can't set a variable either of them sets. Together they hold - * at most 32 variables. Pass a vault with customer-protected entries as - * `vaults.unwrap()` returns it. + * at most 32 variables. */ vault?: SandboxVaultSource; /** diff --git a/src/types/secret.ts b/src/types/secret.ts index 074bf8b..4363081 100644 --- a/src/types/secret.ts +++ b/src/types/secret.ts @@ -4,14 +4,9 @@ import type { CustomerKey } from "../customer-key"; export type SecretValue = string | Uint8Array; /** - * Who can open a secret's values, fixed at creation: - * - `"platform"`: each version is encrypted to the platform's key. - * - `"customer"`: each version is also wrapped with the customer's own key - * (see `CustomerKey`), so the platform stores nothing it can decrypt - * alone. Each use passes the envelope the customer unwrapped, pinned to - * its version; see `secrets.unwrap()` and `vaults.unwrap()`. - * Customer-protected secrets can't be filled into browser pages - * themselves, though an `op_token` one can sign 1Password fills. + * Fixed at creation. `"customer"` secrets are also wrapped with your own + * `CustomerKey`, and each use passes what `secrets.unwrap()` or + * `vaults.unwrap()` returns; they can't be filled into browser pages. */ export type SecretProtection = "platform" | "customer"; diff --git a/src/types/vault.ts b/src/types/vault.ts index f27a8e1..6740777 100644 --- a/src/types/vault.ts +++ b/src/types/vault.ts @@ -36,11 +36,9 @@ export interface VaultUnwrappedEntry { } /** - * A vault with the envelopes of its customer-protected entries, as - * `vaults.unwrap()` returns it: pass it as a sandbox's or process's `vault`. - * The envelopes match the entries as they were unwrapped; if an entry changes - * since, uses fail with `SECRET_VAULT_CHANGED` and the vault must be - * unwrapped again. Anyone holding it can use those versions. + * A vault with its customer-protected entries unwrapped, as `vaults.unwrap()` + * returns it, for a sandbox's or process's `vault`. Anyone holding it can use + * those versions. */ export interface VaultReference { name: string;