@moonmath-ai/zro 0.4.3 → 0.5.0-beta.1

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/e2ee.js ADDED
@@ -0,0 +1,907 @@
1
+ /**
2
+ * Zero-dependency RFC 9180 HPKE client (`zro-hpke-v1`) on Node 22+ `node:crypto`.
3
+ *
4
+ * Implements HPKE Base Mode (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, AES-256-GCM),
5
+ * Ed25519 manifest canonicalization & verification, outer shell builders, and
6
+ * non-streaming + streaming SSE response decryptors for `/v1/chat/completions`,
7
+ * `/v1/responses`, and `/v1/messages`.
8
+ */
9
+ import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey, diffieHellman, randomBytes, sign as cryptoSign, verify as cryptoVerify, } from "node:crypto";
10
+ export const HPKE_MODE_BASE = 0x00;
11
+ export const KEM_DHKEM_X25519_HKDF_SHA256 = 0x0020;
12
+ export const KDF_HKDF_SHA256 = 0x0001;
13
+ export const AEAD_AES_128_GCM = 0x0001;
14
+ export const AEAD_AES_256_GCM = 0x0002;
15
+ export const PROTOCOL_PREFIX = "zro-hpke:v1:";
16
+ export const MANIFEST_ALG = "HPKE-X25519-HKDF-SHA256-AES256GCM";
17
+ export const REQ_INFO_PREFIX = "zro-hpke-v1:";
18
+ export const REQ_AAD = Buffer.from("req", "utf8");
19
+ export const RESP_KEY_EXPORT_LABEL = Buffer.from("zro-hpke-v1/resp/key", "utf8");
20
+ export const RESP_IV_EXPORT_LABEL = Buffer.from("zro-hpke-v1/resp/iv", "utf8");
21
+ /**
22
+ * Production HSM Ed25519 root public key (unpadded base64url, 32 bytes).
23
+ * Mirrors the DNSSEC-protected TXT record at `_zro-e2ee.zro.moonmath.ai`.
24
+ * Override for staging or testing via `--e2ee-root-pubkey` or `ZRO_E2EE_ROOT_PUBKEY`.
25
+ */
26
+ export const DEFAULT_E2EE_ROOT_PUBKEY = "7qLRrP9MviWLHYg7pS9rFoHLsfXlxUK7GXUB7xX1MRY";
27
+ const HPKE_VERSION = Buffer.from("HPKE-v1", "ascii");
28
+ const SUITE_ID_KEM = Buffer.from([0x4b, 0x45, 0x4d, 0x00, 0x20]);
29
+ const NN = 12;
30
+ const NH = 32;
31
+ const NSECRET = 32;
32
+ const NSK = 32;
33
+ const TAG_LEN = 16;
34
+ const X25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b656e04220420", "hex");
35
+ const X25519_SPKI_PREFIX = Buffer.from("302a300506032b656e032100", "hex");
36
+ const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
37
+ const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
38
+ const CANONICAL_UINT_RE = /^(?:0|[1-9][0-9]*)$/;
39
+ const B64U_RE = /^[A-Za-z0-9_-]+$/;
40
+ export class E2EEError extends Error {
41
+ constructor(message) {
42
+ super(message);
43
+ this.name = "E2EEError";
44
+ }
45
+ }
46
+ export class ManifestVerificationError extends E2EEError {
47
+ constructor(message) {
48
+ super(message);
49
+ this.name = "ManifestVerificationError";
50
+ }
51
+ }
52
+ export class DecryptionError extends E2EEError {
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "DecryptionError";
56
+ }
57
+ }
58
+ export class StreamTruncationError extends E2EEError {
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = "StreamTruncationError";
62
+ }
63
+ }
64
+ export function resolveE2eeRootPubkey(flagValue, env = process.env) {
65
+ const value = (flagValue ?? env.ZRO_E2EE_ROOT_PUBKEY ?? DEFAULT_E2EE_ROOT_PUBKEY)?.trim();
66
+ if (!value) {
67
+ throw new E2EEError("E2EE requires a pinned Ed25519 root public key. Pass --e2ee-root-pubkey or set ZRO_E2EE_ROOT_PUBKEY.");
68
+ }
69
+ return value;
70
+ }
71
+ export function b64uEncode(data) {
72
+ return Buffer.from(data).toString("base64url");
73
+ }
74
+ export function b64uDecode(text) {
75
+ if (!text || !B64U_RE.test(text) || text.length % 4 === 1) {
76
+ throw new DecryptionError("Invalid unpadded base64url encoding");
77
+ }
78
+ const raw = Buffer.from(text, "base64url");
79
+ if (raw.toString("base64url") !== text) {
80
+ throw new DecryptionError("Non-canonical base64url encoding");
81
+ }
82
+ return raw;
83
+ }
84
+ function i2osp2(n) {
85
+ const b = Buffer.alloc(2);
86
+ b.writeUInt16BE(n, 0);
87
+ return b;
88
+ }
89
+ function u64Be(seq) {
90
+ if (seq < 0n || seq > 0xffffffffffffffffn) {
91
+ throw new RangeError("seq must be an unsigned 64-bit integer");
92
+ }
93
+ const b = Buffer.alloc(8);
94
+ b.writeBigUInt64BE(seq, 0);
95
+ return b;
96
+ }
97
+ function hkdfExtract(salt, ikm) {
98
+ const key = salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(NH, 0);
99
+ return createHmac("sha256", key).update(ikm).digest();
100
+ }
101
+ function hkdfExpand(prk, info, length) {
102
+ if (length < 0 || length > 255 * NH) {
103
+ throw new RangeError("Invalid HKDF-Expand output length");
104
+ }
105
+ const blocks = [];
106
+ let prev = Buffer.alloc(0);
107
+ let counter = 1;
108
+ let total = 0;
109
+ while (total < length) {
110
+ const h = createHmac("sha256", prk);
111
+ h.update(prev);
112
+ h.update(info);
113
+ h.update(Buffer.from([counter]));
114
+ prev = h.digest();
115
+ blocks.push(prev);
116
+ total += prev.length;
117
+ counter += 1;
118
+ }
119
+ return Buffer.concat(blocks, total).subarray(0, length);
120
+ }
121
+ function labeledExtract(salt, label, ikm, suiteId) {
122
+ const labeledIkm = Buffer.concat([
123
+ HPKE_VERSION,
124
+ suiteId,
125
+ Buffer.from(label, "ascii"),
126
+ ikm,
127
+ ]);
128
+ return hkdfExtract(salt, labeledIkm);
129
+ }
130
+ function labeledExpand(prk, label, info, length, suiteId) {
131
+ const labeledInfo = Buffer.concat([
132
+ i2osp2(length),
133
+ HPKE_VERSION,
134
+ suiteId,
135
+ Buffer.from(label, "ascii"),
136
+ info,
137
+ ]);
138
+ return hkdfExpand(prk, labeledInfo, length);
139
+ }
140
+ function suiteIdHpke(aeadId) {
141
+ if (aeadId !== AEAD_AES_128_GCM && aeadId !== AEAD_AES_256_GCM) {
142
+ throw new RangeError(`Unsupported AEAD id: ${aeadId}`);
143
+ }
144
+ return Buffer.concat([
145
+ Buffer.from("HPKE", "ascii"),
146
+ i2osp2(KEM_DHKEM_X25519_HKDF_SHA256),
147
+ i2osp2(KDF_HKDF_SHA256),
148
+ i2osp2(aeadId),
149
+ ]);
150
+ }
151
+ function aeadKeyLen(aeadId) {
152
+ return aeadId === AEAD_AES_128_GCM ? 16 : 32;
153
+ }
154
+ function aeadAlgoName(aeadId) {
155
+ return aeadId === AEAD_AES_128_GCM ? "aes-128-gcm" : "aes-256-gcm";
156
+ }
157
+ function x25519PrivateKeyObj(skBytes) {
158
+ if (skBytes.length !== NSK) {
159
+ throw new RangeError("X25519 private key must be 32 bytes");
160
+ }
161
+ return createPrivateKey({
162
+ key: Buffer.concat([X25519_PKCS8_PREFIX, skBytes]),
163
+ format: "der",
164
+ type: "pkcs8",
165
+ });
166
+ }
167
+ function x25519PublicKeyObj(pkBytes) {
168
+ if (pkBytes.length !== NSK) {
169
+ throw new RangeError("X25519 public key must be 32 bytes");
170
+ }
171
+ return createPublicKey({
172
+ key: Buffer.concat([X25519_SPKI_PREFIX, pkBytes]),
173
+ format: "der",
174
+ type: "spki",
175
+ });
176
+ }
177
+ export function x25519PublicFromPrivate(skBytes) {
178
+ const priv = x25519PrivateKeyObj(skBytes);
179
+ const pubDer = createPublicKey(priv).export({ format: "der", type: "spki" });
180
+ return Buffer.from(pubDer).subarray(-32);
181
+ }
182
+ function x25519Dh(skBytes, pkBytes) {
183
+ const dh = diffieHellman({
184
+ privateKey: x25519PrivateKeyObj(skBytes),
185
+ publicKey: x25519PublicKeyObj(pkBytes),
186
+ });
187
+ let nonZero = 0;
188
+ for (let i = 0; i < dh.length; i += 1)
189
+ nonZero |= dh[i];
190
+ if (dh.length !== 32 || nonZero === 0) {
191
+ throw new DecryptionError("X25519 DH produced all-zero shared secret");
192
+ }
193
+ return dh;
194
+ }
195
+ export function deriveKeyPair(ikm) {
196
+ const dkpPrk = labeledExtract(Buffer.alloc(0), "dkp_prk", ikm, SUITE_ID_KEM);
197
+ const sk = labeledExpand(dkpPrk, "sk", Buffer.alloc(0), NSK, SUITE_ID_KEM);
198
+ const pk = x25519PublicFromPrivate(sk);
199
+ return { sk, pk };
200
+ }
201
+ function extractAndExpand(dh, kemContext) {
202
+ const eaePrk = labeledExtract(Buffer.alloc(0), "eae_prk", dh, SUITE_ID_KEM);
203
+ return labeledExpand(eaePrk, "shared_secret", kemContext, NSECRET, SUITE_ID_KEM);
204
+ }
205
+ function aesGcmEncrypt(aeadId, key, nonce, aad, plaintext) {
206
+ const cipher = createCipheriv(aeadAlgoName(aeadId), key, nonce);
207
+ cipher.setAAD(aad);
208
+ const enc = Buffer.concat([cipher.update(plaintext), cipher.final()]);
209
+ const tag = cipher.getAuthTag();
210
+ return Buffer.concat([enc, tag]);
211
+ }
212
+ function aesGcmDecrypt(aeadId, key, nonce, aad, ciphertext) {
213
+ if (ciphertext.length < TAG_LEN) {
214
+ throw new DecryptionError("Ciphertext shorter than AES-GCM tag");
215
+ }
216
+ const ct = ciphertext.subarray(0, ciphertext.length - TAG_LEN);
217
+ const tag = ciphertext.subarray(ciphertext.length - TAG_LEN);
218
+ const decipher = createDecipheriv(aeadAlgoName(aeadId), key, nonce);
219
+ decipher.setAAD(aad);
220
+ decipher.setAuthTag(tag);
221
+ try {
222
+ return Buffer.concat([decipher.update(ct), decipher.final()]);
223
+ }
224
+ catch {
225
+ throw new DecryptionError("AES-GCM authentication failed");
226
+ }
227
+ }
228
+ function xorNonce(baseNonce, seq) {
229
+ if (baseNonce.length !== NN) {
230
+ throw new RangeError("base_nonce must be 12 bytes");
231
+ }
232
+ const seqBuf = Buffer.alloc(NN, 0);
233
+ u64Be(seq).copy(seqBuf, 4);
234
+ const out = Buffer.alloc(NN);
235
+ for (let i = 0; i < NN; i += 1) {
236
+ out[i] = baseNonce[i] ^ seqBuf[i];
237
+ }
238
+ return out;
239
+ }
240
+ export class HpkeContext {
241
+ key;
242
+ baseNonce;
243
+ exporterSecret;
244
+ suiteId;
245
+ aeadId;
246
+ role;
247
+ seq = 0n;
248
+ constructor(params) {
249
+ this.key = params.key;
250
+ this.baseNonce = params.baseNonce;
251
+ this.exporterSecret = params.exporterSecret;
252
+ this.suiteId = params.suiteId;
253
+ this.aeadId = params.aeadId;
254
+ this.role = params.role;
255
+ }
256
+ nextNonce() {
257
+ const nonce = xorNonce(this.baseNonce, this.seq);
258
+ this.seq += 1n;
259
+ return nonce;
260
+ }
261
+ seal(aad, plaintext) {
262
+ if (this.role !== "sender") {
263
+ throw new E2EEError("seal() is only valid on a sender context");
264
+ }
265
+ return aesGcmEncrypt(this.aeadId, this.key, this.nextNonce(), aad, plaintext);
266
+ }
267
+ open(aad, ciphertext) {
268
+ if (this.role !== "recipient") {
269
+ throw new E2EEError("open() is only valid on a recipient context");
270
+ }
271
+ return aesGcmDecrypt(this.aeadId, this.key, this.nextNonce(), aad, ciphertext);
272
+ }
273
+ exportSecret(exporterContext, length) {
274
+ return labeledExpand(this.exporterSecret, "sec", exporterContext, length, this.suiteId);
275
+ }
276
+ }
277
+ function keyScheduleBase(sharedSecret, info, aeadId, role) {
278
+ const suiteId = suiteIdHpke(aeadId);
279
+ const pskIdHash = labeledExtract(Buffer.alloc(0), "psk_id_hash", Buffer.alloc(0), suiteId);
280
+ const infoHash = labeledExtract(Buffer.alloc(0), "info_hash", info, suiteId);
281
+ const ksContext = Buffer.concat([Buffer.from([HPKE_MODE_BASE]), pskIdHash, infoHash]);
282
+ const secret = labeledExtract(sharedSecret, "secret", Buffer.alloc(0), suiteId);
283
+ const key = labeledExpand(secret, "key", ksContext, aeadKeyLen(aeadId), suiteId);
284
+ const baseNonce = labeledExpand(secret, "base_nonce", ksContext, NN, suiteId);
285
+ const exporterSecret = labeledExpand(secret, "exp", ksContext, NH, suiteId);
286
+ return new HpkeContext({
287
+ key,
288
+ baseNonce,
289
+ exporterSecret,
290
+ suiteId,
291
+ aeadId,
292
+ role,
293
+ });
294
+ }
295
+ export function setupBaseS(pkR, info, options) {
296
+ const aeadId = options?.aeadId ?? AEAD_AES_256_GCM;
297
+ const ikmE = options?.ikmE ?? randomBytes(32);
298
+ const { sk: skE, pk: enc } = deriveKeyPair(ikmE);
299
+ const dh = x25519Dh(skE, pkR);
300
+ const sharedSecret = extractAndExpand(dh, Buffer.concat([enc, pkR]));
301
+ const ctx = keyScheduleBase(sharedSecret, info, aeadId, "sender");
302
+ return { enc, ctx };
303
+ }
304
+ export function setupBaseR(enc, skR, info, options) {
305
+ const aeadId = options?.aeadId ?? AEAD_AES_256_GCM;
306
+ const pkR = x25519PublicFromPrivate(skR);
307
+ const dh = x25519Dh(skR, enc);
308
+ const sharedSecret = extractAndExpand(dh, Buffer.concat([enc, pkR]));
309
+ return keyScheduleBase(sharedSecret, info, aeadId, "recipient");
310
+ }
311
+ function canonicalizeValue(value) {
312
+ if (value === null || typeof value !== "object") {
313
+ return JSON.stringify(value);
314
+ }
315
+ if (Array.isArray(value)) {
316
+ return "[" + value.map((item) => canonicalizeValue(item)).join(",") + "]";
317
+ }
318
+ const obj = value;
319
+ const keys = Object.keys(obj).sort((a, b) => Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8")));
320
+ const parts = [];
321
+ for (const k of keys) {
322
+ if (obj[k] === undefined)
323
+ continue;
324
+ parts.push(`${JSON.stringify(k)}:${canonicalizeValue(obj[k])}`);
325
+ }
326
+ return "{" + parts.join(",") + "}";
327
+ }
328
+ export function canonicalManifestBytes(manifest) {
329
+ const unsigned = {};
330
+ for (const [k, v] of Object.entries(manifest)) {
331
+ if (k !== "signature")
332
+ unsigned[k] = v;
333
+ }
334
+ return Buffer.from(canonicalizeValue(unsigned), "utf8");
335
+ }
336
+ export function keyFingerprint(publicKeyBytes) {
337
+ return "sha256:" + createHash("sha256").update(publicKeyBytes).digest("hex");
338
+ }
339
+ export function signManifest(unsignedManifest, rootPrivateKeyBytes, rootKid) {
340
+ if (rootPrivateKeyBytes.length !== 32) {
341
+ throw new RangeError("Ed25519 private key seed must be 32 bytes");
342
+ }
343
+ const priv = createPrivateKey({
344
+ key: Buffer.concat([ED25519_PKCS8_PREFIX, rootPrivateKeyBytes]),
345
+ format: "der",
346
+ type: "pkcs8",
347
+ });
348
+ const payload = canonicalManifestBytes(unsignedManifest);
349
+ const sig = cryptoSign(null, payload, priv);
350
+ const out = {};
351
+ for (const [k, v] of Object.entries(unsignedManifest)) {
352
+ if (k !== "signature")
353
+ out[k] = v;
354
+ }
355
+ out.signature = {
356
+ alg: "Ed25519",
357
+ root_kid: rootKid,
358
+ sig: b64uEncode(sig),
359
+ };
360
+ return out;
361
+ }
362
+ export function verifyManifest(manifest, pinnedRootPublicKey) {
363
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
364
+ throw new ManifestVerificationError("Manifest must be a JSON object");
365
+ }
366
+ const m = manifest;
367
+ if (m.version !== "v1") {
368
+ throw new ManifestVerificationError(`Unsupported manifest version: ${String(m.version)}`);
369
+ }
370
+ const sigObj = m.signature;
371
+ if (!sigObj || typeof sigObj !== "object" || sigObj.alg !== "Ed25519" || typeof sigObj.sig !== "string") {
372
+ throw new ManifestVerificationError("Manifest missing valid Ed25519 signature object");
373
+ }
374
+ let sigBytes;
375
+ try {
376
+ sigBytes = b64uDecode(sigObj.sig);
377
+ }
378
+ catch {
379
+ throw new ManifestVerificationError("Invalid base64url in signature.sig");
380
+ }
381
+ if (sigBytes.length !== 64) {
382
+ throw new ManifestVerificationError("Ed25519 signature must be 64 bytes");
383
+ }
384
+ let rootRaw;
385
+ try {
386
+ rootRaw =
387
+ typeof pinnedRootPublicKey === "string"
388
+ ? b64uDecode(pinnedRootPublicKey)
389
+ : Buffer.from(pinnedRootPublicKey);
390
+ }
391
+ catch {
392
+ throw new ManifestVerificationError("Pinned Ed25519 root public key is invalid base64url");
393
+ }
394
+ if (rootRaw.length !== 32) {
395
+ throw new ManifestVerificationError("Pinned Ed25519 root public key must be 32 bytes");
396
+ }
397
+ const rootPub = createPublicKey({
398
+ key: Buffer.concat([ED25519_SPKI_PREFIX, rootRaw]),
399
+ format: "der",
400
+ type: "spki",
401
+ });
402
+ const canonical = canonicalManifestBytes(m);
403
+ if (!cryptoVerify(null, canonical, rootPub, sigBytes)) {
404
+ throw new ManifestVerificationError("Manifest Ed25519 signature verification failed");
405
+ }
406
+ if (!Array.isArray(m.keys) || m.keys.length === 0) {
407
+ throw new ManifestVerificationError("Manifest contains no keys");
408
+ }
409
+ for (const entry of m.keys) {
410
+ if (!entry || typeof entry !== "object") {
411
+ throw new ManifestVerificationError("Manifest key entry must be an object");
412
+ }
413
+ if (entry.alg !== MANIFEST_ALG) {
414
+ throw new ManifestVerificationError(`Unsupported key alg: ${entry.alg}`);
415
+ }
416
+ if (typeof entry.kid !== "string" || !entry.kid || entry.kid.includes(":") || entry.kid.includes(";")) {
417
+ throw new ManifestVerificationError(`Invalid kid: ${String(entry.kid)}`);
418
+ }
419
+ let pkRaw;
420
+ try {
421
+ pkRaw = b64uDecode(entry.public_key);
422
+ }
423
+ catch {
424
+ throw new ManifestVerificationError("Invalid base64url public_key");
425
+ }
426
+ if (pkRaw.length !== 32) {
427
+ throw new ManifestVerificationError("X25519 public_key must be 32 bytes");
428
+ }
429
+ const expectedFp = keyFingerprint(pkRaw);
430
+ if (entry.fingerprint !== expectedFp) {
431
+ throw new ManifestVerificationError(`Fingerprint mismatch for ${entry.kid}`);
432
+ }
433
+ }
434
+ return m;
435
+ }
436
+ export function selectActiveKey(manifest, options) {
437
+ const checkTime = options?.checkTime ?? true;
438
+ const nowMs = (options?.now ?? new Date()).getTime();
439
+ for (const entry of manifest.keys) {
440
+ if (entry.status !== "active")
441
+ continue;
442
+ if (checkTime) {
443
+ if (entry.not_before && nowMs < Date.parse(entry.not_before))
444
+ continue;
445
+ if (entry.not_after && nowMs > Date.parse(entry.not_after))
446
+ continue;
447
+ }
448
+ return { kid: entry.kid, publicKey: b64uDecode(entry.public_key) };
449
+ }
450
+ throw new ManifestVerificationError("No active valid key found in manifest");
451
+ }
452
+ export function supportedE2eeModels(manifest) {
453
+ const out = new Set();
454
+ for (const entry of manifest.supported_models ?? []) {
455
+ if (typeof entry === "string" && entry.trim()) {
456
+ out.add(entry.trim().replace(/^zro\//, ""));
457
+ }
458
+ }
459
+ return out;
460
+ }
461
+ export async function fetchAndVerifyManifest(baseUrl, pinnedRootPublicKey, fetcher = globalThis.fetch) {
462
+ const url = `${baseUrl.replace(/\/+$/, "")}/.well-known/zro-encryption-keys.json`;
463
+ const resp = await fetcher(url, {
464
+ headers: { Accept: "application/json" },
465
+ signal: AbortSignal.timeout(10_000),
466
+ });
467
+ if (!resp.ok) {
468
+ await resp.body?.cancel().catch(() => { });
469
+ throw new ManifestVerificationError(`Failed to fetch key manifest: HTTP ${resp.status}`);
470
+ }
471
+ const manifest = await resp.json();
472
+ return verifyManifest(manifest, pinnedRootPublicKey);
473
+ }
474
+ export function responseFrameNonce(respIv, seq) {
475
+ return xorNonce(respIv, BigInt(seq));
476
+ }
477
+ export function responseFrameAad(kid, seq, isEof = false) {
478
+ const kidBuf = Buffer.from(kid, "utf8");
479
+ const seqBuf = u64Be(BigInt(seq));
480
+ if (isEof) {
481
+ return Buffer.concat([Buffer.from("resp\0", "ascii"), kidBuf, Buffer.from("\0eof\0", "ascii"), seqBuf]);
482
+ }
483
+ return Buffer.concat([Buffer.from("resp\0", "ascii"), kidBuf, Buffer.from("\0", "ascii"), seqBuf]);
484
+ }
485
+ export function encryptResponseFrame(respKey, respIv, kid, seq, plaintext, isEof = false) {
486
+ const nonce = responseFrameNonce(respIv, seq);
487
+ const aad = responseFrameAad(kid, seq, isEof);
488
+ const ct = aesGcmEncrypt(AEAD_AES_256_GCM, respKey, nonce, aad, plaintext);
489
+ const seqStr = BigInt(seq).toString(10);
490
+ return isEof
491
+ ? `${PROTOCOL_PREFIX}${seqStr}:eof:${b64uEncode(ct)};`
492
+ : `${PROTOCOL_PREFIX}${seqStr}:${b64uEncode(ct)};`;
493
+ }
494
+ export function parseWireFrame(rawFrameNoSemi) {
495
+ if (!rawFrameNoSemi.startsWith(PROTOCOL_PREFIX)) {
496
+ throw new DecryptionError("Frame missing zro-hpke:v1: prefix");
497
+ }
498
+ const parts = rawFrameNoSemi.slice(PROTOCOL_PREFIX.length).split(":");
499
+ let seqStr;
500
+ let ctB64;
501
+ let isEof;
502
+ if (parts.length === 2) {
503
+ [seqStr, ctB64] = parts;
504
+ isEof = false;
505
+ }
506
+ else if (parts.length === 3 && parts[1] === "eof") {
507
+ seqStr = parts[0];
508
+ ctB64 = parts[2];
509
+ isEof = true;
510
+ }
511
+ else {
512
+ throw new DecryptionError("Malformed response frame structure");
513
+ }
514
+ if (!CANONICAL_UINT_RE.test(seqStr)) {
515
+ throw new DecryptionError(`Invalid frame sequence number: ${seqStr}`);
516
+ }
517
+ const seq = BigInt(seqStr);
518
+ if (seq > 0xffffffffffffffffn) {
519
+ throw new DecryptionError("Frame sequence number exceeds u64");
520
+ }
521
+ const ct = b64uDecode(ctB64);
522
+ if (ct.length < TAG_LEN) {
523
+ throw new DecryptionError("Frame ciphertext shorter than AES-GCM tag");
524
+ }
525
+ return { seq, isEof, ct };
526
+ }
527
+ export function decryptResponseFrame(respKey, respIv, kid, rawFrameNoSemi) {
528
+ const { seq, isEof, ct } = parseWireFrame(rawFrameNoSemi);
529
+ const nonce = responseFrameNonce(respIv, seq);
530
+ const aad = responseFrameAad(kid, seq, isEof);
531
+ const plaintext = aesGcmDecrypt(AEAD_AES_256_GCM, respKey, nonce, aad, ct);
532
+ return { seq, isEof, plaintext };
533
+ }
534
+ export class StreamDecryptor {
535
+ endpoint;
536
+ kid;
537
+ respKey;
538
+ respIv;
539
+ buf = "";
540
+ expectedSeq = 0n;
541
+ dataFrames = 0;
542
+ eofReceived = false;
543
+ finishReason = null;
544
+ constructor(params) {
545
+ this.endpoint = params.endpoint;
546
+ this.kid = params.kid;
547
+ this.respKey = params.respKey;
548
+ this.respIv = params.respIv;
549
+ }
550
+ feedText(chunk) {
551
+ if (!chunk)
552
+ return [];
553
+ this.buf += chunk;
554
+ const emitted = [];
555
+ let idx = this.buf.indexOf(";");
556
+ while (idx !== -1) {
557
+ const rawFrame = this.buf.slice(0, idx);
558
+ this.buf = this.buf.slice(idx + 1);
559
+ if (!rawFrame) {
560
+ throw new DecryptionError("Empty frame before semicolon");
561
+ }
562
+ if (this.eofReceived) {
563
+ throw new DecryptionError("Unexpected frame received after eof frame");
564
+ }
565
+ const { seq, isEof, plaintext } = decryptResponseFrame(this.respKey, this.respIv, this.kid, rawFrame);
566
+ if (seq !== this.expectedSeq) {
567
+ throw new DecryptionError(`Out-of-order frame sequence: expected ${this.expectedSeq}, got ${seq}`);
568
+ }
569
+ this.expectedSeq += 1n;
570
+ let payload;
571
+ try {
572
+ payload = JSON.parse(plaintext.toString("utf8"));
573
+ }
574
+ catch {
575
+ throw new DecryptionError("Decrypted frame is not valid UTF-8 JSON");
576
+ }
577
+ if (isEof) {
578
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
579
+ throw new DecryptionError("eof frame payload must be a JSON object");
580
+ }
581
+ const obj = payload;
582
+ if (typeof obj.frames !== "number" || !Number.isInteger(obj.frames) || obj.frames !== this.dataFrames) {
583
+ throw new StreamTruncationError(`eof frame count mismatch: expected ${this.dataFrames}, got ${String(obj.frames)}`);
584
+ }
585
+ this.finishReason = typeof obj.finish_reason === "string" ? obj.finish_reason : null;
586
+ this.eofReceived = true;
587
+ }
588
+ else {
589
+ this.dataFrames += 1;
590
+ if (Array.isArray(payload)) {
591
+ emitted.push(...payload);
592
+ }
593
+ else {
594
+ emitted.push(payload);
595
+ }
596
+ }
597
+ idx = this.buf.indexOf(";");
598
+ }
599
+ return emitted;
600
+ }
601
+ finish() {
602
+ if (this.buf.length > 0) {
603
+ throw new StreamTruncationError(`Trailing incomplete encrypted frame (${this.buf.length} chars)`);
604
+ }
605
+ if (!this.eofReceived) {
606
+ throw new StreamTruncationError("Stream ended without authenticated eof frame");
607
+ }
608
+ return { finishReason: this.finishReason, framesCount: this.dataFrames };
609
+ }
610
+ }
611
+ function extractNonStreamingText(outerResponse, endpoint) {
612
+ const choices = outerResponse.choices;
613
+ if (Array.isArray(choices) && choices.length > 0) {
614
+ const msg = choices[0]?.message;
615
+ if (msg && typeof msg.content === "string")
616
+ return msg.content;
617
+ }
618
+ const content = outerResponse.content;
619
+ if (Array.isArray(content) && content.length > 0) {
620
+ const parts = content
621
+ .filter((b) => b && b.type === "text" && typeof b.text === "string")
622
+ .map((b) => b.text);
623
+ if (parts.length > 0)
624
+ return parts.join("");
625
+ }
626
+ const output = outerResponse.output;
627
+ if (Array.isArray(output) && output.length > 0) {
628
+ const parts = [];
629
+ for (const item of output) {
630
+ const blocks = item?.content;
631
+ if (!Array.isArray(blocks))
632
+ continue;
633
+ for (const b of blocks) {
634
+ if (b && typeof b.text === "string")
635
+ parts.push(b.text);
636
+ }
637
+ }
638
+ if (parts.length > 0)
639
+ return parts.join("");
640
+ }
641
+ throw new DecryptionError(`Could not locate encrypted response text slot for ${endpoint}`);
642
+ }
643
+ export function* iterSseEvents(rawText) {
644
+ let eventName = null;
645
+ let dataLines = [];
646
+ for (const rawLine of rawText.split(/\r?\n/)) {
647
+ if (rawLine === "") {
648
+ if (dataLines.length > 0) {
649
+ yield { event: eventName, data: dataLines.join("\n") };
650
+ }
651
+ eventName = null;
652
+ dataLines = [];
653
+ continue;
654
+ }
655
+ if (rawLine.startsWith(":"))
656
+ continue;
657
+ const colon = rawLine.indexOf(":");
658
+ const field = colon === -1 ? rawLine : rawLine.slice(0, colon);
659
+ let value = colon === -1 ? "" : rawLine.slice(colon + 1);
660
+ if (value.startsWith(" "))
661
+ value = value.slice(1);
662
+ if (field === "event")
663
+ eventName = value;
664
+ else if (field === "data")
665
+ dataLines.push(value);
666
+ }
667
+ if (dataLines.length > 0) {
668
+ yield { event: eventName, data: dataLines.join("\n") };
669
+ }
670
+ }
671
+ export function mergeUsage(base, update) {
672
+ if (!update)
673
+ return base;
674
+ const merged = { ...(base ?? {}) };
675
+ for (const [k, v] of Object.entries(update)) {
676
+ if (v !== undefined && v !== null)
677
+ merged[k] = v;
678
+ }
679
+ return merged;
680
+ }
681
+ export class E2EESession {
682
+ endpoint;
683
+ kid;
684
+ enc;
685
+ respKey;
686
+ respIv;
687
+ constructor(params) {
688
+ this.endpoint = params.endpoint;
689
+ this.kid = params.kid;
690
+ this.enc = params.enc;
691
+ this.respKey = params.respKey;
692
+ this.respIv = params.respIv;
693
+ }
694
+ createStreamDecryptor() {
695
+ return new StreamDecryptor({
696
+ endpoint: this.endpoint,
697
+ kid: this.kid,
698
+ respKey: this.respKey,
699
+ respIv: this.respIv,
700
+ });
701
+ }
702
+ decryptResponse(outerResponse) {
703
+ const text = extractNonStreamingText(outerResponse, this.endpoint);
704
+ if (!text.endsWith(";")) {
705
+ throw new DecryptionError("Non-streaming response frame missing trailing ';'");
706
+ }
707
+ const rawFrame = text.slice(0, -1);
708
+ if (rawFrame.includes(";")) {
709
+ throw new DecryptionError("Unexpected multiple frames in non-streaming response");
710
+ }
711
+ const { seq, isEof, plaintext } = decryptResponseFrame(this.respKey, this.respIv, this.kid, rawFrame);
712
+ if (seq !== 0n || isEof) {
713
+ throw new DecryptionError(`Expected non-streaming seq=0 data frame, got seq=${seq} eof=${isEof}`);
714
+ }
715
+ let decrypted;
716
+ try {
717
+ decrypted = JSON.parse(plaintext.toString("utf8"));
718
+ }
719
+ catch {
720
+ throw new DecryptionError("Decrypted response is not valid UTF-8 JSON");
721
+ }
722
+ if (this.endpoint === "chat_completions") {
723
+ if (!Array.isArray(decrypted)) {
724
+ throw new DecryptionError("chat_completions decrypted payload must be a choices array");
725
+ }
726
+ return { ...outerResponse, choices: decrypted };
727
+ }
728
+ if (!decrypted || typeof decrypted !== "object" || Array.isArray(decrypted)) {
729
+ throw new DecryptionError(`${this.endpoint} decrypted payload must be a JSON object`);
730
+ }
731
+ const out = { ...decrypted };
732
+ if (outerResponse.model !== undefined && outerResponse.model !== null) {
733
+ out.model = outerResponse.model;
734
+ }
735
+ if (out.usage == null && outerResponse.usage !== undefined && outerResponse.usage !== null) {
736
+ out.usage = outerResponse.usage;
737
+ }
738
+ return out;
739
+ }
740
+ decryptSseStream(sseText) {
741
+ const dec = this.createStreamDecryptor();
742
+ const result = {
743
+ endpoint: this.endpoint,
744
+ items: [],
745
+ finishReason: null,
746
+ framesCount: 0,
747
+ model: null,
748
+ usage: null,
749
+ };
750
+ for (const { event, data: dataStr } of iterSseEvents(sseText)) {
751
+ if (dataStr.trim() === "[DONE]")
752
+ continue;
753
+ let data;
754
+ try {
755
+ data = JSON.parse(dataStr);
756
+ }
757
+ catch {
758
+ throw new DecryptionError("Invalid JSON in SSE event");
759
+ }
760
+ if (!data || typeof data !== "object")
761
+ continue;
762
+ if (this.endpoint === "chat_completions") {
763
+ if (typeof data.model === "string")
764
+ result.model = data.model;
765
+ if (data.usage && typeof data.usage === "object") {
766
+ result.usage = data.usage;
767
+ }
768
+ const choices = data.choices;
769
+ const delta = choices?.[0]?.delta;
770
+ if (delta && typeof delta.content === "string") {
771
+ result.items.push(...dec.feedText(delta.content));
772
+ }
773
+ }
774
+ else if (this.endpoint === "messages") {
775
+ const evType = event ?? (typeof data.type === "string" ? data.type : null);
776
+ if (evType === "message_start" && data.message && typeof data.message === "object") {
777
+ const msg = data.message;
778
+ if (typeof msg.model === "string")
779
+ result.model = msg.model;
780
+ if (msg.usage && typeof msg.usage === "object") {
781
+ result.usage = mergeUsage(result.usage, msg.usage);
782
+ }
783
+ }
784
+ else if (evType === "message_delta") {
785
+ if (data.usage && typeof data.usage === "object") {
786
+ result.usage = mergeUsage(result.usage, data.usage);
787
+ }
788
+ }
789
+ else if (evType === "content_block_delta") {
790
+ const delta = data.delta;
791
+ if (delta?.type === "text_delta" && typeof delta.text === "string") {
792
+ result.items.push(...dec.feedText(delta.text));
793
+ }
794
+ }
795
+ else if (Array.isArray(data.choices) && data.choices.length > 0) {
796
+ if (typeof data.model === "string")
797
+ result.model = data.model;
798
+ if (data.usage && typeof data.usage === "object") {
799
+ result.usage = data.usage;
800
+ }
801
+ const delta = data.choices[0]?.delta;
802
+ if (delta && typeof delta.content === "string") {
803
+ result.items.push(...dec.feedText(delta.content));
804
+ }
805
+ }
806
+ }
807
+ else if (this.endpoint === "responses") {
808
+ const evType = event ?? (typeof data.type === "string" ? data.type : null);
809
+ if (evType === "response.output_text.delta" && typeof data.delta === "string") {
810
+ result.items.push(...dec.feedText(data.delta));
811
+ }
812
+ else if (evType === "response.created" ||
813
+ evType === "response.completed" ||
814
+ evType === "response.incomplete") {
815
+ const respObj = data.response;
816
+ if (respObj && typeof respObj === "object") {
817
+ if (typeof respObj.model === "string")
818
+ result.model = respObj.model;
819
+ if (respObj.usage && typeof respObj.usage === "object") {
820
+ result.usage = respObj.usage;
821
+ }
822
+ }
823
+ }
824
+ else if (Array.isArray(data.choices) && data.choices.length > 0) {
825
+ if (typeof data.model === "string")
826
+ result.model = data.model;
827
+ if (data.usage && typeof data.usage === "object") {
828
+ result.usage = data.usage;
829
+ }
830
+ const delta = data.choices[0]?.delta;
831
+ if (delta && typeof delta.content === "string") {
832
+ result.items.push(...dec.feedText(delta.content));
833
+ }
834
+ }
835
+ }
836
+ }
837
+ const done = dec.finish();
838
+ result.finishReason = done.finishReason;
839
+ result.framesCount = done.framesCount;
840
+ return result;
841
+ }
842
+ }
843
+ export function encryptRequest(endpoint, innerRequest, options) {
844
+ const model = innerRequest.model;
845
+ if (typeof model !== "string" || !model) {
846
+ throw new E2EEError("innerRequest must contain a non-empty string 'model'");
847
+ }
848
+ const stream = Boolean(innerRequest.stream);
849
+ const pkR = typeof options.publicKey === "string"
850
+ ? b64uDecode(options.publicKey)
851
+ : Buffer.from(options.publicKey);
852
+ if (pkR.length !== 32) {
853
+ throw new E2EEError("Server X25519 public key must be 32 bytes");
854
+ }
855
+ const innerPayload = { ...innerRequest };
856
+ if (endpoint === "responses" || endpoint === "messages") {
857
+ innerPayload._zro_api = endpoint;
858
+ }
859
+ else if (innerPayload._zro_api === undefined) {
860
+ innerPayload._zro_api = "chat_completions";
861
+ }
862
+ const pt = Buffer.from(JSON.stringify(innerPayload), "utf8");
863
+ const info = Buffer.from(`${REQ_INFO_PREFIX}${options.kid}`, "utf8");
864
+ const { enc, ctx } = setupBaseS(pkR, info, {
865
+ aeadId: AEAD_AES_256_GCM,
866
+ ikmE: options.ikmE,
867
+ });
868
+ const ct = ctx.seal(REQ_AAD, pt);
869
+ const envelope = `${PROTOCOL_PREFIX}${options.kid}:${b64uEncode(enc)}:${b64uEncode(ct)}`;
870
+ const respKey = ctx.exportSecret(RESP_KEY_EXPORT_LABEL, 32);
871
+ const respIv = ctx.exportSecret(RESP_IV_EXPORT_LABEL, 12);
872
+ let outerRequest;
873
+ if (endpoint === "chat_completions") {
874
+ outerRequest = {
875
+ model,
876
+ stream,
877
+ messages: [{ role: "user", content: envelope }],
878
+ };
879
+ }
880
+ else if (endpoint === "responses") {
881
+ outerRequest = {
882
+ model,
883
+ stream,
884
+ input: envelope,
885
+ };
886
+ }
887
+ else {
888
+ outerRequest = {
889
+ model,
890
+ max_tokens: options.outerMaxTokens ?? 1,
891
+ stream,
892
+ messages: [{ role: "user", content: envelope }],
893
+ };
894
+ }
895
+ if (options.outerReasoningEffort !== undefined) {
896
+ outerRequest.reasoning_effort = options.outerReasoningEffort;
897
+ }
898
+ const session = new E2EESession({
899
+ endpoint,
900
+ kid: options.kid,
901
+ enc,
902
+ respKey,
903
+ respIv,
904
+ });
905
+ return { outerRequest, session };
906
+ }
907
+ //# sourceMappingURL=e2ee.js.map