@oneaddress/partner-sdk 2.5.0 → 2.7.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.
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  encryptEnvelopeForPartner,
3
3
  encryptSessionForPartner,
4
+ headNamesKey,
4
5
  isFreshTimestamp,
5
- isSafeWebhookUrl
6
- } from "./chunk-ZY2K54LD.mjs";
6
+ isSafeWebhookUrl,
7
+ verifyRegistryHead
8
+ } from "./chunk-CLV6TLSP.mjs";
7
9
 
8
10
  // src/index.ts
9
11
  import crypto from "crypto";
@@ -45,10 +47,12 @@ var D5_BODY_CONDITIONAL = {
45
47
  crossover_key_ids: "key-crossover copy only"
46
48
  };
47
49
  var D5_BODY_DRILL_ONLY = ["conformance"];
50
+ var D5_BODY_ADDED_AT_SEND = ["dispatch_id"];
48
51
  var D5_BODY_ALL_ALLOWED = [
49
52
  ...D5_BODY_ALWAYS,
50
53
  ...Object.keys(D5_BODY_CONDITIONAL),
51
- ...D5_BODY_DRILL_ONLY
54
+ ...D5_BODY_DRILL_ONLY,
55
+ ...D5_BODY_ADDED_AT_SEND
52
56
  ];
53
57
 
54
58
  // ../protocol/src/retention.ts
@@ -69,6 +73,42 @@ function keyShareExpiryIso(dispatchAt, retentionPeriodDays) {
69
73
  return new Date(dispatchAt.getTime() + days * DAY_MS).toISOString();
70
74
  }
71
75
 
