pendra 0.21.1 → 0.23.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 +5 -3
- package/dist/index.d.mts +34 -3
- package/dist/index.d.ts +34 -3
- package/dist/index.js +318 -288
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +318 -288
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -732,243 +732,9 @@ function chunkPlacement(chunk) {
|
|
|
732
732
|
}
|
|
733
733
|
var PLACEMENT_OPT_IN_HEADER = "X-Pendra-Placement";
|
|
734
734
|
|
|
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
735
|
// src/resources/audio/speech.ts
|
|
736
|
+
var ENCODER = new TextEncoder();
|
|
737
|
+
var DECODER = new TextDecoder();
|
|
972
738
|
var BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
973
739
|
function decodeAudio(value) {
|
|
974
740
|
if (typeof value !== "string") return void 0;
|
|
@@ -1011,15 +777,15 @@ var Speech = class {
|
|
|
1011
777
|
if (typeof params.input !== "string" || !params.input.trim()) {
|
|
1012
778
|
throw new Error("input must be a non-empty string");
|
|
1013
779
|
}
|
|
1014
|
-
if (this.client.privateInferenceEnabled) {
|
|
1015
|
-
throw new PrivateInferenceError("Private inference does not support speech synthesis yet.");
|
|
1016
|
-
}
|
|
1017
780
|
const body = { model: params.model, input: params.input };
|
|
1018
781
|
if (params.voice != null) body.voice = params.voice;
|
|
1019
782
|
if (params.response_format != null) body.response_format = params.response_format;
|
|
1020
783
|
const headers = { Accept: "application/json" };
|
|
1021
784
|
if (params.worker_id) headers["X-Pendra-Worker-Id"] = params.worker_id;
|
|
1022
785
|
const timeout = Math.max(this.client.timeout ?? 0, 3e5);
|
|
786
|
+
if (this.client.privateInferenceEnabled) {
|
|
787
|
+
return this.createEncrypted(params, body, timeout);
|
|
788
|
+
}
|
|
1023
789
|
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
1024
790
|
method: "POST",
|
|
1025
791
|
body,
|
|
@@ -1037,29 +803,57 @@ var Speech = class {
|
|
|
1037
803
|
});
|
|
1038
804
|
}
|
|
1039
805
|
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
|
-
|
|
806
|
+
return speechFrom(parsed, text, params, response);
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Private-inference speech. The request options are the sealed JSON body;
|
|
810
|
+
* the worker seals the same `{ audio, format, duration_ms }` result a
|
|
811
|
+
* plaintext JSON reply carries, so the audio comes back exactly as it does
|
|
812
|
+
* without encryption.
|
|
813
|
+
*/
|
|
814
|
+
async createEncrypted(params, body, timeout) {
|
|
815
|
+
const engine = await this.client._privateEngine();
|
|
816
|
+
const { topLevel, decryptor } = engine.seal({
|
|
817
|
+
model: params.model,
|
|
818
|
+
stream: false,
|
|
819
|
+
taskType: "speech",
|
|
820
|
+
body: ENCODER.encode(JSON.stringify(body))
|
|
821
|
+
});
|
|
822
|
+
const { response } = await this.client._fetch("/api/v1/audio/speech", {
|
|
823
|
+
method: "POST",
|
|
824
|
+
body: topLevel,
|
|
825
|
+
headers: params.worker_id ? { "X-Pendra-Worker-Id": params.worker_id } : void 0,
|
|
826
|
+
timeout
|
|
827
|
+
});
|
|
828
|
+
const { inner, placement } = await readSealedReply(response);
|
|
829
|
+
const raw = DECODER.decode(decryptor.openResult(inner));
|
|
830
|
+
const parsed = parseDecryptedJson(raw, response.status);
|
|
831
|
+
return speechFrom(parsed, raw, params, response, placement);
|
|
1061
832
|
}
|
|
1062
833
|
};
|
|
834
|
+
function speechFrom(parsed, raw, params, response, placement) {
|
|
835
|
+
if (!isRecord2(parsed)) {
|
|
836
|
+
throw new APIResponseValidationError("Response was not a speech result", {
|
|
837
|
+
status: response.status,
|
|
838
|
+
body: raw
|
|
839
|
+
});
|
|
840
|
+
}
|
|
841
|
+
const audio = decodeAudio(parsed.audio);
|
|
842
|
+
if (!audio) {
|
|
843
|
+
throw new APIResponseValidationError("Response did not contain decodable audio", {
|
|
844
|
+
status: response.status,
|
|
845
|
+
body: raw
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
const result = {
|
|
849
|
+
audio,
|
|
850
|
+
format: typeof parsed.format === "string" && parsed.format ? parsed.format : params.response_format ?? "wav",
|
|
851
|
+
duration_ms: typeof parsed.duration_ms === "number" && Number.isFinite(parsed.duration_ms) ? parsed.duration_ms : null,
|
|
852
|
+
arrayBuffer: async () => audio.slice().buffer
|
|
853
|
+
};
|
|
854
|
+
if (isRecord2(parsed.pendra)) result.pendra = parsed.pendra;
|
|
855
|
+
return withPlacement(result, response.headers, result.pendra, placement);
|
|
856
|
+
}
|
|
1063
857
|
|
|
1064
858
|
// src/_sse.ts
|
|
1065
859
|
var DEFAULT_EVENT = "message";
|
|
@@ -1257,8 +1051,8 @@ function releaseReader(reader, controller, finished) {
|
|
|
1257
1051
|
}
|
|
1258
1052
|
|
|
1259
1053
|
// src/resources/audio/transcriptions.ts
|
|
1260
|
-
var
|
|
1261
|
-
var
|
|
1054
|
+
var ENCODER2 = new TextEncoder();
|
|
1055
|
+
var DECODER2 = new TextDecoder();
|
|
1262
1056
|
var MAX_FILE_SIZE = 25 * 1024 * 1024;
|
|
1263
1057
|
var MIME_EXT = {
|
|
1264
1058
|
"audio/mpeg": "mp3",
|
|
@@ -1392,7 +1186,7 @@ var Transcriptions = class {
|
|
|
1392
1186
|
model: params.model,
|
|
1393
1187
|
stream: false,
|
|
1394
1188
|
taskType: "transcription",
|
|
1395
|
-
body:
|
|
1189
|
+
body: ENCODER2.encode(JSON.stringify(body)),
|
|
1396
1190
|
binary: new Uint8Array(await blob.arrayBuffer())
|
|
1397
1191
|
});
|
|
1398
1192
|
const { response } = await this.client._fetch(
|
|
@@ -1405,7 +1199,7 @@ var Transcriptions = class {
|
|
|
1405
1199
|
}
|
|
1406
1200
|
);
|
|
1407
1201
|
const { inner, placement } = await readSealedReply(response);
|
|
1408
|
-
const raw =
|
|
1202
|
+
const raw = DECODER2.decode(decryptor.openResult(inner));
|
|
1409
1203
|
const parsed = parseDecryptedJson(raw, response.status);
|
|
1410
1204
|
const place = (r) => withPlacement(r, response.headers, r.pendra, placement);
|
|
1411
1205
|
if (typeof parsed === "string") return place({ text: parsed });
|
|
@@ -1431,7 +1225,7 @@ var Audio = class {
|
|
|
1431
1225
|
};
|
|
1432
1226
|
|
|
1433
1227
|
// src/_privateStreaming.ts
|
|
1434
|
-
var
|
|
1228
|
+
var DECODER3 = new TextDecoder();
|
|
1435
1229
|
var EncryptedStream = class {
|
|
1436
1230
|
constructor(response, controller, decryptor, idleTimeoutMs) {
|
|
1437
1231
|
this.decoder = new TextDecoder();
|
|
@@ -1497,7 +1291,7 @@ var EncryptedStream = class {
|
|
|
1497
1291
|
);
|
|
1498
1292
|
}
|
|
1499
1293
|
const plain = this.decryptor.openChunk(inner);
|
|
1500
|
-
const chunkJson =
|
|
1294
|
+
const chunkJson = DECODER3.decode(plain).trim();
|
|
1501
1295
|
const first = !this.openedAny;
|
|
1502
1296
|
this.openedAny = true;
|
|
1503
1297
|
if (first && isStreamTerminatorDeclaration(chunkJson)) {
|
|
@@ -1551,8 +1345,8 @@ var EncryptedStream = class {
|
|
|
1551
1345
|
};
|
|
1552
1346
|
|
|
1553
1347
|
// src/resources/chat/completions.ts
|
|
1554
|
-
var
|
|
1555
|
-
var
|
|
1348
|
+
var ENCODER3 = new TextEncoder();
|
|
1349
|
+
var DECODER4 = new TextDecoder();
|
|
1556
1350
|
var Completions = class {
|
|
1557
1351
|
constructor(client) {
|
|
1558
1352
|
this.client = client;
|
|
@@ -1593,7 +1387,7 @@ var Completions = class {
|
|
|
1593
1387
|
// The terminator request rides inside the sealed body, so the relay can
|
|
1594
1388
|
// neither strip nor add it: it asks the worker to seal the end of the
|
|
1595
1389
|
// stream (#2157).
|
|
1596
|
-
body:
|
|
1390
|
+
body: ENCODER3.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
|
|
1597
1391
|
messages: params.messages
|
|
1598
1392
|
});
|
|
1599
1393
|
if (stream) {
|
|
@@ -1609,7 +1403,7 @@ var Completions = class {
|
|
|
1609
1403
|
);
|
|
1610
1404
|
const { inner, placement } = await readSealedReply(response);
|
|
1611
1405
|
const plain = decryptor.openResult(inner);
|
|
1612
|
-
const completion = parseDecryptedCompletion(
|
|
1406
|
+
const completion = parseDecryptedCompletion(DECODER4.decode(plain), response.status);
|
|
1613
1407
|
return withPlacement(completion, response.headers, completion.pendra, placement);
|
|
1614
1408
|
}
|
|
1615
1409
|
};
|
|
@@ -1622,8 +1416,8 @@ var Chat = class {
|
|
|
1622
1416
|
};
|
|
1623
1417
|
|
|
1624
1418
|
// src/resources/embeddings.ts
|
|
1625
|
-
var
|
|
1626
|
-
var
|
|
1419
|
+
var ENCODER4 = new TextEncoder();
|
|
1420
|
+
var DECODER5 = new TextDecoder();
|
|
1627
1421
|
function validateParams(params) {
|
|
1628
1422
|
if (!params.model || typeof params.model !== "string") {
|
|
1629
1423
|
throw new Error("model must be a non-empty string");
|
|
@@ -1689,7 +1483,7 @@ var Embeddings = class {
|
|
|
1689
1483
|
model,
|
|
1690
1484
|
stream: false,
|
|
1691
1485
|
taskType: "embeddings",
|
|
1692
|
-
body:
|
|
1486
|
+
body: ENCODER4.encode(JSON.stringify(body))
|
|
1693
1487
|
});
|
|
1694
1488
|
const { response } = await this.client._fetch(
|
|
1695
1489
|
"/api/v1/embeddings",
|
|
@@ -1697,14 +1491,14 @@ var Embeddings = class {
|
|
|
1697
1491
|
);
|
|
1698
1492
|
const { inner, placement } = await readSealedReply(response);
|
|
1699
1493
|
const plain = decryptor.openResult(inner);
|
|
1700
|
-
const result = JSON.parse(
|
|
1494
|
+
const result = JSON.parse(DECODER5.decode(plain));
|
|
1701
1495
|
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1702
1496
|
}
|
|
1703
1497
|
};
|
|
1704
1498
|
|
|
1705
1499
|
// src/resources/images/generations.ts
|
|
1706
|
-
var
|
|
1707
|
-
var
|
|
1500
|
+
var ENCODER5 = new TextEncoder();
|
|
1501
|
+
var DECODER6 = new TextDecoder();
|
|
1708
1502
|
var SIZE_RE = /^\d+x\d+$/;
|
|
1709
1503
|
function validateParams2(params) {
|
|
1710
1504
|
if (!params.prompt || !params.prompt.trim()) {
|
|
@@ -1750,7 +1544,7 @@ var Generations = class {
|
|
|
1750
1544
|
model,
|
|
1751
1545
|
stream: false,
|
|
1752
1546
|
taskType: "image_generation",
|
|
1753
|
-
body:
|
|
1547
|
+
body: ENCODER5.encode(JSON.stringify(body))
|
|
1754
1548
|
});
|
|
1755
1549
|
const { response } = await this.client._fetch(
|
|
1756
1550
|
"/api/v1/images/generations",
|
|
@@ -1758,11 +1552,11 @@ var Generations = class {
|
|
|
1758
1552
|
);
|
|
1759
1553
|
const { inner, placement } = await readSealedReply(response);
|
|
1760
1554
|
const plain = decryptor.openResult(inner);
|
|
1761
|
-
const parsed = parseDecryptedJson(
|
|
1555
|
+
const parsed = parseDecryptedJson(DECODER6.decode(plain), response.status);
|
|
1762
1556
|
if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.data)) {
|
|
1763
1557
|
throw new APIResponseValidationError("Decrypted response was not an image generation", {
|
|
1764
1558
|
status: response.status,
|
|
1765
|
-
body:
|
|
1559
|
+
body: DECODER6.decode(plain)
|
|
1766
1560
|
});
|
|
1767
1561
|
}
|
|
1768
1562
|
const result = parsed;
|
|
@@ -1792,8 +1586,8 @@ var Models = class {
|
|
|
1792
1586
|
};
|
|
1793
1587
|
|
|
1794
1588
|
// src/resources/moderations.ts
|
|
1795
|
-
var
|
|
1796
|
-
var
|
|
1589
|
+
var ENCODER6 = new TextEncoder();
|
|
1590
|
+
var DECODER7 = new TextDecoder();
|
|
1797
1591
|
var MAX_INPUTS = 32;
|
|
1798
1592
|
function isPlainObject2(v) {
|
|
1799
1593
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -1894,7 +1688,7 @@ var Moderations = class {
|
|
|
1894
1688
|
model,
|
|
1895
1689
|
stream: false,
|
|
1896
1690
|
taskType: "moderation",
|
|
1897
|
-
body:
|
|
1691
|
+
body: ENCODER6.encode(JSON.stringify({ model: body.model, stream: false, input: body.input }))
|
|
1898
1692
|
});
|
|
1899
1693
|
const { response } = await this.client._fetch(
|
|
1900
1694
|
"/api/v1/moderations",
|
|
@@ -1903,7 +1697,7 @@ var Moderations = class {
|
|
|
1903
1697
|
const { inner, placement } = await readSealedReply(response);
|
|
1904
1698
|
const plain = decryptor.openResult(inner);
|
|
1905
1699
|
const result = asModeration(
|
|
1906
|
-
parseDecryptedJson(
|
|
1700
|
+
parseDecryptedJson(DECODER7.decode(plain), response.status),
|
|
1907
1701
|
response.status,
|
|
1908
1702
|
"Decrypted response"
|
|
1909
1703
|
);
|
|
@@ -1912,8 +1706,8 @@ var Moderations = class {
|
|
|
1912
1706
|
};
|
|
1913
1707
|
|
|
1914
1708
|
// src/resources/rerank.ts
|
|
1915
|
-
var
|
|
1916
|
-
var
|
|
1709
|
+
var ENCODER7 = new TextEncoder();
|
|
1710
|
+
var DECODER8 = new TextDecoder();
|
|
1917
1711
|
function validateParams4(params) {
|
|
1918
1712
|
if (!params.model || typeof params.model !== "string") {
|
|
1919
1713
|
throw new Error("model must be a non-empty string");
|
|
@@ -1973,7 +1767,7 @@ var Rerank = class {
|
|
|
1973
1767
|
model,
|
|
1974
1768
|
stream: false,
|
|
1975
1769
|
taskType: "rerank",
|
|
1976
|
-
body:
|
|
1770
|
+
body: ENCODER7.encode(JSON.stringify(body))
|
|
1977
1771
|
});
|
|
1978
1772
|
const { response } = await this.client._fetch(
|
|
1979
1773
|
"/api/v1/rerank",
|
|
@@ -1981,15 +1775,251 @@ var Rerank = class {
|
|
|
1981
1775
|
);
|
|
1982
1776
|
const { inner, placement } = await readSealedReply(response);
|
|
1983
1777
|
const plain = decryptor.openResult(inner);
|
|
1984
|
-
const result = JSON.parse(
|
|
1778
|
+
const result = JSON.parse(DECODER8.decode(plain));
|
|
1985
1779
|
return withPlacement(result, response.headers, result.pendra, placement);
|
|
1986
1780
|
}
|
|
1987
1781
|
};
|
|
1988
1782
|
|
|
1989
1783
|
// src/version.ts
|
|
1990
|
-
var VERSION = "0.
|
|
1784
|
+
var VERSION = "0.23.0";
|
|
1991
1785
|
var USER_AGENT = `pendra-node/${VERSION}`;
|
|
1992
1786
|
|
|
1787
|
+
// src/_privateInferenceEngine.ts
|
|
1788
|
+
var PrivateInferenceError = class extends Error {
|
|
1789
|
+
constructor(message) {
|
|
1790
|
+
super(message);
|
|
1791
|
+
this.name = "PrivateInferenceError";
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
|
|
1795
|
+
function parsePinnedFingerprints(pin) {
|
|
1796
|
+
if (typeof pin !== "string") {
|
|
1797
|
+
throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
|
|
1798
|
+
}
|
|
1799
|
+
const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
|
|
1800
|
+
if (fps.length === 0) {
|
|
1801
|
+
throw new PrivateInferenceError(
|
|
1802
|
+
"pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
|
|
1803
|
+
);
|
|
1804
|
+
}
|
|
1805
|
+
const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
|
|
1806
|
+
if (bad.length > 0) {
|
|
1807
|
+
throw new PrivateInferenceError(
|
|
1808
|
+
`pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
|
|
1809
|
+
);
|
|
1810
|
+
}
|
|
1811
|
+
return new Set(fps);
|
|
1812
|
+
}
|
|
1813
|
+
function defaultTofuPath() {
|
|
1814
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
1815
|
+
if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
|
|
1816
|
+
const home = env?.HOME || env?.USERPROFILE || ".";
|
|
1817
|
+
return `${home.replace(/\/$/, "")}/.pendra/known_org_keys.json`;
|
|
1818
|
+
}
|
|
1819
|
+
function isFsError(e) {
|
|
1820
|
+
const err = e;
|
|
1821
|
+
return e instanceof Error && typeof err.code === "string" && typeof err.syscall === "string";
|
|
1822
|
+
}
|
|
1823
|
+
var warnedTofuPaths = /* @__PURE__ */ new Set();
|
|
1824
|
+
function warnTofuUnwritable(tofuPath, e) {
|
|
1825
|
+
if (warnedTofuPaths.has(tofuPath)) return;
|
|
1826
|
+
warnedTofuPaths.add(tofuPath);
|
|
1827
|
+
console.warn(
|
|
1828
|
+
`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.`
|
|
1829
|
+
);
|
|
1830
|
+
}
|
|
1831
|
+
function b64d2(s) {
|
|
1832
|
+
if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(s, "base64"));
|
|
1833
|
+
const binary = atob(s);
|
|
1834
|
+
const out = new Uint8Array(binary.length);
|
|
1835
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
1836
|
+
return out;
|
|
1837
|
+
}
|
|
1838
|
+
var PrivateInferenceEngine = class {
|
|
1839
|
+
constructor(opts) {
|
|
1840
|
+
this.orgPubs = null;
|
|
1841
|
+
this.baseUrl = opts.baseUrl.replace(/\/$/, "");
|
|
1842
|
+
this.apiKey = opts.apiKey;
|
|
1843
|
+
const pin = opts.pinnedFingerprint;
|
|
1844
|
+
this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
|
|
1845
|
+
this.affinitySalt = opts.affinitySalt ?? null;
|
|
1846
|
+
this.tofuPath = opts.tofuPath || defaultTofuPath();
|
|
1847
|
+
}
|
|
1848
|
+
// --- key resolution ---
|
|
1849
|
+
cachedOrgPublicKeys() {
|
|
1850
|
+
return this.orgPubs;
|
|
1851
|
+
}
|
|
1852
|
+
cachedOrgPublicKey() {
|
|
1853
|
+
return this.orgPubs && this.orgPubs.length > 0 ? this.orgPubs[0] : null;
|
|
1854
|
+
}
|
|
1855
|
+
tofuIdentity() {
|
|
1856
|
+
const digest = sha256Hex(new TextEncoder().encode(this.apiKey)).slice(0, 16);
|
|
1857
|
+
return `${this.baseUrl}|${digest}`;
|
|
1858
|
+
}
|
|
1859
|
+
/**
|
|
1860
|
+
* Drop the cached key set so the next call re-fetches it.
|
|
1861
|
+
*
|
|
1862
|
+
* The cache is otherwise held for the whole process lifetime, which is
|
|
1863
|
+
* correct while a fleet keeps one key but fatal when it re-keys: a
|
|
1864
|
+
* long-running server would go on sealing to a fingerprint no worker holds
|
|
1865
|
+
* and fail EVERY request until someone restarted it. The API signals a re-key
|
|
1866
|
+
* with `X-Pendra-Error-Code: no_private_inference_worker`, and this is what
|
|
1867
|
+
* lets the client recover on its own.
|
|
1868
|
+
*
|
|
1869
|
+
* Pinned clients are deliberately NOT re-fetched on that signal — a pin is an
|
|
1870
|
+
* allowlist, so a fetch could only return fingerprints the pin already
|
|
1871
|
+
* rejects. They surface the error instead, which is what pinning means.
|
|
1872
|
+
*/
|
|
1873
|
+
invalidateOrgKey() {
|
|
1874
|
+
this.orgPubs = null;
|
|
1875
|
+
}
|
|
1876
|
+
/** Whether this client seals only to an explicit fingerprint allowlist. */
|
|
1877
|
+
get isPinned() {
|
|
1878
|
+
return this.pinnedFingerprints !== null;
|
|
1879
|
+
}
|
|
1880
|
+
/**
|
|
1881
|
+
* Validate the key(s) returned by GET /v1/private-inference/key, apply the pin
|
|
1882
|
+
* allowlist (or auto-trust TOFU), cache the accepted public keys, and return
|
|
1883
|
+
* them (newest-seen first). The client seals to **all** of the returned keys
|
|
1884
|
+
* so any worker holding any of them can serve the request. Throws
|
|
1885
|
+
* PrivateInferenceError on absence, a malformed key, or (when pinned) an empty
|
|
1886
|
+
* intersection with the pin set.
|
|
1887
|
+
*/
|
|
1888
|
+
async resolveOrgKey(fetchedKeys) {
|
|
1889
|
+
if (this.orgPubs !== null) return this.orgPubs;
|
|
1890
|
+
if (!fetchedKeys || fetchedKeys.length === 0) {
|
|
1891
|
+
throw new PrivateInferenceError(
|
|
1892
|
+
"No encryption key is registered for this organisation. Start a worker and it will be issued one automatically."
|
|
1893
|
+
);
|
|
1894
|
+
}
|
|
1895
|
+
const pubs = [];
|
|
1896
|
+
const fps = [];
|
|
1897
|
+
for (const entry of fetchedKeys) {
|
|
1898
|
+
let pub;
|
|
1899
|
+
try {
|
|
1900
|
+
pub = b64d2(entry.public_key);
|
|
1901
|
+
} catch (e) {
|
|
1902
|
+
throw new PrivateInferenceError(`Malformed workload key from the server: ${String(e)}`);
|
|
1903
|
+
}
|
|
1904
|
+
if (pub.length !== 32) {
|
|
1905
|
+
throw new PrivateInferenceError(
|
|
1906
|
+
`Workload key from the server is ${pub.length} bytes; expected a 32-byte X25519 key.`
|
|
1907
|
+
);
|
|
1908
|
+
}
|
|
1909
|
+
pubs.push(pub);
|
|
1910
|
+
fps.push(fingerprint(pub));
|
|
1911
|
+
}
|
|
1912
|
+
let accepted;
|
|
1913
|
+
if (this.pinnedFingerprints !== null) {
|
|
1914
|
+
accepted = pubs.filter((_p, i) => this.pinnedFingerprints.has(fps[i]));
|
|
1915
|
+
if (accepted.length === 0) {
|
|
1916
|
+
const pinned = Array.from(this.pinnedFingerprints).sort().join(", ");
|
|
1917
|
+
throw new PrivateInferenceError(
|
|
1918
|
+
`None of the org's workload key fingerprints (${fps.join(", ")}) match your pinned fingerprint(s) (${pinned}). Refusing to seal (possible man-in-the-middle). If your fleet re-keyed \u2014 which happens when every worker goes offline at once \u2014 update the pin to a current fingerprint from the console.`
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
} else {
|
|
1922
|
+
try {
|
|
1923
|
+
await this.tofuTrust(fps);
|
|
1924
|
+
} catch (e) {
|
|
1925
|
+
if (!isFsError(e)) throw e;
|
|
1926
|
+
warnTofuUnwritable(this.tofuPath, e);
|
|
1927
|
+
}
|
|
1928
|
+
accepted = pubs;
|
|
1929
|
+
}
|
|
1930
|
+
this.orgPubs = accepted;
|
|
1931
|
+
return accepted;
|
|
1932
|
+
}
|
|
1933
|
+
async tofuTrust(fps) {
|
|
1934
|
+
const store = await this.loadTofu();
|
|
1935
|
+
const identity = this.tofuIdentity();
|
|
1936
|
+
const known = store[identity];
|
|
1937
|
+
const trusted = /* @__PURE__ */ new Set();
|
|
1938
|
+
if (typeof known === "string") {
|
|
1939
|
+
trusted.add(known);
|
|
1940
|
+
} else if (Array.isArray(known)) {
|
|
1941
|
+
for (const f of known) if (typeof f === "string") trusted.add(f);
|
|
1942
|
+
}
|
|
1943
|
+
const before = trusted.size;
|
|
1944
|
+
for (const f of fps) trusted.add(f);
|
|
1945
|
+
if (trusted.size !== before || !Array.isArray(known)) {
|
|
1946
|
+
store[identity] = Array.from(trusted).sort();
|
|
1947
|
+
await this.saveTofu(store);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
async loadTofu() {
|
|
1951
|
+
const fs = await import("fs");
|
|
1952
|
+
let raw;
|
|
1953
|
+
try {
|
|
1954
|
+
raw = fs.readFileSync(this.tofuPath, "utf-8");
|
|
1955
|
+
} catch (e) {
|
|
1956
|
+
if (e.code === "ENOENT") return {};
|
|
1957
|
+
throw e;
|
|
1958
|
+
}
|
|
1959
|
+
let data;
|
|
1960
|
+
try {
|
|
1961
|
+
data = JSON.parse(raw);
|
|
1962
|
+
} catch {
|
|
1963
|
+
return {};
|
|
1964
|
+
}
|
|
1965
|
+
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
1966
|
+
}
|
|
1967
|
+
async saveTofu(store) {
|
|
1968
|
+
const fs = await import("fs");
|
|
1969
|
+
const path = await import("path");
|
|
1970
|
+
const directory = path.dirname(this.tofuPath) || ".";
|
|
1971
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
1972
|
+
const tmp = path.join(directory, `.known_org_keys.${process.pid}.${Date.now()}.tmp`);
|
|
1973
|
+
try {
|
|
1974
|
+
fs.writeFileSync(tmp, JSON.stringify(store), { mode: 384 });
|
|
1975
|
+
try {
|
|
1976
|
+
fs.chmodSync(tmp, 384);
|
|
1977
|
+
} catch {
|
|
1978
|
+
}
|
|
1979
|
+
fs.renameSync(tmp, this.tofuPath);
|
|
1980
|
+
} catch (e) {
|
|
1981
|
+
try {
|
|
1982
|
+
fs.unlinkSync(tmp);
|
|
1983
|
+
} catch {
|
|
1984
|
+
}
|
|
1985
|
+
throw e;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
// --- sealing ---
|
|
1989
|
+
/**
|
|
1990
|
+
* Seal a request body to the resolved org key. Returns `{ topLevel, decryptor }`.
|
|
1991
|
+
* `messages` (chat only) drives the affinity token; pass undefined for non-chat.
|
|
1992
|
+
* `binary` (audio only) is sealed under the same data key as the body.
|
|
1993
|
+
*/
|
|
1994
|
+
seal(args) {
|
|
1995
|
+
if (this.orgPubs === null || this.orgPubs.length === 0) {
|
|
1996
|
+
throw new PrivateInferenceError(
|
|
1997
|
+
"private inference: org key not resolved yet (call resolveOrgKey first)"
|
|
1998
|
+
);
|
|
1999
|
+
}
|
|
2000
|
+
let affinity = null;
|
|
2001
|
+
if (args.messages != null) {
|
|
2002
|
+
affinity = affinityKey(this.apiKey, args.model, args.messages, this.affinitySalt);
|
|
2003
|
+
}
|
|
2004
|
+
const { envelope, responseKeys } = sealRequest(this.orgPubs, args.body, {
|
|
2005
|
+
model: args.model,
|
|
2006
|
+
stream: args.stream,
|
|
2007
|
+
taskType: args.taskType,
|
|
2008
|
+
affinityKey: affinity,
|
|
2009
|
+
binary: args.binary ?? null
|
|
2010
|
+
});
|
|
2011
|
+
const topLevel = {
|
|
2012
|
+
model: args.model,
|
|
2013
|
+
stream: args.stream,
|
|
2014
|
+
pendra_encrypted: envelope
|
|
2015
|
+
};
|
|
2016
|
+
return { topLevel, decryptor: new ResponseDecryptor(responseKeys) };
|
|
2017
|
+
}
|
|
2018
|
+
get keyFetchUrl() {
|
|
2019
|
+
return `${this.baseUrl}/v1/private-inference/key`;
|
|
2020
|
+
}
|
|
2021
|
+
};
|
|
2022
|
+
|
|
1993
2023
|
// src/client.ts
|
|
1994
2024
|
function envTruthy(v) {
|
|
1995
2025
|
if (!v) return false;
|