pendra 0.23.0 → 0.24.0

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/index.mjs CHANGED
@@ -160,10 +160,14 @@ import { extract as extract2, expand as expand2 } from "@noble/hashes/hkdf.js";
160
160
  import { x25519 } from "@noble/curves/ed25519.js";
161
161
  import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
162
162
  import { sha256 } from "@noble/hashes/sha2.js";
163
+ import { sha3_256, shake256 } from "@noble/hashes/sha3.js";
164
+ import { ml_kem768 } from "@noble/post-quantum/ml-kem.js";
163
165
  import { hmac } from "@noble/hashes/hmac.js";
164
166
  import { extract, expand } from "@noble/hashes/hkdf.js";
165
167
  import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
166
- var KEM_ID = 32;
168
+ var KEM_DHKEM_X25519 = 32;
169
+ var KEM_XWING = 25722;
170
+ var KEM_ID = KEM_DHKEM_X25519;
167
171
  var KDF_ID = 1;
168
172
  var AEAD_ID = 3;
169
173
  var NH = 32;
@@ -193,9 +197,19 @@ function concat(...parts) {
193
197
  }
194
198
  return out;
195
199
  }
196
- var SUITE_ID = concat(bytes("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
200
+ function suiteId(kemId) {
201
+ return concat(bytes("HPKE"), i2osp(kemId, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
202
+ }
203
+ var SUITE_ID = suiteId(KEM_DHKEM_X25519);
204
+ var XWING_SUITE_ID = suiteId(KEM_XWING);
197
205
  var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
198
206
  var HPKE_VERSION = bytes("HPKE-v1");
207
+ var X25519_PUBLIC_KEY_SIZE = 32;
208
+ var MLKEM768_EK_SIZE = 1184;
209
+ var MLKEM768_CT_SIZE = 1088;
210
+ var XWING_PUBLIC_KEY_SIZE = MLKEM768_EK_SIZE + 32;
211
+ var XWING_ENC_SIZE = MLKEM768_CT_SIZE + 32;
212
+ var XWING_LABEL = bytes("\\.//^\\");
199
213
  function hkdfExtract(salt, ikm) {
200
214
  const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
201
215
  return extract(sha256, ikm, effectiveSalt);
@@ -203,11 +217,11 @@ function hkdfExtract(salt, ikm) {
203
217
  function hkdfExpand(prk, info, length) {
204
218
  return expand(sha256, prk, info, length);
205
219
  }
206
- function labeledExtract(salt, label, ikm, suiteId) {
207
- return hkdfExtract(salt, concat(HPKE_VERSION, suiteId, label, ikm));
220
+ function labeledExtract(salt, label, ikm, suiteId2) {
221
+ return hkdfExtract(salt, concat(HPKE_VERSION, suiteId2, label, ikm));
208
222
  }
209
- function labeledExpand(prk, label, info, length, suiteId) {
210
- const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId, label, info);
223
+ function labeledExpand(prk, label, info, length, suiteId2) {
224
+ const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId2, label, info);
211
225
  return hkdfExpand(prk, labeledInfo, length);
212
226
  }
213
227
  function extractAndExpand(dh, kemContext) {
@@ -221,12 +235,34 @@ function encap(pkR, skE) {
221
235
  const kemContext = concat(enc, pkR);
222
236
  return [extractAndExpand(dh, kemContext), enc];
223
237
  }
238
+ function xwingCombine(ssPq, ssT, ctT, pkT) {
239
+ return sha3_256(concat(ssPq, ssT, ctT, pkT, XWING_LABEL));
240
+ }
241
+ function validateXWingPublicKey(pk) {
242
+ if (pk.length !== XWING_PUBLIC_KEY_SIZE) {
243
+ throw new Error(`X-Wing public key must be ${XWING_PUBLIC_KEY_SIZE} bytes, got ${pk.length}`);
244
+ }
245
+ ml_kem768.encapsulate(pk.subarray(0, MLKEM768_EK_SIZE));
246
+ }
247
+ function xwingEncap(pk, skE, pqRandomness) {
248
+ if (pk.length !== XWING_PUBLIC_KEY_SIZE) {
249
+ throw new Error(`X-Wing public key must be ${XWING_PUBLIC_KEY_SIZE} bytes, got ${pk.length}`);
250
+ }
251
+ const pkPq = pk.subarray(0, MLKEM768_EK_SIZE);
252
+ const pkT = pk.subarray(MLKEM768_EK_SIZE);
253
+ const skEObj = skE ?? x25519.utils.randomSecretKey();
254
+ const ssT = x25519.getSharedSecret(skEObj, pkT);
255
+ const ctT = x25519.getPublicKey(skEObj);
256
+ const { cipherText: ctPq, sharedSecret: ssPq } = ml_kem768.encapsulate(pkPq, pqRandomness);
257
+ return [xwingCombine(ssPq, ssT, ctT, pkT), concat(ctPq, ctT)];
258
+ }
224
259
  var Context = class {
225
- constructor(key, baseNonce, exporterSecret) {
260
+ constructor(key, baseNonce, exporterSecret, suite = SUITE_ID) {
226
261
  this.seq = 0;
227
262
  this.key = key;
228
263
  this.baseNonce = baseNonce;
229
264
  this.exporterSecret = exporterSecret;
265
+ this.suiteId = suite;
230
266
  }
231
267
  computeNonce() {
232
268
  const seqBytes = i2osp(this.seq, NN);
@@ -247,23 +283,32 @@ var Context = class {
247
283
  return pt;
248
284
  }
249
285
  export(exporterContext, length) {
250
- return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, SUITE_ID);
286
+ return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, this.suiteId);
251
287
  }
252
288
  };
253
- function keySchedule(sharedSecret, info) {
289
+ function keySchedule(sharedSecret, info, suite = SUITE_ID) {
254
290
  const empty = new Uint8Array(0);
255
- const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, SUITE_ID);
256
- const infoHash = labeledExtract(empty, bytes("info_hash"), info, SUITE_ID);
291
+ const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, suite);
292
+ const infoHash = labeledExtract(empty, bytes("info_hash"), info, suite);
257
293
  const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
258
- const secret = labeledExtract(sharedSecret, bytes("secret"), empty, SUITE_ID);
259
- const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, SUITE_ID);
260
- const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, SUITE_ID);
261
- const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, SUITE_ID);
262
- return new Context(key, baseNonce, exporterSecret);
263
- }
264
- function setupBaseS(pkR, info, skE) {
265
- const [sharedSecret, enc] = encap(pkR, skE);
266
- return { enc, ctx: keySchedule(sharedSecret, info) };
294
+ const secret = labeledExtract(sharedSecret, bytes("secret"), empty, suite);
295
+ const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, suite);
296
+ const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, suite);
297
+ const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, suite);
298
+ return new Context(key, baseNonce, exporterSecret, suite);
299
+ }
300
+ function setupBaseS(pkR, info, skE, pqRandomness) {
301
+ if (pkR.length === X25519_PUBLIC_KEY_SIZE) {
302
+ const [sharedSecret, enc] = encap(pkR, skE);
303
+ return { enc, ctx: keySchedule(sharedSecret, info, SUITE_ID) };
304
+ }
305
+ if (pkR.length === XWING_PUBLIC_KEY_SIZE) {
306
+ const [sharedSecret, enc] = xwingEncap(pkR, skE, pqRandomness);
307
+ return { enc, ctx: keySchedule(sharedSecret, info, XWING_SUITE_ID) };
308
+ }
309
+ throw new Error(
310
+ `HPKE recipient key is ${pkR.length} bytes; expected ${X25519_PUBLIC_KEY_SIZE} (X25519) or ${XWING_PUBLIC_KEY_SIZE} (X-Wing)`
311
+ );
267
312
  }
