@oneaddress/partner-sdk 2.7.0 → 2.9.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/index.js CHANGED
@@ -4146,6 +4146,69 @@ function isBlockedIPv4(host) {
4146
4146
  if (a === 192 && b === 168) return true;
4147
4147
  if (a === 169 && b === 254) return true;
4148
4148
  if (a === 100 && b >= 64 && b <= 127) return true;
4149
+ const c = octets[2];
4150
+ if (a === 192 && b === 0 && c === 0) return true;
4151
+ if (a === 198 && (b === 18 || b === 19)) return true;
4152
+ if (a >= 224 && a <= 239) return true;
4153
+ if (a >= 240) return true;
4154
+ return false;
4155
+ }
4156
+ function expandIPv6(clean2) {
4157
+ let text = clean2;
4158
+ const tail = [];
4159
+ const dotted = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4160
+ if (dotted) {
4161
+ const parts = dotted[2].split(".").map((x) => Number.parseInt(x, 10));
4162
+ if (parts.some((x) => !Number.isInteger(x) || x > 255)) return null;
4163
+ tail.push(parts[0] << 8 | parts[1], parts[2] << 8 | parts[3]);
4164
+ text = dotted[1].endsWith("::") ? dotted[1] : dotted[1].slice(0, -1);
4165
+ }
4166
+ const halves = text.split("::");
4167
+ if (halves.length > 2) return null;
4168
+ const parse = (s) => {
4169
+ if (s === "") return [];
4170
+ const out = [];
4171
+ for (const g of s.split(":")) {
4172
+ if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
4173
+ out.push(Number.parseInt(g, 16));
4174
+ }
4175
+ return out;
4176
+ };
4177
+ const head = parse(halves[0]);
4178
+ const rest = halves.length === 2 ? parse(halves[1]) : [];
4179
+ if (!head || !rest) return null;
4180
+ const known = head.length + rest.length + tail.length;
4181
+ if (halves.length === 1) {
4182
+ return known === 8 ? [...head, ...tail] : null;
4183
+ }
4184
+ if (known > 7) return null;
4185
+ return [...head, ...new Array(8 - known).fill(0), ...rest, ...tail];
4186
+ }
4187
+ function v4FromGroups(high, low) {
4188
+ return `${high >> 8 & 255}.${high & 255}.${low >> 8 & 255}.${low & 255}`;
4189
+ }
4190
+ function isBlockedIPv6Groups(g) {
4191
+ const first = g[0];
4192
+ if ((first & 65280) === 65280) return true;
4193
+ if ((first & 65472) === 65152) return true;
4194
+ if ((first & 65472) === 65216) return true;
4195
+ if ((first & 65024) === 64512) return true;
4196
+ if (first === 8194) return isBlockedIPv4(v4FromGroups(g[1], g[2]));
4197
+ if (first === 100 && g[1] === 65435) {
4198
+ if (g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4199
+ if (g[2] === 1) return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4200
+ return true;
4201
+ }
4202
+ if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0) {
4203
+ if (g[5] === 65535 || g[5] === 0) {
4204
+ if (g[5] === 0 && g[6] === 0 && g[7] <= 1) return true;
4205
+ return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4206
+ }
4207
+ return true;
4208
+ }
4209
+ if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 65535 && g[5] === 0) {
4210
+ return isBlockedIPv4(v4FromGroups(g[6], g[7]));
4211
+ }
4149
4212
  return false;
4150
4213
  }
4151
4214
  function v4FromHexPair(highHex, lowHex) {
@@ -4165,6 +4228,9 @@ function isBlockedIPv6(host) {
4165
4228
  }
4166
4229
  clean2 = clean2.split("%")[0];
4167
4230
  if (!clean2.includes(":")) return false;
4231
+ const groups = expandIPv6(clean2);
4232
+ if (!groups) return true;
4233
+ if (isBlockedIPv6Groups(groups)) return true;
4168
4234
  if (clean2 === "::1") return true;
4169
4235
  if (clean2 === "::") return true;
4170
4236
  if (clean2.startsWith("fe80:")) return true;
@@ -4548,12 +4614,26 @@ function hexToBytes4(hex) {
4548
4614
  }
4549
4615
  return out;
4550
4616
  }
