pendra 0.15.0 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -297,6 +297,20 @@ function unsealedReplyError() {
297
297
  "private_inference: refusing an unencrypted reply to an encrypted request (it could have been forged in transit)"
298
298
  );
299
299
  }
300
+ var STREAM_TERMINATOR_KEY = "pendra_stream_terminator";
301
+ function isStreamTerminatorDeclaration(plaintext) {
302
+ try {
303
+ const obj = JSON.parse(plaintext);
304
+ return obj !== null && typeof obj === "object" && !Array.isArray(obj) && Object.keys(obj).length === 1 && obj[STREAM_TERMINATOR_KEY] === 1;
305
+ } catch {
306
+ return false;
307
+ }
308
+ }
309
+ function truncatedStreamError() {
310
+ return new Error(
311
+ "private_inference: the stream ended before the worker's sealed end-of-stream marker; the response may have been truncated in transit"
312
+ );
313
+ }
300
314
  var ResponseDecryptor = class {
301
315
  constructor(responseKeys) {
302
316
  this.dek = null;
@@ -844,6 +858,10 @@ var EncryptedStream = class {
844
858
  this.decoder = new TextDecoder();
845
859
  this.sse = new SseDecoder();
846
860
  this.done = false;
861
+ this.aborted = false;
862
+ this.openedAny = false;
863
+ this.declared = false;
864
+ this.terminated = false;
847
865
  if (!response.body) {
848
866
  throw new Error("Response body is null \u2014 streaming not supported");
849
867
  }
@@ -855,13 +873,18 @@ var EncryptedStream = class {
855
873
  async *[Symbol.asyncIterator]() {
856
874
  try {
857
875
  while (!this.done) {
858
- const { value, done: readerDone } = await readWithIdleTimeout(
859
- this.reader,
860
- this.idleTimeoutMs
861
- );
876
+ let read;
877
+ try {
878
+ read = await readWithIdleTimeout(this.reader, this.idleTimeoutMs);
879
+ } catch (e) {
880
+ if (this.terminated) return;
881
+ throw e;
882
+ }
883
+ const { value, done: readerDone } = read;
862
884
  const payloads = readerDone ? this.sse.flush() : this.sse.push(this.decoder.decode(value, { stream: true }));
863
885
  for (const data of payloads) {
864
886
  if (data === "[DONE]") {
887
+ this.checkEnded();
865
888
  this.done = true;
866
889
  return;
867
890
  }
@@ -869,6 +892,11 @@ var EncryptedStream = class {
869
892
  try {
870
893
  frame = JSON.parse(data);
871
894
  } catch {
895
+ if (this.aborted) continue;
896
+ if (readerDone) {
897
+ if (this.terminated) continue;
898
+ this.checkEnded();
899
+ }
872
900
  throw new APIResponseValidationError("Stream frame was not valid JSON", {
873
901
  body: data
874
902
  });
@@ -876,24 +904,39 @@ var EncryptedStream = class {
876
904
  const inner = frame?.pendra_encrypted;
877
905
  if (!inner) {
878
906
  if (isApiTimingChunk(frame)) {
907
+ this.checkEnded();
879
908
  yield parseStreamFrame(data);
880
909
  continue;
881
910
  }
882
911
  parseStreamFrame(data);
883
912
  throw unsealedReplyError();
884
913
  }
914
+ if (this.terminated) {
915
+ throw new Error(
916
+ "private_inference: refusing a frame after the worker's sealed end of stream"
917
+ );
918
+ }
885
919
  const plain = this.decryptor.openChunk(inner);
886
920
  const chunkJson = DECODER2.decode(plain).trim();
887
- if (!chunkJson || chunkJson === "[DONE]") {
888
- if (chunkJson === "[DONE]") {
889
- this.done = true;
890
- return;
891
- }
921
+ const first = !this.openedAny;
922
+ this.openedAny = true;
923
+ if (first && isStreamTerminatorDeclaration(chunkJson)) {
924
+ this.declared = true;
892
925
  continue;
893
926
  }
927
+ if (chunkJson === "[DONE]") {
928
+ if (this.declared) {
929
+ this.terminated = true;
930
+ continue;
931
+ }
932
+ this.done = true;
933
+ return;
934
+ }
935
+ if (!chunkJson) continue;
894
936
  yield parseStreamFrame(chunkJson, "Decrypted stream frame");
895
937
  }
896
938
  if (readerDone) {
939
+ this.checkEnded();
897
940
  this.done = true;
898
941
  break;
899
942
  }
@@ -902,7 +945,18 @@ var EncryptedStream = class {
902
945
  releaseReader(this.reader, this.controller, this.done);
903
946
  }
904
947
  }
948
+ /**
949
+ * The server ended the stream: it must have carried a sealed frame, and after
950
+ * a declaration, it must have ended on the sealed `[DONE]`.
951
+ */
952
+ checkEnded() {
953
+ if (this.aborted) return;
954
+ if (!this.openedAny || this.declared && !this.terminated) {
955
+ throw truncatedStreamError();
956
+ }
957
+ }
905
958
  abort() {
959
+ this.aborted = true;
906
960
  this.done = true;
907
961
  this.controller.abort();
908
962
  }
@@ -945,7 +999,10 @@ var Completions = class {
945
999
  model: params.model,
946
1000
  stream,
947
1001
  taskType: "chat",
948
- body: ENCODER2.encode(JSON.stringify(body)),
1002
+ // The terminator request rides inside the sealed body, so the relay can
1003
+ // neither strip nor add it: it asks the worker to seal the end of the
1004
+ // stream (#2157).
1005
+ body: ENCODER2.encode(JSON.stringify(stream ? { ...body, [STREAM_TERMINATOR_KEY]: 1 } : body)),
949
1006
  messages: params.messages
950
1007
  });
951
1008
  if (stream) {
@@ -1228,7 +1285,7 @@ var Rerank = class {
1228
1285
  };
1229
1286
 
1230
1287
  // src/version.ts
1231
- var VERSION = "0.15.0";
1288
+ var VERSION = "0.15.2";
1232
1289
  var USER_AGENT = `pendra-node/${VERSION}`;
1233
1290
 
1234
1291
  // src/_privateInferenceEngine.ts
@@ -1238,6 +1295,25 @@ var PrivateInferenceError = class extends Error {
1238
1295
  this.name = "PrivateInferenceError";
1239
1296
  }
1240
1297
  };
1298
+ var FINGERPRINT_RE = /^[0-9a-f]{64}$/;
1299
+ function parsePinnedFingerprints(pin) {
1300
+ if (typeof pin !== "string") {
1301
+ throw new PrivateInferenceError(`pinnedFingerprint must be a string, got ${typeof pin}.`);
1302
+ }
1303
+ const fps = pin.split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1304
+ if (fps.length === 0) {
1305
+ throw new PrivateInferenceError(
1306
+ "pinnedFingerprint was set but contains no fingerprint. Pass the 64-character fingerprint shown in the console, or leave it unset to use automatic trust."
1307
+ );
1308
+ }
1309
+ const bad = fps.filter((f) => !FINGERPRINT_RE.test(f)).sort();
1310
+ if (bad.length > 0) {
1311
+ throw new PrivateInferenceError(
1312
+ `pinnedFingerprint "${bad[0]}" is not a valid fingerprint: expected 64 hexadecimal characters, as shown in the console.`
1313
+ );
1314
+ }
1315
+ return new Set(fps);
1316
+ }
1241
1317
  function defaultTofuPath() {
1242
1318
  const env = typeof process !== "undefined" ? process.env : void 0;
1243
1319
  if (env?.PENDRA_TOFU_PATH) return env.PENDRA_TOFU_PATH;
@@ -1256,8 +1332,8 @@ var PrivateInferenceEngine = class {
1256
1332
  this.orgPubs = null;
1257
1333
  this.baseUrl = opts.baseUrl.replace(/\/$/, "");
1258
1334
  this.apiKey = opts.apiKey;
1259
- const fps = (opts.pinnedFingerprint || "").split(",").map((f) => f.trim().toLowerCase()).filter((f) => f.length > 0);
1260
- this.pinnedFingerprints = fps.length > 0 ? new Set(fps) : null;
1335
+ const pin = opts.pinnedFingerprint;
1336
+ this.pinnedFingerprints = pin === null || pin === void 0 ? null : parsePinnedFingerprints(pin);
1261
1337
  this.affinitySalt = opts.affinitySalt ?? null;
1262
1338
  this.tofuPath = opts.tofuPath || defaultTofuPath();
1263
1339
  }
@@ -1453,12 +1529,19 @@ var Pendra = class {
1453
1529
  }
1454
1530
  let pinnedFingerprint;
1455
1531
  if (typeof piOpt === "object" && piOpt !== null) {
1532
+ for (const key of Object.keys(piOpt)) {
1533
+ if (key !== "pinnedFingerprint") {
1534
+ throw new TypeError(
1535
+ `Unknown privateInference option "${key}". Accepted options: pinnedFingerprint.`
1536
+ );
1537
+ }
1538
+ }
1456
1539
  this.privateInferenceEnabled = true;
1457
1540
  pinnedFingerprint = piOpt.pinnedFingerprint;
1458
1541
  } else {
1459
1542
  this.privateInferenceEnabled = Boolean(piOpt);
1460
1543
  }
1461
- pinnedFingerprint = pinnedFingerprint ?? env?.PENDRA_PINNED_ORG_FINGERPRINT ?? void 0;
1544
+ pinnedFingerprint = pinnedFingerprint ?? (env?.PENDRA_PINNED_ORG_FINGERPRINT || void 0);
1462
1545
  if (this.privateInferenceEnabled) {
1463
1546
  const affinitySalt = env?.PENDRA_AFFINITY_SALT ? new TextEncoder().encode(env.PENDRA_AFFINITY_SALT) : null;
1464
1547
  this._piEngine = new PrivateInferenceEngine({