@oneaddress/partner-sdk 2.4.1 → 2.6.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-FDMB4BNC.mjs";
6
+ isSafeWebhookUrl,
7
+ verifyRegistryHead
8
+ } from "./chunk-QAOGKPD3.mjs";
7
9
 
8
10
  // src/index.ts
9
11
  import crypto from "crypto";
@@ -69,6 +71,36 @@ function keyShareExpiryIso(dispatchAt, retentionPeriodDays) {
69
71
  return new Date(dispatchAt.getTime() + days * DAY_MS).toISOString();
70
72
  }
71
73
 
74
+ // src/app-hosts.ts
75
+ function allowedAppHosts() {
76
+ const hosts = ["oneaddress.io", "app.oneaddress.io"];
77
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
78
+ hosts.push("localhost", "127.0.0.1");
79
+ }
80
+ return new Set(hosts);
81
+ }
82
+ function resolveAppOrigin(baseUrl, label) {
83
+ let parsed;
84
+ try {
85
+ parsed = new URL(baseUrl);
86
+ } catch {
87
+ throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
88
+ }
89
+ const allowed = allowedAppHosts();
90
+ if (!allowed.has(parsed.hostname)) {
91
+ throw new Error(
92
+ `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
93
+ );
94
+ }
95
+ const loopback = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
96
+ if (parsed.protocol !== "https:" && !loopback) {
97
+ throw new Error(
98
+ `[OneAddress SDK] ${label}: appBaseUrl must use https (plain http is accepted for localhost only)`
99
+ );
100
+ }
101
+ return parsed.origin;
102
+ }
103
+
72
104
  // ../name-match/src/index.ts
73
105
  function isEmailLike(value) {
74
106
  return value.includes("@");
@@ -329,6 +361,225 @@ function createOutboxConsumer(opts) {
329
361
  };
330
362
  }
331
363
 
364
+ // src/registry-head-check.ts
365
+ var OA_APP_BASE_URL = "https://oneaddress.io";
366
+ var HEAD_PATH = "/.well-known/oneaddress-key-registry-head.json";
367
+ function parsePinnedRegistryRoots(raw) {
368
+ if (raw === void 0 || raw === null || raw.trim() === "") {
369
+ return { ok: false, configured: false, reason: "no root set configured" };
370
+ }
371
+ let parsed;
372
+ try {
373
+ parsed = JSON.parse(raw);
374
+ } catch {
375
+ return { ok: false, configured: true, reason: "not valid JSON" };
376
+ }
377
+ const list = Array.isArray(parsed) ? parsed : parsed?.keys;
378
+ if (!Array.isArray(list)) {
379
+ return {
380
+ ok: false,
381
+ configured: true,
382
+ reason: 'expected an array of roots, or the published document with a "keys" array'
383
+ };
384
+ }
385
+ if (list.length === 0) {
386
+ return { ok: false, configured: true, reason: "root set is empty" };
387
+ }
388
+ const roots = [];
389
+ for (const [i, entry] of list.entries()) {
390
+ const e = entry;
391
+ 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 === "") {
392
+ return {
393
+ ok: false,
394
+ configured: true,
395
+ reason: `root at index ${i} is missing root_key_id, algorithm or public_key_b64`
396
+ };
397
+ }
398
+ roots.push({
399
+ root_key_id: e.root_key_id,
400
+ algorithm: e.algorithm,
401
+ public_key_b64: e.public_key_b64
402
+ });
403
+ }
404
+ return { ok: true, roots };
405
+ }
406
+ function fromHeadVerdict(v) {
407
+ switch (v) {
408
+ case "unknown-root":
409
+ return {
410
+ verdict: "head-unknown-root",
411
+ alarm: true,
412
+ 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."
413
+ };
414
+ case "bad-signature":
415
+ return {
416
+ verdict: "head-bad-signature",
417
+ alarm: true,
418
+ detail: "the root signature on the head did not verify. Treat as tampering until shown otherwise."
419
+ };
420
+ case "expired":
421
+ return {
422
+ verdict: "head-expired",
423
+ alarm: true,
424
+ 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."
425
+ };
426
+ default:
427
+ return {
428
+ verdict: "head-malformed",
429
+ alarm: true,
430
+ detail: "the document served is not a head this build can verify."
431
+ };
432
+ }
433
+ }
434
+ async function checkRegistryHead(opts) {
435
+ const expectedKeyId = opts.keyId;
436
+ if (!opts.pinnedRoots || opts.pinnedRoots.length === 0) {
437
+ return {
438
+ verdict: "roots-not-pinned",
439
+ checked: false,
440
+ alarm: false,
441
+ 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.",
442
+ expectedKeyId
443
+ };
444
+ }
445
+ const origin = resolveAppOrigin(opts.appBaseUrl ?? OA_APP_BASE_URL, "checkRegistryHead");
446
+ const doFetch = opts.fetchImpl ?? fetch;
447
+ const timeoutMs = opts.timeoutMs ?? 1e4;
448
+ let res;
449
+ try {
450
+ res = await doFetch(`${origin}${HEAD_PATH}`, {
451
+ // No custom headers and no cache-busting on purpose. The head carries no
452
+ // per-caller variance and OneAddress edge-caches it for five minutes, so a
453
+ // fleet of recipients polling hourly costs one origin read between them.
454
+ ...typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? { signal: AbortSignal.timeout(timeoutMs) } : {}
455
+ });
456
+ } catch (err) {
457
+ return {
458
+ verdict: "head-unreachable",
459
+ checked: false,
460
+ alarm: false,
461
+ detail: `could not fetch the head: ${err instanceof Error ? err.message : String(err)}`,
462
+ expectedKeyId
463
+ };
464
+ }
465
+ if (res.status === 503) {
466
+ return {
467
+ verdict: "head-absent",
468
+ checked: false,
469
+ alarm: false,
470
+ detail: "OneAddress is publishing no head right now (503). Consumers are refusing dispatches while this holds.",
471
+ expectedKeyId
472
+ };
473
+ }
474
+ if (!res.ok) {
475
+ return {
476
+ verdict: "head-unreachable",
477
+ checked: false,
478
+ alarm: false,
479
+ detail: `the head endpoint answered HTTP ${res.status}`,
480
+ expectedKeyId
481
+ };
482
+ }
483
+ let doc;
484
+ try {
485
+ doc = await res.json();
486
+ } catch {
487
+ return {
488
+ verdict: "head-malformed",
489
+ checked: false,
490
+ alarm: true,
491
+ detail: "the head endpoint answered 200 with a body that is not JSON.",
492
+ expectedKeyId
493
+ };
494
+ }
495
+ const issued = typeof doc?.issued_at === "string" ? doc.issued_at : void 0;
496
+ const expires = typeof doc?.expires_at === "string" ? doc.expires_at : void 0;
497
+ const headVerdict = await verifyRegistryHead(doc, opts.pinnedRoots, opts.now ?? /* @__PURE__ */ new Date());
498
+ if (headVerdict !== "ok") {
499
+ const mapped = fromHeadVerdict(headVerdict);
500
+ return {
501
+ ...mapped,
502
+ checked: false,
503
+ expectedKeyId,
504
+ headIssuedAt: issued,
505
+ headExpiresAt: expires
506
+ };
507
+ }
508
+ const named = doc.heads?.[opts.partnerId.toLowerCase()];
509
+ if (typeof named !== "string" || named === "") {
510
+ return {
511
+ verdict: "partner-absent",
512
+ checked: true,
513
+ alarm: true,
514
+ 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.",
515
+ expectedKeyId,
516
+ headIssuedAt: issued,
517
+ headExpiresAt: expires
518
+ };
519
+ }
520
+ if (expectedKeyId && headNamesKey(doc, opts.partnerId, expectedKeyId)) {
521
+ return {
522
+ verdict: "ok",
523
+ checked: true,
524
+ alarm: false,
525
+ detail: "the head names the key this recipient expects.",
526
+ namedKeyId: named,
527
+ expectedKeyId,
528
+ headIssuedAt: issued,
529
+ headExpiresAt: expires
530
+ };
531
+ }
532
+ if (opts.holdsKey) {
533
+ let holds;
534
+ try {
535
+ holds = await opts.holdsKey(named);
536
+ } catch (err) {
537
+ return {
538
+ verdict: "key-identity-unknown",
539
+ checked: false,
540
+ alarm: false,
541
+ 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)}`,
542
+ namedKeyId: named,
543
+ expectedKeyId,
544
+ headIssuedAt: issued,
545
+ headExpiresAt: expires
546
+ };
547
+ }
548
+ if (holds) {
549
+ return {
550
+ verdict: "names-key-we-hold",
551
+ checked: true,
552
+ alarm: false,
553
+ detail: `the head names ${named}, which this recipient holds. Consistent with a rotation cutover.`,
554
+ namedKeyId: named,
555
+ expectedKeyId,
556
+ headIssuedAt: issued,
557
+ headExpiresAt: expires
558
+ };
559
+ }
560
+ return {
561
+ verdict: "names-key-we-lack",
562
+ checked: true,
563
+ alarm: true,
564
+ 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.`,
565
+ namedKeyId: named,
566
+ expectedKeyId,
567
+ headIssuedAt: issued,
568
+ headExpiresAt: expires
569
+ };
570
+ }
571
+ return {
572
+ verdict: "key-identity-unknown",
573
+ checked: false,
574
+ alarm: false,
575
+ detail: `the head is valid and names ${named}; configure keyId or holdsKey so this check can tell whether that key is yours.`,
576
+ namedKeyId: named,
577
+ expectedKeyId,
578
+ headIssuedAt: issued,
579
+ headExpiresAt: expires
580
+ };
581
+ }
582
+
332
583
  // src/index.ts
333
584
  var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
334
585
  function createSqlIdempotencyStore(opts) {
@@ -501,7 +752,7 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
501
752
  return JSON.parse(new TextDecoder().decode(plaintext));
502
753
  }
503
754
  async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
504
- const { decryptSession: decryptSessionCrypto } = await import("./src-SNMMZ4BT.mjs");
755
+ const { decryptSession: decryptSessionCrypto } = await import("./src-BPES2DKY.mjs");
505
756
  return decryptSessionCrypto(
506
757
  share,
507
758
  envelopeB64,
@@ -568,7 +819,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
568
819
  new TextEncoder().encode(`oneaddress:transform-session:${partnerId}`)
569
820
  );
570
821
  }
571
- var OA_APP_BASE_URL = "https://oneaddress.io";
822
+ var OA_APP_BASE_URL2 = "https://oneaddress.io";
572
823
  async function confirmUpdate(opts) {
573
824
  const {
574
825
  partnerId,
@@ -578,7 +829,7 @@ async function confirmUpdate(opts) {
578
829
  note,
579
830
  loaRef,
580
831
  memberName,
581
- appBaseUrl = OA_APP_BASE_URL,
832
+ appBaseUrl = OA_APP_BASE_URL2,
582
833
  fetchImpl = fetch
583
834
  } = opts;
584
835
  if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
@@ -628,31 +879,9 @@ async function confirmUpdate(opts) {
628
879
  }
629
880
  return { ok: false, status: res.status, error };
630
881
  }
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`;
882
+ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2) {
883
+ const origin = resolveAppOrigin(appBaseUrl, "fetchLoaPublicKey");
884
+ const url = `${origin}/.well-known/oneaddress-loa-key.pem`;
656
885
  const res = await fetch(url);
657
886
  if (!res.ok) {
658
887
  throw new Error(`[OneAddress SDK] Failed to fetch LOA public key: HTTP ${res.status}`);
@@ -909,6 +1138,21 @@ var InvalidUpdateTypesError = class extends Error {
909
1138
  this.name = "InvalidUpdateTypesError";
910
1139
  }
911
1140
  };
1141
+ var MissingKeyError = class extends Error {
1142
+ constructor(keyId) {
1143
+ super(`[OneAddress SDK] no private key for key_id ${keyId}`);
1144
+ this.keyId = keyId;
1145
+ this.name = "MissingKeyError";
1146
+ }
1147
+ };
1148
+ var SessionDecryptError = class extends Error {
1149
+ constructor(keyId, detail) {
1150
+ super(`[OneAddress SDK] session decrypt failed${keyId ? ` for key_id ${keyId}` : ""}`);
1151
+ this.keyId = keyId;
1152
+ this.detail = detail;
1153
+ this.name = "SessionDecryptError";
1154
+ }
1155
+ };
912
1156
  function requireContactValue(kind, value) {
913
1157
  if (typeof value !== "string" || value === "") {
914
1158
  throw new Error(
@@ -1026,7 +1270,14 @@ function createOneAddressHandler(options) {
1026
1270
  }
1027
1271
  async function buildD5Pieces(body, partnerId) {
1028
1272
  const share = body.session_key_share;
1029
- const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
1273
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
1274
+ if (keyId && shareKeyId && shareKeyId !== keyId) throw new MissingKeyError(shareKeyId);
1275
+ let data;
1276
+ try {
1277
+ data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
1278
+ } catch (err) {
1279
+ throw new SessionDecryptError(shareKeyId, err instanceof Error ? err.message : String(err));
1280
+ }
1030
1281
  const updateTypes = readUpdateTypes(data.update_types);
1031
1282
  if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
1032
1283
  const address = updateTypes.includes("address") ? validateAddress({
@@ -1159,6 +1410,22 @@ function createOneAddressHandler(options) {
1159
1410
  detail: "update_types must be an array of " + UPDATE_TYPE_ORDER.join("|") + ". A name this build does not know was refused rather than dropped. Update @oneaddress/partner-sdk."
1160
1411
  });
1161
1412
  }
1413
+ if (err instanceof MissingKeyError) {
1414
+ console.error("[OneAddress SDK] Handler error:", err.message);
1415
+ return declared(503, {
1416
+ error: "missing_key",
1417
+ key_id: err.keyId,
1418
+ detail: "This receiver is configured for a different key_id and holds no private key for the one this dispatch names. Retry once the key is installed. If the key was retired and destroyed before its destroy_after date, it cannot be recovered from either side."
1419
+ });
1420
+ }
1421
+ if (err instanceof SessionDecryptError) {
1422
+ console.error("[OneAddress SDK] Handler error:", err.detail);
1423
+ return declared(422, {
1424
+ error: "decrypt_failed",
1425
+ ...err.keyId ? { key_id: err.keyId } : {},
1426
+ detail: err.detail
1427
+ });
1428
+ }
1162
1429
  throw err;
1163
1430
  }
1164
1431
  const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
@@ -1579,6 +1846,8 @@ export {
1579
1846
  toOutboxTimestamp,
1580
1847
  fromOutboxTimestamp,
1581
1848
  createOutboxConsumer,
1849
+ parsePinnedRegistryRoots,
1850
+ checkRegistryHead,
1582
1851
  createSqlIdempotencyStore,
1583
1852
  verifySignature,
1584
1853
  verifyWithGrace,