76
+ // ../protocol/src/pull-signature.ts
77
+ var PULL_SIGNATURE_VERSION_HEADER = "X-OneAddress-Signature-Version";
78
+ function pullSigningStringV2(timestamp, method, pathAndQuery, body = "") {
79
+ return `v2.${timestamp}.${method.toUpperCase()}.${pathAndQuery}.${body}`;
80
+ }
81
+
82
+ // src/app-hosts.ts
83
+ function allowedAppHosts() {
84
+ const hosts = ["oneaddress.io", "app.oneaddress.io"];
85
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
86
+ hosts.push("localhost", "127.0.0.1");
87
+ }
88
+ return new Set(hosts);
89
+ }
90
+ function resolveAppOrigin(baseUrl, label) {
91
+ let parsed;
92
+ try {
93
+ parsed = new URL(baseUrl);
94
+ } catch {
95
+ throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
96
+ }
97
+ const allowed = allowedAppHosts();
98
+ if (!allowed.has(parsed.hostname)) {
99
+ throw new Error(
100
+ `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
101
+ );
102
+ }
103
+ const loopback = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
104
+ if (parsed.protocol !== "https:" && !loopback) {
105
+ throw new Error(
106
+ `[OneAddress SDK] ${label}: appBaseUrl must use https (plain http is accepted for localhost only)`
107
+ );
108
+ }
109
+ return parsed.origin;
110
+ }
111
+
72
112
  // ../name-match/src/index.ts
73
113
  function isEmailLike(value) {
74
114
  return value.includes("@");
@@ -329,6 +369,225 @@ function createOutboxConsumer(opts) {
329
369
  };
330
370
  }
331
371
 
372
+ // src/registry-head-check.ts
373
+ var OA_APP_BASE_URL = "https://oneaddress.io";
374
+ var HEAD_PATH = "/.well-known/oneaddress-key-registry-head.json";
375
+ function parsePinnedRegistryRoots(raw) {
376
+ if (raw === void 0 || raw === null || raw.trim() === "") {
377
+ return { ok: false, configured: false, reason: "no root set configured" };
378
+ }
379
+ let parsed;
380
+ try {
381
+ parsed = JSON.parse(raw);
382
+ } catch {
383
+ return { ok: false, configured: true, reason: "not valid JSON" };
384
+ }
385
+ const list = Array.isArray(parsed) ? parsed : parsed?.keys;
386
+ if (!Array.isArray(list)) {
387
+ return {
388
+ ok: false,
389
+ configured: true,
390
+ reason: 'expected an array of roots, or the published document with a "keys" array'
391
+ };
392
+ }
393
+ if (list.length === 0) {
394
+ return { ok: false, configured: true, reason: "root set is empty" };
395
+ }
396
+ const roots = [];
397
+ for (const [i, entry] of list.entries()) {
398
+ const e = entry;
399
+ if (typeof e?.root_key_id !== "string" || e.root_key_id === "" || typeof e?.algorithm !== "string" || e.algorithm === "" || typeof e?.public_key_b64 !== "string" || e.public_key_b64 === "") {
400
+ return {
401
+ ok: false,
402
+ configured: true,
403
+ reason: `root at index ${i} is missing root_key_id, algorithm or public_key_b64`
404
+ };
405
+ }
406
+ roots.push({
407
+ root_key_id: e.root_key_id,
408
+ algorithm: e.algorithm,
409
+ public_key_b64: e.public_key_b64
410
+ });
411
+ }
412
+ return { ok: true, roots };
413
+ }
414
+ function fromHeadVerdict(v) {
415
+ switch (v) {
416
+ case "unknown-root":
417
+ return {
418
+ verdict: "head-unknown-root",
419
+ alarm: true,
420
+ detail: "the head is signed by a root that is not in the pinned set. Either OneAddress rotated its root and did not tell you, or this head was not signed by OneAddress. Do not update the pin from the same source that served this head."
421
+ };
422
+ case "bad-signature":
423
+ return {
424
+ verdict: "head-bad-signature",
425
+ alarm: true,
426
+ detail: "the root signature on the head did not verify. Treat as tampering until shown otherwise."
427
+ };
428
+ case "expired":
429
+ return {
430
+ verdict: "head-expired",
431
+ alarm: true,
432
+ detail: "the head is authentic but past its expiry, so consumers are refusing every dispatch. Usually a missed re-sign at OneAddress; it is also what suppression of head updates looks like, so raise it rather than waiting."
433
+ };
434
+ default:
435
+ return {
436
+ verdict: "head-malformed",
437
+ alarm: true,
438
+ detail: "the document served is not a head this build can verify."
439
+ };
440
+ }
441
+ }
442
+ async function checkRegistryHead(opts) {
443
+ const expectedKeyId = opts.keyId;
444
+ if (!opts.pinnedRoots || opts.pinnedRoots.length === 0) {
445
+ return {
446
+ verdict: "roots-not-pinned",
447
+ checked: false,
448
+ alarm: false,
449
+ detail: "no registry root pinned, so the head cannot be checked. Pin the published root set out of band; fetching it from OneAddress would prove nothing, because the same deployment serves the head.",
450
+ expectedKeyId
451
+ };
452
+ }
453
+ const origin = resolveAppOrigin(opts.appBaseUrl ?? OA_APP_BASE_URL, "checkRegistryHead");
454
+ const doFetch = opts.fetchImpl ?? fetch;
455
+ const timeoutMs = opts.timeoutMs ?? 1e4;
456
+ let res;
457
+ try {
458
+ res = await doFetch(`${origin}${HEAD_PATH}`, {
459
+ // No custom headers and no cache-busting on purpose. The head carries no
460
+ // per-caller variance and OneAddress edge-caches it for five minutes, so a
461
+ // fleet of recipients polling hourly costs one origin read between them.
462
+ ...typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? { signal: AbortSignal.timeout(timeoutMs) } : {}
463
+ });
464
+ } catch (err) {
465
+ return {
466
+ verdict: "head-unreachable",
467
+ checked: false,
468
+ alarm: false,
469
+ detail: `could not fetch the head: ${err instanceof Error ? err.message : String(err)}`,
470
+ expectedKeyId
471
+ };
472
+ }
473
+ if (res.status === 503) {
474
+ return {
475
+ verdict: "head-absent",
476
+ checked: false,
477
+ alarm: false,
478
+ detail: "OneAddress is publishing no head right now (503). Consumers are refusing dispatches while this holds.",
479
+ expectedKeyId
480
+ };
481
+ }
482
+ if (!res.ok) {
483
+ return {
484
+ verdict: "head-unreachable",
485
+ checked: false,
486
+ alarm: false,
487
+ detail: `the head endpoint answered HTTP ${res.status}`,
488
+ expectedKeyId
489
+ };
490
+ }
491
+ let doc;
492
+ try {
493
+ doc = await res.json();
494
+ } catch {
495
+ return {
496
+ verdict: "head-malformed",
497
+ checked: false,
498
+ alarm: true,
499
+ detail: "the head endpoint answered 200 with a body that is not JSON.",
500
+ expectedKeyId
501
+ };
502
+ }
503
+ const issued = typeof doc?.issued_at === "string" ? doc.issued_at : void 0;
504
+ const expires = typeof doc?.expires_at === "string" ? doc.expires_at : void 0;
505
+ const headVerdict = await verifyRegistryHead(doc, opts.pinnedRoots, opts.now ?? /* @__PURE__ */ new Date());
506
+ if (headVerdict !== "ok") {
507
+ const mapped = fromHeadVerdict(headVerdict);
508
+ return {
509
+ ...mapped,
510
+ checked: false,
511
+ expectedKeyId,
512
+ headIssuedAt: issued,
513
+ headExpiresAt: expires
514
+ };
515
+ }
516
+ const named = doc.heads?.[opts.partnerId.toLowerCase()];
517
+ if (typeof named !== "string" || named === "") {
518
+ return {
519
+ verdict: "partner-absent",
520
+ checked: true,
521
+ alarm: true,
522
+ detail: "the head is valid and names no current key for this partner id, so OneAddress is not dispatching to you. Check the partner id first, then ask OneAddress.",
523
+ expectedKeyId,
524
+ headIssuedAt: issued,
525
+ headExpiresAt: expires
526
+ };
527
+ }
528
+ if (expectedKeyId && headNamesKey(doc, opts.partnerId, expectedKeyId)) {
529
+ return {
530
+ verdict: "ok",
531
+ checked: true,
532
+ alarm: false,
533
+ detail: "the head names the key this recipient expects.",
534
+ namedKeyId: named,
535
+ expectedKeyId,
536
+ headIssuedAt: issued,
537
+ headExpiresAt: expires
538
+ };
539
+ }
540
+ if (opts.holdsKey) {
541
+ let holds;
542
+ try {
543
+ holds = await opts.holdsKey(named);
544
+ } catch (err) {
545
+ return {
546
+ verdict: "key-identity-unknown",
547
+ checked: false,
548
+ alarm: false,
549
+ detail: `the head names ${named} and this recipient's key source could not say whether it holds it: ${err instanceof Error ? err.message : String(err)}`,
550
+ namedKeyId: named,
551
+ expectedKeyId,
552
+ headIssuedAt: issued,
553
+ headExpiresAt: expires
554
+ };
555
+ }
556
+ if (holds) {
557
+ return {
558
+ verdict: "names-key-we-hold",
559
+ checked: true,
560
+ alarm: false,
561
+ detail: `the head names ${named}, which this recipient holds. Consistent with a rotation cutover.`,
562
+ namedKeyId: named,
563
+ expectedKeyId,
564
+ headIssuedAt: issued,
565
+ headExpiresAt: expires
566
+ };
567
+ }
568
+ return {
569
+ verdict: "names-key-we-lack",
570
+ checked: true,
571
+ alarm: true,
572
+ detail: `the head names ${named} as the current key for this partner id, and this recipient does not hold it. If you did not rotate to that key, address envelopes are being sealed to a key you cannot read. Contact OneAddress through a channel that is not oneaddress.io.`,
573
+ namedKeyId: named,
574
+ expectedKeyId,
575
+ headIssuedAt: issued,
576
+ headExpiresAt: expires
577
+ };
578
+ }
579
+ return {
580
+ verdict: "key-identity-unknown",
581
+ checked: false,
582
+ alarm: false,
583
+ detail: `the head is valid and names ${named}; configure keyId or holdsKey so this check can tell whether that key is yours.`,
584
+ namedKeyId: named,
585
+ expectedKeyId,
586
+ headIssuedAt: issued,
587
+ headExpiresAt: expires
588
+ };
589
+ }
590
+
332
591
  // src/index.ts
