@oneaddress/partner-sdk 2.5.0 → 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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.6.0] - 2026-10-18
11
+
12
+ ### Added
13
+
14
+ - **`checkRegistryHead` and `parsePinnedRegistryRoots`: ask OneAddress which
15
+ key it says is yours, and check the answer against a root you pinned.**
16
+ OneAddress publishes a root-signed document naming, per partner, the one key
17
+ id that is current. Consumer browsers check it before they encrypt, and that
18
+ check cannot see a deployment that serves a matching substitute for all three
19
+ of the document, the root set and the checking code. A recipient can, because
20
+ it holds its own keys and its own copy of the root.
21
+
22
+ What it does: fetches `/.well-known/oneaddress-key-registry-head.json`,
23
+ verifies the root signature against `pinnedRoots`, and reports whether the
24
+ head names a key you hold (`ok`, `names-key-we-hold`), a key you have never
25
+ held (`names-key-we-lack`, the alarm), or nothing for your partner id. Thirteen
26
+ verdicts, one per distinguishable problem; `checked: false` means the check
27
+ did not run and is never reported as a pass.
28
+
29
+ What it does not do: it refuses to fetch the root set from OneAddress, with no
30
+ option to make it. A root set fetched from the same origin as the head would
31
+ pass against a compromised deployment, which is worse than no check. Pin it
32
+ out of band (see the README). It is detection after the fact: by the time the
33
+ head names a key you lack, any envelope sealed to that key has already gone
34
+ elsewhere. Run it on a schedule, not per dispatch, because the substitution
35
+ diverts the dispatch you would have hung the check on. The drop-in receiver
36
+ runs it hourly when `OA_REGISTRY_ROOTS` is set.
37
+
10
38
  ## [2.5.0] - 2026-10-14
11
39
 
12
40
  ### Changed
package/README.md CHANGED
@@ -904,6 +904,45 @@ Failure mode: `no_match` and `no_account` are **informational only**. The consum
904
904
 
905
905
  ---
906
906
 
907
+ ## Checking which key OneAddress says is yours (added in v2.6.0)
908
+
909
+ OneAddress publishes a root-signed document naming the one key id that is current for each
910
+ partner. `checkRegistryHead` fetches it, verifies the root signature against a root set you
911
+ supply, and tells you whether the named key is one you hold.
912
+
913
+ **Pin the root out of band.** Get the root set once by a route that is not the OneAddress
914
+ website: ask us over a channel you already trust, or compare what a colleague fetched
915
+ separately, and keep it with your other pinned fingerprints. The SDK will not fetch the root
916
+ set for you, because a root fetched from the same origin as the head gives you a check that
917
+ passes against a compromised deployment, which is worse than no check. The roots change on the
918
+ order of years.
919
+
920
+ ```typescript
921
+ import { checkRegistryHead, parsePinnedRegistryRoots } from '@oneaddress/partner-sdk';
922
+
923
+ const roots = parsePinnedRegistryRoots(process.env.OA_REGISTRY_ROOTS); // the published document, pasted
924
+ if (!roots.ok) throw new Error(roots.reason);
925
+
926
+ const result = await checkRegistryHead({
927
+ partnerId: process.env.OA_PARTNER_ID!,
928
+ keyId: process.env.OA_KEY_ID, // the key you expect to be named
929
+ pinnedRoots: roots.roots,
930
+ holdsKey: async (keyId) => myKeyStore.has(keyId),
931
+ });
932
+ if (!result.checked) console.warn('registry check did not run:', result.detail);
933
+ if (result.alarm) page('oneaddress registry head', result.verdict, result.detail);
934
+ ```
935
+
936
+ `names-key-we-lack` is the alarm: the head names a key you have never held, so unless you
937
+ rotated to it, envelopes are being sealed to a key you cannot read. Raise it with us through a
938
+ channel that is not `oneaddress.io`. `names-key-we-hold` is a normal cutover during a rotation.
939
+ `roots-not-pinned`, `head-unreachable` and the other `checked: false` verdicts mean the check did
940
+ not run and should not be read as green.
941
+
942
+ Run it on a schedule (the drop-in receiver runs it hourly), not per dispatch: a substituted key
943
+ diverts the dispatch you would have hung the check on. It detects after the fact and prevents
944
+ nothing on its own; the consumer-side check is what refuses at encrypt time.
945
+
907
946
  ## Edge runtime (Cloudflare Workers, Next.js Edge)
