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.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
|
|
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
|
-
|
|
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,
|
|
207
|
-
return hkdfExtract(salt, concat(HPKE_VERSION,
|
|
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,
|
|
210
|
-
const labeledInfo = concat(i2osp(length, 2), HPKE_VERSION,
|
|
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,
|
|
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,
|
|
256
|
-
const infoHash = labeledExtract(empty, bytes("info_hash"), info,
|
|
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,
|
|
259
|
-
const key = labeledExpand(secret, bytes("key"), keyScheduleContext, NK,
|
|
260
|
-
const baseNonce = labeledExpand(secret, bytes("base_nonce"), keyScheduleContext, NN,
|
|
261
|
-
const exporterSecret = labeledExpand(secret, bytes("exp"), keyScheduleContext, NH,
|
|
262
|
-
return new Context(key, baseNonce, exporterSecret);
|
|
263
|
-
}
|
|
264
|
-
function setupBaseS(pkR, info, skE) {
|
|
265
|
-
|
|
266
|
-
|
|
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);
|
|
@@ -732,243 +782,9 @@ function chunkPlacement(chunk) {
|
|
|
732
782
|
}
|
|
733
783
|
var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
|
|
734
784
|
|
|
735
|
-
// src/_privateInferenceEngine.ts
|
|
736
|
-
var PrivateInferenceError = class extends Error {
|
|
737
|
-
constructor(message) {
|
|
738
|
-
super(message);
|
|
739
|
-
this.name = "PrivateInferenceError";
|
|
740
|
-
}
|
|
741
|
-
};
|
|
742
|
-
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
743
|
-
function parsePinnedFingerprints(pin) {
|
|
744
|
-
if (typeof pin !== "string") {
|
|
745
|
-
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
746
|
-
}
|
|
747
|
-
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
748
|
-
if (fps.length === 0) {
|
|
749
|
-
throw new PrivateInferenceError(
|
|
750
|
-
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
751
|
-
);
|
|
752
|
-
}
|
|
753
|
-
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
754
|
-
if (bad.length > 0) {
|
|
755
|
-
throw new PrivateInferenceError(
|
|
756
|
-
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
757
|
-
);
|
|
758
|
-
}
|
|
759
|
-
return new Set(fps);
|
|
760
|
-
}
|
|
761
|
-
function defaultTofuPath() {
|
|
762
|
-
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
763
|
-
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
764
|
-
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
765
|
-
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
766
|
-
}
|
|
767
|
-
function isFsError(e) {
|
|
768
|
-
const err = e;
|
|
769
|
-
return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
|
|
770
|
-
}
|
|
771
|
-
var warnedTofuPaths = /* @__PURE__ */ new Set();
|
|
772
|
-
function warnTofuUnwritable(tofuPath, e) {
|
|
773
|
-
if (warnedTofuPaths.has(tofuPath)) return;
|
|
774
|
-
warnedTofuPaths.add(tofuPath);
|
|
775
|
-
console.warn(
|
|
776
|
-
`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.`
|
|
777
|
-
);
|
|
778
|
-
}
|
|
779
|
-
function b64d2(s) {
|
|
780
|
-
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
781
|
-
const binary = atob(s);
|
|
782
|
-
const out = new Uint8Array(binary.length);
|
|
783
|
-
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
784
|
-
return out;
|
|
785
|
-
}
|
|
786
|
-
var PrivateInferenceEngine = class {
|
|
787
|
-
constructor(opts) {
|
|
788
|
-
this.orgPubs = null;
|
|
789
|
-
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
790
|
-
this.apiKey = opts.apiKey;
|
|
791
|
-
const pin = opts.pinnedFingerprint;
|
|
792
|
-
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
793
|
-
this.affinitySalt = opts.affinitySalt ?? null;
|
|
794
|
-
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
795
|
-
}
|
|
796
|
-
// --- key resolution ---
|
|
797
|
-
cachedOrgPublicKeys() {
|
|
798
|
-
return this.orgPubs;
|
|
799
|
-
}
|
|
800
|
-
cachedOrgPublicKey() {
|
|
801
|
-
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
802
|
-
}
|
|
803
|
-
tofuIdentity() {
|
|
804
|
-
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
805
|
-
return `${this.baseUrl}|${digest}`;
|
|
806
|
-
}
|
|
807
|
-
/**
|
|
808
|
-
* Drop the cached key set so the next call re-fetches it.
|
|
809
|
-
*
|
|
810
|
-
* The cache is otherwise held for the whole process lifetime, which is
|
|
811
|
-
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
812
|
-
* long-running server would go on sealing to a fingerprint no worker holds
|
|
813
|
-
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
814
|
-
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
815
|
-
* lets the client recover on its own.
|
|
816
|
-
*
|
|
817
|
-
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
818
|
-
* allowlist, so a fetch could only return fingerprints the pin already
|
|
819
|
-
* rejects. They surface the error instead, which is what pinning means.
|
|
820
|
-
*/
|
|
821
|
-
invalidateOrgKey() {
|
|
822
|
-
this.orgPubs = null;
|
|
823
|
-
}
|
|
824
|
-
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
825
|
-
get isPinned() {
|
|
826
|
-
return this.pinnedFingerprints !== null;
|
|
827
|
-
}
|
|
828
|
-
/**
|
|
829
|
-
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
830
|
-
* allowlist (or auto-trust TOFU), cache the accepted public keys, and return
|
|
831
|
-
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
832
|
-
* so any worker holding any of them can serve the request. Throws
|
|
833
|
-
* PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
|
|
834
|
-
* intersection with the pin set.
|
|
835
|
-
*/
|
|
836
|
-
async resolveOrgKey(fetchedKeys) {
|
|
837
|
-
if (this.orgPubs !== null) return this.orgPubs;
|
|
838
|
-
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
839
|
-
throw new PrivateInferenceError(
|
|
840
|
-
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
841
|
-
);
|
|
842
|
-
}
|
|
843
|
-
const pubs = [];
|
|
844
|
-
const fps = [];
|
|
845
|
-
for (const entry of fetchedKeys) {
|
|
846
|
-
let pub;
|
|
847
|
-
try {
|
|
848
|
-
pub = b64d2(entry.public_key);
|
|
849
|
-
} catch (e) {
|
|
850
|
-
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
851
|
-
}
|
|
852
|
-
if (pub.length !== 32) {
|
|
853
|
-
throw new PrivateInferenceError(
|
|
854
|
-
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
855
|
-
);
|
|
856
|
-
}
|
|
857
|
-
pubs.push(pub);
|
|
858
|
-
fps.push(fingerprint(pub));
|
|
859
|
-
}
|
|
860
|
-
let accepted;
|
|
861
|
-
if (this.pinnedFingerprints !== null) {
|
|
862
|
-
accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
|
|
863
|
-
if (accepted.length === 0) {
|
|
864
|
-
const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
|
|
865
|
-
throw new PrivateInferenceError(
|
|
866
|
-
`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.`
|
|
867
|
-
);
|
|
868
|
-
}
|
|
869
|
-
} else {
|
|
870
|
-
try {
|
|
871
|
-
await this.tofuTrust(fps);
|
|
872
|
-
} catch (e) {
|
|
873
|
-
if (!isFsError(e)) throw e;
|
|
874
|
-
warnTofuUnwritable(this.tofuPath, e);
|
|
875
|
-
}
|
|
876
|
-
accepted = pubs;
|
|
877
|
-
}
|
|
878
|
-
this.orgPubs = accepted;
|
|
879
|
-
return accepted;
|
|
880
|
-
}
|
|
881
|
-
async tofuTrust(fps) {
|
|
882
|
-
const store = await this.loadTofu();
|
|
883
|
-
const identity = this.tofuIdentity();
|
|
884
|
-
const known = store[identity];
|
|
885
|
-
const trusted = /* @__PURE__ */ new Set();
|
|
886
|
-
if (typeof known === "string") {
|
|
887
|
-
trusted.add(known);
|
|
888
|
-
} else if (Array.isArray(known)) {
|
|
889
|
-
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
890
|
-
}
|
|
891
|
-
const before = trusted.size;
|
|
892
|
-
for (const f of fps) trusted.add(f);
|
|
893
|
-
if (trusted.size !== before || !Array.isArray(known)) {
|
|
894
|
-
store[identity] = Array.from(trusted).sort();
|
|
895
|
-
await this.saveTofu(store);
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
async loadTofu() {
|
|
899
|
-
const fs = await import("fs");
|
|
900
|
-
let raw;
|
|
901
|
-
try {
|
|
902
|
-
raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
903
|
-
} catch (e) {
|
|
904
|
-
if (e.code === "ENOENT") return {};
|
|
905
|
-
throw e;
|
|
906
|
-
}
|
|
907
|
-
let data;
|
|
908
|
-
try {
|
|
909
|
-
data = JSON.parse(raw);
|
|
910
|
-
} catch {
|
|
911
|
-
return {};
|
|
912
|
-
}
|
|
913
|
-
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
914
|
-
}
|
|
915
|
-
async saveTofu(store) {
|
|
916
|
-
const fs = await import("fs");
|
|
917
|
-
const path = await import("path");
|
|
918
|
-
const directory = path.dirname(this.tofuPath) || ".";
|
|
919
|
-
fs.mkdirSync(directory, { recursive: true });
|
|
920
|
-
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
921
|
-
try {
|
|
922
|
-
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
923
|
-
try {
|
|
924
|
-
fs.chmodSync(tmp, 384);
|
|
925
|
-
} catch {
|
|
926
|
-
}
|
|
927
|
-
fs.renameSync(tmp, this.tofuPath);
|
|
928
|
-
} catch (e) {
|
|
929
|
-
try {
|
|
930
|
-
fs.unlinkSync(tmp);
|
|
931
|
-
} catch {
|
|
932
|
-
}
|
|
933
|
-
throw e;
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
// --- sealing ---
|
|
937
|
-
/**
|
|
938
|
-
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
939
|
-
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
940
|
-
* `binary` (audio only) is sealed under the same data key as the body.
|
|
941
|
-
*/
|
|
942
|
-
seal(args) {
|
|
943
|
-
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
944
|
-
throw new PrivateInferenceError(
|
|
945
|
-
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
946
|
-
);
|
|
947
|
-
}
|
|
948
|
-
let affinity = null;
|
|
949
|
-
if (args.messages != null) {
|
|
950
|
-
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
951
|
-
}
|
|
952
|
-
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
953
|
-
model: args.model,
|
|
954
|
-
stream: args.stream,
|
|
955
|
-
taskType: args.taskType,
|
|
956
|
-
affinityKey: affinity,
|
|
957
|
-
binary: args.binary ?? null
|
|
958
|
-
});
|
|
959
|
-
const topLevel = {
|
|
960
|
-
model: args.model,
|
|
961
|
-
stream: args.stream,
|
|
962
|
-
pendra_encrypted: envelope
|
|
963
|
-
};
|
|
964
|
-
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
965
|
-
}
|
|
966
|
-
get keyFetchUrl() {
|
|
967
|
-
return `${this.baseUrl}/v1/private-inference/key`;
|
|
968
|
-
}
|
|
969
|
-
};
|
|
970
|
-
|
|
971
785
|
// src/resources/audio/speech.ts
|
|
786
|
+
var ENCODER = new TextEncoder();
|
|
787
|
+
var DECODER = new TextDecoder();
|
|
972
788
|
var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
973
789
|
function decodeAudio(value) {
|
|
974
790
|
if (typeof value !== "string") return void 0;
|
|
@@ -1011,15 +827,15 @@ var Speech = class {
|
|
|
1011
827
|
if (typeof params.input !== "string" || !params.input.trim()) {
|
|
1012
828
|
throw new Error("input must be a non-empty string");
|
|
1013
829
|
}
|
|
1014
|
-
if (this.client.privateInferenceEnabled) {
|
|
1015
|
-
throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
|
|
1016
|
-
}
|
|
1017
830
|
const body = { model: params.model, input: params.input };
|
|
1018
831
|
if (params.voice != null) body.voice = params.voice;
|
|
1019
832
|
if (params.response_format != null) body.response_format = params.response_format;
|
|
1020
833
|
const headers = { Accept: "application/json" };
|
|
1021
834
|
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
1022
835
|
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
836
|
+
if (this.client.privateInferenceEnabled) {
|
|
837
|
+
return this.createEncrypted(params, body, timeout);
|
|
838
|
+
}
|
|
1023
839
|
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
1024
840
|
method: "POST",
|
|
1025
841
|
body,
|
|
@@ -1037,29 +853,57 @@ var Speech = class {
|
|
|
1037
853
|
});
|
|
1038
854
|
}
|
|
1039
855
|
throwIfInBandError(parsed, "The server reported an error");
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
856
|
+
return speechFrom(parsed, text, params, response);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Private-inference speech. The request options are the sealed JSON body;
|
|
860
|
+
* the worker seals the same `{ audio, format, duration_ms }` result a
|
|
861
|
+
* plaintext JSON reply carries, so the audio comes back exactly as it does
|
|
862
|
+
* without encryption.
|
|
863
|
+
*/
|
|
864
|
+
async createEncrypted(params, body, timeout) {
|
|
865
|
+
const engine = await this.client._privateEngine();
|
|
866
|
+
const { topLevel, decryptor } = engine.seal({
|
|
867
|
+
model: params.model,
|
|
868
|
+
stream: false,
|
|
869
|
+
taskType: "speech",
|
|
870
|
+
body: ENCODER.encode(JSON.stringify(body))
|
|
871
|
+
});
|
|
872
|
+
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
873
|
+
method: "POST",
|
|
874
|
+
body: topLevel,
|
|
875
|
+
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
|
|
876
|
+
timeout
|
|
877
|
+
});
|
|
878
|
+
const { inner, placement } = await readSealedReply(response);
|
|
879
|
+
const raw = DECODER.decode(decryptor.openResult(inner));
|
|
880
|
+
const parsed = parseDecryptedJson(raw, response.status);
|
|
881
|
+
return speechFrom(parsed, raw, params, response, placement);
|
|
1061
882
|
}
|
|
1062
883
|
};
|
|
884
|
+
function speechFrom(parsed, raw, params, response, placement) {
|
|
885
|
+
if (!isRecord2(parsed)) {
|
|
886
|
+
throw new APIResponseValidationError("Response was not a speech result", {
|
|
887
|
+
status: response.status,
|
|
888
|
+
body: raw
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
const audio = decodeAudio(parsed.audio);
|
|
892
|
+
if (!audio) {
|
|
893
|
+
throw new APIResponseValidationError("Response did not contain decodable audio", {
|
|
894
|
+
status: response.status,
|
|
895
|
+
body: raw
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
const result = {
|
|
899
|
+
audio,
|
|
900
|
+
format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
|
|
901
|
+
duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
|
|
902
|
+
arrayBuffer: async () => audio.slice().buffer
|
|
903
|
+
};
|
|
904
|
+
if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
|
|
905
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
906
|
+
}
|
|
1063
907
|
|
|
1064
908
|
// src/_sse.ts
|
|
1065
909
|
var DEFAULT_EVENT = "message";
|
|
@@ -1257,8 +1101,8 @@ function releaseReader(reader, controller, finished) {
|
|
|
1257
1101
|
}
|
|
1258
1102
|
|
|
1259
1103
|
// src/resources/audio/transcriptions.ts
|
|
1260
|
-
var
|
|
1261
|
-
var
|
|
1104
|
+
var ENCODER2 = new TextEncoder();
|
|
1105
|
+
var DECODER2 = new TextDecoder();
|
|
1262
1106
|
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
1263
1107
|
var MIME_EXT = {
|
|
1264
1108
|
"audio/mpeg": "mp3",
|
|
@@ -1392,7 +1236,7 @@ var Transcriptions = class {
|
|
|
1392
1236
|
model: params.model,
|
|
1393
1237
|
stream: false,
|
|
1394
1238
|
taskType: "transcription",
|
|
1395
|
-
body:
|
|
1239
|
+
body: ENCODER2.encode(JSON.stringify(body)),
|
|
1396
1240
|
binary: new Uint8Array(await blob.arrayBuffer())
|
|
1397
1241
|
});
|
|
1398
1242
|
const { response } = await this.client._fetch(
|
|
@@ -1405,7 +1249,7 @@ var Transcriptions = class {
|
|
|
1405
1249
|
}
|
|
1406
1250
|
);
|
|
1407
1251
|
const { inner, placement } = await readSealedReply(response);
|
|
1408
|
-
const raw =
|
|
1252
|
+
const raw = DECODER2.decode(decryptor.openResult(inner));
|
|
1409
1253
|
const parsed = parseDecryptedJson(raw, response.status);
|
|
1410
1254
|
const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
|
|
1411
1255
|
if (typeof parsed === "string") return place({ text: parsed });
|
|
@@ -1431,7 +1275,7 @@ var Audio = class {
|
|
|
1431
1275
|
};
|
|
1432
1276
|
|
|
1433
1277
|
// src/_privateStreaming.ts
|
|
1434
|
-
var
|
|
1278
|
+
var DECODER3 = new TextDecoder();
|
|
1435
1279
|
var EncryptedStream = class {
|
|
1436
1280
|
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
1437
1281
|
this.decoder = new TextDecoder();
|
|
@@ -1497,7 +1341,7 @@ var EncryptedStream = class {
|
|
|
1497
1341
|
);
|
|
1498
1342
|
}
|
|
1499
1343
|
const plain = this.decryptor.openChunk(inner);
|
|
1500
|
-
const chunkJson =
|
|
1344
|
+
const chunkJson = DECODER3.decode(plain).trim();
|
|
1501
1345
|
const first = !this.openedAny;
|
|
1502
1346
|
this.openedAny = true;
|
|
1503
1347
|
if (first && isStreamTerminatorDeclaration(chunkJson)) {
|
|
@@ -1551,8 +1395,8 @@ var EncryptedStream = class {
|
|
|
1551
1395
|
};
|
|
1552
1396
|
|
|
1553
1397
|
// src/resources/chat/completions.ts
|
|
1554
|
-
var
|
|
1555
|
-
var
|
|
1398
|
+
var ENCODER3 = new TextEncoder();
|
|
1399
|
+
var DECODER4 = new TextDecoder();
|
|
1556
1400
|
var Completions = class {
|
|
1557
1401
|
constructor(client) {
|
|
1558
1402
|
this.client = client;
|
|
@@ -1593,7 +1437,7 @@ var Completions = class {
|
|
|
1593
1437
|
// The terminator request rides inside the sealed body, so the relay can
|
|
1594
1438
|
// neither strip nor add it: it asks the worker to seal the end of the
|
|
1595
1439
|
// stream (#2157).
|
|
1596
|
-
body:
|
|
1440
|
+
body: ENCODER3.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
|
|
1597
1441
|
messages: params.messages
|
|
1598
1442
|
});
|
|
1599
1443
|
if (stream) {
|
|
@@ -1609,7 +1453,7 @@ var Completions = class {
|
|
|
1609
1453
|
);
|
|
1610
1454
|
const { inner, placement } = await readSealedReply(response);
|
|
1611
1455
|
const plain = decryptor.openResult(inner);
|
|
1612
|
-
const completion = parseDecryptedCompletion(
|
|
1456
|
+
const completion = parseDecryptedCompletion(DECODER4.decode(plain), response.status);
|
|
1613
1457
|
return withPlacement(completion, response.headers, completion.pendra, placement);
|
|
1614
1458
|
}
|
|
1615
1459
|
};
|
|
@@ -1622,8 +1466,8 @@ var Chat = class {
|
|
|
1622
1466
|
};
|
|
1623
1467
|
|
|
1624
1468
|
// src/resources/embeddings.ts
|
|
1625
|
-
var
|
|
1626
|
-
var
|
|
1469
|
+
var ENCODER4 = new TextEncoder();
|
|
1470
|
+
var DECODER5 = new TextDecoder();
|
|
1627
1471
|
function validateParams(params) {
|
|
1628
1472
|
if (!params.model || typeof params.model !== "string") {
|
|
1629
1473
|
throw new Error("model must be a non-empty string");
|
|
@@ -1689,7 +1533,7 @@ var Embeddings = class {
|
|
|
1689
1533
|
model,
|
|
1690
1534
|
stream: false,
|
|
1691
1535
|
taskType: "embeddings",
|
|
1692
|
-
body:
|
|
1536
|
+
body: ENCODER4.encode(JSON.stringify(body))
|
|
1693
1537
|
});
|
|
1694
1538
|
const { response } = await this.client._fetch(
|
|
1695
1539
|
"/api/v1/embeddings",
|
|
@@ -1697,14 +1541,14 @@ var Embeddings = class {
|
|
|
1697
1541
|
);
|
|
1698
1542
|
const { inner, placement } = await readSealedReply(response);
|
|
1699
1543
|
const plain = decryptor.openResult(inner);
|
|
1700
|
-
const result = JSON.parse(
|
|
1544
|
+
const result = JSON.parse(DECODER5.decode(plain));
|
|
1701
1545
|
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1702
1546
|
}
|
|
1703
1547
|
};
|
|
1704
1548
|
|
|
1705
1549
|
// src/resources/images/generations.ts
|
|
1706
|
-
var
|
|
1707
|
-
var
|
|
1550
|
+
var ENCODER5 = new TextEncoder();
|
|
1551
|
+
var DECODER6 = new TextDecoder();
|
|
1708
1552
|
var SIZE_RE = /^\d+x\d+$/;
|
|
1709
1553
|
function validateParams2(params) {
|
|
1710
1554
|
if (!params.prompt || !params.prompt.trim()) {
|
|
@@ -1750,7 +1594,7 @@ var Generations = class {
|
|
|
1750
1594
|
model,
|
|
1751
1595
|
stream: false,
|
|
1752
1596
|
taskType: "image_generation",
|
|
1753
|
-
body:
|
|
1597
|
+
body: ENCODER5.encode(JSON.stringify(body))
|
|
1754
1598
|
});
|
|
1755
1599
|
const { response } = await this.client._fetch(
|
|
1756
1600
|
"/api/v1/images/generations",
|
|
@@ -1758,11 +1602,11 @@ var Generations = class {
|
|
|
1758
1602
|
);
|
|
1759
1603
|
const { inner, placement } = await readSealedReply(response);
|
|
1760
1604
|
const plain = decryptor.openResult(inner);
|
|
1761
|
-
const parsed = parseDecryptedJson(
|
|
1605
|
+
const parsed = parseDecryptedJson(DECODER6.decode(plain), response.status);
|
|
1762
1606
|
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1763
1607
|
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
1764
1608
|
status: response.status,
|
|
1765
|
-
body:
|
|
1609
|
+
body: DECODER6.decode(plain)
|
|
1766
1610
|
});
|
|
1767
1611
|
}
|
|
1768
1612
|
const result = parsed;
|
|
@@ -1792,8 +1636,8 @@ var Models = class {
|
|
|
1792
1636
|
};
|
|
1793
1637
|
|
|
1794
1638
|
// src/resources/moderations.ts
|
|
1795
|
-
var
|
|
1796
|
-
var
|
|
1639
|
+
var ENCODER6 = new TextEncoder();
|
|
1640
|
+
var DECODER7 = new TextDecoder();
|
|
1797
1641
|
var MAX_INPUTS = 32;
|
|
1798
1642
|
function isPlainObject2(v) {
|
|
1799
1643
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -1894,7 +1738,7 @@ var Moderations = class {
|
|
|
1894
1738
|
model,
|
|
1895
1739
|
stream: false,
|
|
1896
1740
|
taskType: "moderation",
|
|
1897
|
-
body:
|
|
1741
|
+
body: ENCODER6.encode(JSON.stringify({ model: body.model, stream: false, input: body.input }))
|
|
1898
1742
|
});
|
|
1899
1743
|
const { response } = await this.client._fetch(
|
|
1900
1744
|
"/api/v1/moderations",
|
|
@@ -1903,7 +1747,7 @@ var Moderations = class {
|
|
|
1903
1747
|
const { inner, placement } = await readSealedReply(response);
|
|
1904
1748
|
const plain = decryptor.openResult(inner);
|
|
1905
1749
|
const result = asModeration(
|
|
1906
|
-
parseDecryptedJson(
|
|
1750
|
+
parseDecryptedJson(DECODER7.decode(plain), response.status),
|
|
1907
1751
|
response.status,
|
|
1908
1752
|
"Decrypted response"
|
|
1909
1753
|
);
|
|
@@ -1912,8 +1756,8 @@ var Moderations = class {
|
|
|
1912
1756
|
};
|
|
1913
1757
|
|
|
1914
1758
|
// src/resources/rerank.ts
|
|
1915
|
-
var
|
|
1916
|
-
var
|
|
1759
|
+
var ENCODER7 = new TextEncoder();
|
|
1760
|
+
var DECODER8 = new TextDecoder();
|
|
1917
1761
|
function validateParams4(params) {
|
|
1918
1762
|
if (!params.model || typeof params.model !== "string") {
|
|
1919
1763
|
throw new Error("model must be a non-empty string");
|
|
@@ -1973,7 +1817,7 @@ var Rerank = class {
|
|
|
1973
1817
|
model,
|
|
1974
1818
|
stream: false,
|
|
1975
1819
|
taskType: "rerank",
|
|
1976
|
-
body:
|
|
1820
|
+
body: ENCODER7.encode(JSON.stringify(body))
|
|
1977
1821
|
});
|
|
1978
1822
|
const { response } = await this.client._fetch(
|
|
1979
1823
|
"/api/v1/rerank",
|
|
@@ -1981,15 +1825,305 @@ var Rerank = class {
|
|
|
1981
1825
|
);
|
|
1982
1826
|
const { inner, placement } = await readSealedReply(response);
|
|
1983
1827
|
const plain = decryptor.openResult(inner);
|
|
1984
|
-
const result = JSON.parse(
|
|
1828
|
+
const result = JSON.parse(DECODER8.decode(plain));
|
|
1985
1829
|
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1986
1830
|
}
|
|
1987
1831
|
};
|
|
1988
1832
|
|
|
1989
1833
|
// src/version.ts
|
|
1990
|
-
var VERSION = "0.
|
|
1834
|
+
var VERSION = "0.24.0";
|
|
1991
1835
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1992
1836
|
|
|
1837
|
+
// src/_privateInferenceEngine.ts
|
|
1838
|
+
var PrivateInferenceError = class extends Error {
|
|
1839
|
+
constructor(message) {
|
|
1840
|
+
super(message);
|
|
1841
|
+
this.name = "PrivateInferenceError";
|
|
1842
|
+
}
|
|
1843
|
+
};
|
|
1844
|
+
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
1845
|
+
function parsePinnedFingerprints(pin) {
|
|
1846
|
+
if (typeof pin !== "string") {
|
|
1847
|
+
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
1848
|
+
}
|
|
1849
|
+
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
1850
|
+
if (fps.length === 0) {
|
|
1851
|
+
throw new PrivateInferenceError(
|
|
1852
|
+
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
1853
|
+
);
|
|
1854
|
+
}
|
|
1855
|
+
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
1856
|
+
if (bad.length > 0) {
|
|
1857
|
+
throw new PrivateInferenceError(
|
|
1858
|
+
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
return new Set(fps);
|
|
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
|
+
}
|
|
1898
|
+
function defaultTofuPath() {
|
|
1899
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1900
|
+
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
1901
|
+
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
1902
|
+
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
1903
|
+
}
|
|
1904
|
+
function isFsError(e) {
|
|
1905
|
+
const err = e;
|
|
1906
|
+
return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
|
|
1907
|
+
}
|
|
1908
|
+
var warnedTofuPaths = /* @__PURE__ */ new Set();
|
|
1909
|
+
function warnTofuUnwritable(tofuPath, e) {
|
|
1910
|
+
if (warnedTofuPaths.has(tofuPath)) return;
|
|
1911
|
+
warnedTofuPaths.add(tofuPath);
|
|
1912
|
+
console.warn(
|
|
1913
|
+
`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.`
|
|
1914
|
+
);
|
|
1915
|
+
}
|
|
1916
|
+
function b64d2(s) {
|
|
1917
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
1918
|
+
const binary = atob(s);
|
|
1919
|
+
const out = new Uint8Array(binary.length);
|
|
1920
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
1921
|
+
return out;
|
|
1922
|
+
}
|
|
1923
|
+
var PrivateInferenceEngine = class {
|
|
1924
|
+
constructor(opts) {
|
|
1925
|
+
this.orgPubs = null;
|
|
1926
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
1927
|
+
this.apiKey = opts.apiKey;
|
|
1928
|
+
const pin = opts.pinnedFingerprint;
|
|
1929
|
+
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
1930
|
+
this.affinitySalt = opts.affinitySalt ?? null;
|
|
1931
|
+
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
1932
|
+
}
|
|
1933
|
+
// --- key resolution ---
|
|
1934
|
+
cachedOrgPublicKeys() {
|
|
1935
|
+
return this.orgPubs;
|
|
1936
|
+
}
|
|
1937
|
+
cachedOrgPublicKey() {
|
|
1938
|
+
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
1939
|
+
}
|
|
1940
|
+
tofuIdentity() {
|
|
1941
|
+
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
1942
|
+
return `${this.baseUrl}|${digest}`;
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Drop the cached key set so the next call re-fetches it.
|
|
1946
|
+
*
|
|
1947
|
+
* The cache is otherwise held for the whole process lifetime, which is
|
|
1948
|
+
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
1949
|
+
* long-running server would go on sealing to a fingerprint no worker holds
|
|
1950
|
+
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
1951
|
+
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
1952
|
+
* lets the client recover on its own.
|
|
1953
|
+
*
|
|
1954
|
+
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
1955
|
+
* allowlist, so a fetch could only return fingerprints the pin already
|
|
1956
|
+
* rejects. They surface the error instead, which is what pinning means.
|
|
1957
|
+
*/
|
|
1958
|
+
invalidateOrgKey() {
|
|
1959
|
+
this.orgPubs = null;
|
|
1960
|
+
}
|
|
1961
|
+
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
1962
|
+
get isPinned() {
|
|
1963
|
+
return this.pinnedFingerprints !== null;
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
1967
|
+
* allowlist (or auto-trust TOFU), cache the selected public keys, and return
|
|
1968
|
+
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
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.
|
|
1978
|
+
*/
|
|
1979
|
+
async resolveOrgKey(fetchedKeys) {
|
|
1980
|
+
if (this.orgPubs !== null) return this.orgPubs;
|
|
1981
|
+
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
1982
|
+
throw new PrivateInferenceError(
|
|
1983
|
+
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
1984
|
+
);
|
|
1985
|
+
}
|
|
1986
|
+
const keys = [];
|
|
1987
|
+
for (const entry of fetchedKeys) {
|
|
1988
|
+
let pub;
|
|
1989
|
+
try {
|
|
1990
|
+
pub = b64d2(entry.public_key);
|
|
1991
|
+
} catch (e) {
|
|
1992
|
+
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
1993
|
+
}
|
|
1994
|
+
if (pub.length !== X25519_PUBLIC_KEY_SIZE) {
|
|
1995
|
+
throw new PrivateInferenceError(
|
|
1996
|
+
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
keys.push({ pub, fp: fingerprint(pub), ...parseCompanion(entry) });
|
|
2000
|
+
}
|
|
2001
|
+
let selected;
|
|
2002
|
+
if (this.pinnedFingerprints !== null) {
|
|
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(", ");
|
|
2015
|
+
throw new PrivateInferenceError(
|
|
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.`
|
|
2017
|
+
);
|
|
2018
|
+
}
|
|
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) {
|
|
2026
|
+
try {
|
|
2027
|
+
await this.tofuTrust(selected.map((s) => s.fp));
|
|
2028
|
+
} catch (e) {
|
|
2029
|
+
if (!isFsError(e)) throw e;
|
|
2030
|
+
warnTofuUnwritable(this.tofuPath, e);
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
const accepted = selected.map((s) => s.pub);
|
|
2034
|
+
this.orgPubs = accepted;
|
|
2035
|
+
return accepted;
|
|
2036
|
+
}
|
|
2037
|
+
async tofuTrust(fps) {
|
|
2038
|
+
const store = await this.loadTofu();
|
|
2039
|
+
const identity = this.tofuIdentity();
|
|
2040
|
+
const known = store[identity];
|
|
2041
|
+
const trusted = /* @__PURE__ */ new Set();
|
|
2042
|
+
if (typeof known === "string") {
|
|
2043
|
+
trusted.add(known);
|
|
2044
|
+
} else if (Array.isArray(known)) {
|
|
2045
|
+
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
2046
|
+
}
|
|
2047
|
+
const before = trusted.size;
|
|
2048
|
+
for (const f of fps) trusted.add(f);
|
|
2049
|
+
if (trusted.size !== before || !Array.isArray(known)) {
|
|
2050
|
+
store[identity] = Array.from(trusted).sort();
|
|
2051
|
+
await this.saveTofu(store);
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
async loadTofu() {
|
|
2055
|
+
const fs = await import("fs");
|
|
2056
|
+
let raw;
|
|
2057
|
+
try {
|
|
2058
|
+
raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
2059
|
+
} catch (e) {
|
|
2060
|
+
if (e.code === "ENOENT") return {};
|
|
2061
|
+
throw e;
|
|
2062
|
+
}
|
|
2063
|
+
let data;
|
|
2064
|
+
try {
|
|
2065
|
+
data = JSON.parse(raw);
|
|
2066
|
+
} catch {
|
|
2067
|
+
return {};
|
|
2068
|
+
}
|
|
2069
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
2070
|
+
}
|
|
2071
|
+
async saveTofu(store) {
|
|
2072
|
+
const fs = await import("fs");
|
|
2073
|
+
const path = await import("path");
|
|
2074
|
+
const directory = path.dirname(this.tofuPath) || ".";
|
|
2075
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
2076
|
+
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
2077
|
+
try {
|
|
2078
|
+
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
2079
|
+
try {
|
|
2080
|
+
fs.chmodSync(tmp, 384);
|
|
2081
|
+
} catch {
|
|
2082
|
+
}
|
|
2083
|
+
fs.renameSync(tmp, this.tofuPath);
|
|
2084
|
+
} catch (e) {
|
|
2085
|
+
try {
|
|
2086
|
+
fs.unlinkSync(tmp);
|
|
2087
|
+
} catch {
|
|
2088
|
+
}
|
|
2089
|
+
throw e;
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
// --- sealing ---
|
|
2093
|
+
/**
|
|
2094
|
+
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
2095
|
+
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
2096
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
2097
|
+
*/
|
|
2098
|
+
seal(args) {
|
|
2099
|
+
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
2100
|
+
throw new PrivateInferenceError(
|
|
2101
|
+
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
2102
|
+
);
|
|
2103
|
+
}
|
|
2104
|
+
let affinity = null;
|
|
2105
|
+
if (args.messages != null) {
|
|
2106
|
+
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
2107
|
+
}
|
|
2108
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
2109
|
+
model: args.model,
|
|
2110
|
+
stream: args.stream,
|
|
2111
|
+
taskType: args.taskType,
|
|
2112
|
+
affinityKey: affinity,
|
|
2113
|
+
binary: args.binary ?? null
|
|
2114
|
+
});
|
|
2115
|
+
const topLevel = {
|
|
2116
|
+
model: args.model,
|
|
2117
|
+
stream: args.stream,
|
|
2118
|
+
pendra_encrypted: envelope
|
|
2119
|
+
};
|
|
2120
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
2121
|
+
}
|
|
2122
|
+
get keyFetchUrl() {
|
|
2123
|
+
return `${this.baseUrl}/v1/private-inference/key`;
|
|
2124
|
+
}
|
|
2125
|
+
};
|
|
2126
|
+
|
|
1993
2127
|
// src/client.ts
|
|
1994
2128
|
function envTruthy(v) {
|
|
1995
2129
|
if (!v) return false;
|