@vorim/sdk 3.22.1 → 4.0.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/CHANGELOG.md +30 -0
- package/README.md +48 -0
- package/dist/httpSignatures.cjs +726 -0
- package/dist/httpSignatures.cjs.map +1 -0
- package/dist/httpSignatures.d.cts +131 -0
- package/dist/httpSignatures.d.ts +131 -0
- package/dist/httpSignatures.js +686 -0
- package/dist/httpSignatures.js.map +1 -0
- package/dist/index.cjs +975 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +243 -16
- package/dist/index.d.ts +243 -16
- package/dist/index.js +967 -25
- package/dist/index.js.map +1 -1
- package/dist/integrations/anthropic.d.cts +2 -1
- package/dist/integrations/anthropic.d.ts +2 -1
- package/dist/integrations/ap2.d.cts +2 -1
- package/dist/integrations/ap2.d.ts +2 -1
- package/dist/integrations/aws-iam.d.cts +2 -1
- package/dist/integrations/aws-iam.d.ts +2 -1
- package/dist/integrations/bank-rails.d.cts +2 -1
- package/dist/integrations/bank-rails.d.ts +2 -1
- package/dist/integrations/circle.d.cts +2 -1
- package/dist/integrations/circle.d.ts +2 -1
- package/dist/integrations/cloudflare.d.cts +2 -1
- package/dist/integrations/cloudflare.d.ts +2 -1
- package/dist/integrations/coinbase-cdp.d.cts +2 -1
- package/dist/integrations/coinbase-cdp.d.ts +2 -1
- package/dist/integrations/commerce-agents.d.cts +2 -1
- package/dist/integrations/commerce-agents.d.ts +2 -1
- package/dist/integrations/crewai.d.cts +2 -1
- package/dist/integrations/crewai.d.ts +2 -1
- package/dist/integrations/entra.d.cts +2 -1
- package/dist/integrations/entra.d.ts +2 -1
- package/dist/integrations/fhir.d.cts +2 -1
- package/dist/integrations/fhir.d.ts +2 -1
- package/dist/integrations/grok.d.cts +2 -1
- package/dist/integrations/grok.d.ts +2 -1
- package/dist/integrations/guidewire.d.cts +2 -1
- package/dist/integrations/guidewire.d.ts +2 -1
- package/dist/integrations/hermes.d.cts +2 -1
- package/dist/integrations/hermes.d.ts +2 -1
- package/dist/integrations/jira.d.cts +2 -1
- package/dist/integrations/jira.d.ts +2 -1
- package/dist/integrations/langchain.d.cts +2 -1
- package/dist/integrations/langchain.d.ts +2 -1
- package/dist/integrations/langgraph.d.cts +2 -1
- package/dist/integrations/langgraph.d.ts +2 -1
- package/dist/integrations/legal.d.cts +2 -1
- package/dist/integrations/legal.d.ts +2 -1
- package/dist/integrations/life-sciences.d.cts +2 -1
- package/dist/integrations/life-sciences.d.ts +2 -1
- package/dist/integrations/linear.d.cts +2 -1
- package/dist/integrations/linear.d.ts +2 -1
- package/dist/integrations/lithic.d.cts +2 -1
- package/dist/integrations/lithic.d.ts +2 -1
- package/dist/integrations/llamaindex.d.cts +2 -1
- package/dist/integrations/llamaindex.d.ts +2 -1
- package/dist/integrations/marqeta.d.cts +2 -1
- package/dist/integrations/marqeta.d.ts +2 -1
- package/dist/integrations/modern-treasury.d.cts +2 -1
- package/dist/integrations/modern-treasury.d.ts +2 -1
- package/dist/integrations/muse.d.cts +2 -1
- package/dist/integrations/muse.d.ts +2 -1
- package/dist/integrations/nekuda.d.cts +2 -1
- package/dist/integrations/nekuda.d.ts +2 -1
- package/dist/integrations/okta.d.cts +2 -1
- package/dist/integrations/okta.d.ts +2 -1
- package/dist/integrations/openai.d.cts +2 -1
- package/dist/integrations/openai.d.ts +2 -1
- package/dist/integrations/openrouter.d.cts +2 -1
- package/dist/integrations/openrouter.d.ts +2 -1
- package/dist/integrations/paypal-agent.d.cts +2 -1
- package/dist/integrations/paypal-agent.d.ts +2 -1
- package/dist/integrations/perplexity.d.cts +2 -1
- package/dist/integrations/perplexity.d.ts +2 -1
- package/dist/integrations/plaid.d.cts +2 -1
- package/dist/integrations/plaid.d.ts +2 -1
- package/dist/integrations/ramp.d.cts +2 -1
- package/dist/integrations/ramp.d.ts +2 -1
- package/dist/integrations/shopify.d.cts +2 -1
- package/dist/integrations/shopify.d.ts +2 -1
- package/dist/integrations/siem.d.cts +1 -1
- package/dist/integrations/siem.d.ts +1 -1
- package/dist/integrations/skyfire.d.cts +2 -1
- package/dist/integrations/skyfire.d.ts +2 -1
- package/dist/integrations/stripe-acp.d.cts +2 -1
- package/dist/integrations/stripe-acp.d.ts +2 -1
- package/dist/integrations/stripe-issuing.d.cts +2 -1
- package/dist/integrations/stripe-issuing.d.ts +2 -1
- package/dist/integrations/truanon.d.cts +2 -1
- package/dist/integrations/truanon.d.ts +2 -1
- package/dist/integrations/typesafe.d.cts +2 -1
- package/dist/integrations/typesafe.d.ts +2 -1
- package/dist/integrations/ucp.d.cts +2 -1
- package/dist/integrations/ucp.d.ts +2 -1
- package/dist/integrations/vercel-ai.d.cts +2 -1
- package/dist/integrations/vercel-ai.d.ts +2 -1
- package/dist/integrations/x402.d.cts +2 -1
- package/dist/integrations/x402.d.ts +2 -1
- package/dist/{types-BrDQAJdl.d.cts → types-DphtTyIC.d.cts} +72 -3
- package/dist/{types-BrDQAJdl.d.ts → types-DphtTyIC.d.ts} +72 -3
- package/package.json +11 -1
package/dist/index.js
CHANGED
|
@@ -32,9 +32,9 @@ function jcsCanonicalise(value) {
|
|
|
32
32
|
}
|
|
33
33
|
async function sha256Hex(input) {
|
|
34
34
|
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
35
|
-
const
|
|
36
|
-
if (
|
|
37
|
-
const buf = await
|
|
35
|
+
const subtle2 = globalThis.crypto?.subtle;
|
|
36
|
+
if (subtle2) {
|
|
37
|
+
const buf = await subtle2.digest("SHA-256", bytes);
|
|
38
38
|
return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
39
39
|
}
|
|
40
40
|
const nodeCrypto = await import("crypto");
|
|
@@ -150,9 +150,9 @@ function toHex(buf) {
|
|
|
150
150
|
}
|
|
151
151
|
async function hashPayload(content) {
|
|
152
152
|
const bytes = toBytes(content);
|
|
153
|
-
const
|
|
154
|
-
if (
|
|
155
|
-
return SHA256_PREFIX + toHex(await
|
|
153
|
+
const subtle2 = globalThis.crypto?.subtle;
|
|
154
|
+
if (subtle2) {
|
|
155
|
+
return SHA256_PREFIX + toHex(await subtle2.digest("SHA-256", bytes));
|
|
156
156
|
}
|
|
157
157
|
const nodeCrypto = await import("crypto");
|
|
158
158
|
return SHA256_PREFIX + nodeCrypto.createHash("sha256").update(bytes).digest("hex");
|
|
@@ -165,16 +165,16 @@ async function commitPayload(content, key) {
|
|
|
165
165
|
);
|
|
166
166
|
}
|
|
167
167
|
const bytes = toBytes(content);
|
|
168
|
-
const
|
|
169
|
-
if (
|
|
170
|
-
const cryptoKey = await
|
|
168
|
+
const subtle2 = globalThis.crypto?.subtle;
|
|
169
|
+
if (subtle2) {
|
|
170
|
+
const cryptoKey = await subtle2.importKey(
|
|
171
171
|
"raw",
|
|
172
172
|
keyBytes,
|
|
173
173
|
{ name: "HMAC", hash: "SHA-256" },
|
|
174
174
|
false,
|
|
175
175
|
["sign"]
|
|
176
176
|
);
|
|
177
|
-
const sig = await
|
|
177
|
+
const sig = await subtle2.sign("HMAC", cryptoKey, bytes);
|
|
178
178
|
return HMAC_SHA256_PREFIX + toHex(sig);
|
|
179
179
|
}
|
|
180
180
|
const nodeCrypto = await import("crypto");
|
|
@@ -188,8 +188,686 @@ function isDigest(digest) {
|
|
|
188
188
|
return typeof digest === "string" && DIGEST_RE.test(digest);
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
+
// src/httpSignatures.ts
|
|
192
|
+
var FUTURE_SKEW_SECONDS = 60;
|
|
193
|
+
var HttpSignatureError = class extends Error {
|
|
194
|
+
constructor(message) {
|
|
195
|
+
super(message);
|
|
196
|
+
this.name = "HttpSignatureError";
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
var SfParser = class {
|
|
200
|
+
constructor(s) {
|
|
201
|
+
this.s = s;
|
|
202
|
+
}
|
|
203
|
+
s;
|
|
204
|
+
i = 0;
|
|
205
|
+
fail(msg) {
|
|
206
|
+
throw new HttpSignatureError(`structured field parse error: ${msg} at ${this.i}`);
|
|
207
|
+
}
|
|
208
|
+
peek() {
|
|
209
|
+
return this.s[this.i];
|
|
210
|
+
}
|
|
211
|
+
eof() {
|
|
212
|
+
return this.i >= this.s.length;
|
|
213
|
+
}
|
|
214
|
+
skipSP() {
|
|
215
|
+
while (this.s[this.i] === " ") this.i++;
|
|
216
|
+
}
|
|
217
|
+
skipOWS() {
|
|
218
|
+
while (this.s[this.i] === " " || this.s[this.i] === " ") this.i++;
|
|
219
|
+
}
|
|
220
|
+
parseDictionary() {
|
|
221
|
+
const out = [];
|
|
222
|
+
this.skipSP();
|
|
223
|
+
if (this.eof()) return out;
|
|
224
|
+
for (; ; ) {
|
|
225
|
+
const key = this.parseKey();
|
|
226
|
+
let member;
|
|
227
|
+
if (this.peek() === "=") {
|
|
228
|
+
this.i++;
|
|
229
|
+
member = this.parseItemOrInnerList();
|
|
230
|
+
} else {
|
|
231
|
+
member = { kind: "item", value: { t: "bool", v: true }, params: this.parseParams() };
|
|
232
|
+
}
|
|
233
|
+
const existing = out.findIndex(([k]) => k === key);
|
|
234
|
+
if (existing >= 0) out[existing] = [key, member];
|
|
235
|
+
else out.push([key, member]);
|
|
236
|
+
this.skipOWS();
|
|
237
|
+
if (this.eof()) return out;
|
|
238
|
+
if (this.peek() !== ",") this.fail('expected ","');
|
|
239
|
+
this.i++;
|
|
240
|
+
this.skipOWS();
|
|
241
|
+
if (this.eof()) this.fail('trailing ","');
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
parseItemOrInnerList() {
|
|
245
|
+
if (this.peek() === "(") return this.parseInnerList();
|
|
246
|
+
return this.parseItem();
|
|
247
|
+
}
|
|
248
|
+
parseInnerList() {
|
|
249
|
+
if (this.peek() !== "(") this.fail('expected "("');
|
|
250
|
+
this.i++;
|
|
251
|
+
const items = [];
|
|
252
|
+
for (; ; ) {
|
|
253
|
+
this.skipSP();
|
|
254
|
+
if (this.peek() === ")") {
|
|
255
|
+
this.i++;
|
|
256
|
+
return { kind: "list", items, params: this.parseParams() };
|
|
257
|
+
}
|
|
258
|
+
if (this.eof()) this.fail("unterminated inner list");
|
|
259
|
+
items.push(this.parseItem());
|
|
260
|
+
const c = this.peek();
|
|
261
|
+
if (c !== " " && c !== ")") this.fail('expected SP or ")"');
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
parseItem() {
|
|
265
|
+
const value = this.parseBareItem();
|
|
266
|
+
return { kind: "item", value, params: this.parseParams() };
|
|
267
|
+
}
|
|
268
|
+
parseParams() {
|
|
269
|
+
const out = [];
|
|
270
|
+
while (this.peek() === ";") {
|
|
271
|
+
this.i++;
|
|
272
|
+
this.skipSP();
|
|
273
|
+
const key = this.parseKey();
|
|
274
|
+
let value = { t: "bool", v: true };
|
|
275
|
+
if (this.peek() === "=") {
|
|
276
|
+
this.i++;
|
|
277
|
+
value = this.parseBareItem();
|
|
278
|
+
}
|
|
279
|
+
const existing = out.findIndex(([k]) => k === key);
|
|
280
|
+
if (existing >= 0) out[existing] = [key, value];
|
|
281
|
+
else out.push([key, value]);
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
parseKey() {
|
|
286
|
+
const m = /^[a-z*][a-z0-9_\-.*]*/.exec(this.s.slice(this.i));
|
|
287
|
+
if (!m) this.fail("expected key");
|
|
288
|
+
this.i += m[0].length;
|
|
289
|
+
return m[0];
|
|
290
|
+
}
|
|
291
|
+
parseBareItem() {
|
|
292
|
+
const c = this.peek();
|
|
293
|
+
if (c === '"') return this.parseString();
|
|
294
|
+
if (c === ":") return this.parseBytes();
|
|
295
|
+
if (c === "?") {
|
|
296
|
+
const v = this.s[this.i + 1];
|
|
297
|
+
if (v !== "0" && v !== "1") this.fail("bad boolean");
|
|
298
|
+
this.i += 2;
|
|
299
|
+
return { t: "bool", v: v === "1" };
|
|
300
|
+
}
|
|
301
|
+
if (c === "-" || c >= "0" && c <= "9") {
|
|
302
|
+
const m = /^-?\d{1,15}(\.\d{1,3})?/.exec(this.s.slice(this.i));
|
|
303
|
+
if (!m) this.fail("bad number");
|
|
304
|
+
this.i += m[0].length;
|
|
305
|
+
return m[1] ? { t: "dec", v: Number(m[0]) } : { t: "int", v: Number(m[0]) };
|
|
306
|
+
}
|
|
307
|
+
const tm = /^[A-Za-z*][!#$%&'*+\-.^_`|~0-9A-Za-z:/]*/.exec(this.s.slice(this.i));
|
|
308
|
+
if (tm) {
|
|
309
|
+
this.i += tm[0].length;
|
|
310
|
+
return { t: "tok", v: tm[0] };
|
|
311
|
+
}
|
|
312
|
+
this.fail("unexpected character");
|
|
313
|
+
}
|
|
314
|
+
parseString() {
|
|
315
|
+
this.i++;
|
|
316
|
+
let out = "";
|
|
317
|
+
for (; ; ) {
|
|
318
|
+
if (this.eof()) this.fail("unterminated string");
|
|
319
|
+
const c = this.s[this.i++];
|
|
320
|
+
if (c === "\\") {
|
|
321
|
+
const n = this.s[this.i++];
|
|
322
|
+
if (n !== '"' && n !== "\\") this.fail("bad escape");
|
|
323
|
+
out += n;
|
|
324
|
+
} else if (c === '"') {
|
|
325
|
+
return { t: "str", v: out };
|
|
326
|
+
} else {
|
|
327
|
+
const code = c.charCodeAt(0);
|
|
328
|
+
if (code < 32 || code > 126) this.fail("non-printable in string");
|
|
329
|
+
out += c;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
parseBytes() {
|
|
334
|
+
this.i++;
|
|
335
|
+
const end = this.s.indexOf(":", this.i);
|
|
336
|
+
if (end < 0) this.fail("unterminated byte sequence");
|
|
337
|
+
const b64 = this.s.slice(this.i, end);
|
|
338
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) this.fail("bad base64");
|
|
339
|
+
this.i = end + 1;
|
|
340
|
+
return { t: "bin", v: base64ToBytes(b64) };
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
function serializeBareItem(b) {
|
|
344
|
+
switch (b.t) {
|
|
345
|
+
case "int":
|
|
346
|
+
return String(Math.trunc(b.v));
|
|
347
|
+
case "dec": {
|
|
348
|
+
const r = Math.round(b.v * 1e3) / 1e3;
|
|
349
|
+
return Number.isInteger(r) ? `${r}.0` : String(r);
|
|
350
|
+
}
|
|
351
|
+
case "str":
|
|
352
|
+
return serializeString(b.v);
|
|
353
|
+
case "tok":
|
|
354
|
+
return b.v;
|
|
355
|
+
case "bool":
|
|
356
|
+
return b.v ? "?1" : "?0";
|
|
357
|
+
case "bin":
|
|
358
|
+
return `:${bytesToBase64(b.v)}:`;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
function serializeString(v) {
|
|
362
|
+
if (!/^[\x20-\x7e]*$/.test(v)) throw new HttpSignatureError(`string parameter must be printable ASCII: ${JSON.stringify(v)}`);
|
|
363
|
+
return `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
364
|
+
}
|
|
365
|
+
function serializeParams(params) {
|
|
366
|
+
return params.map(([k, v]) => v.t === "bool" && v.v === true ? `;${k}` : `;${k}=${serializeBareItem(v)}`).join("");
|
|
367
|
+
}
|
|
368
|
+
function serializeItem(item) {
|
|
369
|
+
return serializeBareItem(item.value) + serializeParams(item.params);
|
|
370
|
+
}
|
|
371
|
+
function serializeInnerList(list) {
|
|
372
|
+
return `(${list.items.map(serializeItem).join(" ")})${serializeParams(list.params)}`;
|
|
373
|
+
}
|
|
374
|
+
var DERIVED = /* @__PURE__ */ new Set([
|
|
375
|
+
"@method",
|
|
376
|
+
"@target-uri",
|
|
377
|
+
"@authority",
|
|
378
|
+
"@scheme",
|
|
379
|
+
"@request-target",
|
|
380
|
+
"@path",
|
|
381
|
+
"@query",
|
|
382
|
+
"@query-param",
|
|
383
|
+
"@status"
|
|
384
|
+
]);
|
|
385
|
+
function parseComponent(input) {
|
|
386
|
+
const s = input.trim();
|
|
387
|
+
let name;
|
|
388
|
+
let params;
|
|
389
|
+
if (s.startsWith('"')) {
|
|
390
|
+
const p = new SfParser(s);
|
|
391
|
+
const item = p.parseItem();
|
|
392
|
+
if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
|
|
393
|
+
if (item.value.t !== "str") throw new HttpSignatureError(`bad component identifier: ${input}`);
|
|
394
|
+
name = item.value.v;
|
|
395
|
+
params = item.params;
|
|
396
|
+
} else {
|
|
397
|
+
const semi = s.indexOf(";");
|
|
398
|
+
name = semi < 0 ? s : s.slice(0, semi);
|
|
399
|
+
const p = new SfParser(semi < 0 ? "" : s.slice(semi));
|
|
400
|
+
params = p.parseParams();
|
|
401
|
+
if (!p.eof()) throw new HttpSignatureError(`bad component identifier: ${input}`);
|
|
402
|
+
}
|
|
403
|
+
if (!name) throw new HttpSignatureError("empty component name");
|
|
404
|
+
if (!name.startsWith("@")) name = name.toLowerCase();
|
|
405
|
+
return { name, params };
|
|
406
|
+
}
|
|
407
|
+
function serializeComponent(c) {
|
|
408
|
+
return serializeString(c.name) + serializeParams(c.params);
|
|
409
|
+
}
|
|
410
|
+
function componentKey(c) {
|
|
411
|
+
const sorted = [...c.params].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
412
|
+
return serializeString(c.name) + serializeParams(sorted);
|
|
413
|
+
}
|
|
414
|
+
function componentToItem(c) {
|
|
415
|
+
return { kind: "item", value: { t: "str", v: c.name }, params: c.params };
|
|
416
|
+
}
|
|
417
|
+
function fieldValues(headers, name) {
|
|
418
|
+
const out = [];
|
|
419
|
+
let found = false;
|
|
420
|
+
for (const [k, v] of Object.entries(headers ?? {})) {
|
|
421
|
+
if (k.toLowerCase() !== name || v === void 0 || v === null) continue;
|
|
422
|
+
found = true;
|
|
423
|
+
for (const one of Array.isArray(v) ? v : [v]) out.push(String(one));
|
|
424
|
+
}
|
|
425
|
+
return found ? out : null;
|
|
426
|
+
}
|
|
427
|
+
function cleanFieldValue(v) {
|
|
428
|
+
return v.replace(/\r?\n[ \t]+/g, " ").trim();
|
|
429
|
+
}
|
|
430
|
+
function formPercentEncode(s) {
|
|
431
|
+
const bytes = new TextEncoder().encode(s);
|
|
432
|
+
let out = "";
|
|
433
|
+
for (const b of bytes) {
|
|
434
|
+
const ch = String.fromCharCode(b);
|
|
435
|
+
if (/[A-Za-z0-9*\-._]/.test(ch)) out += ch;
|
|
436
|
+
else out += "%" + b.toString(16).toUpperCase().padStart(2, "0");
|
|
437
|
+
}
|
|
438
|
+
return out;
|
|
439
|
+
}
|
|
440
|
+
function parseUrl(url, what) {
|
|
441
|
+
if (!url) throw new HttpSignatureError(`${what} requires the message url`);
|
|
442
|
+
try {
|
|
443
|
+
return new URL(url);
|
|
444
|
+
} catch {
|
|
445
|
+
throw new HttpSignatureError(`invalid url: ${url}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function derivedValue(c, msg, isResponse) {
|
|
449
|
+
const nameParam = c.params.find(([k]) => k === "name");
|
|
450
|
+
if (c.name !== "@query-param" && nameParam) throw new HttpSignatureError(`parameter "name" is not valid on ${c.name}`);
|
|
451
|
+
switch (c.name) {
|
|
452
|
+
case "@method":
|
|
453
|
+
if (isResponse || !msg.method) throw new HttpSignatureError("@method requires a request");
|
|
454
|
+
return msg.method;
|
|
455
|
+
case "@target-uri": {
|
|
456
|
+
if (isResponse) throw new HttpSignatureError("@target-uri requires a request");
|
|
457
|
+
const u = parseUrl(msg.url, "@target-uri");
|
|
458
|
+
u.hash = "";
|
|
459
|
+
return u.href;
|
|
460
|
+
}
|
|
461
|
+
case "@authority":
|
|
462
|
+
if (isResponse) throw new HttpSignatureError("@authority requires a request");
|
|
463
|
+
return parseUrl(msg.url, "@authority").host.toLowerCase();
|
|
464
|
+
case "@scheme":
|
|
465
|
+
if (isResponse) throw new HttpSignatureError("@scheme requires a request");
|
|
466
|
+
return parseUrl(msg.url, "@scheme").protocol.replace(/:$/, "").toLowerCase();
|
|
467
|
+
case "@request-target": {
|
|
468
|
+
if (isResponse) throw new HttpSignatureError("@request-target requires a request");
|
|
469
|
+
const u = parseUrl(msg.url, "@request-target");
|
|
470
|
+
return (u.pathname || "/") + u.search;
|
|
471
|
+
}
|
|
472
|
+
case "@path":
|
|
473
|
+
if (isResponse) throw new HttpSignatureError("@path requires a request");
|
|
474
|
+
return parseUrl(msg.url, "@path").pathname || "/";
|
|
475
|
+
case "@query": {
|
|
476
|
+
if (isResponse) throw new HttpSignatureError("@query requires a request");
|
|
477
|
+
const u = parseUrl(msg.url, "@query");
|
|
478
|
+
return u.search || "?";
|
|
479
|
+
}
|
|
480
|
+
case "@query-param": {
|
|
481
|
+
if (isResponse) throw new HttpSignatureError("@query-param requires a request");
|
|
482
|
+
if (!nameParam || nameParam[1].t !== "str") throw new HttpSignatureError("@query-param requires a name parameter (String)");
|
|
483
|
+
const wanted = nameParam[1].v;
|
|
484
|
+
const u = parseUrl(msg.url, "@query-param");
|
|
485
|
+
const matches = [];
|
|
486
|
+
for (const [n, v] of new URLSearchParams(u.search)) {
|
|
487
|
+
if (formPercentEncode(n) === wanted) matches.push(v);
|
|
488
|
+
}
|
|
489
|
+
if (matches.length === 0) throw new HttpSignatureError(`query parameter "${wanted}" not found`);
|
|
490
|
+
if (matches.length > 1) throw new HttpSignatureError(`query parameter "${wanted}" occurs more than once and cannot be signed individually`);
|
|
491
|
+
return formPercentEncode(matches[0]);
|
|
492
|
+
}
|
|
493
|
+
case "@status":
|
|
494
|
+
if (!isResponse || msg.status === void 0) throw new HttpSignatureError("@status is only valid on a response");
|
|
495
|
+
return String(Math.trunc(msg.status)).padStart(3, "0");
|
|
496
|
+
default:
|
|
497
|
+
throw new HttpSignatureError(`unknown derived component ${c.name}`);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
var FIELD_PARAMS = /* @__PURE__ */ new Set(["req", "bs"]);
|
|
501
|
+
var DERIVED_PARAMS = /* @__PURE__ */ new Set(["req", "name"]);
|
|
502
|
+
var UNSUPPORTED_FIELD_PARAMS = /* @__PURE__ */ new Set(["sf", "key", "tr"]);
|
|
503
|
+
function componentValue(c, message) {
|
|
504
|
+
const isDerived = c.name.startsWith("@");
|
|
505
|
+
if (c.name === "@signature-params") throw new HttpSignatureError("@signature-params cannot be a covered component");
|
|
506
|
+
if (isDerived && !DERIVED.has(c.name)) throw new HttpSignatureError(`unknown derived component ${c.name}`);
|
|
507
|
+
for (const [k, v] of c.params) {
|
|
508
|
+
const allowed = isDerived ? DERIVED_PARAMS : FIELD_PARAMS;
|
|
509
|
+
if (!allowed.has(k)) {
|
|
510
|
+
if (!isDerived && UNSUPPORTED_FIELD_PARAMS.has(k)) throw new HttpSignatureError(`component parameter "${k}" is not supported`);
|
|
511
|
+
throw new HttpSignatureError(`unknown component parameter "${k}" on ${c.name}`);
|
|
512
|
+
}
|
|
513
|
+
if ((k === "req" || k === "bs") && !(v.t === "bool" && v.v === true)) {
|
|
514
|
+
throw new HttpSignatureError(`component parameter "${k}" must be a true Boolean`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
let target = message;
|
|
518
|
+
let isResponse = message.status !== void 0;
|
|
519
|
+
if (c.params.some(([k]) => k === "req")) {
|
|
520
|
+
if (!isResponse) throw new HttpSignatureError(`component ${c.name} has the req parameter but the message is a request`);
|
|
521
|
+
if (!message.request) throw new HttpSignatureError(`component ${c.name} has the req parameter but no related request was given`);
|
|
522
|
+
target = message.request;
|
|
523
|
+
isResponse = false;
|
|
524
|
+
}
|
|
525
|
+
let value;
|
|
526
|
+
if (isDerived) {
|
|
527
|
+
value = derivedValue(c, target, isResponse);
|
|
528
|
+
} else {
|
|
529
|
+
const raw = fieldValues(target.headers, c.name);
|
|
530
|
+
if (raw === null) throw new HttpSignatureError(`header field "${c.name}" is missing`);
|
|
531
|
+
if (c.params.some(([k]) => k === "bs")) {
|
|
532
|
+
value = raw.map((v) => `:${bytesToBase64(new TextEncoder().encode(cleanFieldValue(v)))}:`).join(", ");
|
|
533
|
+
} else {
|
|
534
|
+
value = raw.map(cleanFieldValue).join(", ");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (/[\r\n]/.test(value)) throw new HttpSignatureError(`component ${c.name} contains a newline`);
|
|
538
|
+
if (!/^[\x20-\x7e\t]*$/.test(value)) throw new HttpSignatureError(`component ${c.name} contains non-ASCII characters`);
|
|
539
|
+
return value;
|
|
540
|
+
}
|
|
541
|
+
function paramsFromObject(params) {
|
|
542
|
+
const out = [];
|
|
543
|
+
for (const [k, v] of Object.entries(params ?? {})) {
|
|
544
|
+
if (v === void 0 || v === null) continue;
|
|
545
|
+
if (!/^[a-z*][a-z0-9_\-.*]*$/.test(k)) throw new HttpSignatureError(`invalid signature parameter name "${k}"`);
|
|
546
|
+
if (typeof v === "number") {
|
|
547
|
+
if (!Number.isInteger(v)) throw new HttpSignatureError(`signature parameter "${k}" must be an integer`);
|
|
548
|
+
out.push([k, { t: "int", v }]);
|
|
549
|
+
} else if (typeof v === "boolean") {
|
|
550
|
+
out.push([k, { t: "bool", v }]);
|
|
551
|
+
} else {
|
|
552
|
+
out.push([k, { t: "str", v: String(v) }]);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
function buildBase(message, components, params) {
|
|
558
|
+
const seen = /* @__PURE__ */ new Set();
|
|
559
|
+
const lines = [];
|
|
560
|
+
for (const c of components) {
|
|
561
|
+
const key = componentKey(c);
|
|
562
|
+
if (seen.has(key)) throw new HttpSignatureError(`duplicate component ${serializeComponent(c)}`);
|
|
563
|
+
seen.add(key);
|
|
564
|
+
lines.push(`${serializeComponent(c)}: ${componentValue(c, message)}`);
|
|
565
|
+
}
|
|
566
|
+
const signatureParams = serializeInnerList({ kind: "list", items: components.map(componentToItem), params });
|
|
567
|
+
lines.push(`"@signature-params": ${signatureParams}`);
|
|
568
|
+
const base = lines.join("\n");
|
|
569
|
+
if (!/^[\x20-\x7e\t\n]*$/.test(base)) throw new HttpSignatureError("signature base is not ASCII");
|
|
570
|
+
return { base, signatureParams };
|
|
571
|
+
}
|
|
572
|
+
function createSignatureBase(message, components, params = {}) {
|
|
573
|
+
return buildBase(message, components.map(parseComponent), paramsFromObject(params)).base;
|
|
574
|
+
}
|
|
575
|
+
function bytesToBase64(bytes) {
|
|
576
|
+
let s = "";
|
|
577
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
578
|
+
return btoa(s);
|
|
579
|
+
}
|
|
580
|
+
function base64ToBytes(b64) {
|
|
581
|
+
const raw = atob(b64);
|
|
582
|
+
const out = new Uint8Array(raw.length);
|
|
583
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
|
|
584
|
+
return out;
|
|
585
|
+
}
|
|
586
|
+
function toBytes2(body) {
|
|
587
|
+
return typeof body === "string" ? new TextEncoder().encode(body) : body;
|
|
588
|
+
}
|
|
589
|
+
function pemToDer(pem) {
|
|
590
|
+
const body = pem.replace(/-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----/, "").replace(/\s+/g, "");
|
|
591
|
+
if (!body) throw new HttpSignatureError("empty PEM");
|
|
592
|
+
return base64ToBytes(body);
|
|
593
|
+
}
|
|
594
|
+
function toArrayBuffer(bytes) {
|
|
595
|
+
const out = new ArrayBuffer(bytes.length);
|
|
596
|
+
new Uint8Array(out).set(bytes);
|
|
597
|
+
return out;
|
|
598
|
+
}
|
|
599
|
+
function constantTimeEqual(a, b) {
|
|
600
|
+
if (a.length !== b.length) return false;
|
|
601
|
+
let d = 0;
|
|
602
|
+
for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];
|
|
603
|
+
return d === 0;
|
|
604
|
+
}
|
|
605
|
+
var OID_ED25519 = [6, 3, 43, 101, 112];
|
|
606
|
+
var OID_EC_PUBLIC_KEY = [6, 7, 42, 134, 72, 206, 61, 2, 1];
|
|
607
|
+
var OID_P256 = [6, 8, 42, 134, 72, 206, 61, 3, 1, 7];
|
|
608
|
+
function hasSeq(hay, needle) {
|
|
609
|
+
outer: for (let i = 0; i + needle.length <= hay.length; i++) {
|
|
610
|
+
for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
|
|
611
|
+
return true;
|
|
612
|
+
}
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
function algFromKeyDer(der) {
|
|
616
|
+
const head = der.slice(0, 32);
|
|
617
|
+
if (hasSeq(head, OID_ED25519)) return "ed25519";
|
|
618
|
+
if (hasSeq(head, OID_EC_PUBLIC_KEY)) {
|
|
619
|
+
if (hasSeq(der.slice(0, 40), OID_P256)) return "ecdsa-p256-sha256";
|
|
620
|
+
throw new HttpSignatureError("unsupported EC curve (only P-256 is supported)");
|
|
621
|
+
}
|
|
622
|
+
throw new HttpSignatureError("unsupported key type (Ed25519 or ECDSA P-256 required)");
|
|
623
|
+
}
|
|
624
|
+
function httpSignatureAlgForKey(pem) {
|
|
625
|
+
return algFromKeyDer(pemToDer(pem));
|
|
626
|
+
}
|
|
627
|
+
function subtle() {
|
|
628
|
+
return globalThis.crypto?.subtle;
|
|
629
|
+
}
|
|
630
|
+
async function digestBytes(alg, data) {
|
|
631
|
+
const s = subtle();
|
|
632
|
+
if (s) return new Uint8Array(await s.digest(alg === "sha-256" ? "SHA-256" : "SHA-512", toArrayBuffer(data)));
|
|
633
|
+
const nodeCrypto = await import("crypto");
|
|
634
|
+
return new Uint8Array(nodeCrypto.createHash(alg === "sha-256" ? "sha256" : "sha512").update(data).digest());
|
|
635
|
+
}
|
|
636
|
+
async function signBytes(alg, privateKeyPem, data) {
|
|
637
|
+
const s = subtle();
|
|
638
|
+
if (s) {
|
|
639
|
+
const der = toArrayBuffer(pemToDer(privateKeyPem));
|
|
640
|
+
if (alg === "ed25519") {
|
|
641
|
+
const key2 = await s.importKey("pkcs8", der, { name: "Ed25519" }, false, ["sign"]);
|
|
642
|
+
return new Uint8Array(await s.sign("Ed25519", key2, toArrayBuffer(data)));
|
|
643
|
+
}
|
|
644
|
+
const key = await s.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
|
|
645
|
+
return new Uint8Array(await s.sign({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(data)));
|
|
646
|
+
}
|
|
647
|
+
const nodeCrypto = await import("crypto");
|
|
648
|
+
if (alg === "ed25519") return new Uint8Array(nodeCrypto.sign(null, data, privateKeyPem));
|
|
649
|
+
return new Uint8Array(nodeCrypto.sign("sha256", data, { key: privateKeyPem, dsaEncoding: "ieee-p1363" }));
|
|
650
|
+
}
|
|
651
|
+
async function verifyBytes(alg, publicKeyPem, data, sig) {
|
|
652
|
+
if (sig.length !== 64) return false;
|
|
653
|
+
const s = subtle();
|
|
654
|
+
if (s) {
|
|
655
|
+
const der = toArrayBuffer(pemToDer(publicKeyPem));
|
|
656
|
+
if (alg === "ed25519") {
|
|
657
|
+
const key2 = await s.importKey("spki", der, { name: "Ed25519" }, false, ["verify"]);
|
|
658
|
+
return s.verify("Ed25519", key2, toArrayBuffer(sig), toArrayBuffer(data));
|
|
659
|
+
}
|
|
660
|
+
const key = await s.importKey("spki", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
|
|
661
|
+
return s.verify({ name: "ECDSA", hash: "SHA-256" }, key, toArrayBuffer(sig), toArrayBuffer(data));
|
|
662
|
+
}
|
|
663
|
+
const nodeCrypto = await import("crypto");
|
|
664
|
+
if (alg === "ed25519") return nodeCrypto.verify(null, data, publicKeyPem, sig);
|
|
665
|
+
return nodeCrypto.verify("sha256", data, { key: publicKeyPem, dsaEncoding: "ieee-p1363" }, sig);
|
|
666
|
+
}
|
|
667
|
+
async function contentDigest(body, alg = "sha-256") {
|
|
668
|
+
if (alg !== "sha-256" && alg !== "sha-512") throw new HttpSignatureError(`unsupported digest algorithm ${alg}`);
|
|
669
|
+
return `${alg}=:${bytesToBase64(await digestBytes(alg, toBytes2(body)))}:`;
|
|
670
|
+
}
|
|
671
|
+
async function checkContentDigest(fieldValue, body) {
|
|
672
|
+
let dict;
|
|
673
|
+
try {
|
|
674
|
+
dict = new SfParser(fieldValue).parseDictionary();
|
|
675
|
+
} catch {
|
|
676
|
+
return "Content-Digest is not a valid structured field";
|
|
677
|
+
}
|
|
678
|
+
const bytes = toBytes2(body);
|
|
679
|
+
let checked = 0;
|
|
680
|
+
for (const [alg, member] of dict) {
|
|
681
|
+
if (alg !== "sha-256" && alg !== "sha-512") continue;
|
|
682
|
+
if (member.kind !== "item" || member.value.t !== "bin") return `Content-Digest ${alg} is not a byte sequence`;
|
|
683
|
+
const actual = await digestBytes(alg, bytes);
|
|
684
|
+
if (!constantTimeEqual(actual, member.value.v)) return `Content-Digest ${alg} does not match the body`;
|
|
685
|
+
checked++;
|
|
686
|
+
}
|
|
687
|
+
return checked > 0 ? null : "Content-Digest has no supported algorithm (sha-256 or sha-512)";
|
|
688
|
+
}
|
|
689
|
+
var LABEL_RE = /^[a-z*][a-z0-9_\-.*]*$/;
|
|
690
|
+
async function signHttpRequest(request, options) {
|
|
691
|
+
if (!options?.privateKey) throw new HttpSignatureError("signHttpRequest requires privateKey (PKCS#8 PEM)");
|
|
692
|
+
const label = options.label ?? "sig1";
|
|
693
|
+
if (!LABEL_RE.test(label)) throw new HttpSignatureError(`invalid label "${label}"`);
|
|
694
|
+
const keyAlg = httpSignatureAlgForKey(options.privateKey);
|
|
695
|
+
if (options.alg && options.alg !== keyAlg) {
|
|
696
|
+
throw new HttpSignatureError(`alg "${options.alg}" does not match the private key (${keyAlg})`);
|
|
697
|
+
}
|
|
698
|
+
const alg = keyAlg;
|
|
699
|
+
const headers = { ...request.headers ?? {} };
|
|
700
|
+
const hasBody = request.body !== void 0 && request.body !== null;
|
|
701
|
+
let digestHeader;
|
|
702
|
+
if (hasBody) {
|
|
703
|
+
digestHeader = await contentDigest(request.body, "sha-256");
|
|
704
|
+
for (const k of Object.keys(headers)) if (k.toLowerCase() === "content-digest") delete headers[k];
|
|
705
|
+
headers["content-digest"] = digestHeader;
|
|
706
|
+
}
|
|
707
|
+
let componentStrs;
|
|
708
|
+
if (options.components) {
|
|
709
|
+
componentStrs = [...options.components];
|
|
710
|
+
} else {
|
|
711
|
+
componentStrs = ["@method", "@target-uri", "@authority"];
|
|
712
|
+
if (fieldValues(headers, "content-type") !== null) componentStrs.push("content-type");
|
|
713
|
+
}
|
|
714
|
+
const components = componentStrs.map(parseComponent);
|
|
715
|
+
if (hasBody && !components.some((c) => c.name === "content-digest" && c.params.length === 0)) {
|
|
716
|
+
components.push({ name: "content-digest", params: [] });
|
|
717
|
+
}
|
|
718
|
+
const created = options.created ?? Math.floor(Date.now() / 1e3);
|
|
719
|
+
const expires = options.expires === null ? void 0 : options.expires ?? created + 300;
|
|
720
|
+
const params = { created };
|
|
721
|
+
if (expires !== void 0) params.expires = expires;
|
|
722
|
+
if (options.nonce !== void 0) params.nonce = options.nonce;
|
|
723
|
+
if (options.includeAlg !== false) params.alg = alg;
|
|
724
|
+
if (options.keyid !== void 0) params.keyid = options.keyid;
|
|
725
|
+
if (options.tag !== void 0) params.tag = options.tag;
|
|
726
|
+
const { base, signatureParams } = buildBase(
|
|
727
|
+
{ method: request.method, url: request.url, headers, body: request.body },
|
|
728
|
+
components,
|
|
729
|
+
paramsFromObject(params)
|
|
730
|
+
);
|
|
731
|
+
const sig = await signBytes(alg, options.privateKey, new TextEncoder().encode(base));
|
|
732
|
+
const out = {
|
|
733
|
+
"Signature-Input": `${label}=${signatureParams}`,
|
|
734
|
+
"Signature": `${label}=:${bytesToBase64(sig)}:`
|
|
735
|
+
};
|
|
736
|
+
if (digestHeader) out["Content-Digest"] = digestHeader;
|
|
737
|
+
return { headers: out, signatureBase: base };
|
|
738
|
+
}
|
|
739
|
+
var SUPPORTED_ALGS = /* @__PURE__ */ new Set(["ed25519", "ecdsa-p256-sha256"]);
|
|
740
|
+
async function verifyHttpRequest(request, options) {
|
|
741
|
+
if (!options?.publicKey && !options?.resolveKey) {
|
|
742
|
+
throw new HttpSignatureError("verifyHttpRequest requires publicKey or resolveKey");
|
|
743
|
+
}
|
|
744
|
+
const result = {
|
|
745
|
+
valid: false,
|
|
746
|
+
label: options.label ?? "",
|
|
747
|
+
covered: [],
|
|
748
|
+
contentDigestChecked: false
|
|
749
|
+
};
|
|
750
|
+
const fail = (reason) => ({ ...result, valid: false, reason });
|
|
751
|
+
const inputRaw = fieldValues(request.headers, "signature-input");
|
|
752
|
+
const sigRaw = fieldValues(request.headers, "signature");
|
|
753
|
+
if (!inputRaw) return fail("missing Signature-Input header");
|
|
754
|
+
if (!sigRaw) return fail("missing Signature header");
|
|
755
|
+
let inputs;
|
|
756
|
+
let sigs;
|
|
757
|
+
try {
|
|
758
|
+
inputs = new SfParser(inputRaw.map(cleanFieldValue).join(", ")).parseDictionary();
|
|
759
|
+
sigs = new SfParser(sigRaw.map(cleanFieldValue).join(", ")).parseDictionary();
|
|
760
|
+
} catch (e) {
|
|
761
|
+
return fail(`malformed signature headers: ${e.message}`);
|
|
762
|
+
}
|
|
763
|
+
const label = options.label ?? inputs[0]?.[0];
|
|
764
|
+
if (!label) return fail("Signature-Input has no signatures");
|
|
765
|
+
result.label = label;
|
|
766
|
+
const input = inputs.find(([k]) => k === label)?.[1];
|
|
767
|
+
const sigMember = sigs.find(([k]) => k === label)?.[1];
|
|
768
|
+
if (!input) return fail(`no Signature-Input for label "${label}"`);
|
|
769
|
+
if (!sigMember) return fail(`no Signature for label "${label}"`);
|
|
770
|
+
if (input.kind !== "list") return fail("Signature-Input member is not an inner list");
|
|
771
|
+
if (sigMember.kind !== "item" || sigMember.value.t !== "bin") return fail("Signature member is not a byte sequence");
|
|
772
|
+
const components = [];
|
|
773
|
+
for (const item of input.items) {
|
|
774
|
+
if (item.value.t !== "str") return fail("covered component is not a string");
|
|
775
|
+
components.push({ name: item.value.v, params: item.params });
|
|
776
|
+
}
|
|
777
|
+
result.covered = components.map(serializeComponent);
|
|
778
|
+
const p = new Map(input.params);
|
|
779
|
+
const getInt = (k) => {
|
|
780
|
+
const v = p.get(k);
|
|
781
|
+
if (v === void 0) return void 0;
|
|
782
|
+
return v.t === "int" ? v.v : null;
|
|
783
|
+
};
|
|
784
|
+
const getStr = (k) => {
|
|
785
|
+
const v = p.get(k);
|
|
786
|
+
if (v === void 0) return void 0;
|
|
787
|
+
return v.t === "str" ? v.v : null;
|
|
788
|
+
};
|
|
789
|
+
const created = getInt("created");
|
|
790
|
+
const expires = getInt("expires");
|
|
791
|
+
const keyid = getStr("keyid");
|
|
792
|
+
const algParam = getStr("alg");
|
|
793
|
+
if (created === null) return fail("created must be an integer");
|
|
794
|
+
if (expires === null) return fail("expires must be an integer");
|
|
795
|
+
if (keyid === null) return fail("keyid must be a string");
|
|
796
|
+
if (algParam === null) return fail("alg must be a string");
|
|
797
|
+
result.created = created;
|
|
798
|
+
result.expires = expires;
|
|
799
|
+
result.keyid = keyid;
|
|
800
|
+
if (options.requiredComponents?.length) {
|
|
801
|
+
const have = new Set(components.map(componentKey));
|
|
802
|
+
for (const r of options.requiredComponents) {
|
|
803
|
+
let rc;
|
|
804
|
+
try {
|
|
805
|
+
rc = parseComponent(r);
|
|
806
|
+
} catch (e) {
|
|
807
|
+
return fail(e.message);
|
|
808
|
+
}
|
|
809
|
+
if (!have.has(componentKey(rc))) return fail(`required component ${serializeComponent(rc)} is not covered`);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
813
|
+
if (expires !== void 0 && now > expires) return fail("signature has expired");
|
|
814
|
+
if (created !== void 0 && created > now + FUTURE_SKEW_SECONDS) return fail("signature created in the future");
|
|
815
|
+
if (options.maxAgeSeconds !== void 0) {
|
|
816
|
+
if (created === void 0) return fail("signature has no created parameter, so its age cannot be checked");
|
|
817
|
+
if (now - created > options.maxAgeSeconds) return fail("signature is older than maxAgeSeconds");
|
|
818
|
+
}
|
|
819
|
+
let publicKey = options.publicKey;
|
|
820
|
+
let resolvedAlg;
|
|
821
|
+
if (!publicKey) {
|
|
822
|
+
let resolved;
|
|
823
|
+
try {
|
|
824
|
+
resolved = await options.resolveKey(keyid);
|
|
825
|
+
} catch (e) {
|
|
826
|
+
return fail(`key resolution failed: ${e.message}`);
|
|
827
|
+
}
|
|
828
|
+
if (!resolved?.publicKey) return fail(`unknown key${keyid ? ` "${keyid}"` : ""}`);
|
|
829
|
+
publicKey = resolved.publicKey;
|
|
830
|
+
resolvedAlg = resolved.alg;
|
|
831
|
+
}
|
|
832
|
+
let keyAlg;
|
|
833
|
+
try {
|
|
834
|
+
keyAlg = httpSignatureAlgForKey(publicKey);
|
|
835
|
+
} catch (e) {
|
|
836
|
+
return fail(e.message);
|
|
837
|
+
}
|
|
838
|
+
if (algParam !== void 0 && !SUPPORTED_ALGS.has(algParam)) return fail(`unsupported algorithm "${algParam}"`);
|
|
839
|
+
if (algParam !== void 0 && algParam !== keyAlg) return fail(`alg "${algParam}" does not match the key (${keyAlg})`);
|
|
840
|
+
if (resolvedAlg !== void 0 && resolvedAlg !== keyAlg) return fail(`resolved key alg "${resolvedAlg}" does not match the key (${keyAlg})`);
|
|
841
|
+
result.alg = keyAlg;
|
|
842
|
+
let base;
|
|
843
|
+
try {
|
|
844
|
+
base = buildBase(
|
|
845
|
+
{ method: request.method, url: request.url, headers: request.headers, body: request.body },
|
|
846
|
+
components,
|
|
847
|
+
input.params
|
|
848
|
+
).base;
|
|
849
|
+
} catch (e) {
|
|
850
|
+
return fail(e.message);
|
|
851
|
+
}
|
|
852
|
+
let ok;
|
|
853
|
+
try {
|
|
854
|
+
ok = await verifyBytes(keyAlg, publicKey, new TextEncoder().encode(base), sigMember.value.v);
|
|
855
|
+
} catch (e) {
|
|
856
|
+
return fail(`signature check failed: ${e.message}`);
|
|
857
|
+
}
|
|
858
|
+
if (!ok) return fail("signature does not verify");
|
|
859
|
+
const coversDigest = components.some((c) => c.name === "content-digest");
|
|
860
|
+
if (coversDigest && request.body !== void 0 && request.body !== null) {
|
|
861
|
+
const dv = fieldValues(request.headers, "content-digest");
|
|
862
|
+
const reason = await checkContentDigest((dv ?? []).map(cleanFieldValue).join(", "), request.body);
|
|
863
|
+
if (reason) return fail(reason);
|
|
864
|
+
result.contentDigestChecked = true;
|
|
865
|
+
}
|
|
866
|
+
return { ...result, valid: true };
|
|
867
|
+
}
|
|
868
|
+
|
|
191
869
|
// src/index.ts
|
|
192
|
-
var SDK_VERSION = true ? "
|
|
870
|
+
var SDK_VERSION = true ? "4.0.0" : "0.0.0";
|
|
193
871
|
var USER_AGENT = `vorim-sdk/${SDK_VERSION}`;
|
|
194
872
|
function sleep(ms) {
|
|
195
873
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -232,6 +910,17 @@ function toApprovalAttestation(raw) {
|
|
|
232
910
|
signature: raw.signature
|
|
233
911
|
};
|
|
234
912
|
}
|
|
913
|
+
function foldTraceparent(input) {
|
|
914
|
+
if (!input.traceparent) return input;
|
|
915
|
+
const { traceparent, ...rest } = input;
|
|
916
|
+
const m = /^[0-9a-f]{2}-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i.exec(traceparent.trim());
|
|
917
|
+
const out = { ...rest };
|
|
918
|
+
if (m) {
|
|
919
|
+
if (!out.trace_id) out.trace_id = m[1].toLowerCase();
|
|
920
|
+
if (!out.span_id) out.span_id = m[2].toLowerCase();
|
|
921
|
+
}
|
|
922
|
+
return out;
|
|
923
|
+
}
|
|
235
924
|
var VorimSDK = class _VorimSDK {
|
|
236
925
|
apiKey;
|
|
237
926
|
baseUrl;
|
|
@@ -287,7 +976,7 @@ var VorimSDK = class _VorimSDK {
|
|
|
287
976
|
}
|
|
288
977
|
}
|
|
289
978
|
this.chainEvents = config.chainEvents ?? false;
|
|
290
|
-
this.runtimeFailOpen = config.runtimeFailOpen ??
|
|
979
|
+
this.runtimeFailOpen = config.runtimeFailOpen ?? false;
|
|
291
980
|
this.noPayload = config.noPayload !== void 0 && config.noPayload !== false;
|
|
292
981
|
this.maxMetadataChars = typeof config.noPayload === "object" && typeof config.noPayload.maxMetadataChars === "number" ? config.noPayload.maxMetadataChars : 256;
|
|
293
982
|
}
|
|
@@ -390,11 +1079,26 @@ var VorimSDK = class _VorimSDK {
|
|
|
390
1079
|
return { agents: env.data ?? [], meta: env.meta ?? null };
|
|
391
1080
|
}
|
|
392
1081
|
/**
|
|
393
|
-
* Update an agent's metadata.
|
|
1082
|
+
* Update an agent's metadata or status.
|
|
1083
|
+
*
|
|
1084
|
+
* `status: 'suspended'` is the kill switch and, since 4.0.0, cascades to
|
|
1085
|
+
* every agent reachable through the agent's active identity delegations
|
|
1086
|
+
* unless `cascade: false`. Setting `status: 'active'` on a suspended agent
|
|
1087
|
+
* reverses exactly that cascade. The returned agent carries
|
|
1088
|
+
* `cascade.suspended` / `cascade.reactivated` with the agent ids touched.
|
|
1089
|
+
* See {@link suspendPreview} for the blast radius before acting.
|
|
394
1090
|
*/
|
|
395
1091
|
async updateAgent(agentId, updates) {
|
|
396
1092
|
return this.patch(`/agents/${agentId}`, updates);
|
|
397
1093
|
}
|
|
1094
|
+
/**
|
|
1095
|
+
* What suspending (or revoking) this agent would touch: its delegation
|
|
1096
|
+
* subtree, how many of those agents are still active, open escalations
|
|
1097
|
+
* across the subtree, and live delegation links. Writes nothing.
|
|
1098
|
+
*/
|
|
1099
|
+
async suspendPreview(agentId) {
|
|
1100
|
+
return this.get(`/agents/${agentId}/suspend-preview`);
|
|
1101
|
+
}
|
|
398
1102
|
/**
|
|
399
1103
|
* Revoke an agent (permanent deactivation).
|
|
400
1104
|
*/
|
|
@@ -754,9 +1458,9 @@ var VorimSDK = class _VorimSDK {
|
|
|
754
1458
|
* poll {@link waitForDecisionResolution} for the human decision.
|
|
755
1459
|
*
|
|
756
1460
|
* Transport failures (network/DNS/timeout/5xx) respect the constructor's
|
|
757
|
-
* `runtimeFailOpen` flag: when
|
|
758
|
-
*
|
|
759
|
-
*
|
|
1461
|
+
* `runtimeFailOpen` flag: when false (default) the underlying error is
|
|
1462
|
+
* re-thrown; when true a synthetic `fallback` decision is returned so a
|
|
1463
|
+
* control-plane blip does not block the agent.
|
|
760
1464
|
*
|
|
761
1465
|
* Always pass the public `agid_*` id as `agentId`.
|
|
762
1466
|
*
|
|
@@ -781,7 +1485,10 @@ var VorimSDK = class _VorimSDK {
|
|
|
781
1485
|
required_scope: input.requiredScope,
|
|
782
1486
|
idempotency_key: input.idempotencyKey,
|
|
783
1487
|
workflow_id: input.workflowId,
|
|
784
|
-
estimated_tokens: input.estimatedTokens
|
|
1488
|
+
estimated_tokens: input.estimatedTokens,
|
|
1489
|
+
trace_id: input.traceId,
|
|
1490
|
+
span_id: input.spanId,
|
|
1491
|
+
traceparent: input.traceparent
|
|
785
1492
|
};
|
|
786
1493
|
let raw;
|
|
787
1494
|
try {
|
|
@@ -801,6 +1508,7 @@ var VorimSDK = class _VorimSDK {
|
|
|
801
1508
|
latencyMs: 0,
|
|
802
1509
|
isFallback: true,
|
|
803
1510
|
policyVersion: 0,
|
|
1511
|
+
swarmId: null,
|
|
804
1512
|
escalationResolution: null,
|
|
805
1513
|
approval: null
|
|
806
1514
|
};
|
|
@@ -819,8 +1527,9 @@ var VorimSDK = class _VorimSDK {
|
|
|
819
1527
|
// Enforcement runs inside beforeAction(): pass `workflowId` + `estimatedTokens`
|
|
820
1528
|
// on the action, and a `token_budget_gt` policy rule denies the action before
|
|
821
1529
|
// the spend if it would breach the budget. These methods manage the budgets
|
|
822
|
-
// and read live spend
|
|
823
|
-
//
|
|
1530
|
+
// and read live spend. They need an API key holding the `runtime:manage`
|
|
1531
|
+
// scope (deliberately separate from `runtime:decide`, so an agent's own key
|
|
1532
|
+
// cannot raise its ceiling).
|
|
824
1533
|
/**
|
|
825
1534
|
* Create or update a token budget for an agent or workflow. One budget per
|
|
826
1535
|
* (scope, scope_ref) — calling this again for the same target updates it.
|
|
@@ -915,19 +1624,20 @@ var VorimSDK = class _VorimSDK {
|
|
|
915
1624
|
* row's `decision` column off `'escalate'`. If we returned that verbatim,
|
|
916
1625
|
* a caller's obvious `if (d.decision === 'deny')` check would never fire
|
|
917
1626
|
* on a human DENIAL — a silent fail-open. So when a resolution is present
|
|
918
|
-
* we translate the verdict: approved → 'allow', denied → 'deny'
|
|
919
|
-
*
|
|
920
|
-
*
|
|
1627
|
+
* we translate the verdict: approved → 'allow', denied → 'deny', and
|
|
1628
|
+
* timed_out (nobody answered within the org's escalation window) → 'deny'.
|
|
1629
|
+
* The raw resolution is also surfaced as `escalationResolution` for
|
|
1630
|
+
* callers that want it explicitly.
|
|
921
1631
|
*
|
|
922
1632
|
* A missing verdict (malformed/truncated response) fails CLOSED to 'deny'
|
|
923
1633
|
* rather than 'fallback', so the deny check fires on garbled input.
|
|
924
1634
|
*/
|
|
925
1635
|
toRuntimeDecision(raw) {
|
|
926
|
-
const resolution = raw?.escalation_resolution === "approved" ? "approved" : raw?.escalation_resolution === "denied" ? "denied" : null;
|
|
1636
|
+
const resolution = raw?.escalation_resolution === "approved" ? "approved" : raw?.escalation_resolution === "denied" ? "denied" : raw?.escalation_resolution === "timed_out" ? "timed_out" : null;
|
|
927
1637
|
const hasVerdict = typeof raw?.decision === "string";
|
|
928
1638
|
let decision;
|
|
929
1639
|
if (raw?.decision === "escalate" && resolution === "approved") decision = "allow";
|
|
930
|
-
else if (raw?.decision === "escalate" && resolution === "denied") decision = "deny";
|
|
1640
|
+
else if (raw?.decision === "escalate" && (resolution === "denied" || resolution === "timed_out")) decision = "deny";
|
|
931
1641
|
else if (hasVerdict) decision = raw.decision;
|
|
932
1642
|
else decision = "deny";
|
|
933
1643
|
return {
|
|
@@ -942,6 +1652,7 @@ var VorimSDK = class _VorimSDK {
|
|
|
942
1652
|
latencyMs: raw?.latency_ms ?? 0,
|
|
943
1653
|
isFallback: raw?.is_fallback ?? !hasVerdict,
|
|
944
1654
|
policyVersion: raw?.policy_version ?? 0,
|
|
1655
|
+
swarmId: typeof raw?.swarm_id === "string" ? raw.swarm_id : null,
|
|
945
1656
|
escalationResolution: resolution,
|
|
946
1657
|
approval: toApprovalAttestation(raw?.approval)
|
|
947
1658
|
};
|
|
@@ -1076,6 +1787,7 @@ var VorimSDK = class _VorimSDK {
|
|
|
1076
1787
|
}
|
|
1077
1788
|
async prepareEvent(event, signOverride) {
|
|
1078
1789
|
this.assertNoPayload(event);
|
|
1790
|
+
event = foldTraceparent(event);
|
|
1079
1791
|
const shouldSign = signOverride ?? this.autoSign;
|
|
1080
1792
|
if (!shouldSign && !this.chainEvents) return event;
|
|
1081
1793
|
if (this.chainEvents) {
|
|
@@ -1195,6 +1907,168 @@ var VorimSDK = class _VorimSDK {
|
|
|
1195
1907
|
}
|
|
1196
1908
|
return result;
|
|
1197
1909
|
}
|
|
1910
|
+
/**
|
|
1911
|
+
* The server-minted swarm an agent belongs to and every member of it.
|
|
1912
|
+
* `{ swarm_id: null, members: [] }` for a standalone agent.
|
|
1913
|
+
*/
|
|
1914
|
+
async getSwarm(agentId) {
|
|
1915
|
+
return this.get(`/agents/${agentId}/swarm`);
|
|
1916
|
+
}
|
|
1917
|
+
// ─── Many agents at once ─────────────────────────────────────────────
|
|
1918
|
+
/**
|
|
1919
|
+
* Register up to 50 agents in one call: an explicit list, or a template
|
|
1920
|
+
* repeated `count` times (names `<prefix>-1` .. `<prefix>-N`), optionally
|
|
1921
|
+
* grouped into a new swarm (`swarm: { name?, root? }`; the first created
|
|
1922
|
+
* agent roots it when `root` is absent). Each created agent's private key
|
|
1923
|
+
* is cached, like `register()`, so the SDK can sign for it at once. The
|
|
1924
|
+
* plan allowance is checked for the whole batch first; a single failure is
|
|
1925
|
+
* listed in `failed`, not thrown.
|
|
1926
|
+
*/
|
|
1927
|
+
async registerMany(input) {
|
|
1928
|
+
const result = await this.post("/agents/bulk", input);
|
|
1929
|
+
for (const c of result?.created ?? []) {
|
|
1930
|
+
const id = c?.agent?.agent_id;
|
|
1931
|
+
if (id && c?.private_key) this.agentKeys.set(id, c.private_key);
|
|
1932
|
+
}
|
|
1933
|
+
return result;
|
|
1934
|
+
}
|
|
1935
|
+
// ─── Declarative swarm spec (vorim.swarm/v1) ─────────────────────────
|
|
1936
|
+
/**
|
|
1937
|
+
* Create or update a swarm from a spec: root, members and who they report
|
|
1938
|
+
* to, guardians, charter, budget and shares, breakers, tripwires. Pass the
|
|
1939
|
+
* YAML or JSON text, or the parsed object. `dryRun` returns the plan
|
|
1940
|
+
* without writing. Needs an org key with `runtime:manage`.
|
|
1941
|
+
*/
|
|
1942
|
+
async applySwarmSpec(spec, opts = {}) {
|
|
1943
|
+
const body = typeof spec === "string" ? { spec } : spec;
|
|
1944
|
+
return this.post(`/swarms/apply?dry_run=${opts.dryRun ? "true" : "false"}`, body);
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* Rehearse a swarm: every active member against a scenario set, through
|
|
1948
|
+
* the real decision pipeline with nothing written, signed with the roster,
|
|
1949
|
+
* charter, budget and policy version it ran under. `preset: 'hazards'`
|
|
1950
|
+
* (default) runs generic side tasks plus one main task; `'replay'` re-judges
|
|
1951
|
+
* the swarm's last 100 decisions; `scenarios` runs your own (each with
|
|
1952
|
+
* `expect: 'allow' | 'not_allow' | 'deny' | 'escalate'`). Verdict is pass,
|
|
1953
|
+
* pass_with_findings or fail. Needs `runtime:manage`.
|
|
1954
|
+
*/
|
|
1955
|
+
async rehearseSwarm(swarmId, input = {}) {
|
|
1956
|
+
return this.post(`/swarms/${encodeURIComponent(swarmId)}/rehearse`, input);
|
|
1957
|
+
}
|
|
1958
|
+
/** Past rehearsals, newest first (summary only; fetch `/swarms/:id/rehearsals/:rid` for the signed payload). */
|
|
1959
|
+
async listSwarmRehearsals(swarmId) {
|
|
1960
|
+
return this.get(`/swarms/${encodeURIComponent(swarmId)}/rehearsals`);
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* A swarm's trust: `min` (gate on it: the least trusted active member),
|
|
1964
|
+
* `weighted_mean` (display, weighted by recent activity), `trimmed_mean`
|
|
1965
|
+
* (for anything derived from peer reports), per member.
|
|
1966
|
+
*/
|
|
1967
|
+
async getSwarmScore(swarmId) {
|
|
1968
|
+
return this.get(`/swarms/${encodeURIComponent(swarmId)}/score`);
|
|
1969
|
+
}
|
|
1970
|
+
/**
|
|
1971
|
+
* Issue a platform-signed attestation of the swarm as it is now: roster
|
|
1972
|
+
* and its hash, policy version and rules hash, charter, budget, kills,
|
|
1973
|
+
* latest rehearsal, receipt chain head and the three scores. Valid 24 h.
|
|
1974
|
+
* Hand it to a counterparty; they verify it against GET /trust/keys.
|
|
1975
|
+
*/
|
|
1976
|
+
async attestSwarm(swarmId) {
|
|
1977
|
+
return this.post(`/swarms/${encodeURIComponent(swarmId)}/attest`, {});
|
|
1978
|
+
}
|
|
1979
|
+
/** Past attestations, newest first (fetch one by id for the signed payload). */
|
|
1980
|
+
async listSwarmAttestations(swarmId) {
|
|
1981
|
+
return this.get(`/swarms/${encodeURIComponent(swarmId)}/attestations`);
|
|
1982
|
+
}
|
|
1983
|
+
/** A swarm as it is now, as a spec: `{ spec, yaml }`. Keep the YAML in git and apply it again. */
|
|
1984
|
+
async getSwarmSpec(swarmId) {
|
|
1985
|
+
return this.get(`/swarms/${encodeURIComponent(swarmId)}/spec`);
|
|
1986
|
+
}
|
|
1987
|
+
/**
|
|
1988
|
+
* A swarm's attention picture: escalations in the last hour against its
|
|
1989
|
+
* budget, the rate to expect, median time to resolve, mean time between
|
|
1990
|
+
* interventions, and the fan-out estimate after Olsen and Goodrich (how
|
|
1991
|
+
* many swarms like this one person could supervise).
|
|
1992
|
+
*/
|
|
1993
|
+
async getSwarmAttention(swarmId) {
|
|
1994
|
+
return this.get(`/swarms/${encodeURIComponent(swarmId)}/attention`);
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Set the swarm's attention budget: `perHour` escalations per rolling hour
|
|
1998
|
+
* a person may be asked to read (null = no budget). Past it `onExceed`
|
|
1999
|
+
* decides: 'deny' (the escalation is denied unread, the default) or
|
|
2000
|
+
* 'suspend' (the whole swarm stops). Returns the swarm detail.
|
|
2001
|
+
*/
|
|
2002
|
+
async setSwarmAttention(swarmId, input) {
|
|
2003
|
+
const body = {};
|
|
2004
|
+
if (input.perHour !== void 0) body.attention_budget_per_hour = input.perHour;
|
|
2005
|
+
if (input.onExceed !== void 0) body.attention_exceeded_action = input.onExceed;
|
|
2006
|
+
return this.patch(`/swarms/${encodeURIComponent(swarmId)}`, body);
|
|
2007
|
+
}
|
|
2008
|
+
// ─── OpenTelemetry ───────────────────────────────────────────────────
|
|
2009
|
+
/**
|
|
2010
|
+
* Attributes for the agent's own spans: the OTel GenAI `gen_ai.agent.id`
|
|
2011
|
+
* plus Vorim's swarm and parent-agent ids (the conventions have no field
|
|
2012
|
+
* for either), so any OTel backend can group a swarm's spans. Cached for
|
|
2013
|
+
* 60 seconds per agent. Pass the active span's trace/span id back to
|
|
2014
|
+
* `beforeAction` / `emit` and Vorim's OTLP connector parents its spans
|
|
2015
|
+
* under yours.
|
|
2016
|
+
*/
|
|
2017
|
+
async otelAttributes(agentId) {
|
|
2018
|
+
const cached = this.otelCache.get(agentId);
|
|
2019
|
+
if (cached && cached.expires > Date.now()) return cached.attrs;
|
|
2020
|
+
const attrs = { "gen_ai.agent.id": agentId, "vorim.agent.id": agentId };
|
|
2021
|
+
try {
|
|
2022
|
+
const swarm = await this.getSwarm(agentId);
|
|
2023
|
+
if (swarm?.swarm_id) {
|
|
2024
|
+
attrs["vorim.swarm.id"] = swarm.swarm_id;
|
|
2025
|
+
const me = swarm.members?.find((m) => m.agent_id === agentId);
|
|
2026
|
+
if (me?.parent_agent_id) attrs["vorim.parent_agent.id"] = me.parent_agent_id;
|
|
2027
|
+
}
|
|
2028
|
+
} catch {
|
|
2029
|
+
}
|
|
2030
|
+
this.otelCache.set(agentId, { attrs, expires: Date.now() + 6e4 });
|
|
2031
|
+
return attrs;
|
|
2032
|
+
}
|
|
2033
|
+
otelCache = /* @__PURE__ */ new Map();
|
|
2034
|
+
// ─── Guardian agents ─────────────────────────────────────────────────
|
|
2035
|
+
//
|
|
2036
|
+
// An agent with metadata.class = 'guardian' judges escalations that a rule
|
|
2037
|
+
// with approver_role 'guardian' assigned to its swarm. It reads the queue
|
|
2038
|
+
// from the server (never from a peer) and answers with a verdict signed by
|
|
2039
|
+
// its own key over one canonical line, so the approval is verifiable
|
|
2040
|
+
// offline against the agent's registered public key. An unanswered
|
|
2041
|
+
// escalation times out as denied: an absent guardian fails closed.
|
|
2042
|
+
/** Pending escalations this guardian may judge (empty for a non-guardian). */
|
|
2043
|
+
async listGuardianEscalations(agentId) {
|
|
2044
|
+
return this.get(`/runtime/guardian/escalations?agent_id=${encodeURIComponent(agentId)}`);
|
|
2045
|
+
}
|
|
2046
|
+
/**
|
|
2047
|
+
* Approve or veto an escalation as a guardian. Needs the agent's private
|
|
2048
|
+
* key (loaded by register(), registerEphemeral() or useAgentKey()). A
|
|
2049
|
+
* quorum rule returns `{ status: 'partial', approvals, required_approvals }`
|
|
2050
|
+
* until enough distinct approvals arrive; one veto denies at once.
|
|
2051
|
+
*/
|
|
2052
|
+
async guardianResolve(agentId, decisionId, resolution) {
|
|
2053
|
+
const key = this.agentKeys.get(agentId);
|
|
2054
|
+
if (!key) {
|
|
2055
|
+
throw new VorimError(
|
|
2056
|
+
400,
|
|
2057
|
+
"AGENT_KEY_NOT_LOADED",
|
|
2058
|
+
`No private key is cached for agent ${agentId}. Call register() or useAgentKey(agentId, privateKeyPem) first.`
|
|
2059
|
+
);
|
|
2060
|
+
}
|
|
2061
|
+
const signedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2062
|
+
const line = `vorim-escalation-approval|v1|${decisionId}|${resolution}|agent:${agentId}|${signedAt}`;
|
|
2063
|
+
const signature = await this.sign(line, key);
|
|
2064
|
+
return this.post("/runtime/guardian/resolve", {
|
|
2065
|
+
agent_id: agentId,
|
|
2066
|
+
decision_id: decisionId,
|
|
2067
|
+
resolution,
|
|
2068
|
+
signed_at: signedAt,
|
|
2069
|
+
signature
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
1198
2072
|
// ─── Credential Delegation ──────────────────────────────────────────
|
|
1199
2073
|
/**
|
|
1200
2074
|
* Register an OAuth provider for credential delegation.
|
|
@@ -1249,6 +2123,67 @@ var VorimSDK = class _VorimSDK {
|
|
|
1249
2123
|
async requestToken(input) {
|
|
1250
2124
|
return this.post("/credentials/token", input);
|
|
1251
2125
|
}
|
|
2126
|
+
// ─── HTTP Message Signatures (RFC 9421) ─────────────────────────
|
|
2127
|
+
/**
|
|
2128
|
+
* Sign an outbound HTTP request (RFC 9421) with an agent's cached Ed25519
|
|
2129
|
+
* key, so the receiver can tell which Vorim agent sent it. `keyid` is the
|
|
2130
|
+
* agent_id, `alg` is `ed25519`, and `tag` defaults to `vorim`. When the
|
|
2131
|
+
* request has a body, a Content-Digest header is added and covered.
|
|
2132
|
+
*
|
|
2133
|
+
* The key must already be in this instance's keyring (from `register()`,
|
|
2134
|
+
* `registerEphemeral()` or `useAgentKey()`). Returns the headers to add.
|
|
2135
|
+
*
|
|
2136
|
+
* ```ts
|
|
2137
|
+
* const { headers } = await vorim.signHttpRequest(agentId, {
|
|
2138
|
+
* method: 'POST', url: 'https://agent-b.example/tasks',
|
|
2139
|
+
* headers: { 'content-type': 'application/json' }, body,
|
|
2140
|
+
* });
|
|
2141
|
+
* await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body });
|
|
2142
|
+
* ```
|
|
2143
|
+
*/
|
|
2144
|
+
async signHttpRequest(agentId, request, options = {}) {
|
|
2145
|
+
const privateKey = this.agentKeys.get(agentId);
|
|
2146
|
+
if (!privateKey) {
|
|
2147
|
+
throw new VorimError(
|
|
2148
|
+
400,
|
|
2149
|
+
"AGENT_KEY_NOT_LOADED",
|
|
2150
|
+
`No private key is cached for agent ${agentId}. Call register() or useAgentKey(agentId, privateKeyPem) first.`
|
|
2151
|
+
);
|
|
2152
|
+
}
|
|
2153
|
+
return signHttpRequest(request, {
|
|
2154
|
+
...options,
|
|
2155
|
+
tag: options.tag ?? "vorim",
|
|
2156
|
+
privateKey,
|
|
2157
|
+
keyid: agentId,
|
|
2158
|
+
alg: "ed25519"
|
|
2159
|
+
});
|
|
2160
|
+
}
|
|
2161
|
+
/**
|
|
2162
|
+
* Verify an RFC 9421 signed request through Vorim. The server resolves the
|
|
2163
|
+
* signature's keyid (an agent_id) to that agent's registered public key,
|
|
2164
|
+
* rejects suspended or revoked agents, and checks Content-Digest when the
|
|
2165
|
+
* body is passed. Public endpoint: no API key scope is needed.
|
|
2166
|
+
*
|
|
2167
|
+
* Pass the request exactly as received: method, full URL, headers, and the
|
|
2168
|
+
* raw body if `content-digest` is covered.
|
|
2169
|
+
*/
|
|
2170
|
+
async verifyHttpRequest(request, options = {}) {
|
|
2171
|
+
const payload = {
|
|
2172
|
+
method: request.method,
|
|
2173
|
+
url: request.url,
|
|
2174
|
+
headers: request.headers
|
|
2175
|
+
};
|
|
2176
|
+
if (typeof request.body === "string") {
|
|
2177
|
+
payload.body = request.body;
|
|
2178
|
+
} else if (request.body instanceof Uint8Array) {
|
|
2179
|
+
let bin = "";
|
|
2180
|
+
for (let i = 0; i < request.body.length; i++) bin += String.fromCharCode(request.body[i]);
|
|
2181
|
+
payload.body_base64 = btoa(bin);
|
|
2182
|
+
}
|
|
2183
|
+
if (options.label !== void 0) payload.label = options.label;
|
|
2184
|
+
if (options.maxAgeSeconds !== void 0) payload.max_age_seconds = options.maxAgeSeconds;
|
|
2185
|
+
return this.post("/http-signatures/verify", payload);
|
|
2186
|
+
}
|
|
1252
2187
|
// ─── Signing ──────────────────────────────────────────────────────
|
|
1253
2188
|
/**
|
|
1254
2189
|
* Sign a payload with an Ed25519 private key (client-side).
|
|
@@ -1436,6 +2371,7 @@ async function deviceLogin(opts) {
|
|
|
1436
2371
|
export {
|
|
1437
2372
|
CANONICAL_TOOL_CATALOGUE_VERSION,
|
|
1438
2373
|
HMAC_SHA256_PREFIX,
|
|
2374
|
+
HttpSignatureError,
|
|
1439
2375
|
SHA256_PREFIX,
|
|
1440
2376
|
VorimDeniedError,
|
|
1441
2377
|
VorimError,
|
|
@@ -1443,18 +2379,24 @@ export {
|
|
|
1443
2379
|
canonicalPayloadV0,
|
|
1444
2380
|
canonicalPayloadV1,
|
|
1445
2381
|
commitPayload,
|
|
2382
|
+
contentDigest,
|
|
2383
|
+
createSignatureBase,
|
|
1446
2384
|
createVorim as default,
|
|
1447
2385
|
deviceLogin,
|
|
1448
2386
|
eventDigest,
|
|
2387
|
+
foldTraceparent,
|
|
1449
2388
|
hashPayload,
|
|
1450
2389
|
hashPreviousEvent,
|
|
1451
2390
|
hashSystemPrompt,
|
|
1452
2391
|
hashTool,
|
|
1453
2392
|
hashToolCatalogue,
|
|
2393
|
+
httpSignatureAlgForKey,
|
|
1454
2394
|
isDigest,
|
|
1455
2395
|
isKeyedCommitment,
|
|
1456
2396
|
jcsCanonicalise,
|
|
1457
2397
|
portableReceiptCanonicalBytes,
|
|
1458
|
-
prepareReplayContext
|
|
2398
|
+
prepareReplayContext,
|
|
2399
|
+
signHttpRequest,
|
|
2400
|
+
verifyHttpRequest
|
|
1459
2401
|
};
|
|
1460
2402
|
//# sourceMappingURL=index.js.map
|