@oneaddress/partner-sdk 1.8.0 → 2.1.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/dist/edge.js CHANGED
@@ -3364,6 +3364,70 @@ var init_safe_url = __esm({
3364
3364
  }
3365
3365
  });
3366
3366
 
3367
+ // ../crypto/src/endpoint-health.ts
3368
+ function classifyEndpointProbe(input) {
3369
+ const status = typeof input.httpStatus === "number" && Number.isFinite(input.httpStatus) ? input.httpStatus : null;
3370
+ if (status === null || status === 0) {
3371
+ const detail = input.error ? `: ${input.error}` : "";
3372
+ return {
3373
+ health: "unreachable",
3374
+ dispatchable: false,
3375
+ summary: `No response from the endpoint${detail}. Check the host is running and reachable.`
3376
+ };
3377
+ }
3378
+ if (status >= 200 && status < 300) {
3379
+ return {
3380
+ health: "healthy",
3381
+ dispatchable: true,
3382
+ summary: `Receiver accepted a signed test request (HTTP ${status}).`
3383
+ };
3384
+ }
3385
+ if (status === 401 || status === 403) {
3386
+ return {
3387
+ health: "auth",
3388
+ dispatchable: false,
3389
+ summary: `Receiver rejected our signature (HTTP ${status}). Check the signing secret matches on both sides.`
3390
+ };
3391
+ }
3392
+ if (MISSING_STATUSES.has(status)) {
3393
+ return {
3394
+ health: "missing",
3395
+ dispatchable: false,
3396
+ summary: `Host answered but no receiver is listening at this path (HTTP ${status}). A stopped tunnel or a stale URL looks exactly like this.`
3397
+ };
3398
+ }
3399
+ if (status === 429) {
3400
+ return {
3401
+ health: "throttled",
3402
+ dispatchable: false,
3403
+ summary: `Receiver is up and rate-limiting us (HTTP 429). Back off and retry, or raise the ceiling; nothing is wrong with the URL.`
3404
+ };
3405
+ }
3406
+ if (status >= 500) {
3407
+ return {
3408
+ health: "degraded",
3409
+ dispatchable: false,
3410
+ summary: `Receiver is present but erroring (HTTP ${status}).`
3411
+ };
3412
+ }
3413
+ return {
3414
+ health: "rejected",
3415
+ dispatchable: false,
3416
+ summary: `Receiver refused the request (HTTP ${status}).`
3417
+ };
3418
+ }
3419
+ function countsAsFailure(verdict) {
3420
+ return !verdict.dispatchable;
3421
+ }
3422
+ var ENDPOINT_FAILURE_THRESHOLD, MISSING_STATUSES;
3423
+ var init_endpoint_health = __esm({
3424
+ "../crypto/src/endpoint-health.ts"() {
3425
+ "use strict";
3426
+ ENDPOINT_FAILURE_THRESHOLD = 3;
3427
+ MISSING_STATUSES = /* @__PURE__ */ new Set([404, 405, 410]);
3428
+ }
3429
+ });
3430
+
3367
3431
  // ../crypto/src/partner-key-attestation.ts
3368
3432
  function assertNoDelimiter(field, value) {
3369
3433
  if (typeof value !== "string" || value.length === 0) {
@@ -3465,6 +3529,9 @@ function assertMapSafe(field, value) {
3465
3529
  }
3466
3530
  }
3467
3531
  function buildRegistryHeadStatement(payload) {
3532
+ if (!KNOWN_VERSIONS.has(payload.version)) {
3533
+ throw new Error(`[registry-head] unknown head version: ${String(payload.version)}`);
3534
+ }
3468
3535
  assertNoLineBreak("issued_at", payload.issued_at);
3469
3536
  assertNoLineBreak("expires_at", payload.expires_at);
3470
3537
  assertMapSafe("root_key_id", payload.root_key_id);
@@ -3481,14 +3548,42 @@ function buildRegistryHeadStatement(payload) {
3481
3548
  }
3482
3549
  seen.add(partnerId);
3483
3550
  }
3484
- return [
3485
- REGISTRY_HEAD_V1,
3551
+ const lines = [
3552
+ payload.version,
3486
3553
  `issued_at:${payload.issued_at}`,
3487
3554
  `expires_at:${payload.expires_at}`,
3488
3555
  `root_key_id:${payload.root_key_id}`,
3489
3556
  `heads:${entries.length}`,
3490
3557
  ...entries.map(([partnerId, keyId]) => `${partnerId}:${keyId}`)
3491
- ].join("\n");
3558
+ ];
3559
+ if (payload.version === REGISTRY_HEAD_V1) {
3560
+ if (payload.staged && Object.keys(payload.staged).length > 0) {
3561
+ throw new Error("[registry-head] v1 statement cannot carry staged entries");
3562
+ }
3563
+ return lines.join("\n");
3564
+ }
3565
+ const stagedEntries = Object.entries(payload.staged ?? {}).map(([partnerId, entry]) => {
3566
+ assertMapSafe("staged partner_id", partnerId);
3567
+ assertMapSafe("staged key_id", entry?.key_id);
3568
+ assertMapSafe("staged key_sha256", entry?.key_sha256);
3569
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) {
3570
+ throw new Error(`[registry-head] staged key_sha256 must be 64 hex chars: ${partnerId}`);
3571
+ }
3572
+ return [partnerId.toLowerCase(), entry.key_id.toLowerCase(), entry.key_sha256.toLowerCase()];
3573
+ });
3574
+ stagedEntries.sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
3575
+ const stagedSeen = /* @__PURE__ */ new Set();
3576
+ for (const [partnerId] of stagedEntries) {
3577
+ if (stagedSeen.has(partnerId)) {
3578
+ throw new Error(`[registry-head] duplicate partner_id in staged: ${partnerId}`);
3579
+ }
3580
+ stagedSeen.add(partnerId);
3581
+ }
3582
+ lines.push(`staged:${stagedEntries.length}`);
3583
+ for (const [partnerId, keyId, digest] of stagedEntries) {
3584
+ lines.push(`${partnerId}:${keyId}:${digest}`);
3585
+ }
3586
+ return lines.join("\n");
3492
3587
  }
3493
3588
  function b64ToBytes2(b64) {
3494
3589
  const normalised = b64.replace(/-/g, "+").replace(/_/g, "/");
@@ -3509,7 +3604,7 @@ function hexToBytes4(hex) {
3509
3604
  }
3510
3605
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
3511
3606
  try {
3512
- if (doc?.version !== REGISTRY_HEAD_V1) return "malformed";
3607
+ if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
3513
3608
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
3514
3609
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
3515
3610
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
@@ -3524,7 +3619,14 @@ async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date())
3524
3619
  issued_at: doc.issued_at,
3525
3620
  expires_at: doc.expires_at,
3526
3621
  root_key_id: doc.root_key_id,
3527
- heads: doc.heads
3622
+ heads: doc.heads,
3623
+ // Passed through rather than dropped: the staged map is part of what the
3624
+ // root signed on a v2 head, so omitting it here would rebuild different
3625
+ // bytes and report `bad-signature` on a perfectly good document. On a v1
3626
+ // head the builder REFUSES a non-empty map, which lands here as
3627
+ // `malformed` — the right answer for a document claiming staged keys its
3628
+ // signature does not cover.
3629
+ staged: doc.staged
3528
3630
  });
