@agimon-ai/doompi-web-security 0.0.1-alpha.58 → 0.0.1-alpha.59
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.
- package/dist/services/browserBundleVerifier/index.cjs.map +1 -1
- package/dist/services/browserBundleVerifier/index.mjs.map +1 -1
- package/dist/services/browserSealedChannel/index.cjs.map +1 -1
- package/dist/services/browserSealedChannel/index.mjs.map +1 -1
- package/dist/services/bundleSigner/index.cjs.map +1 -1
- package/dist/services/bundleSigner/index.mjs.map +1 -1
- package/dist/services/nodeSealedChannel/index.cjs.map +1 -1
- package/dist/services/nodeSealedChannel/index.mjs.map +1 -1
- package/dist/services/sealedTransport/index.cjs.map +1 -1
- package/dist/services/sealedTransport/index.mjs.map +1 -1
- package/dist/services/serialQueue/index.cjs.map +1 -1
- package/dist/services/serialQueue/index.mjs.map +1 -1
- package/dist/types/bundleManifest.cjs.map +1 -1
- package/dist/types/bundleManifest.mjs.map +1 -1
- package/dist/types/sealedChannel.cjs.map +1 -1
- package/dist/types/sealedChannel.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isSignedBundleManifest","canonicalManifest","assetFor"],"sources":["../../../src/services/browserBundleVerifier/index.ts"],"sourcesContent":["import {\n type BundleManifest,\n type SignedBundleManifest,\n assetFor,\n canonicalManifest,\n isSignedBundleManifest,\n} from '../../types/bundleManifest';\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":"kDA0BA,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["isSignedBundleManifest","canonicalManifest","assetFor","require_bundleManifest","decodeBase64Url","standard","value","padded","binary","bytes","index","hex","byte","verifySignedBundleManifest","signed","trustedPublicKey","minimumRevision","key","verifyBundleAsset","asset","manifest","assetPath"],"sources":["../../../src/services/browserBundleVerifier/index.ts"],"sourcesContent":["import {\n type BundleManifest,\n type SignedBundleManifest,\n assetFor,\n canonicalManifest,\n isSignedBundleManifest,\n} from '../../types/bundleManifest';\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 } :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AAE,KAAM,oBAAqB,CAAE,CAC9D,CAEA,GAAI,CAOF,OAAO,MANgB,OAAO,OAAO,OACnC,CAAE,KAAM,QAAS,KAAM,SAAU,EACjCE,EACAb,EAAgBU,EAAO,SAAS,EAChC,IAAI,YAAY,CAAC,CAAC,OAAOb,EAAAA,kBAAkBa,EAAO,QAAQ,CAAC,CAC7D,EACkB,CAAE,GAAI,GAAM,SAAUA,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,eAAsBI,EACpB,EACA,EACA,EACwC,CACxC,IAAMC,EAAQjB,EAAAA,SAASkB,EAAUC,CAAS,EAS1C,OARIF,IAAU,IAAA,GAAkB,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,KAAME,CAAU,CAAE,EAChGZ,EAAM,aAAeU,EAAM,WAMhBR,EAAI,MAAM,OAAO,OAAO,OAAO,UAAWF,CAAK,CAClD,IAAMU,EAAM,OAAS,CAAE,GAAI,EAAK,EAAI,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,iBAAkB,CAAE,EANzF,CACL,GAAI,GACJ,QAAS,CAAE,KAAM,uBAAwB,SAAUA,EAAM,WAAY,OAAQV,EAAM,UAAW,CAChG,CAIJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/browserBundleVerifier/index.ts"],"sourcesContent":["import {\n type BundleManifest,\n type SignedBundleManifest,\n assetFor,\n canonicalManifest,\n isSignedBundleManifest,\n} from '../../types/bundleManifest';\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":"6GA0BA,
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["decodeBase64Url","standard","value","padded","binary","bytes","index","hex","byte","verifySignedBundleManifest","isSignedBundleManifest","signed","trustedPublicKey","minimumRevision","key","canonicalManifest","verifyBundleAsset","asset","assetFor","manifest","assetPath"],"sources":["../../../src/services/browserBundleVerifier/index.ts"],"sourcesContent":["import {\n type BundleManifest,\n type SignedBundleManifest,\n assetFor,\n canonicalManifest,\n isSignedBundleManifest,\n} from '../../types/bundleManifest';\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":"6GA0BA,SAASA,EAAgB,EAA4B,CACnD,IAAMC,EAAWC,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,EACzDC,EAASF,EAAS,OAAO,KAAK,KAAKA,EAAS,OAAS,CAAC,EAAI,EAAG,GAAG,EAChEG,EAAS,KAAKD,CAAM,EACpBE,EAAQ,IAAI,WAAWD,EAAO,MAAM,EAC1C,IAAK,IAAIE,EAAQ,EAAGA,EAAQF,EAAO,OAAQ,GAAS,EAAG,EAAME,GAASF,EAAO,WAAWE,CAAK,EAC7F,OAAOD,EAAM,MACf,CAEA,SAASE,EAAI,EAA4B,CACvC,MAAO,CAAC,GAAG,IAAI,WAAWF,CAAK,CAAC,CAAC,CAAC,IAAK,GAASG,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,CAC7F,CAGA,eAAsBC,EACpB,EACA,EACA,EAAkB,EACiB,CACnC,GAAI,CAACC,EAAuBR,CAAK,EAAG,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,kBAAmB,CAAE,EAC9F,IAAMS,EAA+BT,EACrC,GAAIS,EAAO,YAAcC,EAAkB,MAAO,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,sBAAuB,CAAE,EACzG,GAAI,CAAC,OAAO,cAAcC,CAAe,GAAKA,EAAkB,GAAKF,EAAO,SAAS,SAAWE,EAC9F,MAAO,CACL,GAAI,GACJ,QAAS,CAAE,KAAM,iBAAkB,kBAAiB,eAAgBF,EAAO,SAAS,QAAS,CAC/F,EAGF,IAAIG,EACJ,GAAI,CACF,EAAM,MAAM,OAAO,OAAO,UACxB,OACAd,EAAgBY,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,EACjCE,EACAd,EAAgBW,EAAO,SAAS,EAChC,IAAI,YAAY,CAAC,CAAC,OAAOI,EAAkBJ,EAAO,QAAQ,CAAC,CAC7D,EACkB,CAAE,GAAI,GAAM,SAAUA,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,eAAsBK,EACpB,EACA,EACA,EACwC,CACxC,IAAMC,EAAQC,EAASC,EAAUC,CAAS,EAS1C,OARIH,IAAU,IAAA,GAAkB,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,mBAAoB,KAAMG,CAAU,CAAE,EAChGf,EAAM,aAAeY,EAAM,WAMhBV,EAAI,MAAM,OAAO,OAAO,OAAO,UAAWF,CAAK,CAClD,IAAMY,EAAM,OAAS,CAAE,GAAI,EAAK,EAAI,CAAE,GAAI,GAAO,QAAS,CAAE,KAAM,iBAAkB,CAAE,EANzF,CACL,GAAI,GACJ,QAAS,CAAE,KAAM,uBAAwB,SAAUA,EAAM,WAAY,OAAQZ,EAAM,UAAW,CAChG,CAIJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["infoFor","MAX_MESSAGES_PER_KEY","isSealedEnvelope"],"sources":["../../../src/services/browserSealedChannel/index.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';\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":"iDAuBM,EAAgB,CAAE,KAAM,OAAQ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ACF,EAAY,MAAM,OAAO,OAAO,QAC9B,CAAE,KAAM,EAAQ,GAAI,EAAK,CAAK,EAAG,UAAW,GAAS,EACrD,EACA,EAAK,CAAI,CACX,CACF,MAAQ,CAGN,MAAO,CAAE,GAAI,GAAO,QAAS,MAAO,CACtC,CAIA,MADA,GAAkB,EACX,CAAE,GAAI,GAAM,UAAW,IAAI,WAAW,CAAS,CAAE,CAC1D,CACF,CACF,CASA,eAAsB,EACpB,EAC0E,CACtE,cAAW,QAAQ,SAAW,IAAA,GAClC,GAAI,CACF,IAAM,EAAO,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,kBAC1B,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"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["infoFor","MAX_MESSAGES_PER_KEY","isSealedEnvelope","require_sealedChannel","KEY_ALGORITHM","CIPHER","bytes","binary","value","out","index","base64Url","byte","view","copy","derive","material","secret","direction","nonceFor","nonce","prefix","counter","channelFrom","sendCounter","highestReceived","noncePrefix","sealed","sendKey","plaintext","shape","envelope","body","receiveKey","connectSealedChannel","pair","hostKey","hostPublicKey","peer","clientPublicKey","channelFromSecret","sendDirection"],"sources":["../../../src/services/browserSealedChannel/index.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';\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":"iDAuBMI,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpDC,EAAS,UAef,SAASC,EAAM,EAAuC,CACpD,IAAIC,EACJ,GAAI,CACF,EAAS,KAAKC,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAMC,EAAM,IAAI,WAAW,IAAI,YAAYF,EAAO,MAAM,CAAC,EACzD,IAAK,IAAIG,EAAQ,EAAGA,EAAQH,EAAO,OAAQ,GAAS,EAAG,EAAIG,GAASH,EAAO,WAAWG,CAAK,EAC3F,OAAOD,CACT,CAEA,SAASE,EAAU,EAA2B,CAC5C,IAAIJ,EAAS,GACb,IAAK,IAAMK,KAAQJ,EAAO,GAAU,OAAO,aAAaI,CAAI,EAC5D,OAAO,KAAKL,CAAM,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,EAAE,CAClF,CAEA,SAASM,EAAK,EAAgC,CAC5C,IAAMC,EAAO,IAAI,WAAW,IAAI,YAAYN,EAAM,MAAM,CAAC,EAEzD,OADAM,EAAK,IAAIN,CAAK,EACPM,EAAK,MACd,CAEA,eAAeC,EAAO,EAAqB,EAAgD,CACzF,IAAMC,EAAW,MAAM,OAAO,OAAO,UAAU,MAAOC,EAAQ,OAAQ,GAAO,CAAC,WAAW,CAAC,EAC1F,OAAO,MAAM,OAAO,OAAO,UACzB,CACE,KAAM,OACN,KAAM,UACN,KAAMJ,EAAK,IAAI,YAAY,CAAC,CAAC,OAAO,kBAAS,CAAC,EAC9C,K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1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsBuB,EACpB,EACA,EACA,EACwB,CAGxB,OAAOjB,EAAY,MAFAR,EAAOE,EAAQwB,CAAa,EAEtB,MADH1B,EAAOE,EAAQwB,IAAkB,MAAQ,MAAQ,KAAK,EAC1Cf,CAAW,CAC/C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/browserSealedChannel/index.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';\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":"wGAuBA,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,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,EAAgD,CACzF,IAAM,EAAW,MAAM,OAAO,OAAO,UAAU,MAAO,EAAQ,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AK,kBAC1B,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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["KEY_ALGORITHM","CIPHER","bytes","binary","value","out","index","base64Url","byte","view","copy","derive","material","secret","infoFor","direction","nonceFor","nonce","prefix","counter","channelFrom","sendCounter","highestReceived","MAX_MESSAGES_PER_KEY","noncePrefix","sealed","sendKey","plaintext","shape","envelope","isSealedEnvelope","body","receiveKey","connectSealedChannel","pair","hostKey","hostPublicKey","peer","clientPublicKey","channelFromSecret","sendDirection"],"sources":["../../../src/services/browserSealedChannel/index.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';\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":"wGAuBA,MAAMA,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpDC,EAAS,UAef,SAASC,EAAM,EAAuC,CACpD,IAAIC,EACJ,GAAI,CACF,EAAS,KAAKC,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAMC,EAAM,IAAI,WAAW,IAAI,YAAYF,EAAO,MAAM,CAAC,EACzD,IAAK,IAAIG,EAAQ,EAAGA,EAAQH,EAAO,OAAQ,GAAS,EAAG,EAAIG,GAASH,EAAO,WAAWG,CAAK,EAC3F,OAAOD,CACT,CAEA,SAASE,EAAU,EAA2B,CAC5C,IAAIJ,EAAS,GACb,IAAK,IAAMK,KAAQJ,EAAO,GAAU,OAAO,aAAaI,CAAI,EAC5D,OAAO,KAAKL,CAAM,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAAC,W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AAA,GAAW,OAC3B,IAAME,EAAO,MAAM,OAAO,OAAO,UAAU,MAAO5B,EAAK0B,CAAO,EAAGnC,EAAe,GAAO,CAAC,CAAC,EACnFa,EAAS,MAAM,OAAO,OAAO,WAAW,CAAE,KAAM,OAAQ,OAAQwB,CAAK,EAAGH,EAAK,WAAY,GAAQ,EACjGI,EAAkB/B,EAAU,IAAI,WAAW,MAAM,OAAO,OAAO,UAAU,MAAO2B,EAAK,SAAS,CAAC,CAAC,EACtG,MAAO,CACL,QAASd,EACP,MAAMT,EAAOE,EAAQ,KAAK,EAC1B,MAAMF,EAAOE,EAAQ,KAAK,kBAC1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsB0B,EACpB,EACA,EACA,EACwB,CAGxB,OAAOnB,EAAY,MAFAT,EAAOE,EAAQ2B,CAAa,EAEtB,MADH7B,EAAOE,EAAQ2B,IAAkB,MAAQ,MAAQ,KAAK,EAC1ChB,CAAW,CAC/C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","createPublicKey"],"sources":["../../../src/services/bundleSigner/index.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';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type SignedBundleManifest,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\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":"mNAoBA,MAAM,EAAe,eAMf,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1B,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QA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A,iBAAiB,CAAQ,EAAG,MAAU,MAAM,6CAA6C,EAK9F,MAAO,CAAE,WAAU,WAAA,EAJDC,EAAAA,WAAAA,CAAW,QAAc,CAAC,CACzC,OAAOC,EAAAA,kBAAkB,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,EAAWP,EAAAA,QAAK,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,EAAWA,EAAAA,QAAK,QAAQ,CAAS,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"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","createPublicKey","require_runtime","require_bundleManifest","node_crypto","node_fs","node_path","SIGNING_FILE","SKIPPED","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createBundleSigner","key","privateKey","cache","signFresh","rootStat","assetsDir","assets","left","right","manifest","sign","cacheKey","signed","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.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';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type SignedBundleManifest,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\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":"mNAoBA,MAAMe,EAAe,eAMfC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,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,SAASC,EAAqB,EAAwB,CACpDL,EAAA,QAAG,UAAUM,EAAU,CAAE,UAAW,GAAM,KAAM,GAAe,CAAC,EAChE,IAAMC,EAAOpB,EAAAA,QAAG,UAAUmB,CAAQ,EAClC,GAAI,CAACC,EAAK,YAAY,GAAKA,EAAK,eAAe,EAC7C,MAAU,MAAM,4CAA4CD,GAAU,EACxEN,EAAA,QAAG,UAAUM,EAAU,GAAc,CACvC,CAEA,SAASE,EAAiB,EAAkB,EAAuB,CACjEH,EAAqBC,CAAQ,EAC7B,IAAMG,EAAWrB,EAAAA,QAAK,KAAKkB,EAAU,cAAS,EAC1CI,EACJ,IAAK,IAAIC,EAAU,EAAGA,EAAU,IAAK,GAAW,EAC9C,GAAI,CACF,EAAaxB,EAAAA,QAAG,SAASsB,EAAU,KAAM,GAAS,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AAK,QAAQ4D,CAAS,EACvC,GAAIH,EAAM,IAAIS,CAAQ,EAAG,OAAOT,EAAM,IAAIS,CAAQ,EAClD,IAAMC,EAAST,EAAUQ,CAAQ,EAEjC,OADAT,EAAM,IAAIS,EAAUC,CAAM,EACnBA,CACT,EAEA,MAAO,CACL,cAAiBZ,EAAI,UACrB,OACA,QAAQ,EAAW,CACjB,IAAMW,EAAWlE,EAAAA,QAAK,QAAQ4D,CAAS,EAEvC,OADAH,EAAM,OAAOS,CAAQ,EACdD,EAAKC,CAAQ,CACtB,EACA,WAAW,EAAW,CAChBN,IAAc,IAAA,GAAWH,EAAM,MAAM,EACpCA,EAAM,OAAOzD,EAAAA,QAAK,QAAQ4D,CAAS,CAAC,CAC3C,CACF,CACF,CAGA,SAAgBxB,EAAY,EAA+B,CACzD,OAAO,OAAO,MAAA,EAAK5B,EAAAA,gBAAAA,CAAgB4D,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/bundleSigner/index.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';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type SignedBundleManifest,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\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":"uRAoBA,MAAM,EAAe,eAMf,kBAAU,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,OA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AQ,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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["fs","path","SIGNING_FILE","SKIPPED","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","randomBytes","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","generateKeyPairSync","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createHash","createBundleSigner","key","privateKey","createPrivateKey","cache","signFresh","rootStat","assetsDir","assets","left","right","manifest","isBundleManifest","createSign","canonicalManifest","sign","cacheKey","signed","createPublicKey","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.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';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type SignedBundleManifest,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\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":"uRAoBA,MAAME,EAAe,eAMfC,kBAAU,IAAI,IAAI,CAAC,MA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B,EAAgBxB,EAAUwC,EAAI,SAAS,EACjD,QAAS,KAAK,IAAI,EAClB,QACF,EACA,GAAI,CAACW,EAAiBD,CAAQ,EAAG,MAAU,MAAM,6CAA6C,EAK9F,MAAO,CAAE,WAAU,UAJDE,EAAW,QAAc,CAAC,CACzC,OAAOC,EAAkBH,CAAQ,CAAC,CAAC,CACnC,KAAK,CAAE,IAAKT,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WACe,EAAG,UAAWD,EAAI,SAAU,CACzD,EAEMc,EAAQ,GAAwD,CACpE,IAAMC,EAAW5D,EAAK,QAAQmD,CAAS,EACvC,GAAIH,EAAM,IAAIY,CAAQ,EAAG,OAAOZ,EAAM,IAAIY,CAAQ,EAClD,IAAMC,EAASZ,EAAUW,CAAQ,EAEjC,OADAZ,EAAM,IAAIY,EAAUC,CAAM,EACnBA,CACT,EAEA,MAAO,CACL,cAAiBhB,EAAI,UACrB,OACA,QAAQ,EAAW,CACjB,IAAMe,EAAW5D,EAAK,QAAQmD,CAAS,EAEvC,OADAH,EAAM,OAAOY,CAAQ,EACdD,EAAKC,CAAQ,CACtB,EACA,WAAW,EAAW,CAChBT,IAAc,IAAA,GAAWH,EAAM,MAAM,EACpCA,EAAM,OAAOhD,EAAK,QAAQmD,CAAS,CAAC,CAC3C,CACF,CACF,CAGA,SAAgB3B,EAAY,EAA+B,CACzD,OAAO,OAAO,KAAKsC,EAAgBC,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["hkdfSync","infoFor","MAX_MESSAGES_PER_KEY","createCipheriv","isSealedEnvelope","createDecipheriv","ECDH","createECDH","randomBytes"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\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';\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\nexport interface ClientHandshake {\n /** Base64url uncompressed P-256 point sent to the host. */\n publicKey: string;\n /** Completes the exchange against the host's fresh key and yields the channel. */\n accept(hostPublicKey: 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\nfunction ecdhPoint(value: string): Buffer | undefined {\n if (value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;\n let encoded: Buffer;\n try {\n encoded = Buffer.from(value, 'base64url');\n } catch {\n return undefined;\n }\n if (\n (encoded.length !== 65 && encoded.length !== 33) ||\n (encoded.length === 65 ? encoded[0] !== 4 : encoded[0] !== 2 && encoded[0] !== 3) ||\n encoded.toString('base64url') !== value\n )\n return undefined;\n try {\n return ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n } catch {\n return undefined;\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 const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\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\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"8EAcA,MAAM,EAAQ,aACR,EAAS,cAKT,EAAY,OAAO,KAAK,kBAAkB,EAyBhD,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,IAAkB,MAAQ,MAAQ,KAAK,EACrE,EAAc,GAEd,EAAkB,CAAC,GAEvB,MAAO,CACL,KAAK,EAAW,CACd,GAAI,GAAe,OAAOC,EAAAA,oBAAoB,EAAG,MAAO,CAAE,GAAI,GAAO,QAAS,WAAY,EAC1F,IAAM,EAAQ,EAAS,EAAa,CAAW,EACzC,GAAA,EAASC,EAAAA,eAAAA,CAAe,EAAQ,EAAS,CAAK,EAC9C,EAAO,OAAO,OAAO,CAAC,EAAO,OAAO,CAAS,EAAG,EAAO,MAAM,EAAG,EAAO,WAAW,CAAC,CAAC,EAE1F,MADA,IAAe,GACR,CACL,GAAI,GACJ,SAAU,CAAE,EAAA,EAAmB,EAAG,EAAM,SAAS,WAAW,EAAG,EAAG,EAAK,SAAS,WAAW,CAAE,CAC/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ECDH","createECDH","randomBytes","require_sealedChannel","node_crypto","CURVE","CIPHER","HKDF_SALT","derive","secret","direction","nonceFor","nonce","prefix","counter","createChannel","sendKey","sendDirection","receiveKey","sendCounter","highestReceived","noncePrefix","cipher","body","plaintext","shape","envelope","decipher","ecdhPoint","value","encoded","createHostHandshake","exchange","acceptedPeers","peer","peerPublicKey","createClientHandshake","accepted","host","hostPublicKey"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\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';\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\nexport interface ClientHandshake {\n /** Base64url uncompressed P-256 point sent to the host. */\n publicKey: string;\n /** Completes the exchange against the host's fresh key and yields the channel. */\n accept(hostPublicKey: 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\nfunction ecdhPoint(value: string): Buffer | undefined {\n if (value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;\n let encoded: Buffer;\n try {\n encoded = Buffer.from(value, 'base64url');\n } catch {\n return undefined;\n }\n if (\n (encoded.length !== 65 && encoded.length !== 33) ||\n (encoded.length === 65 ? encoded[0] !== 4 : encoded[0] !== 2 && encoded[0] !== 3) ||\n encoded.toString('base64url') !== value\n )\n return undefined;\n try {\n return ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n } catch {\n return undefined;\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 const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\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\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"8EAcA,MAAMW,EAAQ,aACRC,EAAS,cAKTC,EAAY,OAAO,KAAK,kBAAkB,EAyBhD,SAASC,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,MAAA,EAAKd,EAAAA,SAAAA,CAAS,SAAWe,EAAQF,EAAW,OAAO,KAAKZ,EAAAA,QAAQe,CAAS,CAAC,EAAG,EAAS,CAAC,CACvG,CAUA,SAASC,EAAS,EAAgB,EAAyB,CACzD,IAAMC,EAAQ,OAAO,MAAA,EAAiB,EAGtC,OAFAC,EAAO,KAAKD,EAAO,EAAG,EAAA,CAAqB,EAC3CA,EAAM,iBAAiBE,EAAA,CAA2B,EAC3CF,CACT,CAQA,SAASG,EAAc,EAAgB,EAAgC,EAAoC,CACzG,IAAMC,EAAUR,EAAOC,EAAQQ,CAAa,EACtCC,EAAaV,EAAOC,EAAQQ,IAAkB,MAAQ,MAAQ,KAAK,EACrEE,EAAc,GAEdC,EAAkB,CAAC,GAEvB,MAAO,CACL,KAAK,EAAW,CACd,GAAID,GAAe,OAAOvB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AAAA,CAAWI,CAAK,EACjC2B,EAAS,aAAa,EACtB,IAAIK,EAAW,GACf,MAAO,CACL,UAAWL,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,GAAIK,EAAU,OACd,IAAMC,EAAOV,EAAUW,CAAa,EACpC,GAAID,IAAS,IAAA,GAAW,OACxB,IAAI7B,EACJ,GAAI,CACF,EAASuB,EAAS,cAAcM,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJvB,EAAcN,EAAQ,OAAA,EAAOP,EAAAA,YAAAA,CAAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\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';\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\nexport interface ClientHandshake {\n /** Base64url uncompressed P-256 point sent to the host. */\n publicKey: string;\n /** Completes the exchange against the host's fresh key and yields the channel. */\n accept(hostPublicKey: 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\nfunction ecdhPoint(value: string): Buffer | undefined {\n if (value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;\n let encoded: Buffer;\n try {\n encoded = Buffer.from(value, 'base64url');\n } catch {\n return undefined;\n }\n if (\n (encoded.length !== 65 && encoded.length !== 33) ||\n (encoded.length === 65 ? encoded[0] !== 4 : encoded[0] !== 2 && encoded[0] !== 3) ||\n encoded.toString('base64url') !== value\n )\n return undefined;\n try {\n return ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n } catch {\n return undefined;\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 const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\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\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"oOAcA,MAAM,EAAQ,aACR,EAAS,cAKT,EAAY,OAAO,KAAK,kBAAkB,EAyBhD,SAAS,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,KAAK,EAAS,SAAW,EAAQ,EAAW,OAAO,KAAK,EAAQ,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,EA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a,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,GAAI,EAAU,OACd,IAAM,EAAO,EAAU,CAAa,EACpC,GAAI,IAAS,IAAA,GAAW,OACxB,IAAI,EACJ,GAAI,CACF,EAAS,EAAS,cAAc,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJ,EAAc,EAAQ,MAAO,EAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["CURVE","CIPHER","HKDF_SALT","derive","hkdfSync","secret","infoFor","direction","nonceFor","nonce","prefix","counter","createChannel","sendKey","sendDirection","receiveKey","sendCounter","highestReceived","MAX_MESSAGES_PER_KEY","noncePrefix","cipher","createCipheriv","body","plaintext","shape","envelope","isSealedEnvelope","decipher","createDecipheriv","ecdhPoint","value","encoded","ECDH","createHostHandshake","exchange","createECDH","acceptedPeers","peer","peerPublicKey","randomBytes","createClientHandshake","accepted","host","hostPublicKey"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\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';\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\nexport interface ClientHandshake {\n /** Base64url uncompressed P-256 point sent to the host. */\n publicKey: string;\n /** Completes the exchange against the host's fresh key and yields the channel. */\n accept(hostPublicKey: 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\nfunction ecdhPoint(value: string): Buffer | undefined {\n if (value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;\n let encoded: Buffer;\n try {\n encoded = Buffer.from(value, 'base64url');\n } catch {\n return undefined;\n }\n if (\n (encoded.length !== 65 && encoded.length !== 33) ||\n (encoded.length === 65 ? encoded[0] !== 4 : encoded[0] !== 2 && encoded[0] !== 3) ||\n encoded.toString('base64url') !== value\n )\n return undefined;\n try {\n return ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n } catch {\n return undefined;\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 const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\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\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"oOAcA,MAAMA,EAAQ,aACRC,EAAS,cAKTC,EAAY,OAAO,KAAK,kBAAkB,EAyBhD,SAASC,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,KAAKC,EAAS,SAAWC,EAAQH,EAAW,OAAO,KAAKI,EAAQC,CAAS,CAAC,EAAG,EAAS,CAAC,CACvG,CAUA,SAASC,EAAS,EAAgB,EAAyB,CACzD,IAAMC,EAAQ,OAAO,MAAA,EAAiB,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S6B,EAAS,cAAcG,CAAI,CACtC,MAAQ,CACN,MACF,CAIA,OAHAD,EAAc,IAAIC,EAAK,SAAS,WAAW,CAAC,EAGrCzB,EAAcP,EAAQ,MAAOkC,EAAA,CAA8B,CAAC,CACrE,CACF,CACF,CAGA,SAAgBC,GAAyC,CACvD,IAAMN,EAAWC,EAAWnC,CAAK,EACjCkC,EAAS,aAAa,EACtB,IAAIO,EAAW,GACf,MAAO,CACL,UAAWP,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,GAAIO,EAAU,OACd,IAAMC,EAAOb,EAAUc,CAAa,EACpC,GAAID,IAAS,IAAA,GAAW,OACxB,IAAIrC,EACJ,GAAI,CACF,EAAS6B,EAAS,cAAcQ,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJ9B,EAAcP,EAAQ,MAAOkC,EAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createSerialQueue","describeSealedFailure","connectSealedChannel"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealed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MAAM,EAAU,MAAM,EAAc,KAAK,CAAC,EACzD,GAAI,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAO,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAI,EACJ,GAAI,CACF,EAAU,KAAK,MAAM,EAAQ,OAAO,CAAM,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAAC,EAAqB,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAO,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAM,EAAO,EAAa,EAAQ,IAAI,EACtC,OAAO,IAAI,SAAS,EAAQ,SAAW,KAAO,EAAQ,SAAW,KAAO,EAAQ,SAAW,IAAM,KAAO,EAAM,CAC5G,OAAQ,EAAQ,OAChB,QAAS,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAa,EAAkB,EAAsB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createSerialQueue","describeSealedFailure","connectSealedChannel","require_sealedChannel","require_index","require_index$1","encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","inbound","exchange","relayPath","note","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"sIAkCMM,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS,SAAU,OAAOV,EAAQ,OAAOU,CAAI,EACxD,GAAIA,aAAgB,gBAAiB,OAAOV,EAAQ,OAAOU,EAAK,SAAS,CAAC,EAC1E,GAAIA,aAAgB,KAAM,OAAO,IAAI,WAAW,MAAMA,EAAK,YAAY,CAAC,EACxE,GAAIA,aAAgB,YAAa,OAAO,IAAI,WAAWA,CAAI,EAC3D,GAAI,YAAY,OAAOA,CAAI,EAAG,OAAO,IAAI,WAAWA,EAAK,OAAQA,EAAK,WAAYA,EAAK,UAAU,EACjG,MAAU,MAAM,oEAAoE,CAL5B,CAM1D,CAEA,SAASC,EAAc,EAAuB,CAC5C,GAAI,CAACC,EAAM,WAAW,GAAG,EAAG,MAAU,MAAM,qDAAqD,EACjG,OAAOA,CACT,CAEA,SAASC,EAAqB,EAA6C,CACzE,GAAI,OAAON,GAAU,WAAYA,EAAgB,MAA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":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"4MAmBA,MAeM,EAAU,IAAI,YACd,EAAU,IAAI,YAiBpB,SAAS,EAAa,EAA2B,CAC/C,IAAI,EAAS,GACb,IAAK,IAAM,KAAQ,EAAO,GAAU,OAAO,aAAa,CAAI,EAC5D,OAAO,KAAK,CAAM,CACpB,CAEA,SAAS,EAAa,EAA2B,CAC/C,IAAM,EAAS,KAAK,CAAK,EACzB,OAAO,WAAW,KAAK,EAAS,GAAc,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAe,EAAU,EAA4D,CAC/E,MAA+B,KACnC,IAAI,OAAO,GAAS,SAAU,OAAO,EAAQ,OAAO,CAAI,EACxD,GAAI,aAAgB,gBAAiB,OAAO,EAAQ,OAAO,EAAK,SAAS,CAAC,EAC1E,GAAI,aAAgB,KAAM,OAAO,IAAI,WAAW,MAAM,EAAK,YAAY,CAAC,EACxE,GAAI,aAAgB,YAAa,OAAO,IAAI,WAAW,CAAI,EAC3D,GAAI,YAAY,OAAO,CAAI,EAAG,OAAO,IAAI,WAAW,EAAK,OAAQ,EAAK,WA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,CAAK,EAC3B,QAAS,MAAM,KAAK,IAAI,QAAQ,GAAM,OAAO,CAAC,CAAC,QAAQ,CAAC,EACxD,GAAI,IAAU,IAAA,GAAY,CAAC,EAAI,CAAE,KAAM,EAAa,CAAK,CAAE,CAC7D,EACM,EAAS,MAAM,EAAU,EAAQ,OAAO,KAAK,UAAU,CAAO,CAAC,CAAC,EACtE,GAAI,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAO,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAM,EAAgB,MAAM,MAAM,EAAS,CACzC,OAAQ,OACR,YAAa,cACb,QAAS,CAAE,eAAgB,kBAAkB,EAC7C,KAAM,CACR,CAAC,EACK,EAAS,MAAM,EAAU,MAAM,EAAc,KAAK,CAAC,EACzD,GAAI,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAO,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAI,EACJ,GAAI,CACF,EAAU,KAAK,MAAM,EAAQ,OAAO,CAAM,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAAC,EAAqB,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAO,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAM,EAAO,EAAa,EAAQ,IAAI,EACtC,OAAO,IAAI,SAAS,EAAQ,SAAW,KAAO,EAAQ,SAAW,KAAO,EAAQ,SAAW,IAAM,KAAO,EAAM,CAC5G,OAAQ,EAAQ,OAChB,QAAS,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAa,EAAkB,EAAsB"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","createSerialQueue","inbound","exchange","relayPath","note","describeSealedFailure","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","connectSealedChannel","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"4MAmBA,MAeMA,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS,SAAU,OAAOV,EAAQ,OAAOU,CAAI,EACxD,GAAIA,aAAgB,gBAAiB,OAAOV,EAAQ,OAA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CAAE,MAAOvB,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAaoC,EAAQ,IAAI,EACtC,OAAO,IAAI,SAASA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAOhC,EAAM,CAC5G,OAAQgC,EAAQ,OAChB,QAASA,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAaC,EAAkB1B,EAAsB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/services/serialQueue/index.ts"],"sourcesContent":["/**\n * Runs async work strictly one at a time, in the order it was handed over.\n *\n * The sealed channel needs this on both directions and it is not an\n * optimisation. Sealing increments a nonce counter and opening enforces that\n * the counter strictly increases, so two overlapping operations are a\n * correctness bug rather than a race worth tolerating: two concurrent seals can\n * resolve out of order and reach the wire with descending counters, and two\n * concurrent opens can advance the high-water mark past a message that has not\n * been read yet, which the receiver then rejects as a replay.\n *\n * Deliberately not a general work pool. A pool with any concurrency above one\n * reintroduces exactly the reordering this exists to prevent.\n */\nexport interface SerialQueue {\n /** Resolves with the task's result once every task queued before it has settled. */\n run<T>(task: () => Promise<T>): Promise<T>;\n}\n\nexport function createSerialQueue(): SerialQueue {\n /** The tail of the chain. Rejections are absorbed so one failure cannot stall the rest. */\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n run<T>(task: () => Promise<T>): Promise<T> {\n const result = tail.then(task, task);\n tail = result.catch(() => undefined);\n return result;\n },\n };\n}\n"],"mappings":"AAmBA,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createSerialQueue","tail","result","task"],"sources":["../../../src/services/serialQueue/index.ts"],"sourcesContent":["/**\n * Runs async work strictly one at a time, in the order it was handed over.\n *\n * The sealed channel needs this on both directions and it is not an\n * optimisation. Sealing increments a nonce counter and opening enforces that\n * the counter strictly increases, so two overlapping operations are a\n * correctness bug rather than a race worth tolerating: two concurrent seals can\n * resolve out of order and reach the wire with descending counters, and two\n * concurrent opens can advance the high-water mark past a message that has not\n * been read yet, which the receiver then rejects as a replay.\n *\n * Deliberately not a general work pool. A pool with any concurrency above one\n * reintroduces exactly the reordering this exists to prevent.\n */\nexport interface SerialQueue {\n /** Resolves with the task's result once every task queued before it has settled. */\n run<T>(task: () => Promise<T>): Promise<T>;\n}\n\nexport function createSerialQueue(): SerialQueue {\n /** The tail of the chain. Rejections are absorbed so one failure cannot stall the rest. */\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n run<T>(task: () => Promise<T>): Promise<T> {\n const result = tail.then(task, task);\n tail = result.catch(() => undefined);\n return result;\n },\n };\n}\n"],"mappings":"AAmBA,SAAgBA,GAAiC,CAE/C,IAAIC,EAAyB,QAAQ,QAAQ,EAE7C,MAAO,CACL,IAAO,EAAoC,CACzC,IAAMC,EAASD,EAAK,KAAKE,EAAMA,CAAI,EAEnC,MADA,GAAOD,EAAO,UAAY,IAAA,EAAS,EAC5BA,CACT,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/services/serialQueue/index.ts"],"sourcesContent":["/**\n * Runs async work strictly one at a time, in the order it was handed over.\n *\n * The sealed channel needs this on both directions and it is not an\n * optimisation. Sealing increments a nonce counter and opening enforces that\n * the counter strictly increases, so two overlapping operations are a\n * correctness bug rather than a race worth tolerating: two concurrent seals can\n * resolve out of order and reach the wire with descending counters, and two\n * concurrent opens can advance the high-water mark past a message that has not\n * been read yet, which the receiver then rejects as a replay.\n *\n * Deliberately not a general work pool. A pool with any concurrency above one\n * reintroduces exactly the reordering this exists to prevent.\n */\nexport interface SerialQueue {\n /** Resolves with the task's result once every task queued before it has settled. */\n run<T>(task: () => Promise<T>): Promise<T>;\n}\n\nexport function createSerialQueue(): SerialQueue {\n /** The tail of the chain. Rejections are absorbed so one failure cannot stall the rest. */\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n run<T>(task: () => Promise<T>): Promise<T> {\n const result = tail.then(task, task);\n tail = result.catch(() => undefined);\n return result;\n },\n };\n}\n"],"mappings":"AAmBA,
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["createSerialQueue","tail","result","task"],"sources":["../../../src/services/serialQueue/index.ts"],"sourcesContent":["/**\n * Runs async work strictly one at a time, in the order it was handed over.\n *\n * The sealed channel needs this on both directions and it is not an\n * optimisation. Sealing increments a nonce counter and opening enforces that\n * the counter strictly increases, so two overlapping operations are a\n * correctness bug rather than a race worth tolerating: two concurrent seals can\n * resolve out of order and reach the wire with descending counters, and two\n * concurrent opens can advance the high-water mark past a message that has not\n * been read yet, which the receiver then rejects as a replay.\n *\n * Deliberately not a general work pool. A pool with any concurrency above one\n * reintroduces exactly the reordering this exists to prevent.\n */\nexport interface SerialQueue {\n /** Resolves with the task's result once every task queued before it has settled. */\n run<T>(task: () => Promise<T>): Promise<T>;\n}\n\nexport function createSerialQueue(): SerialQueue {\n /** The tail of the chain. Rejections are absorbed so one failure cannot stall the rest. */\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n run<T>(task: () => Promise<T>): Promise<T> {\n const result = tail.then(task, task);\n tail = result.catch(() => undefined);\n return result;\n },\n };\n}\n"],"mappings":"AAmBA,SAAgBA,GAAiC,CAE/C,IAAIC,EAAyB,QAAQ,QAAQ,EAE7C,MAAO,CACL,IAAO,EAAoC,CACzC,IAAMC,EAASD,EAAK,KAAKE,EAAMA,CAAI,EAEnC,MADA,GAAOD,EAAO,UAAY,IAAA,EAAS,EAC5BA,CACT,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleManifest.cjs","names":[],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\nexport function isBundleManifest(value: unknown): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return paths.has('/index.html');\n}\n\nexport function isSignedBundleManifest(value: unknown): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,
|
|
1
|
+
{"version":3,"file":"bundleManifest.cjs","names":["SHA256","BASE64URL","CONTENT_TYPE","hasExactKeys","keys","value","expected","key","index","isSafeInteger","minimum","isSafeAssetPath","segment","canonicalManifest","lines","manifest","left","right","asset","isBundleManifest","candidate","paths","valueAsset","isSignedBundleManifest","assetFor","path","digestFor"],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\nexport function isBundleManifest(value: unknown): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return paths.has('/index.html');\n}\n\nexport function isSignedBundleManifest(value: unknown): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,MAGMA,EAAS,kBACTC,EAAY,oBACZC,EAAe,4DA6BrB,SAASC,EAAa,EAAe,EAAsC,CACzE,IAAMC,EAAO,OAAO,KAAKC,CAAK,CAAC,CAAC,KAAK,EACrC,OAAOD,EAAK,SAAWE,EAAS,QAAUF,EAAK,OAAO,EAAK,IAAUG,IAAQD,EAASE,EAAM,CAC9F,CAEA,SAASC,EAAc,EAAgB,EAAkC,CACvE,OAAO,OAAOJ,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,GAASK,CAC9E,CAEA,SAASC,EAAgB,EAAiC,CAKxD,OAJI,OAAON,GAAU,UAAYA,EAAM,OAAS,GAAK,CAACA,EAAM,WAAW,GAAG,GACtEA,EAAM,SAAS,IAAI,GAAKA,EAAM,SAAS,IAAI,GAAKA,EAAM,SAAS,GAAG,GAAKA,EAAM,SAAS,GAAG,GACzF,gBAAgB,KAAKA,CAAK,GAA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EAAM,QAAW,UAAY,CAAClB,EAAO,KAAKkB,EAAM,MAAM,GAC7D,CAACT,EAAcS,EAAM,WAAY,CAAC,GAClC,OAAOA,EAAM,aAAgB,UAAY,CAAChB,EAAa,KAAKgB,EAAM,WAAW,EAAG,MAAO,GAC3FG,EAAM,IAAIH,EAAM,IAAI,CACtB,CACA,OAAOG,EAAM,IAAI,aAAa,CAChC,CAEA,SAAgBE,EAAuB,EAA+C,CAEpF,GADI,OAAOlB,GAAU,WAAYA,GAC7B,CAACF,EAAaE,EAAO,CAAC,WAAY,YAAa,WAAW,CAAC,EAAG,MAAO,GACzE,IAAMe,EAAYf,EAClB,OACEc,EAAiBC,EAAU,QAAQ,GACnC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,SAAW,IAC/BnB,EAAU,KAAKmB,EAAU,SAAS,GAClC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,QAAU,KAC9BnB,EAAU,KAAKmB,EAAU,SAAS,CAEtC,CAGA,SAAgBI,EAAS,EAA0B,EAAuC,CACxF,OAAOT,EAAS,OAAO,KAAM,GAAUG,EAAM,OAASO,CAAI,CAC5D,CAGA,SAAgBC,EAAU,EAA0B,EAAkC,CACpF,OAAOF,EAAST,EAAUU,CAAI,CAAC,EAAE,MACnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundleManifest.mjs","names":[],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\nexport function isBundleManifest(value: unknown): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return paths.has('/index.html');\n}\n\nexport function isSignedBundleManifest(value: unknown): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,
|
|
1
|
+
{"version":3,"file":"bundleManifest.mjs","names":["BUNDLE_MANIFEST_ROUTE","BUNDLE_MANIFEST_VERSION","SHA256","BASE64URL","CONTENT_TYPE","hasExactKeys","keys","value","expected","key","index","isSafeInteger","minimum","isSafeAssetPath","segment","canonicalManifest","lines","manifest","left","right","asset","isBundleManifest","candidate","paths","valueAsset","isSignedBundleManifest","assetFor","path","digestFor"],"sources":["../../src/types/bundleManifest.ts"],"sourcesContent":["/**\n * A signed description of cockpit assets for an independently trusted verifier.\n *\n * A manifest does not let a browser SPA defend itself against the server or TLS\n * edge that supplied its executable code. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 2;\n\nconst SHA256 = /^[0-9a-f]{64}$/u;\nconst BASE64URL = /^[A-Za-z0-9_-]+$/u;\nconst CONTENT_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u;\n\nexport interface BundleAsset {\n /** Normalized absolute URL path, without a query or fragment. */\n path: string;\n /** Lowercase hex SHA-256 of the served bytes. */\n sha256: string;\n byteLength: number;\n /** MIME type of the response, without parameters. */\n contentType: string;\n}\n\nexport interface BundleManifest {\n version: typeof BUNDLE_MANIFEST_VERSION;\n /** Monotonically increasing persistent signer revision. */\n revision: number;\n /** Unix time in milliseconds. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the signing key. Trust must be established out of band. */\n publicKey: string;\n}\n\nfunction hasExactKeys(value: object, expected: readonly string[]): boolean {\n const keys = Object.keys(value).sort();\n return keys.length === expected.length && keys.every((key, index) => key === expected[index]);\n}\n\nfunction isSafeInteger(value: unknown, minimum: number): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;\n}\n\nfunction isSafeAssetPath(value: unknown): value is string {\n if (typeof value !== 'string' || value.length < 2 || !value.startsWith('/')) return false;\n if (value.includes('\\\\') || value.includes('\\0') || value.includes('?') || value.includes('#')) return false;\n if (/[^\\x21-\\x7e]/u.test(value) || value.includes('//') || /%(?![0-9a-f]{2})/iu.test(value)) return false;\n if (/%(?:2e|2f|5c)/iu.test(value)) return false;\n return value\n .split('/')\n .slice(1)\n .every((segment) => segment !== '' && segment !== '.' && segment !== '..');\n}\n\n/** The exact bytes signed by Node and verified by WebCrypto. */\nexport function canonicalManifest(manifest: BundleManifest): string {\n const assets = [...manifest.assets].sort((left, right) =>\n left.path < right.path ? -1 : left.path > right.path ? 1 : 0,\n );\n const lines = assets.map(\n (asset) => `${asset.path}\\0${asset.sha256}\\0${String(asset.byteLength)}\\0${asset.contentType}`,\n );\n return [String(manifest.version), String(manifest.revision), String(manifest.builtAt), ...lines].join('\\n');\n}\n\nexport function isBundleManifest(value: unknown): value is BundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['assets', 'builtAt', 'revision', 'version'])) return false;\n const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (!isSafeInteger(candidate.revision, 1) || !isSafeInteger(candidate.builtAt, 0)) return false;\n if (!Array.isArray(candidate.assets) || candidate.assets.length === 0) return false;\n\n const paths = new Set<string>();\n for (const valueAsset of candidate.assets) {\n if (typeof valueAsset !== 'object' || valueAsset === null) return false;\n if (!hasExactKeys(valueAsset, ['byteLength', 'contentType', 'path', 'sha256'])) return false;\n const asset = valueAsset as Partial<BundleAsset>;\n if (!isSafeAssetPath(asset.path) || paths.has(asset.path)) return false;\n if (typeof asset.sha256 !== 'string' || !SHA256.test(asset.sha256)) return false;\n if (!isSafeInteger(asset.byteLength, 0)) return false;\n if (typeof asset.contentType !== 'string' || !CONTENT_TYPE.test(asset.contentType)) return false;\n paths.add(asset.path);\n }\n return paths.has('/index.html');\n}\n\nexport function isSignedBundleManifest(value: unknown): value is SignedBundleManifest {\n if (typeof value !== 'object' || value === null) return false;\n if (!hasExactKeys(value, ['manifest', 'publicKey', 'signature'])) return false;\n const candidate = value as Partial<SignedBundleManifest>;\n return (\n isBundleManifest(candidate.manifest) &&\n typeof candidate.signature === 'string' &&\n candidate.signature.length === 86 &&\n BASE64URL.test(candidate.signature) &&\n typeof candidate.publicKey === 'string' &&\n candidate.publicKey.length <= 512 &&\n BASE64URL.test(candidate.publicKey)\n );\n}\n\n/** The recorded asset for one path, or undefined if the manifest does not cover it. */\nexport function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined {\n return manifest.assets.find((asset) => asset.path === path);\n}\n\n/** The recorded digest for one asset, or undefined if the manifest does not cover it. */\nexport function digestFor(manifest: BundleManifest, path: string): string | undefined {\n return assetFor(manifest, path)?.sha256;\n}\n"],"mappings":"AAQA,MAAaA,EAAwB,wBACxBC,EAA0B,EAEjCC,EAAS,kBACTC,EAAY,oBACZC,EAAe,4DA6BrB,SAASC,EAAa,EAAe,EAAsC,CACzE,IAAMC,EAAO,OAAO,KAAKC,CAAK,CAAC,CAAC,KAAK,EACrC,OAAOD,EAAK,SAAWE,EAAS,QAAUF,EAAK,OAAO,EAAK,IAAUG,IAAQD,EAASE,EAAM,CAC9F,CAEA,SAASC,EAAc,EAAgB,EAAkC,CACvE,OAAO,OAAOJ,GAAU,UAAY,OAAO,cAAcA,CAAK,GAAKA,GAASK,CAC9E,CAEA,SAASC,EAAgB,EAAiC,CAKxD,OAJI,OAAON,GAAU,UAAYA,EAAM,OAAS,GAAK,CAACA,EAAM,WAAW,GAAG,GACtEA,EAAM,SAAS,IAAI,GAAKA,EAAM,SAAS,IAAI,GAAKA,EAAM,SAAS,GAAG,GAAKA,EAAM,SAAS,GAAG,GACzF,gBAAgB,KAAKA,CAAK,GAAKA,EAAM,SAAS,IAAI,GAAK,qBAAqB,KAAKA,CAAK,GACtF,kBAAkB,KAAKA,CAAK,EAAU,GACnCA,EACJ,MAAM,GAAG,CA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AAgB,UAAY,CAAChB,EAAa,KAAKgB,EAAM,WAAW,EAAG,MAAO,GAC3FG,EAAM,IAAIH,EAAM,IAAI,CACtB,CACA,OAAOG,EAAM,IAAI,aAAa,CAChC,CAEA,SAAgBE,EAAuB,EAA+C,CAEpF,GADI,OAAOlB,GAAU,WAAYA,GAC7B,CAACF,EAAaE,EAAO,CAAC,WAAY,YAAa,WAAW,CAAC,EAAG,MAAO,GACzE,IAAMe,EAAYf,EAClB,OACEc,EAAiBC,EAAU,QAAQ,GACnC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,SAAW,IAC/BnB,EAAU,KAAKmB,EAAU,SAAS,GAClC,OAAOA,EAAU,WAAc,UAC/BA,EAAU,UAAU,QAAU,KAC9BnB,EAAU,KAAKmB,EAAU,SAAS,CAEtC,CAGA,SAAgBI,EAAS,EAA0B,EAAuC,CACxF,OAAOT,EAAS,OAAO,KAAM,GAAUG,EAAM,OAASO,CAAI,CAC5D,CAGA,SAAgBC,EAAU,EAA0B,EAAkC,CACpF,OAAOF,EAAST,EAAUU,CAAI,CAAC,EAAE,MACnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sealedChannel.cjs","names":[],"sources":["../../src/types/sealedChannel.ts"],"sourcesContent":["/**\n * The envelope that keeps the tunnel provider out of the payload.\n *\n * Cloudflare terminates TLS at its edge, so everything the cockpit carries\n * (prompts, file previews, model output) is plaintext to them. Sealing the\n * payload underneath their TLS leaves them a relay that can see timing and\n * sizes but not content.\n *\n * The key exchange is anchored on the QR rather than negotiated in band: the\n * host's ephemeral public key is printed on a screen the user is holding, so\n * there is no moment at which a relay could substitute its own. That is the\n * same job Telegram's emoji comparison does for a secret chat, except it\n * happens automatically instead of depending on two people comparing pictures.\n *\n * Declared here because the server seals with `node:crypto` and the browser\n * unseals with WebCrypto, and an envelope is only an envelope if both sides\n * read it identically.\n */\n\n/** Bumped when the envelope layout changes; a mismatch is refused, never guessed at. */\nexport const SEALED_VERSION = 1;\n\n/** Fragment key in the pairing URL carrying the host's ephemeral public key. */\nexport const SEALED_KEY_PARAM = 'k';\n\n/** AES-GCM standard nonce length. Longer is non-standard, shorter is unsafe. */\nexport const NONCE_BYTES = 12;\n/** Random per-channel prefix, so two channels never share a nonce space. */\nexport const NONCE_PREFIX_BYTES = 4;\n/** Monotonic per-direction counter filling the rest of the nonce. */\nexport const NONCE_COUNTER_BYTES = NONCE_BYTES - NONCE_PREFIX_BYTES;\n\n/**\n * Rekey well before the counter could wrap.\n *\n * A repeated nonce under one AES-GCM key is catastrophic, not merely weak: it\n * leaks the XOR of two plaintexts and the authentication subkey. The counter is\n * 64 bits, so this bound is nowhere near it; the point is that the bound exists\n * and is enforced rather than assumed.\n */\nexport const MAX_MESSAGES_PER_KEY = 2 ** 32;\n\n/**\n * HKDF info strings, one per direction.\n *\n * Separate keys per direction, not one shared key, so a message the server sent\n * can never be replayed back at it as though the client had sent it.\n */\nexport const CLIENT_TO_SERVER_INFO = 'doompi/sealed/c2s/v1';\nexport const SERVER_TO_CLIENT_INFO = 'doompi/sealed/s2c/v1';\n\nexport type SealedDirection = 'c2s' | 's2c';\n\nexport function infoFor(direction: SealedDirection): string {\n return direction === 'c2s' ? CLIENT_TO_SERVER_INFO : SERVER_TO_CLIENT_INFO;\n}\n\n/**\n * One sealed message, as it travels.\n *\n * Base64url rather than binary so the same envelope works on a JSON body and a\n * text WebSocket frame without a second encoding path to get wrong.\n */\nexport interface SealedEnvelope {\n v: number;\n /** Base64url, 4-byte prefix plus 8-byte counter. */\n n: string;\n /** Base64url ciphertext with the GCM tag appended. */\n c: string;\n}\n\nexport function isSealedEnvelope(value: unknown): value is SealedEnvelope {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedEnvelope>;\n return candidate.v === SEALED_VERSION && typeof candidate.n === 'string' && typeof candidate.c === 'string';\n}\n\n/** Header naming the client's ephemeral public key during the handshake. */\nexport const SEALED_CLIENT_KEY_HEADER = 'x-doompi-channel-key';\n/** Header carrying a sealed request body's envelope on a non-JSON request. */\nexport const SEALED_BODY_HEADER = 'x-doompi-sealed';\n\nexport type SealedFailure = 'version' | 'malformed' | 'replay' | 'auth' | 'exhausted';\n\n/**\n * Why an unseal failed, in words a diagnostic can show.\n *\n * A decryption failure means a blank cockpit, so every one of these has to name\n * its cause rather than leaving a dead page and no explanation.\n */\nexport function describeSealedFailure(failure: SealedFailure): string {\n switch (failure) {\n case 'version':\n return 'The other end is speaking a different envelope version.';\n case 'malformed':\n return 'A sealed message was not shaped like one.';\n case 'replay':\n return 'A sealed message arrived out of order or twice.';\n case 'auth':\n return 'A sealed message failed its authentication tag, so it was altered in transit.';\n case 'exhausted':\n return 'This channel reached its message limit and must be re-established.';\n }\n}\n"],"mappings":"AAoBA,
|
|
1
|
+
{"version":3,"file":"sealedChannel.cjs","names":["MAX_MESSAGES_PER_KEY","CLIENT_TO_SERVER_INFO","SERVER_TO_CLIENT_INFO","infoFor","direction","isSealedEnvelope","value","candidate","describeSealedFailure","failure"],"sources":["../../src/types/sealedChannel.ts"],"sourcesContent":["/**\n * The envelope that keeps the tunnel provider out of the payload.\n *\n * Cloudflare terminates TLS at its edge, so everything the cockpit carries\n * (prompts, file previews, model output) is plaintext to them. Sealing the\n * payload underneath their TLS leaves them a relay that can see timing and\n * sizes but not content.\n *\n * The key exchange is anchored on the QR rather than negotiated in band: the\n * host's ephemeral public key is printed on a screen the user is holding, so\n * there is no moment at which a relay could substitute its own. That is the\n * same job Telegram's emoji comparison does for a secret chat, except it\n * happens automatically instead of depending on two people comparing pictures.\n *\n * Declared here because the server seals with `node:crypto` and the browser\n * unseals with WebCrypto, and an envelope is only an envelope if both sides\n * read it identically.\n */\n\n/** Bumped when the envelope layout changes; a mismatch is refused, never guessed at. */\nexport const SEALED_VERSION = 1;\n\n/** Fragment key in the pairing URL carrying the host's ephemeral public key. */\nexport const SEALED_KEY_PARAM = 'k';\n\n/** AES-GCM standard nonce length. Longer is non-standard, shorter is unsafe. */\nexport const NONCE_BYTES = 12;\n/** Random per-channel prefix, so two channels never share a nonce space. */\nexport const NONCE_PREFIX_BYTES = 4;\n/** Monotonic per-direction counter filling the rest of the nonce. */\nexport const NONCE_COUNTER_BYTES = NONCE_BYTES - NONCE_PREFIX_BYTES;\n\n/**\n * Rekey well before the counter could wrap.\n *\n * A repeated nonce under one AES-GCM key is catastrophic, not merely weak: it\n * leaks the XOR of two plaintexts and the authentication subkey. The counter is\n * 64 bits, so this bound is nowhere near it; the point is that the bound exists\n * and is enforced rather than assumed.\n */\nexport const MAX_MESSAGES_PER_KEY = 2 ** 32;\n\n/**\n * HKDF info strings, one per direction.\n *\n * Separate keys per direction, not one shared key, so a message the server sent\n * can never be replayed back at it as though the client had sent it.\n */\nexport const CLIENT_TO_SERVER_INFO = 'doompi/sealed/c2s/v1';\nexport const SERVER_TO_CLIENT_INFO = 'doompi/sealed/s2c/v1';\n\nexport type SealedDirection = 'c2s' | 's2c';\n\nexport function infoFor(direction: SealedDirection): string {\n return direction === 'c2s' ? CLIENT_TO_SERVER_INFO : SERVER_TO_CLIENT_INFO;\n}\n\n/**\n * One sealed message, as it travels.\n *\n * Base64url rather than binary so the same envelope works on a JSON body and a\n * text WebSocket frame without a second encoding path to get wrong.\n */\nexport interface SealedEnvelope {\n v: number;\n /** Base64url, 4-byte prefix plus 8-byte counter. */\n n: string;\n /** Base64url ciphertext with the GCM tag appended. */\n c: string;\n}\n\nexport function isSealedEnvelope(value: unknown): value is SealedEnvelope {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedEnvelope>;\n return candidate.v === SEALED_VERSION && typeof candidate.n === 'string' && typeof candidate.c === 'string';\n}\n\n/** Header naming the client's ephemeral public key during the handshake. */\nexport const SEALED_CLIENT_KEY_HEADER = 'x-doompi-channel-key';\n/** Header carrying a sealed request body's envelope on a non-JSON request. */\nexport const SEALED_BODY_HEADER = 'x-doompi-sealed';\n\nexport type SealedFailure = 'version' | 'malformed' | 'replay' | 'auth' | 'exhausted';\n\n/**\n * Why an unseal failed, in words a diagnostic can show.\n *\n * A decryption failure means a blank cockpit, so every one of these has to name\n * its cause rather than leaving a dead page and no explanation.\n */\nexport function describeSealedFailure(failure: SealedFailure): string {\n switch (failure) {\n case 'version':\n return 'The other end is speaking a different envelope version.';\n case 'malformed':\n return 'A sealed message was not shaped like one.';\n case 'replay':\n return 'A sealed message arrived out of order or twice.';\n case 'auth':\n return 'A sealed message failed its authentication tag, so it was altered in transit.';\n case 'exhausted':\n return 'This channel reached its message limit and must be re-established.';\n }\n}\n"],"mappings":"AAoBA,MAoBaA,EAAuB,GAAK,GAQ5BC,EAAwB,uBACxBC,EAAwB,uBAIrC,SAAgBC,EAAQ,EAAoC,CAC1D,OAAOC,IAAc,MAAQH,EAAwBC,CACvD,CAgBA,SAAgBG,EAAiB,EAAyC,CACxE,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,IAAMC,EAAYD,EAClB,OAAOC,EAAU,IAAA,GAAwB,OAAOA,EAAU,GAAM,UAAY,OAAOA,EAAU,GAAM,QACrG,CAeA,SAAgBC,EAAsB,EAAgC,CACpE,OAAQC,EAAR,CACE,IAAK,UACH,MAAO,0DACT,IAAK,YACH,MAAO,4CACT,IAAK,SACH,MAAO,kDACT,IAAK,OACH,MAAO,gFACT,IAAK,YACH,MAAO,oEACX,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sealedChannel.mjs","names":[],"sources":["../../src/types/sealedChannel.ts"],"sourcesContent":["/**\n * The envelope that keeps the tunnel provider out of the payload.\n *\n * Cloudflare terminates TLS at its edge, so everything the cockpit carries\n * (prompts, file previews, model output) is plaintext to them. Sealing the\n * payload underneath their TLS leaves them a relay that can see timing and\n * sizes but not content.\n *\n * The key exchange is anchored on the QR rather than negotiated in band: the\n * host's ephemeral public key is printed on a screen the user is holding, so\n * there is no moment at which a relay could substitute its own. That is the\n * same job Telegram's emoji comparison does for a secret chat, except it\n * happens automatically instead of depending on two people comparing pictures.\n *\n * Declared here because the server seals with `node:crypto` and the browser\n * unseals with WebCrypto, and an envelope is only an envelope if both sides\n * read it identically.\n */\n\n/** Bumped when the envelope layout changes; a mismatch is refused, never guessed at. */\nexport const SEALED_VERSION = 1;\n\n/** Fragment key in the pairing URL carrying the host's ephemeral public key. */\nexport const SEALED_KEY_PARAM = 'k';\n\n/** AES-GCM standard nonce length. Longer is non-standard, shorter is unsafe. */\nexport const NONCE_BYTES = 12;\n/** Random per-channel prefix, so two channels never share a nonce space. */\nexport const NONCE_PREFIX_BYTES = 4;\n/** Monotonic per-direction counter filling the rest of the nonce. */\nexport const NONCE_COUNTER_BYTES = NONCE_BYTES - NONCE_PREFIX_BYTES;\n\n/**\n * Rekey well before the counter could wrap.\n *\n * A repeated nonce under one AES-GCM key is catastrophic, not merely weak: it\n * leaks the XOR of two plaintexts and the authentication subkey. The counter is\n * 64 bits, so this bound is nowhere near it; the point is that the bound exists\n * and is enforced rather than assumed.\n */\nexport const MAX_MESSAGES_PER_KEY = 2 ** 32;\n\n/**\n * HKDF info strings, one per direction.\n *\n * Separate keys per direction, not one shared key, so a message the server sent\n * can never be replayed back at it as though the client had sent it.\n */\nexport const CLIENT_TO_SERVER_INFO = 'doompi/sealed/c2s/v1';\nexport const SERVER_TO_CLIENT_INFO = 'doompi/sealed/s2c/v1';\n\nexport type SealedDirection = 'c2s' | 's2c';\n\nexport function infoFor(direction: SealedDirection): string {\n return direction === 'c2s' ? CLIENT_TO_SERVER_INFO : SERVER_TO_CLIENT_INFO;\n}\n\n/**\n * One sealed message, as it travels.\n *\n * Base64url rather than binary so the same envelope works on a JSON body and a\n * text WebSocket frame without a second encoding path to get wrong.\n */\nexport interface SealedEnvelope {\n v: number;\n /** Base64url, 4-byte prefix plus 8-byte counter. */\n n: string;\n /** Base64url ciphertext with the GCM tag appended. */\n c: string;\n}\n\nexport function isSealedEnvelope(value: unknown): value is SealedEnvelope {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedEnvelope>;\n return candidate.v === SEALED_VERSION && typeof candidate.n === 'string' && typeof candidate.c === 'string';\n}\n\n/** Header naming the client's ephemeral public key during the handshake. */\nexport const SEALED_CLIENT_KEY_HEADER = 'x-doompi-channel-key';\n/** Header carrying a sealed request body's envelope on a non-JSON request. */\nexport const SEALED_BODY_HEADER = 'x-doompi-sealed';\n\nexport type SealedFailure = 'version' | 'malformed' | 'replay' | 'auth' | 'exhausted';\n\n/**\n * Why an unseal failed, in words a diagnostic can show.\n *\n * A decryption failure means a blank cockpit, so every one of these has to name\n * its cause rather than leaving a dead page and no explanation.\n */\nexport function describeSealedFailure(failure: SealedFailure): string {\n switch (failure) {\n case 'version':\n return 'The other end is speaking a different envelope version.';\n case 'malformed':\n return 'A sealed message was not shaped like one.';\n case 'replay':\n return 'A sealed message arrived out of order or twice.';\n case 'auth':\n return 'A sealed message failed its authentication tag, so it was altered in transit.';\n case 'exhausted':\n return 'This channel reached its message limit and must be re-established.';\n }\n}\n"],"mappings":"AAoBA,
|
|
1
|
+
{"version":3,"file":"sealedChannel.mjs","names":["SEALED_VERSION","SEALED_KEY_PARAM","NONCE_BYTES","NONCE_PREFIX_BYTES","NONCE_COUNTER_BYTES","MAX_MESSAGES_PER_KEY","CLIENT_TO_SERVER_INFO","SERVER_TO_CLIENT_INFO","infoFor","direction","isSealedEnvelope","value","candidate","SEALED_CLIENT_KEY_HEADER","SEALED_BODY_HEADER","describeSealedFailure","failure"],"sources":["../../src/types/sealedChannel.ts"],"sourcesContent":["/**\n * The envelope that keeps the tunnel provider out of the payload.\n *\n * Cloudflare terminates TLS at its edge, so everything the cockpit carries\n * (prompts, file previews, model output) is plaintext to them. Sealing the\n * payload underneath their TLS leaves them a relay that can see timing and\n * sizes but not content.\n *\n * The key exchange is anchored on the QR rather than negotiated in band: the\n * host's ephemeral public key is printed on a screen the user is holding, so\n * there is no moment at which a relay could substitute its own. That is the\n * same job Telegram's emoji comparison does for a secret chat, except it\n * happens automatically instead of depending on two people comparing pictures.\n *\n * Declared here because the server seals with `node:crypto` and the browser\n * unseals with WebCrypto, and an envelope is only an envelope if both sides\n * read it identically.\n */\n\n/** Bumped when the envelope layout changes; a mismatch is refused, never guessed at. */\nexport const SEALED_VERSION = 1;\n\n/** Fragment key in the pairing URL carrying the host's ephemeral public key. */\nexport const SEALED_KEY_PARAM = 'k';\n\n/** AES-GCM standard nonce length. Longer is non-standard, shorter is unsafe. */\nexport const NONCE_BYTES = 12;\n/** Random per-channel prefix, so two channels never share a nonce space. */\nexport const NONCE_PREFIX_BYTES = 4;\n/** Monotonic per-direction counter filling the rest of the nonce. */\nexport const NONCE_COUNTER_BYTES = NONCE_BYTES - NONCE_PREFIX_BYTES;\n\n/**\n * Rekey well before the counter could wrap.\n *\n * A repeated nonce under one AES-GCM key is catastrophic, not merely weak: it\n * leaks the XOR of two plaintexts and the authentication subkey. The counter is\n * 64 bits, so this bound is nowhere near it; the point is that the bound exists\n * and is enforced rather than assumed.\n */\nexport const MAX_MESSAGES_PER_KEY = 2 ** 32;\n\n/**\n * HKDF info strings, one per direction.\n *\n * Separate keys per direction, not one shared key, so a message the server sent\n * can never be replayed back at it as though the client had sent it.\n */\nexport const CLIENT_TO_SERVER_INFO = 'doompi/sealed/c2s/v1';\nexport const SERVER_TO_CLIENT_INFO = 'doompi/sealed/s2c/v1';\n\nexport type SealedDirection = 'c2s' | 's2c';\n\nexport function infoFor(direction: SealedDirection): string {\n return direction === 'c2s' ? CLIENT_TO_SERVER_INFO : SERVER_TO_CLIENT_INFO;\n}\n\n/**\n * One sealed message, as it travels.\n *\n * Base64url rather than binary so the same envelope works on a JSON body and a\n * text WebSocket frame without a second encoding path to get wrong.\n */\nexport interface SealedEnvelope {\n v: number;\n /** Base64url, 4-byte prefix plus 8-byte counter. */\n n: string;\n /** Base64url ciphertext with the GCM tag appended. */\n c: string;\n}\n\nexport function isSealedEnvelope(value: unknown): value is SealedEnvelope {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedEnvelope>;\n return candidate.v === SEALED_VERSION && typeof candidate.n === 'string' && typeof candidate.c === 'string';\n}\n\n/** Header naming the client's ephemeral public key during the handshake. */\nexport const SEALED_CLIENT_KEY_HEADER = 'x-doompi-channel-key';\n/** Header carrying a sealed request body's envelope on a non-JSON request. */\nexport const SEALED_BODY_HEADER = 'x-doompi-sealed';\n\nexport type SealedFailure = 'version' | 'malformed' | 'replay' | 'auth' | 'exhausted';\n\n/**\n * Why an unseal failed, in words a diagnostic can show.\n *\n * A decryption failure means a blank cockpit, so every one of these has to name\n * its cause rather than leaving a dead page and no explanation.\n */\nexport function describeSealedFailure(failure: SealedFailure): string {\n switch (failure) {\n case 'version':\n return 'The other end is speaking a different envelope version.';\n case 'malformed':\n return 'A sealed message was not shaped like one.';\n case 'replay':\n return 'A sealed message arrived out of order or twice.';\n case 'auth':\n return 'A sealed message failed its authentication tag, so it was altered in transit.';\n case 'exhausted':\n return 'This channel reached its message limit and must be re-established.';\n }\n}\n"],"mappings":"AAoBA,MAAaA,EAAiB,EAGjBC,EAAmB,IAGnBC,EAAc,GAEdC,EAAqB,EAErBC,EAAsB,EAUtBC,EAAuB,GAAK,GAQ5BC,EAAwB,uBACxBC,EAAwB,uBAIrC,SAAgBC,EAAQ,EAAoC,CAC1D,OAAOC,IAAc,MAAQH,EAAwBC,CACvD,CAgBA,SAAgBG,EAAiB,EAAyC,CACxE,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,IAAMC,EAAYD,EAClB,OAAOC,EAAU,IAAA,GAAwB,OAAOA,EAAU,GAAM,UAAY,OAAOA,EAAU,GAAM,QACrG,CAGA,MAAaC,EAA2B,uBAE3BC,EAAqB,kBAUlC,SAAgBC,EAAsB,EAAgC,CACpE,OAAQC,EAAR,CACE,IAAK,UACH,MAAO,0DACT,IAAK,YACH,MAAO,4CACT,IAAK,SACH,MAAO,kDACT,IAAK,OACH,MAAO,gFACT,IAAK,YACH,MAAO,oEACX,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/doompi-web-security",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.59",
|
|
4
4
|
"description": "Shared security primitives for the DoomPi web cockpit: sealed channels and signed bundle manifests for independently trusted verifiers.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|