@agimon-ai/po-web-security 0.0.0-alpha.2 → 0.0.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/services/bundleSigner/index.cjs +1 -1
- package/dist/services/bundleSigner/index.cjs.map +1 -1
- package/dist/services/bundleSigner/index.mjs +1 -1
- package/dist/services/bundleSigner/index.mjs.map +1 -1
- package/dist/services/nodeSealedChannel/index.cjs +1 -1
- package/dist/services/nodeSealedChannel/index.cjs.map +1 -1
- package/dist/services/nodeSealedChannel/index.d.mts.map +1 -1
- package/dist/services/nodeSealedChannel/index.mjs +1 -1
- package/dist/services/nodeSealedChannel/index.mjs.map +1 -1
- package/dist/services/sealedTransport/index.cjs +1 -1
- package/dist/services/sealedTransport/index.cjs.map +1 -1
- package/dist/services/sealedTransport/index.mjs +1 -1
- package/dist/services/sealedTransport/index.mjs.map +1 -1
- package/package.json +5 -5
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../types/bundleManifest.cjs");let n=require("node:crypto"),r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=`signing.json`,o=`sha256`,s=/* @__PURE__ */ new Set([`.map`]),c=[`web`,`native`],l={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function u(e){r.default.mkdirSync(e,{recursive:!0,mode:448});let t=r.default.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);r.default.chmodSync(e,448)}function d(e,t){u(e);let n=i.default.join(e,`signing.lock`),a;for(let e=0;e<500;e+=1)try{a=r.default.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(a===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{r.default.closeSync(a),r.default.rmSync(n,{force:!0})}}function f(e,t){let o=i.default.join(e,a),s=i.default.join(e,`.${a}.${process.pid}.${(0,n.randomBytes)(8).toString(`hex`)}`),c=r.default.openSync(s,`wx`,384);try{r.default.writeFileSync(c,`${JSON.stringify(t,void 0,2)}\n`),r.default.fsyncSync(c)}finally{r.default.closeSync(c)}try{r.default.renameSync(s,o),r.default.chmodSync(o,384)}catch(e){throw r.default.rmSync(s,{force:!0}),e}}function p(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=y(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function m(e){return d(e,()=>{let t=i.default.join(e,a);try{let n=r.default.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let i=JSON.parse(r.default.readFileSync(t,`utf8`)),a=p(i,t);return r.default.chmodSync(t,384),i.revision===void 0&&f(e,a),a}catch(e){if(e.code!==`ENOENT`)throw e}let o=(0,n.generateKeyPairSync)(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),s={privateKey:o.privateKey,publicKey:Buffer.from(o.publicKey).toString(`base64url`),revision:0};return f(e,s),s})}function h(e,t){return d(e,()=>{let n=i.default.join(e,a),o=p(JSON.parse(r.default.readFileSync(n,`utf8`)),n);if(o.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(o.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let s={...o,revision:o.revision+1};return f(e,s),s.revision})}function g(e){return l[i.default.extname(e).toLowerCase()]??`application/octet-stream`}function _(e,t,a){let o=r.default.readdirSync(t,{withFileTypes:!0});for(let c of o){let o=i.default.join(t,c.name),l=r.default.lstatSync(o);if(l.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${o}`);if(l.isDirectory()){_(e,o,a);continue}if(!l.isFile())throw Error(`refusing to omit unsupported asset: ${o}`);if(s.has(i.default.extname(c.name)))continue;let u=r.default.readFileSync(o);a.push({path:`/${i.default.relative(e,o).split(i.default.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:(0,n.createHash)(`sha256`).update(u).digest(`hex`),byteLength:u.byteLength,contentType:g(o)})}}function v(e,a=()=>{}){let s=m(e),l=(0,n.createPrivateKey)(s.privateKey),u=/* @__PURE__ */ new Map,d=(e,t)=>`${t}:${i.default.resolve(e)}`,f=(i,a)=>{let c=r.default.lstatSync(i);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${i}`);let u=[];if(_(i,i,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:h(e,s.publicKey),builtAt:Date.now(),assets:u};if(!t.isBundleManifest(d,a))throw Error(`refusing to sign an invalid ${a} bundle manifest`);return{manifest:d,signature:(0,n.createSign)(o).update(t.canonicalManifest(d)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},p=(e,t=`web`)=>{let n=d(e,t);if(u.has(n))return u.get(n);let r=f(i.default.resolve(e),t);return u.set(n,r),r};return{publicKey:()=>s.publicKey,sign:p,refresh(e,t=`web`){return u.delete(d(e,t)),p(e,t)},invalidate(e){if(e===void 0)
|
|
1
|
+
const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../types/bundleManifest.cjs");let n=require("node:crypto"),r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);const a=`signing.json`,o=`sha256`,s=/* @__PURE__ */ new Set([`.map`]),c=[`web`,`native`],l={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function u(e){r.default.mkdirSync(e,{recursive:!0,mode:448});let t=r.default.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);r.default.chmodSync(e,448)}function d(e,t){u(e);let n=i.default.join(e,`signing.lock`),a;for(let e=0;e<500;e+=1)try{a=r.default.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(a===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{r.default.closeSync(a),r.default.rmSync(n,{force:!0})}}function f(e,t){let o=i.default.join(e,a),s=i.default.join(e,`.${a}.${process.pid}.${(0,n.randomBytes)(8).toString(`hex`)}`),c=r.default.openSync(s,`wx`,384);try{r.default.writeFileSync(c,`${JSON.stringify(t,void 0,2)}\n`),r.default.fsyncSync(c)}finally{r.default.closeSync(c)}try{r.default.renameSync(s,o),r.default.chmodSync(o,384)}catch(e){throw r.default.rmSync(s,{force:!0}),e}}function p(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=y(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function m(e){return d(e,()=>{let t=i.default.join(e,a);try{let n=r.default.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let i=JSON.parse(r.default.readFileSync(t,`utf8`)),a=p(i,t);return r.default.chmodSync(t,384),i.revision===void 0&&f(e,a),a}catch(e){if(e.code!==`ENOENT`)throw e}let o=(0,n.generateKeyPairSync)(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),s={privateKey:o.privateKey,publicKey:Buffer.from(o.publicKey).toString(`base64url`),revision:0};return f(e,s),s})}function h(e,t){return d(e,()=>{let n=i.default.join(e,a),o=p(JSON.parse(r.default.readFileSync(n,`utf8`)),n);if(o.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(o.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let s={...o,revision:o.revision+1};return f(e,s),s.revision})}function g(e){return l[i.default.extname(e).toLowerCase()]??`application/octet-stream`}function _(e,t,a){let o=r.default.readdirSync(t,{withFileTypes:!0});for(let c of o){let o=i.default.join(t,c.name),l=r.default.lstatSync(o);if(l.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${o}`);if(l.isDirectory()){_(e,o,a);continue}if(!l.isFile())throw Error(`refusing to omit unsupported asset: ${o}`);if(s.has(i.default.extname(c.name)))continue;let u=r.default.readFileSync(o);a.push({path:`/${i.default.relative(e,o).split(i.default.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:(0,n.createHash)(`sha256`).update(u).digest(`hex`),byteLength:u.byteLength,contentType:g(o)})}}function v(e,a=()=>{}){let s=m(e),l=(0,n.createPrivateKey)(s.privateKey),u=/* @__PURE__ */ new Map,d=(e,t)=>`${t}:${i.default.resolve(e)}`,f=(i,a)=>{let c=r.default.lstatSync(i);if(!c.isDirectory()||c.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${i}`);let u=[];if(_(i,i,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:h(e,s.publicKey),builtAt:Date.now(),assets:u};if(!t.isBundleManifest(d,a))throw Error(`refusing to sign an invalid ${a} bundle manifest`);return{manifest:d,signature:(0,n.createSign)(o).update(t.canonicalManifest(d)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},p=(e,t=`web`)=>{let n=d(e,t);if(u.has(n))return u.get(n);let r=f(i.default.resolve(e),t);return u.set(n,r),r};return{publicKey:()=>s.publicKey,sign:p,refresh(e,t=`web`){return u.delete(d(e,t)),p(e,t)},invalidate(e){if(e===void 0)u.clear();else for(let t of c)u.delete(d(e,t))},attest(e,r){return(0,n.createSign)(o).update(t.attestationBytes(e,r)).sign({key:l,dsaEncoding:`ieee-p1363`}).toString(`base64url`)}}}function y(e){return Buffer.from((0,n.createPublicKey)(e).export({type:`spki`,format:`der`})).toString(`base64url`)}exports.createBundleSigner=v,exports.publicKeyOf=y;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","attestationBytes","createPublicKey","require_runtime","require_bundleManifest","node_crypto","node_fs","node_path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createBundleSigner","key","privateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","sign","cacheKey","signed","tag","fields","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"mNAsBA,MAAMgB,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,QAAQ,EACrDC,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EA2BA,SAASC,EAAqB,EAAwB,CACpDP,EAAA,QAAG,UAAUQ,EAAU,CAAE,UAAW,GAAM,KAAM,G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AAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WAAW,CACzB,CACF,CACF,CAGA,SAAgBpB,EAAY,EAA+B,CACzD,OAAO,OAAO,MAAA,EAAK9B,EAAAA,gBAAAA,CAAgBkE,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["fs","path","randomBytes","generateKeyPairSync","createHash","createPrivateKey","isBundleManifest","createSign","canonicalManifest","attestationBytes","createPublicKey","require_runtime","require_bundleManifest","node_crypto","node_fs","node_path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createBundleSigner","key","privateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","sign","cacheKey","signed","tag","fields","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"mNAsBA,MAAMgB,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,QAAQ,EACrDC,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EA2BA,SAASC,EAAqB,EAAwB,CACpDP,EAAA,QAAG,UAAUQ,EAAU,CAAE,UAAW,GAAM,KAAM,GAAe,CAAC,EAChE,IAAMC,EAAOvB,EAAAA,QAAG,UAAUsB,CAAQ,EAClC,GAAI,CAACC,EAAK,YAAY,GAAKA,EAAK,eAAe,EAC7C,MAAU,MAAM,4CAA4CD,GAAU,EACxER,EAAA,QAAG,UAAUQ,EAAU,GAAc,CACvC,CAEA,SAASE,EAAiB,EAAkB,EAAuB,CACjEH,EAAqBC,CAAQ,EAC7B,IAAMG,EAAWxB,EAAAA,QAAK,KAAKqB,EAAU,cAAS,EAC1CI,EACJ,IAAK,IAAIC,EAAU,EAAGA,EAAU,IAAK,GAAW,EAC9C,GAAI,CACF,EAAa3B,EAAAA,QAAG,SAASyB,EAAU,KAAM,GAAS,EAClD,KACF,OAASG,EAAO,CACd,GAAKA,EAAgC,OAAS,SAAU,MAAMA,EAC9D,QAAQ,KAAK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B,EAAyB,QAA4C,CACpG,IAAMC,EAAWV,EAAWE,EAAWD,CAAO,EAC9C,GAAIF,EAAM,IAAIW,CAAQ,EAAG,OAAOX,EAAM,IAAIW,CAAQ,EAClD,IAAMC,EAASR,EAAUhE,EAAAA,QAAK,QAAQ+D,CAAS,EAAGD,CAAO,EAEzD,OADAF,EAAM,IAAIW,EAAUC,CAAM,EACnBA,CACT,EAEA,MAAO,CACL,cAAiBd,EAAI,UACrB,OACA,QAAQ,EAAW,EAAU,MAAO,CAElC,OADAE,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,EACpCQ,EAAKP,EAAWD,CAAO,CAChC,EACA,WAAW,EAAW,CACpB,GAAIC,IAAc,IAAA,GAChBH,EAAM,MAAM,OAGd,IAAK,IAAME,KAAW5C,EAAU0C,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,CAC7E,EACA,OAAO,EAAK,EAAQ,CAClB,OAAA,EAAOxD,EAAAA,WAAAA,CAAWU,CAAc,CAAC,CAC9B,OAAOR,EAAAA,iBAAiBiE,EAAKC,CAAM,CAAC,CAAC,CACrC,KAAK,CAAE,IAAKf,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WAAW,CACzB,CACF,CACF,CAGA,SAAgBpB,EAAY,EAA+B,CACzD,OAAO,OAAO,MAAA,EAAK9B,EAAAA,gBAAAA,CAAgBkE,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{attestationBytes as e,canonicalManifest as t,isBundleManifest as n}from"../../types/bundleManifest.mjs";import{createHash as r,createPrivateKey as i,createPublicKey as a,createSign as o,generateKeyPairSync as s,randomBytes as c}from"node:crypto";import l from"node:fs";import u from"node:path";const d=`signing.json`,f=`sha256`,p=/* @__PURE__ */ new Set([`.map`]),m=[`web`,`native`],h={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function g(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);l.chmodSync(e,448)}function _(e,t){g(e);let n=u.join(e,`signing.lock`),r;for(let e=0;e<500;e+=1)try{r=l.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(r===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{l.closeSync(r),l.rmSync(n,{force:!0})}}function v(e,t){let n=u.join(e,d),r=u.join(e,`.${d}.${process.pid}.${c(8).toString(`hex`)}`),i=l.openSync(r,`wx`,384);try{l.writeFileSync(i,`${JSON.stringify(t,void 0,2)}\n`),l.fsyncSync(i)}finally{l.closeSync(i)}try{l.renameSync(r,n),l.chmodSync(n,384)}catch(e){throw l.rmSync(r,{force:!0}),e}}function y(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=T(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function b(e){return _(e,()=>{let t=u.join(e,d);try{let n=l.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let r=JSON.parse(l.readFileSync(t,`utf8`)),i=y(r,t);return l.chmodSync(t,384),r.revision===void 0&&v(e,i),i}catch(e){if(e.code!==`ENOENT`)throw e}let n=s(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),r={privateKey:n.privateKey,publicKey:Buffer.from(n.publicKey).toString(`base64url`),revision:0};return v(e,r),r})}function x(e,t){return _(e,()=>{let n=u.join(e,d),r=y(JSON.parse(l.readFileSync(n,`utf8`)),n);if(r.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(r.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let i={...r,revision:r.revision+1};return v(e,i),i.revision})}function S(e){return h[u.extname(e).toLowerCase()]??`application/octet-stream`}function C(e,t,n){let i=l.readdirSync(t,{withFileTypes:!0});for(let a of i){let i=u.join(t,a.name),o=l.lstatSync(i);if(o.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${i}`);if(o.isDirectory()){C(e,i,n);continue}if(!o.isFile())throw Error(`refusing to omit unsupported asset: ${i}`);if(p.has(u.extname(a.name)))continue;let s=l.readFileSync(i);n.push({path:`/${u.relative(e,i).split(u.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:r(`sha256`).update(s).digest(`hex`),byteLength:s.byteLength,contentType:S(i)})}}function w(r,a=()=>{}){let s=b(r),c=i(s.privateKey),d=/* @__PURE__ */ new Map,p=(e,t)=>`${t}:${u.resolve(e)}`,h=(e,i)=>{let a=l.lstatSync(e);if(!a.isDirectory()||a.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${e}`);let u=[];if(C(e,e,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:x(r,s.publicKey),builtAt:Date.now(),assets:u};if(!n(d,i))throw Error(`refusing to sign an invalid ${i} bundle manifest`);return{manifest:d,signature:o(f).update(t(d)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},g=(e,t=`web`)=>{let n=p(e,t);if(d.has(n))return d.get(n);let r=h(u.resolve(e),t);return d.set(n,r),r};return{publicKey:()=>s.publicKey,sign:g,refresh(e,t=`web`){return d.delete(p(e,t)),g(e,t)},invalidate(e){if(e===void 0)
|
|
1
|
+
import{attestationBytes as e,canonicalManifest as t,isBundleManifest as n}from"../../types/bundleManifest.mjs";import{createHash as r,createPrivateKey as i,createPublicKey as a,createSign as o,generateKeyPairSync as s,randomBytes as c}from"node:crypto";import l from"node:fs";import u from"node:path";const d=`signing.json`,f=`sha256`,p=/* @__PURE__ */ new Set([`.map`]),m=[`web`,`native`],h={".css":`text/css`,".gif":`image/gif`,".html":`text/html`,".ico":`image/x-icon`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".js":`text/javascript`,".json":`application/json`,".mjs":`text/javascript`,".png":`image/png`,".svg":`image/svg+xml`,".txt":`text/plain`,".wasm":`application/wasm`,".webp":`image/webp`,".woff":`font/woff`,".woff2":`font/woff2`};function g(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw Error(`bundle signing state is not a directory: ${e}`);l.chmodSync(e,448)}function _(e,t){g(e);let n=u.join(e,`signing.lock`),r;for(let e=0;e<500;e+=1)try{r=l.openSync(n,`wx`,384);break}catch(e){if(e.code!==`EEXIST`)throw e;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}if(r===void 0)throw Error(`timed out waiting for bundle signing state lock: ${n}`);try{return t()}finally{l.closeSync(r),l.rmSync(n,{force:!0})}}function v(e,t){let n=u.join(e,d),r=u.join(e,`.${d}.${process.pid}.${c(8).toString(`hex`)}`),i=l.openSync(r,`wx`,384);try{l.writeFileSync(i,`${JSON.stringify(t,void 0,2)}\n`),l.fsyncSync(i)}finally{l.closeSync(i)}try{l.renameSync(r,n),l.chmodSync(n,384)}catch(e){throw l.rmSync(r,{force:!0}),e}}function y(e,t){if(typeof e!=`object`||!e)throw Error(`invalid bundle signing state: ${t}`);let n=e;if(typeof n.privateKey!=`string`||typeof n.publicKey!=`string`)throw Error(`invalid bundle signing state: ${t}`);let r=n.revision===void 0?0:n.revision;if(!Number.isSafeInteger(r)||r<0)throw Error(`invalid bundle signing revision: ${t}`);let i;try{i=T(n.privateKey)}catch{throw Error(`invalid bundle signing private key: ${t}`)}if(i!==n.publicKey)throw Error(`bundle signing keys do not match: ${t}`);return{privateKey:n.privateKey,publicKey:n.publicKey,revision:r}}function b(e){return _(e,()=>{let t=u.join(e,d);try{let n=l.lstatSync(t);if(!n.isFile()||n.isSymbolicLink())throw Error(`invalid bundle signing state file: ${t}`);let r=JSON.parse(l.readFileSync(t,`utf8`)),i=y(r,t);return l.chmodSync(t,384),r.revision===void 0&&v(e,i),i}catch(e){if(e.code!==`ENOENT`)throw e}let n=s(`ec`,{namedCurve:`prime256v1`,privateKeyEncoding:{type:`pkcs8`,format:`pem`},publicKeyEncoding:{type:`spki`,format:`der`}}),r={privateKey:n.privateKey,publicKey:Buffer.from(n.publicKey).toString(`base64url`),revision:0};return v(e,r),r})}function x(e,t){return _(e,()=>{let n=u.join(e,d),r=y(JSON.parse(l.readFileSync(n,`utf8`)),n);if(r.publicKey!==t)throw Error(`bundle signing key changed while the signer was active`);if(r.revision===2**53-1)throw Error(`bundle signing revision is exhausted`);let i={...r,revision:r.revision+1};return v(e,i),i.revision})}function S(e){return h[u.extname(e).toLowerCase()]??`application/octet-stream`}function C(e,t,n){let i=l.readdirSync(t,{withFileTypes:!0});for(let a of i){let i=u.join(t,a.name),o=l.lstatSync(i);if(o.isSymbolicLink())throw Error(`refusing to sign symbolic link: ${i}`);if(o.isDirectory()){C(e,i,n);continue}if(!o.isFile())throw Error(`refusing to omit unsupported asset: ${i}`);if(p.has(u.extname(a.name)))continue;let s=l.readFileSync(i);n.push({path:`/${u.relative(e,i).split(u.sep).map(e=>encodeURIComponent(e)).join(`/`)}`,sha256:r(`sha256`).update(s).digest(`hex`),byteLength:s.byteLength,contentType:S(i)})}}function w(r,a=()=>{}){let s=b(r),c=i(s.privateKey),d=/* @__PURE__ */ new Map,p=(e,t)=>`${t}:${u.resolve(e)}`,h=(e,i)=>{let a=l.lstatSync(e);if(!a.isDirectory()||a.isSymbolicLink())throw Error(`refusing to sign an unsafe asset root: ${e}`);let u=[];if(C(e,e,u),u.length===0)return;u.sort((e,t)=>e.path.localeCompare(t.path));let d={version:2,revision:x(r,s.publicKey),builtAt:Date.now(),assets:u};if(!n(d,i))throw Error(`refusing to sign an invalid ${i} bundle manifest`);return{manifest:d,signature:o(f).update(t(d)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`),publicKey:s.publicKey}},g=(e,t=`web`)=>{let n=p(e,t);if(d.has(n))return d.get(n);let r=h(u.resolve(e),t);return d.set(n,r),r};return{publicKey:()=>s.publicKey,sign:g,refresh(e,t=`web`){return d.delete(p(e,t)),g(e,t)},invalidate(e){if(e===void 0)d.clear();else for(let t of m)d.delete(p(e,t))},attest(t,n){return o(f).update(e(t,n)).sign({key:c,dsaEncoding:`ieee-p1363`}).toString(`base64url`)}}}function T(e){return Buffer.from(a(e).export({type:`spki`,format:`der`})).toString(`base64url`)}export{w as createBundleSigner,T as publicKeyOf};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["fs","path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","randomBytes","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","generateKeyPairSync","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createHash","createBundleSigner","key","privateKey","createPrivateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","isBundleManifest","createSign","canonicalManifest","sign","cacheKey","signed","attestationBytes","tag","fields","createPublicKey","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"6SAsBA,MAAME,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,QAAQ,EACrDC,EAA+C,CACnD,OAAQ,WACR,OAAQ,YACR,QAAS,YACT,OAAQ,eACR,QAAS,aACT,OAAQ,aACR,MAAO,kBACP,QAAS,mBACT,OAAQ,kBACR,OAAQ,YACR,OAAQ,gBACR,OAAQ,aACR,QAAS,mBACT,QAAS,aACT,QAAS,YACT,SAAU,YACZ,EA2BA,SAASC,EAAqB,EAAwB,CACpDP,EAAG,UAAUQ,EAAU,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CAAC,CACzC,OAAO4D,EAAkBH,CAAQ,CAAC,CAAC,CACnC,KAAK,CAAE,IAAKX,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WACe,EAAG,UAAWD,EAAI,SAAU,CACzD,EAEMgB,GAAQ,EAAmB,EAAyB,QAA4C,CACpG,IAAMC,EAAWb,EAAWE,EAAWD,CAAO,EAC9C,GAAIF,EAAM,IAAIc,CAAQ,EAAG,OAAOd,EAAM,IAAIc,CAAQ,EAClD,IAAMC,EAASX,EAAUtD,EAAK,QAAQqD,CAAS,EAAGD,CAAO,EAEzD,OADAF,EAAM,IAAIc,EAAUC,CAAM,EACnBA,CACT,EAEA,MAAO,CACL,cAAiBlB,EAAI,UACrB,OACA,QAAQ,EAAW,EAAU,MAAO,CAElC,OADAG,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,EACpCW,EAAKV,EAAWD,CAAO,CAChC,EACA,WAAW,EAAW,CACpB,GAAIC,IAAc,IAAA,GAAW,CAC3BH,EAAM,MAAM,EACZ,MACF,CACA,IAAK,IAAME,KAAWhD,EAAU8C,EAAM,OAAOC,EAAWE,EAAWD,CAAO,CAAC,CAC7E,EACA,OAAO,EAAK,EAAQ,CAClB,OAAOS,EAAW3D,CAAc,CAAC,CAC9B,OAAOgE,EAAiBC,EAAKC,CAAM,CAAC,CAAC,CACrC,KAAK,CAAE,IAAKpB,EAAY,YAAa,YAAa,CAAC,CAAC,CACpD,SAAS,WAAW,CACzB,CACF,CACF,CAGA,SAAgBtB,EAAY,EAA+B,CACzD,OAAO,OAAO,KAAK2C,EAAgBC,CAAa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["fs","path","SIGNING_FILE","SIGN_ALGORITHM","SKIPPED","PROFILES","MIME_TYPES","ensureStateDirectory","stateDir","stat","withStateLock","lockPath","descriptor","attempt","error","operation","atomicWriteState","destination","temporary","randomBytes","state","parseState","value","keyPath","candidate","revision","derived","publicKeyOf","loadOrCreateState","parsed","pair","generateKeyPairSync","reserveRevision","expectedPublicKey","next","contentTypeFor","filePath","walk","entries","current","entry","full","root","into","bytes","segment","createHash","createBundleSigner","key","privateKey","createPrivateKey","cache","cacheKeyOf","profile","assetsDir","signFresh","rootStat","assets","left","right","manifest","isBundleManifest","createSign","canonicalManifest","sign","cacheKey","signed","attestationBytes","tag","fields","createPublicKey","privateKeyPem"],"sources":["../../../src/services/bundleSigner/index.ts"],"sourcesContent":["import {\n createHash,\n createPrivateKey,\n createPublicKey,\n createSign,\n generateKeyPairSync,\n randomBytes,\n} from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport {\n BUNDLE_MANIFEST_VERSION,\n type BundleAsset,\n type BundleManifest,\n type BundleProfile,\n type SignedBundleManifest,\n attestationBytes,\n canonicalManifest,\n isBundleManifest,\n} from '../../types/bundleManifest';\n\nconst SIGNING_FILE = 'signing.json';\nconst LOCK_FILE = 'signing.lock';\nconst FILE_MODE = 0o600;\nconst DIRECTORY_MODE = 0o700;\nconst CURVE = 'prime256v1';\nconst SIGN_ALGORITHM = 'sha256';\nconst SKIPPED = new Set(['.map']);\nconst PROFILES: readonly BundleProfile[] = ['web', 'native'];\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.css': 'text/css',\n '.gif': 'image/gif',\n '.html': 'text/html',\n '.ico': 'image/x-icon',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.js': 'text/javascript',\n '.json': 'application/json',\n '.mjs': 'text/javascript',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.txt': 'text/plain',\n '.wasm': 'application/wasm',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n};\n\nexport interface BundleSigner {\n /** Base64url SPKI for an independently trusted verifier to pin. */\n publicKey(): string;\n /**\n * Hashes and signs once per asset directory and profile. Undefined when the bundle is empty. Throws\n * when the assets do not match the profile.\n */\n sign(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates and immediately rebuilds one cached manifest. */\n refresh(assetsDir: string, profile?: BundleProfile): SignedBundleManifest | undefined;\n /** Invalidates one cached directory under every profile, or every cached directory when omitted. */\n invalidate(assetsDir?: string): void;\n /**\n * Base64url IEEE P1363 signature over `attestationBytes(tag, fields)` with the bundle key. Throws on a\n * malformed tag.\n */\n attest(tag: string, fields: readonly string[]): string;\n}\n\ninterface StoredState {\n privateKey: string;\n publicKey: string;\n revision: number;\n}\n\nfunction ensureStateDirectory(stateDir: string): void {\n fs.mkdirSync(stateDir, { recursive: true, mode: DIRECTORY_MODE });\n const stat = fs.lstatSync(stateDir);\n if (!stat.isDirectory() || stat.isSymbolicLink())\n throw new Error(`bundle signing state is not a directory: ${stateDir}`);\n fs.chmodSync(stateDir, DIRECTORY_MODE);\n}\n\nfunction withStateLock<T>(stateDir: string, operation: () => T): T {\n ensureStateDirectory(stateDir);\n const lockPath = path.join(stateDir, LOCK_FILE);\n let descriptor: number | undefined;\n for (let attempt = 0; attempt < 500; attempt += 1) {\n try {\n descriptor = fs.openSync(lockPath, 'wx', FILE_MODE);\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);\n }\n }\n if (descriptor === undefined) throw new Error(`timed out waiting for bundle signing state lock: ${lockPath}`);\n try {\n return operation();\n } finally {\n fs.closeSync(descriptor);\n fs.rmSync(lockPath, { force: true });\n }\n}\n\nfunction atomicWriteState(stateDir: string, state: StoredState): void {\n const destination = path.join(stateDir, SIGNING_FILE);\n const temporary = path.join(stateDir, `.${SIGNING_FILE}.${process.pid}.${randomBytes(8).toString('hex')}`);\n const descriptor = fs.openSync(temporary, 'wx', FILE_MODE);\n try {\n fs.writeFileSync(descriptor, `${JSON.stringify(state, undefined, 2)}\\n`);\n fs.fsyncSync(descriptor);\n } finally {\n fs.closeSync(descriptor);\n }\n try {\n fs.renameSync(temporary, destination);\n fs.chmodSync(destination, FILE_MODE);\n } catch (error) {\n fs.rmSync(temporary, { force: true });\n throw error;\n }\n}\n\nfunction parseState(value: unknown, keyPath: string): StoredState {\n if (typeof value !== 'object' || value === null) throw new Error(`invalid bundle signing state: ${keyPath}`);\n const candidate = value as Partial<StoredState>;\n if (typeof candidate.privateKey !== 'string' || typeof candidate.publicKey !== 'string') {\n throw new Error(`invalid bundle signing state: ${keyPath}`);\n }\n const revision = candidate.revision === undefined ? 0 : candidate.revision;\n if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`invalid bundle signing revision: ${keyPath}`);\n let derived: string;\n try {\n derived = publicKeyOf(candidate.privateKey);\n } catch {\n throw new Error(`invalid bundle signing private key: ${keyPath}`);\n }\n if (derived !== candidate.publicKey) throw new Error(`bundle signing keys do not match: ${keyPath}`);\n return { privateKey: candidate.privateKey, publicKey: candidate.publicKey, revision };\n}\n\nfunction loadOrCreateState(stateDir: string): StoredState {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n try {\n const stat = fs.lstatSync(keyPath);\n if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`invalid bundle signing state file: ${keyPath}`);\n const parsed: unknown = JSON.parse(fs.readFileSync(keyPath, 'utf8'));\n const state = parseState(parsed, keyPath);\n fs.chmodSync(keyPath, FILE_MODE);\n if ((parsed as Partial<StoredState>).revision === undefined) atomicWriteState(stateDir, state);\n return state;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n const pair = generateKeyPairSync('ec', {\n namedCurve: CURVE,\n privateKeyEncoding: { type: 'pkcs8', format: 'pem' },\n publicKeyEncoding: { type: 'spki', format: 'der' },\n });\n const state: StoredState = {\n privateKey: pair.privateKey,\n publicKey: Buffer.from(pair.publicKey).toString('base64url'),\n revision: 0,\n };\n atomicWriteState(stateDir, state);\n return state;\n });\n}\n\nfunction reserveRevision(stateDir: string, expectedPublicKey: string): number {\n return withStateLock(stateDir, () => {\n const keyPath = path.join(stateDir, SIGNING_FILE);\n const state = parseState(JSON.parse(fs.readFileSync(keyPath, 'utf8')) as unknown, keyPath);\n if (state.publicKey !== expectedPublicKey)\n throw new Error('bundle signing key changed while the signer was active');\n if (state.revision === Number.MAX_SAFE_INTEGER) throw new Error('bundle signing revision is exhausted');\n const next = { ...state, revision: state.revision + 1 };\n atomicWriteState(stateDir, next);\n return next.revision;\n });\n}\n\nfunction contentTypeFor(filePath: string): string {\n return MIME_TYPES[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';\n}\n\n/** Every servable regular file under the asset root, as browser paths. */\nfunction walk(root: string, current: string, into: BundleAsset[]): void {\n const entries = fs.readdirSync(current, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(current, entry.name);\n const stat = fs.lstatSync(full);\n if (stat.isSymbolicLink()) throw new Error(`refusing to sign symbolic link: ${full}`);\n if (stat.isDirectory()) {\n walk(root, full, into);\n continue;\n }\n if (!stat.isFile()) throw new Error(`refusing to omit unsupported asset: ${full}`);\n if (SKIPPED.has(path.extname(entry.name))) continue;\n const bytes = fs.readFileSync(full);\n into.push({\n path: `/${path\n .relative(root, full)\n .split(path.sep)\n .map((segment) => encodeURIComponent(segment))\n .join('/')}`,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n byteLength: bytes.byteLength,\n contentType: contentTypeFor(full),\n });\n }\n}\n\nexport function createBundleSigner(stateDir: string, _onNotice: (message: string) => void = () => {}): BundleSigner {\n const key = loadOrCreateState(stateDir);\n const privateKey = createPrivateKey(key.privateKey);\n const cache = new Map<string, SignedBundleManifest | undefined>();\n const cacheKeyOf = (assetsDir: string, profile: BundleProfile): string => `${profile}:${path.resolve(assetsDir)}`;\n\n const signFresh = (assetsDir: string, profile: BundleProfile): SignedBundleManifest | undefined => {\n const rootStat = fs.lstatSync(assetsDir);\n if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {\n throw new Error(`refusing to sign an unsafe asset root: ${assetsDir}`);\n }\n const assets: BundleAsset[] = [];\n walk(assetsDir, assetsDir, assets);\n if (assets.length === 0) return undefined;\n assets.sort((left, right) => left.path.localeCompare(right.path));\n const manifest: BundleManifest = {\n version: BUNDLE_MANIFEST_VERSION,\n revision: reserveRevision(stateDir, key.publicKey),\n builtAt: Date.now(),\n assets,\n };\n if (!isBundleManifest(manifest, profile)) throw new Error(`refusing to sign an invalid ${profile} bundle manifest`);\n const signature = createSign(SIGN_ALGORITHM)\n .update(canonicalManifest(manifest))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n return { manifest, signature, publicKey: key.publicKey };\n };\n\n const sign = (assetsDir: string, profile: BundleProfile = 'web'): SignedBundleManifest | undefined => {\n const cacheKey = cacheKeyOf(assetsDir, profile);\n if (cache.has(cacheKey)) return cache.get(cacheKey);\n const signed = signFresh(path.resolve(assetsDir), profile);\n cache.set(cacheKey, signed);\n return signed;\n };\n\n return {\n publicKey: () => key.publicKey,\n sign,\n refresh(assetsDir, profile = 'web') {\n cache.delete(cacheKeyOf(assetsDir, profile));\n return sign(assetsDir, profile);\n },\n invalidate(assetsDir) {\n if (assetsDir === undefined) {\n cache.clear();\n return;\n }\n for (const profile of PROFILES) cache.delete(cacheKeyOf(assetsDir, profile));\n },\n attest(tag, fields) {\n return createSign(SIGN_ALGORITHM)\n .update(attestationBytes(tag, fields))\n .sign({ key: privateKey, dsaEncoding: 'ieee-p1363' })\n .toString('base64url');\n },\n };\n}\n\n/** Re-derives the public key from a stored private key. */\nexport function publicKeyOf(privateKeyPem: string): string {\n return Buffer.from(createPublicKey(privateKeyPem).export({ type: 'spki', format: 'der' }) as Buffer).toString(\n 'base64url',\n );\n}\n"],"mappings":"6SAsBA,MAAME,EAAe,eAKfC,EAAiB,SACjBC,kBAAU,IAAI,IAAI,CAAC,MAAM,CAAC,EAC1BC,EAAqC,CAAC,MAAO,QAAQ,EACrDC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Aa,CAAC,CAAC,OAAO,CAAE,KAAM,OAAQ,OAAQ,KAAM,CAAC,CAAW,CAAC,CAAC,SACnG,WACF,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../types/sealedChannel.cjs");let t=require("node:crypto");const n=`prime256v1`,r=`aes-256-gcm`,i=Buffer.from(`po/sealed/v1`);function a(n,r){return Buffer.from((0,t.hkdfSync)(`sha256`,n,i,Buffer.from(e.infoFor(r)),32))}function o(e,t){let n=Buffer.alloc(12);return e.copy(n,0,0,4),n.writeBigUInt64BE(t,4),n}function s(n,i,s){let c=a(n,i),l=a(n,i===`c2s`?`s2c`:`c2s`),u=0n,d=-1n;return{seal(n){if(u>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let i=o(s,u),a=(0,t.createCipheriv)(r,c,i),l=Buffer.concat([a.update(n),a.final(),a.getAuthTag()]);return u+=1n,{ok:!0,envelope:{v:1,n:i.toString(`base64url`),c:l.toString(`base64url`)}}},open(n){let i=n;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(n))return{ok:!1,failure:`malformed`};let a=Buffer.from(n.n,`base64url`),o=Buffer.from(n.c,`base64url`);if(a.length!==12||o.length<16)return{ok:!1,failure:`malformed`};let s=a.readBigUInt64BE(4);if(s<=d)return{ok:!1,failure:`replay`};let c=(0,t.createDecipheriv)(r,l,a);c.setAuthTag(o.subarray(o.length-16));let u;try{u=Buffer.concat([c.update(o.subarray(0,o.length-16)),c.final()])}catch{return{ok:!1,failure:`auth`}}return d=s,{ok:!0,plaintext:new Uint8Array(u)}}}}function c(e){if(e.length>128||!/^[A-Za-z0-9_-]+$/.test(e))return;let r;try{r=Buffer.from(e,`base64url`)}catch{return}if(!(r.length!==65&&r.length!==33||(r.length===65?r[0]!==4:r[0]!==2&&r[0]!==3)||r.toString(`base64url`)!==e))try{
|
|
1
|
+
const e=require("../../types/sealedChannel.cjs");let t=require("node:crypto");const n=`prime256v1`,r=`aes-256-gcm`,i=Buffer.from(`po/sealed/v1`);function a(n,r){return Buffer.from((0,t.hkdfSync)(`sha256`,n,i,Buffer.from(e.infoFor(r)),32))}function o(e,t){let n=Buffer.alloc(12);return e.copy(n,0,0,4),n.writeBigUInt64BE(t,4),n}function s(n,i,s){let c=a(n,i),l=a(n,i===`c2s`?`s2c`:`c2s`),u=0n,d=-1n;return{seal(n){if(u>=BigInt(e.MAX_MESSAGES_PER_KEY))return{ok:!1,failure:`exhausted`};let i=o(s,u),a=(0,t.createCipheriv)(r,c,i),l=Buffer.concat([a.update(n),a.final(),a.getAuthTag()]);return u+=1n,{ok:!0,envelope:{v:1,n:i.toString(`base64url`),c:l.toString(`base64url`)}}},open(n){let i=n;if(typeof i?.n!=`string`||typeof i.c!=`string`)return{ok:!1,failure:`malformed`};if(i.v!==1)return{ok:!1,failure:`version`};if(!e.isSealedEnvelope(n))return{ok:!1,failure:`malformed`};let a=Buffer.from(n.n,`base64url`),o=Buffer.from(n.c,`base64url`);if(a.length!==12||o.length<16)return{ok:!1,failure:`malformed`};let s=a.readBigUInt64BE(4);if(s<=d)return{ok:!1,failure:`replay`};let c=(0,t.createDecipheriv)(r,l,a);c.setAuthTag(o.subarray(o.length-16));let u;try{u=Buffer.concat([c.update(o.subarray(0,o.length-16)),c.final()])}catch{return{ok:!1,failure:`auth`}}return d=s,{ok:!0,plaintext:new Uint8Array(u)}}}}function c(e){if(e.length>128||!/^[A-Za-z0-9_-]+$/.test(e))return;let r;try{r=Buffer.from(e,`base64url`)}catch{return}if(!(r.length!==65&&r.length!==33||(r.length===65?r[0]!==4:r[0]!==2&&r[0]!==3)||r.toString(`base64url`)!==e))try{let e=t.ECDH.convertKey(r,n,void 0,void 0,`uncompressed`);return Buffer.isBuffer(e)?e:void 0}catch{return}}function l(){let e=(0,t.createECDH)(n);e.generateKeys();let r=/* @__PURE__ */ new Set;return{publicKey:e.getPublicKey().toString(`base64url`),accept(n){let i=c(n);if(i===void 0||r.has(i.toString(`base64url`)))return;let a;try{a=e.computeSecret(i)}catch{return}return r.add(i.toString(`base64url`)),s(a,`s2c`,(0,t.randomBytes)(4))}}}function u(){let e=(0,t.createECDH)(n);e.generateKeys();let r=!1;return{publicKey:e.getPublicKey().toString(`base64url`),accept(n){if(r)return;let i=c(n);if(i===void 0)return;let a;try{a=e.computeSecret(i)}catch{return}return r=!0,s(a,`c2s`,(0,t.randomBytes)(4))}}}exports.createClientHandshake=u,exports.createHostHandshake=l;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["hkdfSync","infoFor","MAX_MESSAGES_PER_KEY","createCipheriv","isSealedEnvelope","createDecipheriv","ECDH","createECDH","randomBytes","require_sealedChannel","node_crypto","CURVE","CIPHER","HKDF_SALT","derive","secret","direction","nonceFor","nonce","prefix","counter","createChannel","sendKey","sendDirection","receiveKey","sendCounter","highestReceived","noncePrefix","cipher","body","plaintext","shape","envelope","decipher","ecdhPoint","value","encoded","createHostHandshake","exchange","acceptedPeers","peer","peerPublicKey","createClientHandshake","accepted","host","hostPublicKey"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\nimport {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\nconst CURVE = 'prime256v1';\nconst CIPHER = 'aes-256-gcm';\nconst KEY_BYTES = 32;\nconst TAG_BYTES = 16;\nconst HKDF_HASH = 'sha256';\n/** Fixed and public: HKDF's salt need not be secret, and a constant keeps both sides in step. */\nconst HKDF_SALT = Buffer.from('po/sealed/v1');\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n /** Seals one message. Counters advance only on success. */\n seal(plaintext: Uint8Array): SealResult;\n open(envelope: unknown): OpenResult;\n}\n\nexport interface HostHandshake {\n /** Base64url uncompressed P-256 point, printed in the QR. */\n publicKey: string;\n /** Completes the exchange against the peer's key and yields the channel. */\n accept(peerPublicKey: string): SealedChannel | undefined;\n}\n\nexport interface ClientHandshake {\n /** Base64url uncompressed P-256 point sent to the host. */\n publicKey: string;\n /** Completes the exchange against the host's fresh key and yields the channel. */\n accept(hostPublicKey: string): SealedChannel | undefined;\n}\n\nfunction derive(secret: Buffer, direction: SealedDirection): Buffer {\n return Buffer.from(hkdfSync(HKDF_HASH, secret, HKDF_SALT, Buffer.from(infoFor(direction)), KEY_BYTES));\n}\n\n/**\n * Builds the nonce for one message.\n *\n * A random per-channel prefix plus a monotonic counter, rather than a random\n * nonce per message: 96 bits is small enough that random nonces collide at a\n * rate worth caring about, and a repeated nonce under one AES-GCM key is\n * catastrophic rather than merely weak.\n */\nfunction nonceFor(prefix: Buffer, counter: bigint): Buffer {\n const nonce = Buffer.alloc(NONCE_BYTES);\n prefix.copy(nonce, 0, 0, NONCE_PREFIX_BYTES);\n nonce.writeBigUInt64BE(counter, NONCE_PREFIX_BYTES);\n return nonce;\n}\n\n/**\n * One direction's sealing state.\n *\n * Send and receive are separate keys and separate counters, so a message the\n * server sent can never be replayed back at it as though the client had sent it.\n */\nfunction createChannel(secret: Buffer, sendDirection: SealedDirection, noncePrefix: Buffer): SealedChannel {\n const sendKey = derive(secret, sendDirection);\n const receiveKey = derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n let sendCounter = 0n;\n /** Strictly increasing: anything at or below what has been seen is a replay. */\n let highestReceived = -1n;\n\n return {\n seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const cipher = createCipheriv(CIPHER, sendKey, nonce);\n const body = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: nonce.toString('base64url'), c: body.toString('base64url') },\n };\n },\n\n open(envelope) {\n // Shape before version: something with no `v` at all is malformed, and\n // calling it a version mismatch would send a reader hunting for a\n // protocol skew that is not there.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = Buffer.from(envelope.n, 'base64url');\n const body = Buffer.from(envelope.c, 'base64url');\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = nonce.readBigUInt64BE(NONCE_PREFIX_BYTES);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n const decipher = createDecipheriv(CIPHER, receiveKey, nonce);\n decipher.setAuthTag(body.subarray(body.length - TAG_BYTES));\n let plaintext: Buffer;\n try {\n plaintext = Buffer.concat([decipher.update(body.subarray(0, body.length - TAG_BYTES)), decipher.final()]);\n } catch {\n // A failed tag means the message was altered, which is the whole point\n // of having one. Never fall back to the ciphertext.\n return { ok: false, failure: 'auth' };\n }\n // Advanced only after the tag verified, so a forged high counter cannot\n // lock out the messages that follow it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\nfunction ecdhPoint(value: string): Buffer | undefined {\n if (value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;\n let encoded: Buffer;\n try {\n encoded = Buffer.from(value, 'base64url');\n } catch {\n return undefined;\n }\n if (\n (encoded.length !== 65 && encoded.length !== 33) ||\n (encoded.length === 65 ? encoded[0] !== 4 : encoded[0] !== 2 && encoded[0] !== 3) ||\n encoded.toString('base64url') !== value\n )\n return undefined;\n try {\n return ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n } catch {\n return undefined;\n }\n}\n\n/**\n * The host half of the handshake.\n *\n * The ephemeral key pair is generated per tunnel and its public half goes in the\n * QR, which is the out-of-band channel that makes this authenticated. A relay\n * that swaps the client's key gets a channel with itself and nothing from the\n * host, because the host only ever derives against the key the client presents\n * and the client only ever derives against the key it read off the screen.\n */\nexport function createHostHandshake(): HostHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n const acceptedPeers = new Set<string>();\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(peerPublicKey) {\n const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\n return undefined;\n }\n acceptedPeers.add(peer.toString('base64url'));\n // The prefix is the host's to choose and travels in every nonce, so the\n // client reads it off the wire rather than needing it up front.\n return createChannel(secret, 's2c', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"8EAcA,MAAMW,EAAQ,aACRC,EAAS,cAKTC,EAAY,OAAO,KAAK,cAAc,EAyB5C,SAASC,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,MAAA,EAAKd,EAAAA,S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S,aAAa,EACtB,IAAMC,kBAAgB,IAAI,IAC1B,MAAO,CACL,UAAWD,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,IAAME,EAAON,EAAUO,CAAa,EACpC,GAAID,IAAS,IAAA,IAAaD,EAAc,IAAIC,EAAK,SAAS,WAAW,CAAC,EAAG,OACzE,IAAIzB,EACJ,GAAI,CACF,EAASuB,EAAS,cAAcE,CAAI,CACtC,MAAQ,CACN,MACF,CAIA,OAHAD,EAAc,IAAIC,EAAK,SAAS,WAAW,CAAC,EAGrCnB,EAAcN,EAAQ,OAAA,EAAOP,EAAAA,YAAAA,CAAAA,CAA8B,CAAC,CACrE,CACF,CACF,CAGA,SAAgBkC,GAAyC,CACvD,IAAMJ,GAAA,EAAW/B,EAAAA,WAAAA,CAAWI,CAAK,EACjC2B,EAAS,aAAa,EACtB,IAAIK,EAAW,GACf,MAAO,CACL,UAAWL,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,GAAIK,EAAU,OACd,IAAMC,EAAOV,EAAUW,CAAa,EACpC,GAAID,IAAS,IAAA,GAAW,OACxB,IAAI7B,EACJ,GAAI,CACF,EAASuB,EAAS,cAAcM,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJvB,EAAcN,EAAQ,OAAA,EAAOP,EAAAA,YAAAA,CAAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["hkdfSync","infoFor","MAX_MESSAGES_PER_KEY","createCipheriv","isSealedEnvelope","createDecipheriv","ECDH","createECDH","randomBytes","require_sealedChannel","node_crypto","CURVE","CIPHER","HKDF_SALT","derive","secret","direction","nonceFor","nonce","prefix","counter","createChannel","sendKey","sendDirection","receiveKey","sendCounter","highestReceived","noncePrefix","cipher","body","plaintext","shape","envelope","decipher","ecdhPoint","value","encoded","point","createHostHandshake","exchange","acceptedPeers","peer","peerPublicKey","createClientHandshake","accepted","host","hostPublicKey"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\nimport {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\nconst CURVE = 'prime256v1';\nconst CIPHER = 'aes-256-gcm';\nconst KEY_BYTES = 32;\nconst TAG_BYTES = 16;\nconst HKDF_HASH = 'sha256';\n/** Fixed and public: HKDF's salt need not be secret, and a constant keeps both sides in step. */\nconst HKDF_SALT = Buffer.from('po/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 const point = ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n return Buffer.isBuffer(point) ? point : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The host half of the handshake.\n *\n * The ephemeral key pair is generated per tunnel and its public half goes in the\n * QR, which is the out-of-band channel that makes this authenticated. A relay\n * that swaps the client's key gets a channel with itself and nothing from the\n * host, because the host only ever derives against the key the client presents\n * and the client only ever derives against the key it read off the screen.\n */\nexport function createHostHandshake(): HostHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n const acceptedPeers = new Set<string>();\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(peerPublicKey) {\n const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\n return undefined;\n }\n acceptedPeers.add(peer.toString('base64url'));\n // The prefix is the host's to choose and travels in every nonce, so the\n // client reads it off the wire rather than needing it up front.\n return createChannel(secret, 's2c', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"8EAcA,MAAMW,EAAQ,aACRC,EAAS,cAKTC,EAAY,OAAO,KAAK,cAAc,EAyB5C,SAASC,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,MAAA,EAAKd,EAAAA,SAAAA,CAAS,SAAWe,EAAQF,EAAW,OAAO,KAAKZ,EAAAA,QAAQe,CAAS,CAAC,EAAG,EAAS,CAAC,CACvG,CAUA,SAASC,EAAS,EAAgB,EAAyB,CACzD,IAAMC,EAAQ,OAAO,MAAA,EAAiB,EAGtC,OAFAC,EAAO,KAAKD,EAAO,EAAG,EAAA,CAAqB,EAC3CA,EAAM,iBAAiBE,EAAA,CAA2B,EAC3CF,CACT,CAQA,SAASG,EAAc,EAAgB,EAAgC,EAAoC,CACzG,IAAMC,EAAUR,EAAOC,EAAQQ,CAAa,EACtCC,EAAaV,EAAOC,EAAQQ,IAAkB,MAAQ,MAAQ,KAAK,EACrEE,EAAc,GAEdC,EAAkB,CAAC,GAEvB,MAAO,CACL,KAAK,EAAW,CACd,GAAID,GAAe,OAAOvB,EAAAA,oBAAoB,EAAG,MAAO,CAAE,GAAI,GAAO,QAAS,WAAY,EAC1F,IAAMgB,EAAQD,EAASU,EAAaF,CAAW,EACzCG,GAAA,EAASzB,EAAAA,eAAAA,CAAeS,EAAQU,EAASJ,CAAK,EAC9CW,EAAO,OAAO,OAAO,CAACD,EA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ACpB,GAAIK,EAAU,OACd,IAAMC,EAAOX,EAAUY,CAAa,EACpC,GAAID,IAAS,IAAA,GAAW,OACxB,IAAI9B,EACJ,GAAI,CACF,EAASwB,EAAS,cAAcM,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJxB,EAAcN,EAAQ,OAAA,EAAOP,EAAAA,YAAAA,CAAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"mappings":";;YAsBY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;YAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;iBAEpE;;EAEf,KAAK,WAAW,aAAa;EAC7B,KAAK,oBAAoB;;iBAGV;;EAEf;;EAEA,OAAO,wBAAwB;;iBAGhB;;EAEf;;EAEA,OAAO,wBAAwB;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"mappings":";;YAsBY;EAAe;EAAU,UAAU;;EAAqB;EAAW,SAAS;;YAC5E;EAAe;EAAU,WAAW;;EAAiB;EAAW,SAAS;;iBAEpE;;EAEf,KAAK,WAAW,aAAa;EAC7B,KAAK,oBAAoB;;iBAGV;;EAEf;;EAEA,OAAO,wBAAwB;;iBAGhB;;EAEf;;EAEA,OAAO,wBAAwB;;;;;;;;;;;wBA8GjB,uBAAuB;;wBAwBvB,yBAAyB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{MAX_MESSAGES_PER_KEY as e,infoFor as t,isSealedEnvelope as n}from"../../types/sealedChannel.mjs";import{ECDH as r,createCipheriv as i,createDecipheriv as a,createECDH as o,hkdfSync as s,randomBytes as c}from"node:crypto";const l=`prime256v1`,u=`aes-256-gcm`,d=Buffer.from(`po/sealed/v1`);function f(e,n){return Buffer.from(s(`sha256`,e,d,Buffer.from(t(n)),32))}function p(e,t){let n=Buffer.alloc(12);return e.copy(n,0,0,4),n.writeBigUInt64BE(t,4),n}function m(t,r,o){let s=f(t,r),c=f(t,r===`c2s`?`s2c`:`c2s`),l=0n,d=-1n;return{seal(t){if(l>=BigInt(e))return{ok:!1,failure:`exhausted`};let n=p(o,l),r=i(u,s,n),a=Buffer.concat([r.update(t),r.final(),r.getAuthTag()]);return l+=1n,{ok:!0,envelope:{v:1,n:n.toString(`base64url`),c:a.toString(`base64url`)}}},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 r=Buffer.from(e.n,`base64url`),i=Buffer.from(e.c,`base64url`);if(r.length!==12||i.length<16)return{ok:!1,failure:`malformed`};let o=r.readBigUInt64BE(4);if(o<=d)return{ok:!1,failure:`replay`};let s=a(u,c,r);s.setAuthTag(i.subarray(i.length-16));let l;try{l=Buffer.concat([s.update(i.subarray(0,i.length-16)),s.final()])}catch{return{ok:!1,failure:`auth`}}return d=o,{ok:!0,plaintext:new Uint8Array(l)}}}}function h(e){if(e.length>128||!/^[A-Za-z0-9_-]+$/.test(e))return;let t;try{t=Buffer.from(e,`base64url`)}catch{return}if(!(t.length!==65&&t.length!==33||(t.length===65?t[0]!==4:t[0]!==2&&t[0]!==3)||t.toString(`base64url`)!==e))try{
|
|
1
|
+
import{MAX_MESSAGES_PER_KEY as e,infoFor as t,isSealedEnvelope as n}from"../../types/sealedChannel.mjs";import{ECDH as r,createCipheriv as i,createDecipheriv as a,createECDH as o,hkdfSync as s,randomBytes as c}from"node:crypto";const l=`prime256v1`,u=`aes-256-gcm`,d=Buffer.from(`po/sealed/v1`);function f(e,n){return Buffer.from(s(`sha256`,e,d,Buffer.from(t(n)),32))}function p(e,t){let n=Buffer.alloc(12);return e.copy(n,0,0,4),n.writeBigUInt64BE(t,4),n}function m(t,r,o){let s=f(t,r),c=f(t,r===`c2s`?`s2c`:`c2s`),l=0n,d=-1n;return{seal(t){if(l>=BigInt(e))return{ok:!1,failure:`exhausted`};let n=p(o,l),r=i(u,s,n),a=Buffer.concat([r.update(t),r.final(),r.getAuthTag()]);return l+=1n,{ok:!0,envelope:{v:1,n:n.toString(`base64url`),c:a.toString(`base64url`)}}},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 r=Buffer.from(e.n,`base64url`),i=Buffer.from(e.c,`base64url`);if(r.length!==12||i.length<16)return{ok:!1,failure:`malformed`};let o=r.readBigUInt64BE(4);if(o<=d)return{ok:!1,failure:`replay`};let s=a(u,c,r);s.setAuthTag(i.subarray(i.length-16));let l;try{l=Buffer.concat([s.update(i.subarray(0,i.length-16)),s.final()])}catch{return{ok:!1,failure:`auth`}}return d=o,{ok:!0,plaintext:new Uint8Array(l)}}}}function h(e){if(e.length>128||!/^[A-Za-z0-9_-]+$/.test(e))return;let t;try{t=Buffer.from(e,`base64url`)}catch{return}if(!(t.length!==65&&t.length!==33||(t.length===65?t[0]!==4:t[0]!==2&&t[0]!==3)||t.toString(`base64url`)!==e))try{let e=r.convertKey(t,l,void 0,void 0,`uncompressed`);return Buffer.isBuffer(e)?e:void 0}catch{return}}function g(){let e=o(l);e.generateKeys();let t=/* @__PURE__ */ new Set;return{publicKey:e.getPublicKey().toString(`base64url`),accept(n){let r=h(n);if(r===void 0||t.has(r.toString(`base64url`)))return;let i;try{i=e.computeSecret(r)}catch{return}return t.add(r.toString(`base64url`)),m(i,`s2c`,c(4))}}}function _(){let e=o(l);e.generateKeys();let t=!1;return{publicKey:e.getPublicKey().toString(`base64url`),accept(n){if(t)return;let r=h(n);if(r===void 0)return;let i;try{i=e.computeSecret(r)}catch{return}return t=!0,m(i,`c2s`,c(4))}}}export{_ as createClientHandshake,g as createHostHandshake};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["CURVE","CIPHER","HKDF_SALT","derive","hkdfSync","secret","infoFor","direction","nonceFor","nonce","prefix","counter","createChannel","sendKey","sendDirection","receiveKey","sendCounter","highestReceived","MAX_MESSAGES_PER_KEY","noncePrefix","cipher","createCipheriv","body","plaintext","shape","envelope","isSealedEnvelope","decipher","createDecipheriv","ecdhPoint","value","encoded","ECDH","createHostHandshake","exchange","createECDH","acceptedPeers","peer","peerPublicKey","randomBytes","createClientHandshake","accepted","host","hostPublicKey"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\nimport {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\nconst CURVE = 'prime256v1';\nconst CIPHER = 'aes-256-gcm';\nconst KEY_BYTES = 32;\nconst TAG_BYTES = 16;\nconst HKDF_HASH = 'sha256';\n/** Fixed and public: HKDF's salt need not be secret, and a constant keeps both sides in step. */\nconst HKDF_SALT = Buffer.from('po/sealed/v1');\n\nexport type SealResult = { ok: true; envelope: SealedEnvelope } | { ok: false; failure: SealedFailure };\nexport type OpenResult = { ok: true; plaintext: Uint8Array } | { ok: false; failure: SealedFailure };\n\nexport interface SealedChannel {\n /** Seals one message. Counters advance only on success. */\n seal(plaintext: Uint8Array): SealResult;\n open(envelope: unknown): OpenResult;\n}\n\nexport interface HostHandshake {\n /** Base64url uncompressed P-256 point, printed in the QR. */\n publicKey: string;\n /** Completes the exchange against the peer's key and yields the channel. */\n accept(peerPublicKey: string): SealedChannel | undefined;\n}\n\nexport interface ClientHandshake {\n /** Base64url uncompressed P-256 point sent to the host. */\n publicKey: string;\n /** Completes the exchange against the host's fresh key and yields the channel. */\n accept(hostPublicKey: string): SealedChannel | undefined;\n}\n\nfunction derive(secret: Buffer, direction: SealedDirection): Buffer {\n return Buffer.from(hkdfSync(HKDF_HASH, secret, HKDF_SALT, Buffer.from(infoFor(direction)), KEY_BYTES));\n}\n\n/**\n * Builds the nonce for one message.\n *\n * A random per-channel prefix plus a monotonic counter, rather than a random\n * nonce per message: 96 bits is small enough that random nonces collide at a\n * rate worth caring about, and a repeated nonce under one AES-GCM key is\n * catastrophic rather than merely weak.\n */\nfunction nonceFor(prefix: Buffer, counter: bigint): Buffer {\n const nonce = Buffer.alloc(NONCE_BYTES);\n prefix.copy(nonce, 0, 0, NONCE_PREFIX_BYTES);\n nonce.writeBigUInt64BE(counter, NONCE_PREFIX_BYTES);\n return nonce;\n}\n\n/**\n * One direction's sealing state.\n *\n * Send and receive are separate keys and separate counters, so a message the\n * server sent can never be replayed back at it as though the client had sent it.\n */\nfunction createChannel(secret: Buffer, sendDirection: SealedDirection, noncePrefix: Buffer): SealedChannel {\n const sendKey = derive(secret, sendDirection);\n const receiveKey = derive(secret, sendDirection === 'c2s' ? 's2c' : 'c2s');\n let sendCounter = 0n;\n /** Strictly increasing: anything at or below what has been seen is a replay. */\n let highestReceived = -1n;\n\n return {\n seal(plaintext) {\n if (sendCounter >= BigInt(MAX_MESSAGES_PER_KEY)) return { ok: false, failure: 'exhausted' };\n const nonce = nonceFor(noncePrefix, sendCounter);\n const cipher = createCipheriv(CIPHER, sendKey, nonce);\n const body = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]);\n sendCounter += 1n;\n return {\n ok: true,\n envelope: { v: SEALED_VERSION, n: nonce.toString('base64url'), c: body.toString('base64url') },\n };\n },\n\n open(envelope) {\n // Shape before version: something with no `v` at all is malformed, and\n // calling it a version mismatch would send a reader hunting for a\n // protocol skew that is not there.\n const shape = envelope as { v?: unknown; n?: unknown; c?: unknown } | null | undefined;\n if (typeof shape?.n !== 'string' || typeof shape.c !== 'string') return { ok: false, failure: 'malformed' };\n if (shape.v !== SEALED_VERSION) return { ok: false, failure: 'version' };\n if (!isSealedEnvelope(envelope)) return { ok: false, failure: 'malformed' };\n const nonce = Buffer.from(envelope.n, 'base64url');\n const body = Buffer.from(envelope.c, 'base64url');\n if (nonce.length !== NONCE_BYTES || body.length < TAG_BYTES) return { ok: false, failure: 'malformed' };\n const counter = nonce.readBigUInt64BE(NONCE_PREFIX_BYTES);\n if (counter <= highestReceived) return { ok: false, failure: 'replay' };\n const decipher = createDecipheriv(CIPHER, receiveKey, nonce);\n decipher.setAuthTag(body.subarray(body.length - TAG_BYTES));\n let plaintext: Buffer;\n try {\n plaintext = Buffer.concat([decipher.update(body.subarray(0, body.length - TAG_BYTES)), decipher.final()]);\n } catch {\n // A failed tag means the message was altered, which is the whole point\n // of having one. Never fall back to the ciphertext.\n return { ok: false, failure: 'auth' };\n }\n // Advanced only after the tag verified, so a forged high counter cannot\n // lock out the messages that follow it.\n highestReceived = counter;\n return { ok: true, plaintext: new Uint8Array(plaintext) };\n },\n };\n}\n\nfunction ecdhPoint(value: string): Buffer | undefined {\n if (value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;\n let encoded: Buffer;\n try {\n encoded = Buffer.from(value, 'base64url');\n } catch {\n return undefined;\n }\n if (\n (encoded.length !== 65 && encoded.length !== 33) ||\n (encoded.length === 65 ? encoded[0] !== 4 : encoded[0] !== 2 && encoded[0] !== 3) ||\n encoded.toString('base64url') !== value\n )\n return undefined;\n try {\n return ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n } catch {\n return undefined;\n }\n}\n\n/**\n * The host half of the handshake.\n *\n * The ephemeral key pair is generated per tunnel and its public half goes in the\n * QR, which is the out-of-band channel that makes this authenticated. A relay\n * that swaps the client's key gets a channel with itself and nothing from the\n * host, because the host only ever derives against the key the client presents\n * and the client only ever derives against the key it read off the screen.\n */\nexport function createHostHandshake(): HostHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n const acceptedPeers = new Set<string>();\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(peerPublicKey) {\n const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\n return undefined;\n }\n acceptedPeers.add(peer.toString('base64url'));\n // The prefix is the host's to choose and travels in every nonce, so the\n // client reads it off the wire rather than needing it up front.\n return createChannel(secret, 's2c', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"oOAcA,MAAMA,EAAQ,aACRC,EAAS,cAKTC,EAAY,OAAO,KAAK,cAAc,EAyB5C,SAASC,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,KAAKC,EAAS,SAAWC,EAAQH,EAAW,OAAO,KAAKI,EAAQC,CAAS,CAAC,EAAG,EAAS,CAAC,CACvG,CAUA,SAASC,EAAS,EAAgB,EAAyB,CACzD,IAAMC,EAAQ,OAAO,MAAA,EAAiB,EAGtC,OAFAC,EAAO,KAAKD,EAAO,EAAG,EAAA,CAAqB,EAC3CA,EAAM,iBAAiBE,EAAA,CAA2B,EAC3CF,CACT,CAQA,SAASG,EAAc,EAAgB,EAAgC,EAAoC,CACzG,IAAMC,EAAUV,EAAOE,EAAQS,CAAa,EACtCC,EAAaZ,EAAOE,EAAQS,IAAkB,MAAQ,MAAQ,KAAK,EACrEE,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AAIO,EAAW,GACf,MAAO,CACL,UAAWP,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,GAAIO,EAAU,OACd,IAAMC,EAAOb,EAAUc,CAAa,EACpC,GAAID,IAAS,IAAA,GAAW,OACxB,IAAIrC,EACJ,GAAI,CACF,EAAS6B,EAAS,cAAcQ,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJ9B,EAAcP,EAAQ,MAAOkC,EAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["CURVE","CIPHER","HKDF_SALT","derive","hkdfSync","secret","infoFor","direction","nonceFor","nonce","prefix","counter","createChannel","sendKey","sendDirection","receiveKey","sendCounter","highestReceived","MAX_MESSAGES_PER_KEY","noncePrefix","cipher","createCipheriv","body","plaintext","shape","envelope","isSealedEnvelope","decipher","createDecipheriv","ecdhPoint","value","encoded","point","ECDH","createHostHandshake","exchange","createECDH","acceptedPeers","peer","peerPublicKey","randomBytes","createClientHandshake","accepted","host","hostPublicKey"],"sources":["../../../src/services/nodeSealedChannel/index.ts"],"sourcesContent":["import { ECDH, createCipheriv, createDecipheriv, createECDH, hkdfSync, randomBytes } from 'node:crypto';\n\nimport {\n MAX_MESSAGES_PER_KEY,\n NONCE_BYTES,\n NONCE_PREFIX_BYTES,\n SEALED_VERSION,\n type SealedDirection,\n type SealedEnvelope,\n type SealedFailure,\n infoFor,\n isSealedEnvelope,\n} from '../../types/sealedChannel';\n\nconst CURVE = 'prime256v1';\nconst CIPHER = 'aes-256-gcm';\nconst KEY_BYTES = 32;\nconst TAG_BYTES = 16;\nconst HKDF_HASH = 'sha256';\n/** Fixed and public: HKDF's salt need not be secret, and a constant keeps both sides in step. */\nconst HKDF_SALT = Buffer.from('po/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 const point = ECDH.convertKey(encoded, CURVE, undefined, undefined, 'uncompressed');\n return Buffer.isBuffer(point) ? point : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The host half of the handshake.\n *\n * The ephemeral key pair is generated per tunnel and its public half goes in the\n * QR, which is the out-of-band channel that makes this authenticated. A relay\n * that swaps the client's key gets a channel with itself and nothing from the\n * host, because the host only ever derives against the key the client presents\n * and the client only ever derives against the key it read off the screen.\n */\nexport function createHostHandshake(): HostHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n const acceptedPeers = new Set<string>();\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(peerPublicKey) {\n const peer = ecdhPoint(peerPublicKey);\n if (peer === undefined || acceptedPeers.has(peer.toString('base64url'))) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(peer);\n } catch {\n return undefined;\n }\n acceptedPeers.add(peer.toString('base64url'));\n // The prefix is the host's to choose and travels in every nonce, so the\n // client reads it off the wire rather than needing it up front.\n return createChannel(secret, 's2c', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n\n/** Creates the client half for a single fresh peer handshake. */\nexport function createClientHandshake(): ClientHandshake {\n const exchange = createECDH(CURVE);\n exchange.generateKeys();\n let accepted = false;\n return {\n publicKey: exchange.getPublicKey().toString('base64url'),\n accept(hostPublicKey) {\n if (accepted) return undefined;\n const host = ecdhPoint(hostPublicKey);\n if (host === undefined) return undefined;\n let secret: Buffer;\n try {\n secret = exchange.computeSecret(host);\n } catch {\n return undefined;\n }\n accepted = true;\n return createChannel(secret, 'c2s', randomBytes(NONCE_PREFIX_BYTES));\n },\n };\n}\n"],"mappings":"oOAcA,MAAMA,EAAQ,aACRC,EAAS,cAKTC,EAAY,OAAO,KAAK,cAAc,EAyB5C,SAASC,EAAO,EAAgB,EAAoC,CAClE,OAAO,OAAO,KAAKC,EAAS,SAAWC,EAAQH,EAAW,OAAO,KAAKI,EAAQC,CAAS,CAAC,EAAG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AAe,CACpB,IAAMG,EAAOT,EAAUU,CAAa,EACpC,GAAID,IAAS,IAAA,IAAaD,EAAc,IAAIC,EAAK,SAAS,WAAW,CAAC,EAAG,OACzE,IAAIjC,EACJ,GAAI,CACF,EAAS8B,EAAS,cAAcG,CAAI,CACtC,MAAQ,CACN,MACF,CAIA,OAHAD,EAAc,IAAIC,EAAK,SAAS,WAAW,CAAC,EAGrC1B,EAAcP,EAAQ,MAAOmC,EAAA,CAA8B,CAAC,CACrE,CACF,CACF,CAGA,SAAgBC,GAAyC,CACvD,IAAMN,EAAWC,EAAWpC,CAAK,EACjCmC,EAAS,aAAa,EACtB,IAAIO,EAAW,GACf,MAAO,CACL,UAAWP,EAAS,aAAa,CAAC,CAAC,SAAS,WAAW,EACvD,OAAO,EAAe,CACpB,GAAIO,EAAU,OACd,IAAMC,EAAOd,EAAUe,CAAa,EACpC,GAAID,IAAS,IAAA,GAAW,OACxB,IAAItC,EACJ,GAAI,CACF,EAAS8B,EAAS,cAAcQ,CAAI,CACtC,MAAQ,CACN,MACF,CAEA,MADA,GAAW,GACJ/B,EAAcP,EAAQ,MAAOmC,EAAA,CAA8B,CAAC,CACrE,CACF,CACF"}
|
|
@@ -1,2 +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)
|
|
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.`;else 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
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["createSerialQueue","describeSealedFailure","connectSealedChannel","require_sealedChannel","require_index","require_index$1","encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","inbound","exchange","relayPath","note","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"sIAkCMM,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS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M,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAAClB,EAAqB0B,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOpB,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAaiC,EAAQ,IAAI,EACtC,OAAO,IAAI,SAASA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAO7B,EAAM,CAC5G,OAAQ6B,EAAQ,OAChB,QAASA,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAaC,EAAkBvB,EAAsB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["createSerialQueue","describeSealedFailure","connectSealedChannel","require_sealedChannel","require_index","require_index$1","encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","inbound","exchange","relayPath","note","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"sIAkCMM,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS,SAAU,OAAOV,EAAQ,OAAOU,CAAI,EACxD,GAAIA,aAAgB,gBAAiB,OAAOV,EAAQ,OAAOU,EAAK,SAAS,CAAC,EAC1E,GAAIA,aAAgB,KAAM,OAAO,IAAI,WAAW,MAAMA,EAAK,YAAY,CAAC,EACxE,GAAIA,aAAgB,YAAa,OAAO,IAAI,WAAWA,CAAI,EAC3D,GAAI,YAAY,OAAOA,CAAI,EAAG,OAAO,IAAI,WAAWA,EAAK,OAAQA,EAAK,WAAYA,EAAK,UAAU,EACjG,MAAU,MAAM,oEAAoE,CAL5B,CAM1D,CAEA,SAASC,EAAc,EAAuB,CAC5C,GAAI,CAACC,EAAM,WAAW,GAAG,EAAG,MAAU,MAAM,qDAAqD,EACjG,OAAOA,CACT,CAEA,SAASC,EAAqB,EAA6C,CACzE,GAAI,OAAON,GAAU,WAAYA,EAAgB,MAAO,GACxD,IAAMO,EAAYP,EAClB,OACEO,EAAU,IAAM,GAChB,OAAOA,EAAU,QAAW,UAC5B,MAAM,QAAQA,EAAU,OAAO,GAC/BA,EAAU,QAAQ,MACf,GAAW,MAAM,QAAQC,CAAM,GAAKA,EAAO,SAAW,GAAKA,EAAO,MAAO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EACtE,GAAIV,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOR,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMmB,EAAgB,MAAM,MAAMH,EAAS,CACzC,OAAQ,OACR,YAAa,cACb,QAAS,CAAE,eAAgB,kBAAkB,EAC7C,KAAMR,CACR,CAAC,EACKI,EAAS,MAAMH,EAAU,MAAMU,EAAc,KAAK,CAAC,EACzD,GAAIP,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOZ,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAIoB,EACJ,GAAI,CACF,EAAU,KAAK,MAAMtC,EAAQ,OAAO8B,CAAM,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAAClB,EAAqB0B,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOpB,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAaiC,EAAQ,IAAI,EACtC,OAAO,IAAI,SAASA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAO7B,EAAM,CAC5G,OAAQ6B,EAAQ,OAChB,QAASA,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAaC,EAAkBvB,EAAsB"}
|
|
@@ -1,2 +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)
|
|
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.`;else 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
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","createSerialQueue","inbound","exchange","relayPath","note","describeSealedFailure","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","connectSealedChannel","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"4MAmBA,MAeMA,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EAC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,OAAQ,GAAI,CAAC,EAEzE,IAAIuB,EACJ,GAAI,CACF,EAAU,KAAK,MAAMzC,EAAQ,OAAOgC,CAAM,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAACpB,EAAqB6B,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOvB,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAaoC,EAAQ,IAAI,EACtC,OAAO,IAAI,SAASA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAOhC,EAAM,CAC5G,OAAQgC,EAAQ,OAChB,QAASA,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAaC,EAAkB1B,EAAsB"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["encoder","decoder","encodeBase64","binary","byte","bytes","decodeBase64","value","character","bodyBytes","body","requestTarget","input","isSealedHttpResponse","candidate","header","part","createSealedTransport","channel","failure","outbound","createSerialQueue","inbound","exchange","relayPath","note","describeSealedFailure","reason","sealBytes","sealed","openBytes","envelope","text","opened","connected","connectSealedChannel","hostPublicKey","path","gateway","init","request","relayResponse","decoded","sealedTransport"],"sources":["../../../src/services/sealedTransport/index.ts"],"sourcesContent":["import { describeSealedFailure, type SealedFailure } from '../../types/sealedChannel';\nimport { connectSealedChannel, type SealedChannel } from '../browserSealedChannel';\nimport { createSerialQueue } from '../serialQueue';\n\n/**\n * The one object the cockpit and every plugin use to talk over a sealed tunnel.\n *\n * Two things make this worth having rather than each caller reaching for the\n * channel directly. First, ordering: sealing advances a nonce counter and\n * opening enforces that it strictly increases, so both directions are pushed\n * through a serial queue and overlapping calls can never reorder into a\n * self-inflicted replay. Second, reach: a plugin that calls `fetch` itself\n * sends plaintext to whoever is relaying the tunnel, and the host cannot stop\n * it. Giving every caller one obvious helper is the only enforcement available.\n *\n * When no channel is established every method is a pass-through, so the same\n * code runs unchanged on the loopback listener where there is nothing to seal.\n */\n\nconst JSON_CONTENT_TYPE = 'application/json';\n\nexport interface SealedTransport {\n /** False on loopback and before the handshake completes, where everything passes through. */\n active(): boolean;\n sealText(text: string): Promise<string>;\n /** Undefined when the message could not be opened; `lastFailure` says why. */\n openText(text: string): Promise<string | undefined>;\n sealBinary(bytes: Uint8Array): Promise<Uint8Array>;\n openBinary(bytes: Uint8Array): Promise<Uint8Array | undefined>;\n /** Drop-in for `fetch`, relaying the complete request through the sealed channel when configured. */\n fetch(input: string, init?: RequestInit): Promise<Response>;\n lastFailure(): string | undefined;\n}\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface SealedHttpRequest {\n v: 1;\n method: string;\n target: string;\n headers: Array<[string, string]>;\n body?: string;\n}\n\ninterface SealedHttpResponse {\n v: 1;\n status: number;\n headers: Array<[string, string]>;\n body: string;\n}\n\nfunction encodeBase64(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n const binary = atob(value);\n return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nasync function bodyBytes(body: RequestInit['body']): Promise<Uint8Array | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return encoder.encode(body);\n if (body instanceof URLSearchParams) return encoder.encode(body.toString());\n if (body instanceof Blob) return new Uint8Array(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n throw new Error('The sealed HTTP transport does not support this request body type.');\n}\n\nfunction requestTarget(input: string): string {\n if (!input.startsWith('/')) throw new Error('A sealed HTTP request must use a root-relative URL.');\n return input;\n}\n\nfunction isSealedHttpResponse(value: unknown): value is SealedHttpResponse {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as Partial<SealedHttpResponse>;\n return (\n candidate.v === 1 &&\n typeof candidate.status === 'number' &&\n Array.isArray(candidate.headers) &&\n candidate.headers.every(\n (header) => Array.isArray(header) && header.length === 2 && header.every((part) => typeof part === 'string'),\n ) &&\n typeof candidate.body === 'string'\n );\n}\nexport function createSealedTransport(): SealedTransport & {\n /** Completes the handshake against the host key from the QR. */\n connect: (hostPublicKey: string) => Promise<string | undefined>;\n /** Drops the channel, so everything falls back to pass-through. */\n reset: () => void;\n /** Selects the same-origin endpoint that carries sealed HTTP exchanges. */\n relayRequestsThrough: (path: string) => void;\n} {\n let channel: SealedChannel | undefined;\n let failure: string | undefined;\n const outbound = createSerialQueue();\n const inbound = createSerialQueue();\n const exchange = createSerialQueue();\n let relayPath: string | undefined;\n const note = (reason: SealedFailure): undefined => {\n // A decryption failure otherwise shows up as a blank page with no cause, so\n // every one of them names itself.\n failure = describeSealedFailure(reason);\n return undefined;\n };\n\n const sealBytes = async (bytes: Uint8Array): Promise<string | undefined> => {\n if (channel === undefined) return undefined;\n const sealed = await channel.seal(bytes);\n if (!sealed.ok) return note(sealed.failure);\n return JSON.stringify(sealed.envelope);\n };\n\n const openBytes = async (text: string): Promise<Uint8Array | undefined> => {\n if (channel === undefined) return undefined;\n let envelope: unknown;\n try {\n envelope = JSON.parse(text);\n } catch {\n return note('malformed');\n }\n const opened = await channel.open(envelope);\n if (!opened.ok) return note(opened.failure);\n return opened.plaintext;\n };\n\n return {\n active: () => channel !== undefined,\n lastFailure: () => failure,\n\n async connect(hostPublicKey) {\n const connected = await connectSealedChannel(hostPublicKey);\n if (connected === undefined) {\n failure = 'This browser could not establish a sealed channel.';\n return undefined;\n }\n channel = connected.channel;\n failure = undefined;\n return connected.clientPublicKey;\n },\n\n relayRequestsThrough(path) {\n relayPath = path;\n },\n\n reset() {\n channel = undefined;\n failure = undefined;\n },\n\n async sealText(text) {\n if (channel === undefined) return text;\n return await outbound.run(async () => {\n const sealed = await sealBytes(encoder.encode(text));\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return sealed;\n });\n },\n\n async openText(text) {\n if (channel === undefined) return text;\n return await inbound.run(async () => {\n const opened = await openBytes(text);\n return opened === undefined ? undefined : decoder.decode(opened);\n });\n },\n\n async sealBinary(bytes) {\n if (channel === undefined) return bytes;\n return await outbound.run(async () => {\n const sealed = await sealBytes(bytes);\n if (sealed === undefined) throw new Error(failure ?? 'The active sealed channel could not encrypt a message.');\n return encoder.encode(sealed);\n });\n },\n\n async openBinary(bytes) {\n if (channel === undefined) return bytes;\n return await inbound.run(async () => await openBytes(decoder.decode(bytes)));\n },\n\n async fetch(input, init) {\n const gateway = relayPath;\n if (channel === undefined || gateway === undefined) return await fetch(input, init);\n return await exchange.run(async () => {\n const bytes = await bodyBytes(init?.body);\n const request: SealedHttpRequest = {\n v: 1,\n method: (init?.method ?? 'GET').toUpperCase(),\n target: requestTarget(input),\n headers: Array.from(new Headers(init?.headers).entries()),\n ...(bytes === undefined ? {} : { body: encodeBase64(bytes) }),\n };\n const sealed = await sealBytes(encoder.encode(JSON.stringify(request)));\n if (sealed === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const relayResponse = await fetch(gateway, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': JSON_CONTENT_TYPE },\n body: sealed,\n });\n const opened = await openBytes(await relayResponse.text());\n if (opened === undefined) {\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(decoder.decode(opened));\n } catch {\n decoded = undefined;\n }\n if (!isSealedHttpResponse(decoded)) {\n failure = 'The sealed HTTP response was malformed.';\n return new Response(JSON.stringify({ error: failure }), { status: 502 });\n }\n const body = decodeBase64(decoded.body);\n return new Response(decoded.status === 204 || decoded.status === 205 || decoded.status === 304 ? null : body, {\n status: decoded.status,\n headers: decoded.headers,\n });\n });\n },\n };\n}\n\n/**\n * The page's one sealed channel.\n *\n * A module singleton rather than an instance per caller, because the cockpit\n * and every plugin are bundled into the same page and all of them must share\n * one pair of nonce counters. Two transports over one handshake would each\n * start counting at zero and the receiver would reject the second as a replay.\n *\n * Inactive until a handshake completes, and inactive forever on the loopback\n * listener, so `sealedTransport.fetch` is a plain `fetch` there.\n */\nexport const sealedTransport = createSealedTransport();\n"],"mappings":"4MAmBA,MAeMA,EAAU,IAAI,YACdC,EAAU,IAAI,YAiBpB,SAASC,EAAa,EAA2B,CAC/C,IAAIC,EAAS,GACb,IAAK,IAAMC,KAAQC,EAAO,GAAU,OAAO,aAAaD,CAAI,EAC5D,OAAO,KAAKD,CAAM,CACpB,CAEA,SAASG,EAAa,EAA2B,CAC/C,IAAMH,EAAS,KAAKI,CAAK,EACzB,OAAO,WAAW,KAAKJ,EAAS,GAAcK,EAAU,WAAW,CAAC,CAAC,CACvE,CAEA,eAAeC,EAAU,EAA4D,CACnF,GAAIC,GAA+B,KACnC,IAAI,OAAOA,GAAS,SAAU,OAAOV,EAAQ,OAAOU,CAAI,EACxD,GAAIA,aAAgB,gBAAiB,OAAOV,EAAQ,OAAOU,EAAK,SAAS,CAAC,EAC1E,GAAIA,aAAgB,KAAM,OAAO,IAAI,WAAW,MAAMA,EAAK,YAAY,CAAC,EACxE,GAAIA,aAAgB,YAAa,OAAO,IAAI,WAAWA,CAAI,EAC3D,GAAI,YAAY,OAAOA,CAAI,EAAG,OAAO,IAAI,WAAWA,EAAK,OAAQA,EAAK,WAAYA,EAAK,UAAU,EACjG,MAAU,MAAM,oEAAoE,CAL5B,CAM1D,CAEA,SAASC,EAAc,EAAuB,CAC5C,GAAI,CAACC,EAAM,WAAW,GAAG,EAAG,MAAU,MAAM,qDAAqD,EACjG,OAAOA,CACT,CAEA,SAASC,EAAqB,EAA6C,CACzE,GAAI,OAAON,GAAU,WAAYA,EAAgB,MAAO,GACxD,IAAMO,EAAYP,EAClB,OACEO,EAAU,IAAM,GAChB,OAAOA,EAAU,QAAW,UAC5B,MAAM,QAAQA,EAAU,OAAO,GAC/BA,EAAU,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AK,UAAUwC,CAAO,CAAC,CAAC,EACtE,GAAIX,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOV,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMsB,EAAgB,MAAM,MAAMH,EAAS,CACzC,OAAQ,OACR,YAAa,cACb,QAAS,CAAE,eAAgB,kBAAkB,EAC7C,KAAMT,CACR,CAAC,EACKI,EAAS,MAAMH,EAAU,MAAMW,EAAc,KAAK,CAAC,EACzD,GAAIR,IAAW,IAAA,GACb,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOd,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAIuB,EACJ,GAAI,CACF,EAAU,KAAK,MAAMzC,EAAQ,OAAOgC,CAAM,CAAC,CAC7C,MAAQ,CACN,EAAU,IAAA,EACZ,CACA,GAAI,CAACpB,EAAqB6B,CAAO,EAE/B,MADA,GAAU,0CACH,IAAI,SAAS,KAAK,UAAU,CAAE,MAAOvB,CAAQ,CAAC,EAAG,CAAE,OAAQ,GAAI,CAAC,EAEzE,IAAMT,EAAOJ,EAAaoC,EAAQ,IAAI,EACtC,OAAO,IAAI,SAASA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,KAAOA,EAAQ,SAAW,IAAM,KAAOhC,EAAM,CAC5G,OAAQgC,EAAQ,OAChB,QAASA,EAAQ,OACnB,CAAC,CACH,CAAC,CACH,CACF,CACF,CAaA,MAAaC,EAAkB1B,EAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-web-security",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.4",
|
|
4
4
|
"description": "Shared security primitives for the Po 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.6.
|
|
61
|
-
"@vitest/coverage-v8": "5.0.
|
|
62
|
-
"tsdown": "0.23.
|
|
60
|
+
"@types/node": "26.6.5",
|
|
61
|
+
"@vitest/coverage-v8": "5.0.4",
|
|
62
|
+
"tsdown": "0.23.1",
|
|
63
63
|
"typescript": "7.0.2",
|
|
64
|
-
"vitest": "5.0.
|
|
64
|
+
"vitest": "5.0.4"
|
|
65
65
|
},
|
|
66
66
|
"engines": {
|
|
67
67
|
"node": ">=24"
|