3529
3631
  const rootKey = await crypto.subtle.importKey(
3530
3632
  "spki",
@@ -3550,28 +3652,354 @@ function headNamesKey(doc, partnerId, keyId) {
3550
3652
  const named = doc.heads?.[partnerId.toLowerCase()];
3551
3653
  return typeof named === "string" && named.toLowerCase() === keyId.toLowerCase();
3552
3654
  }
3553
- var REGISTRY_HEAD_V1, REGISTRY_HEAD_ALG;
3655
+ function headNamesPartner(doc, partnerId) {
3656
+ return typeof doc.heads?.[partnerId.toLowerCase()] === "string";
3657
+ }
3658
+ async function partnerKeyFingerprint(publicKeyB64) {
3659
+ const digest = await crypto.subtle.digest(
3660
+ "SHA-256",
3661
+ b64ToBytes2(publicKeyB64)
3662
+ );
3663
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
3664
+ }
3665
+ async function headNamesStagedKey(doc, partnerId, keyId, publicKeyB64) {
3666
+ try {
3667
+ const entry = doc.staged?.[partnerId.toLowerCase()];
3668
+ if (!entry || typeof entry.key_id !== "string" || typeof entry.key_sha256 !== "string") return false;
3669
+ if (entry.key_id.toLowerCase() !== keyId.toLowerCase()) return false;
3670
+ if (!/^[0-9a-f]{64}$/i.test(entry.key_sha256)) return false;
3671
+ return await partnerKeyFingerprint(publicKeyB64) === entry.key_sha256.toLowerCase();
3672
+ } catch {
3673
+ return false;
3674
+ }
3675
+ }
3676
+ var REGISTRY_HEAD_V1, REGISTRY_HEAD_V2, KNOWN_VERSIONS, REGISTRY_HEAD_ALG;
3554
3677
  var init_registry_head = __esm({
3555
3678
  "../crypto/src/registry-head.ts"() {
3556
3679
  "use strict";
3557
3680
  REGISTRY_HEAD_V1 = "oneaddress-partner-key-registry-head:v1";
3681
+ REGISTRY_HEAD_V2 = "oneaddress-partner-key-registry-head:v2";
3682
+ KNOWN_VERSIONS = /* @__PURE__ */ new Set([REGISTRY_HEAD_V1, REGISTRY_HEAD_V2]);
3558
3683
  REGISTRY_HEAD_ALG = "ECDSA-P256";
3559
3684
  }
3560
3685
  });
3561
3686
 
3687
+ // ../crypto/src/verify-partner-keys.ts
3688
+ async function saysRootNotConfigured(res) {
3689
+ if (res.status !== 503) return false;
3690
+ try {
3691
+ const body = await res.json();
3692
+ return typeof body.error === "string" && body.error.includes("root not configured");
3693
+ } catch {
3694
+ return false;
3695
+ }
3696
+ }
3697
+ async function outcomeFor(partnerId, key, reg, bound) {
3698
+ if (!reg.head) return "head-unusable";
3699
+ if (!key.key_signature || !key.root_key_id) {
3700
+ if (!key.countersignature_exempt) return "unsigned";
3701
+ if (headNamesPartner(reg.head, partnerId)) return "exempt-in-head";
3702
+ return bound.has(partnerId) ? "exempt" : "exempt-unbound";
3703
+ }
3704
+ const attested = await verifyPartnerKeyAttestationWithRoots(
3705
+ {
3706
+ partnerId,
3707
+ keyId: key.key_id,
3708
+ algorithm: key.algorithm,
3709
+ publicKeyB64: key.public_key_b64
3710
+ },
3711
+ key.key_signature,
3712
+ key.root_key_id,
3713
+ reg.roots
3714
+ );
3715
+ if (!attested) return "bad-attestation";
3716
+ return headNamesKey(reg.head, partnerId, key.key_id) ? "ok" : "not-in-head";
3717
+ }
3718
+ async function crossoverOutcomeFor(partnerId, crossover, reg) {
3719
+ if (!reg.head) return "head-unusable";
3720
+ return await headNamesStagedKey(reg.head, partnerId, crossover.key_id, crossover.public_key_b64) ? "ok" : "not-authorised";
3721
+ }
3722
+ function createPartnerKeyVerifier(env = {}) {
3723
+ const baseUrl = env.baseUrl ?? "";
3724
+ const report = env.report ?? (() => {
3725
+ });
3726
+ let registryPromise = null;
3727
+ function worthCaching(load) {
3728
+ return load.ok && load.registry.head !== null;
3729
+ }
3730
+ async function loadRegistry() {
3731
+ try {
3732
+ const [rootsRes, headRes] = await Promise.all([
3733
+ fetch(baseUrl + "/.well-known/oneaddress-key-registry.json", { cache: "no-cache" }),
3734
+ fetch(baseUrl + "/.well-known/oneaddress-key-registry-head.json", { cache: "no-cache" })
3735
+ ]);
3736
+ if (!rootsRes.ok) {
3737
+ const configured = await saysRootNotConfigured(rootsRes);
3738
+ return {
3739
+ ok: false,
3740
+ failure: {
3741
+ reason: configured ? "roots-not-configured" : "roots-http",
3742
+ status: rootsRes.status
3743
+ }
3744
+ };
3745
+ }
3746
+ let roots;
3747
+ try {
3748
+ const rootsBody = await rootsRes.json();
3749
+ roots = rootsBody.keys ?? [];
3750
+ } catch {
3751
+ return { ok: false, failure: { reason: "roots-unreadable", status: rootsRes.status } };
3752
+ }
3753
+ if (roots.length === 0) {
3754
+ return { ok: false, failure: { reason: "roots-empty", status: rootsRes.status } };
3755
+ }
3756
+ let head = null;
3757
+ let headVerdict = "absent";
3758
+ if (headRes.ok) {
3759
+ head = await headRes.json();
3760
+ headVerdict = await verifyRegistryHead(head, roots);
3761
+ if (headVerdict !== "ok" && headVerdict !== "expired") head = null;
3762
+ }
3763
+ return { ok: true, registry: { roots, head, headVerdict } };
3764
+ } catch {
3765
+ return { ok: false, failure: { reason: "fetch-failed" } };
3766
+ }
3767
+ }
3768
+ async function verifyActivePartnerKeys(keys, context) {
3769
+ try {
3770
+ const pending = registryPromise ?? (registryPromise = loadRegistry());
3771
+ const load = await pending;
3772
+ if (!worthCaching(load)) registryPromise = null;
3773
+ if (!load.ok) {
3774
+ report(context, { registry: "unavailable", enforced: false, ...load.failure });
3775
+ return { blocked: {}, crossoverBlocked: {} };
3776
+ }
3777
+ const reg = load.registry;
3778
+ let bound = EMPTY_BOUND;
3779
+ if (env.bindSenderHeldKeys) {
3780
+ try {
3781
+ bound = await env.bindSenderHeldKeys(keys);
3782
+ } catch {
3783
+ report(context, { binder: "threw", enforced: true });
3784
+ }
3785
+ }
3786
+ const tally = {
3787
+ "ok": [],
3788
+ "exempt": [],
3789
+ "exempt-in-head": [],
3790
+ "exempt-unbound": [],
3791
+ "unsigned": [],
3792
+ "bad-attestation": [],
3793
+ "not-in-head": [],
3794
+ "head-unusable": [],
3795
+ "error": []
3796
+ };
3797
+ const blocked = {};
3798
+ const crossoverBlocked = {};
3799
+ const crossoverTally = { "ok": [], "not-authorised": [], "head-unusable": [], "error": [] };
3800
+ for (const [partnerId, key] of Object.entries(keys)) {
3801
+ let outcome;
3802
+ try {
3803
+ outcome = await outcomeFor(partnerId, key, reg, bound);
3804
+ } catch {
3805
+ outcome = "error";
3806
+ }
3807
+ tally[outcome].push(partnerId);
3808
+ if (!ACCEPTABLE.has(outcome)) blocked[partnerId] = outcome;
3809
+ if (!key?.crossover) continue;
3810
+ let xo;
3811
+ try {
3812
+ xo = await crossoverOutcomeFor(partnerId, key.crossover, reg);
3813
+ } catch {
3814
+ xo = "error";
3815
+ }
3816
+ crossoverTally[xo].push(partnerId);
3817
+ if (xo !== "ok") crossoverBlocked[partnerId] = xo;
3818
+ }
3819
+ if (Object.keys(crossoverBlocked).length > 0) {
3820
+ const failedXo = Object.keys(crossoverTally).filter((o) => o !== "ok" && crossoverTally[o].length > 0);
3821
+ report(context, {
3822
+ headVerdict: reg.headVerdict,
3823
+ enforced: true,
3824
+ surface: "crossover",
3825
+ ...Object.fromEntries(failedXo.map((o) => [`crossover-${o}`, crossoverTally[o]]))
3826
+ });
3827
+ }
3828
+ if (Object.keys(blocked).length > 0) {
3829
+ const failed = Object.keys(tally).filter((o) => !ACCEPTABLE.has(o) && tally[o].length > 0);
3830
+ report(context, {
3831
+ headVerdict: reg.headVerdict,
3832
+ enforced: true,
3833
+ total: Object.keys(keys).length,
3834
+ ok: tally.ok.length,
3835
+ // Counted, not listed: an operator reading a real finding needs to know
3836
+ // how many keys were skipped as exempt, without the ids adding noise.
3837
+ exempt: tally.exempt.length,
3838
+ ...Object.fromEntries(failed.map((o) => [o, tally[o]]))
3839
+ });
3840
+ }
3841
+ return { blocked, crossoverBlocked };
3842
+ } catch {
3843
+ report(context, { registry: "verifier-error", enforced: false });
3844
+ return { blocked: {}, crossoverBlocked: {} };
3845
+ }
3846
+ }
3847
+ function __resetRegistryCacheForTests() {
3848
+ registryPromise = null;
3849
+ }
3850
+ return { verifyActivePartnerKeys, __resetRegistryCacheForTests };
3851
+ }
3852
+ var ACCEPTABLE, EMPTY_BOUND, PARTNER_KEY_REFUSED_MESSAGE;
3853
+ var init_verify_partner_keys = __esm({
3854
+ "../crypto/src/verify-partner-keys.ts"() {
3855
+ "use strict";
3856
+ init_partner_key_attestation();
3857
+ init_registry_head();
3858
+ ACCEPTABLE = /* @__PURE__ */ new Set(["ok", "exempt"]);
3859
+ EMPTY_BOUND = /* @__PURE__ */ new Set();
3860
+ PARTNER_KEY_REFUSED_MESSAGE = "Some services are temporarily unavailable and were not updated. Please try again in a moment.";
3861
+ }
3862
+ });
3863
+
3864
+ // ../crypto/src/sender-held-keys.ts
3865
+ function memorySenderHeldKeyStore() {
3866
+ const keys = /* @__PURE__ */ new Map();
3867
+ return {
3868
+ all: async () => [...keys.values()],
3869
+ put: async (key) => {
3870
+ keys.set(key.keyId, key);
3871
+ }
3872
+ };
3873
+ }
3874
+ function toB64(bytes) {
3875
+ let s = "";
3876
+ for (const b of bytes) s += String.fromCharCode(b);
3877
+ return btoa(s);
3878
+ }
3879
+ async function keyIdForPublicKey(spki) {
3880
+ const d = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", spki)).slice(0, 16);
3881
+ d[6] = d[6] & 15 | 128;
3882
+ d[8] = d[8] & 63 | 128;
3883
+ const h = [...d].map((b) => b.toString(16).padStart(2, "0")).join("");
3884
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
3885
+ }
3886
+ function createSenderHeldKeyBinder(storeFor) {
3887
+ let pending = null;
3888
+ async function mint() {
3889
+ if (typeof globalThis.crypto === "undefined" || !globalThis.crypto.subtle) return null;
3890
+ let store = storeFor();
3891
+ try {
3892
+ const existing = await store.all();
3893
+ if (existing.length > 0) {
3894
+ return [...existing].sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
3895
+ }
3896
+ } catch {
3897
+ store = memorySenderHeldKeyStore();
3898
+ }
3899
+ const pair = await globalThis.crypto.subtle.generateKey(
3900
+ { name: "ECDH", namedCurve: "P-256" },
3901
+ false,
3902
+ ["deriveBits"]
3903
+ );
3904
+ const spki = new Uint8Array(await globalThis.crypto.subtle.exportKey("spki", pair.publicKey));
3905
+ const key = {
3906
+ keyId: await keyIdForPublicKey(spki),
3907
+ publicKeyB64: toB64(spki),
3908
+ privateKey: pair.privateKey,
3909
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
3910
+ };
3911
+ try {
3912
+ await store.put(key);
3913
+ } catch {
3914
+ }
3915
+ return key;
3916
+ }
3917
+ function getOrCreate() {
3918
+ pending ??= mint().catch(() => {
3919
+ pending = null;
3920
+ return null;
3921
+ });
3922
+ return pending;
3923
+ }
3924
+ const bind = async (keys) => {
3925
+ const bound = /* @__PURE__ */ new Set();
3926
+ const flagged = Object.entries(keys).filter(([, k]) => k?.countersignature_exempt === true);
3927
+ if (flagged.length === 0) return bound;
3928
+ const own = await getOrCreate();
3929
+ if (!own) return bound;
3930
+ for (const [partnerId, k] of flagged) {
3931
+ k.key_id = own.keyId;
3932
+ k.public_key_b64 = own.publicKeyB64;
3933
+ k.algorithm = SENDER_HELD_KEY_ALGORITHM;
3934
+ k.key_signature = null;
3935
+ k.root_key_id = null;
3936
+ delete k.crossover;
3937
+ bound.add(partnerId);
3938
+ }
3939
+ return bound;
3940
+ };
3941
+ return Object.assign(bind, { getOrCreate });
3942
+ }
3943
+ async function openSealedWithSenderHeldKey(share, envelope, partnerId, store) {
3944
+ let keys;
3945
+ try {
3946
+ keys = await store.all();
3947
+ } catch {
3948
+ return { ok: false, reason: "no-key" };
3949
+ }
3950
+ const key = keys.find((k) => k.keyId === share.key_id);
3951
+ if (!key) return { ok: false, reason: "no-key" };
3952
+ try {
3953
+ const data = await decryptSession(share, envelope, {
3954
+ name: "this device",
3955
+ async deriveSharedSecret(epkSpki) {
3956
+ const epk = await globalThis.crypto.subtle.importKey(
3957
+ "spki",
3958
+ epkSpki,
3959
+ { name: "ECDH", namedCurve: "P-256" },
3960
+ false,
3961
+ []
3962
+ );
3963
+ return new Uint8Array(
3964
+ await globalThis.crypto.subtle.deriveBits({ name: "ECDH", public: epk }, key.privateKey, 256)
3965
+ );
3966
+ }
3967
+ }, partnerId);
3968
+ return { ok: true, data };
3969
+ } catch {
3970
+ return { ok: false, reason: "unreadable" };
3971
+ }
3972
+ }
3973
+ var SENDER_HELD_KEY_ALGORITHM;
3974
+ var init_sender_held_keys = __esm({
3975
+ "../crypto/src/sender-held-keys.ts"() {
3976
+ "use strict";
3977
+ init_src();
3978
+ SENDER_HELD_KEY_ALGORITHM = "ECDH-P256-AES-GCM-256";
3979
+ }
3980
+ });
3981
+
3562
3982
  // ../crypto/src/index.ts
3563
3983
  var src_exports = {};
3564
3984
  __export(src_exports, {
3565
3985
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
3986
+ ENDPOINT_FAILURE_THRESHOLD: () => ENDPOINT_FAILURE_THRESHOLD,
3566
3987
  PARTNER_KEY_ATTESTATION_ALG: () => PARTNER_KEY_ATTESTATION_ALG,
3567
3988
  PARTNER_KEY_ATTESTATION_V1: () => PARTNER_KEY_ATTESTATION_V1,
3989
+ PARTNER_KEY_REFUSED_MESSAGE: () => PARTNER_KEY_REFUSED_MESSAGE,
3568
3990
  REGISTRY_HEAD_ALG: () => REGISTRY_HEAD_ALG,
3569
3991
  REGISTRY_HEAD_V1: () => REGISTRY_HEAD_V1,
3992
+ REGISTRY_HEAD_V2: () => REGISTRY_HEAD_V2,
3993
+ SENDER_HELD_KEY_ALGORITHM: () => SENDER_HELD_KEY_ALGORITHM,
3570
3994
  buildPartnerKeyAttestation: () => buildPartnerKeyAttestation,
3571
3995
  buildRegistryHeadStatement: () => buildRegistryHeadStatement,
3996
+ classifyEndpointProbe: () => classifyEndpointProbe,
3572
3997
  cleanNameAliases: () => cleanNameAliases,
3573
3998
  computeBlindIndex: () => computeBlindIndex,
3574
3999
  computeCustomerBlindIndex: () => computeCustomerBlindIndex,
4000
+ countsAsFailure: () => countsAsFailure,
4001
+ createPartnerKeyVerifier: () => createPartnerKeyVerifier,
4002
+ createSenderHeldKeyBinder: () => createSenderHeldKeyBinder,
3575
4003
  decryptAddress: () => decryptAddress,
3576
4004
  decryptSession: () => decryptSession,
3577
4005
  encryptAddressForAll: () => encryptAddressForAll,
@@ -3583,12 +4011,18 @@ __export(src_exports, {
3583
4011
  generateHybridPartnerKeyPair: () => generateHybridPartnerKeyPair,
3584
4012
  generatePartnerKeyPair: () => generatePartnerKeyPair,
3585
4013
  headNamesKey: () => headNamesKey,
4014
+ headNamesPartner: () => headNamesPartner,
4015
+ headNamesStagedKey: () => headNamesStagedKey,
3586
4016
  isEmailLike: () => isEmailLike,
3587
4017
  isFreshTimestamp: () => isFreshTimestamp,
3588
4018
  isIpLiteralHost: () => isIpLiteralHost,
3589
4019
  isSafeWebhookUrl: () => isSafeWebhookUrl,
4020
+ keyIdForPublicKey: () => keyIdForPublicKey,
4021
+ memorySenderHeldKeyStore: () => memorySenderHeldKeyStore,
3590
4022
  normaliseAddress: () => normaliseAddress,
3591
4023
  normalizeForBlindIndex: () => normalizeForBlindIndex,
4024
+ openSealedWithSenderHeldKey: () => openSealedWithSenderHeldKey,
4025
+ partnerKeyFingerprint: () => partnerKeyFingerprint,
3592
4026
  rootKeyIdFromSpki: () => rootKeyIdFromSpki,
3593
4027
  rootKeyIdFromSpkiB64: () => rootKeyIdFromSpkiB64,
3594
4028
  signWebhookPayload: () => signWebhookPayload,
@@ -3972,21 +4406,21 @@ async function encryptSessionForAll(partners) {
3972
4406
  );
3973
4407
  return Object.fromEntries(results.map((r) => [r.partner_id, r]));
3974
4408
  }
3975
- async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
4409
+ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId, expectedAlg) {
3976
4410
  if (share.alg !== "ECDH-ES+HKDF-SHA256+A256GCM" && share.alg !== "RSA-OAEP-256+A256GCM" && share.alg !== "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3977
4411
  throw new Error(`decryptSession: unsupported alg ${share.alg}`);
3978
4412
  }
3979
4413
  if (share.v !== 2) {
3980
4414
  throw new Error(`decryptSession: unsupported share version ${share.v}`);
3981
4415
  }
4416
+ if (expectedAlg && share.alg !== expectedAlg) {
4417
+ throw new Error(
4418
+ `decryptSession: algorithm downgrade - the dispatch wraps SK_n as ${share.alg}, but this key is provisioned for ${expectedAlg}. Refusing rather than attempting a different wrap than the recipient chose.`
4419
+ );
4420
+ }
3982
4421
  const ops = typeof privateKeyB64 === "string" ? null : privateKeyB64;
3983
4422
  if (ops) {
3984
- if (share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM") {
3985
- throw new Error(
3986
- `decryptSession: key source "${ops.name}" performs private-key operations without releasing the key, which no KMS offers for ML-KEM. Use an exportable key source for post-quantum shares.`
3987
- );
3988
- }
3989
- const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : "deriveSharedSecret";
4423
+ const needed = share.alg === "RSA-OAEP-256+A256GCM" ? "decryptRsaOaep" : share.alg === "MLKEM768X25519+HKDF-SHA256+A256GCM" ? "decapsulateXWing" : "deriveSharedSecret";
3990
4424
  if (typeof ops[needed] !== "function") {
3991
4425
  throw new Error(
3992
4426
  `decryptSession: key source "${ops.name}" cannot do ${needed}, which ${share.alg} requires.`
@@ -3998,7 +4432,13 @@ async function decryptSession(share, envelopeB64, privateKeyB64, partnerId) {
3998
4432
  if (!share.epk) {
3999
4433
  throw new Error("decryptSession: hybrid share missing epk (KEM ciphertext)");
4000
4434
  }
4001
- const sharedSecret = XWing.decapsulate(b64UrlToBytes(share.epk), b64ToBytes3(privateKeyB64));
4435
+ const kemCiphertext = b64UrlToBytes(share.epk);
4436
+ const sharedSecret = ops ? toArrayBuffer(await ops.decapsulateXWing(kemCiphertext)) : toArrayBuffer(XWing.decapsulate(kemCiphertext, b64ToBytes3(privateKeyB64)));
4437
+ if (ops && sharedSecret.byteLength !== 32) {
4438
+ throw new Error(
4439
+ `decryptSession: key source "${ops.name}" returned a ${sharedSecret.byteLength}-byte shared secret; X-Wing decapsulation is 32 bytes with no KDF applied.`
4440
+ );
4441
+ }
4002
4442
  const wrappedBytes = b64UrlToBytes(share.wrapped_key);
4003
4443
  if (wrappedBytes.length < WRAP_SALT_LENGTH + WRAP_IV_LENGTH + 16) {
4004
4444
  throw new Error("decryptSession: wrapped_key too short");
@@ -4213,9 +4653,20 @@ var init_src = __esm({
4213
4653
  init_hybrid();
4214
4654
  init_replay_window();
4215
4655
  init_safe_url();
4656
+ init_endpoint_health();
4216
4657
  init_partner_key_attestation();
4217
4658
  init_registry_head();
4218
- subtle = () => globalThis.crypto.subtle;
4659
+ init_verify_partner_keys();
4660
+ init_sender_held_keys();
4661
+ subtle = () => {
4662
+ const webcrypto = globalThis.crypto;
4663
+ if (!webcrypto?.subtle) {
4664
+ throw new Error(
4665
+ "Web Crypto is unavailable in this runtime, so no encryption or key operation can run. In Node this needs version 19 or later, where globalThis.crypto is enabled by default (Node 18 has it behind --experimental-global-webcrypto, and is itself end-of-life). Check with `node -v` and upgrade, or re-run with NODE_OPTIONS=--experimental-global-webcrypto as a one-off."
4666
+ );
4667
+ }
4668
+ return webcrypto.subtle;
4669
+ };
4219
4670
  AU_STATE_FULL = {
4220
4671
  "new south wales": "NSW",
4221
4672
  "victoria": "VIC",
@@ -4281,6 +4732,45 @@ init_src();
4281
4732
  var CURRENT_VERSION = "2026.1";
4282
4733
  var SUPPORTED_VERSIONS = ["2026.1"];
4283
4734
 
4735
+ // ../protocol/src/d5-body.ts
4736
+ var D5_BODY_ALWAYS = [
4737
+ "event",
4738
+ "id_verification",
4739
+ "key_share_expiry",
4740
+ "oneaddress_version",
4741
+ "partner_id",
4742
+ "session_envelope",
4743
+ "session_key_share",
4744
+ "stripe_session_id",
4745
+ "timestamp",
4746
+ "update_id",
4747
+ "user_id"
4748
+ ];
4749
+ var D5_BODY_CONDITIONAL = {
4750
+ /**
4751
+ * The signed Letter of Authority, sealed to the same key_id as the session.
4752
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
4753
+ * live partner receives. Omitted best-effort when no key is available, which
4754
+ * is a state a live partner is never in.
4755
+ */
4756
+ loa_encrypted: "partner has a usable encryption key",
4757
+ /**
4758
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
4759
+ * copy of one update carries the same id so a receiver holding more than one
4760
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
4761
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
4762
+ */
4763
+ id: "key-crossover copy only",
4764
+ /** The sibling marker naming the other key_ids this update was sealed to. */
4765
+ crossover_key_ids: "key-crossover copy only"
4766
+ };
4767
+ var D5_BODY_DRILL_ONLY = ["conformance"];
4768
+ var D5_BODY_ALL_ALLOWED = [
4769
+ ...D5_BODY_ALWAYS,
4770
+ ...Object.keys(D5_BODY_CONDITIONAL),
4771
+ ...D5_BODY_DRILL_ONLY
4772
+ ];
4773
+
4284
4774
  // src/index.ts
4285
4775
  init_src();
4286
4776
  init_src();
@@ -4353,7 +4843,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
4353
4843
  function base64urlToBuffer(b64) {
4354
4844
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4355
4845
  }
4356
- function pemToBase64(pem) {
4846
+ function pemToBase64(pemRaw) {
4847
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
4357
4848
  const begin = pem.indexOf("-----BEGIN");
4358
4849
  if (begin === -1) return pem.replace(/\s/g, "");
4359
4850
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -4413,13 +4904,14 @@ async function decryptAddress2(payload, privateKeyPem, partnerId) {
4413
4904
  );
4414
4905
  return JSON.parse(new TextDecoder().decode(plaintext));
4415
4906
  }
4416
- async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId) {
4907
+ async function decryptSession2(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
4417
4908
  const { decryptSession: decryptSessionCrypto } = await Promise.resolve().then(() => (init_src(), src_exports));
4418
4909
  return decryptSessionCrypto(
4419
4910
  share,
4420
4911
  envelopeB64,
4421
4912
  typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
4422
- partnerId
4913
+ partnerId,
4914
+ expectedAlg
4423
4915
  );
4424
4916
  }
4425
4917
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
@@ -4481,6 +4973,65 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
4481
4973
  );
4482
4974
  }
4483
4975
  var OA_APP_BASE_URL = "https://oneaddress.io";
4976
+ async function confirmUpdate(opts2) {
4977
+ const {
4978
+ partnerId,
4979
+ secret,
4980
+ dispatchId,
4981
+ status = "confirmed",
4982
+ note,
4983
+ loaRef,
4984
+ memberName,
4985
+ appBaseUrl = OA_APP_BASE_URL,
4986
+ fetchImpl = fetch
4987
+ } = opts2;
4988
+ if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
4989
+ if (!secret) return { ok: false, status: 0, error: "secret is required" };
4990
+ const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
4991
+ if (!Number.isInteger(id) || id <= 0) {
4992
+ return {
4993
+ ok: false,
4994
+ status: 0,
4995
+ error: `dispatchId must be a positive integer, received ${JSON.stringify(dispatchId)} \u2014 it comes from the X-OneAddress-Dispatch header on the webhook you are confirming`
4996
+ };
4997
+ }
4998
+ const body = JSON.stringify({
4999
+ dispatch_id: id,
5000
+ partner_id: partnerId,
5001
+ status,
5002
+ ...note !== void 0 ? { note } : {},
5003
+ ...loaRef !== void 0 ? { loa_ref: loaRef } : {},
5004
+ ...memberName !== void 0 ? { member_name: memberName } : {}
5005
+ });
5006
+ const timestamp = String(Math.floor(Date.now() / 1e3));
5007
+ const signature = import_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
5008
+ let base = appBaseUrl;
5009
+ while (base.endsWith("/")) base = base.slice(0, -1);
5010
+ let res;
5011
+ try {
5012
+ res = await fetchImpl(`${base}/api/confirm`, {
5013
+ method: "POST",
5014
+ headers: {
5015
+ "Content-Type": "application/json",
5016
+ "Authorization": `Bearer ${secret}`,
5017
+ "X-OneAddress-Timestamp": timestamp,
5018
+ "X-OneAddress-Signature": signature
5019
+ },
5020
+ // The SAME string that was signed. Not an object, and not re-stringified.
5021
+ body
5022
+ });
5023
+ } catch (err) {
5024
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
5025
+ }
5026
+ if (res.ok) return { ok: true, status: res.status };
5027
+ let error;
5028
+ try {
5029
+ const parsed = await res.json();
5030
+ if (typeof parsed?.error === "string") error = parsed.error;
5031
+ } catch {
5032
+ }
5033
+ return { ok: false, status: res.status, error };
5034
+ }
4484
5035
  function allowedLoaHosts() {
4485
5036
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
4486
5037
  if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
@@ -4501,6 +5052,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
4501
5052
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
4502
5053
  );
4503
5054
  }
5055
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
5056
+ if (parsedBase.protocol !== "https:" && !loopback) {
5057
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
5058
+ }
4504
5059
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
4505
5060
  const res = await fetch(url);
4506
5061
  if (!res.ok) {
@@ -4577,12 +5132,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
4577
5132
  return false;
4578
5133
  }
4579
5134
  }
4580
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
5135
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
4581
5136
  const data = await decryptSession2(
4582
5137
  loaEncrypted.session_key_share,
4583
5138
  loaEncrypted.session_envelope,
4584
5139
  privateKeyPem,
4585
- partnerId
5140
+ partnerId,
5141
+ expectedAlg
4586
5142
  );
4587
5143
  return data;
4588
5144
  }
@@ -4664,12 +5220,32 @@ function compareAddresses(a, b) {
4664
5220
  if (aCountry && bCountry && aCountry !== bCountry) return false;
4665
5221
  return true;
4666
5222
  }
5223
+ function isAllowedCallbackHost(raw, extraHosts) {
5224
+ let host;
5225
+ try {
5226
+ const u = new URL(raw);
5227
+ if (u.protocol !== "https:") return false;
5228
+ host = u.hostname.toLowerCase();
5229
+ } catch {
5230
+ return false;
5231
+ }
5232
+ if (host === "oneaddress.io" || host.endsWith(".oneaddress.io")) return true;
5233
+ const envRaw = typeof process !== "undefined" ? process.env?.OA_CALLBACK_HOST_ALLOWLIST ?? "" : "";
5234
+ const allowed = [
5235
+ ...envRaw.split(",").map((h) => h.trim().toLowerCase()),
5236
+ ...(extraHosts ?? []).map((h) => h.trim().toLowerCase())
5237
+ ].filter(Boolean);
5238
+ return allowed.includes(host);
5239
+ }
4667
5240
  async function sendVerifyResult(params) {
4668
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
5241
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
4669
5242
  const safe = isSafeWebhookUrl(callbackUrl);
4670
5243
  if (!safe.ok) {
4671
5244
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
4672
5245
  }
5246
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
5247
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
5248
+ }
4673
5249
  const res = await fetch(callbackUrl, {
4674
5250
  method: "POST",
4675
5251
  headers: { "Content-Type": "application/json" },
@@ -4686,33 +5262,155 @@ async function sendVerifyResult(params) {
4686
5262
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
4687
5263
  }
4688
5264
  }
4689
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
5265
+ var UPDATE_TYPE_ORDER = ["address", "phone", "email"];
5266
+ function normaliseAcceptedUpdateTypes(raw) {
5267
+ const kept = new Set(Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : []);
5268
+ return UPDATE_TYPE_ORDER.filter((t) => t === "address" || kept.has(t));
5269
+ }
5270
+ function readUpdateTypes(raw) {
5271
+ if (raw === void 0 || raw === null) return ["address"];
5272
+ if (!Array.isArray(raw)) return null;
5273
+ if (raw.length === 0) return ["address"];
5274
+ const out = [];
5275
+ for (const v of raw) {
5276
+ if (typeof v !== "string" || !UPDATE_TYPE_ORDER.includes(v)) return null;
5277
+ if (!out.includes(v)) out.push(v);
5278
+ }
5279
+ return out;
5280
+ }
5281
+ var InvalidUpdateTypesError = class extends Error {
5282
+ constructor(raw) {
5283
+ super("[OneAddress SDK] update_types names a kind this build does not know");
5284
+ this.raw = raw;
5285
+ this.name = "InvalidUpdateTypesError";
5286
+ }
5287
+ };
5288
+ function requireContactValue(kind, value) {
5289
+ if (typeof value !== "string" || value === "") {
5290
+ throw new Error(
5291
+ `[OneAddress SDK] Decrypted envelope declares update_types "${kind}" but carries no new_${kind}. This may indicate a decryption error or a schema change. Update @oneaddress/partner-sdk.`
5292
+ );
5293
+ }
5294
+ return value;
5295
+ }
5296
+ var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
4690
5297
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
5298
+ var warnedConsentUnverified = false;
5299
+ var warnedNoIdempotencyStore = false;
5300
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
5301
+ var XWING_SEED_BYTES = 32;
5302
+ function assertUsablePrivateKey(privateKeyPem) {
5303
+ if (typeof privateKeyPem !== "string") {
5304
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
5305
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
5306
+ }
5307
+ return;
5308
+ }
5309
+ if (privateKeyPem.trim() === "") {
5310
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
5311
+ }
5312
+ const der = pemToBuffer(privateKeyPem);
5313
+ if (der.length === XWING_SEED_BYTES) return;
5314
+ try {
5315
+ import_crypto.default.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
5316
+ } catch (err) {
5317
+ const refused = new Error(
5318
+ `[OneAddress SDK] privateKeyPem does not import as a PKCS#8 private key (${err instanceof Error ? err.message : String(err)}). Paste the whole key including the BEGIN/END lines; a key stored as one line with literal \\n sequences is accepted, a truncated one is not.`
5319
+ );
5320
+ refused.cause = err;
5321
+ throw refused;
5322
+ }
5323
+ }
5324
+ function requirePemFor(purpose, key) {
5325
+ if (typeof key === "string") return key;
5326
+ throw new Error(
5327
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
5328
+ );
5329
+ }
5330
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
5331
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
5332
+ if (loa.update_uid !== envelopeUpdateUid) {
5333
+ throw new Error(
5334
+ "[OneAddress SDK] D5 LOA is for a different update than the envelope it arrived with (update_uid mismatch); refusing rather than applying an address under someone else's consent"
5335
+ );
5336
+ }
5337
+ }
4691
5338
  function createOneAddressHandler(options) {
4692
5339
  const {
4693
5340
  webhookSecret,
4694
5341
  previousWebhookSecret,
4695
5342
  webhookSecretGraceUntil,
4696
5343
  privateKeyPem,
5344
+ expectedAlg,
5345
+ keyId,
4697
5346
  loaPublicKeyPem,
5347
+ requireLoa = Boolean(loaPublicKeyPem),
5348
+ confirm,
4698
5349
  onUpdate,
4699
5350
  onVerify,
4700
5351
  onAccountVerify,
4701
5352
  onTest,
4702
5353
  timestampToleranceSecs = 300,
4703
- idempotencyStore
5354
+ idempotencyStore,
5355
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
5356
+ allowedCallbackHosts
4704
5357
  } = options;
5358
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
5359
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
5360
+ }
5361
+ assertUsablePrivateKey(privateKeyPem);
5362
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
5363
+ throw new Error(
5364
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
5365
+ );
5366
+ }
5367
+ if (webhookSecretGraceUntil !== void 0) {
5368
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
5369
+ if (Number.isNaN(until)) {
5370
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
5371
+ }
5372
+ }
5373
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
5374
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
5375
+ }
5376
+ function enforceLoaPresence(body) {
5377
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
5378
+ if (present) return;
5379
+ if (requireLoa) {
5380
+ throw new Error(
5381
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
5382
+ );
5383
+ }
5384
+ if (!warnedConsentUnverified) {
5385
+ warnedConsentUnverified = true;
5386
+ console.warn(
5387
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5388
+ "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Set loaPublicKeyPem (which turns requireLoa on) to refuse such dispatches. Logged once per process."
5389
+ );
5390
+ }
5391
+ }
5392
+ const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
5393
+ function declared(status, payload) {
5394
+ return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
5395
+ status,
5396
+ headers: { "Content-Type": "application/json" }
5397
+ });
5398
+ }
4705
5399
  async function buildD5Pieces(body, partnerId) {
4706
5400
  const share = body.session_key_share;
4707
- const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId);
4708
- const address = validateAddress({
5401
+ const data = await decryptSession2(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
5402
+ const updateTypes = readUpdateTypes(data.update_types);
5403
+ if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
5404
+ const address = updateTypes.includes("address") ? validateAddress({
4709
5405
  street: data.new_address?.street,
4710
5406
  suburb: data.new_address?.suburb,
4711
5407
  state: data.new_address?.state,
4712
5408
  postcode: data.new_address?.postcode,
4713
5409
  country: data.new_address?.country,
4714
5410
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
4715
- });
5411
+ }) : void 0;
5412
+ const newPhone = updateTypes.includes("phone") ? requireContactValue("phone", data.new_phone) : void 0;
5413
+ const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
4716
5414
  const customer = {
4717
5415
  email: "",
4718
5416
  name: data.verified_name ?? "",
@@ -4725,19 +5423,29 @@ function createOneAddressHandler(options) {
4725
5423
  loa = await decryptLoaEncrypted(
4726
5424
  body.loa_encrypted,
4727
5425
  privateKeyPem,
4728
- partnerId
5426
+ partnerId,
5427
+ expectedAlg
4729
5428
  );
4730
5429
  loa_ref = d5LoaRef(loa);
4731
5430
  if (loaPublicKeyPem) {
4732
5431
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
4733
5432
  if (!valid) throw new Error("D5 LOA signature verification failed");
4734
5433
  }
5434
+ assertLoaBoundToEnvelope(loa, data.update_uid);
4735
5435
  }
4736
- return { address, customer, loa, loa_ref, raw: data };
5436
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
4737
5437
  }
4738
5438
  function isD5Body(body) {
4739
5439
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
4740
5440
  }
5441
+ function isCrossoverSiblingToSkip(body) {
5442
+ if (!keyId || !isD5Body(body)) return false;
5443
+ const share = body.session_key_share;
5444
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
5445
+ if (!shareKeyId || shareKeyId === keyId) return false;
5446
+ const siblings = body.crossover_key_ids;
5447
+ return Array.isArray(siblings) && siblings.includes(keyId);
5448
+ }
4741
5449
  return async function handler(req) {
4742
5450
  const rawBody = await req.text();
4743
5451
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -4756,7 +5464,11 @@ function createOneAddressHandler(options) {
4756
5464
  }
4757
5465
  let body;
4758
5466
  try {
4759
- body = JSON.parse(rawBody);
5467
+ const parsed = JSON.parse(rawBody);
5468
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
5469
+ throw new TypeError("body is not a JSON object");
5470
+ }
5471
+ body = parsed;
4760
5472
  } catch {
4761
5473
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
4762
5474
  status: 400,
@@ -4773,51 +5485,86 @@ function createOneAddressHandler(options) {
4773
5485
  const partnerId = body.partner_id ?? "";
4774
5486
  const tsNum = Number(tsHeader);
4775
5487
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
5488
+ if (isCrossoverSiblingToSkip(body)) {
5489
+ return declared(200, { ok: true, skipped: true, crossover: true });
5490
+ }
4776
5491
  if (dispatchId) {
4777
5492
  if (!idempotencyStore) {
4778
- if (process.env.NODE_ENV === "test") {
5493
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
5494
+ if (nodeEnv === "test") {
4779
5495
  throw new Error(
4780
5496
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
4781
5497
  );
4782
5498
  }
5499
+ if (!warnedNoIdempotencyStore) {
5500
+ warnedNoIdempotencyStore = true;
5501
+ console.warn(
5502
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
5503
+ "[OneAddress SDK] a dispatch arrived with X-OneAddress-Dispatch and no idempotencyStore is wired, so a retried delivery will be processed again. Pass idempotencyStore: createSqlIdempotencyStore({ query }) to createOneAddressHandler. Logged once per process."
5504
+ );
5505
+ }
4783
5506
  } else if (idempotencyStore.claim) {
4784
5507
  const claim = await idempotencyStore.claim(dispatchId);
4785
5508
  if (claim === "duplicate") {
4786
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
4787
- status: 200,
4788
- headers: { "Content-Type": "application/json" }
4789
- });
5509
+ return declared(200, { ok: true, duplicate: true });
4790
5510
  }
4791
5511
  } else {
4792
5512
  const alreadySeen = await idempotencyStore.has(dispatchId);
4793
5513
  if (alreadySeen) {
4794
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
4795
- status: 200,
4796
- headers: { "Content-Type": "application/json" }
4797
- });
5514
+ return declared(200, { ok: true, duplicate: true });
4798
5515
  }
4799
5516
  }
4800
5517
  }
4801
5518
  try {
4802
- if (body.event === "address.updated") {
5519
+ if (body.event === "address.updated" || body.event === "contact.updated") {
5520
+ const wireEvent = body.event;
4803
5521
  let event;
5522
+ enforceLoaPresence(body);
4804
5523
  if (isD5Body(body)) {
4805
- const d5 = await buildD5Pieces(body, partnerId);
5524
+ let d5;
5525
+ try {
5526
+ d5 = await buildD5Pieces(body, partnerId);
5527
+ } catch (err) {
5528
+ if (err instanceof InvalidUpdateTypesError) {
5529
+ return declared(422, {
5530
+ error: "invalid_update_types",
5531
+ 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."
5532
+ });
5533
+ }
5534
+ throw err;
5535
+ }
5536
+ const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
5537
+ if (notAccepted.length > 0) {
5538
+ return declared(422, {
5539
+ error: "update_type_not_accepted",
5540
+ update_types: notAccepted,
5541
+ detail: "This receiver declares acceptedUpdateTypes " + JSON.stringify(acceptedUpdateTypes) + " and the dispatch carries " + JSON.stringify(d5.updateTypes) + ". Nothing was processed. Widen acceptedUpdateTypes once onUpdate stores the new kind, then re-run conformance."
5542
+ });
5543
+ }
4806
5544
  event = {
4807
- event: "address.updated",
5545
+ event: wireEvent,
4808
5546
  version: body.oneaddress_version ?? body.version ?? "2.0",
4809
5547
  id: body.id ?? "",
4810
5548
  timestamp: tsNum,
4811
5549
  partner_id: partnerId,
4812
5550
  dispatchId,
4813
5551
  customer: d5.customer,
5552
+ update_types: d5.updateTypes,
4814
5553
  address: d5.address,
5554
+ new_phone: d5.newPhone,
5555
+ new_email: d5.newEmail,
4815
5556
  loa: d5.loa,
4816
5557
  loa_ref: d5.loa_ref,
4817
5558
  id_verification: body.id_verification,
4818
5559
  raw: d5.raw
4819
5560
  };
4820
5561
  } else {
5562
+ if (wireEvent === "contact.updated") {
5563
+ return declared(400, {
5564
+ error: "missing_session_envelope",
5565
+ detail: "contact.updated requires session_envelope + session_key_share"
5566
+ });
5567
+ }
4821
5568
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
4822
5569
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
4823
5570
  status: 400,
@@ -4825,19 +5572,25 @@ function createOneAddressHandler(options) {
4825
5572
  });
4826
5573
  }
4827
5574
  const encrypted = body.address_encrypted;
4828
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5575
+ const rawAddress = await decryptAddress2(
5576
+ encrypted,
5577
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
5578
+ partnerId
5579
+ );
4829
5580
  let loa;
4830
5581
  let loa_ref;
4831
5582
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
4832
5583
  loa = await decryptLoaEncrypted(
4833
5584
  body.loa_encrypted,
4834
5585
  privateKeyPem,
4835
- partnerId
5586
+ partnerId,
5587
+ expectedAlg
4836
5588
  );
4837
5589
  loa_ref = d5LoaRef(loa);
4838
5590
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
4839
5591
  throw new Error("D5 LOA signature verification failed");
4840
5592
  }
5593
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
4841
5594
  }
4842
5595
  const customer = {
4843
5596
  email: "",
@@ -4853,6 +5606,8 @@ function createOneAddressHandler(options) {
4853
5606
  partner_id: partnerId,
4854
5607
  dispatchId,
4855
5608
  customer,
5609
+ // The legacy blob predates kinds and always carries an address.
5610
+ update_types: ["address"],
4856
5611
  address: validateAddress(rawAddress),
4857
5612
  loa,
4858
5613
  loa_ref,
@@ -4868,10 +5623,26 @@ function createOneAddressHandler(options) {
4868
5623
  // NOSONAR
4869
5624
  );
4870
5625
  }
4871
- return new Response(JSON.stringify({ ok: true, ...result }), {
4872
- status: 200,
4873
- headers: { "Content-Type": "application/json" }
4874
- });
5626
+ if (confirm && dispatchId) {
5627
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
5628
+ void confirmUpdate({
5629
+ partnerId: confirm.partnerId,
5630
+ secret: confirm.confirmSecret,
5631
+ dispatchId,
5632
+ status,
5633
+ loaRef: event.loa_ref,
5634
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
5635
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
5636
+ }).then(
5637
+ (r) => {
5638
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
5639
+ },
5640
+ // NOSONAR
5641
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
5642
+ // NOSONAR
5643
+ );
5644
+ }
5645
+ return declared(200, { ok: true, ...result });
4875
5646
  }
4876
5647
  if (body.event === "address.verify" && onVerify) {
4877
5648
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -4881,7 +5652,11 @@ function createOneAddressHandler(options) {
4881
5652
  });
4882
5653
  }
4883
5654
  const encrypted = body.address_encrypted;
4884
- const rawAddress = await decryptAddress2(encrypted, privateKeyPem, partnerId);
5655
+ const rawAddress = await decryptAddress2(
5656
+ encrypted,
5657
+ requirePemFor("address.verify decryption", privateKeyPem),
5658
+ partnerId
5659
+ );
4885
5660
  const event = {
4886
5661
  event: "address.verify",
4887
5662
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -4914,23 +5689,21 @@ function createOneAddressHandler(options) {
4914
5689
  batchId: body.batch_id ?? 0,
4915
5690
  partnerId,
4916
5691
  match: matched,
4917
- note: result && typeof result.note === "string" ? result.note : void 0
5692
+ note: result && typeof result.note === "string" ? result.note : void 0,
5693
+ allowedCallbackHosts
4918
5694
  });
4919
5695
  } catch (err) {
4920
5696
  console.error("[OneAddress SDK] verify-result callback failed:", err);
4921
5697
  }
4922
5698
  }
