Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(vaults): add browser crypto library (#674)

Call White7c085f740fe1
diff --git a/docs/plans/avault-custody-core.md b/docs/plans/avault-custody-core.md
index 81ade0c71..ed4a9c67c 100644
--- a/docs/plans/avault-custody-core.md
+++ b/docs/plans/avault-custody-core.md
@@ -536,14 +536,35 @@ These are starting recommendations, not frozen choices — items #2 (envelope) a
| Verb | Input | Output | Purpose |
|---|---|---|---|
-| `pubkey` | — | X25519 public key + fingerprint | the browser fetches this before sealing a blind box (protected tier must pin / attest it) |
+| `pubkey` | — | X25519 public key + fingerprint | one-shot `pubkey` supports blind-box create; protected DEK release uses the resident agent's ephemeral `pubkey` frame |
| `seal` | blind box (the value) + name/scheme | envelope `{ciphertext, nonce, wrap_meta}` | standard-tier create: open box → wrap DEK under master → return ciphertext (never plaintext) |
-| `deliver` | envelope + mode (`run` / `fetch` / `inject`) + *optional* DEK blind box | exit code / response body | decrypt and deliver. No DEK ⇒ standard tier (master key); with DEK ⇒ protected tier (browser-released DEK) |
-| `sign` | key envelope + digest/tx + *optional* DEK blind box | signature (public) | standard-tier signing (secp256k1); the private key never leaves `avault` |
+| `deliver` | envelope + mode (`run` / `fetch` / `inject`) | exit code / response body | one-shot standard-tier delivery uses the master key; protected delivery uses resident-agent grants, never inline DEK boxes |
+| `sign` | key envelope + digest/tx | signature (public) | one-shot standard-tier signing; protected signing uses resident-agent grants or browser-local signing |
| `key export` / `key import` | passphrase (stdin) | encrypted backup / ok | back up, migrate, restore the master key |
The resident agent (P2) adds `grant` / `release`: cache a scope's DEK-set for a TTL so repeated uses in-window skip re-unlock. Standard-tier signing of an ETH key is `sign`; protected-tier ETH signing happens entirely in the browser and never reaches this interface.
+### Blind-box AAD contract
+
+Browser blind boxes use HPKE Base mode with DHKEM-X25519-HKDF-SHA256, HKDF-SHA256, AES-256-GCM. The JSON scheme is `hpke-x25519-hkdfsha256-aes256gcm-v1`; HPKE `info` is `avault:blind-box:v1`. The HPKE AAD is operation-bound bytes:
+
+```text
+"avault:blind-box:aad:v1"
+ || field(purpose)
+ || field(name)
+ || field("machine-aesgcm-v1")
+ || field(0x01)
+ || field(scope_type or "")
+ || field(scope_ref or "")
+ || field(sign_scheme or "")
+ || field(digest or "")
+ || field(approval_nonce or "")
+ || field(approval_expires_at_unix_be or "")
+ || field(operation_hash or "")
+```
+
+`field(x)` is `uint32_be(len(x)) || x`; strings are UTF-8; signing digests and operation hashes are raw 32-byte values. Protected DEK blind boxes require approval metadata and are accepted only by the resident agent; one-shot CLI paths reject inline `dek_blindbox` / `approval` fields. Agent grants authenticate `scope_type` and `scope_ref` directly in AAD and bind the grant TTL in `operation_hash`: agent delivery uses `"agent-deliver"`, name, `ttl_secs_u64_be`; agent signing uses `"agent-sign"`, scheme, raw digest, `ttl_secs_u64_be`. The shared byte vectors live in `tests/vectors/p2_core_crypto.json` in the avault repo and are mirrored into the browser tests.
+
### Transport
Two modes, the same integration touchpoints as `askill`. **Both channels carry only names, blind boxes, ciphertext, and results — never plaintext or keys.**
diff --git a/ui/package-lock.json b/ui/package-lock.json
index f7a9521eb..8194d14b0 100644
--- a/ui/package-lock.json
+++ b/ui/package-lock.json
@@ -9,7 +9,10 @@
"version": "0.0.0",
"dependencies": {
"@codemirror/language-data": "^6.5.2",
+ "@hpke/core": "^1.9.0",
+ "@hpke/dhkem-x25519": "^1.8.0",
"@lexical/react": "^0.45.0",
+ "@noble/curves": "^2.2.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
@@ -26,6 +29,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"framer-motion": "^12.26.2",
+ "hash-wasm": "^4.12.0",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
"lexical": "^0.45.0",
@@ -61,7 +65,8 @@
"tailwindcss": "^4.1.18",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
- "vite": "^8.0.16"
+ "vite": "^8.0.16",
+ "vitest": "^4.1.9"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
@@ -989,6 +994,39 @@
"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
"license": "MIT"
},
+ "node_modules/@hpke/common": {
+ "version": "1.10.1",
+ "resolved": "https://registry.npmjs.org/@hpke/common/-/common-1.10.1.tgz",
+ "integrity": "sha512-moJwhmtLtuxiUzzNp1jpfBfx8yefKoO9D/RCR9dmwrnc7qjJqId1rEtQz+lSlU5cabX8daToMSx/7HayXOiaFw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/@hpke/core": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/@hpke/core/-/core-1.9.0.tgz",
+ "integrity": "sha512-pFxWl1nNJeQCSUFs7+GAblHvXBCjn9EPN65vdKlYQil2aURaRxfGMO6vBKGqm1YHTKwiAxJQNEI70PbSowMP9Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@hpke/common": "^1.10.0"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "node_modules/@hpke/dhkem-x25519": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/@hpke/dhkem-x25519/-/dhkem-x25519-1.8.0.tgz",
+ "integrity": "sha512-S1MWWkAfu+TFxySgv5+2P3O4Mx/jk7BsoplzQaA1s3sfUJVJ2UsZsSzSsMc+FXJumLXncoJFlO6mK6mDGspfmA==",
+ "license": "MIT",
+ "dependencies": {
+ "@hpke/common": "^1.10.0"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
"node_modules/@humanfs/core": {
"version": "0.19.1",
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz",
@@ -1590,6 +1628,33 @@
"@emnapi/runtime": "^1.7.1"
}
},
+ "node_modules/@noble/curves": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz",
+ "integrity": "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@noble/hashes": "2.2.0"
+ },
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
+ "node_modules/@noble/hashes": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz",
+ "integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.133.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.133.0.tgz",
@@ -2619,6 +2684,13 @@
"integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",
"license": "MIT"
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@tailwindcss/node": {
"version": "4.1.18",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",
@@ -2961,6 +3033,17 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
"node_modules/@types/debug": {
"version": "4.1.13",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",
@@ -2970,6 +3053,13 @@
"@types/ms": "*"
}
},
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -3435,6 +3525,119 @@
}
}
},
+ "node_modules/@vitest/expect": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.9.tgz",
+ "integrity": "sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.9",
+ "@vitest/utils": "4.1.9",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.9.tgz",
+ "integrity": "sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.9",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.9.tgz",
+ "integrity": "sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.9.tgz",
+ "integrity": "sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.9",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.9.tgz",
+ "integrity": "sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.9",
+ "@vitest/utils": "4.1.9",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.9.tgz",
+ "integrity": "sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.9.tgz",
+ "integrity": "sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.9",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
"node_modules/@xterm/addon-fit": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
@@ -3543,6 +3746,16 @@
"node": ">=10"
}
},
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/autoprefixer": {
"version": "10.4.23",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz",
@@ -3693,6 +3906,16 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -3982,6 +4205,13 @@
"node": ">=10.13.0"
}
},
+ "node_modules/es-module-lexer": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz",
+ "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -4189,6 +4419,16 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
"node_modules/esutils": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
@@ -4199,6 +4439,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/extend": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
@@ -4413,6 +4663,12 @@
"node": ">=8"
}
},
+ "node_modules/hash-wasm": {
+ "version": "4.12.0",
+ "resolved": "https://registry.npmjs.org/hash-wasm/-/hash-wasm-4.12.0.tgz",
+ "integrity": "sha512-+/2B2rYLb48I/evdOIhP+K/DD2ca2fgBjp6O+GBEnCDk2e4rpeXIK8GvIyRPjTezgmWn9gmKwkQjjx6BtqDHVQ==",
+ "license": "MIT"
+ },
"node_modules/hast-util-to-html": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
@@ -6106,6 +6362,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/obug": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.3.tgz",
+ "integrity": "sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/oniguruma-parser": {
"version": "0.12.2",
"resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz",
@@ -6237,6 +6507,13 @@
"node": ">=8"
}
},
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6736,6 +7013,13 @@
"node": ">=20"
}
},
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -6756,6 +7040,20 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz",
+ "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/stringify-entities": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
@@ -6857,6 +7155,23 @@
"url": "https://opencollective.com/webpack"
}
},
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
+ "integrity": "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -6874,6 +7189,16 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tinyrainbow": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/trim-lines": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
@@ -7527,6 +7852,96 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/vitest": {
+ "version": "4.1.9",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.9.tgz",
+ "integrity": "sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.9",
+ "@vitest/mocker": "4.1.9",
+ "@vitest/pretty-format": "4.1.9",
+ "@vitest/runner": "4.1.9",
+ "@vitest/snapshot": "4.1.9",
+ "@vitest/spy": "4.1.9",
+ "@vitest/utils": "4.1.9",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.9",
+ "@vitest/browser-preview": "4.1.9",
+ "@vitest/browser-webdriverio": "4.1.9",
+ "@vitest/coverage-istanbul": "4.1.9",
+ "@vitest/coverage-v8": "4.1.9",
+ "@vitest/ui": "4.1.9",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
"node_modules/void-elements": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
@@ -7558,6 +7973,23 @@
"node": ">= 8"
}
},
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
diff --git a/ui/package.json b/ui/package.json
index 81697f5b7..a8845de72 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -11,11 +11,15 @@
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview",
+ "test:crypto": "vitest run src/lib/vaultCrypto.test.ts",
"validate:theme": "node scripts/validate-theme.mjs"
},
"dependencies": {
"@codemirror/language-data": "^6.5.2",
+ "@hpke/core": "^1.9.0",
+ "@hpke/dhkem-x25519": "^1.8.0",
"@lexical/react": "^0.45.0",
+ "@noble/curves": "^2.2.0",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-popover": "^1.1.15",
@@ -32,6 +36,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"framer-motion": "^12.26.2",
+ "hash-wasm": "^4.12.0",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
"lexical": "^0.45.0",
@@ -67,6 +72,7 @@
"tailwindcss": "^4.1.18",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
- "vite": "^8.0.16"
+ "vite": "^8.0.16",
+ "vitest": "^4.1.9"
}
}
diff --git a/ui/src/lib/__fixtures__/p2_core_crypto.json b/ui/src/lib/__fixtures__/p2_core_crypto.json
new file mode 100644
index 000000000..d5faad0c5
--- /dev/null
+++ b/ui/src/lib/__fixtures__/p2_core_crypto.json
@@ -0,0 +1,108 @@
+{
+ "blind_box": {
+ "scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1",
+ "hpke_info_utf8": "avault:blind-box:v1",
+ "master_key_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "public_key": "gvhYRR/emWVthJ2XlGcbHvSN1QlnHYTQTWGKKQz9Zjs=",
+ "fingerprint": "0cd6109d66dd3a5e36f072b67c7f77e00b7cf6e10bd7e574681b0af0ac8ae4b0",
+ "rng_seed_hex": "4242424242424242424242424242424242424242424242424242424242424242",
+ "plaintext_hex": "626c696e6420736563726574",
+ "box": {
+ "scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1",
+ "enc": "y5JxBydhfDn3qZTxJtkiArzKIllWj625u+9lp54ATSM=",
+ "ct": "52ffaaYq51gf/85kI0O34uvfiHbLRwiOaLOBcQ=="
+ },
+ "aad_domain_utf8": "avault:blind-box:aad:v1",
+ "context": {
+ "purpose": "seal",
+ "name": "BLIND_SECRET",
+ "scheme": "machine-aesgcm-v1",
+ "version": 1
+ },
+ "aad_hex": "617661756c743a626c696e642d626f783a6161643a7631000000047365616c0000000c424c494e445f534543524554000000116d616368696e652d61657367636d2d7631000000010100000000000000000000000000000000000000000000000000000000"
+ },
+ "blind_box_aad_examples": {
+ "domain_utf8": "avault:blind-box:aad:v1",
+ "field_encoding": "uint32_be(len) || bytes",
+ "wrap_scheme": "machine-aesgcm-v1",
+ "version": 1,
+ "digest_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "cases": [
+ {
+ "purpose": "seal",
+ "name": "BLIND_SECRET",
+ "scope_type": "",
+ "scope_ref": "",
+ "sign_scheme": "",
+ "digest_hex": "",
+ "approval_nonce_hex": "",
+ "approval_expires_at_unix": null,
+ "operation_hash_hex": "",
+ "aad_hex": "617661756c743a626c696e642d626f783a6161643a7631000000047365616c0000000c424c494e445f534543524554000000116d616368696e652d61657367636d2d7631000000010100000000000000000000000000000000000000000000000000000000"
+ },
+ {
+ "purpose": "agent-deliver",
+ "name": "OPENAI_API_KEY",
+ "scope_type": "session",
+ "scope_ref": "ses_123",
+ "sign_scheme": "",
+ "digest_hex": "",
+ "approval_nonce_hex": "0102030405060708090a0b0c0d0e0f10",
+ "approval_expires_at_unix": 4102444800,
+ "operation_hash_hex": "1dee5d24a4cf46e0c9d84ab9383b239a96a78f2bbc3694be5ef9f6ccd1c71358",
+ "aad_hex": "617661756c743a626c696e642d626f783a6161643a76310000000d6167656e742d64656c697665720000000e4f50454e41495f4150495f4b4559000000116d616368696e652d61657367636d2d763100000001010000000773657373696f6e000000077365735f3132330000000000000000000000100102030405060708090a0b0c0d0e0f100000000800000000f4865700000000201dee5d24a4cf46e0c9d84ab9383b239a96a78f2bbc3694be5ef9f6ccd1c71358",
+ "ttl_secs": 300,
+ "operation_hash_kind": "agent-deliver",
+ "operation_hash_fields_hex": [
+ "6167656e742d64656c69766572",
+ "4f50454e41495f4150495f4b4559",
+ "000000000000012c"
+ ]
+ },
+ {
+ "purpose": "agent-sign",
+ "name": "ETH_SIGNING_KEY",
+ "scope_type": "session",
+ "scope_ref": "ses_123",
+ "sign_scheme": "ecdsa-secp256k1-recoverable",
+ "digest_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "approval_nonce_hex": "0102030405060708090a0b0c0d0e0f10",
+ "approval_expires_at_unix": 4102444800,
+ "operation_hash_hex": "32897201cc2e18d2e0ada45a310b1f52bcbb3f73bc7d15c7ea685859bf30edfe",
+ "aad_hex": "617661756c743a626c696e642d626f783a6161643a76310000000a6167656e742d7369676e0000000f4554485f5349474e494e475f4b4559000000116d616368696e652d61657367636d2d763100000001010000000773657373696f6e000000077365735f3132330000001b65636473612d736563703235366b312d7265636f76657261626c6500000020000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f000000100102030405060708090a0b0c0d0e0f100000000800000000f48657000000002032897201cc2e18d2e0ada45a310b1f52bcbb3f73bc7d15c7ea685859bf30edfe",
+ "ttl_secs": 300,
+ "operation_hash_kind": "agent-sign",
+ "operation_hash_fields_hex": [
+ "6167656e742d7369676e",
+ "65636473612d736563703235366b312d7265636f76657261626c65",
+ "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "000000000000012c"
+ ]
+ }
+ ],
+ "approval_nonce_hex": "0102030405060708090a0b0c0d0e0f10",
+ "approval_expires_at_unix": 4102444800
+ },
+ "signing": {
+ "private_key_hex": "4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318",
+ "digest_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
+ "schnorr_aux_rand_hex": "0000000000000000000000000000000000000000000000000000000000000000",
+ "schemes": [
+ {
+ "scheme": "ecdsa-secp256k1-recoverable",
+ "signature_hex": "4ca3aca3a41bc1ca96d67707e525ac6bd77ddc197a34b4c020be1ee636e29617199556ded3234058daafff2bc3153da60d402d0c71389a11a790b9f1a5862e80",
+ "recovery_id": 0
+ },
+ {
+ "scheme": "ecdsa-secp256k1-der",
+ "signature_hex": "304402204ca3aca3a41bc1ca96d67707e525ac6bd77ddc197a34b4c020be1ee636e296170220199556ded3234058daafff2bc3153da60d402d0c71389a11a790b9f1a5862e80",
+ "recovery_id": null
+ },
+ {
+ "scheme": "schnorr-secp256k1-bip340",
+ "signature_hex": "931a3386e9ec69fe1471ba85933640948c0296a79ce2d3801ad5a4d9353550aeb0a5e80358b68088bda70b46e6b77a640c1216826f96292e5799ba2bb7bf1342",
+ "recovery_id": null
+ }
+ ]
+ }
+}
diff --git a/ui/src/lib/vaultCrypto.test.ts b/ui/src/lib/vaultCrypto.test.ts
new file mode 100644
index 000000000..16b1c8736
--- /dev/null
+++ b/ui/src/lib/vaultCrypto.test.ts
@@ -0,0 +1,496 @@
+import { describe, expect, it } from 'vitest';
+import { Aes256Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
+import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
+import { scrypt } from 'hash-wasm';
+
+import vectors from './__fixtures__/p2_core_crypto.json';
+import {
+ BLIND_BOX_AAD_DOMAIN,
+ BLIND_BOX_SCHEME,
+ addPasswordCopy,
+ avaultPublicKeyFingerprint,
+ base64ToBytes,
+ blindBoxAad,
+ blindBoxAadHex,
+ blindBoxAgentDeliverOperationHash,
+ blindBoxAgentSignOperationHash,
+ blindBoxOperationHash,
+ buildWrapMeta,
+ bytesToBase64,
+ bytesFromHex,
+ bytesToHexString,
+ derivePasskeyKek,
+ newVmk,
+ passkeyPrfSaltEntries,
+ passkeyPrfSalts,
+ protectedDekReleaseBlindBoxContext,
+ protectedRecordAadHex,
+ releaseProtectedDek,
+ sealBlindBox,
+ sealProtected,
+ signDigest,
+ SIGN_SCHEME_ECDSA_SECP256K1_DER,
+ SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE,
+ SIGN_SCHEME_SCHNORR_SECP256K1_BIP340,
+ standardCreateBlindBoxContext,
+ unwrapProtectedDek,
+ unwrapVmk,
+ WRAP_META_VERSION,
+ WRAP_SCHEME,
+ webAuthnPrfExtensionInput,
+ type SignatureScheme,
+ type BlindBoxContext,
+} from './vaultCrypto';
+
+type P2Vectors = typeof vectors;
+
+const p2 = vectors as P2Vectors;
+const encoder = new TextEncoder();
+const vectorBlindBoxName = p2.blind_box.context.name;
+
+function arrayBuffer(bytes: Uint8Array): ArrayBuffer {
+ const out = new ArrayBuffer(bytes.byteLength);
+ new Uint8Array(out).set(bytes);
+ return out;
+}
+
+async function hkdfSha256(ikm: Uint8Array, salt: string, info: string, length: number): Promise<Uint8Array> {
+ const key = await crypto.subtle.importKey('raw', arrayBuffer(ikm), 'HKDF', false, ['deriveBits']);
+ return new Uint8Array(
+ await crypto.subtle.deriveBits(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: encoder.encode(salt),
+ info: encoder.encode(info),
+ },
+ key,
+ length * 8,
+ ),
+ );
+}
+
+async function aesgcmEncryptForTest(key: Uint8Array, nonce: Uint8Array, plaintext: Uint8Array): Promise<Uint8Array> {
+ const cryptoKey = await crypto.subtle.importKey('raw', arrayBuffer(key), 'AES-GCM', false, ['encrypt']);
+ return new Uint8Array(
+ await crypto.subtle.encrypt(
+ {
+ name: 'AES-GCM',
+ iv: arrayBuffer(nonce),
+ },
+ cryptoKey,
+ arrayBuffer(plaintext),
+ ),
+ );
+}
+
+async function malformedScryptVmkCopy(password: string, plaintext: Uint8Array) {
+ const salt = new Uint8Array(16).fill(0xa5);
+ const nonce = new Uint8Array(12).fill(0x5a);
+ const kek = (await scrypt({
+ password: encoder.encode(password),
+ salt,
+ costFactor: 2 ** 15,
+ blockSize: 8,
+ parallelism: 1,
+ hashLength: 32,
+ outputType: 'binary',
+ })) as Uint8Array;
+ const wrapped = await aesgcmEncryptForTest(kek, nonce, plaintext);
+ return {
+ kind: 'password',
+ kdf: 'scrypt',
+ n: 2 ** 15,
+ r: 8,
+ p: 1,
+ salt: bytesToBase64(salt),
+ nonce: bytesToBase64(nonce),
+ wrapped: bytesToBase64(wrapped),
+ };
+}
+
+async function avaultVectorReceiverKey(): Promise<CryptoKeyPair> {
+ const suite = new CipherSuite({
+ kem: new DhkemX25519HkdfSha256(),
+ kdf: new HkdfSha256(),
+ aead: new Aes256Gcm(),
+ });
+ const ikm = await hkdfSha256(
+ bytesFromHex(p2.blind_box.master_key_hex),
+ 'avault:blind-box:receiver-salt:v1',
+ 'avault:blind-box:receiver-x25519:v1',
+ 32,
+ );
+ return suite.kem.deriveKeyPair(ikm);
+}
+
+async function openBlindBox(box: { enc: string; ct: string }, aad: Uint8Array): Promise<Uint8Array> {
+ const suite = new CipherSuite({
+ kem: new DhkemX25519HkdfSha256(),
+ kdf: new HkdfSha256(),
+ aead: new Aes256Gcm(),
+ });
+ return new Uint8Array(
+ await suite.open(
+ {
+ recipientKey: (await avaultVectorReceiverKey()).privateKey,
+ enc: base64ToBytes(box.enc),
+ info: encoder.encode(p2.blind_box.hpke_info_utf8),
+ },
+ base64ToBytes(box.ct),
+ aad,
+ ),
+ );
+}
+
+function approvalFromVector(vector: (typeof p2.blind_box_aad_examples.cases)[number]) {
+ return {
+ nonce: bytesFromHex(vector.approval_nonce_hex),
+ expiresAtUnix: vector.approval_expires_at_unix ?? 0,
+ };
+}
+
+async function blindBoxContextFromVector(vector: (typeof p2.blind_box_aad_examples.cases)[number]): Promise<BlindBoxContext> {
+ switch (vector.purpose) {
+ case 'seal':
+ return standardCreateBlindBoxContext(vector.name);
+ case 'agent-deliver':
+ return await protectedDekReleaseBlindBoxContext(vector.name, {
+ kind: 'agent-deliver',
+ scopeType: vector.scope_type,
+ scopeRef: vector.scope_ref,
+ ttlSecs: vector.ttl_secs,
+ approval: approvalFromVector(vector),
+ operationHash: vector.operation_hash_hex,
+ });
+ case 'agent-sign':
+ return await protectedDekReleaseBlindBoxContext(vector.name, {
+ kind: 'agent-sign',
+ scopeType: vector.scope_type,
+ scopeRef: vector.scope_ref,
+ signatureScheme: vector.sign_scheme as SignatureScheme,
+ digest: vector.digest_hex,
+ ttlSecs: vector.ttl_secs,
+ approval: approvalFromVector(vector),
+ operationHash: vector.operation_hash_hex,
+ });
+ default:
+ throw new Error(`unexpected blind-box AAD vector purpose: ${vector.purpose}`);
+ }
+}
+
+describe('vaultCrypto signing vectors', () => {
+ it('matches avault secp256k1 signatures byte-for-byte', () => {
+ for (const vector of p2.signing.schemes) {
+ const scheme = vector.scheme as SignatureScheme;
+ const result = signDigest(p2.signing.private_key_hex, p2.signing.digest_hex, scheme, {
+ schnorrAuxRand:
+ scheme === SIGN_SCHEME_SCHNORR_SECP256K1_BIP340 ? p2.signing.schnorr_aux_rand_hex : undefined,
+ });
+
+ expect(result.signature).toBe(vector.signature_hex);
+ expect(result.recovery_id).toBe(vector.recovery_id);
+ }
+ });
+
+ it('keeps the ECDSA recoverable signature as r||s plus recovery id', () => {
+ const result = signDigest(
+ p2.signing.private_key_hex,
+ p2.signing.digest_hex,
+ SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE,
+ );
+
+ expect(result.signature).toHaveLength(128);
+ expect(result.recovery_id).toBe(0);
+ });
+
+ it('returns DER and BIP340 encodings for their wire schemes', () => {
+ const der = signDigest(p2.signing.private_key_hex, p2.signing.digest_hex, SIGN_SCHEME_ECDSA_SECP256K1_DER);
+ const schnorr = signDigest(
+ p2.signing.private_key_hex,
+ p2.signing.digest_hex,
+ SIGN_SCHEME_SCHNORR_SECP256K1_BIP340,
+ { schnorrAuxRand: p2.signing.schnorr_aux_rand_hex },
+ );
+
+ expect(der.signature.startsWith('30')).toBe(true);
+ expect(schnorr.signature).toHaveLength(128);
+ expect(der.recovery_id).toBeNull();
+ expect(schnorr.recovery_id).toBeNull();
+ });
+});
+
+describe('vaultCrypto blind boxes', () => {
+ it('matches all shared avault blind-box AAD examples byte-for-byte', async () => {
+ expect(p2.blind_box.aad_domain_utf8).toBe(BLIND_BOX_AAD_DOMAIN);
+ expect(p2.blind_box_aad_examples.wrap_scheme).toBe(WRAP_SCHEME);
+ expect(p2.blind_box_aad_examples.version).toBe(WRAP_META_VERSION);
+ for (const vector of p2.blind_box_aad_examples.cases) {
+ expect(blindBoxAadHex(await blindBoxContextFromVector(vector))).toBe(vector.aad_hex);
+ }
+ });
+
+ it('derives shared operation hash examples from length-prefixed fields', async () => {
+ const agentDeliver = p2.blind_box_aad_examples.cases.find((vector) => vector.purpose === 'agent-deliver');
+ const agentSign = p2.blind_box_aad_examples.cases.find((vector) => vector.purpose === 'agent-sign');
+ if (!agentDeliver || !agentSign) {
+ throw new Error('missing shared operation-hash examples');
+ }
+
+ for (const vector of p2.blind_box_aad_examples.cases) {
+ if (!vector.operation_hash_hex || !vector.operation_hash_fields_hex) {
+ continue;
+ }
+ await expect(
+ blindBoxOperationHash(vector.operation_hash_fields_hex.map(bytesFromHex)).then(bytesToHexString),
+ ).resolves.toBe(vector.operation_hash_hex);
+ }
+ await expect(
+ blindBoxAgentDeliverOperationHash(agentDeliver.name, agentDeliver.ttl_secs).then(bytesToHexString),
+ ).resolves.toBe(agentDeliver.operation_hash_hex);
+ await expect(
+ blindBoxAgentSignOperationHash(
+ agentSign.sign_scheme as SignatureScheme,
+ agentSign.digest_hex,
+ agentSign.ttl_secs,
+ ).then(bytesToHexString),
+ ).resolves.toBe(agentSign.operation_hash_hex);
+ });
+
+ it('opens the shared avault blind-box vector with the recorded operation-context AAD', async () => {
+ const context = standardCreateBlindBoxContext(p2.blind_box.context.name);
+ expect(blindBoxAadHex(context)).toBe(p2.blind_box.aad_hex);
+ await expect(openBlindBox(p2.blind_box.box, blindBoxAad(context))).resolves.toEqual(
+ bytesFromHex(p2.blind_box.plaintext_hex),
+ );
+ });
+
+ it('seals to the avault public key with the operation-context AAD', async () => {
+ const plaintext = encoder.encode('blind secret');
+ const context = standardCreateBlindBoxContext(vectorBlindBoxName);
+ const box = await sealBlindBox(base64ToBytes(bytesToBase64(plaintext)), {
+ public_key: p2.blind_box.public_key,
+ fingerprint: p2.blind_box.fingerprint,
+ }, context);
+
+ expect(box.scheme).toBe(BLIND_BOX_SCHEME);
+ expect(base64ToBytes(box.enc)).toHaveLength(32);
+ expect(base64ToBytes(box.ct).length).toBeGreaterThan(16);
+ expect(Object.keys(box).sort()).toEqual(['ct', 'enc', 'scheme']);
+ await expect(openBlindBox(box, blindBoxAad(context))).resolves.toEqual(plaintext);
+ await expect(openBlindBox(box, blindBoxAad(standardCreateBlindBoxContext('OTHER_SECRET')))).rejects.toThrow();
+ });
+
+ it('rejects a substituted avault public key when a fingerprint is pinned', async () => {
+ await expect(
+ sealBlindBox('x', {
+ public_key: p2.blind_box.public_key,
+ fingerprint: '00'.repeat(32),
+ }, standardCreateBlindBoxContext(vectorBlindBoxName)),
+ ).rejects.toThrow(/fingerprint/);
+ });
+
+ it('enforces the daemon vault secret-name syntax before producing AAD', async () => {
+ expect(() => standardCreateBlindBoxContext('OPENAI_API_KEY')).not.toThrow();
+ expect(() => standardCreateBlindBoxContext(' OPENAI_API_KEY ')).toThrow(/secret name/);
+ expect(() => standardCreateBlindBoxContext('openai_key')).toThrow(/secret name/);
+ expect(() => standardCreateBlindBoxContext('1OPENAI_KEY')).toThrow(/secret name/);
+ await expect(
+ protectedDekReleaseBlindBoxContext('openai_key', {
+ kind: 'agent-deliver',
+ scopeType: 'session',
+ scopeRef: 'sess-1',
+ ttlSecs: 60,
+ approval: { nonce: new Uint8Array(16).fill(1), expiresAtUnix: 1 },
+ operationHash: '00'.repeat(32),
+ }),
+ ).rejects.toThrow(/secret name/);
+ });
+});
+
+describe('vaultCrypto protected hierarchy', () => {
+ it('unwraps the VMK with either passkey PRF or fallback password', async () => {
+ const vmk = newVmk();
+ const prfSalt = new Uint8Array(32).fill(0x11);
+ const prfOutput = new Uint8Array(32).fill(0x22);
+ const wrapMeta = await buildWrapMeta(vmk, [
+ { kind: 'passkey', prfOutput, prfSalt, credentialId: 'cred-1' },
+ { kind: 'password', password: 'less-secure-fallback' },
+ ]);
+
+ await expect(unwrapVmk(wrapMeta, { kind: 'passkey', prfOutput })).resolves.toEqual(vmk);
+ await expect(unwrapVmk(wrapMeta, 'less-secure-fallback')).resolves.toEqual(vmk);
+ expect(JSON.parse(wrapMeta).copies.find((copy: { kind: string }) => copy.kind === 'password')?.kdf).toBe('scrypt');
+ expect(passkeyPrfSalts(wrapMeta)).toEqual([prfSalt]);
+ expect(passkeyPrfSaltEntries(wrapMeta)).toEqual([{ prfSalt, credentialId: 'cred-1' }]);
+ expect(webAuthnPrfExtensionInput(prfSalt).prf.eval.first.byteLength).toBe(32);
+
+ const withArgon2id = await addPasswordCopy(wrapMeta, vmk, 'argon2id-fallback', {
+ memorySize: 512,
+ iterations: 2,
+ });
+ const copies = JSON.parse(withArgon2id).copies as Array<{ kind: string; kdf?: string }>;
+ expect(copies.at(-1)?.kdf).toBe('argon2id');
+ });
+
+ it('skips malformed authenticated VMK copies and tries the next valid copy', async () => {
+ const vmk = newVmk();
+ const password = 'less-secure-fallback';
+ const malformed = await malformedScryptVmkCopy(password, new Uint8Array(31).fill(0x44));
+ const valid = await buildWrapMeta(vmk, [password]);
+ const combined = JSON.stringify({
+ v: 1,
+ copies: [malformed, ...JSON.parse(valid).copies],
+ });
+
+ await expect(unwrapVmk(combined, password)).resolves.toEqual(vmk);
+ });
+
+ it('rejects blank password wrap factors before deriving VMK copies', async () => {
+ const vmk = newVmk();
+
+ await expect(buildWrapMeta(vmk, [''])).rejects.toThrow(/password/);
+ await expect(buildWrapMeta(vmk, [{ kind: 'password', password: ' ' }])).rejects.toThrow(/password/);
+ await expect(addPasswordCopy(JSON.stringify({ v: 1, copies: [] }), vmk, '')).rejects.toThrow(/password/);
+ });
+
+ it('wraps a protected value with a per-record DEK and releases only that DEK', async () => {
+ const vmk = newVmk();
+ const recordContext = { name: 'OPENAI_API_KEY' };
+ const sealed = await sealProtected(new TextEncoder().encode('protected value'), vmk, recordContext);
+ const dek = await unwrapProtectedDek(sealed, vmk, recordContext);
+ const agentDeliver = p2.blind_box_aad_examples.cases.find((vector) => vector.purpose === 'agent-deliver');
+ const agentSign = p2.blind_box_aad_examples.cases.find((vector) => vector.purpose === 'agent-sign');
+ if (!agentDeliver || !agentSign) {
+ throw new Error('missing shared agent AAD examples');
+ }
+ const context = await protectedDekReleaseBlindBoxContext('OPENAI_API_KEY', {
+ kind: 'agent-deliver',
+ scopeType: agentDeliver.scope_type,
+ scopeRef: agentDeliver.scope_ref,
+ ttlSecs: agentDeliver.ttl_secs,
+ approval: approvalFromVector(agentDeliver),
+ operationHash: agentDeliver.operation_hash_hex,
+ });
+ const avaultPublicKey = {
+ public_key: p2.blind_box.public_key,
+ fingerprint: p2.blind_box.fingerprint,
+ };
+ const released = await releaseProtectedDek(sealed, vmk, avaultPublicKey, recordContext, context);
+
+ expect(dek).toHaveLength(32);
+ expect(protectedRecordAadHex(recordContext)).not.toBe(protectedRecordAadHex({ name: 'OTHER_SIGNING_KEY' }));
+ expect(released.scheme).toBe(BLIND_BOX_SCHEME);
+ expect(base64ToBytes(released.enc)).toHaveLength(32);
+ expect(base64ToBytes(released.ct).length).toBe(32 + 16);
+ await expect(unwrapProtectedDek(sealed, vmk, { name: 'OTHER_SIGNING_KEY' })).rejects.toThrow();
+ await expect(releaseProtectedDek(sealed, vmk, { public_key: p2.blind_box.public_key }, recordContext, context)).rejects.toThrow(
+ /fingerprint/,
+ );
+ await expect(
+ releaseProtectedDek(
+ { ...sealed, wrapped_dek: bytesToBase64(new Uint8Array(48).fill(0x7f)) },
+ vmk,
+ { public_key: p2.blind_box.public_key, fingerprint: '00'.repeat(32) },
+ recordContext,
+ context,
+ ),
+ ).rejects.toThrow(/fingerprint/);
+ const badPublicKey = {
+ public_key: bytesToBase64(new Uint8Array(31).fill(0x5a)),
+ };
+ await expect(
+ releaseProtectedDek(
+ { ...sealed, wrapped_dek: bytesToBase64(new Uint8Array(48).fill(0x7f)) },
+ vmk,
+ { ...badPublicKey, fingerprint: await avaultPublicKeyFingerprint(badPublicKey) },
+ recordContext,
+ context,
+ ),
+ ).rejects.toThrow(/public key/);
+ await expect(releaseProtectedDek(sealed, vmk, avaultPublicKey, { name: 'OTHER_SIGNING_KEY' }, context)).rejects.toThrow(
+ /record name/,
+ );
+ await expect(openBlindBox(released, blindBoxAad(context))).resolves.toEqual(dek);
+ await expect(
+ protectedDekReleaseBlindBoxContext('OPENAI_API_KEY', {
+ kind: 'agent-deliver',
+ scopeType: agentDeliver.scope_type,
+ scopeRef: agentDeliver.scope_ref,
+ ttlSecs: 999,
+ approval: approvalFromVector(agentDeliver),
+ operationHash: agentDeliver.operation_hash_hex,
+ }),
+ ).rejects.toThrow(/operation hash/);
+ await expect(
+ releaseProtectedDek(
+ { ...sealed, wrapped_dek: bytesToBase64(new Uint8Array(48).fill(0x7f)) },
+ vmk,
+ avaultPublicKey,
+ recordContext,
+ { ...context, operationHash: new Uint8Array(32).fill(0x42) },
+ ),
+ ).rejects.toThrow(/operation hash/);
+ const signContext = await protectedDekReleaseBlindBoxContext('OPENAI_API_KEY', {
+ kind: 'agent-sign',
+ scopeType: agentSign.scope_type,
+ scopeRef: agentSign.scope_ref,
+ digest: agentSign.digest_hex,
+ ttlSecs: agentSign.ttl_secs,
+ signatureScheme: agentSign.sign_scheme as SignatureScheme,
+ approval: approvalFromVector(agentSign),
+ operationHash: agentSign.operation_hash_hex,
+ });
+ await expect(releaseProtectedDek(sealed, vmk, avaultPublicKey, recordContext, signContext)).rejects.toThrow(
+ /signed locally/,
+ );
+ await expect(
+ openBlindBox(
+ released,
+ blindBoxAad(
+ await protectedDekReleaseBlindBoxContext('OPENAI_API_KEY', {
+ kind: 'agent-deliver',
+ scopeType: agentDeliver.scope_type,
+ scopeRef: 'other-scope',
+ ttlSecs: agentDeliver.ttl_secs,
+ approval: approvalFromVector(agentDeliver),
+ operationHash: agentDeliver.operation_hash_hex,
+ }),
+ ),
+ ),
+ ).rejects.toThrow();
+ });
+
+ it('copies ArrayBuffer inputs before zeroizing local buffers', () => {
+ const key = bytesFromHex(p2.signing.private_key_hex);
+ const keyBuffer = key.buffer.slice(key.byteOffset, key.byteOffset + key.byteLength);
+ signDigest(keyBuffer, p2.signing.digest_hex, SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE);
+ expect(bytesToHexString(new Uint8Array(keyBuffer))).toBe(p2.signing.private_key_hex);
+ });
+
+ it('does not wipe caller-owned VMK ArrayBuffers when unwrapping protected DEKs', async () => {
+ const vmk = newVmk();
+ const vmkBuffer = vmk.buffer.slice(vmk.byteOffset, vmk.byteOffset + vmk.byteLength);
+ const sealed = await sealProtected(new TextEncoder().encode('protected value'), vmkBuffer, { name: 'OPENAI_API_KEY' });
+ await expect(unwrapProtectedDek(sealed, vmkBuffer, { name: 'OPENAI_API_KEY' })).resolves.toHaveLength(32);
+ expect(bytesToHexString(new Uint8Array(vmkBuffer))).toBe(bytesToHexString(vmk));
+ });
+
+ it('does not wipe caller-owned protected plaintext ArrayBuffers after sealing', async () => {
+ const vmk = newVmk();
+ const plaintext = new TextEncoder().encode('protected value');
+ const plaintextBuffer = plaintext.buffer.slice(plaintext.byteOffset, plaintext.byteOffset + plaintext.byteLength);
+ await sealProtected(plaintextBuffer, vmk, { name: 'OPENAI_API_KEY' });
+
+ expect(new TextDecoder().decode(plaintextBuffer)).toBe('protected value');
+ });
+
+ it('derives a stable passkey KEK from WebAuthn PRF output and salt', async () => {
+ const prfOutput = new Uint8Array(32).fill(7);
+ const prfSalt = new Uint8Array(32).fill(9);
+
+ expect(bytesToHexString(await derivePasskeyKek(prfOutput, prfSalt))).toBe(
+ bytesToHexString(await derivePasskeyKek(prfOutput, prfSalt)),
+ );
+ });
+});
diff --git a/ui/src/lib/vaultCrypto.ts b/ui/src/lib/vaultCrypto.ts
new file mode 100644
index 000000000..c2b9bfee6
--- /dev/null
+++ b/ui/src/lib/vaultCrypto.ts
@@ -0,0 +1,1248 @@
+import { Aes256Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
+import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
+import { secp256k1, schnorr } from '@noble/curves/secp256k1.js';
+import { bytesToHex, hexToBytes } from '@noble/curves/utils.js';
+import { argon2id, scrypt } from 'hash-wasm';
+
+export const BLIND_BOX_SCHEME = 'hpke-x25519-hkdfsha256-aes256gcm-v1';
+export const BLIND_BOX_HPKE_INFO = 'avault:blind-box:v1';
+export const BLIND_BOX_AAD_DOMAIN = 'avault:blind-box:aad:v1';
+export const WRAP_SCHEME = 'machine-aesgcm-v1';
+export const WRAP_META_VERSION = 1;
+export const SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE = 'ecdsa-secp256k1-recoverable';
+export const SIGN_SCHEME_ECDSA_SECP256K1_DER = 'ecdsa-secp256k1-der';
+export const SIGN_SCHEME_SCHNORR_SECP256K1_BIP340 = 'schnorr-secp256k1-bip340';
+
+const KEY_BYTES = 32;
+const NONCE_BYTES = 12;
+const ARGON2_VERSION = 19;
+const PASSKEY_PRF_SALT_BYTES = 32;
+const PASSKEY_HKDF_INFO = 'avault:protected-vmk:kek-passkey:v1';
+const SECRET_NAME_PATTERN = /^[A-Z][A-Z0-9_]*$/;
+const DEFAULT_SCRYPT = {
+ n: 2 ** 15,
+ r: 8,
+ p: 1,
+} as const;
+
+const DEFAULT_ARGON2ID = {
+ iterations: 3,
+ memorySize: 64 * 1024,
+ parallelism: 1,
+} as const;
+
+const textEncoder = new TextEncoder();
+
+type BytesLike = Uint8Array | ArrayBuffer | ArrayBufferView;
+type HexOrBytes = BytesLike | string;
+
+export type BlindBox = {
+ scheme: typeof BLIND_BOX_SCHEME;
+ enc: string;
+ ct: string;
+};
+
+export type AvaultPublicKey = {
+ public_key: string;
+ fingerprint?: string;
+};
+
+export type ProtectedSealed = {
+ ciphertext: string;
+ nonce: string;
+ dek_nonce: string;
+ wrapped_dek: string;
+};
+
+export type ProtectedRecordContext = {
+ name: string;
+ scheme?: typeof WRAP_SCHEME;
+ version?: typeof WRAP_META_VERSION;
+};
+
+export type Argon2idParams = {
+ iterations: number;
+ memorySize: number;
+ parallelism: number;
+};
+
+type PasswordScryptFactor = {
+ kind: 'password';
+ password: string;
+ kdf?: 'scrypt';
+};
+
+type PasswordArgon2idFactor = {
+ kind: 'password';
+ password: string;
+ kdf: 'argon2id';
+ argon2id?: Partial<Argon2idParams>;
+};
+
+export type PasswordWrapFactor = PasswordScryptFactor | PasswordArgon2idFactor;
+
+export type PasskeyWrapFactor = {
+ kind: 'passkey';
+ prfOutput: BytesLike;
+ prfSalt: BytesLike;
+ credentialId?: string;
+};
+
+export type VmkWrapFactor = PasswordWrapFactor | PasskeyWrapFactor;
+
+export type PasswordUnlockFactor = {
+ kind: 'password';
+ password: string;
+};
+
+export type PasskeyUnlockFactor = {
+ kind: 'passkey';
+ prfOutput: BytesLike;
+ prfSalt?: BytesLike;
+};
+
+export type VmkUnlockFactor = PasswordUnlockFactor | PasskeyUnlockFactor;
+
+export type SignatureScheme =
+ | typeof SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE
+ | typeof SIGN_SCHEME_ECDSA_SECP256K1_DER
+ | typeof SIGN_SCHEME_SCHNORR_SECP256K1_BIP340;
+
+export type SignatureResult = {
+ scheme: SignatureScheme;
+ signature: string;
+ recovery_id: number | null;
+};
+
+export type SignDigestOptions = {
+ schnorrAuxRand?: HexOrBytes;
+};
+
+export type BlindBoxApproval = {
+ nonce: BytesLike;
+ expiresAtUnix: number | bigint;
+};
+
+export type BlindBoxOperationHashField = string | BytesLike;
+
+export type StandardCreateBlindBoxContext = {
+ purpose: 'seal';
+ name: string;
+};
+
+export type AgentDeliverBlindBoxContext = {
+ purpose: 'agent-deliver';
+ name: string;
+ scopeType: string;
+ scopeRef: string;
+ ttlSecs: number | bigint;
+ approvalNonce: BytesLike;
+ approvalExpiresAtUnix: number | bigint;
+ operationHash: HexOrBytes;
+};
+
+export type AgentSignBlindBoxContext = {
+ purpose: 'agent-sign';
+ name: string;
+ scopeType: string;
+ scopeRef: string;
+ signScheme: SignatureScheme;
+ digest: HexOrBytes;
+ ttlSecs: number | bigint;
+ approvalNonce: BytesLike;
+ approvalExpiresAtUnix: number | bigint;
+ operationHash: HexOrBytes;
+};
+
+export type ProtectedDekReleaseBlindBoxContext = AgentDeliverBlindBoxContext | AgentSignBlindBoxContext;
+export type ProtectedDekDeliveryBlindBoxContext = AgentDeliverBlindBoxContext;
+
+export type BlindBoxContext = StandardCreateBlindBoxContext | ProtectedDekReleaseBlindBoxContext;
+
+export type ProtectedDekReleaseOperation =
+ | {
+ kind: 'agent-deliver';
+ scopeType: string;
+ scopeRef: string;
+ ttlSecs: number | bigint;
+ approval: BlindBoxApproval;
+ operationHash: HexOrBytes;
+ }
+ | {
+ kind: 'agent-sign';
+ scopeType: string;
+ scopeRef: string;
+ signatureScheme: SignatureScheme;
+ digest: HexOrBytes;
+ ttlSecs: number | bigint;
+ approval: BlindBoxApproval;
+ operationHash: HexOrBytes;
+ };
+
+type WrapMeta = {
+ v: 1;
+ copies: WrapCopy[];
+};
+
+type PasswordArgon2idCopy = {
+ kind: 'password';
+ kdf: 'argon2id';
+ version: 19;
+ iterations: number;
+ memorySize: number;
+ parallelism: number;
+ salt: string;
+ nonce: string;
+ wrapped: string;
+};
+
+type PasswordScryptCopy = {
+ kind: 'password';
+ kdf: 'scrypt';
+ n: number;
+ r: number;
+ p: number;
+ salt: string;
+ nonce: string;
+ wrapped: string;
+};
+
+type PasskeyPrfCopy = {
+ kind: 'passkey';
+ kdf: 'webauthn-prf-hkdf-sha256';
+ prf_salt: string;
+ nonce: string;
+ wrapped: string;
+ credential_id?: string;
+};
+
+type WrapCopy = PasswordArgon2idCopy | PasswordScryptCopy | PasskeyPrfCopy;
+
+export type WebAuthnPrfExtensionInput = {
+ prf: {
+ eval: {
+ first: ArrayBuffer;
+ };
+ };
+};
+
+export type PasskeyPrfSalt = {
+ prfSalt: Uint8Array;
+ credentialId?: string;
+};
+
+function toUint8Array(value: BytesLike, field = 'bytes'): Uint8Array {
+ if (value instanceof Uint8Array) {
+ return new Uint8Array(value);
+ }
+ if (value instanceof ArrayBuffer) {
+ return new Uint8Array(value.slice(0));
+ }
+ if (ArrayBuffer.isView(value)) {
+ return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
+ }
+ throw new TypeError(`${field} must be bytes`);
+}
+
+function toArrayBuffer(value: BytesLike): ArrayBuffer {
+ const bytes = toUint8Array(value);
+ const out = new ArrayBuffer(bytes.byteLength);
+ new Uint8Array(out).set(bytes);
+ bytes.fill(0);
+ return out;
+}
+
+function utf8(value: string): Uint8Array {
+ return textEncoder.encode(value);
+}
+
+function randomBytes(length: number): Uint8Array {
+ const out = new Uint8Array(length);
+ crypto.getRandomValues(out);
+ return out;
+}
+
+export function bytesToBase64(value: BytesLike): string {
+ const bytes = toUint8Array(value);
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ return btoa(binary);
+}
+
+export function base64ToBytes(value: string): Uint8Array {
+ return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
+}
+
+export function bytesFromHex(value: string): Uint8Array {
+ return hexToBytes(value);
+}
+
+export function bytesToHexString(value: BytesLike): string {
+ return bytesToHex(toUint8Array(value));
+}
+
+function assertLength(bytes: Uint8Array, length: number, field: string): void {
+ if (bytes.length !== length) {
+ throw new Error(`${field} must be ${length} bytes`);
+ }
+}
+
+function wipeArrayBuffer(buffer: ArrayBuffer | undefined): void {
+ if (buffer) {
+ new Uint8Array(buffer).fill(0);
+ }
+}
+
+function normalizeArgon2idParams(params?: Partial<Argon2idParams>): Argon2idParams {
+ const normalized = { ...DEFAULT_ARGON2ID, ...params };
+ if (!Number.isInteger(normalized.iterations) || normalized.iterations < 1 || normalized.iterations > 10) {
+ throw new Error('argon2id iterations out of bounds');
+ }
+ if (!Number.isInteger(normalized.memorySize) || normalized.memorySize < 8 || normalized.memorySize > 256 * 1024) {
+ throw new Error('argon2id memorySize out of bounds');
+ }
+ if (!Number.isInteger(normalized.parallelism) || normalized.parallelism < 1 || normalized.parallelism > 8) {
+ throw new Error('argon2id parallelism out of bounds');
+ }
+ return normalized;
+}
+
+function validateScryptParams(n: number, r: number, p: number): void {
+ if (!Number.isInteger(n) || n < 2 || (n & (n - 1)) !== 0 || n > 2 ** 17) {
+ throw new Error('scrypt N out of bounds');
+ }
+ if (!Number.isInteger(r) || r < 1 || r > 16) {
+ throw new Error('scrypt r out of bounds');
+ }
+ if (!Number.isInteger(p) || p < 1 || p > 16) {
+ throw new Error('scrypt p out of bounds');
+ }
+}
+
+async function aesgcmEncrypt(
+ key: BytesLike,
+ nonce: BytesLike,
+ data: BytesLike,
+ additionalData?: BytesLike,
+): Promise<Uint8Array> {
+ let keyBuffer: ArrayBuffer | undefined;
+ let nonceBuffer: ArrayBuffer | undefined;
+ let dataBuffer: ArrayBuffer | undefined;
+ let additionalDataBuffer: ArrayBuffer | undefined;
+ try {
+ keyBuffer = toArrayBuffer(key);
+ nonceBuffer = toArrayBuffer(nonce);
+ dataBuffer = toArrayBuffer(data);
+ additionalDataBuffer = additionalData ? toArrayBuffer(additionalData) : undefined;
+ const cryptoKey = await crypto.subtle.importKey('raw', keyBuffer, 'AES-GCM', false, ['encrypt']);
+ const ct = await crypto.subtle.encrypt(
+ {
+ name: 'AES-GCM',
+ iv: nonceBuffer,
+ ...(additionalDataBuffer ? { additionalData: additionalDataBuffer } : {}),
+ },
+ cryptoKey,
+ dataBuffer,
+ );
+ return new Uint8Array(ct);
+ } finally {
+ wipeArrayBuffer(keyBuffer);
+ wipeArrayBuffer(nonceBuffer);
+ wipeArrayBuffer(dataBuffer);
+ wipeArrayBuffer(additionalDataBuffer);
+ }
+}
+
+async function aesgcmDecrypt(
+ key: BytesLike,
+ nonce: BytesLike,
+ data: BytesLike,
+ additionalData?: BytesLike,
+): Promise<Uint8Array> {
+ let keyBuffer: ArrayBuffer | undefined;
+ let nonceBuffer: ArrayBuffer | undefined;
+ let dataBuffer: ArrayBuffer | undefined;
+ let additionalDataBuffer: ArrayBuffer | undefined;
+ try {
+ keyBuffer = toArrayBuffer(key);
+ nonceBuffer = toArrayBuffer(nonce);
+ dataBuffer = toArrayBuffer(data);
+ additionalDataBuffer = additionalData ? toArrayBuffer(additionalData) : undefined;
+ const cryptoKey = await crypto.subtle.importKey('raw', keyBuffer, 'AES-GCM', false, ['decrypt']);
+ const pt = await crypto.subtle.decrypt(
+ {
+ name: 'AES-GCM',
+ iv: nonceBuffer,
+ ...(additionalDataBuffer ? { additionalData: additionalDataBuffer } : {}),
+ },
+ cryptoKey,
+ dataBuffer,
+ );
+ return new Uint8Array(pt);
+ } finally {
+ wipeArrayBuffer(keyBuffer);
+ wipeArrayBuffer(nonceBuffer);
+ wipeArrayBuffer(dataBuffer);
+ wipeArrayBuffer(additionalDataBuffer);
+ }
+}
+
+async function hkdfSha256(ikm: BytesLike, salt: BytesLike, info: BytesLike, length: number): Promise<Uint8Array> {
+ let ikmBuffer: ArrayBuffer | undefined;
+ let saltBuffer: ArrayBuffer | undefined;
+ let infoBuffer: ArrayBuffer | undefined;
+ try {
+ ikmBuffer = toArrayBuffer(ikm);
+ saltBuffer = toArrayBuffer(salt);
+ infoBuffer = toArrayBuffer(info);
+ const key = await crypto.subtle.importKey('raw', ikmBuffer, 'HKDF', false, ['deriveBits']);
+ const bits = await crypto.subtle.deriveBits(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: saltBuffer,
+ info: infoBuffer,
+ },
+ key,
+ length * 8,
+ );
+ return new Uint8Array(bits);
+ } finally {
+ wipeArrayBuffer(ikmBuffer);
+ wipeArrayBuffer(saltBuffer);
+ wipeArrayBuffer(infoBuffer);
+ }
+}
+
+async function kekPasswordArgon2id(password: string, salt: BytesLike, params?: Partial<Argon2idParams>): Promise<Uint8Array> {
+ const normalized = normalizeArgon2idParams(params);
+ return (await argon2id({
+ password: utf8(password),
+ salt: toUint8Array(salt),
+ iterations: normalized.iterations,
+ memorySize: normalized.memorySize,
+ parallelism: normalized.parallelism,
+ hashLength: KEY_BYTES,
+ outputType: 'binary',
+ })) as Uint8Array;
+}
+
+async function kekPasswordScrypt(password: string, salt: BytesLike, n: number, r: number, p: number): Promise<Uint8Array> {
+ validateScryptParams(n, r, p);
+ return (await scrypt({
+ password: utf8(password),
+ salt: toUint8Array(salt),
+ costFactor: n,
+ blockSize: r,
+ parallelism: p,
+ hashLength: KEY_BYTES,
+ outputType: 'binary',
+ })) as Uint8Array;
+}
+
+export async function derivePasskeyKek(prfOutput: BytesLike, prfSalt: BytesLike): Promise<Uint8Array> {
+ const output = toUint8Array(prfOutput, 'passkey PRF output');
+ try {
+ const salt = toUint8Array(prfSalt, 'passkey PRF salt');
+ assertLength(output, KEY_BYTES, 'passkey PRF output');
+ assertLength(salt, PASSKEY_PRF_SALT_BYTES, 'passkey PRF salt');
+ return await hkdfSha256(output, salt, utf8(PASSKEY_HKDF_INFO), KEY_BYTES);
+ } finally {
+ output.fill(0);
+ }
+}
+
+export function newVmk(): Uint8Array {
+ return randomBytes(KEY_BYTES);
+}
+
+export function newPasskeyPrfSalt(): Uint8Array {
+ return randomBytes(PASSKEY_PRF_SALT_BYTES);
+}
+
+export function webAuthnPrfExtensionInput(prfSalt: BytesLike): WebAuthnPrfExtensionInput {
+ const salt = toUint8Array(prfSalt, 'passkey PRF salt');
+ assertLength(salt, PASSKEY_PRF_SALT_BYTES, 'passkey PRF salt');
+ return { prf: { eval: { first: toArrayBuffer(salt) } } };
+}
+
+function parseWrapMeta(wrapMeta: string | WrapMeta): WrapMeta {
+ const parsed = typeof wrapMeta === 'string' ? JSON.parse(wrapMeta) : wrapMeta;
+ if (parsed?.v !== 1 || !Array.isArray(parsed.copies)) {
+ throw new Error('invalid protected wrap_meta');
+ }
+ return parsed as WrapMeta;
+}
+
+function normalizeWrapFactors(factors: VmkWrapFactor[] | string[]): VmkWrapFactor[] {
+ return factors.map((factor): VmkWrapFactor => {
+ if (typeof factor === 'string') {
+ return { kind: 'password', password: requireNonBlankPassword(factor) };
+ }
+ if (factor.kind === 'password') {
+ return { ...factor, password: requireNonBlankPassword(factor.password) };
+ }
+ return factor;
+ });
+}
+
+async function passwordArgon2idCopy(vmk: BytesLike, factor: PasswordArgon2idFactor): Promise<PasswordArgon2idCopy> {
+ const vmkBytes = toUint8Array(vmk, 'VMK');
+ const salt = randomBytes(16);
+ const nonce = randomBytes(NONCE_BYTES);
+ let kek: Uint8Array | undefined;
+ try {
+ assertLength(vmkBytes, KEY_BYTES, 'VMK');
+ const params = normalizeArgon2idParams(factor.argon2id);
+ kek = await kekPasswordArgon2id(factor.password, salt, params);
+ const wrapped = await aesgcmEncrypt(kek, nonce, vmkBytes);
+ return {
+ kind: 'password',
+ kdf: 'argon2id',
+ version: ARGON2_VERSION,
+ iterations: params.iterations,
+ memorySize: params.memorySize,
+ parallelism: params.parallelism,
+ salt: bytesToBase64(salt),
+ nonce: bytesToBase64(nonce),
+ wrapped: bytesToBase64(wrapped),
+ };
+ } finally {
+ kek?.fill(0);
+ vmkBytes.fill(0);
+ }
+}
+
+async function passwordScryptCopy(vmk: BytesLike, password: string): Promise<PasswordScryptCopy> {
+ const vmkBytes = toUint8Array(vmk, 'VMK');
+ const salt = randomBytes(16);
+ const nonce = randomBytes(NONCE_BYTES);
+ let kek: Uint8Array | undefined;
+ try {
+ assertLength(vmkBytes, KEY_BYTES, 'VMK');
+ kek = await kekPasswordScrypt(password, salt, DEFAULT_SCRYPT.n, DEFAULT_SCRYPT.r, DEFAULT_SCRYPT.p);
+ const wrapped = await aesgcmEncrypt(kek, nonce, vmkBytes);
+ return {
+ kind: 'password',
+ kdf: 'scrypt',
+ n: DEFAULT_SCRYPT.n,
+ r: DEFAULT_SCRYPT.r,
+ p: DEFAULT_SCRYPT.p,
+ salt: bytesToBase64(salt),
+ nonce: bytesToBase64(nonce),
+ wrapped: bytesToBase64(wrapped),
+ };
+ } finally {
+ kek?.fill(0);
+ vmkBytes.fill(0);
+ }
+}
+
+async function passwordCopy(vmk: BytesLike, factor: PasswordWrapFactor): Promise<PasswordArgon2idCopy | PasswordScryptCopy> {
+ const password = requireNonBlankPassword(factor.password);
+ return factor.kdf === 'argon2id'
+ ? passwordArgon2idCopy(vmk, { ...factor, password })
+ : passwordScryptCopy(vmk, password);
+}
+
+async function passkeyCopy(vmk: BytesLike, factor: PasskeyWrapFactor): Promise<PasskeyPrfCopy> {
+ const vmkBytes = toUint8Array(vmk, 'VMK');
+ const nonce = randomBytes(NONCE_BYTES);
+ let kek: Uint8Array | undefined;
+ let prfSalt: Uint8Array | undefined;
+ try {
+ assertLength(vmkBytes, KEY_BYTES, 'VMK');
+ prfSalt = toUint8Array(factor.prfSalt, 'passkey PRF salt');
+ assertLength(prfSalt, PASSKEY_PRF_SALT_BYTES, 'passkey PRF salt');
+ kek = await derivePasskeyKek(factor.prfOutput, prfSalt);
+ const wrapped = await aesgcmEncrypt(kek, nonce, vmkBytes);
+ return {
+ kind: 'passkey',
+ kdf: 'webauthn-prf-hkdf-sha256',
+ prf_salt: bytesToBase64(prfSalt),
+ nonce: bytesToBase64(nonce),
+ wrapped: bytesToBase64(wrapped),
+ ...(factor.credentialId ? { credential_id: factor.credentialId } : {}),
+ };
+ } finally {
+ kek?.fill(0);
+ prfSalt?.fill(0);
+ vmkBytes.fill(0);
+ }
+}
+
+export async function buildWrapMeta(vmk: BytesLike, factors: VmkWrapFactor[] | string[]): Promise<string> {
+ const vmkBytes = toUint8Array(vmk, 'VMK');
+ try {
+ assertLength(vmkBytes, KEY_BYTES, 'VMK');
+ const normalized = normalizeWrapFactors(factors);
+ if (normalized.length === 0) {
+ throw new Error('at least one protected unlock factor is required');
+ }
+ const copies: WrapCopy[] = [];
+ for (const factor of normalized) {
+ copies.push(factor.kind === 'password' ? await passwordCopy(vmkBytes, factor) : await passkeyCopy(vmkBytes, factor));
+ }
+ return JSON.stringify({ v: 1, copies } satisfies WrapMeta);
+ } finally {
+ vmkBytes.fill(0);
+ }
+}
+
+export async function addPasswordCopy(
+ wrapMeta: string,
+ vmk: BytesLike,
+ password: string,
+ argon2idParams?: Partial<Argon2idParams>,
+): Promise<string> {
+ const meta = parseWrapMeta(wrapMeta);
+ meta.copies.push(
+ await passwordCopy(vmk, {
+ kind: 'password',
+ password,
+ ...(argon2idParams ? { kdf: 'argon2id', argon2id: argon2idParams } : {}),
+ }),
+ );
+ return JSON.stringify(meta);
+}
+
+export async function addPasskeyCopy(
+ wrapMeta: string,
+ vmk: BytesLike,
+ prfOutput: BytesLike,
+ prfSalt: BytesLike,
+ credentialId?: string,
+): Promise<string> {
+ const meta = parseWrapMeta(wrapMeta);
+ meta.copies.push(await passkeyCopy(vmk, { kind: 'passkey', prfOutput, prfSalt, credentialId }));
+ return JSON.stringify(meta);
+}
+
+async function unwrapPasswordCopy(copy: PasswordArgon2idCopy | PasswordScryptCopy, password: string): Promise<Uint8Array> {
+ const salt = base64ToBytes(copy.salt);
+ const nonce = base64ToBytes(copy.nonce);
+ const wrapped = base64ToBytes(copy.wrapped);
+ const kek =
+ copy.kdf === 'argon2id'
+ ? await kekPasswordArgon2id(password, salt, {
+ iterations: copy.iterations,
+ memorySize: copy.memorySize,
+ parallelism: copy.parallelism,
+ })
+ : await kekPasswordScrypt(password, salt, copy.n, copy.r, copy.p);
+ try {
+ return await aesgcmDecrypt(kek, nonce, wrapped);
+ } finally {
+ kek.fill(0);
+ }
+}
+
+async function unwrapPasskeyCopy(copy: PasskeyPrfCopy, factor: PasskeyUnlockFactor): Promise<Uint8Array> {
+ const prfSalt = base64ToBytes(copy.prf_salt);
+ if (factor.prfSalt && bytesToBase64(factor.prfSalt) !== copy.prf_salt) {
+ throw new Error('passkey PRF salt does not match copy');
+ }
+ const kek = await derivePasskeyKek(factor.prfOutput, prfSalt);
+ try {
+ return await aesgcmDecrypt(kek, base64ToBytes(copy.nonce), base64ToBytes(copy.wrapped));
+ } finally {
+ kek.fill(0);
+ }
+}
+
+export async function unwrapVmk(wrapMeta: string | WrapMeta, factor: VmkUnlockFactor | string): Promise<Uint8Array> {
+ const meta = parseWrapMeta(wrapMeta);
+ const normalized: VmkUnlockFactor = typeof factor === 'string' ? { kind: 'password', password: factor } : factor;
+ for (const copy of meta.copies) {
+ try {
+ if (normalized.kind === 'password' && copy.kind === 'password') {
+ const vmk = await unwrapPasswordCopy(copy, normalized.password);
+ try {
+ assertLength(vmk, KEY_BYTES, 'VMK');
+ return vmk;
+ } catch (error) {
+ vmk.fill(0);
+ throw error;
+ }
+ }
+ if (normalized.kind === 'passkey' && copy.kind === 'passkey') {
+ const vmk = await unwrapPasskeyCopy(copy, normalized);
+ try {
+ assertLength(vmk, KEY_BYTES, 'VMK');
+ return vmk;
+ } catch (error) {
+ vmk.fill(0);
+ throw error;
+ }
+ }
+ } catch {
+ // Wrong factor or corrupt copy; try the next independent VMK copy.
+ }
+ }
+ throw new Error('no protected VMK copy could be unwrapped');
+}
+
+export function passkeyPrfSalts(wrapMeta: string | WrapMeta): Uint8Array[] {
+ return passkeyPrfSaltEntries(wrapMeta).map((entry) => entry.prfSalt);
+}
+
+export function passkeyPrfSaltEntries(wrapMeta: string | WrapMeta): PasskeyPrfSalt[] {
+ return parseWrapMeta(wrapMeta)
+ .copies.filter((copy): copy is PasskeyPrfCopy => copy.kind === 'passkey')
+ .map((copy) => ({
+ prfSalt: base64ToBytes(copy.prf_salt),
+ ...(copy.credential_id ? { credentialId: copy.credential_id } : {}),
+ }));
+}
+
+function protectedRecordAad(context: ProtectedRecordContext): Uint8Array {
+ const out: number[] = [];
+ pushLengthPrefixed(out, utf8(validateSecretName(context.name)));
+ pushLengthPrefixed(out, utf8(context.scheme ?? WRAP_SCHEME));
+ pushLengthPrefixed(out, new Uint8Array([context.version ?? WRAP_META_VERSION]));
+ return new Uint8Array(out);
+}
+
+export function protectedRecordAadHex(context: ProtectedRecordContext): string {
+ return bytesToHex(protectedRecordAad(context));
+}
+
+function requireNonBlankPassword(password: string): string {
+ if (typeof password !== 'string' || password.trim() === '') {
+ throw new Error('password must not be empty');
+ }
+ return password;
+}
+
+function requirePinnedPublicKey(publicKey: AvaultPublicKey): AvaultPublicKey & { fingerprint: string } {
+ if (!publicKey.fingerprint) {
+ throw new Error('protected DEK release requires a pinned avault public key fingerprint');
+ }
+ return publicKey as AvaultPublicKey & { fingerprint: string };
+}
+
+async function requireValidPinnedPublicKey(publicKey: AvaultPublicKey): Promise<AvaultPublicKey & { fingerprint: string }> {
+ const pinned = requirePinnedPublicKey(publicKey);
+ const rawPublicKey = publicKeyBytes(pinned);
+ assertLength(rawPublicKey, KEY_BYTES, 'avault public key');
+ const actual = await publicKeyFingerprint(rawPublicKey);
+ if (actual !== pinned.fingerprint.toLowerCase()) {
+ throw new Error('avault public key fingerprint mismatch');
+ }
+ return pinned;
+}
+
+function assertReleaseMatchesRecord(recordContext: ProtectedRecordContext, context: ProtectedDekReleaseBlindBoxContext): void {
+ if (validateSecretName(recordContext.name) !== validateSecretName(context.name)) {
+ throw new Error('protected DEK release context name does not match record name');
+ }
+}
+
+function assertDeliveryReleaseContext(
+ context: ProtectedDekReleaseBlindBoxContext,
+): asserts context is ProtectedDekDeliveryBlindBoxContext {
+ if (context.purpose === 'agent-sign') {
+ throw new Error('protected signing keys must be signed locally; DEK release only supports delivery contexts');
+ }
+}
+
+export async function sealProtected(
+ value: BytesLike,
+ vmk: BytesLike,
+ context: ProtectedRecordContext,
+): Promise<ProtectedSealed> {
+ const vmkBytes = toUint8Array(vmk, 'VMK');
+ const dek = randomBytes(KEY_BYTES);
+ let valueBytes: Uint8Array | undefined;
+ try {
+ assertLength(vmkBytes, KEY_BYTES, 'VMK');
+ valueBytes = toUint8Array(value, 'value');
+ const aad = protectedRecordAad(context);
+ const valueNonce = randomBytes(NONCE_BYTES);
+ const ciphertext = await aesgcmEncrypt(dek, valueNonce, valueBytes, aad);
+ const dekNonce = randomBytes(NONCE_BYTES);
+ const wrappedDek = await aesgcmEncrypt(vmkBytes, dekNonce, dek, aad);
+ return {
+ ciphertext: bytesToBase64(ciphertext),
+ nonce: bytesToBase64(valueNonce),
+ dek_nonce: bytesToBase64(dekNonce),
+ wrapped_dek: bytesToBase64(wrappedDek),
+ };
+ } finally {
+ dek.fill(0);
+ vmkBytes.fill(0);
+ valueBytes?.fill(0);
+ }
+}
+
+export async function unwrapProtectedDek(
+ sealed: ProtectedSealed,
+ vmk: BytesLike,
+ context: ProtectedRecordContext,
+): Promise<Uint8Array> {
+ const vmkBytes = toUint8Array(vmk, 'VMK');
+ try {
+ assertLength(vmkBytes, KEY_BYTES, 'VMK');
+ const dek = await aesgcmDecrypt(
+ vmkBytes,
+ base64ToBytes(sealed.dek_nonce),
+ base64ToBytes(sealed.wrapped_dek),
+ protectedRecordAad(context),
+ );
+ try {
+ assertLength(dek, KEY_BYTES, 'DEK');
+ return dek;
+ } catch (error) {
+ dek.fill(0);
+ throw error;
+ }
+ } finally {
+ vmkBytes.fill(0);
+ }
+}
+
+export async function openProtected(
+ sealed: ProtectedSealed,
+ vmk: BytesLike,
+ context: ProtectedRecordContext,
+): Promise<Uint8Array> {
+ const dek = await unwrapProtectedDek(sealed, vmk, context);
+ try {
+ return await aesgcmDecrypt(
+ dek,
+ base64ToBytes(sealed.nonce),
+ base64ToBytes(sealed.ciphertext),
+ protectedRecordAad(context),
+ );
+ } finally {
+ dek.fill(0);
+ }
+}
+
+export async function releaseProtectedDek(
+ sealed: ProtectedSealed,
+ vmk: BytesLike,
+ publicKey: AvaultPublicKey,
+ recordContext: ProtectedRecordContext,
+ context: ProtectedDekDeliveryBlindBoxContext,
+): Promise<BlindBox> {
+ assertDeliveryReleaseContext(context);
+ assertReleaseMatchesRecord(recordContext, context);
+ await assertAgentDeliverReleaseHash(context);
+ const pinnedPublicKey = await requireValidPinnedPublicKey(publicKey);
+ const dek = await unwrapProtectedDek(sealed, vmk, recordContext);
+ try {
+ return await sealBlindBox(dek, pinnedPublicKey, context);
+ } finally {
+ dek.fill(0);
+ }
+}
+
+function hpkeSuite(): CipherSuite {
+ return new CipherSuite({
+ kem: new DhkemX25519HkdfSha256(),
+ kdf: new HkdfSha256(),
+ aead: new Aes256Gcm(),
+ });
+}
+
+function publicKeyBytes(publicKey: AvaultPublicKey | string): Uint8Array {
+ return base64ToBytes(typeof publicKey === 'string' ? publicKey : publicKey.public_key);
+}
+
+async function publicKeyFingerprint(publicKeyRaw: Uint8Array): Promise<string> {
+ const digest = await crypto.subtle.digest('SHA-256', toArrayBuffer(publicKeyRaw));
+ return bytesToHex(new Uint8Array(digest));
+}
+
+export async function avaultPublicKeyFingerprint(publicKey: AvaultPublicKey | string): Promise<string> {
+ return publicKeyFingerprint(publicKeyBytes(publicKey));
+}
+
+export async function sealBlindBox(
+ plaintext: BytesLike | string,
+ publicKey: AvaultPublicKey | string,
+ context: BlindBoxContext,
+): Promise<BlindBox> {
+ const suite = hpkeSuite();
+ const publicKeyRaw = publicKeyBytes(publicKey);
+ assertLength(publicKeyRaw, KEY_BYTES, 'avault public key');
+ if (typeof publicKey !== 'string' && publicKey.fingerprint) {
+ const actual = await avaultPublicKeyFingerprint(publicKey);
+ if (actual !== publicKey.fingerprint.toLowerCase()) {
+ throw new Error('avault public key fingerprint mismatch');
+ }
+ }
+
+ const recipientPublicKey = await suite.kem.deserializePublicKey(publicKeyRaw);
+ const pt = typeof plaintext === 'string' ? utf8(plaintext) : toUint8Array(plaintext, 'plaintext');
+ try {
+ const sealed = await suite.seal(
+ { recipientPublicKey, info: utf8(BLIND_BOX_HPKE_INFO) },
+ pt,
+ blindBoxAad(context),
+ );
+ return {
+ scheme: BLIND_BOX_SCHEME,
+ enc: bytesToBase64(new Uint8Array(sealed.enc)),
+ ct: bytesToBase64(new Uint8Array(sealed.ct)),
+ };
+ } finally {
+ pt.fill(0);
+ }
+}
+
+function normalizeDigest(digest: BytesLike | string): Uint8Array {
+ const bytes = typeof digest === 'string' ? hexToBytes(digest) : toUint8Array(digest, 'digest');
+ assertLength(bytes, KEY_BYTES, 'digest');
+ return bytes;
+}
+
+function normalizePrivateKey(privateKey: BytesLike | string): Uint8Array {
+ const bytes = typeof privateKey === 'string' ? hexToBytes(privateKey) : toUint8Array(privateKey, 'private key');
+ try {
+ assertLength(bytes, KEY_BYTES, 'private key');
+ if (!secp256k1.utils.isValidSecretKey(bytes)) {
+ throw new Error('invalid secp256k1 private key');
+ }
+ return bytes;
+ } catch (error) {
+ bytes.fill(0);
+ throw error;
+ }
+}
+
+function normalizeHexOrBytes(value: HexOrBytes, field: string): Uint8Array {
+ return typeof value === 'string' ? hexToBytes(value) : toUint8Array(value, field);
+}
+
+function validateSecretName(name: string): string {
+ if (typeof name !== 'string' || !SECRET_NAME_PATTERN.test(name)) {
+ throw new Error('vault secret name must match ^[A-Z][A-Z0-9_]*$');
+ }
+ return name;
+}
+
+function validateNonEmpty(value: string, field: string): string {
+ if (typeof value !== 'string' || value.trim() === '') {
+ throw new Error(`${field} is required`);
+ }
+ return value;
+}
+
+function normalizeOperationHash(value: HexOrBytes): Uint8Array {
+ const bytes = normalizeHexOrBytes(value, 'operation hash');
+ assertLength(bytes, KEY_BYTES, 'operation hash');
+ return bytes;
+}
+
+function normalizeApproval(approval: BlindBoxApproval): {
+ approvalNonce: Uint8Array;
+ approvalExpiresAtUnix: bigint;
+} {
+ const approvalNonce = toUint8Array(approval.nonce, 'approval nonce');
+ if (approvalNonce.length < 16 || approvalNonce.length > 128) {
+ throw new Error('approval nonce must be 16..128 bytes');
+ }
+ const approvalExpiresAtUnix = normalizeUnixU64(approval.expiresAtUnix);
+ return { approvalNonce, approvalExpiresAtUnix };
+}
+
+function normalizeU64(value: number | bigint, field: string): bigint {
+ if (typeof value === 'number' && (!Number.isSafeInteger(value) || value < 0)) {
+ throw new Error(`${field} out of bounds`);
+ }
+ const normalized = typeof value === 'bigint' ? value : BigInt(value);
+ if (normalized < 0n || normalized > 0xffff_ffff_ffff_ffffn) {
+ throw new Error(`${field} out of bounds`);
+ }
+ return normalized;
+}
+
+function normalizeUnixU64(value: number | bigint): bigint {
+ return normalizeU64(value, 'approval expiry');
+}
+
+function u64Be(value: number | bigint, field: string): Uint8Array {
+ const normalized = normalizeU64(value, field);
+ const out = new Uint8Array(8);
+ new DataView(out.buffer).setBigUint64(0, normalized, false);
+ return out;
+}
+
+function approvalExpiryBytes(value: number | bigint): Uint8Array {
+ return u64Be(value, 'approval expiry');
+}
+
+function pushLengthPrefixed(out: number[], value: BytesLike): void {
+ const bytes = toUint8Array(value);
+ if (bytes.length > 0xffff_ffff) {
+ throw new Error('blind-box AAD field is too large');
+ }
+ out.push((bytes.length >>> 24) & 0xff, (bytes.length >>> 16) & 0xff, (bytes.length >>> 8) & 0xff, bytes.length & 0xff);
+ out.push(...bytes);
+}
+
+function normalizeBlindBoxContext(context: BlindBoxContext): BlindBoxContext {
+ switch (context.purpose) {
+ case 'seal':
+ return standardCreateBlindBoxContext(context.name);
+ case 'agent-deliver': {
+ const approval = normalizeApproval({
+ nonce: context.approvalNonce,
+ expiresAtUnix: context.approvalExpiresAtUnix,
+ });
+ return {
+ purpose: 'agent-deliver',
+ name: validateSecretName(context.name),
+ scopeType: validateNonEmpty(context.scopeType, 'scope type'),
+ scopeRef: validateNonEmpty(context.scopeRef, 'scope ref'),
+ ttlSecs: normalizeU64(context.ttlSecs, 'ttl seconds'),
+ approvalNonce: approval.approvalNonce,
+ approvalExpiresAtUnix: approval.approvalExpiresAtUnix,
+ operationHash: normalizeOperationHash(context.operationHash),
+ };
+ }
+ case 'agent-sign': {
+ const approval = normalizeApproval({
+ nonce: context.approvalNonce,
+ expiresAtUnix: context.approvalExpiresAtUnix,
+ });
+ return {
+ purpose: 'agent-sign',
+ name: validateSecretName(context.name),
+ scopeType: validateNonEmpty(context.scopeType, 'scope type'),
+ scopeRef: validateNonEmpty(context.scopeRef, 'scope ref'),
+ signScheme: context.signScheme,
+ digest: normalizeDigest(context.digest),
+ ttlSecs: normalizeU64(context.ttlSecs, 'ttl seconds'),
+ approvalNonce: approval.approvalNonce,
+ approvalExpiresAtUnix: approval.approvalExpiresAtUnix,
+ operationHash: normalizeOperationHash(context.operationHash),
+ };
+ }
+ default:
+ throw new Error('unsupported blind-box context purpose');
+ }
+}
+
+export function standardCreateBlindBoxContext(name: string): StandardCreateBlindBoxContext {
+ return {
+ purpose: 'seal',
+ name: validateSecretName(name),
+ };
+}
+
+async function normalizeAndCheckOperationHash(
+ expectedFields: BlindBoxOperationHashField[],
+ suppliedHash: HexOrBytes,
+): Promise<Uint8Array> {
+ const supplied = normalizeOperationHash(suppliedHash);
+ const computed = await blindBoxOperationHash(expectedFields);
+ if (bytesToHex(supplied) !== bytesToHex(computed)) {
+ throw new Error('operation hash does not match release operation fields');
+ }
+ return supplied;
+}
+
+async function assertAgentDeliverReleaseHash(context: ProtectedDekDeliveryBlindBoxContext): Promise<void> {
+ const supplied = normalizeOperationHash(context.operationHash);
+ const computed = await blindBoxAgentDeliverOperationHash(context.name, context.ttlSecs);
+ if (bytesToHex(supplied) !== bytesToHex(computed)) {
+ throw new Error('operation hash does not match release operation fields');
+ }
+}
+
+export async function protectedDekReleaseBlindBoxContext(
+ name: string,
+ operation: ProtectedDekReleaseOperation,
+): Promise<ProtectedDekReleaseBlindBoxContext> {
+ const normalizedName = validateSecretName(name);
+ const approval = normalizeApproval(operation.approval);
+
+ switch (operation.kind) {
+ case 'agent-deliver': {
+ const ttlSecs = normalizeU64(operation.ttlSecs, 'ttl seconds');
+ return {
+ purpose: 'agent-deliver',
+ name: normalizedName,
+ scopeType: validateNonEmpty(operation.scopeType, 'scope type'),
+ scopeRef: validateNonEmpty(operation.scopeRef, 'scope ref'),
+ ttlSecs,
+ approvalNonce: approval.approvalNonce,
+ approvalExpiresAtUnix: approval.approvalExpiresAtUnix,
+ operationHash: await normalizeAndCheckOperationHash(
+ ['agent-deliver', normalizedName, u64Be(ttlSecs, 'ttl seconds')],
+ operation.operationHash,
+ ),
+ };
+ }
+ case 'agent-sign': {
+ const digest = normalizeDigest(operation.digest);
+ const ttlSecs = normalizeU64(operation.ttlSecs, 'ttl seconds');
+ return {
+ purpose: 'agent-sign',
+ name: normalizedName,
+ scopeType: validateNonEmpty(operation.scopeType, 'scope type'),
+ scopeRef: validateNonEmpty(operation.scopeRef, 'scope ref'),
+ signScheme: operation.signatureScheme,
+ digest,
+ ttlSecs,
+ approvalNonce: approval.approvalNonce,
+ approvalExpiresAtUnix: approval.approvalExpiresAtUnix,
+ operationHash: await normalizeAndCheckOperationHash(
+ [
+ 'agent-sign',
+ operation.signatureScheme,
+ digest,
+ u64Be(ttlSecs, 'ttl seconds'),
+ ],
+ operation.operationHash,
+ ),
+ };
+ }
+ default:
+ throw new Error('unsupported blind-box release operation');
+ }
+}
+
+export async function blindBoxOperationHash(fields: BlindBoxOperationHashField[]): Promise<Uint8Array> {
+ const encoded: number[] = [];
+ for (const field of fields) {
+ pushLengthPrefixed(encoded, typeof field === 'string' ? utf8(field) : toUint8Array(field));
+ }
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', new Uint8Array(encoded)));
+}
+
+export async function blindBoxAgentDeliverOperationHash(
+ name: string,
+ ttlSecs: number | bigint,
+): Promise<Uint8Array> {
+ return blindBoxOperationHash([
+ 'agent-deliver',
+ validateSecretName(name),
+ u64Be(ttlSecs, 'ttl seconds'),
+ ]);
+}
+
+export async function blindBoxAgentSignOperationHash(
+ signScheme: SignatureScheme,
+ digest: HexOrBytes,
+ ttlSecs: number | bigint,
+): Promise<Uint8Array> {
+ return blindBoxOperationHash([
+ 'agent-sign',
+ signScheme,
+ normalizeDigest(digest),
+ u64Be(ttlSecs, 'ttl seconds'),
+ ]);
+}
+
+export function blindBoxAad(context: BlindBoxContext): Uint8Array {
+ const normalized = normalizeBlindBoxContext(context);
+ const out: number[] = [...utf8(BLIND_BOX_AAD_DOMAIN)];
+ pushLengthPrefixed(out, utf8(normalized.purpose));
+ pushLengthPrefixed(out, utf8(normalized.name));
+ pushLengthPrefixed(out, utf8(WRAP_SCHEME));
+ pushLengthPrefixed(out, new Uint8Array([WRAP_META_VERSION]));
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'agent-deliver' || normalized.purpose === 'agent-sign'
+ ? utf8(normalized.scopeType)
+ : new Uint8Array(),
+ );
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'agent-deliver' || normalized.purpose === 'agent-sign'
+ ? utf8(normalized.scopeRef)
+ : new Uint8Array(),
+ );
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'agent-sign' ? utf8(normalized.signScheme) : new Uint8Array(),
+ );
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'agent-sign' ? normalizeDigest(normalized.digest) : new Uint8Array(),
+ );
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'seal' ? new Uint8Array() : toUint8Array(normalized.approvalNonce, 'approval nonce'),
+ );
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'seal'
+ ? new Uint8Array()
+ : approvalExpiryBytes(normalized.approvalExpiresAtUnix),
+ );
+ pushLengthPrefixed(
+ out,
+ normalized.purpose === 'seal' ? new Uint8Array() : normalizeOperationHash(normalized.operationHash),
+ );
+ return new Uint8Array(out);
+}
+
+export function blindBoxAadHex(context: BlindBoxContext): string {
+ return bytesToHex(blindBoxAad(context));
+}
+
+export function signDigest(
+ privateKey: HexOrBytes,
+ digest: HexOrBytes,
+ scheme: SignatureScheme,
+ options: SignDigestOptions = {},
+): SignatureResult {
+ const key = normalizePrivateKey(privateKey);
+ try {
+ const msg = normalizeDigest(digest);
+ if (scheme === SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE) {
+ const recovered = secp256k1.sign(msg, key, { prehash: false, lowS: true, format: 'recovered' });
+ return {
+ scheme,
+ signature: bytesToHex(recovered.slice(1)),
+ recovery_id: recovered[0] ?? null,
+ };
+ }
+ if (scheme === SIGN_SCHEME_ECDSA_SECP256K1_DER) {
+ return {
+ scheme,
+ signature: bytesToHex(secp256k1.sign(msg, key, { prehash: false, lowS: true, format: 'der' })),
+ recovery_id: null,
+ };
+ }
+ if (scheme === SIGN_SCHEME_SCHNORR_SECP256K1_BIP340) {
+ const aux = options.schnorrAuxRand
+ ? normalizeHexOrBytes(options.schnorrAuxRand, 'schnorr aux randomness')
+ : undefined;
+ if (aux) {
+ assertLength(aux, KEY_BYTES, 'schnorr aux randomness');
+ }
+ return {
+ scheme,
+ signature: bytesToHex(schnorr.sign(msg, key, aux)),
+ recovery_id: null,
+ };
+ }
+ throw new Error('unsupported signing scheme');
+ } finally {
+ key.fill(0);
+ }
+}
+
+export async function signProtectedDigest(
+ sealedKey: ProtectedSealed,
+ vmk: BytesLike,
+ context: ProtectedRecordContext,
+ digest: BytesLike | string,
+ scheme: SignatureScheme,
+ options: SignDigestOptions = {},
+): Promise<SignatureResult> {
+ const privateKey = await openProtected(sealedKey, vmk, context);
+ try {
+ return signDigest(privateKey, digest, scheme, options);
+ } finally {
+ privateKey.fill(0);
+ }
+}
diff --git a/ui/tsconfig.app.json b/ui/tsconfig.app.json
index a54a98377..a48dee479 100644
--- a/ui/tsconfig.app.json
+++ b/ui/tsconfig.app.json
@@ -28,5 +28,6 @@
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
- "include": ["src"]
+ "include": ["src"],
+ "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"]
}