@vorim/sdk 3.22.1 → 3.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.
Files changed (99) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +48 -0
  3. package/dist/httpSignatures.cjs +726 -0
  4. package/dist/httpSignatures.cjs.map +1 -0
  5. package/dist/httpSignatures.d.cts +131 -0
  6. package/dist/httpSignatures.d.ts +131 -0
  7. package/dist/httpSignatures.js +686 -0
  8. package/dist/httpSignatures.js.map +1 -0
  9. package/dist/index.cjs +764 -13
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +49 -1
  12. package/dist/index.d.ts +49 -1
  13. package/dist/index.js +757 -12
  14. package/dist/index.js.map +1 -1
  15. package/dist/integrations/anthropic.d.cts +1 -0
  16. package/dist/integrations/anthropic.d.ts +1 -0
  17. package/dist/integrations/ap2.d.cts +1 -0
  18. package/dist/integrations/ap2.d.ts +1 -0
  19. package/dist/integrations/aws-iam.d.cts +1 -0
  20. package/dist/integrations/aws-iam.d.ts +1 -0
  21. package/dist/integrations/bank-rails.d.cts +1 -0
  22. package/dist/integrations/bank-rails.d.ts +1 -0
  23. package/dist/integrations/circle.d.cts +1 -0
  24. package/dist/integrations/circle.d.ts +1 -0
  25. package/dist/integrations/cloudflare.d.cts +1 -0
  26. package/dist/integrations/cloudflare.d.ts +1 -0
  27. package/dist/integrations/coinbase-cdp.d.cts +1 -0
  28. package/dist/integrations/coinbase-cdp.d.ts +1 -0
  29. package/dist/integrations/commerce-agents.d.cts +1 -0
  30. package/dist/integrations/commerce-agents.d.ts +1 -0
  31. package/dist/integrations/crewai.d.cts +1 -0
  32. package/dist/integrations/crewai.d.ts +1 -0
  33. package/dist/integrations/entra.d.cts +1 -0
  34. package/dist/integrations/entra.d.ts +1 -0
  35. package/dist/integrations/fhir.d.cts +1 -0
  36. package/dist/integrations/fhir.d.ts +1 -0
  37. package/dist/integrations/grok.d.cts +1 -0
  38. package/dist/integrations/grok.d.ts +1 -0
  39. package/dist/integrations/guidewire.d.cts +1 -0
  40. package/dist/integrations/guidewire.d.ts +1 -0
  41. package/dist/integrations/hermes.d.cts +1 -0
  42. package/dist/integrations/hermes.d.ts +1 -0
  43. package/dist/integrations/jira.d.cts +1 -0
  44. package/dist/integrations/jira.d.ts +1 -0
  45. package/dist/integrations/langchain.d.cts +1 -0
  46. package/dist/integrations/langchain.d.ts +1 -0
  47. package/dist/integrations/langgraph.d.cts +1 -0
  48. package/dist/integrations/langgraph.d.ts +1 -0
  49. package/dist/integrations/legal.d.cts +1 -0
  50. package/dist/integrations/legal.d.ts +1 -0
  51. package/dist/integrations/life-sciences.d.cts +1 -0
  52. package/dist/integrations/life-sciences.d.ts +1 -0
  53. package/dist/integrations/linear.d.cts +1 -0
  54. package/dist/integrations/linear.d.ts +1 -0
  55. package/dist/integrations/lithic.d.cts +1 -0
  56. package/dist/integrations/lithic.d.ts +1 -0
  57. package/dist/integrations/llamaindex.d.cts +1 -0
  58. package/dist/integrations/llamaindex.d.ts +1 -0
  59. package/dist/integrations/marqeta.d.cts +1 -0
  60. package/dist/integrations/marqeta.d.ts +1 -0
  61. package/dist/integrations/modern-treasury.d.cts +1 -0
  62. package/dist/integrations/modern-treasury.d.ts +1 -0
  63. package/dist/integrations/muse.d.cts +1 -0
  64. package/dist/integrations/muse.d.ts +1 -0
  65. package/dist/integrations/nekuda.d.cts +1 -0
  66. package/dist/integrations/nekuda.d.ts +1 -0
  67. package/dist/integrations/okta.d.cts +1 -0
  68. package/dist/integrations/okta.d.ts +1 -0
  69. package/dist/integrations/openai.d.cts +1 -0
  70. package/dist/integrations/openai.d.ts +1 -0
  71. package/dist/integrations/openrouter.d.cts +1 -0
  72. package/dist/integrations/openrouter.d.ts +1 -0
  73. package/dist/integrations/paypal-agent.d.cts +1 -0
  74. package/dist/integrations/paypal-agent.d.ts +1 -0
  75. package/dist/integrations/perplexity.d.cts +1 -0
  76. package/dist/integrations/perplexity.d.ts +1 -0
  77. package/dist/integrations/plaid.d.cts +1 -0
  78. package/dist/integrations/plaid.d.ts +1 -0
  79. package/dist/integrations/ramp.d.cts +1 -0
  80. package/dist/integrations/ramp.d.ts +1 -0
  81. package/dist/integrations/shopify.d.cts +1 -0
  82. package/dist/integrations/shopify.d.ts +1 -0
  83. package/dist/integrations/skyfire.d.cts +1 -0
  84. package/dist/integrations/skyfire.d.ts +1 -0
  85. package/dist/integrations/stripe-acp.d.cts +1 -0
  86. package/dist/integrations/stripe-acp.d.ts +1 -0
  87. package/dist/integrations/stripe-issuing.d.cts +1 -0
  88. package/dist/integrations/stripe-issuing.d.ts +1 -0
  89. package/dist/integrations/truanon.d.cts +1 -0
  90. package/dist/integrations/truanon.d.ts +1 -0
  91. package/dist/integrations/typesafe.d.cts +1 -0
  92. package/dist/integrations/typesafe.d.ts +1 -0
  93. package/dist/integrations/ucp.d.cts +1 -0
  94. package/dist/integrations/ucp.d.ts +1 -0
  95. package/dist/integrations/vercel-ai.d.cts +1 -0
  96. package/dist/integrations/vercel-ai.d.ts +1 -0
  97. package/dist/integrations/x402.d.cts +1 -0
  98. package/dist/integrations/x402.d.ts +1 -0
  99. package/package.json +11 -1