908
947
 
909
948
  ```typescript
@@ -3168,6 +3168,49 @@ async function verifyPartnerKeyAttestationWithRoots(input, signatureHex, rootKey
3168
3168
  return verifyPartnerKeyAttestation(input, signatureHex, root.public_key_b64);
3169
3169
  }
3170
3170
 
3171
+ // ../crypto/src/registry-root-pin.ts
3172
+ var PINNED_REGISTRY_ROOTS = Object.freeze([
3173
+ Object.freeze({
3174
+ root_key_id: "rk1_251368ec9b0a84ae",
3175
+ spki_sha256: "251368ec9b0a84ae9881533bd1687efb7d439edd927aef47c1bb3bb069b3dc1d"
3176
+ })
3177
+ ]);
3178
+ var overrideForTests = null;
3179
+ function __setPinnedRegistryRootsForTests(pins) {
3180
+ overrideForTests = pins;
3181
+ }
3182
+ function pinnedRegistryRoots() {
3183
+ return overrideForTests ?? PINNED_REGISTRY_ROOTS;
3184
+ }
3185
+ function b64ToBytes2(b64) {
3186
+ const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3187
+ const binary = atob(normalised);
3188
+ const out = new Uint8Array(binary.length);
3189
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
3190
+ return out;
3191
+ }
3192
+ async function spkiSha256HexFromB64(spkiB64) {
3193
+ const digest = await crypto.subtle.digest("SHA-256", b64ToBytes2(spkiB64));
3194
+ return bytesToHex3(new Uint8Array(digest));
3195
+ }
3196
+ async function rootIsPinned(root) {
3197
+ try {
3198
+ const digest = await spkiSha256HexFromB64(root.public_key_b64);
3199
+ return pinnedRegistryRoots().some(
3200
+ (p) => p.root_key_id === root.root_key_id && p.spki_sha256 === digest
3201
+ );
3202
+ } catch {
3203
+ return false;
3204
+ }
3205
+ }
3206
+ async function unpinnedRootIds(roots) {
3207
+ const out = [];
3208
+ for (const root of roots) {
3209
+ if (!await rootIsPinned(root)) out.push(String(root?.root_key_id ?? "(no id)"));
3210
+ }
3211
+ return out;
3212
+ }
3213
+
3171
3214
  // ../crypto/src/registry-head.ts
3172
3215
  var REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3173
3216
  var REGISTRY_HEAD_V2 = "oneaddress-partner-key-registry-head:v2";
@@ -3244,7 +3287,7 @@ function buildRegistryHeadStatement(payload) {
3244
3287
  }
3245
3288
  return lines.join("\n");
3246
3289
  }
3247
- function b64ToBytes2(b64) {
3290
+ function b64ToBytes3(b64) {
3248
3291
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
3249
3292
  const binary = atob(normalised);
3250
3293
  const out = new Uint8Array(binary.length);
@@ -3289,7 +3332,7 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3289
3332
  });
3290
3333
  const rootKey = await crypto.subtle.importKey(
3291
3334
  "spki",
3292
- b64ToBytes2(root.public_key_b64),
3335
+ b64ToBytes3(root.public_key_b64),
3293
3336
  { name: "ECDSA", namedCurve: "P-256" },
3294
3337
  false,
3295
3338
  ["verify"]
@@ -3317,7 +3360,7 @@ function headNamesPartner(doc, partnerId) {
3317
3360
  async function partnerKeyFingerprint(publicKeyB64) {
3318
3361
  const digest = await crypto.subtle.digest(
3319
3362
  "SHA-256",
3320
- b64ToBytes2(publicKeyB64)
3363
+ b64ToBytes3(publicKeyB64)
3321
3364
  );
3322
3365
  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3323
3366
  }
@@ -3346,6 +3389,7 @@ async function saysRootNotConfigured(res) {
3346
3389
  }
3347
3390
  }
3348
3391
  async function outcomeFor(partnerId, key, reg, bound) {
3392
+ if (reg.unpinnedRoots.length > 0) return "root-unpinned";
3349
3393
  if (!reg.head) return "head-unusable";
3350
3394
  if (!key.key_signature || !key.root_key_id) {
3351
3395
  if (!key.countersignature_exempt) return "unsigned";
@@ -3404,6 +3448,10 @@ function createPartnerKeyVerifier(env = {}) {
3404
3448
  if (roots.length === 0) {
3405
3449
  return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
3406
3450
  }
3451
+ const unpinnedRoots = await unpinnedRootIds(roots);
3452
+ if (unpinnedRoots.length > 0) {
3453
+ return { ok: true, registry: { roots: [], head: null, headVerdict: "root-unpinned", unpinnedRoots } };
3454
+ }
3407
3455
  let head = null;
3408
3456
  let headVerdict = "absent";
3409
3457
  if (headRes.ok) {
@@ -3411,7 +3459,7 @@ function createPartnerKeyVerifier(env = {}) {
3411
3459
  headVerdict = await verifyRegistryHead(head, roots);
3412
3460
  if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
3413
3461
  }
3414
- return { ok: true, registry: { roots, head, headVerdict } };
3462
+ return { ok: true, registry: { roots, head, headVerdict, unpinnedRoots: [] } };
3415
3463
  } catch {
3416
3464
  return { ok: false, failure: { reason: "fetch-failed" } };
3417
3465
  }
@@ -3443,6 +3491,7 @@ function createPartnerKeyVerifier(env = {}) {
3443
3491
  "bad-attestation": [],
3444
3492
  "not-in-head": [],
3445
3493
  "head-unusable": [],
3494
+ "root-unpinned": [],
3446
3495
  "error": []
3447
3496
  };
3448
3497
  const blocked = {};
@@ -3486,6 +3535,9 @@ function createPartnerKeyVerifier(env = {}) {
3486
3535
  // Counted, not listed: an operator reading a real finding needs to know
3487
3536
  // how many keys were skipped as exempt, without the ids adding noise.
3488
3537
  exempt: tally.exempt.length,
3538
+ // The served root ids the bundle refused, so a report of a rotation
3539
+ // that outran its client build names the root to add.
3540
+ ...reg.unpinnedRoots.length > 0 ? { unpinnedRoots: reg.unpinnedRoots } : {},
3489
3541
  ...Object.fromEntries(failed.map((o) => [o, tally[o]]))
3490
3542
  });
3491
3543
  }
@@ -3614,7 +3666,7 @@ async function openSealedWithSenderHeldKey(share, envelope, partnerId, store) {
3614
3666
  }
3615
3667
 
3616
3668
  // ../crypto/src/index.ts
3617
- function b64ToBytes3(b64) {
3669
+ function b64ToBytes4(b64) {
3618
3670
  const binary = atob(b64);
3619
3671
  const bytes = new Uint8Array(binary.length);
3620
3672
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.codePointAt(i) ?? 0;
@@ -3622,13 +3674,13 @@ function b64ToBytes3(b64) {
3622
3674
  }
3623
3675
  function keyB64ToBytes(key) {
3624
3676
  const begin = key.indexOf("-----BEGIN");
3625
- if (begin === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3677
+ if (begin === -1) return b64ToBytes4(key.replace(/\s+/g, ""));
3626
3678
  const armourEnd = key.indexOf("-----", begin + "-----BEGIN".length);
3627
- if (armourEnd === -1) return b64ToBytes3(key.replace(/\s+/g, ""));
3679
+ if (armourEnd === -1) return b64ToBytes4(key.replace(/\s+/g, ""));
3628
3680
  const bodyStart = armourEnd + "-----".length;
3629
3681
  const end = key.indexOf("-----END", bodyStart);
3630
3682
  const body = end === -1 ? key.slice(bodyStart) : key.slice(bodyStart, end);
3631
- return b64ToBytes3(body.replace(/\s+/g, ""));
3683
+ return b64ToBytes4(body.replace(/\s+/g, ""));
3632
3684
  }
3633
3685
  function bytesToB64(bytes) {
3634
3686
  return btoa(String.fromCodePoint(...bytes));
@@ -3740,7 +3792,7 @@ function generateHybridPartnerKeyPair() {
3740
3792
  }
3741
3793
  async function encryptAddressForPartner(address, partner) {
3742
3794
  const address_ = normaliseAddress(address);
3743
- const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
3795
+ const partnerPubKey = await importP256PublicKey(b64ToBytes4(partner.publicKeyB64));
3744
3796
  const ephemeral = await subtle().generateKey(
3745
3797
  { name: "ECDH", namedCurve: "P-256" },
3746
3798
  true,
@@ -3788,7 +3840,7 @@ async function encryptAddressForPartner(address, partner) {
3788
3840
  };
3789
3841
  }
3790
3842
  async function encryptPayloadForPartner(payload, partner) {
3791
- const partnerPubKey = await importP256PublicKey(b64ToBytes3(partner.publicKeyB64));
3843
+ const partnerPubKey = await importP256PublicKey(b64ToBytes4(partner.publicKeyB64));
3792
3844
  const ephemeral = await subtle().generateKey(
3793
3845
  { name: "ECDH", namedCurve: "P-256" },
3794
3846
  true,
@@ -3841,7 +3893,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
3841
3893
  );
3842
3894
  const ephemeralPub = await subtle().importKey(
3843
3895
  "raw",
3844
- b64ToBytes3(encrypted.ephemeralPublicKey),
3896
+ b64ToBytes4(encrypted.ephemeralPublicKey),
3845
3897
  { name: "ECDH", namedCurve: "P-256" },
3846
3898
  false,
3847
3899
  []
@@ -3851,7 +3903,7 @@ async function decryptAddress(encrypted, privateKeyB64) {
3851
3903
  privateKey,
3852
3904
  256
3853
3905
  );
3854
- const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes3(encrypted.hkdfSalt) : new Uint8Array(32);
3906
+ const hkdfSalt = encrypted.hkdfSalt ? b64ToBytes4(encrypted.hkdfSalt) : new Uint8Array(32);
3855
3907
  const aesKey = await subtle().importKey(
3856
3908
  "raw",
3857
3909
  await subtle().deriveBits(
@@ -3869,9 +3921,9 @@ async function decryptAddress(encrypted, privateKeyB64) {
3869
3921
  ["decrypt"]
3870
3922
  );
3871
3923
  const plainBuf = await subtle().decrypt(
3872
- { name: "AES-GCM", iv: b64ToBytes3(encrypted.iv) },
3924
+ { name: "AES-GCM", iv: b64ToBytes4(encrypted.iv) },
3873
3925
  aesKey,
3874
- b64ToBytes3(encrypted.ciphertext)
3926
+ b64ToBytes4(encrypted.ciphertext)
3875
3927
  );
3876
3928
  return JSON.parse(new TextDecoder().decode(plainBuf));
3877
3929
  }
@@ -3900,7 +3952,7 @@ function bytesToB64Url(bytes) {
3900
3952
  }
3901
3953
  function b64UrlToBytes(b64url) {
3902
3954
  const pad = b64url.length % 4 === 0 ? "" : "=".repeat(4 - b64url.length % 4);
3903
- return b64ToBytes3(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3955
+ return b64ToBytes4(b64url.replace(/-/g, "+").replace(/_/g, "/") + pad);
3904
3956
  }
3905
3957
  function toArrayBuffer(bytes) {
3906
3958
  return bytes.slice().buffer;
@@ -3922,7 +3974,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
3922
3974
  const session_envelope = bytesToB64Url(concat(sessionIv, sessionCt));
3923
3975
  const skRawForWrap = new Uint8Array(await subtle().exportKey("raw", sk));
3924
3976
  if (isHybridScheme(partner.algorithm)) {
3925
- const { cipherText: kemCt, sharedSecret: sharedSecret2 } = ml_kem768_x25519.encapsulate(b64ToBytes3(partner.public_key_b64));
3977
+ const { cipherText: kemCt, sharedSecret: sharedSecret2 } = ml_kem768_x25519.encapsulate(b64ToBytes4(partner.public_key_b64));
3926
3978
  const wrapSalt2 = globalThis.crypto.getRandomValues(new Uint8Array(WRAP_SALT_LENGTH));
3927
3979
  const wrapKeyRaw2 = await subtle().deriveBits(
3928
3980
  { name: "HKDF", hash: "SHA-256", salt: wrapSalt2, info: sessionWrapInfoPq(partner.partner_id) },
@@ -3949,7 +4001,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
3949
4001
  };
3950
4002
  }
3951
4003
  if (isRsaScheme(partner.algorithm)) {
3952
- const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes3(partner.public_key_b64));
4004
+ const partnerRsaPub = await importRsaOaepPublicKey(b64ToBytes4(partner.public_key_b64));
3953
4005
  const rsaWrapped = new Uint8Array(
3954
4006
  await subtle().encrypt({ name: "RSA-OAEP" }, partnerRsaPub, skRawForWrap)
3955
4007
  );
@@ -3966,7 +4018,7 @@ async function encryptEnvelopeForPartner(payload, partner) {
3966
4018
  }
3967
4019
  };
3968
4020
  }
3969
- const partnerPub = await importP256PublicKey(b64ToBytes3(partner.public_key_b64));
4021
+ const partnerPub = await importP256PublicKey(b64ToBytes4(partner.public_key_b64));
3970
4022
  const ephemeral = await subtle().generateKey(
3971
4023
  { name: "ECDH", namedCurve: "P-256" },
3972
4024
  true,
@@ -4048,7 +4100,7 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expe
4048
4100
  throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
4049
4101
  }
4050
4102
  const kemCiphertext = b64UrlToBytes(share.epk);
4051
- const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(ml_kem768_x25519.decapsulate(kemCiphertext, b64ToBytes3(privateKeyB64)));
4103
+ const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(ml_kem768_x25519.decapsulate(kemCiphertext, b64ToBytes4(privateKeyB64)));
4052
4104
  if (ops && sharedSecret.byteLength !== 32) {
4053
4105
  throw new Error(
4054
4106
  `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; X-Wing decapsulation is 32 bytes with no KDF applied.`
@@ -4281,6 +4333,12 @@ export {
4281
4333
  rootKeyIdFromSpkiB64,
4282
4334
  verifyPartnerKeyAttestation,
4283
4335
  verifyPartnerKeyAttestationWithRoots,
4336
+ PINNED_REGISTRY_ROOTS,
4337
+ __setPinnedRegistryRootsForTests,
4338
+ pinnedRegistryRoots,
4339
+ spkiSha256HexFromB64,
4340
+ rootIsPinned,
4341
+ unpinnedRootIds,
4284
4342
  REGISTRY_HEAD_V1,
4285
4343
  REGISTRY_HEAD_V2,
4286
4344
  REGISTRY_HEAD_ALG,
@@ -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-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-RBLFVBGY.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}`);
@@ -1617,6 +1846,8 @@ export {
1617
1846
  toOutboxTimestamp,
1618
1847
  fromOutboxTimestamp,
1619
1848
  createOutboxConsumer,
1849
+ parsePinnedRegistryRoots,
1850
+ checkRegistryHead,
1620
1851
  createSqlIdempotencyStore,
1621
1852
  verifySignature,
1622
1853
  verifyWithGrace,