333
592
  var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
334
593
  function createSqlIdempotencyStore(opts) {
@@ -419,6 +678,7 @@ function createSqlIdempotencyStore(opts) {
419
678
  }
420
679
  function verifySignature(rawBody, signature, timestamp, secret) {
421
680
  if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
681
+ if (!secret) return false;
422
682
  const sigPayload = `${timestamp}.${rawBody}`;
423
683
  const expected = crypto.createHmac("sha256", secret).update(sigPayload).digest("hex");
424
684
  const sigBuffer = Buffer.from(signature, "hex");
@@ -426,6 +686,17 @@ function verifySignature(rawBody, signature, timestamp, secret) {
426
686
  if (sigBuffer.length !== expBuffer.length) return false;
427
687
  return crypto.timingSafeEqual(sigBuffer, expBuffer);
428
688
  }
689
+ function signPullRequest(opts) {
690
+ if (!opts.secret) throw new Error("signPullRequest: secret is required");
691
+ const u = new URL(opts.url);
692
+ const ts = String(opts.timestamp ?? Math.floor(Date.now() / 1e3));
693
+ const signature = crypto.createHmac("sha256", opts.secret).update(pullSigningStringV2(ts, opts.method ?? "GET", `${u.pathname}${u.search}`, opts.body ?? "")).digest("hex");
694
+ return {
695
+ "X-OneAddress-Timestamp": ts,
696
+ "X-OneAddress-Signature": signature,
697
+ [PULL_SIGNATURE_VERSION_HEADER]: "2"
698
+ };
699
+ }
429
700
  function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousSecret, graceUntil) {
430
701
  if (verifySignature(rawBody, signature, timestamp, currentSecret)) return true;
431
702
  if (previousSecret && previousSecret !== currentSecret && graceUntil) {
@@ -501,7 +772,7 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
501
772
  return JSON.parse(new TextDecoder().decode(plaintext));
502
773
  }
503
774
  async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
504
- const { decryptSession: decryptSessionCrypto } = await import("./src-RBLFVBGY.mjs");
775
+ const { decryptSession: decryptSessionCrypto } = await import("./src-FPYBM6X6.mjs");
505
776
  return decryptSessionCrypto(
506
777
  share,
507
778
  envelopeB64,
@@ -568,7 +839,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
568
839
  new TextEncoder().encode(`oneaddress:transform-session:${partnerId}`)
569
840
  );
570
841
  }
571
- var OA_APP_BASE_URL = "https://oneaddress.io";
842
+ var OA_APP_BASE_URL2 = "https://oneaddress.io";
572
843
  async function confirmUpdate(opts) {
573
844
  const {
574
845
  partnerId,
@@ -578,7 +849,7 @@ async function confirmUpdate(opts) {
578
849
  note,
579
850
  loaRef,
580
851
  memberName,
581
- appBaseUrl = OA_APP_BASE_URL,
852
+ appBaseUrl = OA_APP_BASE_URL2,
582
853
  fetchImpl = fetch
583
854
  } = opts;
584
855
  if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
@@ -628,31 +899,9 @@ async function confirmUpdate(opts) {
628
899
  }
629
900
  return { ok: false, status: res.status, error };
630
901
  }
631
- function allowedLoaHosts() {
632
- const hosts = ["oneaddress.io", "app.oneaddress.io"];
633
- if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
634
- hosts.push("localhost", "127.0.0.1");
635
- }
636
- return new Set(hosts);
637
- }
638
- async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
639
- let parsedBase;
640
- try {
641
- parsedBase = new URL(appBaseUrl);
642
- } catch {
643
- throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl is not a valid URL");
644
- }
645
- const allowedHosts = allowedLoaHosts();
646
- if (!allowedHosts.has(parsedBase.hostname)) {
647
- throw new Error(
648
- `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
649
- );
650
- }
651
- const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
652
- if (parsedBase.protocol !== "https:" && !loopback) {
653
- throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
654
- }
655
- const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
902
+ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2) {
903
+ const origin = resolveAppOrigin(appBaseUrl, "fetchLoaPublicKey");
904
+ const url = `${origin}/.well-known/oneaddress-loa-key.pem`;
656
905
  const res = await fetch(url);
657
906
  if (!res.ok) {
658
907
  throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
@@ -1134,14 +1383,22 @@ function createOneAddressHandler(options) {
1134
1383
  }
1135
1384
  const partnerId = body.partner_id ?? "";
1136
1385
  const tsNum = Number(tsHeader);
1137
- const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
1386
+ const headerDispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
1387
+ const bodyDispatchId = typeof body.dispatch_id === "string" ? body.dispatch_id : "";
1388
+ if (bodyDispatchId && headerDispatchId && bodyDispatchId !== headerDispatchId) {
1389
+ return new Response(JSON.stringify({ error: "dispatch_id_mismatch" }), {
1390
+ status: 400,
1391
+ headers: { "Content-Type": "application/json" }
1392
+ });
1393
+ }
1394
+ const dispatchId = bodyDispatchId || headerDispatchId;
1138
1395
  if (isCrossoverSiblingToSkip(body)) {
1139
1396
  return declared(200, { ok: true, skipped: true, crossover: true });
1140
1397
  }
1141
1398
  if (dispatchId) {
1142
1399
  if (!idempotencyStore) {
1143
1400
  const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
1144
- if (nodeEnv === "test") {
1401
+ if (nodeEnv === "test" && headerDispatchId) {
1145
1402
  throw new Error(
1146
1403
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
1147
1404
  );
@@ -1617,8 +1874,11 @@ export {
1617
1874
  toOutboxTimestamp,
1618
1875
  fromOutboxTimestamp,
1619
1876
  createOutboxConsumer,
1877
+ parsePinnedRegistryRoots,
1878
+ checkRegistryHead,
1620
1879
  createSqlIdempotencyStore,
1621
1880
  verifySignature,
1881
+ signPullRequest,
1622
1882
  verifyWithGrace,
1623
1883
  decryptAddress,
1624
1884
  decryptSession,