@agimon-ai/doompi-web-security 0.0.1-alpha.4 → 0.0.1-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +14 -7
  2. package/dist/browser.cjs +1 -1
  3. package/dist/browser.d.mts +5 -3
  4. package/dist/browser.mjs +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.mts +3 -3
  7. package/dist/index.mjs +1 -1
  8. package/dist/node.cjs +1 -1
  9. package/dist/node.d.mts +3 -3
  10. package/dist/node.mjs +1 -1
  11. package/dist/services/browserBundleVerifier/index.cjs +2 -0
  12. package/dist/services/browserBundleVerifier/index.cjs.map +1 -0
  13. package/dist/services/browserBundleVerifier/index.d.mts +44 -0
  14. package/dist/services/browserBundleVerifier/index.d.mts.map +1 -0
  15. package/dist/services/browserBundleVerifier/index.mjs +2 -0
  16. package/dist/services/browserBundleVerifier/index.mjs.map +1 -0
  17. package/dist/services/browserSealedChannel/index.cjs +2 -0
  18. package/dist/services/browserSealedChannel/index.cjs.map +1 -0
  19. package/dist/{adapters/browserSealedChannel.d.mts → services/browserSealedChannel/index.d.mts} +8 -9
  20. package/dist/services/browserSealedChannel/index.d.mts.map +1 -0
  21. package/dist/services/browserSealedChannel/index.mjs +2 -0
  22. package/dist/services/browserSealedChannel/index.mjs.map +1 -0
  23. package/dist/services/bundleSigner/index.cjs +2 -0
  24. package/dist/services/bundleSigner/index.cjs.map +1 -0
  25. package/dist/services/bundleSigner/index.d.mts +17 -0
  26. package/dist/services/bundleSigner/index.d.mts.map +1 -0
  27. package/dist/services/bundleSigner/index.mjs +2 -0
  28. package/dist/services/bundleSigner/index.mjs.map +1 -0
  29. package/dist/services/nodeSealedChannel/index.cjs +2 -0
  30. package/dist/services/nodeSealedChannel/index.cjs.map +1 -0
  31. package/dist/{adapters/nodeSealedChannel.d.cts → services/nodeSealedChannel/index.d.mts} +16 -9
  32. package/dist/services/nodeSealedChannel/index.d.mts.map +1 -0
  33. package/dist/services/nodeSealedChannel/index.mjs +2 -0
  34. package/dist/services/nodeSealedChannel/index.mjs.map +1 -0
  35. package/dist/services/sealedTransport/index.cjs +2 -0
  36. package/dist/services/sealedTransport/index.cjs.map +1 -0
  37. package/dist/{adapters/sealedTransport.d.cts → services/sealedTransport/index.d.mts} +5 -6
  38. package/dist/services/sealedTransport/index.d.mts.map +1 -0
  39. package/dist/services/sealedTransport/index.mjs +2 -0
  40. package/dist/services/sealedTransport/index.mjs.map +1 -0
  41. package/dist/services/{serialQueue.cjs → serialQueue/index.cjs} +1 -1
  42. package/dist/services/serialQueue/index.cjs.map +1 -0
  43. package/dist/services/{serialQueue.d.cts → serialQueue/index.d.mts} +4 -5
  44. package/dist/services/serialQueue/index.d.mts.map +1 -0
  45. package/dist/services/{serialQueue.mjs → serialQueue/index.mjs} +1 -1
  46. package/dist/services/serialQueue/index.mjs.map +1 -0
  47. package/dist/types/bundleManifest.cjs +0 -0
  48. package/dist/types/bundleManifest.cjs.map +1 -1
  49. package/dist/types/bundleManifest.d.mts +24 -28
  50. package/dist/types/bundleManifest.d.mts.map +1 -1
  51. package/dist/types/bundleManifest.mjs +0 -0
  52. package/dist/types/bundleManifest.mjs.map +1 -1
  53. package/dist/types/sealedChannel.d.mts +16 -17
  54. package/dist/types/sealedChannel.d.mts.map +1 -1
  55. package/package.json +5 -5
  56. package/dist/adapters/browserSealedChannel.cjs +0 -2
  57. package/dist/adapters/browserSealedChannel.cjs.map +0 -1
  58. package/dist/adapters/browserSealedChannel.d.cts +0 -36
  59. package/dist/adapters/browserSealedChannel.d.cts.map +0 -1
  60. package/dist/adapters/browserSealedChannel.d.mts.map +0 -1
  61. package/dist/adapters/browserSealedChannel.mjs +0 -2
  62. package/dist/adapters/browserSealedChannel.mjs.map +0 -1
  63. package/dist/adapters/bundleSigner.cjs +0 -2
  64. package/dist/adapters/bundleSigner.cjs.map +0 -1
  65. package/dist/adapters/bundleSigner.d.cts +0 -14
  66. package/dist/adapters/bundleSigner.d.cts.map +0 -1
  67. package/dist/adapters/bundleSigner.d.mts +0 -14
  68. package/dist/adapters/bundleSigner.d.mts.map +0 -1
  69. package/dist/adapters/bundleSigner.mjs +0 -2
  70. package/dist/adapters/bundleSigner.mjs.map +0 -1
  71. package/dist/adapters/nodeSealedChannel.cjs +0 -2
  72. package/dist/adapters/nodeSealedChannel.cjs.map +0 -1
  73. package/dist/adapters/nodeSealedChannel.d.cts.map +0 -1
  74. package/dist/adapters/nodeSealedChannel.d.mts +0 -40
  75. package/dist/adapters/nodeSealedChannel.d.mts.map +0 -1
  76. package/dist/adapters/nodeSealedChannel.mjs +0 -2
  77. package/dist/adapters/nodeSealedChannel.mjs.map +0 -1
  78. package/dist/adapters/sealedTransport.cjs +0 -2
  79. package/dist/adapters/sealedTransport.cjs.map +0 -1
  80. package/dist/adapters/sealedTransport.d.cts.map +0 -1
  81. package/dist/adapters/sealedTransport.d.mts +0 -43
  82. package/dist/adapters/sealedTransport.d.mts.map +0 -1
  83. package/dist/adapters/sealedTransport.mjs +0 -2
  84. package/dist/adapters/sealedTransport.mjs.map +0 -1
  85. package/dist/browser.d.cts +0 -3
  86. package/dist/index.d.cts +0 -4
  87. package/dist/node.d.cts +0 -3
  88. package/dist/services/serialQueue.cjs.map +0 -1
  89. package/dist/services/serialQueue.d.cts.map +0 -1
  90. package/dist/services/serialQueue.d.mts +0 -23
  91. package/dist/services/serialQueue.d.mts.map +0 -1
  92. package/dist/services/serialQueue.mjs.map +0 -1
  93. package/dist/types/bundleManifest.d.cts +0 -48
  94. package/dist/types/bundleManifest.d.cts.map +0 -1
  95. package/dist/types/sealedChannel.d.cts +0 -77
  96. package/dist/types/sealedChannel.d.cts.map +0 -1
