@agimon-ai/doompi-web-security 0.0.1-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +92 -0
  3. package/dist/_virtual/_rolldown/runtime.cjs +1 -0
  4. package/dist/adapters/browserBundleVerifier.cjs +2 -0
  5. package/dist/adapters/browserBundleVerifier.cjs.map +1 -0
  6. package/dist/adapters/browserBundleVerifier.d.cts +45 -0
  7. package/dist/adapters/browserBundleVerifier.d.cts.map +1 -0
  8. package/dist/adapters/browserBundleVerifier.d.mts +45 -0
  9. package/dist/adapters/browserBundleVerifier.d.mts.map +1 -0
  10. package/dist/adapters/browserBundleVerifier.mjs +2 -0
  11. package/dist/adapters/browserBundleVerifier.mjs.map +1 -0
  12. package/dist/adapters/browserSealedChannel.cjs +2 -0
  13. package/dist/adapters/browserSealedChannel.cjs.map +1 -0
  14. package/dist/adapters/browserSealedChannel.d.cts +36 -0
  15. package/dist/adapters/browserSealedChannel.d.cts.map +1 -0
  16. package/dist/adapters/browserSealedChannel.d.mts +36 -0
  17. package/dist/adapters/browserSealedChannel.d.mts.map +1 -0
  18. package/dist/adapters/browserSealedChannel.mjs +2 -0
  19. package/dist/adapters/browserSealedChannel.mjs.map +1 -0
  20. package/dist/adapters/bundleSigner.cjs +2 -0
  21. package/dist/adapters/bundleSigner.cjs.map +1 -0
  22. package/dist/adapters/bundleSigner.d.cts +18 -0
  23. package/dist/adapters/bundleSigner.d.cts.map +1 -0
  24. package/dist/adapters/bundleSigner.d.mts +18 -0
  25. package/dist/adapters/bundleSigner.d.mts.map +1 -0
  26. package/dist/adapters/bundleSigner.mjs +2 -0
  27. package/dist/adapters/bundleSigner.mjs.map +1 -0
  28. package/dist/adapters/nodeSealedChannel.cjs +2 -0
  29. package/dist/adapters/nodeSealedChannel.cjs.map +1 -0
  30. package/dist/adapters/nodeSealedChannel.d.cts +40 -0
  31. package/dist/adapters/nodeSealedChannel.d.cts.map +1 -0
  32. package/dist/adapters/nodeSealedChannel.d.mts +40 -0
  33. package/dist/adapters/nodeSealedChannel.d.mts.map +1 -0
  34. package/dist/adapters/nodeSealedChannel.mjs +2 -0
  35. package/dist/adapters/nodeSealedChannel.mjs.map +1 -0
  36. package/dist/adapters/sealedTransport.cjs +2 -0
  37. package/dist/adapters/sealedTransport.cjs.map +1 -0
  38. package/dist/adapters/sealedTransport.d.cts +43 -0
  39. package/dist/adapters/sealedTransport.d.cts.map +1 -0
  40. package/dist/adapters/sealedTransport.d.mts +43 -0
  41. package/dist/adapters/sealedTransport.d.mts.map +1 -0
  42. package/dist/adapters/sealedTransport.mjs +2 -0
  43. package/dist/adapters/sealedTransport.mjs.map +1 -0
  44. package/dist/browser.cjs +1 -0
  45. package/dist/browser.d.cts +5 -0
  46. package/dist/browser.d.mts +5 -0
  47. package/dist/browser.mjs +1 -0
  48. package/dist/index.cjs +1 -0
  49. package/dist/index.d.cts +4 -0
  50. package/dist/index.d.mts +4 -0
  51. package/dist/index.mjs +1 -0
  52. package/dist/node.cjs +1 -0
  53. package/dist/node.d.cts +3 -0
  54. package/dist/node.d.mts +3 -0
  55. package/dist/node.mjs +1 -0
  56. package/dist/services/serialQueue.cjs +2 -0
  57. package/dist/services/serialQueue.cjs.map +1 -0
  58. package/dist/services/serialQueue.d.cts +23 -0
  59. package/dist/services/serialQueue.d.cts.map +1 -0
  60. package/dist/services/serialQueue.d.mts +23 -0
  61. package/dist/services/serialQueue.d.mts.map +1 -0
  62. package/dist/services/serialQueue.mjs +2 -0
  63. package/dist/services/serialQueue.mjs.map +1 -0
  64. package/dist/types/bundleManifest.cjs +3 -0
  65. package/dist/types/bundleManifest.cjs.map +1 -0
  66. package/dist/types/bundleManifest.d.cts +45 -0
  67. package/dist/types/bundleManifest.d.cts.map +1 -0
  68. package/dist/types/bundleManifest.d.mts +45 -0
  69. package/dist/types/bundleManifest.d.mts.map +1 -0
  70. package/dist/types/bundleManifest.mjs +3 -0
  71. package/dist/types/bundleManifest.mjs.map +1 -0
  72. package/dist/types/sealedChannel.cjs +2 -0
  73. package/dist/types/sealedChannel.cjs.map +1 -0
  74. package/dist/types/sealedChannel.d.cts +77 -0
  75. package/dist/types/sealedChannel.d.cts.map +1 -0
  76. package/dist/types/sealedChannel.d.mts +77 -0
  77. package/dist/types/sealedChannel.d.mts.map +1 -0
  78. package/dist/types/sealedChannel.mjs +2 -0
  79. package/dist/types/sealedChannel.mjs.map +1 -0
  80. package/llms.txt +9 -0
  81. package/package.json +76 -0
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vuong Ngo
4
+ Copyright (c) 2026 pulseaiclub
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # @agimon-ai/doompi-web-security
2
+
3
+ Shared security primitives for the DoomPi web cockpit: the sealed-channel envelope, its `node:crypto`
4
+ and WebCrypto halves, and the signed bundle manifest.
5
+
6
+ This package holds no policy and starts nothing. It exists because three different programs need to
7
+ agree byte for byte on the same crypto: the cockpit hub (Node), the cockpit page (browser), and every
8
+ web plugin bundled into that page.
9
+
10
+ ## Why it is a package
11
+
12
+ A plugin in another package cannot import from a client application, and the sealed transport is a
13
+ module singleton whose nonce counters every caller must share. A second copy would start counting at
14
+ zero and the receiver would reject everything it sent as a replay. One package, deduped in the
15
+ bundle, is what makes that impossible.
16
+
17
+ ## Subpaths
18
+
19
+ | Import | Runs where | What it carries |
20
+ | ---------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------- |
21
+ | `@agimon-ai/doompi-web-security` | both | The envelope contract, the bundle manifest shape, the canonical serialization both sides sign and verify |
22
+ | `@agimon-ai/doompi-web-security/browser` | the page | The WebCrypto channel and `sealedTransport`, the shared instance plugins use |
23
+ | `@agimon-ai/doompi-web-security/node` | the hub | The `node:crypto` channel, the host handshake, and the bundle signer |
24
+
25
+ ## The sealed channel
26
+
27
+ A hosted tunnel terminates TLS at its provider's edge, so without application sealing everything the
28
+ cockpit carries is plaintext to them. Sealing the payload underneath their TLS leaves them a relay that
29
+ sees timing and sizes but not content.
30
+
31
+ The QR pairing path anchors key exchange out of band. The host's ephemeral P-256 public key is printed on
32
+ the screen the user is holding, so the relay cannot substitute its own. A returning device instead receives
33
+ the current public key after proving a passkey. That path depends on the trusted code-delivery edge described
34
+ above, and the key itself is public rather than secret.
35
+
36
+ Three properties worth knowing, because getting any of them wrong is silent:
37
+
38
+ - **Separate keys per direction.** Derived with different HKDF info strings, so a message the server
39
+ sent can never be replayed back at it as though the client had sent it.
40
+ - **Nonces are a random per-channel prefix plus a monotonic counter**, never random per message. A
41
+ repeated nonce under one AES-GCM key leaks the XOR of two plaintexts and the authentication subkey;
42
+ 96 bits is small enough that random nonces collide at a rate worth caring about.
43
+ - **Both directions are serialized.** Sealing advances the counter and opening demands it strictly
44
+ increase, so overlapping asynchronous calls are a correctness bug, not a race worth tolerating.
45
+ `createSerialQueue` is what prevents a burst of socket sends from reordering into a self-inflicted
46
+ replay.
47
+
48
+ Every failure names itself. A decryption failure otherwise shows up as a blank page with nothing to
49
+ go on.
50
+
51
+ ## The signed bundle-manifest primitive
52
+
53
+ The Node signer traverses a public asset root without following symlinks, requires `/index.html`, hashes each
54
+ byte sequence, and signs a strict canonical manifest v2 with ECDSA P-256. Revision state and the private key
55
+ are persisted atomically at mode `0600`; malformed or replaced state fails closed instead of rotating
56
+ silently.
57
+
58
+ The browser verifier accepts only the public SPKI and minimum revision pinned by the physical QR. DoomPi's
59
+ package-owned service worker verifies the envelope and every asset before committing a Cache Storage revision,
60
+ then atomically records the active bundle in IndexedDB. A same-revision digest conflict, signer mismatch,
61
+ missing cache, bad MIME metadata, length mismatch, or hash mismatch is refused. The last-known-good bundle
62
+ remains active during a failed refresh.
63
+
64
+ This does not make the package-owned bootstrap self-protecting. A TLS edge that replaces `/pair` or `/sw.js`
65
+ could remove the verifier before it runs. Once the intended bootstrap is installed, however, host and plugin
66
+ JavaScript cannot execute until its signed bytes pass verification.
67
+
68
+ `canonicalManifest` is hand-rolled rather than `JSON.stringify` of the whole object, because a signature
69
+ is only worth anything if signer and verifier agree byte for byte, and key order in a JSON object is an
70
+ implementation detail.
71
+
72
+ ## Public API
73
+
74
+ ```ts
75
+ import { canonicalManifest, describeSealedFailure, isSealedEnvelope } from '@agimon-ai/doompi-web-security';
76
+ import { sealedTransport } from '@agimon-ai/doompi-web-security/browser';
77
+ import { createBundleSigner, createHostHandshake } from '@agimon-ai/doompi-web-security/node';
78
+ ```
79
+
80
+ ## Development
81
+
82
+ ```bash
83
+ pnpm build
84
+ pnpm typecheck
85
+ pnpm test
86
+ pnpm lint
87
+ ```
88
+
89
+ The round-trip test is the one that matters: it seals with `node:crypto` and opens with real
90
+ WebCrypto, so the two implementations cannot drift apart without a failure.
91
+
92
+ Maintained by [Agimon](https://agimon.ai/about).
@@ -0,0 +1 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));exports.__toESM=s;
@@ -0,0 +1,2 @@
1
+ const e=require("../types/bundleManifest.cjs");function t(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=t.padEnd(Math.ceil(t.length/4)*4,`=`),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e+=1)i[e]=r.charCodeAt(e);return i.buffer}function n(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function r(n,r,i=0){if(!e.isSignedBundleManifest(n))return{ok:!1,failure:{code:`invalid-envelope`}};let a=n;if(a.publicKey!==r)return{ok:!1,failure:{code:`untrusted-public-key`}};if(!Number.isSafeInteger(i)||i<0||a.manifest.revision<i)return{ok:!1,failure:{code:`stale-revision`,minimumRevision:i,actualRevision:a.manifest.revision}};let o;try{o=await crypto.subtle.importKey(`spki`,t(r),{name:`ECDSA`,namedCurve:`P-256`},!1,[`verify`])}catch{return{ok:!1,failure:{code:`invalid-public-key`}}}try{return await crypto.subtle.verify({name:`ECDSA`,hash:`SHA-256`},o,t(a.signature),new TextEncoder().encode(e.canonicalManifest(a.manifest)))?{ok:!0,manifest:a.manifest}:{ok:!1,failure:{code:`invalid-signature`}}}catch{return{ok:!1,failure:{code:`invalid-signature`}}}}async function i(t,r,i){let a=e.assetFor(t,r);return a===void 0?{ok:!1,failure:{code:`asset-not-listed`,path:r}}:i.byteLength===a.byteLength?n(await crypto.subtle.digest(`SHA-256`,i))===a.sha256?{ok:!0}:{ok:!1,failure:{code:`digest-mismatch`}}:{ok:!1,failure:{code:`byte-length-mismatch`,expected:a.byteLength,actual:i.byteLength}}}exports.verifyBundleAsset=i,exports.verifySignedBundleManifest=r;
2
+ //# sourceMappingURL=browserBundleVerifier.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserBundleVerifier.cjs","names":["isSignedBundleManifest","canonicalManifest","assetFor"],"sources":["../../src/adapters/browserBundleVerifier.ts"],"sourcesContent":["import {\n type BundleManifest,\n type SignedBundleManifest,\n assetFor,\n canonicalManifest,\n isSignedBundleManifest,\n} from '../types/bundleManifest.ts';\n\nexport type BundleVerificationFailure =\n | { code: 'invalid-envelope' }\n | { code: 'untrusted-public-key' }\n | { code: 'stale-revision'; minimumRevision: number; actualRevision: number }\n | { code: 'invalid-public-key' }\n | { code: 'invalid-signature' };\n\nexport type BundleVerificationResult =\n | { ok: true; manifest: BundleManifest }\n | { ok: false; failure: BundleVerificationFailure };\n\nexport type BundleAssetVerificationFailure =\n | { code: 'asset-not-listed'; path: string }\n | { code: 'byte-length-mismatch'; expected: number; actual: number }\n | { code: 'digest-mismatch' };\n\nexport type BundleAssetVerificationResult = { ok: true } | { ok: false; failure: BundleAssetVerificationFailure };\n\nfunction decodeBase64Url(value: string): ArrayBuffer {\n const standard = value.replaceAll('-', '+').replaceAll('_', '/');\n const padded = standard.padEnd(Math.ceil(standard.length / 4) * 4, '=');\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes.buffer;\n}\n\nfunction hex(bytes: ArrayBuffer): string {\n return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/** Verifies a strict envelope against a separately trusted key and revision floor. */\nexport async function verifySignedBundleManifest(\n value: unknown,\n trustedPublicKey: string,\n minimumRevision = 0,\n): Promise<BundleVerificationResult> {\n if (!isSignedBundleManifest(value)) return { ok: false, failure: { code: 'invalid-envelope' } };\n const signed: SignedBundleManifest = value;\n if (signed.publicKey !== trustedPublicKey) return { ok: false, failure: { code: 'untrusted-public-key' } };\n if (!Number.isSafeInteger(minimumRevision) || minimumRevision < 0 || signed.manifest.revision < minimumRevision) {\n return {\n ok: false,\n failure: { code: 'stale-revision', minimumRevision, actualRevision: signed.manifest.revision },\n };\n }\n\n let key: CryptoKey;\n try {\n key = await crypto.subtle.importKey(\n 'spki',\n decodeBase64Url(trustedPublicKey),\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['verify'],\n );\n } catch {\n return { ok: false, failure: { code: 'invalid-public-key' } };\n }\n\n try {\n const verified = await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n key,\n decodeBase64Url(signed.signature),\n new TextEncoder().encode(canonicalManifest(signed.manifest)),\n );\n return verified ? { ok: true, manifest: signed.manifest } : { ok: false, failure: { code: 'invalid-signature' } };\n } catch {\n return { ok: false, failure: { code: 'invalid-signature' } };\n }\n}\n\n/** Verifies fetched raw response bytes against an authenticated manifest. */\nexport async function verifyBundleAsset(\n manifest: BundleManifest,\n assetPath: string,\n bytes: ArrayBuffer,\n): Promise<BundleAssetVerificationResult> {\n const asset = assetFor(manifest, assetPath);\n if (asset === undefined) return { ok: false, failure: { code: 'asset-not-listed', path: assetPath } };\n if (bytes.byteLength !== asset.byteLength) {\n return {\n ok: false,\n failure: { code: 'byte-length-mismatch', expected: asset.byteLength, actual: bytes.byteLength },\n };\n }\n const digest = hex(await crypto.subtle.digest('SHA-256', bytes));\n return digest === asset.sha256 ? { ok: true } : { ok: false, failure: { code: 'digest-mismatch' } };\n}\n"],"mappings":"+CA0BA,SAAS,EAAgB,EAA4B,CACnD,IAAM,EAAW,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,EACzD,EAAS,EAAS,OAAO,KAAK,KAAK,EAAS,OAAS,CAAC,EAAI,EAAG,GAAG,EAChE,EA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,EAAI,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,CAAE,CAClH,MAAQ,CACN,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,CAAE,CAC7D,CACF,CAGA,eAAsB,EACpB,EACA,EACA,EACwC,CACxC,IAAM,EAAQC,EAAAA,SAAS,EAAU,CAAS,EAS1C,OARI,IAAU,IAAA,GAAkB,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,KAAM,CAAU,CAAE,EAChG,EAAM,aAAe,EAAM,WAMhB,EAAI,MAAM,OAAO,OAAO,OAAO,UAAW,CAAK,CAClD,IAAM,EAAM,OAAS,CAAE,GAAI,EAAK,EAAI,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,iBAAkB,CAAE,EANzF,CACL,GAAI,GACJ,QAAS,CAAE,KAAM,uBAAwB,SAAU,EAAM,WAAY,OAAQ,EAAM,UAAW,CAChG,CAIJ"}
@@ -0,0 +1,45 @@
1
+ import { BundleManifest } from "../types/bundleManifest.cjs";
2
+ //#region src/adapters/browserBundleVerifier.d.ts
3
+ type BundleVerificationFailure = {
4
+ code: 'invalid-envelope';
5
+ } | {
6
+ code: 'untrusted-public-key';
7
+ } | {
8
+ code: 'stale-revision';
9
+ minimumRevision: number;
10
+ actualRevision: number;
11
+ } | {
12
+ code: 'invalid-public-key';
13
+ } | {
14
+ code: 'invalid-signature';
15
+ };
16
+ type BundleVerificationResult = {
17
+ ok: true;
18
+ manifest: BundleManifest;
19
+ } | {
20
+ ok: false;
21
+ failure: BundleVerificationFailure;
22
+ };
23
+ type BundleAssetVerificationFailure = {
24
+ code: 'asset-not-listed';
25
+ path: string;
26
+ } | {
27
+ code: 'byte-length-mismatch';
28
+ expected: number;
29
+ actual: number;
30
+ } | {
31
+ code: 'digest-mismatch';
32
+ };
33
+ type BundleAssetVerificationResult = {
34
+ ok: true;
35
+ } | {
36
+ ok: false;
37
+ failure: BundleAssetVerificationFailure;
38
+ };
39
+ /** Verifies a strict envelope against a separately trusted key and revision floor. */
40
+ declare function verifySignedBundleManifest(value: unknown, trustedPublicKey: string, minimumRevision?: number): Promise<BundleVerificationResult>;
41
+ /** Verifies fetched raw response bytes against an authenticated manifest. */
42
+ declare function verifyBundleAsset(manifest: BundleManifest, assetPath: string, bytes: ArrayBuffer): Promise<BundleAssetVerificationResult>;
43
+ //#endregion
44
+ export { BundleAssetVerificationFailure, BundleAssetVerificationResult, BundleVerificationFailure, BundleVerificationResult, verifyBundleAsset, verifySignedBundleManifest };
45
+ //# sourceMappingURL=browserBundleVerifier.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserBundleVerifier.d.cts","names":[],"sources":["../../src/adapters/browserBundleVerifier.ts"],"mappings":";;KAQY;EACN;;EACA;;EACA;EAAwB;EAAyB;;EACjD;;EACA;;KAEM;EACN;EAAU,UAAU;;EACpB;EAAW,SAAS;;KAEd;EACN;EAA0B;;EAC1B;EAA8B;EAAkB;;EAChD;;KAEM;EAAkC;;EAAe;EAAW,SAAS;;;iBAgB3D,2BACpB,gBACA,0BACA,2BACC,QAAQ;;iBAsCW,kBACpB,UAAU,gBACV,mBACA,OAAO,cACN,QAAQ"}
@@ -0,0 +1,45 @@
1
+ import { BundleManifest } from "../types/bundleManifest.mjs";
2
+ //#region src/adapters/browserBundleVerifier.d.ts
3
+ type BundleVerificationFailure = {
4
+ code: 'invalid-envelope';
5
+ } | {
6
+ code: 'untrusted-public-key';
7
+ } | {
8
+ code: 'stale-revision';
9
+ minimumRevision: number;
10
+ actualRevision: number;
11
+ } | {
12
+ code: 'invalid-public-key';
13
+ } | {
14
+ code: 'invalid-signature';
15
+ };
16
+ type BundleVerificationResult = {
17
+ ok: true;
18
+ manifest: BundleManifest;
19
+ } | {
20
+ ok: false;
21
+ failure: BundleVerificationFailure;
22
+ };
23
+ type BundleAssetVerificationFailure = {
24
+ code: 'asset-not-listed';
25
+ path: string;
26
+ } | {
27
+ code: 'byte-length-mismatch';
28
+ expected: number;
29
+ actual: number;
30
+ } | {
31
+ code: 'digest-mismatch';
32
+ };
33
+ type BundleAssetVerificationResult = {
34
+ ok: true;
35
+ } | {
36
+ ok: false;
37
+ failure: BundleAssetVerificationFailure;
38
+ };
39
+ /** Verifies a strict envelope against a separately trusted key and revision floor. */
40
+ declare function verifySignedBundleManifest(value: unknown, trustedPublicKey: string, minimumRevision?: number): Promise<BundleVerificationResult>;
41
+ /** Verifies fetched raw response bytes against an authenticated manifest. */
42
+ declare function verifyBundleAsset(manifest: BundleManifest, assetPath: string, bytes: ArrayBuffer): Promise<BundleAssetVerificationResult>;
43
+ //#endregion
44
+ export { BundleAssetVerificationFailure, BundleAssetVerificationResult, BundleVerificationFailure, BundleVerificationResult, verifyBundleAsset, verifySignedBundleManifest };
45
+ //# sourceMappingURL=browserBundleVerifier.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserBundleVerifier.d.mts","names":[],"sources":["../../src/adapters/browserBundleVerifier.ts"],"mappings":";;KAQY;EACN;;EACA;;EACA;EAAwB;EAAyB;;EACjD;;EACA;;KAEM;EACN;EAAU,UAAU;;EACpB;EAAW,SAAS;;KAEd;EACN;EAA0B;;EAC1B;EAA8B;EAAkB;;EAChD;;KAEM;EAAkC;;EAAe;EAAW,SAAS;;;iBAgB3D,2BACpB,gBACA,0BACA,2BACC,QAAQ;;iBAsCW,kBACpB,UAAU,gBACV,mBACA,OAAO,cACN,QAAQ"}
@@ -0,0 +1,2 @@
1
+ import{assetFor as e,canonicalManifest as t,isSignedBundleManifest as n}from"../types/bundleManifest.mjs";function r(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=t.padEnd(Math.ceil(t.length/4)*4,`=`),r=atob(n),i=new Uint8Array(r.length);for(let e=0;e<r.length;e+=1)i[e]=r.charCodeAt(e);return i.buffer}function i(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function a(e,i,a=0){if(!n(e))return{ok:!1,failure:{code:`invalid-envelope`}};let o=e;if(o.publicKey!==i)return{ok:!1,failure:{code:`untrusted-public-key`}};if(!Number.isSafeInteger(a)||a<0||o.manifest.revision<a)return{ok:!1,failure:{code:`stale-revision`,minimumRevision:a,actualRevision:o.manifest.revision}};let s;try{s=await crypto.subtle.importKey(`spki`,r(i),{name:`ECDSA`,namedCurve:`P-256`},!1,[`verify`])}catch{return{ok:!1,failure:{code:`invalid-public-key`}}}try{return await crypto.subtle.verify({name:`ECDSA`,hash:`SHA-256`},s,r(o.signature),new TextEncoder().encode(t(o.manifest)))?{ok:!0,manifest:o.manifest}:{ok:!1,failure:{code:`invalid-signature`}}}catch{return{ok:!1,failure:{code:`invalid-signature`}}}}async function o(t,n,r){let a=e(t,n);return a===void 0?{ok:!1,failure:{code:`asset-not-listed`,path:n}}:r.byteLength===a.byteLength?i(await crypto.subtle.digest(`SHA-256`,r))===a.sha256?{ok:!0}:{ok:!1,failure:{code:`digest-mismatch`}}:{ok:!1,failure:{code:`byte-length-mismatch`,expected:a.byteLength,actual:r.byteLength}}}export{o as verifyBundleAsset,a as verifySignedBundleManifest};
2
+ //# sourceMappingURL=browserBundleVerifier.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserBundleVerifier.mjs","names":[],"sources":["../../src/adapters/browserBundleVerifier.ts"],"sourcesContent":["import {\n type BundleManifest,\n type SignedBundleManifest,\n assetFor,\n canonicalManifest,\n isSignedBundleManifest,\n} from '../types/bundleManifest.ts';\n\nexport type BundleVerificationFailure =\n | { code: 'invalid-envelope' }\n | { code: 'untrusted-public-key' }\n | { code: 'stale-revision'; minimumRevision: number; actualRevision: number }\n | { code: 'invalid-public-key' }\n | { code: 'invalid-signature' };\n\nexport type BundleVerificationResult =\n | { ok: true; manifest: BundleManifest }\n | { ok: false; failure: BundleVerificationFailure };\n\nexport type BundleAssetVerificationFailure =\n | { code: 'asset-not-listed'; path: string }\n | { code: 'byte-length-mismatch'; expected: number; actual: number }\n | { code: 'digest-mismatch' };\n\nexport type BundleAssetVerificationResult = { ok: true } | { ok: false; failure: BundleAssetVerificationFailure };\n\nfunction decodeBase64Url(value: string): ArrayBuffer {\n const standard = value.replaceAll('-', '+').replaceAll('_', '/');\n const padded = standard.padEnd(Math.ceil(standard.length / 4) * 4, '=');\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes.buffer;\n}\n\nfunction hex(bytes: ArrayBuffer): string {\n return [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/** Verifies a strict envelope against a separately trusted key and revision floor. */\nexport async function verifySignedBundleManifest(\n value: unknown,\n trustedPublicKey: string,\n minimumRevision = 0,\n): Promise<BundleVerificationResult> {\n if (!isSignedBundleManifest(value)) return { ok: false, failure: { code: 'invalid-envelope' } };\n const signed: SignedBundleManifest = value;\n if (signed.publicKey !== trustedPublicKey) return { ok: false, failure: { code: 'untrusted-public-key' } };\n if (!Number.isSafeInteger(minimumRevision) || minimumRevision < 0 || signed.manifest.revision < minimumRevision) {\n return {\n ok: false,\n failure: { code: 'stale-revision', minimumRevision, actualRevision: signed.manifest.revision },\n };\n }\n\n let key: CryptoKey;\n try {\n key = await crypto.subtle.importKey(\n 'spki',\n decodeBase64Url(trustedPublicKey),\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['verify'],\n );\n } catch {\n return { ok: false, failure: { code: 'invalid-public-key' } };\n }\n\n try {\n const verified = await crypto.subtle.verify(\n { name: 'ECDSA', hash: 'SHA-256' },\n key,\n decodeBase64Url(signed.signature),\n new TextEncoder().encode(canonicalManifest(signed.manifest)),\n );\n return verified ? { ok: true, manifest: signed.manifest } : { ok: false, failure: { code: 'invalid-signature' } };\n } catch {\n return { ok: false, failure: { code: 'invalid-signature' } };\n }\n}\n\n/** Verifies fetched raw response bytes against an authenticated manifest. */\nexport async function verifyBundleAsset(\n manifest: BundleManifest,\n assetPath: string,\n bytes: ArrayBuffer,\n): Promise<BundleAssetVerificationResult> {\n const asset = assetFor(manifest, assetPath);\n if (asset === undefined) return { ok: false, failure: { code: 'asset-not-listed', path: assetPath } };\n if (bytes.byteLength !== asset.byteLength) {\n return {\n ok: false,\n failure: { code: 'byte-length-mismatch', expected: asset.byteLength, actual: bytes.byteLength },\n };\n }\n const digest = hex(await crypto.subtle.digest('SHA-256', bytes));\n return digest === asset.sha256 ? { ok: true } : { ok: false, failure: { code: 'digest-mismatch' } };\n}\n"],"mappings":"0GA0BA,SAAS,EAAgB,EAA4B,CACnD,IAAM,EAAW,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,EACzD,EAAS,EAAS,OAAO,KAAK,KAAK,EAAS,OAAS,CAAC,EAAI,EAAG,GAAG,EAChE,EAAS,KAAK,CAAM,EACpB,EAAQ,IAAI,WAAW,EAAO,MAAM,EAC1C,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,EAAM,GAAS,EAAO,WAAW,CAAK,EAC7F,OAAO,EAAM,MACf,CAEA,SAAS,EAAI,EAA4B,CACvC,MAAO,CAAC,GAAG,IAAI,WAAW,CAAK,CAAC,CAAC,CAAC,IAAK,GAAS,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAC7F,CAGA,eAAsB,EACpB,EACA,EACA,EAAkB,EACiB,CACnC,GAAI,CAAC,EAAuB,CAAK,EAAG,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,kBAAmB,CAAE,EAC9F,IAAM,EAA+B,EACrC,GAAI,EAAO,YAAc,EAAkB,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,sBAAuB,CAAE,EACzG,GAAI,CAAC,OAAO,cAAc,CAAe,GAAK,EAAkB,GAAK,EAAO,SAAS,SAAW,EAC9F,MAAO,CACL,GAAI,GACJ,QAAS,CAAE,KAAM,iBAAkB,kBAAiB,eAAgB,EAAO,SAAS,QAAS,CAC/F,EAGF,IAAI,EACJ,GAAI,CACF,EAAM,MAAM,OAAO,OAAO,UACxB,OACA,EAAgB,CAAgB,EAChC,CAAE,KAAM,QAAS,WAAY,OAAQ,EACrC,GACA,CAAC,QAAQ,CACX,CACF,MAAQ,CACN,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,oBAAqB,CAAE,CAC9D,CAEA,GAAI,CAOF,OAAO,MANgB,OAAO,OAAO,OACnC,CAAE,KAAM,QAAS,KAAM,SAAU,EACjC,EACA,EAAgB,EAAO,SAAS,EAChC,IAAI,YAAY,CAAC,CAAC,OAAO,EAAkB,EAAO,QAAQ,CAAC,CAC7D,EACkB,CAAE,GAAI,GAAM,SAAU,EAAO,QAAS,EAAI,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,CAAE,CAClH,MAAQ,CACN,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,CAAE,CAC7D,CACF,CAGA,eAAsB,EACpB,EACA,EACA,EACwC,CACxC,IAAM,EAAQ,EAAS,EAAU,CAAS,EAS1C,OARI,IAAU,IAAA,GAAkB,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,KAAM,CAAU,CAAE,EAChG,EAAM,aAAe,EAAM,WAMhB,EAAI,MAAM,OAAO,OAAO,OAAO,UAAW,CAAK,CAClD,IAAM,EAAM,OAAS,CAAE,GAAI,EAAK,EAAI,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,iBAAkB,CAAE,EANzF,CACL,GAAI,GACJ,QAAS,CAAE,KAAM,uBAAwB,SAAU,EAAM,WAAY,OAAQ,EAAM,UAAW,CAChG,CAIJ"}
@@ -0,0 +1,2 @@
1
+ const e=require("../types/sealedChannel.cjs"),t={name:`ECDH`,namedCurve:`P-256`},n=`AES-GCM`;function r(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function i(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function a(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function o(t,r){let i=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:a(new TextEncoder().encode(`doompi/sealed/v1`)),info:a(new TextEncoder().encode(e.infoFor(r)))},i,{name:n,length:256},!1,[`encrypt`,`decrypt`])}function s(e,t){let n=new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function c(t,o,c){let l=0n,u=-1n;return{async seal(r){if(l>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let o=s(c,l),u=await crypto.subtle.encrypt({name:n,iv:a(o),tagLength:128},t,a(r));return l+=1n,{ok:!0,envelope:{v:1,n:i(o),c:i(new Uint8Array(u))}}},async open(t){let i=t;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(t))return{ok:!1,failure:`malformed`};let s=r(t.n),c=r(t.c);if(s===void 0||c===void 0||s.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(a(s)).getBigUint64(4,!1);if(l<=u)return{ok:!1,failure:`replay`};let d;try{d=await crypto.subtle.decrypt({name:n,iv:a(s),tagLength:128},o,a(c))}catch{return{ok:!1,failure:`auth`}}return u=l,{ok:!0,plaintext:new Uint8Array(d)}}}}async function l(e){if(globalThis.crypto?.subtle!==void 0)try{let n=await crypto.subtle.generateKey(t,!1,[`deriveBits`]),s=r(e);if(s===void 0)return;let l=await crypto.subtle.importKey(`raw`,a(s),t,!1,[]),u=await crypto.subtle.deriveBits({name:`ECDH`,public:l},n.privateKey,256),d=i(new Uint8Array(await crypto.subtle.exportKey(`raw`,n.publicKey)));return{channel:c(await o(u,`c2s`),await o(u,`s2c`),new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function u(e,t,n){return c(await o(e,t),await o(e,t===`c2s`?`s2c`:`c2s`),n)}exports.channelFromSecret=u,exports.connectSealedChannel=l;
2
+ //# sourceMappingURL=browserSealedChannel.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserSealedChannel.cjs","names":["infoFor","MAX_MESSAGES_PER_KEY","isSealedEnvelope"],"sources":["../../src/adapters/browserSealedChannel.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../types/sealedChannel.ts';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'doompi/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"8CAuBM,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpD,EAAS,UAef,SAAS,EAAM,EAAuC,CACpD,IAAI,EACJ,GAAI,CACF,EAAS,KAAK,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAM,EAAM,IAAI,WAAW,IAAI,YAAY,EAAO,MAAM,CAAC,EACzD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,EAAI,GAAS,EAAO,WAAW,CAAK,EAC3F,OAAO,CACT,CAEA,SAAS,EAAU,EAA2B,CAC5C,IAAI,EAAS,GACb,IAAK,IAAM,KAAQ,EAAO,GAAU,OAAO,aAAa,CAAI,EAC5D,OAAO,KAAK,CAAM,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,EAAE,CAClF,CAEA,SAAS,EAAK,EAAgC,CAC5C,IAAM,EAAO,IAAI,WAAW,IAAI,YAAY,EAAM,MAAM,CAAC,EAEzD,OADA,EAAK,IAAI,CAAK,EACP,EAAK,MACd,CAEA,eAAe,EAAO,EAAqB,EAAg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,EACtG,MAAO,CACL,QAAS,EACP,MAAM,EAAO,EAAQ,KAAK,EAC1B,MAAM,EAAO,EAAQ,KAAK,EAC1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsB,EACpB,EACA,EACA,EACwB,CAGxB,OAAO,EAAY,MAFA,EAAO,EAAQ,CAAa,EAEtB,MADH,EAAO,EAAQ,IAAkB,MAAQ,MAAQ,KAAK,EAC1C,CAAW,CAC/C"}
@@ -0,0 +1,36 @@
1
+ import { SealedDirection, SealedEnvelope, SealedFailure } from "../types/sealedChannel.cjs";
2
+ //#region src/adapters/browserSealedChannel.d.ts
3
+ type SealResult = {
4
+ ok: true;
5
+ envelope: SealedEnvelope;
6
+ } | {
7
+ ok: false;
8
+ failure: SealedFailure;
9
+ };
10
+ type OpenResult = {
11
+ ok: true;
12
+ plaintext: Uint8Array;
13
+ } | {
14
+ ok: false;
15
+ failure: SealedFailure;
16
+ };
17
+ interface SealedChannel {
18
+ seal(plaintext: Uint8Array): Promise<SealResult>;
19
+ open(envelope: unknown): Promise<OpenResult>;
20
+ }
21
+ /**
22
+ * Completes the handshake against the host key read out of the QR fragment.
23
+ *
24
+ * That key never travelled through the tunnel, which is what makes this
25
+ * authenticated: a relay can watch the client's public key go past and learn
26
+ * nothing, and it cannot substitute the host's because it never carried it.
27
+ */
28
+ declare function connectSealedChannel(hostPublicKey: string): Promise<{
29
+ channel: SealedChannel;
30
+ clientPublicKey: string;
31
+ } | undefined>;
32
+ /** Exposed so a test can build the browser side against a known secret. */
33
+ declare function channelFromSecret(secret: ArrayBuffer, sendDirection: SealedDirection, noncePrefix: Uint8Array): Promise<SealedChannel>;
34
+ //#endregion
35
+ export { OpenResult, SealResult, SealedChannel, channelFromSecret, connectSealedChannel };
36
+ //# sourceMappingURL=browserSealedChannel.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserSealedChannel.d.cts","names":[],"sources":["../../src/adapters/browserSealedChannel.ts"],"mappings":";;KA8BY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;KAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;UAEpE;EACf,KAAK,WAAW,aAAa,QAAQ;EACrC,KAAK,oBAAoB,QAAQ;;;;;;;;;iBA+Gb,qBACpB,wBACC;EAAU,SAAS;EAAe;;;iBAyBf,kBACpB,QAAQ,aACR,eAAe,iBACf,aAAa,aACZ,QAAQ"}
@@ -0,0 +1,36 @@
1
+ import { SealedDirection, SealedEnvelope, SealedFailure } from "../types/sealedChannel.mjs";
2
+ //#region src/adapters/browserSealedChannel.d.ts
3
+ type SealResult = {
4
+ ok: true;
5
+ envelope: SealedEnvelope;
6
+ } | {
7
+ ok: false;
8
+ failure: SealedFailure;
9
+ };
10
+ type OpenResult = {
11
+ ok: true;
12
+ plaintext: Uint8Array;
13
+ } | {
14
+ ok: false;
15
+ failure: SealedFailure;
16
+ };
17
+ interface SealedChannel {
18
+ seal(plaintext: Uint8Array): Promise<SealResult>;
19
+ open(envelope: unknown): Promise<OpenResult>;
20
+ }
21
+ /**
22
+ * Completes the handshake against the host key read out of the QR fragment.
23
+ *
24
+ * That key never travelled through the tunnel, which is what makes this
25
+ * authenticated: a relay can watch the client's public key go past and learn
26
+ * nothing, and it cannot substitute the host's because it never carried it.
27
+ */
28
+ declare function connectSealedChannel(hostPublicKey: string): Promise<{
29
+ channel: SealedChannel;
30
+ clientPublicKey: string;
31
+ } | undefined>;
32
+ /** Exposed so a test can build the browser side against a known secret. */
33
+ declare function channelFromSecret(secret: ArrayBuffer, sendDirection: SealedDirection, noncePrefix: Uint8Array): Promise<SealedChannel>;
34
+ //#endregion
35
+ export { OpenResult, SealResult, SealedChannel, channelFromSecret, connectSealedChannel };
36
+ //# sourceMappingURL=browserSealedChannel.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserSealedChannel.d.mts","names":[],"sources":["../../src/adapters/browserSealedChannel.ts"],"mappings":";;KA8BY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;KAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;UAEpE;EACf,KAAK,WAAW,aAAa,QAAQ;EACrC,KAAK,oBAAoB,QAAQ;;;;;;;;;iBA+Gb,qBACpB,wBACC;EAAU,SAAS;EAAe;;;iBAyBf,kBACpB,QAAQ,aACR,eAAe,iBACf,aAAa,aACZ,QAAQ"}
@@ -0,0 +1,2 @@
1
+ import{MAX_MESSAGES_PER_KEY as e,infoFor as t,isSealedEnvelope as n}from"../types/sealedChannel.mjs";const r={name:`ECDH`,namedCurve:`P-256`},i=`AES-GCM`;function a(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function o(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function s(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function c(e,n){let r=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:s(new TextEncoder().encode(`doompi/sealed/v1`)),info:s(new TextEncoder().encode(t(n)))},r,{name:i,length:256},!1,[`encrypt`,`decrypt`])}function l(e,t){let n=new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function u(t,r,c){let u=0n,d=-1n;return{async seal(n){if(u>=BigInt(e))return{ok:!1,failure:`exhausted`};let r=l(c,u),a=await crypto.subtle.encrypt({name:i,iv:s(r),tagLength:128},t,s(n));return u+=1n,{ok:!0,envelope:{v:1,n:o(r),c:o(new Uint8Array(a))}}},async open(e){let t=e;if(typeof t?.n!=`string`||typeof t.c!=`string`)return{ok:!1,failure:`malformed`};if(t.v!==1)return{ok:!1,failure:`version`};if(!n(e))return{ok:!1,failure:`malformed`};let o=a(e.n),c=a(e.c);if(o===void 0||c===void 0||o.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(s(o)).getBigUint64(4,!1);if(l<=d)return{ok:!1,failure:`replay`};let u;try{u=await crypto.subtle.decrypt({name:i,iv:s(o),tagLength:128},r,s(c))}catch{return{ok:!1,failure:`auth`}}return d=l,{ok:!0,plaintext:new Uint8Array(u)}}}}async function d(e){if(globalThis.crypto?.subtle!==void 0)try{let t=await crypto.subtle.generateKey(r,!1,[`deriveBits`]),n=a(e);if(n===void 0)return;let i=await crypto.subtle.importKey(`raw`,s(n),r,!1,[]),l=await crypto.subtle.deriveBits({name:`ECDH`,public:i},t.privateKey,256),d=o(new Uint8Array(await crypto.subtle.exportKey(`raw`,t.publicKey)));return{channel:u(await c(l,`c2s`),await c(l,`s2c`),new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function f(e,t,n){return u(await c(e,t),await c(e,t===`c2s`?`s2c`:`c2s`),n)}export{f as channelFromSecret,d as connectSealedChannel};
2
+ //# sourceMappingURL=browserSealedChannel.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserSealedChannel.mjs","names":[],"sources":["../../src/adapters/browserSealedChannel.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../types/sealedChannel.ts';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'doompi/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"qGAuBA,MAAM,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpD,EAAS,UAef,SAAS,EAAM,EAAuC,CACpD,IAAI,EACJ,GAAI,CACF,EAAS,KAAK,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAM,EAAM,IAAI,WAAW,IAAI,YAAY,EAAO,MAAM,CAAC,EACzD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,EAAI,GAAS,EAAO,WAA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AO,MAAM,OAAO,OAAO,YAAY,EAAe,GAAO,CAAC,YAAY,CAAC,EAC3E,EAAU,EAAM,CAAa,EACnC,GAAI,IAAY,IAAA,GAAW,OAC3B,IAAM,EAAO,MAAM,OAAO,OAAO,UAAU,MAAO,EAAK,CAAO,EAAG,EAAe,GAAO,CAAC,CAAC,EACnF,EAAS,MAAM,OAAO,OAAO,WAAW,CAAE,KAAM,OAAQ,OAAQ,CAAK,EAAG,EAAK,WAAY,GAAQ,EACjG,EAAkB,EAAU,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,MAAO,EAAK,SAAS,CAAC,CAAC,EACtG,MAAO,CACL,QAAS,EACP,MAAM,EAAO,EAAQ,KAAK,EAC1B,MAAM,EAAO,EAAQ,KAAK,EAC1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsB,EACpB,EACA,EACA,EACwB,CAGxB,OAAO,EAAY,MAFA,EAAO,EAAQ,CAAa,EAEtB,MADH,EAAO,EAAQ,IAAkB,MAAQ,MAAQ,KAAK,EAC1C,CAAW,CAC/C"}
@@ -0,0 +1,2 @@
1
+ const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../types/bundleManifest.cjs");let n=require("node:crypto"),r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=`signing.json`,o=new Set([`.map`]),s={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function c(e){r.default.mkdirSync(e,{recursive:!0,mode:448});let t=r.default.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);r.default.chmodSync(e,448)}function l(e,t){c(e);let n=i.default.join(e,`signing.lock`),a;for(let e=0;e<500;e+=1)try{a=r.default.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(a===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{r.default.closeSync(a),r.default.rmSync(n,{force:!0})}}function u(e,t){let o=i.default.join(e,a),s=i.default.join(e,`.${a}.${process.pid}.${(0,n.randomBytes)(8).toString(`hex`)}`),c=r.default.openSync(s,`wx`,384);try{r.default.writeFileSync(c,`${JSON.stringify(t,void 0,2)}\n`),r.default.fsyncSync(c)}finally{r.default.closeSync(c)}try{r.default.renameSync(s,o),r.default.chmodSync(o,384)}catch(e){throw r.default.rmSync(s,{force:!0}),e}}function d(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=_(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function f(e){return l(e,()=>{let t=i.default.join(e,a);try{let n=r.default.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let i=JSON.parse(r.default.readFileSync(t,`utf8`)),a=d(i,t);return r.default.chmodSync(t,384),i.revision===void 0&&u(e,a),a}catch(e){if(e.code!==`ENOENT`)throw e}let o=(0,n.generateKeyPairSync)(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),s={privateKey:o.privateKey,publicKey:Buffer.from(o.publicKey).toString(`base64url`),revision:0};return u(e,s),s})}function p(e,t){return l(e,()=>{let n=i.default.join(e,a),o=d(JSON.parse(r.default.readFileSync(n,`utf8`)),n);if(o.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(o.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let s={...o,revision:o.revision+1};return u(e,s),s.revision})}function m(e){return s[i.default.extname(e).toLowerCase()]??`application/octet-stream`}function h(e,t,a){let s=r.default.readdirSync(t,{withFileTypes:!0});for(let c of s){let s=i.default.join(t,c.name),l=r.default.lstatSync(s);if(l.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${s}`);if(l.isDirectory()){h(e,s,a);continue}if(!l.isFile())throw Error(`refusing to omit unsupported asset: ${s}`);if(o.has(i.default.extname(c.name)))continue;let u=r.default.readFileSync(s);a.push({path:`/${i.default.relative(e,s).split(i.default.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:(0,n.createHash)(`sha256`).update(u).digest(`hex`),byteLength:u.byteLength,contentType:m(s)})}}function g(e,a=()=>{}){let o=f(e),s=(0,n.createPrivateKey)(o.privateKey),c=new Map,l=i=>{let a=r.default.lstatSync(i);if(!a.isDirectory()||a.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${i}`);let c=[];if(h(i,i,c),c.length===0)return;c.sort((e,t)=>e.path.localeCompare(t.path));let l={version:2,revision:p(e,o.publicKey),builtAt:Date.now(),assets:c};if(!t.isBundleManifest(l))throw Error(`refusing to sign an invalid bundle manifest`);return{manifest:l,signature:(0,n.createSign)(`sha256`).update(t.canonicalManifest(l)).sign({key:s,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:o.publicKey}},u=e=>{let t=i.default.resolve(e);if(c.has(t))return c.get(t);let n=l(t);return c.set(t,n),n};return{publicKey:()=>o.publicKey,sign:u,refresh(e){let t=i.default.resolve(e);return c.delete(t),u(t)},invalidate(e){e===void 0?c.clear():c.delete(i.default.resolve(e))}}}function _(e){return Buffer.from((0,n.createPublicKey)(e).export({type:`spki`,format:`der`})).toString(`base64url`)}exports.createBundleSigner=g,exports.publicKeyOf=_;
2
+ //# sourceMappingURL=bundleSigner.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleSigner.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","createPublicKey"],"sources":["../../src/adapters/bundleSigner.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type SignedBundleManifest,\n canonicalManifest,\n isBundleManifest,\n} from '../types/bundleManifest.ts';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /** Hashes and signs once per asset directory. Undefined when the bundle is empty. */\n sign(assetsDir: string): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string): SignedBundleManifest | undefined;\n /** Invalidates one cached directory, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n\n const signFresh = (assetsDir: string): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest)) throw new Error('refusing to sign an invalid bundle manifest');\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string): SignedBundleManifest | undefined => {\n const cacheKey = path.resolve(assetsDir);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(cacheKey);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir) {\n const cacheKey = path.resolve(assetsDir);\n cache.delete(cacheKey);\n return sign(cacheKey);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) cache.clear();\n else cache.delete(path.resolve(assetsDir));\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"6MAmBA,MAAM,EAAe,eAMf,EAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1B,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EAmBA,SAAS,EAAqB,EAAwB,CACpD,EAAA,QAAG,UAAU,EAAU,CAAE,UAAW,GAAM,KAAM,GAAe,CAAC,EAChE,IAAM,EAAOA,EAAAA,QAAG,UAAU,CAAQ,EAClC,GAAI,CAAC,EAAK,YAAY,GAAK,EAAK,eAAe,EAC7C,MAAU,MAAM,4CAA4C,GAAU,EACxE,EAAA,QAAG,UAAU,EAAU,GAAc,CACvC,CAEA,SAAS,EAAiB,EAAkB,EAAuB,CACjE,EAAqB,CAAQ,EAC7B,IAAM,EAAWC,EAAAA,QAAK,KAAK,EAAU,cAAS,EAC1C,EACJ,IAAK,IAAI,EAAU,EAAG,EAAU,IAAK,GAAW,EAC9C,GAAI,CACF,EAAaD,EAAAA,QAAG,S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EAEvC,OADA,EAAM,OAAO,CAAQ,EACd,EAAK,CAAQ,CACtB,EACA,WAAW,EAAW,CAChB,IAAc,IAAA,GAAW,EAAM,MAAM,EACpC,EAAM,OAAOA,EAAAA,QAAK,QAAQ,CAAS,CAAC,CAC3C,CACF,CACF,CAGA,SAAgB,EAAY,EAA+B,CACzD,OAAO,OAAO,MAAA,EAAKQ,EAAAA,gBAAAA,CAAgB,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
@@ -0,0 +1,18 @@
1
+ import { SignedBundleManifest } from "../types/bundleManifest.cjs";
2
+ //#region src/adapters/bundleSigner.d.ts
3
+ interface BundleSigner {
4
+ /** Base64url SPKI for an independently trusted verifier to pin. */
5
+ publicKey(): string;
6
+ /** Hashes and signs once per asset directory. Undefined when the bundle is empty. */
7
+ sign(assetsDir: string): SignedBundleManifest | undefined;
8
+ /** Invalidates and immediately rebuilds one cached manifest. */
9
+ refresh(assetsDir: string): SignedBundleManifest | undefined;
10
+ /** Invalidates one cached directory, or every cached directory when omitted. */
11
+ invalidate(assetsDir?: string): void;
12
+ }
13
+ declare function createBundleSigner(stateDir: string, _onNotice?: (message: string) => void): BundleSigner;
14
+ /** Re-derives the public key from a stored private key. */
15
+ declare function publicKeyOf(privateKeyPem: string): string;
16
+ //#endregion
17
+ export { BundleSigner, createBundleSigner, publicKeyOf };
18
+ //# sourceMappingURL=bundleSigner.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleSigner.d.cts","names":[],"sources":["../../src/adapters/bundleSigner.ts"],"mappings":";;UA6CiB;;EAEf;;EAEA,KAAK,oBAAoB;;EAEzB,QAAQ,oBAAoB;;EAE5B,WAAW;;iBAsJG,mBAAmB,kBAAkB,aAAY,2BAAsC;;iBAoDvF,YAAY"}
@@ -0,0 +1,18 @@
1
+ import { SignedBundleManifest } from "../types/bundleManifest.mjs";
2
+ //#region src/adapters/bundleSigner.d.ts
3
+ interface BundleSigner {
4
+ /** Base64url SPKI for an independently trusted verifier to pin. */
5
+ publicKey(): string;
6
+ /** Hashes and signs once per asset directory. Undefined when the bundle is empty. */
7
+ sign(assetsDir: string): SignedBundleManifest | undefined;
8
+ /** Invalidates and immediately rebuilds one cached manifest. */
9
+ refresh(assetsDir: string): SignedBundleManifest | undefined;
10
+ /** Invalidates one cached directory, or every cached directory when omitted. */
11
+ invalidate(assetsDir?: string): void;
12
+ }
13
+ declare function createBundleSigner(stateDir: string, _onNotice?: (message: string) => void): BundleSigner;
14
+ /** Re-derives the public key from a stored private key. */
15
+ declare function publicKeyOf(privateKeyPem: string): string;
16
+ //#endregion
17
+ export { BundleSigner, createBundleSigner, publicKeyOf };
18
+ //# sourceMappingURL=bundleSigner.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleSigner.d.mts","names":[],"sources":["../../src/adapters/bundleSigner.ts"],"mappings":";;UA6CiB;;EAEf;;EAEA,KAAK,oBAAoB;;EAEzB,QAAQ,oBAAoB;;EAE5B,WAAW;;iBAsJG,mBAAmB,kBAAkB,aAAY,2BAAsC;;iBAoDvF,YAAY"}
@@ -0,0 +1,2 @@
1
+ import{canonicalManifest as e,isBundleManifest as t}from"../types/bundleManifest.mjs";import{createHash as n,createPrivateKey as r,createPublicKey as i,createSign as a,generateKeyPairSync as o,randomBytes as s}from"node:crypto";import c from"node:fs";import l from"node:path";const u=`signing.json`,d=new Set([`.map`]),f={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function p(e){c.mkdirSync(e,{recursive:!0,mode:448});let t=c.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);c.chmodSync(e,448)}function m(e,t){p(e);let n=l.join(e,`signing.lock`),r;for(let e=0;e<500;e+=1)try{r=c.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(r===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{c.closeSync(r),c.rmSync(n,{force:!0})}}function h(e,t){let n=l.join(e,u),r=l.join(e,`.${u}.${process.pid}.${s(8).toString(`hex`)}`),i=c.openSync(r,`wx`,384);try{c.writeFileSync(i,`${JSON.stringify(t,void 0,2)}\n`),c.fsyncSync(i)}finally{c.closeSync(i)}try{c.renameSync(r,n),c.chmodSync(n,384)}catch(e){throw c.rmSync(r,{force:!0}),e}}function g(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=S(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function _(e){return m(e,()=>{let t=l.join(e,u);try{let n=c.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let r=JSON.parse(c.readFileSync(t,`utf8`)),i=g(r,t);return c.chmodSync(t,384),r.revision===void 0&&h(e,i),i}catch(e){if(e.code!==`ENOENT`)throw e}let n=o(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),r={privateKey:n.privateKey,publicKey:Buffer.from(n.publicKey).toString(`base64url`),revision:0};return h(e,r),r})}function v(e,t){return m(e,()=>{let n=l.join(e,u),r=g(JSON.parse(c.readFileSync(n,`utf8`)),n);if(r.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(r.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let i={...r,revision:r.revision+1};return h(e,i),i.revision})}function y(e){return f[l.extname(e).toLowerCase()]??`application/octet-stream`}function b(e,t,r){let i=c.readdirSync(t,{withFileTypes:!0});for(let a of i){let i=l.join(t,a.name),o=c.lstatSync(i);if(o.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${i}`);if(o.isDirectory()){b(e,i,r);continue}if(!o.isFile())throw Error(`refusing to omit unsupported asset: ${i}`);if(d.has(l.extname(a.name)))continue;let s=c.readFileSync(i);r.push({path:`/${l.relative(e,i).split(l.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:n(`sha256`).update(s).digest(`hex`),byteLength:s.byteLength,contentType:y(i)})}}function x(n,i=()=>{}){let o=_(n),s=r(o.privateKey),u=new Map,d=r=>{let i=c.lstatSync(r);if(!i.isDirectory()||i.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${r}`);let l=[];if(b(r,r,l),l.length===0)return;l.sort((e,t)=>e.path.localeCompare(t.path));let u={version:2,revision:v(n,o.publicKey),builtAt:Date.now(),assets:l};if(!t(u))throw Error(`refusing to sign an invalid bundle manifest`);return{manifest:u,signature:a(`sha256`).update(e(u)).sign({key:s,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:o.publicKey}},f=e=>{let t=l.resolve(e);if(u.has(t))return u.get(t);let n=d(t);return u.set(t,n),n};return{publicKey:()=>o.publicKey,sign:f,refresh(e){let t=l.resolve(e);return u.delete(t),f(t)},invalidate(e){e===void 0?u.clear():u.delete(l.resolve(e))}}}function S(e){return Buffer.from(i(e).export({type:`spki`,format:`der`})).toString(`base64url`)}export{x as createBundleSigner,S as publicKeyOf};
2
+ //# sourceMappingURL=bundleSigner.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundleSigner.mjs","names":[],"sources":["../../src/adapters/bundleSigner.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type SignedBundleManifest,\n canonicalManifest,\n isBundleManifest,\n} from '../types/bundleManifest.ts';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /** Hashes and signs once per asset directory. Undefined when the bundle is empty. */\n sign(assetsDir: string): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string): SignedBundleManifest | undefined;\n /** Invalidates one cached directory, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n\n const signFresh = (assetsDir: string): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest)) throw new Error('refusing to sign an invalid bundle manifest');\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string): SignedBundleManifest | undefined => {\n const cacheKey = path.resolve(assetsDir);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(cacheKey);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir) {\n const cacheKey = path.resolve(assetsDir);\n cache.delete(cacheKey);\n return sign(cacheKey);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) cache.clear();\n else cache.delete(path.resolve(assetsDir));\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"oRAmBA,MAAM,EAAe,eAMf,EAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1B,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EAmBA,SAAS,EAAqB,EAAwB,CACpD,EAAG,UAAU,EAAU,CAAE,UAAW,GAAM,KAAM,GAAe,CAAC,EAChE,IAAM,EAAO,EAAG,UAAU,CAAQ,EAClC,GAAI,CAAC,EAAK,YAAY,GAAK,EAAK,eAAe,EAC7C,MAAU,MAAM,4CAA4C,GAAU,EACxE,EAAG,UAAU,EAAU,GAAc,CACvC,CAEA,SAAS,EAAiB,EAAkB,EAAuB,CACjE,EAAqB,CAAQ,EAC7B,IAAM,EAAW,EAAK,KAAK,EAAU,cAAS,EAC1C,EACJ,IAAK,IAAI,EAAU,EAAG,EAAU,IAAK,GAAW,EAC9C,GAAI,CACF,EAAa,EAAG,SAAS,EAAU,KAAM,GAAS,EAClD,KACF,OAAS,EAAO,CACd,GAAK,EAAgC,OAAS,SAAU,MAAM,EAC9D,QAAQ,KAAK,IAAI,WAAW,IAAI,kBAAkB,CAAC,CAAC,EAAG,EAAG,EAAG,EAAE,CACjE,CAEF,GAAI,IAAe,IAAA,GAAW,MAAU,MAAM,oDAAoD,GAAU,EAC5G,GAA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,IAAI,CAAC,EAChE,IAAM,EAA2B,CAC/B,QAAA,EACA,SAAU,EAAgB,EAAU,EAAI,SAAS,EACjD,QAAS,KAAK,IAAI,EAClB,QACF,EACA,GAAI,CAAC,EAAiB,CAAQ,EAAG,MAAU,MAAM,6CAA6C,EAK9F,MAAO,CAAE,WAAU,UAJD,EAAW,QAAc,CAAC,CACzC,OAAO,EAAkB,CAAQ,CAAC,CAAC,CACnC,KAAK,CAAE,IAAK,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WACe,EAAG,UAAW,EAAI,SAAU,CACzD,EAEM,EAAQ,GAAwD,CACpE,IAAM,EAAW,EAAK,QAAQ,CAAS,EACvC,GAAI,EAAM,IAAI,CAAQ,EAAG,OAAO,EAAM,IAAI,CAAQ,EAClD,IAAM,EAAS,EAAU,CAAQ,EAEjC,OADA,EAAM,IAAI,EAAU,CAAM,EACnB,CACT,EAEA,MAAO,CACL,cAAiB,EAAI,UACrB,OACA,QAAQ,EAAW,CACjB,IAAM,EAAW,EAAK,QAAQ,CAAS,EAEvC,OADA,EAAM,OAAO,CAAQ,EACd,EAAK,CAAQ,CACtB,EACA,WAAW,EAAW,CAChB,IAAc,IAAA,GAAW,EAAM,MAAM,EACpC,EAAM,OAAO,EAAK,QAAQ,CAAS,CAAC,CAC3C,CACF,CACF,CAGA,SAAgB,EAAY,EAA+B,CACzD,OAAO,OAAO,KAAK,EAAgB,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../types/sealedChannel.cjs");let t=require("node:crypto");const n=`prime256v1`,r=`aes-256-gcm`,i=Buffer.from(`doompi/sealed/v1`);function a(n,r){return Buffer.from((0,t.hkdfSync)(`sha256`,n,i,Buffer.from(e.infoFor(r)),32))}function o(e,t){let n=Buffer.alloc(12);return e.copy(n,0,0,4),n.writeBigUInt64BE(t,4),n}function s(n,i,s){let c=a(n,i),l=a(n,i===`c2s`?`s2c`:`c2s`),u=0n,d=-1n;return{seal(n){if(u>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let i=o(s,u),a=(0,t.createCipheriv)(r,c,i),l=Buffer.concat([a.update(n),a.final(),a.getAuthTag()]);return u+=1n,{ok:!0,envelope:{v:1,n:i.toString(`base64url`),c:l.toString(`base64url`)}}},open(n){let i=n;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(n))return{ok:!1,failure:`malformed`};let a=Buffer.from(n.n,`base64url`),o=Buffer.from(n.c,`base64url`);if(a.length!==12||o.length<16)return{ok:!1,failure:`malformed`};let s=a.readBigUInt64BE(4);if(s<=d)return{ok:!1,failure:`replay`};let c=(0,t.createDecipheriv)(r,l,a);c.setAuthTag(o.subarray(o.length-16));let u;try{u=Buffer.concat([c.update(o.subarray(0,o.length-16)),c.final()])}catch{return{ok:!1,failure:`auth`}}return d=s,{ok:!0,plaintext:new Uint8Array(u)}}}}function c(){let e=(0,t.createECDH)(n);e.generateKeys();let r=new Set;return{publicKey:e.getPublicKey().toString(`base64url`),accept(i){let a,o;try{if(a=t.ECDH.convertKey(Buffer.from(i,`base64url`),n,void 0,void 0,`uncompressed`),r.has(a.toString(`base64url`)))return;o=e.computeSecret(a)}catch{return}return r.add(a.toString(`base64url`)),s(o,`s2c`,(0,t.randomBytes)(4))}}}exports.createHostHandshake=c;
2
+ //# sourceMappingURL=nodeSealedChannel.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodeSealedChannel.cjs","names":["hkdfSync","infoFor","MAX_MESSAGES_PER_KEY","createCipheriv","isSealedEnvelope","createDecipheriv","createECDH","ECDH","randomBytes"],"sources":["../../src/adapters/nodeSealedChannel.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\nimport {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../types/sealedChannel.ts';\n\nconst CURVE = 'prime256v1';\nconst CIPHER = 'aes-256-gcm';\nconst KEY_BYTES = 32;\nconst TAG_BYTES = 16;\nconst HKDF_HASH = 'sha256';\n/** Fixed and public: HKDF's salt need not be secret, and a constant keeps both sides in step. */\nconst HKDF_SALT = Buffer.from('doompi/sealed/v1');\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n /** Seals one message. Counters advance only on success. */\n seal(plaintext: Uint8Array): SealResult;\n open(envelope: unknown): OpenResult;\n}\n\nexport interface HostHandshake {\n /** Base64url uncompressed P-256 point, printed in the QR. */\n publicKey: string;\n /** Completes the exchange against the peer's key and yields the channel. */\n accept(peerPublicKey: string): SealedChannel | undefined;\n}\n\nfunction derive(secret: Buffer, direction: SealedDirection): Buffer {\n return Buffer.from(hkdfSync(HKDF_HASH, secret, HKDF_SALT, Buffer.from(infoFor(direction)), KEY_BYTES));\n}\n\n/**\n * Builds the nonce for one message.\n *\n * A random per-channel prefix plus a monotonic counter, rather than a random\n * nonce per message: 96 bits is small enough that random nonces collide at a\n * rate worth caring about, and a repeated nonce under one AES-GCM key is\n * catastrophic rather than merely weak.\n */\nfunction nonceFor(prefix: Buffer, counter: bigint): Buffer {\n const nonce = Buffer.alloc(NONCE_BYTES);\n prefix.copy(nonce, 0, 0, NONCE_PREFIX_BYTES);\n nonce.writeBigUInt64BE(counter, NONCE_PREFIX_BYTES);\n return nonce;\n}\n\n/**\n * One direction's sealing state.\n *\n * Send and receive are separate keys and separate counters, so a message the\n * server sent can never be replayed back at it as though the client had sent it.\n */\nfunction createChannel(secret: Buffer, sendDirection: SealedDirection, noncePrefix: Buffer): SealedChannel {\n const sendKey = derive(secret, sendDirection);\n const receiveKey = derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n let sendCounter = 0n;\n /** Strictly increasing: anything at or below what has been seen is a replay. */\n let highestReceived = -1n;\n\n return {\n seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const cipher = createCipheriv(CIPHER, sendKey, nonce);\n const body = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: nonce.toString('base64url'), c: body.toString('base64url') },\n };\n },\n\n open(envelope) {\n // Shape before version: something with no `v` at all is malformed, and\n // calling it a version mismatch would send a reader hunting for a\n // protocol skew that is not there.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = Buffer.from(envelope.n, 'base64url');\n const body = Buffer.from(envelope.c, 'base64url');\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = nonce.readBigUInt64BE(NONCE_PREFIX_BYTES);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n const decipher = createDecipheriv(CIPHER, receiveKey, nonce);\n decipher.setAuthTag(body.subarray(body.length - TAG_BYTES));\n let plaintext: Buffer;\n try {\n plaintext = Buffer.concat([decipher.update(body.subarray(0, body.length - TAG_BYTES)), decipher.final()]);\n } catch {\n // A failed tag means the message was altered, which is the whole point\n // of having one. Never fall back to the ciphertext.\n return { ok: false, failure: 'auth' };\n }\n // Advanced only after the tag verified, so a forged high counter cannot\n // lock out the messages that follow it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * The host half of the handshake.\n *\n * The ephemeral key pair is generated per tunnel and its public half goes in the\n * QR, which is the out-of-band channel that makes this authenticated. A relay\n * that swaps the client's key gets a channel with itself and nothing from the\n * host, because the host only ever derives against the key the client presents\n * and the client only ever derives against the key it read off the screen.\n */\nexport function createHostHandshake(): HostHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n const acceptedPeers = new Set<string>();\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(peerPublicKey) {\n let peer: Buffer;\n let secret: Buffer;\n try {\n peer = ECDH.convertKey(Buffer.from(peerPublicKey, 'base64url'), CURVE, undefined, undefined, 'uncompressed');\n if (acceptedPeers.has(peer.toString('base64url'))) return undefined;\n secret = exchange.computeSecret(peer);\n } catch {\n // A key that is not a point on the curve; there is no channel to make.\n return undefined;\n }\n acceptedPeers.add(peer.toString('base64url'));\n // The prefix is the host's to choose and travels in every nonce, so the\n // client reads it off the wire rather than needing it up front.\n return createChannel(secret, 's2c', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"2EAaA,MAAM,EAAQ,aACR,EAAS,cAKT,EAAY,OAAO,KAAK,kBAAkB,EAkBhD,SAAS,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,MAAA,EAAKA,EAAAA,SAAAA,CAAS,SAAW,EAAQ,EAAW,OAAO,KAAKC,EAAAA,QAAQ,CAAS,CAAC,EAAG,EAAS,CAAC,CACvG,CAUA,SAAS,EAAS,EAAgB,EAAyB,CACzD,IAAM,EAAQ,OAAO,MAAA,EAAiB,EAGtC,OAFA,EAAO,KAAK,EAAO,EAAG,EAAA,CAAqB,EAC3C,EAAM,iBAAiB,EAAA,CAA2B,EAC3C,CACT,CAQA,SAAS,EAAc,EAAgB,EAAgC,EAAoC,CACzG,IAAM,EAAU,EAAO,EAAQ,CAAa,EACtC,EAAa,EAAO,EAAQ,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