268
313
  function randomBytes(n) {
269
314
  return nobleRandomBytes(n);
@@ -343,6 +388,11 @@ function sealRequest(orgPubs, body, opts) {
343
388
  const seen = /* @__PURE__ */ new Set();
344
389
  const uniquePubs = [];
345
390
  for (const p of pubs) {
391
+ if (p.length !== X25519_PUBLIC_KEY_SIZE && p.length !== XWING_PUBLIC_KEY_SIZE) {
392
+ throw new Error(
393
+ `sealRequest: org public key is ${p.length} bytes; expected ${X25519_PUBLIC_KEY_SIZE} (X25519) or ${XWING_PUBLIC_KEY_SIZE} (X-Wing)`
394
+ );
395
+ }
346
396
  const fp = fingerprint(p);
347
397
  if (!seen.has(fp)) {
348
398
  seen.add(fp);
@@ -1781,7 +1831,7 @@ var Rerank = class {
1781
1831
  };
1782
1832
 
1783
1833
  // src/version.ts
1784
- var VERSION = "0.23.0";
1834
+ var VERSION = "0.24.0";
1785
1835
  var USER_AGENT = `pendra-node/${VERSION}`;
1786
1836
 
1787
1837
  // src/_privateInferenceEngine.ts
@@ -1810,6 +1860,41 @@ function parsePinnedFingerprints(pin) {
1810
1860
  }
1811
1861
  return new Set(fps);
1812
1862
  }
1863
+ var B64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
1864
+ function warnIgnoredCompanion(reason) {
1865
+ console.warn(`pendra: ignoring a post-quantum key from the server (${reason}); using the classical key.`);
1866
+ }
1867
+ function parseCompanion(entry) {
1868
+ const none = { pqPub: null, pqFp: null };
1869
+ const raw = entry.pq_public_key;
1870
+ if (raw === void 0 || raw === null) return none;
1871
+ if (typeof raw !== "string" || raw.length % 4 !== 0 || !B64_RE.test(raw)) {
1872
+ warnIgnoredCompanion("not valid base64");
1873
+ return none;
1874
+ }
1875
+ const pqPub = b64d2(raw);
1876
+ if (pqPub.length !== XWING_PUBLIC_KEY_SIZE) {
1877
+ warnIgnoredCompanion(`${pqPub.length} bytes, expected ${XWING_PUBLIC_KEY_SIZE}`);
1878
+ return none;
1879
+ }
1880
+ const pqFp = fingerprint(pqPub);
1881
+ const claimed = entry.pq_fingerprint;
1882
+ if (typeof claimed !== "string" || claimed.toLowerCase() !== pqFp) {
1883
+ warnIgnoredCompanion(`its fingerprint (${String(claimed)}) doesn't match its bytes (${pqFp})`);
1884
+ return none;
1885
+ }
1886
+ try {
1887
+ validateXWingPublicKey(pqPub);
1888
+ } catch (e) {
1889
+ warnIgnoredCompanion(String(e instanceof Error ? e.message : e));
1890
+ return none;
1891
+ }
1892
+ return { pqPub, pqFp };
1893
+ }
1894
+ function hybridOnlyIfAny(selected) {
1895
+ const hybrid = selected.filter((s) => s.pub.length === XWING_PUBLIC_KEY_SIZE);
1896
+ return hybrid.length > 0 ? hybrid : selected;
1897
+ }
1813
1898
  function defaultTofuPath() {
1814
1899
  const env = typeof process !== "undefined" ? process.env : void 0;
1815
1900
  if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
@@ -1879,11 +1964,17 @@ var PrivateInferenceEngine = class {
1879
1964
  }
1880
1965
  /**
1881
1966
  * Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
1882
- * allowlist (or auto-trust TOFU), cache the accepted public keys, and return
1967
+ * allowlist (or auto-trust TOFU), cache the selected public keys, and return
1883
1968
  * them (newest-seen first). The client seals to **all** of the returned keys
1884
- * so any worker holding any of them can serve the request. Throws
1885
- * PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
1886
- * intersection with the pin set.
1969
+ * so any worker holding any of them can serve the request.
1970
+ *
1971
+ * A key may carry a post-quantum X-Wing companion (`pq_public_key`). Each key
1972
+ * contributes its companion when it has a valid one the client may use, else
1973
+ * its classical key; and if any selected key is a companion, only companions
1974
+ * are sealed to (see `hybridOnlyIfAny`).
1975
+ *
1976
+ * Throws PrivateInferenceError on absence, a malformed key, or (when pinned)
1977
+ * an empty intersection with the pin set.
1887
1978
  */
1888
1979
  async resolveOrgKey(fetchedKeys) {
1889
1980
  if (this.orgPubs !== null) return this.orgPubs;
@@ -1892,8 +1983,7 @@ var PrivateInferenceEngine = class {
1892
1983
  "No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
1893
1984
  );
1894
1985
  }
1895
- const pubs = [];
1896
- const fps = [];
1986
+ const keys = [];
1897
1987
  for (const entry of fetchedKeys) {
1898
1988
  let pub;
1899
1989
  try {
@@ -1901,32 +1991,46 @@ var PrivateInferenceEngine = class {
1901
1991
  } catch (e) {
1902
1992
  throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
1903
1993
  }
1904
- if (pub.length !== 32) {
1994
+ if (pub.length !== X25519_PUBLIC_KEY_SIZE) {
1905
1995
  throw new PrivateInferenceError(
1906
1996
  `Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
1907
1997
  );
1908
1998
  }
1909
- pubs.push(pub);
1910
- fps.push(fingerprint(pub));
1999
+ keys.push({ pub, fp: fingerprint(pub), ...parseCompanion(entry) });
1911
2000
  }
1912
- let accepted;
2001
+ let selected;
1913
2002
  if (this.pinnedFingerprints !== null) {
1914
- accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
1915
- if (accepted.length === 0) {
1916
- const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
2003
+ const pins = this.pinnedFingerprints;
2004
+ selected = [];
2005
+ for (const k of keys) {
2006
+ if (k.pqPub !== null && k.pqFp !== null && pins.has(k.pqFp)) {
2007
+ selected.push({ pub: k.pqPub, fp: k.pqFp });
2008
+ } else if (pins.has(k.fp)) {
2009
+ selected.push({ pub: k.pub, fp: k.fp });
2010
+ }
2011
+ }
2012
+ if (selected.length === 0) {
2013
+ const offered = [...keys.map((k) => k.fp), ...keys.flatMap((k) => k.pqFp ? [k.pqFp] : [])];
2014
+ const pinned = Array.from(pins).sort().join(", ");
1917
2015
  throw new PrivateInferenceError(
1918
- `None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
2016
+ `None of the org's workload key fingerprints (${offered.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
1919
2017
  );
1920
2018
  }
1921
2019
  } else {
2020
+ selected = keys.map(
2021
+ (k) => k.pqPub !== null && k.pqFp !== null ? { pub: k.pqPub, fp: k.pqFp } : { pub: k.pub, fp: k.fp }
2022
+ );
2023
+ }
2024
+ selected = hybridOnlyIfAny(selected);
2025
+ if (this.pinnedFingerprints === null) {
1922
2026
  try {
1923
- await this.tofuTrust(fps);
2027
+ await this.tofuTrust(selected.map((s) => s.fp));
1924
2028
  } catch (e) {
1925
2029
  if (!isFsError(e)) throw e;
1926
2030
  warnTofuUnwritable(this.tofuPath, e);
1927
2031
  }
1928
- accepted = pubs;
1929
2032
  }
2033
+ const accepted = selected.map((s) => s.pub);
1930
2034
  this.orgPubs = accepted;
1931
2035
  return accepted;
1932
2036
  }