pendra 0.22.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/README.md +59 -14
- package/dist/index.d.mts +20 -4
- package/dist/index.d.ts +20 -4
- package/dist/index.js +442 -308
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +442 -308
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -3
package/dist/index.js
CHANGED
|
@@ -206,10 +206,14 @@ var import_hkdf2 = require("@noble/hashes/hkdf.js");
|
|
|
206
206
|
var import_ed25519 = require("@noble/curves/ed25519.js");
|
|
207
207
|
var import_chacha = require("@noble/ciphers/chacha.js");
|
|
208
208
|
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
209
|
+
var import_sha3 = require("@noble/hashes/sha3.js");
|
|
210
|
+
var import_ml_kem = require("@noble/post-quantum/ml-kem.js");
|
|
209
211
|
var import_hmac = require("@noble/hashes/hmac.js");
|
|
210
212
|
var import_hkdf = require("@noble/hashes/hkdf.js");
|
|
211
213
|
var import_utils = require("@noble/hashes/utils.js");
|
|
212
|
-
var
|
|
214
|
+
var KEM_DHKEM_X25519 = 32;
|
|
215
|
+
var KEM_XWING = 25722;
|
|
216
|
+
var KEM_ID = KEM_DHKEM_X25519;
|
|
213
217
|
var KDF_ID = 1;
|
|
214
218
|
var AEAD_ID = 3;
|
|
215
219
|
var NH = 32;
|
|
@@ -239,9 +243,19 @@ function concat(...parts) {
|
|
|
239
243
|
}
|
|
240
244
|
return out;
|
|
241
245
|
}
|
|
242
|
-
|
|
246
|
+
function suiteId(kemId) {
|
|
247
|
+
return concat(bytes("HPKE"), i2osp(kemId, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2));
|
|
248
|
+
}
|
|
249
|
+
var SUITE_ID = suiteId(KEM_DHKEM_X25519);
|
|
250
|
+
var XWING_SUITE_ID = suiteId(KEM_XWING);
|
|
243
251
|
var KEM_SUITE_ID = concat(bytes("KEM"), i2osp(KEM_ID, 2));
|
|
244
252
|
var HPKE_VERSION = bytes("HPKE-v1");
|
|
253
|
+
var X25519_PUBLIC_KEY_SIZE = 32;
|
|
254
|
+
var MLKEM768_EK_SIZE = 1184;
|
|
255
|
+
var MLKEM768_CT_SIZE = 1088;
|
|
256
|
+
var XWING_PUBLIC_KEY_SIZE = MLKEM768_EK_SIZE + 32;
|
|
257
|
+
var XWING_ENC_SIZE = MLKEM768_CT_SIZE + 32;
|
|
258
|
+
var XWING_LABEL = bytes("\\.//^\\");
|
|
245
259
|
function hkdfExtract(salt, ikm) {
|
|
246
260
|
const effectiveSalt = salt.length === 0 ? new Uint8Array(NH) : salt;
|
|
247
261
|
return (0, import_hkdf.extract)(import_sha2.sha256, ikm, effectiveSalt);
|
|
@@ -249,11 +263,11 @@ function hkdfExtract(salt, ikm) {
|
|
|
249
263
|
function hkdfExpand(prk, info, length) {
|
|
250
264
|
return (0, import_hkdf.expand)(import_sha2.sha256, prk, info, length);
|
|
251
265
|
}
|
|
252
|
-
function labeledExtract(salt, label, ikm,
|
|
253
|
-
return hkdfExtract(salt, concat(HPKE_VERSION,
|
|
266
|
+
function labeledExtract(salt, label, ikm, suiteId2) {
|
|
267
|
+
return hkdfExtract(salt, concat(HPKE_VERSION, suiteId2, label, ikm));
|
|
254
268
|
}
|
|
255
|
-
function labeledExpand(prk, label, info, length,
|
|
256
|
-
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION,
|
|
269
|
+
function labeledExpand(prk, label, info, length, suiteId2) {
|
|
270
|
+
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION, suiteId2, label, info);
|
|
257
271
|
return hkdfExpand(prk, labeledInfo, length);
|
|
258
272
|
}
|
|
259
273
|
function extractAndExpand(dh, kemContext) {
|
|
@@ -267,12 +281,34 @@ function encap(pkR, skE) {
|
|
|
267
281
|
const kemContext = concat(enc, pkR);
|
|
268
282
|
return [extractAndExpand(dh, kemContext), enc];
|
|
269
283
|
}
|
|
284
|
+
function xwingCombine(ssPq, ssT, ctT, pkT) {
|
|
285
|
+
return (0, import_sha3.sha3_256)(concat(ssPq, ssT, ctT, pkT, XWING_LABEL));
|
|
286
|
+
}
|
|
287
|
+
function validateXWingPublicKey(pk) {
|
|
288
|
+
if (pk.length !== XWING_PUBLIC_KEY_SIZE) {
|
|
289
|
+
throw new Error(`X-Wing public key must be ${XWING_PUBLIC_KEY_SIZE} bytes, got ${pk.length}`);
|
|
290
|
+
}
|
|
291
|
+
import_ml_kem.ml_kem768.encapsulate(pk.subarray(0, MLKEM768_EK_SIZE));
|
|
292
|
+
}
|
|
293
|
+
function xwingEncap(pk, skE, pqRandomness) {
|
|
294
|
+
if (pk.length !== XWING_PUBLIC_KEY_SIZE) {
|
|
295
|
+
throw new Error(`X-Wing public key must be ${XWING_PUBLIC_KEY_SIZE} bytes, got ${pk.length}`);
|
|
296
|
+
}
|
|
297
|
+
const pkPq = pk.subarray(0, MLKEM768_EK_SIZE);
|
|
298
|
+
const pkT = pk.subarray(MLKEM768_EK_SIZE);
|
|
299
|
+
const skEObj = skE ?? import_ed25519.x25519.utils.randomSecretKey();
|
|
300
|
+
const ssT = import_ed25519.x25519.getSharedSecret(skEObj, pkT);
|
|
301
|
+
const ctT = import_ed25519.x25519.getPublicKey(skEObj);
|
|
302
|
+
const { cipherText: ctPq, sharedSecret: ssPq } = import_ml_kem.ml_kem768.encapsulate(pkPq, pqRandomness);
|
|
303
|
+
return [xwingCombine(ssPq, ssT, ctT, pkT), concat(ctPq, ctT)];
|
|
304
|
+
}
|
|
270
305
|
var Context = class {
|
|
271
|
-
constructor(key, baseNonce, exporterSecret) {
|
|
306
|
+
constructor(key, baseNonce, exporterSecret, suite = SUITE_ID) {
|
|
272
307
|
this.seq = 0;
|
|
273
308
|
this.key = key;
|
|
274
309
|
this.baseNonce = baseNonce;
|
|
275
310
|
this.exporterSecret = exporterSecret;
|
|
311
|
+
this.suiteId = suite;
|
|
276
312
|
}
|
|
277
313
|
computeNonce() {
|
|
278
314
|
const seqBytes = i2osp(this.seq, NN);
|
|
@@ -293,23 +329,32 @@ var Context = class {
|
|
|
293
329
|
return pt;
|
|
294
330
|
}
|
|
295
331
|
export(exporterContext, length) {
|
|
296
|
-
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length,
|
|
332
|
+
return labeledExpand(this.exporterSecret, bytes("sec"), exporterContext, length, this.suiteId);
|
|
297
333
|
}
|
|
298
334
|
};
|
|
299
|
-
function keySchedule(sharedSecret, info) {
|
|
335
|
+
function keySchedule(sharedSecret, info, suite = SUITE_ID) {
|
|
300
336
|
const empty = new Uint8Array(0);
|
|
301
|
-
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty,
|
|
302
|
-
const infoHash = labeledExtract(empty, bytes("info_hash"), info,
|
|
337
|
+
const pskIdHash = labeledExtract(empty, bytes("psk_id_hash"), empty, suite);
|
|
338
|
+
const infoHash = labeledExtract(empty, bytes("info_hash"), info, suite);
|
|
303
339
|
const keyScheduleContext = concat(new Uint8Array([0]), pskIdHash, infoHash);
|
|
304
|
-
const secret = labeledExtract(sharedSecret, bytes("secret"), empty,
|
|
305
|
-
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK,
|
|
306
|
-
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN,
|
|
307
|
-
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH,
|
|
308
|
-
return new Context(key, baseNonce, exporterSecret);
|
|
309
|
-
}
|
|
310
|
-
function setupBaseS(pkR, info, skE) {
|
|
311
|
-
|
|
312
|
-
|
|
340
|
+
const secret = labeledExtract(sharedSecret, bytes("secret"), empty, suite);
|
|
341
|
+
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK, suite);
|
|
342
|
+
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN, suite);
|
|
343
|
+
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH, suite);
|
|
344
|
+
return new Context(key, baseNonce, exporterSecret, suite);
|
|
345
|
+
}
|
|
346
|
+
function setupBaseS(pkR, info, skE, pqRandomness) {
|
|
347
|
+
if (pkR.length === X25519_PUBLIC_KEY_SIZE) {
|
|
348
|
+
const [sharedSecret, enc] = encap(pkR, skE);
|
|
349
|
+
return { enc, ctx: keySchedule(sharedSecret, info, SUITE_ID) };
|
|
350
|
+
}
|
|
351
|
+
if (pkR.length === XWING_PUBLIC_KEY_SIZE) {
|
|
352
|
+
const [sharedSecret, enc] = xwingEncap(pkR, skE, pqRandomness);
|
|
353
|
+
return { enc, ctx: keySchedule(sharedSecret, info, XWING_SUITE_ID) };
|
|
354
|
+
}
|
|
355
|
+
throw new Error(
|
|
356
|
+
`HPKE recipient key is ${pkR.length} bytes; expected ${X25519_PUBLIC_KEY_SIZE} (X25519) or ${XWING_PUBLIC_KEY_SIZE} (X-Wing)`
|
|
357
|
+
);
|
|
313
358
|
}
|
|
314
359
|
function randomBytes(n) {
|
|
315
360
|
return (0, import_utils.randomBytes)(n);
|
|
@@ -389,6 +434,11 @@ function sealRequest(orgPubs, body, opts) {
|
|
|
389
434
|
const seen = /* @__PURE__ */ new Set();
|
|
390
435
|
const uniquePubs = [];
|
|
391
436
|
for (const p of pubs) {
|
|
437
|
+
if (p.length !== X25519_PUBLIC_KEY_SIZE && p.length !== XWING_PUBLIC_KEY_SIZE) {
|
|
438
|
+
throw new Error(
|
|
439
|
+
`sealRequest: org public key is ${p.length} bytes; expected ${X25519_PUBLIC_KEY_SIZE} (X25519) or ${XWING_PUBLIC_KEY_SIZE} (X-Wing)`
|
|
440
|
+
);
|
|
441
|
+
}
|
|
392
442
|
const fp = fingerprint(p);
|
|
393
443
|
if (!seen.has(fp)) {
|
|
394
444
|
seen.add(fp);
|
|
@@ -778,243 +828,9 @@ function chunkPlacement(chunk) {
|
|
|
778
828
|
}
|
|
779
829
|
var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
|
|
780
830
|
|
|
781
|
-
// src/_privateInferenceEngine.ts
|
|
782
|
-
var PrivateInferenceError = class extends Error {
|
|
783
|
-
constructor(message) {
|
|
784
|
-
super(message);
|
|
785
|
-
this.name = "PrivateInferenceError";
|
|
786
|
-
}
|
|
787
|
-
};
|
|
788
|
-
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
789
|
-
function parsePinnedFingerprints(pin) {
|
|
790
|
-
if (typeof pin !== "string") {
|
|
791
|
-
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
792
|
-
}
|
|
793
|
-
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
794
|
-
if (fps.length === 0) {
|
|
795
|
-
throw new PrivateInferenceError(
|
|
796
|
-
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
797
|
-
);
|
|
798
|
-
}
|
|
799
|
-
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
800
|
-
if (bad.length > 0) {
|
|
801
|
-
throw new PrivateInferenceError(
|
|
802
|
-
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
803
|
-
);
|
|
804
|
-
}
|
|
805
|
-
return new Set(fps);
|
|
806
|
-
}
|
|
807
|
-
function defaultTofuPath() {
|
|
808
|
-
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
809
|
-
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
810
|
-
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
811
|
-
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
812
|
-
}
|
|
813
|
-
function isFsError(e) {
|
|
814
|
-
const err = e;
|
|
815
|
-
return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
|
|
816
|
-
}
|
|
817
|
-
var warnedTofuPaths = /* @__PURE__ */ new Set();
|
|
818
|
-
function warnTofuUnwritable(tofuPath, e) {
|
|
819
|
-
if (warnedTofuPaths.has(tofuPath)) return;
|
|
820
|
-
warnedTofuPaths.add(tofuPath);
|
|
821
|
-
console.warn(
|
|
822
|
-
`pendra: could not update the private-inference trust store at ${tofuPath} (${e.message}). Continuing: the store only records trusted key fingerprints and requests are still encrypted. Set PENDRA_TOFU_PATH to a writable file to silence this warning.`
|
|
823
|
-
);
|
|
824
|
-
}
|
|
825
|
-
function b64d2(s) {
|
|
826
|
-
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
827
|
-
const binary = atob(s);
|
|
828
|
-
const out = new Uint8Array(binary.length);
|
|
829
|
-
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
830
|
-
return out;
|
|
831
|
-
}
|
|
832
|
-
var PrivateInferenceEngine = class {
|
|
833
|
-
constructor(opts) {
|
|
834
|
-
this.orgPubs = null;
|
|
835
|
-
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
836
|
-
this.apiKey = opts.apiKey;
|
|
837
|
-
const pin = opts.pinnedFingerprint;
|
|
838
|
-
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
839
|
-
this.affinitySalt = opts.affinitySalt ?? null;
|
|
840
|
-
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
841
|
-
}
|
|
842
|
-
// --- key resolution ---
|
|
843
|
-
cachedOrgPublicKeys() {
|
|
844
|
-
return this.orgPubs;
|
|
845
|
-
}
|
|
846
|
-
cachedOrgPublicKey() {
|
|
847
|
-
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
848
|
-
}
|
|
849
|
-
tofuIdentity() {
|
|
850
|
-
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
851
|
-
return `${this.baseUrl}|${digest}`;
|
|
852
|
-
}
|
|
853
|
-
/**
|
|
854
|
-
* Drop the cached key set so the next call re-fetches it.
|
|
855
|
-
*
|
|
856
|
-
* The cache is otherwise held for the whole process lifetime, which is
|
|
857
|
-
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
858
|
-
* long-running server would go on sealing to a fingerprint no worker holds
|
|
859
|
-
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
860
|
-
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
861
|
-
* lets the client recover on its own.
|
|
862
|
-
*
|
|
863
|
-
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
864
|
-
* allowlist, so a fetch could only return fingerprints the pin already
|
|
865
|
-
* rejects. They surface the error instead, which is what pinning means.
|
|
866
|
-
*/
|
|
867
|
-
invalidateOrgKey() {
|
|
868
|
-
this.orgPubs = null;
|
|
869
|
-
}
|
|
870
|
-
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
871
|
-
get isPinned() {
|
|
872
|
-
return this.pinnedFingerprints !== null;
|
|
873
|
-
}
|
|
874
|
-
/**
|
|
875
|
-
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
876
|
-
* allowlist (or auto-trust TOFU), cache the accepted public keys, and return
|
|
877
|
-
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
878
|
-
* so any worker holding any of them can serve the request. Throws
|
|
879
|
-
* PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
|
|
880
|
-
* intersection with the pin set.
|
|
881
|
-
*/
|
|
882
|
-
async resolveOrgKey(fetchedKeys) {
|
|
883
|
-
if (this.orgPubs !== null) return this.orgPubs;
|
|
884
|
-
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
885
|
-
throw new PrivateInferenceError(
|
|
886
|
-
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
887
|
-
);
|
|
888
|
-
}
|
|
889
|
-
const pubs = [];
|
|
890
|
-
const fps = [];
|
|
891
|
-
for (const entry of fetchedKeys) {
|
|
892
|
-
let pub;
|
|
893
|
-
try {
|
|
894
|
-
pub = b64d2(entry.public_key);
|
|
895
|
-
} catch (e) {
|
|
896
|
-
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
897
|
-
}
|
|
898
|
-
if (pub.length !== 32) {
|
|
899
|
-
throw new PrivateInferenceError(
|
|
900
|
-
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
901
|
-
);
|
|
902
|
-
}
|
|
903
|
-
pubs.push(pub);
|
|
904
|
-
fps.push(fingerprint(pub));
|
|
905
|
-
}
|
|
906
|
-
let accepted;
|
|
907
|
-
if (this.pinnedFingerprints !== null) {
|
|
908
|
-
accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
|
|
909
|
-
if (accepted.length === 0) {
|
|
910
|
-
const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
|
|
911
|
-
throw new PrivateInferenceError(
|
|
912
|
-
`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.`
|
|
913
|
-
);
|
|
914
|
-
}
|
|
915
|
-
} else {
|
|
916
|
-
try {
|
|
917
|
-
await this.tofuTrust(fps);
|
|
918
|
-
} catch (e) {
|
|
919
|
-
if (!isFsError(e)) throw e;
|
|
920
|
-
warnTofuUnwritable(this.tofuPath, e);
|
|
921
|
-
}
|
|
922
|
-
accepted = pubs;
|
|
923
|
-
}
|
|
924
|
-
this.orgPubs = accepted;
|
|
925
|
-
return accepted;
|
|
926
|
-
}
|
|
927
|
-
async tofuTrust(fps) {
|
|
928
|
-
const store = await this.loadTofu();
|
|
929
|
-
const identity = this.tofuIdentity();
|
|
930
|
-
const known = store[identity];
|
|
931
|
-
const trusted = /* @__PURE__ */ new Set();
|
|
932
|
-
if (typeof known === "string") {
|
|
933
|
-
trusted.add(known);
|
|
934
|
-
} else if (Array.isArray(known)) {
|
|
935
|
-
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
936
|
-
}
|
|
937
|
-
const before = trusted.size;
|
|
938
|
-
for (const f of fps) trusted.add(f);
|
|
939
|
-
if (trusted.size !== before || !Array.isArray(known)) {
|
|
940
|
-
store[identity] = Array.from(trusted).sort();
|
|
941
|
-
await this.saveTofu(store);
|
|
942
|
-
}
|
|
943
|
-
}
|
|
944
|
-
async loadTofu() {
|
|
945
|
-
const fs = await import("fs");
|
|
946
|
-
let raw;
|
|
947
|
-
try {
|
|
948
|
-
raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
949
|
-
} catch (e) {
|
|
950
|
-
if (e.code === "ENOENT") return {};
|
|
951
|
-
throw e;
|
|
952
|
-
}
|
|
953
|
-
let data;
|
|
954
|
-
try {
|
|
955
|
-
data = JSON.parse(raw);
|
|
956
|
-
} catch {
|
|
957
|
-
return {};
|
|
958
|
-
}
|
|
959
|
-
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
960
|
-
}
|
|
961
|
-
async saveTofu(store) {
|
|
962
|
-
const fs = await import("fs");
|
|
963
|
-
const path = await import("path");
|
|
964
|
-
const directory = path.dirname(this.tofuPath) || ".";
|
|
965
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
966
|
-
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
967
|
-
try {
|
|
968
|
-
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
969
|
-
try {
|
|
970
|
-
fs.chmodSync(tmp, 384);
|
|
971
|
-
} catch {
|
|
972
|
-
}
|
|
973
|
-
fs.renameSync(tmp, this.tofuPath);
|
|
974
|
-
} catch (e) {
|
|
975
|
-
try {
|
|
976
|
-
fs.unlinkSync(tmp);
|
|
977
|
-
} catch {
|
|
978
|
-
}
|
|
979
|
-
throw e;
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
// --- sealing ---
|
|
983
|
-
/**
|
|
984
|
-
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
985
|
-
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
986
|
-
* `binary` (audio only) is sealed under the same data key as the body.
|
|
987
|
-
*/
|
|
988
|
-
seal(args) {
|
|
989
|
-
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
990
|
-
throw new PrivateInferenceError(
|
|
991
|
-
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
992
|
-
);
|
|
993
|
-
}
|
|
994
|
-
let affinity = null;
|
|
995
|
-
if (args.messages != null) {
|
|
996
|
-
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
997
|
-
}
|
|
998
|
-
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
999
|
-
model: args.model,
|
|
1000
|
-
stream: args.stream,
|
|
1001
|
-
taskType: args.taskType,
|
|
1002
|
-
affinityKey: affinity,
|
|
1003
|
-
binary: args.binary ?? null
|
|
1004
|
-
});
|
|
1005
|
-
const topLevel = {
|
|
1006
|
-
model: args.model,
|
|
1007
|
-
stream: args.stream,
|
|
1008
|
-
pendra_encrypted: envelope
|
|
1009
|
-
};
|
|
1010
|
-
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
1011
|
-
}
|
|
1012
|
-
get keyFetchUrl() {
|
|
1013
|
-
return `${this.baseUrl}/v1/private-inference/key`;
|
|
1014
|
-
}
|
|
1015
|
-
};
|
|
1016
|
-
|
|
1017
831
|
// src/resources/audio/speech.ts
|
|
832
|
+
var ENCODER = new TextEncoder();
|
|
833
|
+
var DECODER = new TextDecoder();
|
|
1018
834
|
var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
1019
835
|
function decodeAudio(value) {
|
|
1020
836
|
if (typeof value !== "string") return void 0;
|
|
@@ -1057,15 +873,15 @@ var Speech = class {
|
|
|
1057
873
|
if (typeof params.input !== "string" || !params.input.trim()) {
|
|
1058
874
|
throw new Error("input must be a non-empty string");
|
|
1059
875
|
}
|
|
1060
|
-
if (this.client.privateInferenceEnabled) {
|
|
1061
|
-
throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
|
|
1062
|
-
}
|
|
1063
876
|
const body = { model: params.model, input: params.input };
|
|
1064
877
|
if (params.voice != null) body.voice = params.voice;
|
|
1065
878
|
if (params.response_format != null) body.response_format = params.response_format;
|
|
1066
879
|
const headers = { Accept: "application/json" };
|
|
1067
880
|
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
1068
881
|
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
882
|
+
if (this.client.privateInferenceEnabled) {
|
|
883
|
+
return this.createEncrypted(params, body, timeout);
|
|
884
|
+
}
|
|
1069
885
|
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
1070
886
|
method: "POST",
|
|
1071
887
|
body,
|
|
@@ -1083,29 +899,57 @@ var Speech = class {
|
|
|
1083
899
|
});
|
|
1084
900
|
}
|
|
1085
901
|
throwIfInBandError(parsed, "The server reported an error");
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
902
|
+
return speechFrom(parsed, text, params, response);
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Private-inference speech. The request options are the sealed JSON body;
|
|
906
|
+
* the worker seals the same `{ audio, format, duration_ms }` result a
|
|
907
|
+
* plaintext JSON reply carries, so the audio comes back exactly as it does
|
|
908
|
+
* without encryption.
|
|
909
|
+
*/
|
|
910
|
+
async createEncrypted(params, body, timeout) {
|
|
911
|
+
const engine = await this.client._privateEngine();
|
|
912
|
+
const { topLevel, decryptor } = engine.seal({
|
|
913
|
+
model: params.model,
|
|
914
|
+
stream: false,
|
|
915
|
+
taskType: "speech",
|
|
916
|
+
body: ENCODER.encode(JSON.stringify(body))
|
|
917
|
+
});
|
|
918
|
+
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
919
|
+
method: "POST",
|
|
920
|
+
body: topLevel,
|
|
921
|
+
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
|
|
922
|
+
timeout
|
|
923
|
+
});
|
|
924
|
+
const { inner, placement } = await readSealedReply(response);
|
|
925
|
+
const raw = DECODER.decode(decryptor.openResult(inner));
|
|
926
|
+
const parsed = parseDecryptedJson(raw, response.status);
|
|
927
|
+
return speechFrom(parsed, raw, params, response, placement);
|
|
1107
928
|
}
|
|
1108
929
|
};
|
|
930
|
+
function speechFrom(parsed, raw, params, response, placement) {
|
|
931
|
+
if (!isRecord2(parsed)) {
|
|
932
|
+
throw new APIResponseValidationError("Response was not a speech result", {
|
|
933
|
+
status: response.status,
|
|
934
|
+
body: raw
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
const audio = decodeAudio(parsed.audio);
|
|
938
|
+
if (!audio) {
|
|
939
|
+
throw new APIResponseValidationError("Response did not contain decodable audio", {
|
|
940
|
+
status: response.status,
|
|
941
|
+
body: raw
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
const result = {
|
|
945
|
+
audio,
|
|
946
|
+
format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
|
|
947
|
+
duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
|
|
948
|
+
arrayBuffer: async () => audio.slice().buffer
|
|
949
|
+
};
|
|
950
|
+
if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
|
|
951
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
952
|
+
}
|
|
1109
953
|
|
|
1110
954
|
// src/_sse.ts
|
|
1111
955
|
var DEFAULT_EVENT = "message";
|
|
@@ -1303,8 +1147,8 @@ function releaseReader(reader, controller, finished) {
|
|
|
1303
1147
|
}
|
|
1304
1148
|
|
|
1305
1149
|
// src/resources/audio/transcriptions.ts
|
|
1306
|
-
var
|
|
1307
|
-
var
|
|
1150
|
+
var ENCODER2 = new TextEncoder();
|
|
1151
|
+
var DECODER2 = new TextDecoder();
|
|
1308
1152
|
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
1309
1153
|
var MIME_EXT = {
|
|
1310
1154
|
"audio/mpeg": "mp3",
|
|
@@ -1438,7 +1282,7 @@ var Transcriptions = class {
|
|
|
1438
1282
|
model: params.model,
|
|
1439
1283
|
stream: false,
|
|
1440
1284
|
taskType: "transcription",
|
|
1441
|
-
body:
|
|
1285
|
+
body: ENCODER2.encode(JSON.stringify(body)),
|
|
1442
1286
|
binary: new Uint8Array(await blob.arrayBuffer())
|
|
1443
1287
|
});
|
|
1444
1288
|
const { response } = await this.client._fetch(
|
|
@@ -1451,7 +1295,7 @@ var Transcriptions = class {
|
|
|
1451
1295
|
}
|
|
1452
1296
|
);
|
|
1453
1297
|
const { inner, placement } = await readSealedReply(response);
|
|
1454
|
-
const raw =
|
|
1298
|
+
const raw = DECODER2.decode(decryptor.openResult(inner));
|
|
1455
1299
|
const parsed = parseDecryptedJson(raw, response.status);
|
|
1456
1300
|
const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
|
|
1457
1301
|
if (typeof parsed === "string") return place({ text: parsed });
|
|
@@ -1477,7 +1321,7 @@ var Audio = class {
|
|
|
1477
1321
|
};
|
|
1478
1322
|
|
|
1479
1323
|
// src/_privateStreaming.ts
|
|
1480
|
-
var
|
|
1324
|
+
var DECODER3 = new TextDecoder();
|
|
1481
1325
|
var EncryptedStream = class {
|
|
1482
1326
|
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
1483
1327
|
this.decoder = new TextDecoder();
|
|
@@ -1543,7 +1387,7 @@ var EncryptedStream = class {
|
|
|
1543
1387
|
);
|
|
1544
1388
|
}
|
|
1545
1389
|
const plain = this.decryptor.openChunk(inner);
|
|
1546
|
-
const chunkJson =
|
|
1390
|
+
const chunkJson = DECODER3.decode(plain).trim();
|
|
1547
1391
|
const first = !this.openedAny;
|
|
1548
1392
|
this.openedAny = true;
|
|
1549
1393
|
if (first && isStreamTerminatorDeclaration(chunkJson)) {
|
|
@@ -1597,8 +1441,8 @@ var EncryptedStream = class {
|
|
|
1597
1441
|
};
|
|
1598
1442
|
|
|
1599
1443
|
// src/resources/chat/completions.ts
|
|
1600
|
-
var
|
|
1601
|
-
var
|
|
1444
|
+
var ENCODER3 = new TextEncoder();
|
|
1445
|
+
var DECODER4 = new TextDecoder();
|
|
1602
1446
|
var Completions = class {
|
|
1603
1447
|
constructor(client) {
|
|
1604
1448
|
this.client = client;
|
|
@@ -1639,7 +1483,7 @@ var Completions = class {
|
|
|
1639
1483
|
// The terminator request rides inside the sealed body, so the relay can
|
|
1640
1484
|
// neither strip nor add it: it asks the worker to seal the end of the
|
|
1641
1485
|
// stream (#2157).
|
|
1642
|
-
body:
|
|
1486
|
+
body: ENCODER3.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
|
|
1643
1487
|
messages: params.messages
|
|
1644
1488
|
});
|
|
1645
1489
|
if (stream) {
|
|
@@ -1655,7 +1499,7 @@ var Completions = class {
|
|
|
1655
1499
|
);
|
|
1656
1500
|
const { inner, placement } = await readSealedReply(response);
|
|
1657
1501
|
const plain = decryptor.openResult(inner);
|
|
1658
|
-
const completion = parseDecryptedCompletion(
|
|
1502
|
+
const completion = parseDecryptedCompletion(DECODER4.decode(plain), response.status);
|
|
1659
1503
|
return withPlacement(completion, response.headers, completion.pendra, placement);
|
|
1660
1504
|
}
|
|
1661
1505
|
};
|
|
@@ -1668,8 +1512,8 @@ var Chat = class {
|
|
|
1668
1512
|
};
|
|
1669
1513
|
|
|
1670
1514
|
// src/resources/embeddings.ts
|
|
1671
|
-
var
|
|
1672
|
-
var
|
|
1515
|
+
var ENCODER4 = new TextEncoder();
|
|
1516
|
+
var DECODER5 = new TextDecoder();
|
|
1673
1517
|
function validateParams(params) {
|
|
1674
1518
|
if (!params.model || typeof params.model !== "string") {
|
|
1675
1519
|
throw new Error("model must be a non-empty string");
|
|
@@ -1735,7 +1579,7 @@ var Embeddings = class {
|
|
|
1735
1579
|
model,
|
|
1736
1580
|
stream: false,
|
|
1737
1581
|
taskType: "embeddings",
|
|
1738
|
-
body:
|
|
1582
|
+
body: ENCODER4.encode(JSON.stringify(body))
|
|
1739
1583
|
});
|
|
1740
1584
|
const { response } = await this.client._fetch(
|
|
1741
1585
|
"/api/v1/embeddings",
|
|
@@ -1743,14 +1587,14 @@ var Embeddings = class {
|
|
|
1743
1587
|
);
|
|
1744
1588
|
const { inner, placement } = await readSealedReply(response);
|
|
1745
1589
|
const plain = decryptor.openResult(inner);
|
|
1746
|
-
const result = JSON.parse(
|
|
1590
|
+
const result = JSON.parse(DECODER5.decode(plain));
|
|
1747
1591
|
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1748
1592
|
}
|
|
1749
1593
|
};
|
|
1750
1594
|
|
|
1751
1595
|
// src/resources/images/generations.ts
|
|
1752
|
-
var
|
|
1753
|
-
var
|
|
1596
|
+
var ENCODER5 = new TextEncoder();
|
|
1597
|
+
var DECODER6 = new TextDecoder();
|
|
1754
1598
|
var SIZE_RE = /^\d+x\d+$/;
|
|
1755
1599
|
function validateParams2(params) {
|
|
1756
1600
|
if (!params.prompt || !params.prompt.trim()) {
|
|
@@ -1796,7 +1640,7 @@ var Generations = class {
|
|
|
1796
1640
|
model,
|
|
1797
1641
|
stream: false,
|
|
1798
1642
|
taskType: "image_generation",
|
|
1799
|
-
body:
|
|
1643
|
+
body: ENCODER5.encode(JSON.stringify(body))
|
|
1800
1644
|
});
|
|
1801
1645
|
const { response } = await this.client._fetch(
|
|
1802
1646
|
"/api/v1/images/generations",
|
|
@@ -1804,11 +1648,11 @@ var Generations = class {
|
|
|
1804
1648
|
);
|
|
1805
1649
|
const { inner, placement } = await readSealedReply(response);
|
|
1806
1650
|
const plain = decryptor.openResult(inner);
|
|
1807
|
-
const parsed = parseDecryptedJson(
|
|
1651
|
+
const parsed = parseDecryptedJson(DECODER6.decode(plain), response.status);
|
|
1808
1652
|
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1809
1653
|
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
1810
1654
|
status: response.status,
|
|
1811
|
-
body:
|
|
1655
|
+
body: DECODER6.decode(plain)
|
|
1812
1656
|
});
|
|
1813
1657
|
}
|
|
1814
1658
|
const result = parsed;
|
|
@@ -1838,8 +1682,8 @@ var Models = class {
|
|
|
1838
1682
|
};
|
|
1839
1683
|
|
|
1840
1684
|
// src/resources/moderations.ts
|
|
1841
|
-
var
|
|
1842
|
-
var
|
|
1685
|
+
var ENCODER6 = new TextEncoder();
|
|
1686
|
+
var DECODER7 = new TextDecoder();
|
|
1843
1687
|
var MAX_INPUTS = 32;
|
|
1844
1688
|
function isPlainObject2(v) {
|
|
1845
1689
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -1940,7 +1784,7 @@ var Moderations = class {
|
|
|
1940
1784
|
model,
|
|
1941
1785
|
stream: false,
|
|
1942
1786
|
taskType: "moderation",
|
|
1943
|
-
body:
|
|
1787
|
+
body: ENCODER6.encode(JSON.stringify({ model: body.model, stream: false, input: body.input }))
|
|
1944
1788
|
});
|
|
1945
1789
|
const { response } = await this.client._fetch(
|
|
1946
1790
|
"/api/v1/moderations",
|
|
@@ -1949,7 +1793,7 @@ var Moderations = class {
|
|
|
1949
1793
|
const { inner, placement } = await readSealedReply(response);
|
|
1950
1794
|
const plain = decryptor.openResult(inner);
|
|
1951
1795
|
const result = asModeration(
|
|
1952
|
-
parseDecryptedJson(
|
|
1796
|
+
parseDecryptedJson(DECODER7.decode(plain), response.status),
|
|
1953
1797
|
response.status,
|
|
1954
1798
|
"Decrypted response"
|
|
1955
1799
|
);
|
|
@@ -1958,8 +1802,8 @@ var Moderations = class {
|
|
|
1958
1802
|
};
|
|
1959
1803
|
|
|
1960
1804
|
// src/resources/rerank.ts
|
|
1961
|
-
var
|
|
1962
|
-
var
|
|
1805
|
+
var ENCODER7 = new TextEncoder();
|
|
1806
|
+
var DECODER8 = new TextDecoder();
|
|
1963
1807
|
function validateParams4(params) {
|
|
1964
1808
|
if (!params.model || typeof params.model !== "string") {
|
|
1965
1809
|
throw new Error("model must be a non-empty string");
|
|
@@ -2019,7 +1863,7 @@ var Rerank = class {
|
|
|
2019
1863
|
model,
|
|
2020
1864
|
stream: false,
|
|
2021
1865
|
taskType: "rerank",
|
|
2022
|
-
body:
|
|
1866
|
+
body: ENCODER7.encode(JSON.stringify(body))
|
|
2023
1867
|
});
|
|
2024
1868
|
const { response } = await this.client._fetch(
|
|
2025
1869
|
"/api/v1/rerank",
|
|
@@ -2027,15 +1871,305 @@ var Rerank = class {
|
|
|
2027
1871
|
);
|
|
2028
1872
|
const { inner, placement } = await readSealedReply(response);
|
|
2029
1873
|
const plain = decryptor.openResult(inner);
|
|
2030
|
-
const result = JSON.parse(
|
|
1874
|
+
const result = JSON.parse(DECODER8.decode(plain));
|
|
2031
1875
|
return withPlacement(result, response.headers, result.pendra, placement);
|
|
2032
1876
|
}
|
|
2033
1877
|
};
|
|
2034
1878
|
|
|
2035
1879
|
// src/version.ts
|
|
2036
|
-
var VERSION = "0.
|
|
1880
|
+
var VERSION = "0.24.0";
|
|
2037
1881
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
2038
1882
|
|
|
1883
|
+
// src/_privateInferenceEngine.ts
|
|
1884
|
+
var PrivateInferenceError = class extends Error {
|
|
1885
|
+
constructor(message) {
|
|
1886
|
+
super(message);
|
|
1887
|
+
this.name = "PrivateInferenceError";
|
|
1888
|
+
}
|
|
1889
|
+
};
|
|
1890
|
+
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
1891
|
+
function parsePinnedFingerprints(pin) {
|
|
1892
|
+
if (typeof pin !== "string") {
|
|
1893
|
+
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
1894
|
+
}
|
|
1895
|
+
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
1896
|
+
if (fps.length === 0) {
|
|
1897
|
+
throw new PrivateInferenceError(
|
|
1898
|
+
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
1902
|
+
if (bad.length > 0) {
|
|
1903
|
+
throw new PrivateInferenceError(
|
|
1904
|
+
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
1905
|
+
);
|
|
1906
|
+
}
|
|
1907
|
+
return new Set(fps);
|
|
1908
|
+
}
|
|
1909
|
+
var B64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
1910
|
+
function warnIgnoredCompanion(reason) {
|
|
1911
|
+
console.warn(`pendra: ignoring a post-quantum key from the server (${reason}); using the classical key.`);
|
|
1912
|
+
}
|
|
1913
|
+
function parseCompanion(entry) {
|
|
1914
|
+
const none = { pqPub: null, pqFp: null };
|
|
1915
|
+
const raw = entry.pq_public_key;
|
|
1916
|
+
if (raw === void 0 || raw === null) return none;
|
|
1917
|
+
if (typeof raw !== "string" || raw.length % 4 !== 0 || !B64_RE.test(raw)) {
|
|
1918
|
+
warnIgnoredCompanion("not valid base64");
|
|
1919
|
+
return none;
|
|
1920
|
+
}
|
|
1921
|
+
const pqPub = b64d2(raw);
|
|
1922
|
+
if (pqPub.length !== XWING_PUBLIC_KEY_SIZE) {
|
|
1923
|
+
warnIgnoredCompanion(`${pqPub.length} bytes, expected ${XWING_PUBLIC_KEY_SIZE}`);
|
|
1924
|
+
return none;
|
|
1925
|
+
}
|
|
1926
|
+
const pqFp = fingerprint(pqPub);
|
|
1927
|
+
const claimed = entry.pq_fingerprint;
|
|
1928
|
+
if (typeof claimed !== "string" || claimed.toLowerCase() !== pqFp) {
|
|
1929
|
+
warnIgnoredCompanion(`its fingerprint (${String(claimed)}) doesn't match its bytes (${pqFp})`);
|
|
1930
|
+
return none;
|
|
1931
|
+
}
|
|
1932
|
+
try {
|
|
1933
|
+
validateXWingPublicKey(pqPub);
|
|
1934
|
+
} catch (e) {
|
|
1935
|
+
warnIgnoredCompanion(String(e instanceof Error ? e.message : e));
|
|
1936
|
+
return none;
|
|
1937
|
+
}
|
|
1938
|
+
return { pqPub, pqFp };
|
|
1939
|
+
}
|
|
1940
|
+
function hybridOnlyIfAny(selected) {
|
|
1941
|
+
const hybrid = selected.filter((s) => s.pub.length === XWING_PUBLIC_KEY_SIZE);
|
|
1942
|
+
return hybrid.length > 0 ? hybrid : selected;
|
|
1943
|
+
}
|
|
1944
|
+
function defaultTofuPath() {
|
|
1945
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1946
|
+
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
1947
|
+
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
1948
|
+
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
1949
|
+
}
|
|
1950
|
+
function isFsError(e) {
|
|
1951
|
+
const err = e;
|
|
1952
|
+
return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
|
|
1953
|
+
}
|
|
1954
|
+
var warnedTofuPaths = /* @__PURE__ */ new Set();
|
|
1955
|
+
function warnTofuUnwritable(tofuPath, e) {
|
|
1956
|
+
if (warnedTofuPaths.has(tofuPath)) return;
|
|
1957
|
+
warnedTofuPaths.add(tofuPath);
|
|
1958
|
+
console.warn(
|
|
1959
|
+
`pendra: could not update the private-inference trust store at ${tofuPath} (${e.message}). Continuing: the store only records trusted key fingerprints and requests are still encrypted. Set PENDRA_TOFU_PATH to a writable file to silence this warning.`
|
|
1960
|
+
);
|
|
1961
|
+
}
|
|
1962
|
+
function b64d2(s) {
|
|
1963
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
1964
|
+
const binary = atob(s);
|
|
1965
|
+
const out = new Uint8Array(binary.length);
|
|
1966
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
1967
|
+
return out;
|
|
1968
|
+
}
|
|
1969
|
+
var PrivateInferenceEngine = class {
|
|
1970
|
+
constructor(opts) {
|
|
1971
|
+
this.orgPubs = null;
|
|
1972
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
1973
|
+
this.apiKey = opts.apiKey;
|
|
1974
|
+
const pin = opts.pinnedFingerprint;
|
|
1975
|
+
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
1976
|
+
this.affinitySalt = opts.affinitySalt ?? null;
|
|
1977
|
+
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
1978
|
+
}
|
|
1979
|
+
// --- key resolution ---
|
|
1980
|
+
cachedOrgPublicKeys() {
|
|
1981
|
+
return this.orgPubs;
|
|
1982
|
+
}
|
|
1983
|
+
cachedOrgPublicKey() {
|
|
1984
|
+
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
1985
|
+
}
|
|
1986
|
+
tofuIdentity() {
|
|
1987
|
+
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
1988
|
+
return `${this.baseUrl}|${digest}`;
|
|
1989
|
+
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Drop the cached key set so the next call re-fetches it.
|
|
1992
|
+
*
|
|
1993
|
+
* The cache is otherwise held for the whole process lifetime, which is
|
|
1994
|
+
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
1995
|
+
* long-running server would go on sealing to a fingerprint no worker holds
|
|
1996
|
+
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
1997
|
+
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
1998
|
+
* lets the client recover on its own.
|
|
1999
|
+
*
|
|
2000
|
+
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
2001
|
+
* allowlist, so a fetch could only return fingerprints the pin already
|
|
2002
|
+
* rejects. They surface the error instead, which is what pinning means.
|
|
2003
|
+
*/
|
|
2004
|
+
invalidateOrgKey() {
|
|
2005
|
+
this.orgPubs = null;
|
|
2006
|
+
}
|
|
2007
|
+
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
2008
|
+
get isPinned() {
|
|
2009
|
+
return this.pinnedFingerprints !== null;
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
2013
|
+
* allowlist (or auto-trust TOFU), cache the selected public keys, and return
|
|
2014
|
+
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
2015
|
+
* so any worker holding any of them can serve the request.
|
|
2016
|
+
*
|
|
2017
|
+
* A key may carry a post-quantum X-Wing companion (`pq_public_key`). Each key
|
|
2018
|
+
* contributes its companion when it has a valid one the client may use, else
|
|
2019
|
+
* its classical key; and if any selected key is a companion, only companions
|
|
2020
|
+
* are sealed to (see `hybridOnlyIfAny`).
|
|
2021
|
+
*
|
|
2022
|
+
* Throws PrivateInferenceError on absence, a malformed key, or (when pinned)
|
|
2023
|
+
* an empty intersection with the pin set.
|
|
2024
|
+
*/
|
|
2025
|
+
async resolveOrgKey(fetchedKeys) {
|
|
2026
|
+
if (this.orgPubs !== null) return this.orgPubs;
|
|
2027
|
+
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
2028
|
+
throw new PrivateInferenceError(
|
|
2029
|
+
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
2030
|
+
);
|
|
2031
|
+
}
|
|
2032
|
+
const keys = [];
|
|
2033
|
+
for (const entry of fetchedKeys) {
|
|
2034
|
+
let pub;
|
|
2035
|
+
try {
|
|
2036
|
+
pub = b64d2(entry.public_key);
|
|
2037
|
+
} catch (e) {
|
|
2038
|
+
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
2039
|
+
}
|
|
2040
|
+
if (pub.length !== X25519_PUBLIC_KEY_SIZE) {
|
|
2041
|
+
throw new PrivateInferenceError(
|
|
2042
|
+
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
2043
|
+
);
|
|
2044
|
+
}
|
|
2045
|
+
keys.push({ pub, fp: fingerprint(pub), ...parseCompanion(entry) });
|
|
2046
|
+
}
|
|
2047
|
+
let selected;
|
|
2048
|
+
if (this.pinnedFingerprints !== null) {
|
|
2049
|
+
const pins = this.pinnedFingerprints;
|
|
2050
|
+
selected = [];
|
|
2051
|
+
for (const k of keys) {
|
|
2052
|
+
if (k.pqPub !== null && k.pqFp !== null && pins.has(k.pqFp)) {
|
|
2053
|
+
selected.push({ pub: k.pqPub, fp: k.pqFp });
|
|
2054
|
+
} else if (pins.has(k.fp)) {
|
|
2055
|
+
selected.push({ pub: k.pub, fp: k.fp });
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
if (selected.length === 0) {
|
|
2059
|
+
const offered = [...keys.map((k) => k.fp), ...keys.flatMap((k) => k.pqFp ? [k.pqFp] : [])];
|
|
2060
|
+
const pinned = Array.from(pins).sort().join(", ");
|
|
2061
|
+
throw new PrivateInferenceError(
|
|
2062
|
+
`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.`
|
|
2063
|
+
);
|
|
2064
|
+
}
|
|
2065
|
+
} else {
|
|
2066
|
+
selected = keys.map(
|
|
2067
|
+
(k) => k.pqPub !== null && k.pqFp !== null ? { pub: k.pqPub, fp: k.pqFp } : { pub: k.pub, fp: k.fp }
|
|
2068
|
+
);
|
|
2069
|
+
}
|
|
2070
|
+
selected = hybridOnlyIfAny(selected);
|
|
2071
|
+
if (this.pinnedFingerprints === null) {
|
|
2072
|
+
try {
|
|
2073
|
+
await this.tofuTrust(selected.map((s) => s.fp));
|
|
2074
|
+
} catch (e) {
|
|
2075
|
+
if (!isFsError(e)) throw e;
|
|
2076
|
+
warnTofuUnwritable(this.tofuPath, e);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
const accepted = selected.map((s) => s.pub);
|
|
2080
|
+
this.orgPubs = accepted;
|
|
2081
|
+
return accepted;
|
|
2082
|
+
}
|
|
2083
|
+
async tofuTrust(fps) {
|
|
2084
|
+
const store = await this.loadTofu();
|
|
2085
|
+
const identity = this.tofuIdentity();
|
|
2086
|
+
const known = store[identity];
|
|
2087
|
+
const trusted = /* @__PURE__ */ new Set();
|
|
2088
|
+
if (typeof known === "string") {
|
|
2089
|
+
trusted.add(known);
|
|
2090
|
+
} else if (Array.isArray(known)) {
|
|
2091
|
+
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
2092
|
+
}
|
|
2093
|
+
const before = trusted.size;
|
|
2094
|
+
for (const f of fps) trusted.add(f);
|
|
2095
|
+
if (trusted.size !== before || !Array.isArray(known)) {
|
|
2096
|
+
store[identity] = Array.from(trusted).sort();
|
|
2097
|
+
await this.saveTofu(store);
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
async loadTofu() {
|
|
2101
|
+
const fs = await import("fs");
|
|
2102
|
+
let raw;
|
|
2103
|
+
try {
|
|
2104
|
+
raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
2105
|
+
} catch (e) {
|
|
2106
|
+
if (e.code === "ENOENT") return {};
|
|
2107
|
+
throw e;
|
|
2108
|
+
}
|
|
2109
|
+
let data;
|
|
2110
|
+
try {
|
|
2111
|
+
data = JSON.parse(raw);
|
|
2112
|
+
} catch {
|
|
2113
|
+
return {};
|
|
2114
|
+
}
|
|
2115
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
2116
|
+
}
|
|
2117
|
+
async saveTofu(store) {
|
|
2118
|
+
const fs = await import("fs");
|
|
2119
|
+
const path = await import("path");
|
|
2120
|
+
const directory = path.dirname(this.tofuPath) || ".";
|
|
2121
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
2122
|
+
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
2123
|
+
try {
|
|
2124
|
+
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
2125
|
+
try {
|
|
2126
|
+
fs.chmodSync(tmp, 384);
|
|
2127
|
+
} catch {
|
|
2128
|
+
}
|
|
2129
|
+
fs.renameSync(tmp, this.tofuPath);
|
|
2130
|
+
} catch (e) {
|
|
2131
|
+
try {
|
|
2132
|
+
fs.unlinkSync(tmp);
|
|
2133
|
+
} catch {
|
|
2134
|
+
}
|
|
2135
|
+
throw e;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
// --- sealing ---
|
|
2139
|
+
/**
|
|
2140
|
+
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
2141
|
+
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
2142
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
2143
|
+
*/
|
|
2144
|
+
seal(args) {
|
|
2145
|
+
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
2146
|
+
throw new PrivateInferenceError(
|
|
2147
|
+
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
2148
|
+
);
|
|
2149
|
+
}
|
|
2150
|
+
let affinity = null;
|
|
2151
|
+
if (args.messages != null) {
|
|
2152
|
+
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
2153
|
+
}
|
|
2154
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
2155
|
+
model: args.model,
|
|
2156
|
+
stream: args.stream,
|
|
2157
|
+
taskType: args.taskType,
|
|
2158
|
+
affinityKey: affinity,
|
|
2159
|
+
binary: args.binary ?? null
|
|
2160
|
+
});
|
|
2161
|
+
const topLevel = {
|
|
2162
|
+
model: args.model,
|
|
2163
|
+
stream: args.stream,
|
|
2164
|
+
pendra_encrypted: envelope
|
|
2165
|
+
};
|
|
2166
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
2167
|
+
}
|
|
2168
|
+
get keyFetchUrl() {
|
|
2169
|
+
return `${this.baseUrl}/v1/private-inference/key`;
|
|
2170
|
+
}
|
|
2171
|
+
};
|
|
2172
|
+
|
|
2039
2173
|
// src/client.ts
|
|
2040
2174
|
function envTruthy(v) {
|
|
2041
2175
|
if (!v) return false;
|