@@ -0,0 +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,EAAO,EAAQ,CAAa,EACtC,EAAa,EAAO,EAAQ,IAAkB,MAAQ,MAAQ,KAAK,EACrE,EAAc,GAEd,EAAkB,CAAC,GAEvB,MAAO,CACL,KAAK,EAAW,CACd,GAAI,GAAe,OAAO,CAAoB,EAAG,MAAO,CAAE,GAAI,GAAO,QAAS,WAAY,EAC1F,IAAM,EAAQ,EAAS,EAAa,CAAW,EACzC,EAAS,EAAe,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/F,CACF,EAEA,KAAK,EAAU,CAIb,IAAM,EAAQ,EACd,GAAI,OAAO,GAA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AAK,WAAW,EAAS,EAAO,IAAA,GAAW,IAAA,GAAW,cAAc,CAC7E,MAAQ,CACN,MACF,CACF,CAWA,SAAgB,GAAqC,CACnD,IAAM,EAAW,EAAW,CAAK,EACjC,EAAS,aAAa,EACtB,IAAM,kBAAgB,IAAI,IAC1B,MAAO,CACL,UAAW,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,IAAM,EAAO,EAAU,CAAa,EACpC,GAAI,IAAS,IAAA,IAAa,EAAc,IAAI,EAAK,SAAS,WAAW,CAAC,EAAG,OACzE,IAAI,EACJ,GAAI,CACF,EAAS,EAAS,cAAc,CAAI,CACtC,MAAQ,CACN,MACF,CAIA,OAHA,EAAc,IAAI,EAAK,SAAS,WAAW,CAAC,EAGrC,EAAc,EAAQ,MAAO,EAAA,CAA8B,CAAC,CACrE,CACF,CACF,CAGA,SAAgB,GAAyC,CACvD,IAAM,EAAW,EAAW,CAAK,EACjC,EAAS,aAAa,EACtB,IAAI,EAAW,GACf,MAAO,CACL,UAAW,EAAS,aAAa,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"}
@@ -0,0 +1,2 @@
1
+ const e=require("../../types/sealedChannel.cjs"),t=require("../browserSealedChannel/index.cjs"),n=require("../serialQueue/index.cjs"),r=new TextEncoder,i=new TextDecoder;function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function o(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}async function s(e){if(e!=null){if(typeof e==`string`)return r.encode(e);if(e instanceof URLSearchParams)return r.encode(e.toString());if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`The sealed HTTP transport does not support this request body type.`)}}function c(e){if(!e.startsWith(`/`))throw Error(`A sealed HTTP request must use a root-relative URL.`);return e}function l(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.v===1&&typeof t.status==`number`&&Array.isArray(t.headers)&&t.headers.every(e=>Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`))&&typeof t.body==`string`}function u(){let u,d,f=n.createSerialQueue(),p=n.createSerialQueue(),m=n.createSerialQueue(),h,g=t=>{d=e.describeSealedFailure(t)},_=async e=>{if(u===void 0)return;let t=await u.seal(e);return t.ok?JSON.stringify(t.envelope):g(t.failure)},v=async e=>{if(u===void 0)return;let t;try{t=JSON.parse(e)}catch{return g(`malformed`)}let n=await u.open(t);return n.ok?n.plaintext:g(n.failure)};return{active:()=>u!==void 0,lastFailure:()=>d,async connect(e){let n=await t.connectSealedChannel(e);if(n===void 0){d=`This browser could not establish a sealed channel.`;return}return u=n.channel,d=void 0,n.clientPublicKey},relayRequestsThrough(e){h=e},reset(){u=void 0,d=void 0},async sealText(e){return u===void 0?e:await f.run(async()=>{let t=await _(r.encode(e));if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return t})},async openText(e){return u===void 0?e:await p.run(async()=>{let t=await v(e);return t===void 0?void 0:i.decode(t)})},async sealBinary(e){return u===void 0?e:await f.run(async()=>{let t=await _(e);if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return r.encode(t)})},async openBinary(e){return u===void 0?e:await p.run(async()=>await v(i.decode(e)))},async fetch(e,t){let n=h;return u===void 0||n===void 0?await fetch(e,t):await m.run(async()=>{let u=await s(t?.body),f={v:1,method:(t?.method??`GET`).toUpperCase(),target:c(e),headers:Array.from(new Headers(t?.headers).entries()),...u===void 0?{}:{body:a(u)}},p=await _(r.encode(JSON.stringify(f)));if(p===void 0)return new Response(JSON.stringify({error:d}),{status:502});let m=await fetch(n,{method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`},body:p}),h=await v(await m.text());if(h===void 0)return new Response(JSON.stringify({error:d}),{status:502});let g;try{g=JSON.parse(i.decode(h))}catch{g=void 0}if(!l(g))return d=`The sealed HTTP response was malformed.`,new Response(JSON.stringify({error:d}),{status:502});let y=o(g.body);return new Response(g.status===204||g.status===205||g.status===304?null:y,{status:g.status,headers:g.headers})})}}}const d=u();exports.createSealedTransport=u,exports.sealedTransport=d;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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 `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"sIAkCM,EAAU,IAAI,YACd,EAAU,IAAI,YAiBpB,SAAS,EAAa,EAA2B,CAC/C,IAAI,EAAS,GACb,IAAK,IAAM,KAAQ,EAAO,GAAU,OAAO,aAAa,CAAI,EAC5D,OAAO,KA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M,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,5 +1,5 @@
1
- //#region src/adapters/sealedTransport.d.ts
2
- interface SealedTransport {
1
+ //#region src/services/sealedTransport/index.d.ts
2
+ export interface SealedTransport {
3
3
  /** False on loopback and before the handshake completes, where everything passes through. */
4
4
  active(): boolean;
5
5
  sealText(text: string): Promise<string>;
@@ -11,7 +11,7 @@ interface SealedTransport {
11
11
  fetch(input: string, init?: RequestInit): Promise<Response>;
12
12
  lastFailure(): string | undefined;
13
13
  }
14
- declare function createSealedTransport(): SealedTransport & {
14
+ export declare function createSealedTransport(): SealedTransport & {
15
15
  /** Completes the handshake against the host key from the QR. */
16
16
  connect: (hostPublicKey: string) => Promise<string | undefined>;
17
17
  /** Drops the channel, so everything falls back to pass-through. */
@@ -30,7 +30,7 @@ declare function createSealedTransport(): SealedTransport & {
30
30
  * Inactive until a handshake completes, and inactive forever on the loopback
31
31
  * listener, so `sealedTransport.fetch` is a plain `fetch` there.
32
32
  */
33
- declare const sealedTransport: SealedTransport & {
33
+ export declare const sealedTransport: SealedTransport & {
34
34
  /** Completes the handshake against the host key from the QR. */
35
35
  connect: (hostPublicKey: string) => Promise<string | undefined>;
36
36
  /** Drops the channel, so everything falls back to pass-through. */
@@ -39,5 +39,4 @@ declare const sealedTransport: SealedTransport & {
39
39
  relayRequestsThrough: (path: string) => void;
40
40
  };
41
41
  //#endregion
42
- export { SealedTransport, createSealedTransport, sealedTransport };
43
- //# sourceMappingURL=sealedTransport.d.cts.map
42
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/sealedTransport/index.ts"],"mappings":";iBAqBiB;;EAEf;EACA,SAAS,eAAe;;EAExB,SAAS,eAAe;EACxB,WAAW,OAAO,aAAa,QAAQ;EACvC,WAAW,OAAO,aAAa,QAAQ;;EAEvC,MAAM,eAAe,OAAO,cAAc,QAAQ;EAClD;;wBA4Dc,yBAAyB;;EAEvC,UAAU,0BAA0B;;EAEpC;;EAEA,uBAAuB;;;;;;;;;;;;;qBAmJZ,iBAAe;;EAvJjB,UAAC,0BAA0B;;EAE7B;;EAEe,uBAAC"}
@@ -0,0 +1,2 @@
1
+ import{describeSealedFailure as e}from"../../types/sealedChannel.mjs";import{connectSealedChannel as t}from"../browserSealedChannel/index.mjs";import{createSerialQueue as n}from"../serialQueue/index.mjs";const r=new TextEncoder,i=new TextDecoder;function a(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function o(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}async function s(e){if(e!=null){if(typeof e==`string`)return r.encode(e);if(e instanceof URLSearchParams)return r.encode(e.toString());if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw Error(`The sealed HTTP transport does not support this request body type.`)}}function c(e){if(!e.startsWith(`/`))throw Error(`A sealed HTTP request must use a root-relative URL.`);return e}function l(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.v===1&&typeof t.status==`number`&&Array.isArray(t.headers)&&t.headers.every(e=>Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`))&&typeof t.body==`string`}function u(){let u,d,f=n(),p=n(),m=n(),h,g=t=>{d=e(t)},_=async e=>{if(u===void 0)return;let t=await u.seal(e);return t.ok?JSON.stringify(t.envelope):g(t.failure)},v=async e=>{if(u===void 0)return;let t;try{t=JSON.parse(e)}catch{return g(`malformed`)}let n=await u.open(t);return n.ok?n.plaintext:g(n.failure)};return{active:()=>u!==void 0,lastFailure:()=>d,async connect(e){let n=await t(e);if(n===void 0){d=`This browser could not establish a sealed channel.`;return}return u=n.channel,d=void 0,n.clientPublicKey},relayRequestsThrough(e){h=e},reset(){u=void 0,d=void 0},async sealText(e){return u===void 0?e:await f.run(async()=>{let t=await _(r.encode(e));if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return t})},async openText(e){return u===void 0?e:await p.run(async()=>{let t=await v(e);return t===void 0?void 0:i.decode(t)})},async sealBinary(e){return u===void 0?e:await f.run(async()=>{let t=await _(e);if(t===void 0)throw Error(d??`The active sealed channel could not encrypt a message.`);return r.encode(t)})},async openBinary(e){return u===void 0?e:await p.run(async()=>await v(i.decode(e)))},async fetch(e,t){let n=h;return u===void 0||n===void 0?await fetch(e,t):await m.run(async()=>{let u=await s(t?.body),f={v:1,method:(t?.method??`GET`).toUpperCase(),target:c(e),headers:Array.from(new Headers(t?.headers).entries()),...u===void 0?{}:{body:a(u)}},p=await _(r.encode(JSON.stringify(f)));if(p===void 0)return new Response(JSON.stringify({error:d}),{status:502});let m=await fetch(n,{method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`},body:p}),h=await v(await m.text());if(h===void 0)return new Response(JSON.stringify({error:d}),{status:502});let g;try{g=JSON.parse(i.decode(h))}catch{g=void 0}if(!l(g))return d=`The sealed HTTP response was malformed.`,new Response(JSON.stringify({error:d}),{status:502});let y=o(g.body);return new Response(g.status===204||g.status===205||g.status===304?null:y,{status:g.status,headers:g.headers})})}}}const d=u();export{u as createSealedTransport,d as sealedTransport};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"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,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,EAA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2
- //# sourceMappingURL=serialQueue.cjs.map
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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,SAAgB,GAAiC,CAE/C,IAAI,EAAyB,QAAQ,QAAQ,EAE7C,MAAO,CACL,IAAO,EAAoC,CACzC,IAAM,EAAS,EAAK,KAAK,EAAM,CAAI,EAEnC,MADA,GAAO,EAAO,UAAY,IAAA,EAAS,EAC5B,CACT,CACF,CACF"}
@@ -1,4 +1,4 @@
1
- //#region src/services/serialQueue.d.ts
1
+ //#region src/services/serialQueue/index.d.ts
2
2
  /**
3
3
  * Runs async work strictly one at a time, in the order it was handed over.
4
4
  *
@@ -13,11 +13,10 @@
13
13
  * Deliberately not a general work pool. A pool with any concurrency above one
14
14
  * reintroduces exactly the reordering this exists to prevent.
15
15
  */
16
- interface SerialQueue {
16
+ export interface SerialQueue {
17
17
  /** Resolves with the task's result once every task queued before it has settled. */
18
18
  run<T>(task: () => Promise<T>): Promise<T>;
19
19
  }
20
- declare function createSerialQueue(): SerialQueue;
20
+ export declare function createSerialQueue(): SerialQueue;
21
21
  //#endregion
22
- export { SerialQueue, createSerialQueue };
23
- //# sourceMappingURL=serialQueue.d.cts.map
22
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/serialQueue/index.ts"],"mappings":";;;;;;;;;;;;;;;iBAciB;;EAEf,IAAI,GAAG,YAAY,QAAQ,KAAK,QAAQ;;wBAG1B,qBAAqB"}
@@ -1,2 +1,2 @@
1
1
  function e(){let e=Promise.resolve();return{run(t){let n=e.then(t,t);return e=n.catch(()=>void 0),n}}}export{e as createSerialQueue};
2
- //# sourceMappingURL=serialQueue.mjs.map
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +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,SAAgB,GAAiC,CAE/C,IAAI,EAAyB,QAAQ,QAAQ,EAE7C,MAAO,CACL,IAAO,EAAoC,CACzC,IAAM,EAAS,EAAK,KAAK,EAAM,CAAI,EAEnC,MADA,GAAO,EAAO,UAAY,IAAA,EAAS,EAC5B,CACT,CACF,CACF"}
Binary file
@@ -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. Such an attacker can omit the\n * verifier or substitute its trust key. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n *\n * Lives in types rather than services because any verifier must use the same\n * canonical encoding the server signs, byte for byte.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 1;\n\nexport interface BundleAsset {\n /** Path as the browser requests it, leading slash included. */\n path: string;\n /** Lowercase hex SHA-256 of the bytes served at that path. */\n sha256: string;\n}\n\nexport interface BundleManifest {\n version: number;\n /** Milliseconds, so a stale manifest is visible without another lookup. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the key that signed it; trust must be established out of band. */\n publicKey: string;\n}\n\n/**\n * The exact bytes that get signed.\n *\n * Hand-rolled rather than `JSON.stringify` of the whole object, because a\n * signature is only worth anything if both sides agree byte for byte on what\n * was signed. Key order in a JSON object is an implementation detail; a sorted\n * line-per-asset encoding is not.\n */\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((asset) => `${asset.path}\u0000${asset.sha256}`);\n return [String(manifest.version), 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 const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (typeof candidate.builtAt !== 'number' || !Array.isArray(candidate.assets)) return false;\n return candidate.assets.every(\n (asset: unknown) =>\n typeof asset === 'object' &&\n asset !== null &&\n typeof (asset as BundleAsset).path === 'string' &&\n /^[0-9a-f]{64}$/u.test((asset as BundleAsset).sha256),\n );\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 manifest.assets.find((asset) => asset.path === path)?.sha256;\n}\n"],"mappings":"AA6CA,SAAgB,EAAkB,EAAkC,CAIlE,IAAM,EAHS,CAAC,GAAG,EAAS,MAAM,CAAC,CAAC,MAAM,EAAM,IAC9C,EAAK,KAAO,EAAM,KAAO,GAAK,IAAK,KAAO,EAAM,KAE/B,CAAC,CAAC,IAAK,GAAU,GAAG,EAAM,KAAK,GAAG,EAAM,QAAQ,EACnE,MAAO,CAAC,OAAO,EAAS,OAAO,EAAG,OAAO,EAAS,OAAO,EAAG,GAAG,CAAK,CAAC,CAAC,KAAK;CAAI,CACjF,CAEA,SAAgB,EAAiB,EAAyC,CACxE,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAY,EAGlB,OAFI,EAAU,UAAA,GACV,OAAO,EAAU,SAAY,UAAY,CAAC,MAAM,QAAQ,EAAU,MAAM,EAAU,GAC/E,EAAU,OAAO,MACrB,GACC,OAAO,GAAU,YACjB,GACA,OAAQ,EAAsB,MAAS,UACvC,kBAAkB,KAAM,EAAsB,MAAM,CACxD,CACF,CAGA,SAAgB,EAAU,EAA0B,EAAkC,CACpF,OAAO,EAAS,OAAO,KAAM,GAAU,EAAM,OAAS,CAAI,CAAC,EAAE,MAC/D"}
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,MAGM,EAAS,kBACT,EAAY,oBACZ,EAAe,4DA6BrB,SAAS,EAAa,EAAe,EAAsC,CACzE,IAAM,EAAO,OAAO,KAAK,CAAK,CAAC,CAAC,KAAK,EACrC,OAAO,EAAK,SAAW,EAAS,QAAU,EAAK,OAAO,EAAK,IAAU,IAAQ,EAAS,EAAM,CAC9F,CAEA,SAAS,EAAc,EAAgB,EAAkC,CACvE,OAAO,OAAO,GAAU,UAAY,OAAO,cAAc,CAAK,GAAK,GAAS,CAC9E,CAEA,SAAS,EAAgB,EAAiC,CAKxD,OAJI,OAAO,GAAU,UAAY,EAAM,OAAS,GAAK,CAAC,EAAM,WAAW,GAAG,GACtE,EAAM,SAAS,IAAI,GAAK,EAAM,SAAS,IAAI,GAAK,EAAM,SAAS,GAAG,GAAK,EAAM,SAAS,GAAG,GACzF,gBAAgB,KAAK,CAAK,GAAK,EAAM,SAAS,IAAI,GAAK,qBAAqB,KAAK,CAAK,GACtF,kBAAkB,KAAK,CAAK,EAAU,GACnC,EACJ,MAAM,GAAG,CAAC,CACV,MAAM,CAAC,CAAC,CACR,MAAO,GAAY,IAAY,IAAM,IAAY,KAAO,IAAY,IAAI,CAC7E,CAGA,SAAgB,EAAkB,EAAkC,CAIlE,IAAM,EAHS,CAAC,GAAG,EAAS,MAAM,CAAC,CAAC,MAAM,EAAM,IAC9C,EAAK,KAAO,EAAM,KAAO,GAAK,IAAK,KAAO,EAAM,KAE/B,CAAC,CAAC,IAClB,GAAU,GAAG,EAAM,KAAK,IAAI,EAAM,OAAO,IAAI,OAAO,EAAM,UAAU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GAClC,OAAO,EAAU,WAAc,UAC/B,EAAU,UAAU,QAAU,KAC9B,EAAU,KAAK,EAAU,SAAS,CAEtC,CAGA,SAAgB,EAAS,EAA0B,EAAuC,CACxF,OAAO,EAAS,OAAO,KAAM,GAAU,EAAM,OAAS,CAAI,CAC5D,CAGA,SAAgB,EAAU,EAA0B,EAAkC,CACpF,OAAO,EAAS,EAAU,CAAI,CAAC,EAAE,MACnC"}
@@ -3,46 +3,42 @@
3
3
  * A signed description of cockpit assets for an independently trusted verifier.
4
4
  *
5
5
  * A manifest does not let a browser SPA defend itself against the server or TLS
6
- * edge that supplied its executable code. Such an attacker can omit the
7
- * verifier or substitute its trust key. Consumers need a separately trusted
6
+ * edge that supplied its executable code. Consumers need a separately trusted
8
7
  * bootstrap and key before these signatures become a delivery guarantee.
9
- *
10
- * Lives in types rather than services because any verifier must use the same
11
- * canonical encoding the server signs, byte for byte.
12
8
  */
13
- declare const BUNDLE_MANIFEST_ROUTE = "/bundle-manifest.json";
14
- declare const BUNDLE_MANIFEST_VERSION = 1;
15
- interface BundleAsset {
16
- /** Path as the browser requests it, leading slash included. */
9
+ export declare const BUNDLE_MANIFEST_ROUTE = "/bundle-manifest.json";
10
+ export declare const BUNDLE_MANIFEST_VERSION = 2;
11
+ export interface BundleAsset {
12
+ /** Normalized absolute URL path, without a query or fragment. */
17
13
  path: string;
18
- /** Lowercase hex SHA-256 of the bytes served at that path. */
14
+ /** Lowercase hex SHA-256 of the served bytes. */
19
15
  sha256: string;
16
+ byteLength: number;
17
+ /** MIME type of the response, without parameters. */
18
+ contentType: string;
20
19
  }
21
- interface BundleManifest {
22
- version: number;
23
- /** Milliseconds, so a stale manifest is visible without another lookup. */
20
+ export interface BundleManifest {
21
+ version: typeof BUNDLE_MANIFEST_VERSION;
22
+ /** Monotonically increasing persistent signer revision. */
23
+ revision: number;
24
+ /** Unix time in milliseconds. */
24
25
  builtAt: number;
25
26
  assets: BundleAsset[];
26
27
  }
27
- interface SignedBundleManifest {
28
+ export interface SignedBundleManifest {
28
29
  manifest: BundleManifest;
29
- /** Base64url ECDSA P-256 signature over the canonical serialization. */
30
+ /** Base64url IEEE P1363 ECDSA P-256 signature over the canonical serialization. */
30
31
  signature: string;
31
- /** Base64url SPKI of the key that signed it; trust must be established out of band. */
32
+ /** Base64url SPKI of the signing key. Trust must be established out of band. */
32
33
  publicKey: string;
33
34
  }
34
- /**
35
- * The exact bytes that get signed.
36
- *
37
- * Hand-rolled rather than `JSON.stringify` of the whole object, because a
38
- * signature is only worth anything if both sides agree byte for byte on what
39
- * was signed. Key order in a JSON object is an implementation detail; a sorted
40
- * line-per-asset encoding is not.
41
- */
42
- declare function canonicalManifest(manifest: BundleManifest): string;
43
- declare function isBundleManifest(value: unknown): value is BundleManifest;
35
+ /** The exact bytes signed by Node and verified by WebCrypto. */
36
+ export declare function canonicalManifest(manifest: BundleManifest): string;
37
+ export declare function isBundleManifest(value: unknown): value is BundleManifest;
38
+ export declare function isSignedBundleManifest(value: unknown): value is SignedBundleManifest;
39
+ /** The recorded asset for one path, or undefined if the manifest does not cover it. */
40
+ export declare function assetFor(manifest: BundleManifest, path: string): BundleAsset | undefined;
44
41
  /** The recorded digest for one asset, or undefined if the manifest does not cover it. */
45
- declare function digestFor(manifest: BundleManifest, path: string): string | undefined;
42
+ export declare function digestFor(manifest: BundleManifest, path: string): string | undefined;
46
43
  //#endregion
47
- export { BUNDLE_MANIFEST_ROUTE, BUNDLE_MANIFEST_VERSION, BundleAsset, BundleManifest, SignedBundleManifest, canonicalManifest, digestFor, isBundleManifest };
48
44
  //# sourceMappingURL=bundleManifest.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundleManifest.d.mts","names":[],"sources":["../../src/types/bundleManifest.ts"],"mappings":";;;;;;;;;;;;cAYa;cACA;UAEI;;EAEf;;EAEA;;UAGe;EACf;;EAEA;EACA,QAAQ;;UAGO;EACf,UAAU;;EAEV;;EAEA;;;;;;;;;;iBAWc,kBAAkB,UAAU;iBAQ5B,iBAAiB,iBAAiB,SAAS;;iBAe3C,UAAU,UAAU,gBAAgB"}
1
+ {"version":3,"file":"bundleManifest.d.mts","names":[],"sources":["../../src/types/bundleManifest.ts"],"mappings":";;;;;;;;qBAQa;qBACA;iBAMI;;EAEf;;EAEA;EACA;;EAEA;;iBAGe;EACf,gBAAgB;;EAEhB;;EAEA;EACA,QAAQ;;iBAGO;EACf,UAAU;;EAEV;;EAEA;;;wBAwBc,kBAAkB,UAAU;wBAU5B,iBAAiB,iBAAiB,SAAS;wBAsB3C,uBAAuB,iBAAiB,SAAS;;wBAgBjD,SAAS,UAAU,gBAAgB,eAAe;;wBAKlD,UAAU,UAAU,gBAAgB"}
Binary file
@@ -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. Such an attacker can omit the\n * verifier or substitute its trust key. Consumers need a separately trusted\n * bootstrap and key before these signatures become a delivery guarantee.\n *\n * Lives in types rather than services because any verifier must use the same\n * canonical encoding the server signs, byte for byte.\n */\n\nexport const BUNDLE_MANIFEST_ROUTE = '/bundle-manifest.json';\nexport const BUNDLE_MANIFEST_VERSION = 1;\n\nexport interface BundleAsset {\n /** Path as the browser requests it, leading slash included. */\n path: string;\n /** Lowercase hex SHA-256 of the bytes served at that path. */\n sha256: string;\n}\n\nexport interface BundleManifest {\n version: number;\n /** Milliseconds, so a stale manifest is visible without another lookup. */\n builtAt: number;\n assets: BundleAsset[];\n}\n\nexport interface SignedBundleManifest {\n manifest: BundleManifest;\n /** Base64url ECDSA P-256 signature over the canonical serialization. */\n signature: string;\n /** Base64url SPKI of the key that signed it; trust must be established out of band. */\n publicKey: string;\n}\n\n/**\n * The exact bytes that get signed.\n *\n * Hand-rolled rather than `JSON.stringify` of the whole object, because a\n * signature is only worth anything if both sides agree byte for byte on what\n * was signed. Key order in a JSON object is an implementation detail; a sorted\n * line-per-asset encoding is not.\n */\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((asset) => `${asset.path}\u0000${asset.sha256}`);\n return [String(manifest.version), 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 const candidate = value as Partial<BundleManifest>;\n if (candidate.version !== BUNDLE_MANIFEST_VERSION) return false;\n if (typeof candidate.builtAt !== 'number' || !Array.isArray(candidate.assets)) return false;\n return candidate.assets.every(\n (asset: unknown) =>\n typeof asset === 'object' &&\n asset !== null &&\n typeof (asset as BundleAsset).path === 'string' &&\n /^[0-9a-f]{64}$/u.test((asset as BundleAsset).sha256),\n );\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 manifest.assets.find((asset) => asset.path === path)?.sha256;\n}\n"],"mappings":"AAYA,MAAa,EAAwB,wBACxB,EAA0B,EAgCvC,SAAgB,EAAkB,EAAkC,CAIlE,IAAM,EAHS,CAAC,GAAG,EAAS,MAAM,CAAC,CAAC,MAAM,EAAM,IAC9C,EAAK,KAAO,EAAM,KAAO,GAAK,IAAK,KAAO,EAAM,KAE/B,CAAC,CAAC,IAAK,GAAU,GAAG,EAAM,KAAK,GAAG,EAAM,QAAQ,EACnE,MAAO,CAAC,OAAO,EAAS,OAAO,EAAG,OAAO,EAAS,OAAO,EAAG,GAAG,CAAK,CAAC,CAAC,KAAK;CAAI,CACjF,CAEA,SAAgB,EAAiB,EAAyC,CACxE,GAAI,OAAO,GAAU,WAAY,EAAgB,MAAO,GACxD,IAAM,EAAY,EAGlB,OAFI,EAAU,UAAA,GACV,OAAO,EAAU,SAAY,UAAY,CAAC,MAAM,QAAQ,EAAU,MAAM,EAAU,GAC/E,EAAU,OAAO,MACrB,GACC,OAAO,GAAU,YACjB,GACA,OAAQ,EAAsB,MAAS,UACvC,kBAAkB,KAAM,EAAsB,MAAM,CACxD,CACF,CAGA,SAAgB,EAAU,EAA0B,EAAkC,CACpF,OAAO,EAAS,OAAO,KAAM,GAAU,EAAM,OAAS,CAAI,CAAC,EAAE,MAC/D"}
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,MAAa,EAAwB,wBACxB,EAA0B,EAEjC,EAAS,kBACT,EAAY,oBACZ,EAAe,4DA6BrB,SAAS,EAAa,EAAe,EAAsC,CACzE,IAAM,EAAO,OAAO,KAAK,CAAK,CAAC,CAAC,KAAK,EACrC,OAAO,EAAK,SAAW,EAAS,QAAU,EAAK,OAAO,EAAK,IAAU,IAAQ,EAAS,EAAM,CAC9F,CAEA,SAAS,EAAc,EAAgB,EAAkC,CACvE,OAAO,OAAO,GAAU,UAAY,OAAO,cAAc,CAAK,GAAK,GAAS,CAC9E,CAEA,SAAS,EAAgB,EAAiC,CAKxD,OAJI,OAAO,GAAU,UAAY,EAAM,OAAS,GAAK,CAAC,EAAM,WAAW,GAAG,GACtE,EAAM,SAAS,IAAI,GAAK,EAAM,SAAS,IAAI,GAAK,EAAM,SAAS,GAAG,GAAK,EAAM,SAAS,GAAG,GACzF,gBAAgB,KAAK,CAAK,GAAK,EAAM,SAAS,IAAI,GAAK,qBAAqB,KAAK,CAAK,GACtF,kBAAkB,KAAK,CAAK,EAAU,GACnC,EACJ,MA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EAAG,MAAO,GAC3F,EAAM,IAAI,EAAM,IAAI,CACtB,CACA,OAAO,EAAM,IAAI,aAAa,CAChC,CAEA,SAAgB,EAAuB,EAA+C,CAEpF,GADI,OAAO,GAAU,WAAY,GAC7B,CAAC,EAAa,EAAO,CAAC,WAAY,YAAa,WAAW,CAAC,EAAG,MAAO,GACzE,IAAM,EAAY,EAClB,OACE,EAAiB,EAAU,QAAQ,GACnC,OAAO,EAAU,WAAc,UAC/B,EAAU,UAAU,SAAW,IAC/B,EAAU,KAAK,EAAU,SAAS,GAClC,OAAO,EAAU,WAAc,UAC/B,EAAU,UAAU,QAAU,KAC9B,EAAU,KAAK,EAAU,SAAS,CAEtC,CAGA,SAAgB,EAAS,EAA0B,EAAuC,CACxF,OAAO,EAAS,OAAO,KAAM,GAAU,EAAM,OAAS,CAAI,CAC5D,CAGA,SAAgB,EAAU,EAA0B,EAAkC,CACpF,OAAO,EAAS,EAAU,CAAI,CAAC,EAAE,MACnC"}
@@ -18,15 +18,15 @@
18
18
  * read it identically.
19
19
  */
20
20
  /** Bumped when the envelope layout changes; a mismatch is refused, never guessed at. */
21
- declare const SEALED_VERSION = 1;
21
+ export declare const SEALED_VERSION = 1;
22
22
  /** Fragment key in the pairing URL carrying the host's ephemeral public key. */
23
- declare const SEALED_KEY_PARAM = "k";
23
+ export declare const SEALED_KEY_PARAM = "k";
24
24
  /** AES-GCM standard nonce length. Longer is non-standard, shorter is unsafe. */
25
- declare const NONCE_BYTES = 12;
25
+ export declare const NONCE_BYTES = 12;
26
26
  /** Random per-channel prefix, so two channels never share a nonce space. */
27
- declare const NONCE_PREFIX_BYTES = 4;
27
+ export declare const NONCE_PREFIX_BYTES = 4;
28
28
  /** Monotonic per-direction counter filling the rest of the nonce. */
29
- declare const NONCE_COUNTER_BYTES: number;
29
+ export declare const NONCE_COUNTER_BYTES: number;
30
30
  /**
31
31
  * Rekey well before the counter could wrap.
32
32
  *
@@ -35,43 +35,42 @@ declare const NONCE_COUNTER_BYTES: number;
35
35
  * 64 bits, so this bound is nowhere near it; the point is that the bound exists
36
36
  * and is enforced rather than assumed.
37
37
  */
38
- declare const MAX_MESSAGES_PER_KEY: number;
38
+ export declare const MAX_MESSAGES_PER_KEY: number;
39
39
  /**
40
40
  * HKDF info strings, one per direction.
41
41
  *
42
42
  * Separate keys per direction, not one shared key, so a message the server sent
43
43
  * can never be replayed back at it as though the client had sent it.
44
44
  */
45
- declare const CLIENT_TO_SERVER_INFO = "doompi/sealed/c2s/v1";
46
- declare const SERVER_TO_CLIENT_INFO = "doompi/sealed/s2c/v1";
47
- type SealedDirection = 'c2s' | 's2c';
48
- declare function infoFor(direction: SealedDirection): string;
45
+ export declare const CLIENT_TO_SERVER_INFO = "doompi/sealed/c2s/v1";
46
+ export declare const SERVER_TO_CLIENT_INFO = "doompi/sealed/s2c/v1";
47
+ export type SealedDirection = 'c2s' | 's2c';
48
+ export declare function infoFor(direction: SealedDirection): string;
49
49
  /**
50
50
  * One sealed message, as it travels.
51
51
  *
52
52
  * Base64url rather than binary so the same envelope works on a JSON body and a
53
53
  * text WebSocket frame without a second encoding path to get wrong.
54
54
  */
55
- interface SealedEnvelope {
55
+ export interface SealedEnvelope {
56
56
  v: number;
57
57
  /** Base64url, 4-byte prefix plus 8-byte counter. */
58
58
  n: string;
59
59
  /** Base64url ciphertext with the GCM tag appended. */
60
60
  c: string;
61
61
  }
62
- declare function isSealedEnvelope(value: unknown): value is SealedEnvelope;
62
+ export declare function isSealedEnvelope(value: unknown): value is SealedEnvelope;
63
63
  /** Header naming the client's ephemeral public key during the handshake. */
64
- declare const SEALED_CLIENT_KEY_HEADER = "x-doompi-channel-key";
64
+ export declare const SEALED_CLIENT_KEY_HEADER = "x-doompi-channel-key";
65
65
  /** Header carrying a sealed request body's envelope on a non-JSON request. */
66
- declare const SEALED_BODY_HEADER = "x-doompi-sealed";
67
- type SealedFailure = 'version' | 'malformed' | 'replay' | 'auth' | 'exhausted';
66
+ export declare const SEALED_BODY_HEADER = "x-doompi-sealed";
67
+ export type SealedFailure = 'version' | 'malformed' | 'replay' | 'auth' | 'exhausted';
68
68
  /**
69
69
  * Why an unseal failed, in words a diagnostic can show.
70
70
  *
71
71
  * A decryption failure means a blank cockpit, so every one of these has to name
72
72
  * its cause rather than leaving a dead page and no explanation.
73
73
  */
74
- declare function describeSealedFailure(failure: SealedFailure): string;
74
+ export declare function describeSealedFailure(failure: SealedFailure): string;
75
75
  //#endregion
76
- export { CLIENT_TO_SERVER_INFO, MAX_MESSAGES_PER_KEY, NONCE_BYTES, NONCE_COUNTER_BYTES, NONCE_PREFIX_BYTES, SEALED_BODY_HEADER, SEALED_CLIENT_KEY_HEADER, SEALED_KEY_PARAM, SEALED_VERSION, SERVER_TO_CLIENT_INFO, SealedDirection, SealedEnvelope, SealedFailure, describeSealedFailure, infoFor, isSealedEnvelope };
77
76
  //# sourceMappingURL=sealedChannel.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sealedChannel.d.mts","names":[],"sources":["../../src/types/sealedChannel.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;cAoBa;;cAGA;;cAGA;;cAEA;;cAEA;;;;;;;;;cAUA;;;;;;;cAQA;cACA;KAED;iBAEI,QAAQ,WAAW;;;;;;;UAUlB;EACf;;EAEA;;EAEA;;iBAGc,iBAAiB,iBAAiB,SAAS;;cAO9C;;cAEA;KAED;;;;;;;iBAQI,sBAAsB,SAAS"}
1
+ {"version":3,"file":"sealedChannel.d.mts","names":[],"sources":["../../src/types/sealedChannel.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;qBAoBa;;qBAGA;;qBAGA;;qBAEA;;qBAEA;;;;;;;;;qBAUA;;;;;;;qBAQA;qBACA;YAED;wBAEI,QAAQ,WAAW;;;;;;;iBAUlB;EACf;;EAEA;;EAEA;;wBAGc,iBAAiB,iBAAiB,SAAS;;qBAO9C;;qBAEA;YAED;;;;;;;wBAQI,sBAAsB,SAAS"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/doompi-web-security",
3
- "version": "0.0.1-alpha.4",
3
+ "version": "0.0.1-alpha.41",
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",
@@ -57,11 +57,11 @@
57
57
  "access": "public"
58
58
  },
59
59
  "devDependencies": {
60
- "@types/node": "26.2.0",
61
- "@vitest/coverage-v8": "4.1.11",
62
- "tsdown": "0.22.14",
60
+ "@types/node": "26.6.1",
61
+ "@vitest/coverage-v8": "5.0.1",
62
+ "tsdown": "0.23.0",
63
63
  "typescript": "7.0.2",
64
- "vitest": "4.1.11"
64
+ "vitest": "5.0.1"
65
65
  },
66
66
  "engines": {
67
67
  "node": ">=22.19.0"
@@ -1,2 +0,0 @@
1
- const e=require("../types/sealedChannel.cjs"),t={name:`ECDH`,namedCurve:`P-256`},n=`AES-GCM`;function r(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function i(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function a(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function o(t,r){let i=await crypto.subtle.importKey(`raw`,t,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:a(new TextEncoder().encode(`doompi/sealed/v1`)),info:a(new TextEncoder().encode(e.infoFor(r)))},i,{name:n,length:256},!1,[`encrypt`,`decrypt`])}function s(e,t){let n=new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function c(t,o,c){let l=0n,u=-1n;return{async seal(r){if(l>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let o=s(c,l),u=await crypto.subtle.encrypt({name:n,iv:a(o),tagLength:128},t,a(r));return l+=1n,{ok:!0,envelope:{v:1,n:i(o),c:i(new Uint8Array(u))}}},async open(t){let i=t;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(t))return{ok:!1,failure:`malformed`};let s=r(t.n),c=r(t.c);if(s===void 0||c===void 0||s.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(a(s)).getBigUint64(4,!1);if(l<=u)return{ok:!1,failure:`replay`};let d;try{d=await crypto.subtle.decrypt({name:n,iv:a(s),tagLength:128},o,a(c))}catch{return{ok:!1,failure:`auth`}}return u=l,{ok:!0,plaintext:new Uint8Array(d)}}}}async function l(e){if(globalThis.crypto?.subtle!==void 0)try{let n=await crypto.subtle.generateKey(t,!1,[`deriveBits`]),s=r(e);if(s===void 0)return;let l=await crypto.subtle.importKey(`raw`,a(s),t,!1,[]),u=await crypto.subtle.deriveBits({name:`ECDH`,public:l},n.privateKey,256),d=i(new Uint8Array(await crypto.subtle.exportKey(`raw`,n.publicKey)));return{channel:c(await o(u,`c2s`),await o(u,`s2c`),new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function u(e,t,n){return c(await o(e,t),await o(e,t===`c2s`?`s2c`:`c2s`),n)}exports.channelFromSecret=u,exports.connectSealedChannel=l;
2
- //# sourceMappingURL=browserSealedChannel.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserSealedChannel.cjs","names":["infoFor","MAX_MESSAGES_PER_KEY","isSealedEnvelope"],"sources":["../../src/adapters/browserSealedChannel.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../types/sealedChannel.ts';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'doompi/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"8CAuBM,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpD,EAAS,UAef,SAAS,EAAM,EAAuC,CACpD,IAAI,EACJ,GAAI,C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,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,EAC1B,IAAI,WAAA,CAA6B,CACnC,EACA,iBACF,CACF,MAAQ,CAGN,MACF,CACF,CAGA,eAAsB,EACpB,EACA,EACA,EACwB,CAGxB,OAAO,EAAY,MAFA,EAAO,EAAQ,CAAa,EAEtB,MADH,EAAO,EAAQ,IAAkB,MAAQ,MAAQ,KAAK,EAC1C,CAAW,CAC/C"}
@@ -1,36 +0,0 @@
1
- import { SealedDirection, SealedEnvelope, SealedFailure } from "../types/sealedChannel.cjs";
2
- //#region src/adapters/browserSealedChannel.d.ts
3
- type SealResult = {
4
- ok: true;
5
- envelope: SealedEnvelope;
6
- } | {
7
- ok: false;
8
- failure: SealedFailure;
9
- };
10
- type OpenResult = {
11
- ok: true;
12
- plaintext: Uint8Array;
13
- } | {
14
- ok: false;
15
- failure: SealedFailure;
16
- };
17
- interface SealedChannel {
18
- seal(plaintext: Uint8Array): Promise<SealResult>;
19
- open(envelope: unknown): Promise<OpenResult>;
20
- }
21
- /**
22
- * Completes the handshake against the host key read out of the QR fragment.
23
- *
24
- * That key never travelled through the tunnel, which is what makes this
25
- * authenticated: a relay can watch the client's public key go past and learn
26
- * nothing, and it cannot substitute the host's because it never carried it.
27
- */
28
- declare function connectSealedChannel(hostPublicKey: string): Promise<{
29
- channel: SealedChannel;
30
- clientPublicKey: string;
31
- } | undefined>;
32
- /** Exposed so a test can build the browser side against a known secret. */
33
- declare function channelFromSecret(secret: ArrayBuffer, sendDirection: SealedDirection, noncePrefix: Uint8Array): Promise<SealedChannel>;
34
- //#endregion
35
- export { OpenResult, SealResult, SealedChannel, channelFromSecret, connectSealedChannel };
36
- //# sourceMappingURL=browserSealedChannel.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserSealedChannel.d.cts","names":[],"sources":["../../src/adapters/browserSealedChannel.ts"],"mappings":";;KA8BY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;KAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;UAEpE;EACf,KAAK,WAAW,aAAa,QAAQ;EACrC,KAAK,oBAAoB,QAAQ;;;;;;;;;iBA+Gb,qBACpB,wBACC;EAAU,SAAS;EAAe;;;iBAyBf,kBACpB,QAAQ,aACR,eAAe,iBACf,aAAa,aACZ,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserSealedChannel.d.mts","names":[],"sources":["../../src/adapters/browserSealedChannel.ts"],"mappings":";;KA8BY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;KAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;UAEpE;EACf,KAAK,WAAW,aAAa,QAAQ;EACrC,KAAK,oBAAoB,QAAQ;;;;;;;;;iBA+Gb,qBACpB,wBACC;EAAU,SAAS;EAAe;;;iBAyBf,kBACpB,QAAQ,aACR,eAAe,iBACf,aAAa,aACZ,QAAQ"}
@@ -1,2 +0,0 @@
1
- import{MAX_MESSAGES_PER_KEY as e,infoFor as t,isSealedEnvelope as n}from"../types/sealedChannel.mjs";const r={name:`ECDH`,namedCurve:`P-256`},i=`AES-GCM`;function a(e){let t;try{t=atob(e.replaceAll(`-`,`+`).replaceAll(`_`,`/`))}catch{return}let n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function o(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replaceAll(`=`,``)}function s(e){let t=new Uint8Array(new ArrayBuffer(e.length));return t.set(e),t.buffer}async function c(e,n){let r=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:s(new TextEncoder().encode(`doompi/sealed/v1`)),info:s(new TextEncoder().encode(t(n)))},r,{name:i,length:256},!1,[`encrypt`,`decrypt`])}function l(e,t){let n=new Uint8Array(12);return n.set(e.subarray(0,4),0),new DataView(n.buffer).setBigUint64(4,t,!1),n}function u(t,r,c){let u=0n,d=-1n;return{async seal(n){if(u>=BigInt(e))return{ok:!1,failure:`exhausted`};let r=l(c,u),a=await crypto.subtle.encrypt({name:i,iv:s(r),tagLength:128},t,s(n));return u+=1n,{ok:!0,envelope:{v:1,n:o(r),c:o(new Uint8Array(a))}}},async open(e){let t=e;if(typeof t?.n!=`string`||typeof t.c!=`string`)return{ok:!1,failure:`malformed`};if(t.v!==1)return{ok:!1,failure:`version`};if(!n(e))return{ok:!1,failure:`malformed`};let o=a(e.n),c=a(e.c);if(o===void 0||c===void 0||o.length!==12||c.length<16)return{ok:!1,failure:`malformed`};let l=new DataView(s(o)).getBigUint64(4,!1);if(l<=d)return{ok:!1,failure:`replay`};let u;try{u=await crypto.subtle.decrypt({name:i,iv:s(o),tagLength:128},r,s(c))}catch{return{ok:!1,failure:`auth`}}return d=l,{ok:!0,plaintext:new Uint8Array(u)}}}}async function d(e){if(globalThis.crypto?.subtle!==void 0)try{let t=await crypto.subtle.generateKey(r,!1,[`deriveBits`]),n=a(e);if(n===void 0)return;let i=await crypto.subtle.importKey(`raw`,s(n),r,!1,[]),l=await crypto.subtle.deriveBits({name:`ECDH`,public:i},t.privateKey,256),d=o(new Uint8Array(await crypto.subtle.exportKey(`raw`,t.publicKey)));return{channel:u(await c(l,`c2s`),await c(l,`s2c`),new Uint8Array(4)),clientPublicKey:d}}catch{return}}async function f(e,t,n){return u(await c(e,t),await c(e,t===`c2s`?`s2c`:`c2s`),n)}export{f as channelFromSecret,d as connectSealedChannel};
2
- //# sourceMappingURL=browserSealedChannel.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browserSealedChannel.mjs","names":[],"sources":["../../src/adapters/browserSealedChannel.ts"],"sourcesContent":["import {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../types/sealedChannel.ts';\n\n/**\n * The browser half of the sealed channel.\n *\n * Mirrors `nodeSealedChannel.ts` exactly, on WebCrypto instead of\n * `node:crypto`. Two implementations rather than one because a shared one would\n * drag node builtins into every browser bundle that imports it, and this\n * package is imported by plugins that ship to the page. The envelope contract\n * they both read lives in `../types/sealedChannel.ts`, and a round-trip test\n * pins the two together so they cannot drift.\n */\n\nconst KEY_ALGORITHM = { name: 'ECDH', namedCurve: 'P-256' } as const;\nconst CIPHER = 'AES-GCM';\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = 16;\nconst HKDF_SALT = 'doompi/sealed/v1';\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n seal(plaintext: Uint8Array): Promise<SealResult>;\n open(envelope: unknown): Promise<OpenResult>;\n}\n\n/** Undefined rather than a throw: a malformed field is a verdict, not an exception. */\nfunction bytes(value: string): Uint8Array | undefined {\n let binary: string;\n try {\n binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));\n } catch {\n return undefined;\n }\n const out = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) out[index] = binary.charCodeAt(index);\n return out;\n}\n\nfunction base64Url(value: Uint8Array): string {\n let binary = '';\n for (const byte of value) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nfunction view(value: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(new ArrayBuffer(value.length));\n copy.set(value);\n return copy.buffer;\n}\n\nasync function derive(secret: ArrayBuffer, direction: SealedDirection): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);\n return await crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: view(new TextEncoder().encode(HKDF_SALT)),\n info: view(new TextEncoder().encode(infoFor(direction))),\n },\n material,\n { name: CIPHER, length: KEY_BITS },\n false,\n ['encrypt', 'decrypt'],\n );\n}\n\nfunction nonceFor(prefix: Uint8Array, counter: bigint): Uint8Array {\n const nonce = new Uint8Array(NONCE_BYTES);\n nonce.set(prefix.subarray(0, NONCE_PREFIX_BYTES), 0);\n new DataView(nonce.buffer).setBigUint64(NONCE_PREFIX_BYTES, counter, false);\n return nonce;\n}\n\nfunction channelFrom(sendKey: CryptoKey, receiveKey: CryptoKey, noncePrefix: Uint8Array): SealedChannel {\n let sendCounter = 0n;\n let highestReceived = -1n;\n\n return {\n async seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const sealed = await crypto.subtle.encrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n sendKey,\n view(plaintext),\n );\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: base64Url(nonce), c: base64Url(new Uint8Array(sealed)) },\n };\n },\n\n async open(envelope) {\n // Shape before version, matching the server: something with no `v` at all\n // is malformed rather than a protocol skew.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = bytes(envelope.n);\n const body = bytes(envelope.c);\n if (nonce === undefined || body === undefined) return { ok: false, failure: 'malformed' };\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = new DataView(view(nonce)).getBigUint64(NONCE_PREFIX_BYTES, false);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n let plaintext: ArrayBuffer;\n try {\n plaintext = await crypto.subtle.decrypt(\n { name: CIPHER, iv: view(nonce), tagLength: TAG_BITS },\n receiveKey,\n view(body),\n );\n } catch {\n // A failed tag means the message was altered in transit; there is no\n // partial result worth salvaging.\n return { ok: false, failure: 'auth' };\n }\n // Only after the tag verified, so a forged high counter cannot lock out\n // every message that legitimately follows it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\n/**\n * Completes the handshake against the host key read out of the QR fragment.\n *\n * That key never travelled through the tunnel, which is what makes this\n * authenticated: a relay can watch the client's public key go past and learn\n * nothing, and it cannot substitute the host's because it never carried it.\n */\nexport async function connectSealedChannel(\n hostPublicKey: string,\n): Promise<{ channel: SealedChannel; clientPublicKey: string } | undefined> {\n if (globalThis.crypto?.subtle === undefined) return undefined;\n try {\n const pair = await crypto.subtle.generateKey(KEY_ALGORITHM, false, ['deriveBits']);\n const hostKey = bytes(hostPublicKey);\n if (hostKey === undefined) return undefined;\n const peer = await crypto.subtle.importKey('raw', view(hostKey), KEY_ALGORITHM, false, []);\n const secret = await crypto.subtle.deriveBits({ name: 'ECDH', public: peer }, pair.privateKey, KEY_BITS);\n const clientPublicKey = base64Url(new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)));\n return {\n channel: channelFrom(\n await derive(secret, 'c2s'),\n await derive(secret, 's2c'),\n new Uint8Array(NONCE_PREFIX_BYTES),\n ),\n clientPublicKey,\n };\n } catch {\n // A malformed host key or a context without ECDH; the caller falls back to\n // an unsealed channel and says so rather than failing silently.\n return undefined;\n }\n}\n\n/** Exposed so a test can build the browser side against a known secret. */\nexport async function channelFromSecret(\n secret: ArrayBuffer,\n sendDirection: SealedDirection,\n noncePrefix: Uint8Array,\n): Promise<SealedChannel> {\n const send = await derive(secret, sendDirection);\n const receive = await derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n return channelFrom(send, receive, noncePrefix);\n}\n"],"mappings":"qGAuBA,MAAM,EAAgB,CAAE,KAAM,OAAQ,WAAY,OAAQ,EACpD,EAAS,UAef,SAAS,EAAM,EAAuC,CACpD,IAAI,EACJ,GAAI,CACF,EAAS,KAAK,EAAM,WAAW,IAAK,GAAG,CAAC,CAAC,WAAW,IAAK,GAAG,CAAC,CAC/D,MAAQ,CACN,MACF,CACA,IAAM,EAAM,IAAI,WAAW,IAAI,YAAY,EAAO,MAAM,CAAC,EACzD,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAO,OAAQ,GAAS,EAAG,EAAI,GAAS,EAAO,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,EAA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