@vorim/sdk 3.22.0 → 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 +14 -0
  2. package/README.md +60 -6
  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 +61 -1
  12. package/dist/index.d.ts +61 -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
@@ -0,0 +1,726 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/httpSignatures.ts
31
+ var httpSignatures_exports = {};
32
+ __export(httpSignatures_exports, {
33
+ HttpSignatureError: () => HttpSignatureError,
34
+ contentDigest: () => contentDigest,
35
+ createSignatureBase: () => createSignatureBase,
36
+ httpSignatureAlgForKey: () => httpSignatureAlgForKey,
37
+ signHttpRequest: () => signHttpRequest,
38
+ verifyHttpRequest: () => verifyHttpRequest
39
+ });
40
+ module.exports = __toCommonJS(httpSignatures_exports);
41
+ var FUTURE_SKEW_SECONDS = 60;
42
+ var HttpSignatureError = class extends Error {
43
+ constructor(message) {
44
+ super(message);
45
+ this.name = "HttpSignatureError";
46
+ }
47
+ };
48
+ var SfParser = class {
49
+ constructor(s) {
50
+ this.s = s;
51
+ }
52
+ s;
53
+ i = 0;
54
+ fail(msg) {
55
+ throw new HttpSignatureError(`structured field parse error: ${msg} at ${this.i}`);
56
+ }
57
+ peek() {
58
+ return this.s[this.i];
59
+ }
60
+ eof() {
61
+ return this.i >= this.s.length;
62
+ }
63
+ skipSP() {
64
+ while (this.s[this.i] === " ") this.i++;
65
+ }
66
+ skipOWS() {
67
+ while (this.s[this.i] === " " || this.s[this.i] === " ") this.i++;
68
+ }
69
+ parseDictionary() {
70
+ const out = [];
71
+ this.skipSP();
72
+ if (this.eof()) return out;
73
+ for (; ; ) {
74
+ const key = this.parseKey();
75
+ let member;
76
+ if (this.peek() === "=") {
77
+ this.i++;
78
+ member = this.parseItemOrInnerList();
79
+ } else {
80
+ member = { kind: "item", value: { t: "bool", v: true }, params: this.parseParams() };
81
+ }
82
+ const existing = out.findIndex(([k]) => k === key);
83
+ if (existing >= 0) out[existing] = [key, member];
84
+ else out.push([key, member]);
85
+ this.skipOWS();
86
+ if (this.eof()) return out;
87
+ if (this.peek() !== ",") this.fail('expected ","');
88
+ this.i++;
89
+ this.skipOWS();
90
+ if (this.eof()) this.fail('trailing ","');
91
+ }
92
+ }
93
+ parseItemOrInnerList() {
94
+ if (this.peek() === "(") return this.parseInnerList();
95
+ return this.parseItem();
96
+ }
97
+ parseInnerList() {
98
+ if (this.peek() !== "(") this.fail('expected "("');
99
+ this.i++;
100
+ const items = [];
101
+ for (; ; ) {
102
+ this.skipSP();
103
+ if (this.peek() === ")") {
104
+ this.i++;
105
+ return { kind: "list", items, params: this.parseParams() };
106
+ }
107
+ if (this.eof()) this.fail("unterminated inner list");
108
+ items.push(this.parseItem());
109
+ const c = this.peek();
110
+ if (c !== " " && c !== ")") this.fail('expected SP or ")"');
111
+ }
112
+ }
113
+ parseItem() {
114
+ const value = this.parseBareItem();
115
+ return { kind: "item", value, params: this.parseParams() };
116
+ }
117
+ parseParams() {
118
+ const out = [];
119
+ while (this.peek() === ";") {
120
+ this.i++;
121
+ this.skipSP();
122
+ const key = this.parseKey();
123
+ let value = { t: "bool", v: true };
124
+ if (this.peek() === "=") {
125
+ this.i++;
126
+ value = this.parseBareItem();
127
+ }
128
+ const existing = out.findIndex(([k]) => k === key);
129
+ if (existing >= 0) out[existing] = [key, value];
130
+ else out.push([key, value]);
131
+ }
132
+ return out;
133
+ }
134
+ parseKey() {
135
+ const m = /^[a-z*][a-z0-9_\-.*]*/.exec(this.s.slice(this.i));
136
+ if (!m) this.fail("expected key");
137
+ this.i += m[0].length;
138
+ return m[0];
139
+ }
140
+ parseBareItem() {
141
+ const c = this.peek();
142
+ if (c === '"') return this.parseString();
143
+ if (c === ":") return this.parseBytes();
144
+ if (c === "?") {
145
+ const v = this.s[this.i + 1];
146
+ if (v !== "0" && v !== "1") this.fail("bad boolean");
147
+ this.i += 2;
148
+ return { t: "bool", v: v === "1" };
149
+ }
150
+ if (c === "-" || c >= "0" && c <= "9") {
151
+ const m = /^-?\d{1,15}(\.\d{1,3})?/.exec(this.s.slice(this.i));
152
+ if (!m) this.fail("bad number");
153
+ this.i += m[0].length;
154
+ return m[1] ? { t: "dec", v: Number(m[0]) } : { t: "int", v: Number(m[0]) };
155
+ }
156
+ const tm = /^[A-Za-z*][!#$%&'*+\-.^_`|~0-9A-Za-z:/]*/.exec(this.s.slice(this.i));
157
+ if (tm) {
158
+ this.i += tm[0].length;
159
+ return { t: "tok", v: tm[0] };
160
+ }
161
+ this.fail("unexpected character");
162
+ }
163
+ parseString() {
164
+ this.i++;
165
+ let out = "";
166
+ for (; ; ) {
167
+ if (this.eof()) this.fail("unterminated string");
168
+ const c = this.s[this.i++];
169
+ if (c === "\\") {
170
+ const n = this.s[this.i++];
171
+ if (n !== '"' && n !== "\\") this.fail("bad escape");
172
+ out += n;
173
+ } else if (c === '"') {
174
+ return { t: "str", v: out };
175
+ } else {
176
+ const code = c.charCodeAt(0);
177
+ if (code < 32 || code > 126) this.fail("non-printable in string");
178
+ out += c;
179
+ }
180
+ }
181
+ }
182
+ parseBytes() {
183
+ this.i++;
184
+ const end = this.s.indexOf(":", this.i);
185
+ if (end < 0) this.fail("unterminated byte sequence");
186
+ const b64 = this.s.slice(this.i, end);
187
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) this.fail("bad base64");
188
+ this.i = end + 1;
189
+ return { t: "bin", v: base64ToBytes(b64) };
190
+ }
191
+ };
192
+ function serializeBareItem(b) {
193
+ switch (b.t) {
194
+ case "int":
195
+ return String(Math.trunc(b.v));
196
+ case "dec": {
197
+ const r = Math.round(b.v * 1e3) / 1e3;
198
+ return Number.isInteger(r) ? `${r}.0` : String(r);
199
+ }
200
+ case "str":
201
+ return serializeString(b.v);
202
+ case "tok":
203
+ return b.v;
204
+ case "bool":
205
+ return b.v ? "?1" : "?0";
206
+ case "bin":
207
+ return `:${bytesToBase64(b.v)}:`;
208
+ }
209
+ }
210
+ function serializeString(v) {
211
+ if (!/^[\x20-\x7e]*$/.test(v)) throw new HttpSignatureError(`string parameter must be printable ASCII: ${JSON.stringify(v)}`);
212
+ return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
213
+ }
214
+ function serializeParams(params) {
215
+ return params.map(([k, v]) => v.t === "bool" && v.v === true ? `;${k}` : `;${k}=${serializeBareItem(v)}`).join("");
216
+ }
217
+ function serializeItem(item) {
218
+ return serializeBareItem(item.value) + serializeParams(item.params);
219
+ }
220
+ function serializeInnerList(list) {
221
+ return `(${list.items.map(serializeItem).join(" ")})${serializeParams(list.params)}`;
222
+ }
223
+ var DERIVED = /* @__PURE__ */ new Set([
224
+ "@method",
225
+ "@target-uri",
226
+ "@authority",
227
+ "@scheme",
228
+ "@request-target",
229
+ "@path",
230
+ "@query",
231
+ "@query-param",
232
+ "@status"
233
+ ]);
234
+ function parseComponent(input) {
235
+ const s = input.trim();
236
+ let name;
237
+ let params;
238
+ if (s.startsWith('"')) {
239
+ const p = new SfParser(s);
240
+ const item = p.parseItem();
241
+ if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
242
+ if (item.value.t !== "str") throw new HttpSignatureError(`bad component identifier: ${input}`);
243
+ name = item.value.v;
244
+ params = item.params;
245
+ } else {
246
+ const semi = s.indexOf(";");
247
+ name = semi < 0 ? s : s.slice(0, semi);
248
+ const p = new SfParser(semi < 0 ? "" : s.slice(semi));
249
+ params = p.parseParams();
250
+ if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
251
+ }
252
+ if (!name) throw new HttpSignatureError("empty component name");
253
+ if (!name.startsWith("@")) name = name.toLowerCase();
254
+ return { name, params };
255
+ }
256
+ function serializeComponent(c) {
257
+ return serializeString(c.name) + serializeParams(c.params);
258
+ }
259
+ function componentKey(c) {
260
+ const sorted = [...c.params].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
261
+ return serializeString(c.name) + serializeParams(sorted);
262
+ }
263
+ function componentToItem(c) {
264
+ return { kind: "item", value: { t: "str", v: c.name }, params: c.params };
265
+ }
266
+ function fieldValues(headers, name) {
267
+ const out = [];
268
+ let found = false;
269
+ for (const [k, v] of Object.entries(headers ?? {})) {
270
+ if (k.toLowerCase() !== name || v === void 0 || v === null) continue;
271
+ found = true;
272
+ for (const one of Array.isArray(v) ? v : [v]) out.push(String(one));
273
+ }
274
+ return found ? out : null;
275
+ }
276
+ function cleanFieldValue(v) {
277
+ return v.replace(/\r?\n[ \t]+/g, " ").trim();
278
+ }
279
+ function formPercentEncode(s) {
280
+ const bytes = new TextEncoder().encode(s);
281
+ let out = "";
282
+ for (const b of bytes) {
283
+ const ch = String.fromCharCode(b);
284
+ if (/[A-Za-z0-9*\-._]/.test(ch)) out += ch;
285
+ else out += "%" + b.toString(16).toUpperCase().padStart(2, "0");
286
+ }
287
+ return out;
288
+ }
289
+ function parseUrl(url, what) {
290
+ if (!url) throw new HttpSignatureError(`${what} requires the message url`);
291
+ try {
292
+ return new URL(url);
293
+ } catch {
294
+ throw new HttpSignatureError(`invalid url: ${url}`);
295
+ }
296
+ }
297
+ function derivedValue(c, msg, isResponse) {
298
+ const nameParam = c.params.find(([k]) => k === "name");
299
+ if (c.name !== "@query-param" && nameParam) throw new HttpSignatureError(`parameter "name" is not valid on ${c.name}`);
300
+ switch (c.name) {
301
+ case "@method":
302
+ if (isResponse || !msg.method) throw new HttpSignatureError("@method requires a request");
303
+ return msg.method;
304
+ case "@target-uri": {
305
+ if (isResponse) throw new HttpSignatureError("@target-uri requires a request");
306
+ const u = parseUrl(msg.url, "@target-uri");
307
+ u.hash = "";
308
+ return u.href;
309
+ }
310
+ case "@authority":
311
+ if (isResponse) throw new HttpSignatureError("@authority requires a request");
312
+ return parseUrl(msg.url, "@authority").host.toLowerCase();
313
+ case "@scheme":
314
+ if (isResponse) throw new HttpSignatureError("@scheme requires a request");
315
+ return parseUrl(msg.url, "@scheme").protocol.replace(/:$/, "").toLowerCase();
316
+ case "@request-target": {
317
+ if (isResponse) throw new HttpSignatureError("@request-target requires a request");
318
+ const u = parseUrl(msg.url, "@request-target");
319
+ return (u.pathname || "/") + u.search;
320
+ }
321
+ case "@path":
322
+ if (isResponse) throw new HttpSignatureError("@path requires a request");
323
+ return parseUrl(msg.url, "@path").pathname || "/";
324
+ case "@query": {
325
+ if (isResponse) throw new HttpSignatureError("@query requires a request");
326
+ const u = parseUrl(msg.url, "@query");
327
+ return u.search || "?";
328
+ }
329
+ case "@query-param": {
330
+ if (isResponse) throw new HttpSignatureError("@query-param requires a request");
331
+ if (!nameParam || nameParam[1].t !== "str") throw new HttpSignatureError("@query-param requires a name parameter (String)");
332
+ const wanted = nameParam[1].v;
333
+ const u = parseUrl(msg.url, "@query-param");
334
+ const matches = [];
335
+ for (const [n, v] of new URLSearchParams(u.search)) {
336
+ if (formPercentEncode(n) === wanted) matches.push(v);
337
+ }
338
+ if (matches.length === 0) throw new HttpSignatureError(`query parameter "${wanted}" not found`);
339
+ if (matches.length > 1) throw new HttpSignatureError(`query parameter "${wanted}" occurs more than once and cannot be signed individually`);
340
+ return formPercentEncode(matches[0]);
341
+ }
342
+ case "@status":
343
+ if (!isResponse || msg.status === void 0) throw new HttpSignatureError("@status is only valid on a response");
344
+ return String(Math.trunc(msg.status)).padStart(3, "0");
345
+ default:
346
+ throw new HttpSignatureError(`unknown derived component ${c.name}`);
347
+ }
348
+ }
349
+ var FIELD_PARAMS = /* @__PURE__ */ new Set(["req", "bs"]);
350
+ var DERIVED_PARAMS = /* @__PURE__ */ new Set(["req", "name"]);
351
+ var UNSUPPORTED_FIELD_PARAMS = /* @__PURE__ */ new Set(["sf", "key", "tr"]);
352
+ function componentValue(c, message) {
353
+ const isDerived = c.name.startsWith("@");
354
+ if (c.name === "@signature-params") throw new HttpSignatureError("@signature-params cannot be a covered component");
355
+ if (isDerived && !DERIVED.has(c.name)) throw new HttpSignatureError(`unknown derived component ${c.name}`);
356
+ for (const [k, v] of c.params) {
357
+ const allowed = isDerived ? DERIVED_PARAMS : FIELD_PARAMS;
358
+ if (!allowed.has(k)) {
359
+ if (!isDerived && UNSUPPORTED_FIELD_PARAMS.has(k)) throw new HttpSignatureError(`component parameter "${k}" is not supported`);
360
+ throw new HttpSignatureError(`unknown component parameter "${k}" on ${c.name}`);
361
+ }
362
+ if ((k === "req" || k === "bs") && !(v.t === "bool" && v.v === true)) {
363
+ throw new HttpSignatureError(`component parameter "${k}" must be a true Boolean`);
364
+ }
365
+ }
366
+ let target = message;
367
+ let isResponse = message.status !== void 0;
368
+ if (c.params.some(([k]) => k === "req")) {
369
+ if (!isResponse) throw new HttpSignatureError(`component ${c.name} has the req parameter but the message is a request`);
370
+ if (!message.request) throw new HttpSignatureError(`component ${c.name} has the req parameter but no related request was given`);
371
+ target = message.request;
372
+ isResponse = false;
373
+ }
374
+ let value;
375
+ if (isDerived) {
376
+ value = derivedValue(c, target, isResponse);
377
+ } else {
378
+ const raw = fieldValues(target.headers, c.name);
379
+ if (raw === null) throw new HttpSignatureError(`header field "${c.name}" is missing`);
380
+ if (c.params.some(([k]) => k === "bs")) {
381
+ value = raw.map((v) => `:${bytesToBase64(new TextEncoder().encode(cleanFieldValue(v)))}:`).join(", ");
382
+ } else {
383
+ value = raw.map(cleanFieldValue).join(", ");
384
+ }
385
+ }
386
+ if (/[\r\n]/.test(value)) throw new HttpSignatureError(`component ${c.name} contains a newline`);
387
+ if (!/^[\x20-\x7e\t]*$/.test(value)) throw new HttpSignatureError(`component ${c.name} contains non-ASCII characters`);
388
+ return value;
389
+ }
390
+ function paramsFromObject(params) {
391
+ const out = [];
392
+ for (const [k, v] of Object.entries(params ?? {})) {
393
+ if (v === void 0 || v === null) continue;
394
+ if (!/^[a-z*][a-z0-9_\-.*]*$/.test(k)) throw new HttpSignatureError(`invalid signature parameter name "${k}"`);
395
+ if (typeof v === "number") {
396
+ if (!Number.isInteger(v)) throw new HttpSignatureError(`signature parameter "${k}" must be an integer`);
397
+ out.push([k, { t: "int", v }]);
398
+ } else if (typeof v === "boolean") {
399
+ out.push([k, { t: "bool", v }]);
400
+ } else {
401
+ out.push([k, { t: "str", v: String(v) }]);
402
+ }
403
+ }
404
+ return out;
405
+ }
406
+ function buildBase(message, components, params) {
407
+ const seen = /* @__PURE__ */ new Set();
408
+ const lines = [];
409
+ for (const c of components) {
410
+ const key = componentKey(c);
411
+ if (seen.has(key)) throw new HttpSignatureError(`duplicate component ${serializeComponent(c)}`);
412
+ seen.add(key);
413
+ lines.push(`${serializeComponent(c)}: ${componentValue(c, message)}`);
414
+ }
415
+ const signatureParams = serializeInnerList({ kind: "list", items: components.map(componentToItem), params });
416
+ lines.push(`"@signature-params": ${signatureParams}`);
417
+ const base = lines.join("\n");
418
+ if (!/^[\x20-\x7e\t\n]*$/.test(base)) throw new HttpSignatureError("signature base is not ASCII");
419
+ return { base, signatureParams };
420
+ }
421
+ function createSignatureBase(message, components, params = {}) {
422
+ return buildBase(message, components.map(parseComponent), paramsFromObject(params)).base;
423
+ }
424
+ function bytesToBase64(bytes) {
425
+ let s = "";
426
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
427
+ return btoa(s);
428
+ }
429
+ function base64ToBytes(b64) {
430
+ const raw = atob(b64);
431
+ const out = new Uint8Array(raw.length);
432
+ for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
433
+ return out;
434
+ }
435
+ function toBytes(body) {
436
+ return typeof body === "string" ? new TextEncoder().encode(body) : body;
437
+ }
438
+ function pemToDer(pem) {
439
+ const body = pem.replace(/-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----/, "").replace(/\s+/g, "");
440
+ if (!body) throw new HttpSignatureError("empty PEM");
441
+ return base64ToBytes(body);
442
+ }
443
+ function toArrayBuffer(bytes) {
444
+ const out = new ArrayBuffer(bytes.length);
445
+ new Uint8Array(out).set(bytes);
446
+ return out;
447
+ }
448
+ function constantTimeEqual(a, b) {
449
+ if (a.length !== b.length) return false;
450
+ let d = 0;
451
+ for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
452
+ return d === 0;
453
+ }
454
+ var OID_ED25519 = [6, 3, 43, 101, 112];
455
+ var OID_EC_PUBLIC_KEY = [6, 7, 42, 134, 72, 206, 61, 2, 1];
456
+ var OID_P256 = [6, 8, 42, 134, 72, 206, 61, 3, 1, 7];
457
+ function hasSeq(hay, needle) {
458
+ outer: for (let i = 0; i + needle.length <= hay.length; i++) {
459
+ for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
460
+ return true;
461
+ }
462
+ return false;
463
+ }
464
+ function algFromKeyDer(der) {
465
+ const head = der.slice(0, 32);
466
+ if (hasSeq(head, OID_ED25519)) return "ed25519";
467
+ if (hasSeq(head, OID_EC_PUBLIC_KEY)) {
468
+ if (hasSeq(der.slice(0, 40), OID_P256)) return "ecdsa-p256-sha256";
469
+ throw new HttpSignatureError("unsupported EC curve (only P-256 is supported)");
470
+ }
471
+ throw new HttpSignatureError("unsupported key type (Ed25519 or ECDSA P-256 required)");
472
+ }
473
+ function httpSignatureAlgForKey(pem) {
474
+ return algFromKeyDer(pemToDer(pem));
475
+ }
476
+ function subtle() {
477
+ return globalThis.crypto?.subtle;
478
+ }
479
+ async function digestBytes(alg, data) {
480
+ const s = subtle();
481
+ if (s) return new Uint8Array(await s.digest(alg === "sha-256" ? "SHA-256" : "SHA-512", toArrayBuffer(data)));
482
+ const nodeCrypto = await import("crypto");
483
+ return new Uint8Array(nodeCrypto.createHash(alg === "sha-256" ? "sha256" : "sha512").update(data).digest());
484
+ }
485
+ async function signBytes(alg, privateKeyPem, data) {
486
+ const s = subtle();
487
+ if (s) {
488
+ const der = toArrayBuffer(pemToDer(privateKeyPem));
489
+ if (alg === "ed25519") {
490
+ const key2 = await s.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
491
+ return new Uint8Array(await s.sign("Ed25519", key2, toArrayBuffer(data)));
492
+ }
493
+ const key = await s.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
494
+ return new Uint8Array(await s.sign({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(data)));
495
+ }
496
+ const nodeCrypto = await import("crypto");
497
+ if (alg === "ed25519") return new Uint8Array(nodeCrypto.sign(null, data, privateKeyPem));
498
+ return new Uint8Array(nodeCrypto.sign("sha256", data, { key: privateKeyPem, dsaEncoding: "ieee-p1363" }));
499
+ }
500
+ async function verifyBytes(alg, publicKeyPem, data, sig) {
501
+ if (sig.length !== 64) return false;
502
+ const s = subtle();
503
+ if (s) {
504
+ const der = toArrayBuffer(pemToDer(publicKeyPem));
505
+ if (alg === "ed25519") {
506
+ const key2 = await s.importKey("spki", der, { name: "Ed25519" }, false, ["verify"]);
507
+ return s.verify("Ed25519", key2, toArrayBuffer(sig), toArrayBuffer(data));
508
+ }
509
+ const key = await s.importKey("spki", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
510
+ return s.verify({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(sig), toArrayBuffer(data));
511
+ }
512
+ const nodeCrypto = await import("crypto");
513
+ if (alg === "ed25519") return nodeCrypto.verify(null, data, publicKeyPem, sig);
514
+ return nodeCrypto.verify("sha256", data, { key: publicKeyPem, dsaEncoding: "ieee-p1363" }, sig);
515
+ }
516
+ async function contentDigest(body, alg = "sha-256") {
517
+ if (alg !== "sha-256" && alg !== "sha-512") throw new HttpSignatureError(`unsupported digest algorithm ${alg}`);
518
+ return `${alg}=:${bytesToBase64(await digestBytes(alg, toBytes(body)))}:`;
519
+ }
520
+ async function checkContentDigest(fieldValue, body) {
521
+ let dict;
522
+ try {
523
+ dict = new SfParser(fieldValue).parseDictionary();
524
+ } catch {
525
+ return "Content-Digest is not a valid structured field";
526
+ }
527
+ const bytes = toBytes(body);
528
+ let checked = 0;
529
+ for (const [alg, member] of dict) {
530
+ if (alg !== "sha-256" && alg !== "sha-512") continue;
531
+ if (member.kind !== "item" || member.value.t !== "bin") return `Content-Digest ${alg} is not a byte sequence`;
532
+ const actual = await digestBytes(alg, bytes);
533
+ if (!constantTimeEqual(actual, member.value.v)) return `Content-Digest ${alg} does not match the body`;
534
+ checked++;
535
+ }
536
+ return checked > 0 ? null : "Content-Digest has no supported algorithm (sha-256 or sha-512)";
537
+ }
538
+ var LABEL_RE = /^[a-z*][a-z0-9_\-.*]*$/;
539
+ async function signHttpRequest(request, options) {
540
+ if (!options?.privateKey) throw new HttpSignatureError("signHttpRequest requires privateKey (PKCS#8 PEM)");
541
+ const label = options.label ?? "sig1";
542
+ if (!LABEL_RE.test(label)) throw new HttpSignatureError(`invalid label "${label}"`);
543
+ const keyAlg = httpSignatureAlgForKey(options.privateKey);
544
+ if (options.alg && options.alg !== keyAlg) {
545
+ throw new HttpSignatureError(`alg "${options.alg}" does not match the private key (${keyAlg})`);
546
+ }
547
+ const alg = keyAlg;
548
+ const headers = { ...request.headers ?? {} };
549
+ const hasBody = request.body !== void 0 && request.body !== null;
550
+ let digestHeader;
551
+ if (hasBody) {
552
+ digestHeader = await contentDigest(request.body, "sha-256");
553
+ for (const k of Object.keys(headers)) if (k.toLowerCase() === "content-digest") delete headers[k];
554
+ headers["content-digest"] = digestHeader;
555
+ }
556
+ let componentStrs;
557
+ if (options.components) {
558
+ componentStrs = [...options.components];
559
+ } else {
560
+ componentStrs = ["@method", "@target-uri", "@authority"];
561
+ if (fieldValues(headers, "content-type") !== null) componentStrs.push("content-type");
562
+ }
563
+ const components = componentStrs.map(parseComponent);
564
+ if (hasBody && !components.some((c) => c.name === "content-digest" && c.params.length === 0)) {
565
+ components.push({ name: "content-digest", params: [] });
566
+ }
567
+ const created = options.created ?? Math.floor(Date.now() / 1e3);
568
+ const expires = options.expires === null ? void 0 : options.expires ?? created + 300;
569
+ const params = { created };
570
+ if (expires !== void 0) params.expires = expires;
571
+ if (options.nonce !== void 0) params.nonce = options.nonce;
572
+ if (options.includeAlg !== false) params.alg = alg;
573
+ if (options.keyid !== void 0) params.keyid = options.keyid;
574
+ if (options.tag !== void 0) params.tag = options.tag;
575
+ const { base, signatureParams } = buildBase(
576
+ { method: request.method, url: request.url, headers, body: request.body },
577
+ components,
578
+ paramsFromObject(params)
579
+ );
580
+ const sig = await signBytes(alg, options.privateKey, new TextEncoder().encode(base));
581
+ const out = {
582
+ "Signature-Input": `${label}=${signatureParams}`,
583
+ "Signature": `${label}=:${bytesToBase64(sig)}:`
584
+ };
585
+ if (digestHeader) out["Content-Digest"] = digestHeader;
586
+ return { headers: out, signatureBase: base };
587
+ }
588
+ var SUPPORTED_ALGS = /* @__PURE__ */ new Set(["ed25519", "ecdsa-p256-sha256"]);
589
+ async function verifyHttpRequest(request, options) {
590
+ if (!options?.publicKey && !options?.resolveKey) {
591
+ throw new HttpSignatureError("verifyHttpRequest requires publicKey or resolveKey");
592
+ }
593
+ const result = {
594
+ valid: false,
595
+ label: options.label ?? "",
596
+ covered: [],
597
+ contentDigestChecked: false
598
+ };
599
+ const fail = (reason) => ({ ...result, valid: false, reason });
600
+ const inputRaw = fieldValues(request.headers, "signature-input");
601
+ const sigRaw = fieldValues(request.headers, "signature");
602
+ if (!inputRaw) return fail("missing Signature-Input header");
603
+ if (!sigRaw) return fail("missing Signature header");
604
+ let inputs;
605
+ let sigs;
606
+ try {
607
+ inputs = new SfParser(inputRaw.map(cleanFieldValue).join(", ")).parseDictionary();
608
+ sigs = new SfParser(sigRaw.map(cleanFieldValue).join(", ")).parseDictionary();
609
+ } catch (e) {
610
+ return fail(`malformed signature headers: ${e.message}`);
611
+ }
612
+ const label = options.label ?? inputs[0]?.[0];
613
+ if (!label) return fail("Signature-Input has no signatures");
614
+ result.label = label;
615
+ const input = inputs.find(([k]) => k === label)?.[1];
616
+ const sigMember = sigs.find(([k]) => k === label)?.[1];
617
+ if (!input) return fail(`no Signature-Input for label "${label}"`);
618
+ if (!sigMember) return fail(`no Signature for label "${label}"`);
619
+ if (input.kind !== "list") return fail("Signature-Input member is not an inner list");
620
+ if (sigMember.kind !== "item" || sigMember.value.t !== "bin") return fail("Signature member is not a byte sequence");
621
+ const components = [];
622
+ for (const item of input.items) {
623
+ if (item.value.t !== "str") return fail("covered component is not a string");
624
+ components.push({ name: item.value.v, params: item.params });
625
+ }
626
+ result.covered = components.map(serializeComponent);
627
+ const p = new Map(input.params);
628
+ const getInt = (k) => {
629
+ const v = p.get(k);
630
+ if (v === void 0) return void 0;
631
+ return v.t === "int" ? v.v : null;
632
+ };
633
+ const getStr = (k) => {
634
+ const v = p.get(k);
635
+ if (v === void 0) return void 0;
636
+ return v.t === "str" ? v.v : null;
637
+ };
638
+ const created = getInt("created");
639
+ const expires = getInt("expires");
640
+ const keyid = getStr("keyid");
641
+ const algParam = getStr("alg");
642
+ if (created === null) return fail("created must be an integer");
643
+ if (expires === null) return fail("expires must be an integer");
644
+ if (keyid === null) return fail("keyid must be a string");
645
+ if (algParam === null) return fail("alg must be a string");
646
+ result.created = created;
647
+ result.expires = expires;
648
+ result.keyid = keyid;
649
+ if (options.requiredComponents?.length) {
650
+ const have = new Set(components.map(componentKey));
651
+ for (const r of options.requiredComponents) {
652
+ let rc;
653
+ try {
654
+ rc = parseComponent(r);
655
+ } catch (e) {
656
+ return fail(e.message);
657
+ }
658
+ if (!have.has(componentKey(rc))) return fail(`required component ${serializeComponent(rc)} is not covered`);
659
+ }
660
+ }
661
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
662
+ if (expires !== void 0 && now > expires) return fail("signature has expired");
663
+ if (created !== void 0 && created > now + FUTURE_SKEW_SECONDS) return fail("signature created in the future");
664
+ if (options.maxAgeSeconds !== void 0) {
665
+ if (created === void 0) return fail("signature has no created parameter, so its age cannot be checked");
666
+ if (now - created > options.maxAgeSeconds) return fail("signature is older than maxAgeSeconds");
667
+ }
668
+ let publicKey = options.publicKey;
669
+ let resolvedAlg;
670
+ if (!publicKey) {
671
+ let resolved;
672
+ try {
673
+ resolved = await options.resolveKey(keyid);
674
+ } catch (e) {
675
+ return fail(`key resolution failed: ${e.message}`);
676
+ }
677
+ if (!resolved?.publicKey) return fail(`unknown key${keyid ? ` "${keyid}"` : ""}`);
678
+ publicKey = resolved.publicKey;
679
+ resolvedAlg = resolved.alg;
680
+ }
681
+ let keyAlg;
682
+ try {
683
+ keyAlg = httpSignatureAlgForKey(publicKey);
684
+ } catch (e) {
685
+ return fail(e.message);
686
+ }
687
+ if (algParam !== void 0 && !SUPPORTED_ALGS.has(algParam)) return fail(`unsupported algorithm "${algParam}"`);
688
+ if (algParam !== void 0 && algParam !== keyAlg) return fail(`alg "${algParam}" does not match the key (${keyAlg})`);
689
+ if (resolvedAlg !== void 0 && resolvedAlg !== keyAlg) return fail(`resolved key alg "${resolvedAlg}" does not match the key (${keyAlg})`);
690
+ result.alg = keyAlg;
691
+ let base;
692
+ try {
693
+ base = buildBase(
694
+ { method: request.method, url: request.url, headers: request.headers, body: request.body },
695
+ components,
696
+ input.params
697
+ ).base;
698
+ } catch (e) {
699
+ return fail(e.message);
700
+ }
701
+ let ok;
702
+ try {
703
+ ok = await verifyBytes(keyAlg, publicKey, new TextEncoder().encode(base), sigMember.value.v);
704
+ } catch (e) {
705
+ return fail(`signature check failed: ${e.message}`);
706
+ }
707
+ if (!ok) return fail("signature does not verify");
708
+ const coversDigest = components.some((c) => c.name === "content-digest");
709
+ if (coversDigest && request.body !== void 0 && request.body !== null) {
710
+ const dv = fieldValues(request.headers, "content-digest");
711
+ const reason = await checkContentDigest((dv ?? []).map(cleanFieldValue).join(", "), request.body);
712
+ if (reason) return fail(reason);
713
+ result.contentDigestChecked = true;
714
+ }
715
+ return { ...result, valid: true };
716
+ }
717
+ // Annotate the CommonJS export names for ESM import in node:
718
+ 0 && (module.exports = {
719
+ HttpSignatureError,
720
+ contentDigest,
721
+ createSignatureBase,
722
+ httpSignatureAlgForKey,
723
+ signHttpRequest,
724
+ verifyHttpRequest
725
+ });
726
+ //# sourceMappingURL=httpSignatures.cjs.map