4617
+ function mapsAreCanonical(doc) {
4618
+ const canonical = (s) => typeof s === "string" && s === s.toLowerCase();
4619
+ for (const [partnerId, keyId] of Object.entries(doc.heads)) {
4620
+ if (!canonical(partnerId) || !canonical(keyId)) return false;
4621
+ }
4622
+ if (doc.staged === void 0) return true;
4623
+ if (!doc.staged || typeof doc.staged !== "object" || Array.isArray(doc.staged)) return false;
4624
+ for (const [partnerId, entry] of Object.entries(doc.staged)) {
4625
+ if (!canonical(partnerId) || !entry || typeof entry !== "object") return false;
4626
+ if (!canonical(entry.key_id) || !canonical(entry.key_sha256)) return false;
4627
+ }
4628
+ return true;
4629
+ }
4551
4630
  async function verifyRegistryHead(doc, roots, now = /* @__PURE__ */ new Date()) {
4552
4631
  try {
4553
4632
  if (!doc || !KNOWN_VERSIONS.has(doc.version)) return "malformed";
4554
4633
  if (doc.algorithm !== REGISTRY_HEAD_ALG) return "malformed";
4555
4634
  if (typeof doc.signature !== "string" || !/^[0-9a-f]{128}$/i.test(doc.signature)) return "malformed";
4556
4635
  if (!doc.heads || typeof doc.heads !== "object") return "malformed";
4636
+ if (!mapsAreCanonical(doc)) return "malformed";
4557
4637
  const expires = Date.parse(doc.expires_at);
4558
4638
  const issued = Date.parse(doc.issued_at);
4559
4639
  if (Number.isNaN(expires) || Number.isNaN(issued)) return "malformed";
@@ -5720,12 +5800,28 @@ var init_src = __esm({
5720
5800
  var index_exports = {};
5721
5801
  __export(index_exports, {
5722
5802
  CURRENT_VERSION: () => CURRENT_VERSION,
5803
+ DEFAULT_IDEMPOTENCY_LEASE_SECS: () => DEFAULT_IDEMPOTENCY_LEASE_SECS,
5804
+ DEFAULT_MAX_BODY_BYTES: () => DEFAULT_MAX_BODY_BYTES,
5723
5805
  DEFAULT_REPLAY_WINDOW_SECS: () => DEFAULT_REPLAY_WINDOW_SECS,
5806
+ EffectiveDateMismatchError: () => EffectiveDateMismatchError,
5807
+ LOA_MAX_TYPED_ALIASES: () => LOA_MAX_TYPED_ALIASES,
5808
+ LOA_MIN_SHORT_FORM_LETTERS: () => LOA_MIN_SHORT_FORM_LETTERS,
5809
+ LOA_PUBLIC_KEY_CACHE_MS: () => LOA_PUBLIC_KEY_CACHE_MS,
5810
+ LOA_V2_REFUSALS: () => LOA_V2_REFUSALS,
5811
+ LoaPublicKeyUnavailableError: () => LoaPublicKeyUnavailableError,
5812
+ LoaV2RefusedError: () => LoaV2RefusedError,
5813
+ MAX_ADDRESS_FIELD_CHARS: () => MAX_ADDRESS_FIELD_CHARS,
5724
5814
  OUTBOX_LEASE_COLUMNS: () => OUTBOX_LEASE_COLUMNS,
5725
5815
  SUPPORTED_VERSIONS: () => SUPPORTED_VERSIONS,
5816
+ _resetLoaKeyCacheForTests: () => _resetLoaKeyCacheForTests,
5726
5817
  _resetOnceWarningsForTests: () => _resetOnceWarningsForTests,
5818
+ acceptTypedAliases: () => acceptTypedAliases,
5819
+ assertEffectiveDateBound: () => assertEffectiveDateBound,
5727
5820
  buildSignedTestWebhook: () => buildSignedTestWebhook,
5821
+ cachedLoaPublicKey: () => cachedLoaPublicKey,
5728
5822
  canonicalD5LoaForm: () => canonicalD5LoaForm,
5823
+ canonicalD5LoaFormV2: () => canonicalD5LoaFormV2,
5824
+ checkLoaV2: () => checkLoaV2,
5729
5825
  checkRegistryHead: () => checkRegistryHead,
5730
5826
  compareAddresses: () => compareAddresses,
5731
5827
  computeBlindIndex: () => computeBlindIndex,
@@ -5742,9 +5838,16 @@ __export(index_exports, {
5742
5838
  findMatchingStoredName: () => findMatchingStoredName,
5743
5839
  formatAddressParts: () => formatAddressParts,
5744
5840
  fromOutboxTimestamp: () => fromOutboxTimestamp,
5841
+ hasLoaV2: () => hasLoaV2,
5842
+ isAcceptableAlias: () => isAcceptableAlias,
5745
5843
  isEmailLike: () => isEmailLike2,
5746
5844
  isFreshTimestamp: () => isFreshTimestamp,
5845
+ loaEnvelopeSha256: () => loaEnvelopeSha256,
5846
+ loaFirstName: () => loaFirstName,
5847
+ loaNamesMatch: () => loaNamesMatch,
5848
+ loaSurname: () => loaSurname,
5747
5849
  namePoolMatches: () => namePoolMatches,
5850
+ normaliseLoaName: () => normaliseLoaName,
5748
5851
  normalizeForBlindIndex: () => normalizeForBlindIndex,
5749
5852
  parsePinnedRegistryRoots: () => parsePinnedRegistryRoots,
5750
5853
  readAddressParts: () => readAddressParts,
@@ -5755,9 +5858,11 @@ __export(index_exports, {
5755
5858
  transform: () => transformAddress,
5756
5859
  transformAddress: () => transformAddress,
5757
5860
  transformSession: () => transformSession,
5861
+ typedAliasesOf: () => typedAliasesOf,
5758
5862
  validateAddress: () => validateAddress,
5759
5863
  verify: () => verifySignature,
5760
5864
  verifyD5LOA: () => verifyD5LOA,
5865
+ verifyD5LOAv2: () => verifyD5LOAv2,
5761
5866
  verifyGrace: () => verifyWithGrace,
5762
5867
  verifyLOA: () => verifyLOA,
5763
5868
  verifySignature: () => verifySignature,
@@ -5771,6 +5876,19 @@ init_src();
5771
5876
  var CURRENT_VERSION = "2026.1";
5772
5877
  var SUPPORTED_VERSIONS = ["2026.1"];
5773
5878
 
5879
+ // ../protocol/src/notice-period.ts
5880
+ var ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
5881
+ function isIsoDate(value) {
5882
+ if (typeof value !== "string") return false;
5883
+ const m = ISO_DATE.exec(value);
5884
+ if (!m) return false;
5885
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
5886
+ return toIso(d) === value;
5887
+ }
5888
+ function toIso(d) {
5889
+ return d.toISOString().slice(0, 10);
5890
+ }
5891
+
5774
5892
  // ../protocol/src/d5-body.ts
5775
5893
  var D5_BODY_ALWAYS = [
5776
5894
  "event",
@@ -5780,7 +5898,6 @@ var D5_BODY_ALWAYS = [
5780
5898
  "partner_id",
5781
5899
  "session_envelope",
5782
5900
  "session_key_share",
5783
- "stripe_session_id",
5784
5901
  "timestamp",
5785
5902
  "update_id",
5786
5903
  "user_id"
@@ -5801,7 +5918,18 @@ var D5_BODY_CONDITIONAL = {
5801
5918
  */
5802
5919
  id: "key-crossover copy only",
5803
5920
  /** The sibling marker naming the other key_ids this update was sealed to. */
5804
- crossover_key_ids: "key-crossover copy only"
5921
+ crossover_key_ids: "key-crossover copy only",
5922
+ /**
5923
+ * The day the change takes effect, `YYYY-MM-DD` (31 Oct 2026). Set on every
5924
+ * dispatch made for a SCHEDULED MOVE, which is its move date. A scheduled
5925
+ * move sends each recipient early enough for its own notice period
5926
+ * (`resolveRecipientSendPlan` in `notice-period.ts`), so the update can
5927
+ * arrive days before the customer moves; a recipient that treated it as
5928
+ * immediate could start charging at the new address from the day it arrived.
5929
+ * Absent on an immediate update, which takes effect on receipt. Optional for
5930
+ * receivers: an SDK that does not know the field ignores it.
5931
+ */
5932
+ effective_date: "scheduled move only"
5805
5933
  };
5806
5934
  var D5_BODY_DRILL_ONLY = ["conformance"];
5807
5935
  var D5_BODY_ADDED_AT_SEND = ["dispatch_id"];
@@ -5836,6 +5964,110 @@ function pullSigningStringV2(timestamp, method, pathAndQuery, body = "") {
5836
5964
  return `v2.${timestamp}.${method.toUpperCase()}.${pathAndQuery}.${body}`;
5837
5965
  }
5838
5966
 
5967
+ // ../protocol/src/loa-v2.ts
5968
+ var LOA_V2_VERSION_TAG = "oneaddress-loa/2";
5969
+ var LOA_V2_LEGACY_ENVELOPE_TAG = "oneaddress-legacy-envelope/1";
5970
+ var LOA_V2_FIELD_ORDER = [
5971
+ "consumer_name",
5972
+ "authorisation_date",
5973
+ "scope",
5974
+ "update_uid",
5975
+ "partner_id",
5976
+ "envelope_sha256"
5977
+ ];
5978
+ var LOA_MAX_TYPED_ALIASES = 3;
5979
+ var LoaV2FieldError = class extends Error {
5980
+ constructor(field, reason) {
5981
+ super(`LOA v2 field ${field} ${reason}`);
5982
+ this.field = field;
5983
+ this.name = "LoaV2FieldError";
5984
+ }
5985
+ };
5986
+ var CONTROL_RE = /[\u0000-\u001F\u007F]/;
5987
+ var LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
5988
+ function utf8Length(s) {
5989
+ return new TextEncoder().encode(s).length;
5990
+ }
5991
+ function encodeField(name, value) {
5992
+ if (typeof value !== "string") throw new LoaV2FieldError(name, "is not a string");
5993
+ if (CONTROL_RE.test(value)) throw new LoaV2FieldError(name, "contains a control character");
5994
+ if (LONE_SURROGATE_RE.test(value)) throw new LoaV2FieldError(name, "is not well-formed Unicode");
5995
+ return `${utf8Length(value)}:${value}
5996
+ `;
5997
+ }
5998
+ function canonicalLoaV2(fields) {
5999
+ let out = encodeField("version", LOA_V2_VERSION_TAG);
6000
+ for (const f of LOA_V2_FIELD_ORDER) out += encodeField(f, fields[f]);
6001
+ const aliases = fields.consumer_typed_aliases;
6002
+ if (!Array.isArray(aliases)) throw new LoaV2FieldError("consumer_typed_aliases", "is not a list");
6003
+ if (aliases.length > LOA_MAX_TYPED_ALIASES) {
6004
+ throw new LoaV2FieldError("consumer_typed_aliases", `has more than ${LOA_MAX_TYPED_ALIASES} entries`);
6005
+ }
6006
+ out += encodeField("consumer_typed_aliases", String(aliases.length));
6007
+ for (const a of aliases) out += encodeField("consumer_typed_aliases", a);
6008
+ return out;
6009
+ }
6010
+ function loaV2EnvelopeDigestInput(envelope) {
6011
+ if (typeof envelope === "string") return envelope;
6012
+ if (!envelope || typeof envelope !== "object") {
6013
+ throw new LoaV2FieldError("envelope", "is neither a session_envelope string nor an address_encrypted object");
6014
+ }
6015
+ return encodeField("tag", LOA_V2_LEGACY_ENVELOPE_TAG) + encodeField("ephemeralPublicKey", envelope.ephemeralPublicKey) + encodeField("iv", envelope.iv) + encodeField("ciphertext", envelope.ciphertext) + encodeField("hkdfSalt", envelope.hkdfSalt ?? "");
6016
+ }
6017
+ var ASCII_WS_RE = /[ \t\n\v\f\r]+/;
6018
+ var MARK_RE = /\p{M}/gu;
6019
+ function normaliseLoaName(name) {
6020
+ return name.normalize("NFKD").replace(MARK_RE, "").toLowerCase().replace(/\u03C2/g, "\u03C3").split(ASCII_WS_RE).filter((t) => t.length > 0).join(" ");
6021
+ }
6022
+ function loaSurname(name) {
6023
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
6024
+ return tokens.length > 0 ? tokens[tokens.length - 1] : "";
6025
+ }
6026
+ function loaFirstName(name) {
6027
+ const tokens = normaliseLoaName(name).split(" ").filter((t) => t.length > 0);
6028
+ return tokens.length > 0 ? tokens[0] : "";
6029
+ }
6030
+ function loaNamesMatch(a, b) {
6031
+ const na = normaliseLoaName(a);
6032
+ return na.length > 0 && na === normaliseLoaName(b);
6033
+ }
6034
+ var LOA_MIN_SHORT_FORM_LETTERS = 3;
6035
+ function codePoints(s) {
6036
+ return Array.from(s).length;
6037
+ }
6038
+ function isAcceptableAlias(verifiedName, alias) {
6039
+ const vFirst = loaFirstName(verifiedName);
6040
+ const aFirst = loaFirstName(alias);
6041
+ if (!vFirst || !aFirst) return false;
6042
+ if (aFirst === vFirst) return true;
6043
+ const [shorter, longer] = codePoints(aFirst) <= codePoints(vFirst) ? [aFirst, vFirst] : [vFirst, aFirst];
6044
+ return codePoints(shorter) >= LOA_MIN_SHORT_FORM_LETTERS && longer.startsWith(shorter);
6045
+ }
6046
+ function acceptTypedAliases(verifiedName, aliases) {
6047
+ const out = [];
6048
+ if (!Array.isArray(aliases)) return out;
6049
+ const seen = /* @__PURE__ */ new Set([normaliseLoaName(verifiedName)]);
6050
+ for (const a of aliases) {
6051
+ if (out.length >= LOA_MAX_TYPED_ALIASES) break;
6052
+ if (typeof a !== "string") continue;
6053
+ if (CONTROL_RE.test(a) || LONE_SURROGATE_RE.test(a)) continue;
6054
+ const n = normaliseLoaName(a);
6055
+ if (!n || seen.has(n)) continue;
6056
+ if (!isAcceptableAlias(verifiedName, a)) continue;
6057
+ seen.add(n);
6058
+ out.push(a);
6059
+ }
6060
+ return out;
6061
+ }
6062
+ var LOA_V2_REFUSALS = [
6063
+ "loa_v2_malformed",
6064
+ "loa_v2_signature_invalid",
6065
+ "loa_v2_partner_mismatch",
6066
+ "loa_v2_update_mismatch",
6067
+ "loa_v2_envelope_mismatch",
6068
+ "loa_v2_name_mismatch"
6069
+ ];
6070
+
5839
6071
  // src/app-hosts.ts
5840
6072
  function allowedAppHosts() {
5841
6073
  const hosts = ["oneaddress.io", "app.oneaddress.io"];
@@ -5844,7 +6076,7 @@ function allowedAppHosts() {
5844
6076
  }
5845
6077
  return new Set(hosts);
5846
6078
  }
5847
- function resolveAppOrigin(baseUrl, label) {
6079
+ function resolveAppOrigin(baseUrl, label, extraHosts) {
5848
6080
  let parsed;
5849
6081
  try {
5850
6082
  parsed = new URL(baseUrl);
@@ -5852,6 +6084,9 @@ function resolveAppOrigin(baseUrl, label) {
5852
6084
  throw new Error(`[OneAddress SDK] ${label}: appBaseUrl is not a valid URL`);
5853
6085
  }
5854
6086
  const allowed = allowedAppHosts();
6087
+ for (const h of extraHosts ?? []) {
6088
+ if (typeof h === "string" && h.trim() !== "") allowed.add(h.trim().toLowerCase());
6089
+ }
5855
6090
  if (!allowed.has(parsed.hostname)) {
5856
6091
  throw new Error(
5857
6092
  `[OneAddress SDK] ${label}: appBaseUrl host must be one of: ${[...allowed].join(", ")}`
@@ -5887,26 +6122,38 @@ function surnameVariants(token) {
5887
6122
  if (!token.includes("-")) return [token];
5888
6123
  return [token, ...token.split("-").filter(Boolean)];
5889
6124
  }
6125
+ var MAX_ALIASES = 10;
6126
+ var MAX_TOKENS_PER_NAME = 8;
6127
+ var MAX_POOL_TOKENS = 24;
5890
6128
  function namePoolMatches(providedNames, storedName) {
5891
6129
  if (isEmailLike2(storedName)) return false;
5892
- const provided = providedNames.filter((n) => Boolean(n) && !isEmailLike2(n));
6130
+ const provided = providedNames.filter((n) => typeof n === "string" && n !== "" && !isEmailLike2(n));
5893
6131
  const primary = tokenize(provided[0] ?? "");
5894
- if (primary.length === 0) return false;
6132
+ if (primary.length === 0 || primary.length > MAX_TOKENS_PER_NAME) return false;
6133
+ const aliases = provided.slice(1, 1 + MAX_ALIASES).map(tokenize).filter((t) => t.length > 0 && t.length <= MAX_TOKENS_PER_NAME);
6134
+ const distinct = new Set(primary);
6135
+ for (const t of aliases) for (const tok of t) distinct.add(tok);
6136
+ if (distinct.size > MAX_POOL_TOKENS) return false;
5895
6137
  const surnames = new Set(surnameVariants(primary[primary.length - 1]));
5896
- for (let i = 1; i < provided.length; i++) {
5897
- const t = tokenize(provided[i]);
5898
- if (t.length >= 2) for (const v of surnameVariants(t[t.length - 1])) surnames.add(v);
5899
- }
5900
- const all = /* @__PURE__ */ new Set();
5901
- for (const n of provided) for (const t of tokenize(n)) all.add(t);
5902
- const given = [...all].filter((t) => !surnames.has(t));
6138
+ for (const t of aliases) {
6139
+ const last = t[t.length - 1];
6140
+ if (t.length >= 2 && last.length >= 2) for (const v of surnameVariants(last)) surnames.add(v);
6141
+ }
6142
+ const givenSet = /* @__PURE__ */ new Set();
6143
+ for (const tok of primary) if (!surnames.has(tok)) givenSet.add(tok);
6144
+ for (const t of aliases) for (const tok of t) if (tok.length >= 2 && !surnames.has(tok)) givenSet.add(tok);
6145
+ const given = [...givenSet];
6146
+ const fullGiven = given.filter((g) => g.length >= 2);
5903
6147
  const stored = tokenize(storedName);
5904
- if (stored.length === 0) return false;
6148
+ if (stored.length < 2) return false;
5905
6149
  const storedSurname = stored[stored.length - 1];
5906
6150
  const storedGiven = stored.slice(0, -1);
5907
6151
  if (!surnameVariants(storedSurname).some((v) => surnames.has(v))) return false;
5908
6152
  const covered = (tok) => given.includes(tok) || tok.length === 1 && given.some((g) => g[0] === tok) || given.some((g) => g.length === 1 && g === tok[0]);
5909
- return storedGiven.every(covered);
6153
+ if (!storedGiven.every(covered)) return false;
6154
+ return storedGiven.some(
6155
+ (tok) => fullGiven.includes(tok) || tok.length === 1 && fullGiven.some((g) => g[0] === tok)
6156
+ );
5910
6157
  }
5911
6158
  function findMatchingStoredName(providedNames, storedCandidates) {
5912
6159
  return storedCandidates.find((candidate) => namePoolMatches(providedNames, candidate));
@@ -6338,6 +6585,18 @@ async function checkRegistryHead(opts2) {
6338
6585
  headExpiresAt: expires
6339
6586
  };
6340
6587
  }
6588
+ if (expectedKeyId) {
6589
+ return {
6590
+ verdict: "names-key-we-lack",
6591
+ checked: true,
6592
+ alarm: true,
6593
+ detail: `the head names ${named} as the current key for this partner id, not ${expectedKeyId}, the key this recipient is configured with. If you did not rotate to ${named}, address envelopes are being sealed to a key you cannot read: contact OneAddress through a channel that is not oneaddress.io. If you did rotate, update keyId, or pass holdsKey so a key you hold is recognised.`,
6594
+ namedKeyId: named,
6595
+ expectedKeyId,
6596
+ headIssuedAt: issued,
6597
+ headExpiresAt: expires
6598
+ };
6599
+ }
6341
6600
  return {
6342
6601
  verdict: "key-identity-unknown",
6343
6602
  checked: false,
@@ -6352,14 +6611,21 @@ async function checkRegistryHead(opts2) {
6352
6611
 
6353
6612
  // src/index.ts
6354
6613
  var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
6614
+ var DEFAULT_IDEMPOTENCY_LEASE_SECS = 120;
6355
6615
  function createSqlIdempotencyStore(opts2) {
6356
6616
  const table = opts2.table ?? "oneaddress_dispatches";
6357
6617
  const dialect = opts2.dialect ?? "postgres";
6618
+ const leaseSeconds = opts2.leaseSeconds ?? DEFAULT_IDEMPOTENCY_LEASE_SECS;
6358
6619
  if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
6359
6620
  throw new Error(
6360
6621
  `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
6361
6622
  );
6362
6623
  }
6624
+ if (typeof leaseSeconds !== "number" || !Number.isSafeInteger(leaseSeconds) || leaseSeconds < 0 || leaseSeconds > 86400) {
6625
+ throw new Error(
6626
+ `[OneAddress SDK] createSqlIdempotencyStore: leaseSeconds must be a whole number from 0 to 86400, got ${String(leaseSeconds)}`
6627
+ );
6628
+ }
6363
6629
  const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
6364
6630
  const ph = opts2.placeholder ?? defaultPh;
6365
6631
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
@@ -6378,7 +6644,26 @@ function createSqlIdempotencyStore(opts2) {
6378
6644
  [dispatchId]
6379
6645
  );
6380
6646
  if (tokenOf(rows[0]) === token) return "fresh";
6381
- return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
6647
+ if (completedOf(rows[0])) return "duplicate";
6648
+ const takeover = import_crypto2.default.randomBytes(16).toString("hex");
6649
+ await opts2.query(
6650
+ `UPDATE ${table} SET received_at = CURRENT_TIMESTAMP, claim_token = ${ph(1)} WHERE dispatch_id = ${ph(2)} AND completed_at IS NULL AND ${staleClaim(3)}`,
6651
+ leaseParams([takeover, dispatchId])
6652
+ );
6653
+ const after = await opts2.query(
6654
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
6655
+ [dispatchId]
6656
+ );
6657
+ if (tokenOf(after[0]) === takeover) return "retry-after-incomplete";
6658
+ return completedOf(after[0]) ? "duplicate" : "in-progress";
6659
+ }
6660
+ function staleClaim(n) {
6661
+ if (leaseSeconds === 0) return "1 = 1";
6662
+ const cutoff = dialect === "postgres" ? `received_at < CURRENT_TIMESTAMP - make_interval(secs => ${ph(n)})` : dialect === "sqlite" ? `julianday(received_at) < julianday('now') - (${ph(n)} / 86400.0)` : dialect === "mysql" ? `received_at < CURRENT_TIMESTAMP - INTERVAL ${ph(n)} SECOND` : `received_at < DATEADD(second, -${ph(n)}, CURRENT_TIMESTAMP)`;
6663
+ return `(received_at IS NULL OR ${cutoff})`;
6664
+ }
6665
+ function leaseParams(params) {
6666
+ return leaseSeconds === 0 ? params : [...params, leaseSeconds];
6382
6667
  }
6383
6668
  async function setByUpsert(dispatchId) {
6384
6669
  if (dialect === "mysql") {
@@ -6412,11 +6697,22 @@ function createSqlIdempotencyStore(opts2) {
6412
6697
  [dispatchId]
6413
6698
  );
6414
6699
  if (inserted.length > 0) return "fresh";
6700
+ const took = await opts2.query(
6701
+ `UPDATE ${table} SET received_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL AND ${staleClaim(2)} RETURNING dispatch_id`,
6702
+ leaseParams([dispatchId])
6703
+ );
6704
+ if (took.length > 0) return "retry-after-incomplete";
6415
6705
  const rows = await opts2.query(
6416
6706
  `SELECT completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
6417
6707
  [dispatchId]
6418
6708
  );
6419
- return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
6709
+ return completedOf(rows[0]) ? "duplicate" : "in-progress";
6710
+ },
6711
+ async release(dispatchId) {
6712
+ await opts2.query(
6713
+ `DELETE FROM ${table} WHERE dispatch_id = ${ph(1)} AND completed_at IS NULL`,
6714
+ [dispatchId]
6715
+ );
6420
6716
  },
6421
6717
  async complete(dispatchId) {
6422
6718
  await opts2.query(
@@ -6602,6 +6898,7 @@ async function transformSession(share, envelopeB64, privateKeyPem, partnerId, re
6602
6898
  );
6603
6899
  }
6604
6900
  var OA_APP_BASE_URL2 = "https://oneaddress.io";
6901
+ var CONFIRM_PATH = "/api/confirm";
6605
6902
  async function confirmUpdate(opts2) {
6606
6903
  const {
6607
6904
  partnerId,
@@ -6616,6 +6913,13 @@ async function confirmUpdate(opts2) {
6616
6913
  } = opts2;
6617
6914
  if (!partnerId) return { ok: false, status: 0, error: "partnerId is required" };
6618
6915
  if (!secret) return { ok: false, status: 0, error: "secret is required" };
6916
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(partnerId)) {
6917
+ return {
6918
+ ok: false,
6919
+ status: 0,
6920
+ error: `partnerId must be your partner UUID from the portal, received ${JSON.stringify(partnerId)}`
6921
+ };
6922
+ }
6619
6923
  const id = typeof dispatchId === "string" ? Number(dispatchId) : dispatchId;
6620
6924
  if (!Number.isInteger(id) || id <= 0) {
6621
6925
  return {
@@ -6633,18 +6937,22 @@ async function confirmUpdate(opts2) {
6633
6937
  ...memberName !== void 0 ? { member_name: memberName } : {}
6634
6938
  });
6635
6939
  const timestamp = String(Math.floor(Date.now() / 1e3));
6636
- const signature = import_crypto2.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
6637
- let base = appBaseUrl;
6638
- while (base.endsWith("/")) base = base.slice(0, -1);
6940
+ const signature = import_crypto2.default.createHmac("sha256", secret).update(pullSigningStringV2(timestamp, "POST", CONFIRM_PATH, body)).digest("hex");
6941
+ let origin;
6942
+ try {
6943
+ origin = resolveAppOrigin(appBaseUrl, "confirmUpdate", opts2.allowedHosts);
6944
+ } catch (err) {
6945
+ return { ok: false, status: 0, error: err instanceof Error ? err.message : String(err) };
6946
+ }
6639
6947
  let res;
6640
6948
  try {
6641
- res = await fetchImpl(`${base}/api/confirm`, {
6949
+ res = await fetchImpl(`${origin}${CONFIRM_PATH}`, {
6642
6950
  method: "POST",
6643
6951
  headers: {
6644
6952
  "Content-Type": "application/json",
6645
- "Authorization": `Bearer ${secret}`,
6646
6953
  "X-OneAddress-Timestamp": timestamp,
6647
- "X-OneAddress-Signature": signature
6954
+ "X-OneAddress-Signature": signature,
6955
+ [PULL_SIGNATURE_VERSION_HEADER]: "2"
6648
6956
  },
6649
6957
  // The SAME string that was signed. Not an object, and not re-stringified.
6650
6958
  body
@@ -6670,6 +6978,48 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2) {
6670
6978
  }
6671
6979
  return res.text();
6672
6980
  }
6981
+ var LOA_PUBLIC_KEY_CACHE_MS = 24 * 60 * 60 * 1e3;
6982
+ var loaKeyCache = /* @__PURE__ */ new Map();
6983
+ var loaKeyInFlight = /* @__PURE__ */ new Map();
6984
+ var LoaPublicKeyUnavailableError = class extends Error {
6985
+ constructor(from, cause) {
6986
+ super(
6987
+ `[OneAddress SDK] could not fetch OneAddress's LOA public key from ${from} (${cause}). requireLoa is on (the default since 2.8.0), so this dispatch is refused and OneAddress will retry it. Pin the key with loaPublicKeyPem (from fetchLoaPublicKey), or set requireLoa: false to process dispatches without verifying consent.`
6988
+ );
6989
+ this.from = from;
6990
+ this.name = "LoaPublicKeyUnavailableError";
6991
+ }
6992
+ };
6993
+ async function cachedLoaPublicKey(appBaseUrl = OA_APP_BASE_URL2, now = Date.now()) {
6994
+ const origin = resolveAppOrigin(appBaseUrl, "cachedLoaPublicKey");
6995
+ const held = loaKeyCache.get(origin);
6996
+ if (held && now - held.at < LOA_PUBLIC_KEY_CACHE_MS) return held.pem;
6997
+ let pending = loaKeyInFlight.get(origin);
6998
+ if (!pending) {
6999
+ pending = (async () => {
7000
+ const pem = (await fetchLoaPublicKey(origin)).trim();
7001
+ if (!pem.includes("-----BEGIN PUBLIC KEY-----")) {
7002
+ throw new Error("the response is not a PEM public key");
7003
+ }
7004
+ loaKeyCache.set(origin, { pem, at: Date.now() });
7005
+ return pem;
7006
+ })().finally(() => loaKeyInFlight.delete(origin));
7007
+ loaKeyInFlight.set(origin, pending);
7008
+ }
7009
+ try {
7010
+ return await pending;
7011
+ } catch (err) {
7012
+ if (held) return held.pem;
7013
+ throw new LoaPublicKeyUnavailableError(
7014
+ `${origin}/.well-known/oneaddress-loa-key.pem`,
7015
+ err instanceof Error ? err.message : String(err)
7016
+ );
7017
+ }
7018
+ }
7019
+ function _resetLoaKeyCacheForTests() {
7020
+ loaKeyCache.clear();
7021
+ loaKeyInFlight.clear();
7022
+ }
6673
7023
  async function verifyLOA(loa, publicKeyPem) {
6674
7024
  if (loa.algorithm !== "ECDSA-P256") {
6675
7025
  console.warn(
@@ -6749,6 +7099,91 @@ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expec
6749
7099
  );
6750
7100
  return data;
6751
7101
  }
7102
+ function hasLoaV2(loa) {
7103
+ return typeof loa.oneaddress_signature_v2 === "string";
7104
+ }
7105
+ function canonicalD5LoaFormV2(loa) {
7106
+ return canonicalLoaV2({
7107
+ consumer_name: loa.consumer_name,
7108
+ authorisation_date: loa.authorisation_date,
7109
+ scope: loa.scope,
7110
+ update_uid: loa.update_uid,
7111
+ partner_id: loa.partner_id,
7112
+ envelope_sha256: loa.envelope_sha256,
7113
+ consumer_typed_aliases: loa.consumer_typed_aliases
7114
+ });
7115
+ }
7116
+ function loaEnvelopeSha256(envelope) {
7117
+ return import_crypto2.default.createHash("sha256").update(loaV2EnvelopeDigestInput(envelope), "utf8").digest("hex");
7118
+ }
7119
+ async function verifyD5LOAv2(loa, publicKeyPem) {
7120
+ if (loa.signature_algorithm !== "ECDSA-P256" || !hasLoaV2(loa)) return false;
7121
+ let text;
7122
+ try {
7123
+ text = canonicalD5LoaFormV2(loa);
7124
+ } catch {
7125
+ return false;
7126
+ }
7127
+ try {
7128
+ const key = await import_crypto2.default.subtle.importKey(
7129
+ "spki",
7130
+ pemToBuffer(publicKeyPem),
7131
+ { name: "ECDSA", namedCurve: "P-256" },
7132
+ false,
7133
+ ["verify"]
7134
+ );
7135
+ return await import_crypto2.default.subtle.verify(
7136
+ { name: "ECDSA", hash: "SHA-256" },
7137
+ key,
7138
+ Buffer.from(loa.oneaddress_signature_v2, "hex"),
7139
+ new TextEncoder().encode(text)
7140
+ );
7141
+ } catch {
7142
+ return false;
7143
+ }
7144
+ }
7145
+ function typedAliasesOf(loa) {
7146
+ if (!hasLoaV2(loa)) return [];
7147
+ return acceptTypedAliases(loa.consumer_name, loa.consumer_typed_aliases);
7148
+ }
7149
+ function bodyUpdateIdString(v) {
7150
+ if (typeof v === "string") return v;
7151
+ if (typeof v === "number" && Number.isSafeInteger(v)) return String(v);
7152
+ return null;
7153
+ }
7154
+ async function checkLoaV2(loa, ctx) {
7155
+ if (!hasLoaV2(loa) || typeof loa.partner_id !== "string" || typeof loa.envelope_sha256 !== "string") {
7156
+ return "loa_v2_malformed";
7157
+ }
7158
+ try {
7159
+ canonicalD5LoaFormV2(loa);
7160
+ } catch {
7161
+ return "loa_v2_malformed";
7162
+ }
7163
+ if (ctx.publicKeyPem !== void 0 && !await verifyD5LOAv2(loa, ctx.publicKeyPem)) {
7164
+ return "loa_v2_signature_invalid";
7165
+ }
7166
+ if (loa.partner_id !== ctx.partnerId) return "loa_v2_partner_mismatch";
7167
+ if (bodyUpdateIdString(ctx.updateId) !== loa.update_uid) return "loa_v2_update_mismatch";
7168
+ let digest;
7169
+ try {
7170
+ digest = loaEnvelopeSha256(ctx.envelope);
7171
+ } catch {
7172
+ return "loa_v2_envelope_mismatch";
7173
+ }
7174
+ if (digest !== loa.envelope_sha256) return "loa_v2_envelope_mismatch";
7175
+ if (typeof ctx.envelopeVerifiedName !== "string" || !loaNamesMatch(ctx.envelopeVerifiedName, loa.consumer_name)) {
7176
+ return "loa_v2_name_mismatch";
7177
+ }
7178
+ return null;
7179
+ }
7180
+ var LoaV2RefusedError = class extends Error {
7181
+ constructor(code) {
7182
+ super(`[OneAddress SDK] D5 LOA v2 refused (${code}); refusing rather than applying an update the consent record does not cover`);
7183
+ this.code = code;
7184
+ this.name = "LoaV2RefusedError";
7185
+ }
7186
+ };
6752
7187
  var ADDRESS_REQUIRED_FIELDS = [
6753
7188
  "street",
6754
7189
  "suburb",
@@ -6756,19 +7191,60 @@ var ADDRESS_REQUIRED_FIELDS = [
6756
7191
  "postcode",
6757
7192
  "country"
6758
7193
  ];
7194
+ var MAX_ADDRESS_FIELD_CHARS = 512;
6759
7195
  function validateAddress(raw) {
6760
- if (typeof raw !== "object" || raw === null) {
7196
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
6761
7197
  throw new Error("[OneAddress SDK] Decrypted address payload is not an object");
6762
7198
  }
6763
7199
  const obj = raw;
6764
7200
  for (const field of ADDRESS_REQUIRED_FIELDS) {
6765
- if (typeof obj[field] !== "string" || obj[field] === "") {
7201
+ const value = obj[field];
7202
+ if (typeof value !== "string" || value === "") {
6766
7203
  throw new Error(
6767
- `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change \u2014 update @oneaddress/partner-sdk.`
7204
+ `[OneAddress SDK] Decrypted address is missing required field "${field}". This may indicate a decryption error or a schema change - update @oneaddress/partner-sdk.`
6768
7205
  );
6769
7206
  }
7207
+ if (value.length > MAX_ADDRESS_FIELD_CHARS) {
7208
+ throw new Error(
7209
+ `[OneAddress SDK] Decrypted address field "${field}" is ${value.length} characters, over the ${MAX_ADDRESS_FIELD_CHARS} this SDK accepts; refusing rather than truncating`
7210
+ );
7211
+ }
7212
+ }
7213
+ const rawUpdatedAt = obj.updated_at;
7214
+ let updatedAt;
7215
+ if (rawUpdatedAt === void 0 || rawUpdatedAt === null) updatedAt = "";
7216
+ else if (typeof rawUpdatedAt === "number" && Number.isFinite(rawUpdatedAt)) updatedAt = String(rawUpdatedAt);
7217
+ else if (typeof rawUpdatedAt === "string") updatedAt = rawUpdatedAt;
7218
+ else throw new Error('[OneAddress SDK] Decrypted address field "updated_at" is not a string');
7219
+ if (updatedAt.length > MAX_ADDRESS_FIELD_CHARS) {
7220
+ throw new Error(
7221
+ `[OneAddress SDK] Decrypted address field "updated_at" is over the ${MAX_ADDRESS_FIELD_CHARS} characters this SDK accepts`
7222
+ );
6770
7223
  }
6771
- return obj;
7224
+ return {
7225
+ street: obj.street,
7226
+ suburb: obj.suburb,
7227
+ state: obj.state,
7228
+ postcode: obj.postcode,
7229
+ country: obj.country,
7230
+ updated_at: updatedAt
7231
+ };
7232
+ }
7233
+ function legacyAddressOf(blob, body) {
7234
+ return validateAddress({
7235
+ street: blob.street,
7236
+ suburb: blob.suburb,
7237
+ state: blob.state,
7238
+ postcode: blob.postcode,
7239
+ country: blob.country,
7240
+ updated_at: typeof blob.updated_at === "string" ? blob.updated_at : body.timestamp ?? ""
7241
+ });
7242
+ }
7243
+ function stringOr(value, fallback) {
7244
+ return typeof value === "string" ? value : fallback;
7245
+ }
7246
+ function stringsOf(value) {
7247
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
6772
7248
  }
6773
7249
  var ADDRESS_ALIASES = {
6774
7250
  line1: ["line1", "address_line1", "street", "streetAddress"],
@@ -6952,6 +7428,41 @@ function _resetOnceWarningsForTests() {
6952
7428
  warnedNoIdempotencyStore = false;
6953
7429
  }
6954
7430
  var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
7431
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
7432
+ var IN_PROGRESS_RETRY_AFTER_SECS = 30;
7433
+ async function readBodyCapped(req, max) {
7434
+ const declaredLength = req.headers.get("content-length");
7435
+ if (declaredLength !== null && /^\s*\d+\s*$/.test(declaredLength) && Number(declaredLength) > max) {
7436
+ return null;
7437
+ }
7438
+ const stream = req.body;
7439
+ if (stream && typeof stream.getReader === "function") {
7440
+ const reader = stream.getReader();
7441
+ const chunks = [];
7442
+ let total = 0;
7443
+ for (; ; ) {
7444
+ const { done, value } = await reader.read();
7445
+ if (done) break;
7446
+ if (!value) continue;
7447
+ total += value.byteLength;
7448
+ if (total > max) {
7449
+ await reader.cancel().catch(() => void 0);
7450
+ return null;
7451
+ }
7452
+ chunks.push(value);
7453
+ }
7454
+ const joined = new Uint8Array(total);
7455
+ let offset = 0;
7456
+ for (const c of chunks) {
7457
+ joined.set(c, offset);
7458
+ offset += c.byteLength;
7459
+ }
7460
+ return new TextDecoder("utf-8").decode(joined);
7461
+ }
7462
+ const text = await req.text();
7463
+ if (text.length > max || new TextEncoder().encode(text).byteLength > max) return null;
7464
+ return text;
7465
+ }
6955
7466
  var XWING_SEED_BYTES = 32;
6956
7467
  function assertUsablePrivateKey(privateKeyPem) {
6957
7468
  if (typeof privateKeyPem !== "string") {
@@ -6981,6 +7492,21 @@ function requirePemFor(purpose, key) {
6981
7492
  `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
6982
7493
  );
6983
7494
  }
7495
+ var EffectiveDateMismatchError = class extends Error {
7496
+ constructor(sealed, body) {
7497
+ super(
7498
+ `[OneAddress SDK] effective_date in the body (${JSON.stringify(body ?? null)}) does not match the one sealed in the envelope (${JSON.stringify(sealed ?? null)}); refusing rather than applying a date the consumer did not seal`
7499
+ );
7500
+ this.sealed = sealed;
7501
+ this.body = body;
7502
+ this.name = "EffectiveDateMismatchError";
7503
+ }
7504
+ };
7505
+ function assertEffectiveDateBound(sealed, body) {
7506
+ if (sealed === void 0 && body === void 0) return;
7507
+ if (sealed !== void 0 && body !== void 0 && sealed === body) return;
7508
+ throw new EffectiveDateMismatchError(sealed, body);
7509
+ }
6984
7510
  function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
6985
7511
  if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
6986
7512
  if (loa.update_uid !== envelopeUpdateUid) {
@@ -6998,13 +7524,16 @@ function createOneAddressHandler(options) {
6998
7524
  expectedAlg,
6999
7525
  keyId,
7000
7526
  loaPublicKeyPem,
7001
- requireLoa = Boolean(loaPublicKeyPem),
7527
+ requireLoa = true,
7528
+ loaPublicKeyBaseUrl,
7002
7529
  confirm,
7530
+ partnerId: configuredPartnerId,
7003
7531
  onUpdate,
7004
7532
  onVerify,
7005
7533
  onAccountVerify,
7006
7534
  onTest,
7007
7535
  timestampToleranceSecs = 300,
7536
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
7008
7537
  idempotencyStore,
7009
7538
  acceptedUpdateTypes: acceptedUpdateTypesRaw,
7010
7539
  allowedCallbackHosts
@@ -7018,6 +7547,9 @@ function createOneAddressHandler(options) {
7018
7547
  `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
7019
7548
  );
7020
7549
  }
7550
+ if (typeof maxBodyBytes !== "number" || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes <= 0) {
7551
+ throw new Error(`[OneAddress SDK] maxBodyBytes must be a positive whole number of bytes, got ${String(maxBodyBytes)}`);
7552
+ }
7021
7553
  if (webhookSecretGraceUntil !== void 0) {
7022
7554
  const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
7023
7555
  if (Number.isNaN(until)) {
@@ -7027,6 +7559,15 @@ function createOneAddressHandler(options) {
7027
7559
  if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
7028
7560
  throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
7029
7561
  }
7562
+ if (typeof requireLoa !== "boolean") {
7563
+ throw new Error(`[OneAddress SDK] requireLoa must be true or false, got ${String(requireLoa)}`);
7564
+ }
7565
+ if (loaPublicKeyBaseUrl !== void 0) resolveAppOrigin(loaPublicKeyBaseUrl, "loaPublicKeyBaseUrl");
7566
+ async function loaVerificationKey() {
7567
+ if (loaPublicKeyPem) return loaPublicKeyPem;
7568
+ if (!requireLoa) return void 0;
7569
+ return cachedLoaPublicKey(loaPublicKeyBaseUrl ?? OA_APP_BASE_URL2);
7570
+ }
7030
7571
  function enforceLoaPresence(body) {
7031
7572
  const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
7032
7573
  if (present) return;
@@ -7039,7 +7580,7 @@ function createOneAddressHandler(options) {
7039
7580
  warnedConsentUnverified = true;
7040
7581
  console.warn(
7041
7582
  // NOSONAR - intentional SDK diagnostic, not user-controlled data
7042
- "[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."
7583
+ "[OneAddress SDK] a dispatch arrived with no loa_encrypted and requireLoa is off, so consent for this update is UNVERIFIED. Remove requireLoa: false (it is on by default) to refuse such dispatches. Logged once per process."
7043
7584
  );
7044
7585
  }
7045
7586
  }
@@ -7074,9 +7615,9 @@ function createOneAddressHandler(options) {
7074
7615
  const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
7075
7616
  const customer = {
7076
7617
  email: "",
7077
- name: data.verified_name ?? "",
7078
- account_number: data.account_number ?? null,
7079
- known_names: Array.isArray(data.known_names) ? data.known_names : []
7618
+ name: stringOr(data.verified_name, ""),
7619
+ account_number: stringOr(data.account_number, null),
7620
+ known_names: stringsOf(data.known_names)
7080
7621
  };
7081
7622
  let loa;
7082
7623
  let loa_ref;
@@ -7088,12 +7629,25 @@ function createOneAddressHandler(options) {
7088
7629
  expectedAlg
7089
7630
  );
7090
7631
  loa_ref = d5LoaRef(loa);
7091
- if (loaPublicKeyPem) {
7092
- const valid = await verifyD5LOA(loa, loaPublicKeyPem);
7632
+ const loaKey = await loaVerificationKey();
7633
+ if (loaKey) {
7634
+ const valid = await verifyD5LOA(loa, loaKey);
7093
7635
  if (!valid) throw new Error("D5 LOA signature verification failed");
7094
7636
  }
7095
7637
  assertLoaBoundToEnvelope(loa, data.update_uid);
7638
+ if (hasLoaV2(loa)) {
7639
+ const refusal = await checkLoaV2(loa, {
7640
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7641
+ updateId: body.update_id,
7642
+ envelope: body.session_envelope,
7643
+ envelopeVerifiedName: data.verified_name,
7644
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7645
+ });
7646
+ if (refusal) throw new LoaV2RefusedError(refusal);
7647
+ customer.known_names = typedAliasesOf(loa);
7648
+ }
7096
7649
  }
7650
+ assertEffectiveDateBound(data.effective_date, body.effective_date);
7097
7651
  return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
7098
7652
  }
7099
7653
  function isD5Body(body) {
@@ -7108,7 +7662,13 @@ function createOneAddressHandler(options) {
7108
7662
  return Array.isArray(siblings) && siblings.includes(keyId);
7109
7663
  }
7110
7664
  return async function handler(req) {
7111
- const rawBody = await req.text();
7665
+ const rawBody = await readBodyCapped(req, maxBodyBytes);
7666
+ if (rawBody === null) {
7667
+ return new Response(JSON.stringify({ error: "Payload too large" }), {
7668
+ status: 413,
7669
+ headers: { "Content-Type": "application/json" }
7670
+ });
7671
+ }
7112
7672
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
7113
7673
  const tsHeader = req.headers.get("x-oneaddress-timestamp") ?? "";
7114
7674
  if (!isFreshTimestamp(tsHeader, timestampToleranceSecs)) {
@@ -7157,6 +7717,8 @@ function createOneAddressHandler(options) {
7157
7717
  if (isCrossoverSiblingToSkip(body)) {
7158
7718
  return declared(200, { ok: true, skipped: true, crossover: true });
7159
7719
  }
7720
+ let claimed = false;
7721
+ let completed = false;
7160
7722
  if (dispatchId) {
7161
7723
  if (!idempotencyStore) {
7162
7724
  const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
@@ -7177,6 +7739,17 @@ function createOneAddressHandler(options) {
7177
7739
  if (claim === "duplicate") {
7178
7740
  return declared(200, { ok: true, duplicate: true });
7179
7741
  }
7742
+ if (claim === "in-progress") {
7743
+ return new Response(JSON.stringify({
7744
+ error: "dispatch_in_progress",
7745
+ detail: "Another delivery of this dispatch is being processed. Retry later.",
7746
+ accepted_update_types: acceptedUpdateTypes
7747
+ }), {
7748
+ status: 503,
7749
+ headers: { "Content-Type": "application/json", "Retry-After": String(IN_PROGRESS_RETRY_AFTER_SECS) }
7750
+ });
7751
+ }
7752
+ claimed = true;
7180
7753
  } else {
7181
7754
  const alreadySeen = await idempotencyStore.has(dispatchId);
7182
7755
  if (alreadySeen) {
@@ -7190,6 +7763,12 @@ function createOneAddressHandler(options) {
7190
7763
  let event;
7191
7764
  enforceLoaPresence(body);
7192
7765
  if (isD5Body(body)) {
7766
+ if (body.effective_date !== void 0 && !isIsoDate(body.effective_date)) {
7767
+ return declared(400, {
7768
+ error: "invalid_effective_date",
7769
+ detail: "effective_date must be a YYYY-MM-DD calendar date. Nothing was processed."
7770
+ });
7771
+ }
7193
7772
  let d5;
7194
7773
  try {
7195
7774
  d5 = await buildD5Pieces(body, partnerId);
@@ -7241,6 +7820,7 @@ function createOneAddressHandler(options) {
7241
7820
  loa: d5.loa,
7242
7821
  loa_ref: d5.loa_ref,
7243
7822
  id_verification: body.id_verification,
7823
+ ...body.effective_date !== void 0 ? { effective_date: body.effective_date } : {},
7244
7824
  raw: d5.raw
7245
7825
  };
7246
7826
  } else {
@@ -7272,16 +7852,27 @@ function createOneAddressHandler(options) {
7272
7852
  expectedAlg
7273
7853
  );
7274
7854
  loa_ref = d5LoaRef(loa);
7275
- if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
7855
+ const loaKey = await loaVerificationKey();
7856
+ if (loaKey && !await verifyD5LOA(loa, loaKey)) {
7276
7857
  throw new Error("D5 LOA signature verification failed");
7277
7858
  }
7278
7859
  assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
7860
+ if (hasLoaV2(loa)) {
7861
+ const refusal = await checkLoaV2(loa, {
7862
+ partnerId: configuredPartnerId ?? confirm?.partnerId ?? partnerId,
7863
+ updateId: body.update_id,
7864
+ envelope: encrypted,
7865
+ envelopeVerifiedName: rawAddress.fullName,
7866
+ ...loaKey ? { publicKeyPem: loaKey } : {}
7867
+ });
7868
+ if (refusal) throw new LoaV2RefusedError(refusal);
7869
+ }
7279
7870
  }
7280
7871
  const customer = {
7281
7872
  email: "",
7282
- name: rawAddress.fullName ?? "",
7283
- account_number: rawAddress.accountReference ?? null,
7284
- known_names: Array.isArray(rawAddress.knownNames) ? rawAddress.knownNames : []
7873
+ name: stringOr(rawAddress.fullName, ""),
7874
+ account_number: stringOr(rawAddress.accountReference, null),
7875
+ known_names: loa && hasLoaV2(loa) ? typedAliasesOf(loa) : stringsOf(rawAddress.knownNames)
7285
7876
  };
7286
7877
  event = {
7287
7878
  event: "address.updated",
@@ -7293,7 +7884,8 @@ function createOneAddressHandler(options) {
7293
7884
  customer,
7294
7885
  // The legacy blob predates kinds and always carries an address.
7295
7886
  update_types: ["address"],
7296
- address: validateAddress(rawAddress),
7887
+ // Six named fields, never the blob: see validateAddress.
7888
+ address: legacyAddressOf(rawAddress, body),
7297
7889
  loa,
7298
7890
  loa_ref,
7299
7891
  id_verification: body.id_verification,
@@ -7301,6 +7893,7 @@ function createOneAddressHandler(options) {
7301
7893
  };
7302
7894
  }
7303
7895
  const result = await onUpdate(event);
7896
+ completed = true;
7304
7897
  if (dispatchId && idempotencyStore) {
7305
7898
  const record = idempotencyStore.complete ? idempotencyStore.complete(dispatchId) : idempotencyStore.set(dispatchId);
7306
7899
  await record.catch(
@@ -7310,13 +7903,16 @@ function createOneAddressHandler(options) {
7310
7903
  }
7311
7904
  if (confirm && dispatchId) {
7312
7905
  const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
7906
+ const note = result && typeof result === "object" && typeof result.note === "string" ? result.note : void 0;
7313
7907
  void confirmUpdate({
7314
7908
  partnerId: confirm.partnerId,
7315
7909
  secret: confirm.confirmSecret,
7316
7910
  dispatchId,
7317
7911
  status,
7912
+ ...note !== void 0 ? { note } : {},
7318
7913
  loaRef: event.loa_ref,
7319
7914
  ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
7915
+ ...confirm.allowedHosts ? { allowedHosts: confirm.allowedHosts } : {},
7320
7916
  ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
7321
7917
  }).then(
7322
7918
  (r) => {
@@ -7353,7 +7949,7 @@ function createOneAddressHandler(options) {
7353
7949
  user_id: body.user_id ?? "",
7354
7950
  customer: body.customer,
7355
7951
  customer_match: body.customer_match,
7356
- address: validateAddress(rawAddress),
7952
+ address: legacyAddressOf(rawAddress, body),
7357
7953
  loa: body.loa,
7358
7954
  id_verification: body.id_verification,
7359
7955
  raw: rawAddress
@@ -7392,10 +7988,10 @@ function createOneAddressHandler(options) {
7392
7988
  partnerId
7393
7989
  );
7394
7990
  customer = {
7395
- email: raw.email ?? "",
7396
- name: raw.name ?? "",
7397
- account_number: raw.account_number ?? null,
7398
- known_names: Array.isArray(raw.known_names) ? raw.known_names : []
7991
+ email: stringOr(raw.email, ""),
7992
+ name: stringOr(raw.name, ""),
7993
+ account_number: stringOr(raw.account_number, null),
7994
+ known_names: stringsOf(raw.known_names)
7399
7995
  };
7400
7996
  } else {
7401
7997
  customer = body.customer ?? {};
@@ -7482,6 +8078,13 @@ function createOneAddressHandler(options) {
7482
8078
  status: 500,
7483
8079
  headers: { "Content-Type": "application/json" }
7484
8080
  });
8081
+ } finally {
8082
+ if (claimed && !completed && idempotencyStore?.release) {
8083
+ await idempotencyStore.release(dispatchId).catch(
8084
+ (err) => console.error("[OneAddress SDK] idempotency release failed:", err)
8085
+ // NOSONAR
8086
+ );
8087
+ }
7485
8088
  }
7486
8089
  };
7487
8090
  }
@@ -7541,6 +8144,9 @@ async function buildSignedTestWebhook(opts2) {
7541
8144
  account_number: "TEST-0001",
7542
8145
  id_verification_ref: import_crypto2.default.randomUUID(),
7543
8146
  known_names: [],
8147
+ // Sealed beside the body copy, as the relay's pay step does, so a
8148
+ // rehearsed scheduled move passes the handler's binding check.
8149
+ ...opts2.effectiveDate !== void 0 ? { effective_date: opts2.effectiveDate } : {},
7544
8150
  ...opts2.session ?? {}
7545
8151
  };
7546
8152
  const envelope = await encryptSessionForPartner(sessionData, partnerKey);
@@ -7555,6 +8161,10 @@ async function buildSignedTestWebhook(opts2) {
7555
8161
  oneaddress_acn: "696 078 869",
7556
8162
  oneaddress_signature: "00".repeat(64),
7557
8163
  signature_algorithm: "ECDSA-P256",
8164
+ partner_id: opts2.partnerId,
8165
+ envelope_sha256: loaEnvelopeSha256(envelope.session_envelope),
8166
+ consumer_typed_aliases: acceptTypedAliases(sessionData.verified_name, sessionData.known_names ?? []),
8167
+ oneaddress_signature_v2: "00".repeat(64),
7558
8168
  ...opts2.loa ?? {}
7559
8169
  };
7560
8170
  if (opts2.loaSigningKeyPem) {
@@ -7565,12 +8175,19 @@ async function buildSignedTestWebhook(opts2) {
7565
8175
  false,
7566
8176
  ["sign"]
7567
8177
  );
7568
- const sig2 = await import_crypto2.default.subtle.sign(
8178
+ const signHex = async (text) => Buffer.from(await import_crypto2.default.subtle.sign(
7569
8179
  { name: "ECDSA", hash: "SHA-256" },
7570
8180
  key,
7571
- new TextEncoder().encode(canonicalD5LoaForm(loa))
7572
- );
7573
- loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
8181
+ new TextEncoder().encode(text)
8182
+ )).toString("hex");
8183
+ loa.oneaddress_signature = await signHex(canonicalD5LoaForm(loa));
8184
+ let v2Text;
8185
+ try {
8186
+ v2Text = canonicalD5LoaFormV2(loa);
8187
+ } catch {
8188
+ v2Text = null;
8189
+ }
8190
+ if (hasLoaV2(loa) && v2Text !== null) loa.oneaddress_signature_v2 = await signHex(v2Text);
7574
8191
  }
7575
8192
  const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
7576
8193
  loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
@@ -7592,9 +8209,9 @@ async function buildSignedTestWebhook(opts2) {
7592
8209
  key_share_expiry: keyShareExpiryIso(new Date(nowSecs * 1e3), opts2.retentionPeriodDays),
7593
8210
  id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
7594
8211
  ...loa_encrypted ? { loa_encrypted } : {},
8212
+ ...opts2.effectiveDate !== void 0 ? { effective_date: opts2.effectiveDate } : {},
7595
8213
  // On the wire with a `null` value when no PaymentIntent backed the update,
7596
8214
  // so the KEY is present either way.
7597
- stripe_session_id: opts2.stripeSessionId ?? null,
7598
8215
  // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
7599
8216
  // by default. A test that needs them passes them through `extraBody`, which
7600
8217
  // is exactly the circumstance the relay emits them in.
@@ -7628,12 +8245,28 @@ async function buildSignedTestWebhook(opts2) {
7628
8245
  // Annotate the CommonJS export names for ESM import in node:
7629
8246
  0 && (module.exports = {
7630
8247
  CURRENT_VERSION,
8248
+ DEFAULT_IDEMPOTENCY_LEASE_SECS,
8249
+ DEFAULT_MAX_BODY_BYTES,
7631
8250
  DEFAULT_REPLAY_WINDOW_SECS,
8251
+ EffectiveDateMismatchError,
8252
+ LOA_MAX_TYPED_ALIASES,
8253
+ LOA_MIN_SHORT_FORM_LETTERS,
8254
+ LOA_PUBLIC_KEY_CACHE_MS,
8255
+ LOA_V2_REFUSALS,
8256
+ LoaPublicKeyUnavailableError,
8257
+ LoaV2RefusedError,
8258
+ MAX_ADDRESS_FIELD_CHARS,
7632
8259
  OUTBOX_LEASE_COLUMNS,
7633
8260
  SUPPORTED_VERSIONS,
8261
+ _resetLoaKeyCacheForTests,
7634
8262
  _resetOnceWarningsForTests,
8263
+ acceptTypedAliases,
8264
+ assertEffectiveDateBound,
7635
8265
  buildSignedTestWebhook,
8266
+ cachedLoaPublicKey,
7636
8267
  canonicalD5LoaForm,
8268
+ canonicalD5LoaFormV2,
8269
+ checkLoaV2,
7637
8270
  checkRegistryHead,
7638
8271
  compareAddresses,
7639
8272
  computeBlindIndex,
@@ -7650,9 +8283,16 @@ async function buildSignedTestWebhook(opts2) {
7650
8283
  findMatchingStoredName,
7651
8284
  formatAddressParts,
7652
8285
  fromOutboxTimestamp,
8286
+ hasLoaV2,
8287
+ isAcceptableAlias,
7653
8288
  isEmailLike,
7654
8289
  isFreshTimestamp,
8290
+ loaEnvelopeSha256,
8291
+ loaFirstName,
8292
+ loaNamesMatch,
8293
+ loaSurname,
7655
8294
  namePoolMatches,
8295
+ normaliseLoaName,
7656
8296
  normalizeForBlindIndex,
7657
8297
  parsePinnedRegistryRoots,
7658
8298
  readAddressParts,
@@ -7663,9 +8303,11 @@ async function buildSignedTestWebhook(opts2) {
7663
8303
  transform,
7664
8304
  transformAddress,
7665
8305
  transformSession,
8306
+ typedAliasesOf,
7666
8307
  validateAddress,
7667
8308
  verify,
7668
8309
  verifyD5LOA,
8310
+ verifyD5LOAv2,
7669
8311
  verifyGrace,
7670
8312
  verifyLOA,
7671
8313
  verifySignature,