4923
- return new Response(JSON.stringify({ ok: true, match: matched }), {
4924
- status: 200,
4925
- headers: { "Content-Type": "application/json" }
4926
- });
5699
+ return declared(200, { ok: true, match: matched });
4927
5700
  }
4928
5701
  if (body.event === "account.verify" && onAccountVerify) {
4929
5702
  let customer;
4930
5703
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
4931
5704
  const raw = await decryptAddress2(
4932
5705
  body.customer_encrypted,
4933
- privateKeyPem,
5706
+ requirePemFor("account.verify decryption", privateKeyPem),
4934
5707
  partnerId
4935
5708
  );
4936
5709
  customer = {
@@ -4954,10 +5727,7 @@ function createOneAddressHandler(options) {
4954
5727
  raw: body
4955
5728
  };
4956
5729
  const result = await onAccountVerify(event);
4957
- return new Response(JSON.stringify({ ok: true, ...result }), {
4958
- status: 200,
4959
- headers: { "Content-Type": "application/json" }
4960
- });
5730
+ return declared(200, { ok: true, ...result });
4961
5731
  }
4962
5732
  if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
4963
5733
  if (!isD5Body(body)) {
@@ -4967,6 +5737,7 @@ function createOneAddressHandler(options) {
4967
5737
  });
4968
5738
  }
4969
5739
  const d5 = await buildD5Pieces(body, partnerId);
5740
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
4970
5741
  await onTest({
4971
5742
  event: body.event,
4972
5743
  index: typeof body.index === "number" ? body.index : void 0,
@@ -4978,9 +5749,11 @@ function createOneAddressHandler(options) {
4978
5749
  address: d5.address,
4979
5750
  raw: d5.raw
4980
5751
  });
4981
- return new Response(JSON.stringify({ ok: true, test: true }), {
4982
- status: 200,
4983
- headers: { "Content-Type": "application/json" }
5752
+ return declared(200, {
5753
+ ok: true,
5754
+ test: true,
5755
+ verification: true,
5756
+ index: typeof body.index === "number" ? body.index : void 0
4984
5757
  });
4985
5758
  }
4986
5759
  const evt = typeof body.event === "string" ? body.event : "(none)";
@@ -5007,7 +5780,7 @@ function createOneAddressHandler(options) {
5007
5780
  // NOSONAR
5008
5781
  );
5009
5782
  }
5010
- return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
5783
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt, accepted_update_types: acceptedUpdateTypes }), {
5011
5784
  status: 200,
5012
5785
  headers: { "Content-Type": "application/json" }
5013
5786
  });