package/dist/index.cjs CHANGED
@@ -32,6 +32,7 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  CANONICAL_TOOL_CATALOGUE_VERSION: () => CANONICAL_TOOL_CATALOGUE_VERSION,
34
34
  HMAC_SHA256_PREFIX: () => HMAC_SHA256_PREFIX,
35
+ HttpSignatureError: () => HttpSignatureError,
35
36
  SHA256_PREFIX: () => SHA256_PREFIX,
36
37
  VorimDeniedError: () => VorimDeniedError,
37
38
  VorimError: () => VorimError,
@@ -39,6 +40,8 @@ __export(index_exports, {
39
40
  canonicalPayloadV0: () => canonicalPayloadV0,
40
41
  canonicalPayloadV1: () => canonicalPayloadV1,
41
42
  commitPayload: () => commitPayload,
43
+ contentDigest: () => contentDigest,
44
+ createSignatureBase: () => createSignatureBase,
42
45
  default: () => createVorim,
43
46
  deviceLogin: () => deviceLogin,
44
47
  eventDigest: () => eventDigest,
@@ -47,11 +50,14 @@ __export(index_exports, {
47
50
  hashSystemPrompt: () => hashSystemPrompt,
48
51
  hashTool: () => hashTool,
49
52
  hashToolCatalogue: () => hashToolCatalogue,
53
+ httpSignatureAlgForKey: () => httpSignatureAlgForKey,
50
54
  isDigest: () => isDigest,
51
55
  isKeyedCommitment: () => isKeyedCommitment,
52
56
  jcsCanonicalise: () => jcsCanonicalise,
53
57
  portableReceiptCanonicalBytes: () => portableReceiptCanonicalBytes,
54
- prepareReplayContext: () => prepareReplayContext
58
+ prepareReplayContext: () => prepareReplayContext,
59
+ signHttpRequest: () => signHttpRequest,
60
+ verifyHttpRequest: () => verifyHttpRequest
55
61
  });
56
62
  module.exports = __toCommonJS(index_exports);
57
63
 
@@ -89,9 +95,9 @@ function jcsCanonicalise(value) {
89
95
  }
90
96
  async function sha256Hex(input) {
91
97
  const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
92
- const subtle = globalThis.crypto?.subtle;
93
- if (subtle) {
94
- const buf = await subtle.digest("SHA-256", bytes);
98
+ const subtle2 = globalThis.crypto?.subtle;
99
+ if (subtle2) {
100
+ const buf = await subtle2.digest("SHA-256", bytes);
95
101
  return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
96
102
  }
97
103
  const nodeCrypto = await import("crypto");
@@ -207,9 +213,9 @@ function toHex(buf) {
207
213
  }
208
214
  async function hashPayload(content) {
209
215
  const bytes = toBytes(content);
210
- const subtle = globalThis.crypto?.subtle;
211
- if (subtle) {
212
- return SHA256_PREFIX + toHex(await subtle.digest("SHA-256", bytes));
216
+ const subtle2 = globalThis.crypto?.subtle;
217
+ if (subtle2) {
218
+ return SHA256_PREFIX + toHex(await subtle2.digest("SHA-256", bytes));
213
219
  }
214
220
  const nodeCrypto = await import("crypto");
215
221
  return SHA256_PREFIX + nodeCrypto.createHash("sha256").update(bytes).digest("hex");
@@ -222,16 +228,16 @@ async function commitPayload(content, key) {
222
228
  );
223
229
  }
224
230
  const bytes = toBytes(content);
225
- const subtle = globalThis.crypto?.subtle;
226
- if (subtle) {
227
- const cryptoKey = await subtle.importKey(
231
+ const subtle2 = globalThis.crypto?.subtle;
232
+ if (subtle2) {
233
+ const cryptoKey = await subtle2.importKey(
228
234
  "raw",
229
235
  keyBytes,
230
236
  { name: "HMAC", hash: "SHA-256" },
231
237
  false,
232
238
  ["sign"]
233
239
  );
234
- const sig = await subtle.sign("HMAC", cryptoKey, bytes);
240
+ const sig = await subtle2.sign("HMAC", cryptoKey, bytes);
235
241
  return HMAC_SHA256_PREFIX + toHex(sig);
236
242
  }
237
243
  const nodeCrypto = await import("crypto");
@@ -245,8 +251,686 @@ function isDigest(digest) {
245
251
  return typeof digest === "string" && DIGEST_RE.test(digest);
246
252
  }
247
253
 
254
+ // src/httpSignatures.ts
255
+ var FUTURE_SKEW_SECONDS = 60;
256
+ var HttpSignatureError = class extends Error {
257
+ constructor(message) {
258
+ super(message);
259
+ this.name = "HttpSignatureError";
260
+ }
261
+ };
262
+ var SfParser = class {
263
+ constructor(s) {
264
+ this.s = s;
265
+ }
266
+ s;
267
+ i = 0;
268
+ fail(msg) {
269
+ throw new HttpSignatureError(`structured field parse error: ${msg} at ${this.i}`);
270
+ }
271
+ peek() {
272
+ return this.s[this.i];
273
+ }
274
+ eof() {
275
+ return this.i >= this.s.length;
276
+ }
277
+ skipSP() {
278
+ while (this.s[this.i] === " ") this.i++;
279
+ }
280
+ skipOWS() {
281
+ while (this.s[this.i] === " " || this.s[this.i] === " ") this.i++;
282
+ }
283
+ parseDictionary() {
284
+ const out = [];
285
+ this.skipSP();
286
+ if (this.eof()) return out;
287
+ for (; ; ) {
288
+ const key = this.parseKey();
289
+ let member;
290
+ if (this.peek() === "=") {
291
+ this.i++;
292
+ member = this.parseItemOrInnerList();
293
+ } else {
294
+ member = { kind: "item", value: { t: "bool", v: true }, params: this.parseParams() };
295
+ }
296
+ const existing = out.findIndex(([k]) => k === key);
297
+ if (existing >= 0) out[existing] = [key, member];
298
+ else out.push([key, member]);
299
+ this.skipOWS();
300
+ if (this.eof()) return out;
301
+ if (this.peek() !== ",") this.fail('expected ","');
302
+ this.i++;
303
+ this.skipOWS();
304
+ if (this.eof()) this.fail('trailing ","');
305
+ }
306
+ }
307
+ parseItemOrInnerList() {
308
+ if (this.peek() === "(") return this.parseInnerList();
309
+ return this.parseItem();
310
+ }
311
+ parseInnerList() {
312
+ if (this.peek() !== "(") this.fail('expected "("');
313
+ this.i++;
314
+ const items = [];
315
+ for (; ; ) {
316
+ this.skipSP();
317
+ if (this.peek() === ")") {
318
+ this.i++;
319
+ return { kind: "list", items, params: this.parseParams() };
320
+ }
321
+ if (this.eof()) this.fail("unterminated inner list");
322
+ items.push(this.parseItem());
323
+ const c = this.peek();
324
+ if (c !== " " && c !== ")") this.fail('expected SP or ")"');
325
+ }
326
+ }
327
+ parseItem() {
328
+ const value = this.parseBareItem();
329
+ return { kind: "item", value, params: this.parseParams() };
330
+ }
331
+ parseParams() {
332
+ const out = [];
333
+ while (this.peek() === ";") {
334
+ this.i++;
335
+ this.skipSP();
336
+ const key = this.parseKey();
337
+ let value = { t: "bool", v: true };
338
+ if (this.peek() === "=") {
339
+ this.i++;
340
+ value = this.parseBareItem();
341
+ }
342
+ const existing = out.findIndex(([k]) => k === key);
343
+ if (existing >= 0) out[existing] = [key, value];
344
+ else out.push([key, value]);
345
+ }
346
+ return out;
347
+ }
348
+ parseKey() {
349
+ const m = /^[a-z*][a-z0-9_\-.*]*/.exec(this.s.slice(this.i));
350
+ if (!m) this.fail("expected key");
351
+ this.i += m[0].length;
352
+ return m[0];
353
+ }
354
+ parseBareItem() {
355
+ const c = this.peek();
356
+ if (c === '"') return this.parseString();
357
+ if (c === ":") return this.parseBytes();
358
+ if (c === "?") {
359
+ const v = this.s[this.i + 1];
360
+ if (v !== "0" && v !== "1") this.fail("bad boolean");
361
+ this.i += 2;
362
+ return { t: "bool", v: v === "1" };
363
+ }
364
+ if (c === "-" || c >= "0" && c <= "9") {
365
+ const m = /^-?\d{1,15}(\.\d{1,3})?/.exec(this.s.slice(this.i));
366
+ if (!m) this.fail("bad number");
367
+ this.i += m[0].length;
368
+ return m[1] ? { t: "dec", v: Number(m[0]) } : { t: "int", v: Number(m[0]) };
369
+ }
370
+ const tm = /^[A-Za-z*][!#$%&'*+\-.^_`|~0-9A-Za-z:/]*/.exec(this.s.slice(this.i));
371
+ if (tm) {
372
+ this.i += tm[0].length;
373
+ return { t: "tok", v: tm[0] };
374
+ }
375
+ this.fail("unexpected character");
376
+ }
377
+ parseString() {
378
+ this.i++;
379
+ let out = "";
380
+ for (; ; ) {
381
+ if (this.eof()) this.fail("unterminated string");
382
+ const c = this.s[this.i++];
383
+ if (c === "\\") {
384
+ const n = this.s[this.i++];
385
+ if (n !== '"' && n !== "\\") this.fail("bad escape");
386
+ out += n;
387
+ } else if (c === '"') {
388
+ return { t: "str", v: out };
389
+ } else {
390
+ const code = c.charCodeAt(0);
391
+ if (code < 32 || code > 126) this.fail("non-printable in string");
392
+ out += c;
393
+ }
394
+ }
395
+ }
396
+ parseBytes() {
397
+ this.i++;
398
+ const end = this.s.indexOf(":", this.i);
399
+ if (end < 0) this.fail("unterminated byte sequence");
400
+ const b64 = this.s.slice(this.i, end);
401
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) this.fail("bad base64");
402
+ this.i = end + 1;
403
+ return { t: "bin", v: base64ToBytes(b64) };
404
+ }
405
+ };
406
+ function serializeBareItem(b) {
407
+ switch (b.t) {
408
+ case "int":
409
+ return String(Math.trunc(b.v));
410
+ case "dec": {
411
+ const r = Math.round(b.v * 1e3) / 1e3;
412
+ return Number.isInteger(r) ? `${r}.0` : String(r);
413
+ }
414
+ case "str":
415
+ return serializeString(b.v);
416
+ case "tok":
417
+ return b.v;
418
+ case "bool":
419
+ return b.v ? "?1" : "?0";
420
+ case "bin":
421
+ return `:${bytesToBase64(b.v)}:`;
422
+ }
423
+ }
424
+ function serializeString(v) {
425
+ if (!/^[\x20-\x7e]*$/.test(v)) throw new HttpSignatureError(`string parameter must be printable ASCII: ${JSON.stringify(v)}`);
426
+ return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
427
+ }
428
+ function serializeParams(params) {
429
+ return params.map(([k, v]) => v.t === "bool" && v.v === true ? `;${k}` : `;${k}=${serializeBareItem(v)}`).join("");
430
+ }
431
+ function serializeItem(item) {
432
+ return serializeBareItem(item.value) + serializeParams(item.params);
433
+ }
434
+ function serializeInnerList(list) {
435
+ return `(${list.items.map(serializeItem).join(" ")})${serializeParams(list.params)}`;
436
+ }
437
+ var DERIVED = /* @__PURE__ */ new Set([
438
+ "@method",
439
+ "@target-uri",
440
+ "@authority",
441
+ "@scheme",
442
+ "@request-target",
443
+ "@path",
444
+ "@query",
445
+ "@query-param",
446
+ "@status"
447
+ ]);
448
+ function parseComponent(input) {
449
+ const s = input.trim();
450
+ let name;
451
+ let params;
452
+ if (s.startsWith('"')) {
453
+ const p = new SfParser(s);
454
+ const item = p.parseItem();
455
+ if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
456
+ if (item.value.t !== "str") throw new HttpSignatureError(`bad component identifier: ${input}`);
457
+ name = item.value.v;
458
+ params = item.params;
459
+ } else {
460
+ const semi = s.indexOf(";");
461
+ name = semi < 0 ? s : s.slice(0, semi);
462
+ const p = new SfParser(semi < 0 ? "" : s.slice(semi));
463
+ params = p.parseParams();
464
+ if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
465
+ }
466
+ if (!name) throw new HttpSignatureError("empty component name");
467
+ if (!name.startsWith("@")) name = name.toLowerCase();
468
+ return { name, params };
469
+ }
470
+ function serializeComponent(c) {
471
+ return serializeString(c.name) + serializeParams(c.params);
472
+ }
473
+ function componentKey(c) {
474
+ const sorted = [...c.params].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
475
+ return serializeString(c.name) + serializeParams(sorted);
476
+ }
477
+ function componentToItem(c) {
478
+ return { kind: "item", value: { t: "str", v: c.name }, params: c.params };
479
+ }
480
+ function fieldValues(headers, name) {
481
+ const out = [];
482
+ let found = false;
483
+ for (const [k, v] of Object.entries(headers ?? {})) {
484
+ if (k.toLowerCase() !== name || v === void 0 || v === null) continue;
485
+ found = true;
486
+ for (const one of Array.isArray(v) ? v : [v]) out.push(String(one));
487
+ }
488
+ return found ? out : null;
489
+ }
490
+ function cleanFieldValue(v) {
491
+ return v.replace(/\r?\n[ \t]+/g, " ").trim();
492
+ }
493
+ function formPercentEncode(s) {
494
+ const bytes = new TextEncoder().encode(s);
495
+ let out = "";
496
+ for (const b of bytes) {
497
+ const ch = String.fromCharCode(b);
498
+ if (/[A-Za-z0-9*\-._]/.test(ch)) out += ch;
499
+ else out += "%" + b.toString(16).toUpperCase().padStart(2, "0");
500
+ }
501
+ return out;
502
+ }
503
+ function parseUrl(url, what) {
504
+ if (!url) throw new HttpSignatureError(`${what} requires the message url`);
505
+ try {
506
+ return new URL(url);
507
+ } catch {
508
+ throw new HttpSignatureError(`invalid url: ${url}`);
509
+ }
510
+ }
511
+ function derivedValue(c, msg, isResponse) {
512
+ const nameParam = c.params.find(([k]) => k === "name");
513
+ if (c.name !== "@query-param" && nameParam) throw new HttpSignatureError(`parameter "name" is not valid on ${c.name}`);
514
+ switch (c.name) {
515
+ case "@method":
516
+ if (isResponse || !msg.method) throw new HttpSignatureError("@method requires a request");
517
+ return msg.method;
518
+ case "@target-uri": {
519
+ if (isResponse) throw new HttpSignatureError("@target-uri requires a request");
520
+ const u = parseUrl(msg.url, "@target-uri");
521
+ u.hash = "";
522
+ return u.href;
523
+ }
524
+ case "@authority":
525
+ if (isResponse) throw new HttpSignatureError("@authority requires a request");
526
+ return parseUrl(msg.url, "@authority").host.toLowerCase();
527
+ case "@scheme":
528
+ if (isResponse) throw new HttpSignatureError("@scheme requires a request");
529
+ return parseUrl(msg.url, "@scheme").protocol.replace(/:$/, "").toLowerCase();
530
+ case "@request-target": {
531
+ if (isResponse) throw new HttpSignatureError("@request-target requires a request");
532
+ const u = parseUrl(msg.url, "@request-target");
533
+ return (u.pathname || "/") + u.search;
534
+ }
535
+ case "@path":
536
+ if (isResponse) throw new HttpSignatureError("@path requires a request");
537
+ return parseUrl(msg.url, "@path").pathname || "/";
538
+ case "@query": {
539
+ if (isResponse) throw new HttpSignatureError("@query requires a request");
540
+ const u = parseUrl(msg.url, "@query");
541
+ return u.search || "?";
542
+ }
543
+ case "@query-param": {
544
+ if (isResponse) throw new HttpSignatureError("@query-param requires a request");
545
+ if (!nameParam || nameParam[1].t !== "str") throw new HttpSignatureError("@query-param requires a name parameter (String)");
546
+ const wanted = nameParam[1].v;
547
+ const u = parseUrl(msg.url, "@query-param");
548
+ const matches = [];
549
+ for (const [n, v] of new URLSearchParams(u.search)) {
550
+ if (formPercentEncode(n) === wanted) matches.push(v);
551
+ }
552
+ if (matches.length === 0) throw new HttpSignatureError(`query parameter "${wanted}" not found`);
553
+ if (matches.length > 1) throw new HttpSignatureError(`query parameter "${wanted}" occurs more than once and cannot be signed individually`);
554
+ return formPercentEncode(matches[0]);
555
+ }
556
+ case "@status":
557
+ if (!isResponse || msg.status === void 0) throw new HttpSignatureError("@status is only valid on a response");
558
+ return String(Math.trunc(msg.status)).padStart(3, "0");
559
+ default:
560
+ throw new HttpSignatureError(`unknown derived component ${c.name}`);
561
+ }
562
+ }
563
+ var FIELD_PARAMS = /* @__PURE__ */ new Set(["req", "bs"]);
564
+ var DERIVED_PARAMS = /* @__PURE__ */ new Set(["req", "name"]);
565
+ var UNSUPPORTED_FIELD_PARAMS = /* @__PURE__ */ new Set(["sf", "key", "tr"]);
566
+ function componentValue(c, message) {
567
+ const isDerived = c.name.startsWith("@");
568
+ if (c.name === "@signature-params") throw new HttpSignatureError("@signature-params cannot be a covered component");
569
+ if (isDerived && !DERIVED.has(c.name)) throw new HttpSignatureError(`unknown derived component ${c.name}`);
570
+ for (const [k, v] of c.params) {
571
+ const allowed = isDerived ? DERIVED_PARAMS : FIELD_PARAMS;
572
+ if (!allowed.has(k)) {
573
+ if (!isDerived && UNSUPPORTED_FIELD_PARAMS.has(k)) throw new HttpSignatureError(`component parameter "${k}" is not supported`);
574
+ throw new HttpSignatureError(`unknown component parameter "${k}" on ${c.name}`);
575
+ }
576
+ if ((k === "req" || k === "bs") && !(v.t === "bool" && v.v === true)) {
577
+ throw new HttpSignatureError(`component parameter "${k}" must be a true Boolean`);
578
+ }
579
+ }
580
+ let target = message;
581
+ let isResponse = message.status !== void 0;
582
+ if (c.params.some(([k]) => k === "req")) {
583
+ if (!isResponse) throw new HttpSignatureError(`component ${c.name} has the req parameter but the message is a request`);
584
+ if (!message.request) throw new HttpSignatureError(`component ${c.name} has the req parameter but no related request was given`);
585
+ target = message.request;
586
+ isResponse = false;
587
+ }
588
+ let value;
589
+ if (isDerived) {
590
+ value = derivedValue(c, target, isResponse);
591
+ } else {
592
+ const raw = fieldValues(target.headers, c.name);
593
+ if (raw === null) throw new HttpSignatureError(`header field "${c.name}" is missing`);
594
+ if (c.params.some(([k]) => k === "bs")) {
595
+ value = raw.map((v) => `:${bytesToBase64(new TextEncoder().encode(cleanFieldValue(v)))}:`).join(", ");
596
+ } else {
597
+ value = raw.map(cleanFieldValue).join(", ");
598
+ }
599
+ }
600
+ if (/[\r\n]/.test(value)) throw new HttpSignatureError(`component ${c.name} contains a newline`);
601
+ if (!/^[\x20-\x7e\t]*$/.test(value)) throw new HttpSignatureError(`component ${c.name} contains non-ASCII characters`);
602
+ return value;
603
+ }
604
+ function paramsFromObject(params) {
605
+ const out = [];
606
+ for (const [k, v] of Object.entries(params ?? {})) {
607
+ if (v === void 0 || v === null) continue;
608
+ if (!/^[a-z*][a-z0-9_\-.*]*$/.test(k)) throw new HttpSignatureError(`invalid signature parameter name "${k}"`);
609
+ if (typeof v === "number") {
610
+ if (!Number.isInteger(v)) throw new HttpSignatureError(`signature parameter "${k}" must be an integer`);
611
+ out.push([k, { t: "int", v }]);
612
+ } else if (typeof v === "boolean") {
613
+ out.push([k, { t: "bool", v }]);
614
+ } else {
615
+ out.push([k, { t: "str", v: String(v) }]);
616
+ }
617
+ }
618
+ return out;
619
+ }
620
+ function buildBase(message, components, params) {
621
+ const seen = /* @__PURE__ */ new Set();
622
+ const lines = [];
623
+ for (const c of components) {
624
+ const key = componentKey(c);
625
+ if (seen.has(key)) throw new HttpSignatureError(`duplicate component ${serializeComponent(c)}`);
626
+ seen.add(key);
627
+ lines.push(`${serializeComponent(c)}: ${componentValue(c, message)}`);
628
+ }
629
+ const signatureParams = serializeInnerList({ kind: "list", items: components.map(componentToItem), params });
630
+ lines.push(`"@signature-params": ${signatureParams}`);
631
+ const base = lines.join("\n");
632
+ if (!/^[\x20-\x7e\t\n]*$/.test(base)) throw new HttpSignatureError("signature base is not ASCII");
633
+ return { base, signatureParams };
634
+ }
635
+ function createSignatureBase(message, components, params = {}) {
636
+ return buildBase(message, components.map(parseComponent), paramsFromObject(params)).base;
637
+ }
638
+ function bytesToBase64(bytes) {
639
+ let s = "";
640
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
641
+ return btoa(s);
642
+ }
643
+ function base64ToBytes(b64) {
644
+ const raw = atob(b64);
645
+ const out = new Uint8Array(raw.length);
646
+ for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
647
+ return out;
648
+ }
649
+ function toBytes2(body) {
650
+ return typeof body === "string" ? new TextEncoder().encode(body) : body;
651
+ }
652
+ function pemToDer(pem) {
653
+ const body = pem.replace(/-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----/, "").replace(/\s+/g, "");
654
+ if (!body) throw new HttpSignatureError("empty PEM");
655
+ return base64ToBytes(body);
656
+ }
657
+ function toArrayBuffer(bytes) {
658
+ const out = new ArrayBuffer(bytes.length);
659
+ new Uint8Array(out).set(bytes);
660
+ return out;
661
+ }
662
+ function constantTimeEqual(a, b) {
663
+ if (a.length !== b.length) return false;
664
+ let d = 0;
665
+ for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
666
+ return d === 0;
667
+ }
668
+ var OID_ED25519 = [6, 3, 43, 101, 112];
669
+ var OID_EC_PUBLIC_KEY = [6, 7, 42, 134, 72, 206, 61, 2, 1];
670
+ var OID_P256 = [6, 8, 42, 134, 72, 206, 61, 3, 1, 7];
671
+ function hasSeq(hay, needle) {
672
+ outer: for (let i = 0; i + needle.length <= hay.length; i++) {
673
+ for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
674
+ return true;
675
+ }
676
+ return false;
677
+ }
678
+ function algFromKeyDer(der) {
679
+ const head = der.slice(0, 32);
680
+ if (hasSeq(head, OID_ED25519)) return "ed25519";
681
+ if (hasSeq(head, OID_EC_PUBLIC_KEY)) {
682
+ if (hasSeq(der.slice(0, 40), OID_P256)) return "ecdsa-p256-sha256";
683
+ throw new HttpSignatureError("unsupported EC curve (only P-256 is supported)");
684
+ }
685
+ throw new HttpSignatureError("unsupported key type (Ed25519 or ECDSA P-256 required)");
686
+ }
687
+ function httpSignatureAlgForKey(pem) {
688
+ return algFromKeyDer(pemToDer(pem));
689
+ }
690
+ function subtle() {
691
+ return globalThis.crypto?.subtle;
692
+ }
693
+ async function digestBytes(alg, data) {
694
+ const s = subtle();
695
+ if (s) return new Uint8Array(await s.digest(alg === "sha-256" ? "SHA-256" : "SHA-512", toArrayBuffer(data)));
696
+ const nodeCrypto = await import("crypto");
697
+ return new Uint8Array(nodeCrypto.createHash(alg === "sha-256" ? "sha256" : "sha512").update(data).digest());
698
+ }
699
+ async function signBytes(alg, privateKeyPem, data) {
700
+ const s = subtle();
701
+ if (s) {
702
+ const der = toArrayBuffer(pemToDer(privateKeyPem));
703
+ if (alg === "ed25519") {
704
+ const key2 = await s.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
705
+ return new Uint8Array(await s.sign("Ed25519", key2, toArrayBuffer(data)));
706
+ }
707
+ const key = await s.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
708
+ return new Uint8Array(await s.sign({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(data)));
709
+ }
710
+ const nodeCrypto = await import("crypto");
711
+ if (alg === "ed25519") return new Uint8Array(nodeCrypto.sign(null, data, privateKeyPem));
712
+ return new Uint8Array(nodeCrypto.sign("sha256", data, { key: privateKeyPem, dsaEncoding: "ieee-p1363" }));
713
+ }
714
+ async function verifyBytes(alg, publicKeyPem, data, sig) {
715
+ if (sig.length !== 64) return false;
716
+ const s = subtle();
717
+ if (s) {
718
+ const der = toArrayBuffer(pemToDer(publicKeyPem));
719
+ if (alg === "ed25519") {
720
+ const key2 = await s.importKey("spki", der, { name: "Ed25519" }, false, ["verify"]);
721
+ return s.verify("Ed25519", key2, toArrayBuffer(sig), toArrayBuffer(data));
722
+ }
723
+ const key = await s.importKey("spki", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
724
+ return s.verify({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(sig), toArrayBuffer(data));
725
+ }
726
+ const nodeCrypto = await import("crypto");
727
+ if (alg === "ed25519") return nodeCrypto.verify(null, data, publicKeyPem, sig);
728
+ return nodeCrypto.verify("sha256", data, { key: publicKeyPem, dsaEncoding: "ieee-p1363" }, sig);
729
+ }
730
+ async function contentDigest(body, alg = "sha-256") {
731
+ if (alg !== "sha-256" && alg !== "sha-512") throw new HttpSignatureError(`unsupported digest algorithm ${alg}`);
732
+ return `${alg}=:${bytesToBase64(await digestBytes(alg, toBytes2(body)))}:`;
733
+ }
734
+ async function checkContentDigest(fieldValue, body) {
735
+ let dict;
736
+ try {
737
+ dict = new SfParser(fieldValue).parseDictionary();
738
+ } catch {
739
+ return "Content-Digest is not a valid structured field";
740
+ }
741
+ const bytes = toBytes2(body);
742
+ let checked = 0;
743
+ for (const [alg, member] of dict) {
744
+ if (alg !== "sha-256" && alg !== "sha-512") continue;
745
+ if (member.kind !== "item" || member.value.t !== "bin") return `Content-Digest ${alg} is not a byte sequence`;
746
+ const actual = await digestBytes(alg, bytes);
747
+ if (!constantTimeEqual(actual, member.value.v)) return `Content-Digest ${alg} does not match the body`;
748
+ checked++;
749
+ }
750
+ return checked > 0 ? null : "Content-Digest has no supported algorithm (sha-256 or sha-512)";
751
+ }
752
+ var LABEL_RE = /^[a-z*][a-z0-9_\-.*]*$/;
753
+ async function signHttpRequest(request, options) {
754
+ if (!options?.privateKey) throw new HttpSignatureError("signHttpRequest requires privateKey (PKCS#8 PEM)");
755
+ const label = options.label ?? "sig1";
756
+ if (!LABEL_RE.test(label)) throw new HttpSignatureError(`invalid label "${label}"`);
757
+ const keyAlg = httpSignatureAlgForKey(options.privateKey);
758
+ if (options.alg && options.alg !== keyAlg) {
759
+ throw new HttpSignatureError(`alg "${options.alg}" does not match the private key (${keyAlg})`);
760
+ }
761
+ const alg = keyAlg;
762
+ const headers = { ...request.headers ?? {} };
763
+ const hasBody = request.body !== void 0 && request.body !== null;
764
+ let digestHeader;
765
+ if (hasBody) {
766
+ digestHeader = await contentDigest(request.body, "sha-256");
767
+ for (const k of Object.keys(headers)) if (k.toLowerCase() === "content-digest") delete headers[k];
768
+ headers["content-digest"] = digestHeader;
769
+ }
770
+ let componentStrs;
771
+ if (options.components) {
772
+ componentStrs = [...options.components];
773
+ } else {
774
+ componentStrs = ["@method", "@target-uri", "@authority"];
775
+ if (fieldValues(headers, "content-type") !== null) componentStrs.push("content-type");
776
+ }
777
+ const components = componentStrs.map(parseComponent);
778
+ if (hasBody && !components.some((c) => c.name === "content-digest" && c.params.length === 0)) {
779
+ components.push({ name: "content-digest", params: [] });
780
+ }
781
+ const created = options.created ?? Math.floor(Date.now() / 1e3);
782
+ const expires = options.expires === null ? void 0 : options.expires ?? created + 300;
783
+ const params = { created };
784
+ if (expires !== void 0) params.expires = expires;
785
+ if (options.nonce !== void 0) params.nonce = options.nonce;
786
+ if (options.includeAlg !== false) params.alg = alg;
787
+ if (options.keyid !== void 0) params.keyid = options.keyid;
788
+ if (options.tag !== void 0) params.tag = options.tag;
789
+ const { base, signatureParams } = buildBase(
790
+ { method: request.method, url: request.url, headers, body: request.body },
791
+ components,
792
+ paramsFromObject(params)
793
+ );
794
+ const sig = await signBytes(alg, options.privateKey, new TextEncoder().encode(base));
795
+ const out = {
796
+ "Signature-Input": `${label}=${signatureParams}`,
797
+ "Signature": `${label}=:${bytesToBase64(sig)}:`
798
+ };
799
+ if (digestHeader) out["Content-Digest"] = digestHeader;
800
+ return { headers: out, signatureBase: base };
801
+ }
802
+ var SUPPORTED_ALGS = /* @__PURE__ */ new Set(["ed25519", "ecdsa-p256-sha256"]);
803
+ async function verifyHttpRequest(request, options) {
804
+ if (!options?.publicKey && !options?.resolveKey) {
805
+ throw new HttpSignatureError("verifyHttpRequest requires publicKey or resolveKey");
806
+ }
807
+ const result = {
808
+ valid: false,
809
+ label: options.label ?? "",
810
+ covered: [],
811
+ contentDigestChecked: false
812
+ };
813
+ const fail = (reason) => ({ ...result, valid: false, reason });
814
+ const inputRaw = fieldValues(request.headers, "signature-input");
815
+ const sigRaw = fieldValues(request.headers, "signature");
816
+ if (!inputRaw) return fail("missing Signature-Input header");
817
+ if (!sigRaw) return fail("missing Signature header");
818
+ let inputs;
819
+ let sigs;
820
+ try {
821
+ inputs = new SfParser(inputRaw.map(cleanFieldValue).join(", ")).parseDictionary();
822
+ sigs = new SfParser(sigRaw.map(cleanFieldValue).join(", ")).parseDictionary();
823
+ } catch (e) {
824
+ return fail(`malformed signature headers: ${e.message}`);
825
+ }
826
+ const label = options.label ?? inputs[0]?.[0];
827
+ if (!label) return fail("Signature-Input has no signatures");
828
+ result.label = label;
829
+ const input = inputs.find(([k]) => k === label)?.[1];
830
+ const sigMember = sigs.find(([k]) => k === label)?.[1];
831
+ if (!input) return fail(`no Signature-Input for label "${label}"`);
832
+ if (!sigMember) return fail(`no Signature for label "${label}"`);
833
+ if (input.kind !== "list") return fail("Signature-Input member is not an inner list");
834
+ if (sigMember.kind !== "item" || sigMember.value.t !== "bin") return fail("Signature member is not a byte sequence");
835
+ const components = [];
836
+ for (const item of input.items) {
837
+ if (item.value.t !== "str") return fail("covered component is not a string");
838
+ components.push({ name: item.value.v, params: item.params });
839
+ }
840
+ result.covered = components.map(serializeComponent);
841
+ const p = new Map(input.params);
842
+ const getInt = (k) => {
843
+ const v = p.get(k);
844
+ if (v === void 0) return void 0;
845
+ return v.t === "int" ? v.v : null;
846
+ };
847
+ const getStr = (k) => {
848
+ const v = p.get(k);
849
+ if (v === void 0) return void 0;
850
+ return v.t === "str" ? v.v : null;
851
+ };
852
+ const created = getInt("created");
853
+ const expires = getInt("expires");
854
+ const keyid = getStr("keyid");
855
+ const algParam = getStr("alg");
856
+ if (created === null) return fail("created must be an integer");
857
+ if (expires === null) return fail("expires must be an integer");
858
+ if (keyid === null) return fail("keyid must be a string");
859
+ if (algParam === null) return fail("alg must be a string");
860
+ result.created = created;
861
+ result.expires = expires;
862
+ result.keyid = keyid;
863
+ if (options.requiredComponents?.length) {
864
+ const have = new Set(components.map(componentKey));
865
+ for (const r of options.requiredComponents) {
866
+ let rc;
867
+ try {
868
+ rc = parseComponent(r);
869
+ } catch (e) {
870
+ return fail(e.message);
871
+ }
872
+ if (!have.has(componentKey(rc))) return fail(`required component ${serializeComponent(rc)} is not covered`);
873
+ }
874
+ }
875
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
876
+ if (expires !== void 0 && now > expires) return fail("signature has expired");
877
+ if (created !== void 0 && created > now + FUTURE_SKEW_SECONDS) return fail("signature created in the future");
878
+ if (options.maxAgeSeconds !== void 0) {
879
+ if (created === void 0) return fail("signature has no created parameter, so its age cannot be checked");
880
+ if (now - created > options.maxAgeSeconds) return fail("signature is older than maxAgeSeconds");
881
+ }
882
+ let publicKey = options.publicKey;
883
+ let resolvedAlg;
884
+ if (!publicKey) {
885
+ let resolved;
886
+ try {
887
+ resolved = await options.resolveKey(keyid);
888
+ } catch (e) {
889
+ return fail(`key resolution failed: ${e.message}`);
890
+ }
891
+ if (!resolved?.publicKey) return fail(`unknown key${keyid ? ` "${keyid}"` : ""}`);
892
+ publicKey = resolved.publicKey;
893
+ resolvedAlg = resolved.alg;
894
+ }
895
+ let keyAlg;
896
+ try {
897
+ keyAlg = httpSignatureAlgForKey(publicKey);
898
+ } catch (e) {
899
+ return fail(e.message);
900
+ }
901
+ if (algParam !== void 0 && !SUPPORTED_ALGS.has(algParam)) return fail(`unsupported algorithm "${algParam}"`);
902
+ if (algParam !== void 0 && algParam !== keyAlg) return fail(`alg "${algParam}" does not match the key (${keyAlg})`);
903
+ if (resolvedAlg !== void 0 && resolvedAlg !== keyAlg) return fail(`resolved key alg "${resolvedAlg}" does not match the key (${keyAlg})`);
904
+ result.alg = keyAlg;
905
+ let base;
906
+ try {
907
+ base = buildBase(
908
+ { method: request.method, url: request.url, headers: request.headers, body: request.body },
909
+ components,
910
+ input.params
911
+ ).base;
912
+ } catch (e) {
913
+ return fail(e.message);
914
+ }
915
+ let ok;
916
+ try {
917
+ ok = await verifyBytes(keyAlg, publicKey, new TextEncoder().encode(base), sigMember.value.v);
918
+ } catch (e) {
919
+ return fail(`signature check failed: ${e.message}`);
920
+ }
921
+ if (!ok) return fail("signature does not verify");
922
+ const coversDigest = components.some((c) => c.name === "content-digest");
923
+ if (coversDigest && request.body !== void 0 && request.body !== null) {
924
+ const dv = fieldValues(request.headers, "content-digest");
925
+ const reason = await checkContentDigest((dv ?? []).map(cleanFieldValue).join(", "), request.body);
926
+ if (reason) return fail(reason);
927
+ result.contentDigestChecked = true;
928
+ }
929
+ return { ...result, valid: true };
930
+ }
931
+
248
932
  // src/index.ts
249
- var SDK_VERSION = true ? "3.22.1" : "0.0.0";
933
+ var SDK_VERSION = true ? "3.23.0" : "0.0.0";
250
934
  var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
251
935
  function sleep(ms) {
252
936
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -1306,6 +1990,67 @@ var VorimSDK = class _VorimSDK {
1306
1990
  async requestToken(input) {
1307
1991
  return this.post("/credentials/token", input);
1308
1992
  }
1993
+ // ─── HTTP Message Signatures (RFC 9421) ─────────────────────────
1994
+ /**
1995
+ * Sign an outbound HTTP request (RFC 9421) with an agent's cached Ed25519
1996
+ * key, so the receiver can tell which Vorim agent sent it. `keyid` is the
1997
+ * agent_id, `alg` is `ed25519`, and `tag` defaults to `vorim`. When the
1998
+ * request has a body, a Content-Digest header is added and covered.
1999
+ *
2000
+ * The key must already be in this instance's keyring (from `register()`,
2001
+ * `registerEphemeral()` or `useAgentKey()`). Returns the headers to add.
2002
+ *
2003
+ * ```ts
2004
+ * const { headers } = await vorim.signHttpRequest(agentId, {
2005
+ * method: 'POST', url: 'https://agent-b.example/tasks',
2006
+ * headers: { 'content-type': 'application/json' }, body,
2007
+ * });
2008
+ * await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body });
2009
+ * ```
2010
+ */
2011
+ async signHttpRequest(agentId, request, options = {}) {
2012
+ const privateKey = this.agentKeys.get(agentId);
2013
+ if (!privateKey) {
2014
+ throw new VorimError(
2015
+ 400,
2016
+ "AGENT_KEY_NOT_LOADED",
2017
+ `No private key is cached for agent ${agentId}. Call register() or useAgentKey(agentId, privateKeyPem) first.`
2018
+ );
2019
+ }
2020
+ return signHttpRequest(request, {
2021
+ ...options,
2022
+ tag: options.tag ?? "vorim",
2023
+ privateKey,
2024
+ keyid: agentId,
2025
+ alg: "ed25519"
2026
+ });
2027
+ }
2028
+ /**
2029
+ * Verify an RFC 9421 signed request through Vorim. The server resolves the
2030
+ * signature's keyid (an agent_id) to that agent's registered public key,
2031
+ * rejects suspended or revoked agents, and checks Content-Digest when the
2032
+ * body is passed. Public endpoint: no API key scope is needed.
2033
+ *
2034
+ * Pass the request exactly as received: method, full URL, headers, and the
2035
+ * raw body if `content-digest` is covered.
2036
+ */
2037
+ async verifyHttpRequest(request, options = {}) {
2038
+ const payload = {
2039
+ method: request.method,
2040
+ url: request.url,
2041
+ headers: request.headers
2042
+ };
2043
+ if (typeof request.body === "string") {
2044
+ payload.body = request.body;
2045
+ } else if (request.body instanceof Uint8Array) {
2046
+ let bin = "";
2047
+ for (let i = 0; i < request.body.length; i++) bin += String.fromCharCode(request.body[i]);
2048
+ payload.body_base64 = btoa(bin);
2049
+ }
2050
+ if (options.label !== void 0) payload.label = options.label;
2051
+ if (options.maxAgeSeconds !== void 0) payload.max_age_seconds = options.maxAgeSeconds;
2052
+ return this.post("/http-signatures/verify", payload);
2053
+ }
1309
2054
  // ─── Signing ──────────────────────────────────────────────────────
1310
2055
  /**
1311
2056
  * Sign a payload with an Ed25519 private key (client-side).
@@ -1494,6 +2239,7 @@ async function deviceLogin(opts) {
1494
2239
  0 && (module.exports = {
1495
2240
  CANONICAL_TOOL_CATALOGUE_VERSION,
1496
2241
  HMAC_SHA256_PREFIX,
2242
+ HttpSignatureError,
1497
2243
  SHA256_PREFIX,
1498
2244
  VorimDeniedError,
1499
2245
  VorimError,
@@ -1501,6 +2247,8 @@ async function deviceLogin(opts) {
1501
2247
  canonicalPayloadV0,
1502
2248
  canonicalPayloadV1,
1503
2249
  commitPayload,
2250
+ contentDigest,
2251
+ createSignatureBase,
1504
2252
  deviceLogin,
1505
2253
  eventDigest,
1506
2254
  hashPayload,
@@ -1508,10 +2256,13 @@ async function deviceLogin(opts) {
1508
2256
  hashSystemPrompt,
1509
2257
  hashTool,
1510
2258
  hashToolCatalogue,
2259
+ httpSignatureAlgForKey,
1511
2260
  isDigest,
1512
2261
  isKeyedCommitment,
1513
2262
  jcsCanonicalise,
1514
2263
  portableReceiptCanonicalBytes,
1515
- prepareReplayContext
2264
+ prepareReplayContext,
2265
+ signHttpRequest,
2266
+ verifyHttpRequest
1516
2267
  });
1517
2268
  //# sourceMappingURL=index.cjs.map