@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.
@@ -1,7 +1,9 @@
1
1
  import {
2
+ encryptEnvelopeForPartner,
3
+ encryptSessionForPartner,
2
4
  isFreshTimestamp,
3
5
  isSafeWebhookUrl
4
- } from "./chunk-O2D5XGSN.mjs";
6
+ } from "./chunk-LIHXDUUA.mjs";
5
7
 
6
8
  // src/index.ts
7
9
  import crypto from "crypto";
@@ -10,6 +12,45 @@ import crypto from "crypto";
10
12
  var CURRENT_VERSION = "2026.1";
11
13
  var SUPPORTED_VERSIONS = ["2026.1"];
12
14
 
15
+ // ../protocol/src/d5-body.ts
16
+ var D5_BODY_ALWAYS = [
17
+ "event",
18
+ "id_verification",
19
+ "key_share_expiry",
20
+ "oneaddress_version",
21
+ "partner_id",
22
+ "session_envelope",
23
+ "session_key_share",
24
+ "stripe_session_id",
25
+ "timestamp",
26
+ "update_id",
27
+ "user_id"
28
+ ];
29
+ var D5_BODY_CONDITIONAL = {
30
+ /**
31
+ * The signed Letter of Authority, sealed to the same key_id as the session.
32
+ * Present whenever the partner has a usable key — i.e. on every dispatch a
33
+ * live partner receives. Omitted best-effort when no key is available, which
34
+ * is a state a live partner is never in.
35
+ */
36
+ loa_encrypted: "partner has a usable encryption key",
37
+ /**
38
+ * The shared webhook event id. Set ONLY on a key-crossover copy, where every
39
+ * copy of one update carries the same id so a receiver holding more than one
40
+ * rotation key applies it once. Absent on an ordinary dispatch, whose
41
+ * receiver idempotency falls back to the `X-OneAddress-Dispatch` header.
42
+ */
43
+ id: "key-crossover copy only",
44
+ /** The sibling marker naming the other key_ids this update was sealed to. */
45
+ crossover_key_ids: "key-crossover copy only"
46
+ };
47
+ var D5_BODY_DRILL_ONLY = ["conformance"];
48
+ var D5_BODY_ALL_ALLOWED = [
49
+ ...D5_BODY_ALWAYS,
50
+ ...Object.keys(D5_BODY_CONDITIONAL),
51
+ ...D5_BODY_DRILL_ONLY
52
+ ];
53
+
13
54
  // ../name-match/src/index.ts
14
55
  function isEmailLike(value) {
15
56
  return value.includes("@");
@@ -132,9 +173,17 @@ function createOutboxConsumer(opts) {
132
173
  if (!Number.isFinite(batchSize) || batchSize < 1) {
133
174
  throw new Error(`[OneAddress SDK] batchSize must be a positive integer, got ${opts.batchSize}`);
134
175
  }
176
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 0) {
177
+ throw new Error(`[OneAddress SDK] maxAttempts must be an integer >= 0, got ${opts.maxAttempts}`);
178
+ }
135
179
  const ph = d.ph;
136
180
  const token = () => randomBytes(16).toString("hex");
137
181
  const stamp = (at) => toOutboxTimestamp(dialect, at);
182
+ const heldTokens = /* @__PURE__ */ new Map();
183
+ const claimPredicate = (dispatchId, firstPh) => {
184
+ const tok = heldTokens.get(dispatchId);
185
+ return tok === void 0 ? { sql: `dispatch_id = ${ph(firstPh)}`, params: [dispatchId] } : { sql: `dispatch_id = ${ph(firstPh)} AND ${CLAIM_TOKEN} = ${ph(firstPh + 1)}`, params: [dispatchId, tok] };
186
+ };
138
187
  const claimable = (cutoffPh) => `written_at IS NOT NULL AND processed_at IS NULL AND (${CLAIMED_AT} IS NULL OR ${CLAIMED_AT} < ${cutoffPh})` + (maxAttempts > 0 ? ` AND (${ATTEMPTS} IS NULL OR ${ATTEMPTS} < ${maxAttempts})` : "");
139
188
  const toRow = (r) => ({
140
189
  dispatchId: String(r.dispatch_id ?? r.dispatchId ?? ""),
@@ -142,6 +191,10 @@ function createOutboxConsumer(opts) {
142
191
  attempts: Number(r[ATTEMPTS] ?? 0) || 0,
143
192
  fields: r
144
193
  });
194
+ const claimed = (rows, tok) => rows.map(toRow).map((row) => {
195
+ heldTokens.set(row.dispatchId, tok);
196
+ return row;
197
+ });
145
198
  async function claimBatch() {
146
199
  const at = now();
147
200
  const claimedAt = stamp(at);
@@ -152,14 +205,14 @@ function createOutboxConsumer(opts) {
152
205
  `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize} FOR UPDATE SKIP LOCKED) RETURNING *`,
153
206
  [claimedAt, tok, cutoff]
154
207
  );
155
- return rows2.map(toRow);
208
+ return claimed(rows2, tok);
156
209
  }
157
210
  if (dialect === "mssql") {
158
211
  const rows2 = await opts.query(
159
212
  `UPDATE TOP (${batchSize}) ${table} WITH (UPDLOCK, READPAST, ROWLOCK) SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} OUTPUT INSERTED.* WHERE ${claimable(ph(3))}`,
160
213
  [claimedAt, tok, cutoff]
161
214
  );
162
- return rows2.map(toRow);
215
+ return claimed(rows2, tok);
163
216
  }
164
217
  const claim = dialect === "mysql" ? `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize}` : `UPDATE ${table} SET ${CLAIMED_AT} = ${ph(1)}, ${CLAIM_TOKEN} = ${ph(2)} WHERE dispatch_id IN (SELECT dispatch_id FROM ${table} WHERE ${claimable(ph(3))} ORDER BY received_at LIMIT ${batchSize})`;
165
218
  await opts.query(claim, [claimedAt, tok, cutoff]);
@@ -167,7 +220,7 @@ function createOutboxConsumer(opts) {
167
220
  `SELECT * FROM ${table} WHERE ${CLAIM_TOKEN} = ${ph(1)} AND processed_at IS NULL`,
168
221
  [tok]
169
222
  );
170
- return rows.map(toRow);
223
+ return claimed(rows, tok);
171
224
  }
172
225
  return {
173
226
  async ensureSchema() {
@@ -196,23 +249,29 @@ function createOutboxConsumer(opts) {
196
249
  },
197
250
  claimBatch,
198
251
  async markProcessed(dispatchId) {
252
+ const where = claimPredicate(dispatchId, 2);
199
253
  await opts.query(
200
- `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
201
- [stamp(now()), dispatchId]
254
+ `UPDATE ${table} SET processed_at = ${ph(1)}, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
255
+ [stamp(now()), ...where.params]
202
256
  );
257
+ heldTokens.delete(dispatchId);
203
258
  },
204
259
  async markFailed(dispatchId, error) {
205
260
  const message = error instanceof Error ? error.message : String(error);
261
+ const where = claimPredicate(dispatchId, 2);
206
262
  await opts.query(
207
- `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(2)}`,
208
- [message.slice(0, 500), dispatchId]
263
+ `UPDATE ${table} SET processing_error = ${ph(1)}, ${ATTEMPTS} = COALESCE(${ATTEMPTS}, 0) + 1, ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
264
+ [message.slice(0, 500), ...where.params]
209
265
  );
266
+ heldTokens.delete(dispatchId);
210
267
  },
211
268
  async release(dispatchId) {
269
+ const where = claimPredicate(dispatchId, 1);
212
270
  await opts.query(
213
- `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE dispatch_id = ${ph(1)}`,
214
- [dispatchId]
271
+ `UPDATE ${table} SET ${CLAIMED_AT} = NULL, ${CLAIM_TOKEN} = NULL WHERE ${where.sql}`,
272
+ where.params
215
273
  );
274
+ heldTokens.delete(dispatchId);
216
275
  },
217
276
  async process(handler) {
218
277
  const rows = await claimBatch();
@@ -253,15 +312,62 @@ function createOutboxConsumer(opts) {
253
312
  }
254
313
 
255
314
  // src/index.ts
315
+ var IDEMPOTENCY_DIALECTS = ["postgres", "sqlite", "mysql", "mssql"];
256
316
  function createSqlIdempotencyStore(opts) {
257
317
  const table = opts.table ?? "oneaddress_dispatches";
258
- const ph = opts.placeholder ?? ((n) => `$${n}`);
318
+ const dialect = opts.dialect ?? "postgres";
319
+ if (!IDEMPOTENCY_DIALECTS.includes(dialect)) {
320
+ throw new Error(
321
+ `[OneAddress SDK] createSqlIdempotencyStore: unknown dialect "${dialect}". Supported: ${IDEMPOTENCY_DIALECTS.join(", ")}.`
322
+ );
323
+ }
324
+ const defaultPh = dialect === "postgres" ? (n) => `$${n}` : dialect === "mssql" ? (n) => `@p${n}` : () => "?";
325
+ const ph = opts.placeholder ?? defaultPh;
259
326
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
260
327
  throw new Error(`[OneAddress SDK] invalid table name: ${table}`);
261
328
  }
262
329
  const completedOf = (row) => row?.completed_at ?? row?.completedAt ?? null;
330
+ const tokenOf = (row) => row?.claim_token ?? row?.claimToken ?? null;
331
+ async function claimByToken(dispatchId) {
332
+ const token = crypto.randomBytes(16).toString("hex");
333
+ await opts.query(
334
+ dialect === "mysql" ? `INSERT IGNORE INTO ${table} (dispatch_id, claim_token) VALUES (${ph(1)}, ${ph(2)})` : `INSERT INTO ${table} (dispatch_id, claim_token) SELECT ${ph(1)}, ${ph(2)} WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
335
+ [dispatchId, token]
336
+ );
337
+ const rows = await opts.query(
338
+ `SELECT claim_token, completed_at FROM ${table} WHERE dispatch_id = ${ph(1)}`,
339
+ [dispatchId]
340
+ );
341
+ if (tokenOf(rows[0]) === token) return "fresh";
342
+ return completedOf(rows[0]) ? "duplicate" : "retry-after-incomplete";
343
+ }
344
+ async function setByUpsert(dispatchId) {
345
+ if (dialect === "mysql") {
346
+ await opts.query(
347
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE completed_at = CURRENT_TIMESTAMP`,
348
+ [dispatchId]
349
+ );
350
+ return;
351
+ }
352
+ if (dialect === "mssql") {
353
+ await opts.query(
354
+ `UPDATE ${table} SET completed_at = CURRENT_TIMESTAMP WHERE dispatch_id = ${ph(1)}`,
355
+ [dispatchId]
356
+ );
357
+ await opts.query(
358
+ `INSERT INTO ${table} (dispatch_id, completed_at) SELECT ${ph(1)}, CURRENT_TIMESTAMP WHERE NOT EXISTS (SELECT 1 FROM ${table} WHERE dispatch_id = ${ph(1)})`,
359
+ [dispatchId]
360
+ );
361
+ return;
362
+ }
363
+ await opts.query(
364
+ `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
365
+ [dispatchId]
366
+ );
367
+ }
263
368
  return {
264
369
  async claim(dispatchId) {
370
+ if (dialect === "mysql" || dialect === "mssql") return claimByToken(dispatchId);
265
371
  const inserted = await opts.query(
266
372
  `INSERT INTO ${table} (dispatch_id) VALUES (${ph(1)}) ON CONFLICT (dispatch_id) DO NOTHING RETURNING dispatch_id`,
267
373
  [dispatchId]
@@ -289,10 +395,7 @@ function createSqlIdempotencyStore(opts) {
289
395
  return rows.length > 0 && Boolean(completedOf(rows[0]));
290
396
  },
291
397
  async set(dispatchId) {
292
- await opts.query(
293
- `INSERT INTO ${table} (dispatch_id, completed_at) VALUES (${ph(1)}, CURRENT_TIMESTAMP) ON CONFLICT (dispatch_id) DO UPDATE SET completed_at = CURRENT_TIMESTAMP`,
294
- [dispatchId]
295
- );
398
+ await setByUpsert(dispatchId);
296
399
  }
297
400
  };
298
401
  }
@@ -318,7 +421,8 @@ function verifyWithGrace(rawBody, timestamp, signature, currentSecret, previousS
318
421
  function base64urlToBuffer(b64) {
319
422
  return Buffer.from(b64.replace(/-/g, "+").replace(/_/g, "/"), "base64");
320
423
  }
321
- function pemToBase64(pem) {
424
+ function pemToBase64(pemRaw) {
425
+ const pem = pemRaw.replace(/(?:\\r)?\\n/g, "\n");
322
426
  const begin = pem.indexOf("-----BEGIN");
323
427
  if (begin === -1) return pem.replace(/\s/g, "");
324
428
  const armourEnd = pem.indexOf("-----", begin + "-----BEGIN".length);
@@ -378,13 +482,14 @@ async function decryptAddress(payload, privateKeyPem, partnerId) {
378
482
  );
379
483
  return JSON.parse(new TextDecoder().decode(plaintext));
380
484
  }
381
- async function decryptSession(share, envelopeB64, privateKeyPem, partnerId) {
382
- const { decryptSession: decryptSessionCrypto } = await import("./src-UOJOUUGB.mjs");
485
+ async function decryptSession(share, envelopeB64, privateKeyPem, partnerId, expectedAlg) {
486
+ const { decryptSession: decryptSessionCrypto } = await import("./src-ENJJ6YZU.mjs");
383
487
  return decryptSessionCrypto(
384
488
  share,
385
489
  envelopeB64,
386
490
  typeof privateKeyPem === "string" ? pemToBase64(privateKeyPem) : privateKeyPem,
387
- partnerId
491
+ partnerId,
492
+ expectedAlg
388
493
  );
389
494
  }
390
495
  async function transformAddress(payload, privateKeyPem, partnerId, recipientSpkiPem) {
@@ -525,6 +630,10 @@ async function fetchLoaPublicKey(appBaseUrl = OA_APP_BASE_URL) {
525
630
  `[OneAddress SDK] fetchLoaPublicKey: appBaseUrl host must be one of: ${[...allowedHosts].join(", ")}`
526
631
  );
527
632
  }
633
+ const loopback = parsedBase.hostname === "localhost" || parsedBase.hostname === "127.0.0.1";
634
+ if (parsedBase.protocol !== "https:" && !loopback) {
635
+ throw new Error("[OneAddress SDK] fetchLoaPublicKey: appBaseUrl must use https (plain http is accepted for localhost only)");
636
+ }
528
637
  const url = `${parsedBase.origin}/.well-known/oneaddress-loa-key.pem`;
529
638
  const res = await fetch(url);
530
639
  if (!res.ok) {
@@ -601,12 +710,13 @@ async function verifyD5LOA(loa, publicKeyPem) {
601
710
  return false;
602
711
  }
603
712
  }
604
- async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId) {
713
+ async function decryptLoaEncrypted(loaEncrypted, privateKeyPem, partnerId, expectedAlg) {
605
714
  const data = await decryptSession(
606
715
  loaEncrypted.session_key_share,
607
716
  loaEncrypted.session_envelope,
608
717
  privateKeyPem,
609
- partnerId
718
+ partnerId,
719
+ expectedAlg
610
720
  );
611
721
  return data;
612
722
  }
@@ -716,12 +826,32 @@ function compareAddresses(a, b) {
716
826
  if (aCountry && bCountry && aCountry !== bCountry) return false;
717
827
  return true;
718
828
  }
829
+ function isAllowedCallbackHost(raw, extraHosts) {
830
+ let host;
831
+ try {
832
+ const u = new URL(raw);
833
+ if (u.protocol !== "https:") return false;
834
+ host = u.hostname.toLowerCase();
835
+ } catch {
836
+ return false;
837
+ }
838
+ if (host === "oneaddress.io" || host.endsWith(".oneaddress.io")) return true;
839
+ const envRaw = typeof process !== "undefined" ? process.env?.OA_CALLBACK_HOST_ALLOWLIST ?? "" : "";
840
+ const allowed = [
841
+ ...envRaw.split(",").map((h) => h.trim().toLowerCase()),
842
+ ...(extraHosts ?? []).map((h) => h.trim().toLowerCase())
843
+ ].filter(Boolean);
844
+ return allowed.includes(host);
845
+ }
719
846
  async function sendVerifyResult(params) {
720
- const { callbackUrl, callbackToken, batchId, partnerId, match, note } = params;
847
+ const { callbackUrl, callbackToken, batchId, partnerId, match, note, allowedCallbackHosts } = params;
721
848
  const safe = isSafeWebhookUrl(callbackUrl);
722
849
  if (!safe.ok) {
723
850
  throw new Error(`[OneAddress SDK] refusing verify-result callback to unsafe URL: ${safe.reason}`);
724
851
  }
852
+ if (!isAllowedCallbackHost(callbackUrl, allowedCallbackHosts)) {
853
+ throw new Error(`[OneAddress SDK] refusing verify-result callback to non-OneAddress host: ${callbackUrl}`);
854
+ }
725
855
  const res = await fetch(callbackUrl, {
726
856
  method: "POST",
727
857
  headers: { "Content-Type": "application/json" },
@@ -738,33 +868,159 @@ async function sendVerifyResult(params) {
738
868
  throw new Error(`[OneAddress SDK] verify-result callback to ${callbackUrl} failed: HTTP ${res.status}`);
739
869
  }
740
870
  }
741
- var HANDLED_EVENTS = ["address.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
871
+ var UPDATE_TYPE_ORDER = ["address", "phone", "email"];
872
+ function normaliseAcceptedUpdateTypes(raw) {
873
+ const kept = new Set(Array.isArray(raw) ? raw.filter((v) => typeof v === "string") : []);
874
+ return UPDATE_TYPE_ORDER.filter((t) => t === "address" || kept.has(t));
875
+ }
876
+ function readUpdateTypes(raw) {
877
+ if (raw === void 0 || raw === null) return ["address"];
878
+ if (!Array.isArray(raw)) return null;
879
+ if (raw.length === 0) return ["address"];
880
+ const out = [];
881
+ for (const v of raw) {
882
+ if (typeof v !== "string" || !UPDATE_TYPE_ORDER.includes(v)) return null;
883
+ if (!out.includes(v)) out.push(v);
884
+ }
885
+ return out;
886
+ }
887
+ var InvalidUpdateTypesError = class extends Error {
888
+ constructor(raw) {
889
+ super("[OneAddress SDK] update_types names a kind this build does not know");
890
+ this.raw = raw;
891
+ this.name = "InvalidUpdateTypesError";
892
+ }
893
+ };
894
+ function requireContactValue(kind, value) {
895
+ if (typeof value !== "string" || value === "") {
896
+ throw new Error(
897
+ `[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.`
898
+ );
899
+ }
900
+ return value;
901
+ }
902
+ var HANDLED_EVENTS = ["address.updated", "contact.updated", "address.verify", "account.verify", "address.test", "address.test-dispatch"];
742
903
  var warnedUnhandledEvents = /* @__PURE__ */ new Set();
904
+ var warnedConsentUnverified = false;
905
+ var warnedNoIdempotencyStore = false;
906
+ function _resetOnceWarningsForTests() {
907
+ warnedConsentUnverified = false;
908
+ warnedNoIdempotencyStore = false;
909
+ }
910
+ var MAX_TIMESTAMP_TOLERANCE_SECS = 86400;
911
+ var XWING_SEED_BYTES = 32;
912
+ function assertUsablePrivateKey(privateKeyPem) {
913
+ if (typeof privateKeyPem !== "string") {
914
+ if (!privateKeyPem || typeof privateKeyPem !== "object" || typeof privateKeyPem.name !== "string") {
915
+ throw new Error("[OneAddress SDK] privateKeyPem must be a PEM string or a PrivateKeyOperations delegate");
916
+ }
917
+ return;
918
+ }
919
+ if (privateKeyPem.trim() === "") {
920
+ throw new Error("[OneAddress SDK] privateKeyPem is required: set it to your PKCS#8 private key from the Partner Portal");
921
+ }
922
+ const der = pemToBuffer(privateKeyPem);
923
+ if (der.length === XWING_SEED_BYTES) return;
924
+ try {
925
+ crypto.createPrivateKey({ key: der, format: "der", type: "pkcs8" });
926
+ } catch (err) {
927
+ const refused = new Error(
928
+ `[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.`
929
+ );
930
+ refused.cause = err;
931
+ throw refused;
932
+ }
933
+ }
934
+ function requirePemFor(purpose, key) {
935
+ if (typeof key === "string") return key;
936
+ throw new Error(
937
+ `[OneAddress SDK] ${purpose} needs the raw private key; a PrivateKeyOperations delegate ("${key.name}") covers session envelopes only`
938
+ );
939
+ }
940
+ function assertLoaBoundToEnvelope(loa, envelopeUpdateUid) {
941
+ if (typeof loa.update_uid !== "string" || typeof envelopeUpdateUid !== "string") return;
942
+ if (loa.update_uid !== envelopeUpdateUid) {
943
+ throw new Error(
944
+ "[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"
945
+ );
946
+ }
947
+ }
743
948
  function createOneAddressHandler(options) {
744
949
  const {
745
950
  webhookSecret,
746
951
  previousWebhookSecret,
747
952
  webhookSecretGraceUntil,
748
953
  privateKeyPem,
954
+ expectedAlg,
955
+ keyId,
749
956
  loaPublicKeyPem,
957
+ requireLoa = Boolean(loaPublicKeyPem),
958
+ confirm,
750
959
  onUpdate,
751
960
  onVerify,
752
961
  onAccountVerify,
753
962
  onTest,
754
963
  timestampToleranceSecs = 300,
755
- idempotencyStore
964
+ idempotencyStore,
965
+ acceptedUpdateTypes: acceptedUpdateTypesRaw,
966
+ allowedCallbackHosts
756
967
  } = options;
968
+ if (typeof webhookSecret !== "string" || webhookSecret === "") {
969
+ throw new Error("[OneAddress SDK] webhookSecret is required: an empty secret would verify no signature at all");
970
+ }
971
+ assertUsablePrivateKey(privateKeyPem);
972
+ if (typeof timestampToleranceSecs !== "number" || !Number.isFinite(timestampToleranceSecs) || timestampToleranceSecs <= 0 || timestampToleranceSecs > MAX_TIMESTAMP_TOLERANCE_SECS) {
973
+ throw new Error(
974
+ `[OneAddress SDK] timestampToleranceSecs must be a positive number of seconds up to ${MAX_TIMESTAMP_TOLERANCE_SECS}, got ${String(timestampToleranceSecs)}`
975
+ );
976
+ }
977
+ if (webhookSecretGraceUntil !== void 0) {
978
+ const until = typeof webhookSecretGraceUntil === "number" ? webhookSecretGraceUntil : Date.parse(webhookSecretGraceUntil);
979
+ if (Number.isNaN(until)) {
980
+ throw new Error(`[OneAddress SDK] webhookSecretGraceUntil is not a date: ${String(webhookSecretGraceUntil)}`);
981
+ }
982
+ }
983
+ if (confirm && (!confirm.partnerId || !confirm.confirmSecret)) {
984
+ throw new Error("[OneAddress SDK] confirm needs both partnerId and confirmSecret");
985
+ }
986
+ function enforceLoaPresence(body) {
987
+ const present = !!body.loa_encrypted && typeof body.loa_encrypted === "object";
988
+ if (present) return;
989
+ if (requireLoa) {
990
+ throw new Error(
991
+ "[OneAddress SDK] dispatch carries no loa_encrypted and requireLoa is on: refusing to apply an update whose consent proof is missing"
992
+ );
993
+ }
994
+ if (!warnedConsentUnverified) {
995
+ warnedConsentUnverified = true;
996
+ console.warn(
997
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
998
+ "[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."
999
+ );
1000
+ }
1001
+ }
1002
+ const acceptedUpdateTypes = normaliseAcceptedUpdateTypes(acceptedUpdateTypesRaw);
1003
+ function declared(status, payload) {
1004
+ return new Response(JSON.stringify({ ...payload, accepted_update_types: acceptedUpdateTypes }), {
1005
+ status,
1006
+ headers: { "Content-Type": "application/json" }
1007
+ });
1008
+ }
757
1009
  async function buildD5Pieces(body, partnerId) {
758
1010
  const share = body.session_key_share;
759
- const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId);
760
- const address = validateAddress({
1011
+ const data = await decryptSession(share, body.session_envelope, privateKeyPem, partnerId, expectedAlg);
1012
+ const updateTypes = readUpdateTypes(data.update_types);
1013
+ if (updateTypes === null) throw new InvalidUpdateTypesError(data.update_types);
1014
+ const address = updateTypes.includes("address") ? validateAddress({
761
1015
  street: data.new_address?.street,
762
1016
  suburb: data.new_address?.suburb,
763
1017
  state: data.new_address?.state,
764
1018
  postcode: data.new_address?.postcode,
765
1019
  country: data.new_address?.country,
766
1020
  updated_at: data.dispatch_timestamp ?? body.timestamp ?? ""
767
- });
1021
+ }) : void 0;
1022
+ const newPhone = updateTypes.includes("phone") ? requireContactValue("phone", data.new_phone) : void 0;
1023
+ const newEmail = updateTypes.includes("email") ? requireContactValue("email", data.new_email) : void 0;
768
1024
  const customer = {
769
1025
  email: "",
770
1026
  name: data.verified_name ?? "",
@@ -777,19 +1033,29 @@ function createOneAddressHandler(options) {
777
1033
  loa = await decryptLoaEncrypted(
778
1034
  body.loa_encrypted,
779
1035
  privateKeyPem,
780
- partnerId
1036
+ partnerId,
1037
+ expectedAlg
781
1038
  );
782
1039
  loa_ref = d5LoaRef(loa);
783
1040
  if (loaPublicKeyPem) {
784
1041
  const valid = await verifyD5LOA(loa, loaPublicKeyPem);
785
1042
  if (!valid) throw new Error("D5 LOA signature verification failed");
786
1043
  }
1044
+ assertLoaBoundToEnvelope(loa, data.update_uid);
787
1045
  }
788
- return { address, customer, loa, loa_ref, raw: data };
1046
+ return { updateTypes, address, newPhone, newEmail, customer, loa, loa_ref, raw: data };
789
1047
  }
790
1048
  function isD5Body(body) {
791
1049
  return typeof body.session_envelope === "string" && !!body.session_key_share && typeof body.session_key_share === "object";
792
1050
  }
1051
+ function isCrossoverSiblingToSkip(body) {
1052
+ if (!keyId || !isD5Body(body)) return false;
1053
+ const share = body.session_key_share;
1054
+ const shareKeyId = typeof share?.key_id === "string" ? share.key_id : "";
1055
+ if (!shareKeyId || shareKeyId === keyId) return false;
1056
+ const siblings = body.crossover_key_ids;
1057
+ return Array.isArray(siblings) && siblings.includes(keyId);
1058
+ }
793
1059
  return async function handler(req) {
794
1060
  const rawBody = await req.text();
795
1061
  const sig = req.headers.get("x-oneaddress-signature") ?? "";
@@ -808,7 +1074,11 @@ function createOneAddressHandler(options) {
808
1074
  }
809
1075
  let body;
810
1076
  try {
811
- body = JSON.parse(rawBody);
1077
+ const parsed = JSON.parse(rawBody);
1078
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1079
+ throw new TypeError("body is not a JSON object");
1080
+ }
1081
+ body = parsed;
812
1082
  } catch {
813
1083
  return new Response(JSON.stringify({ error: "Invalid JSON" }), {
814
1084
  status: 400,
@@ -825,51 +1095,86 @@ function createOneAddressHandler(options) {
825
1095
  const partnerId = body.partner_id ?? "";
826
1096
  const tsNum = Number(tsHeader);
827
1097
  const dispatchId = req.headers.get("x-oneaddress-dispatch") ?? "";
1098
+ if (isCrossoverSiblingToSkip(body)) {
1099
+ return declared(200, { ok: true, skipped: true, crossover: true });
1100
+ }
828
1101
  if (dispatchId) {
829
1102
  if (!idempotencyStore) {
830
- if (process.env.NODE_ENV === "test") {
1103
+ const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV : void 0;
1104
+ if (nodeEnv === "test") {
831
1105
  throw new Error(
832
1106
  "[OneAddress SDK] idempotencyStore is required in test mode when X-OneAddress-Dispatch is present. Wire up an idempotencyStore to prevent double-processing on retry."
833
1107
  );
834
1108
  }
1109
+ if (!warnedNoIdempotencyStore) {
1110
+ warnedNoIdempotencyStore = true;
1111
+ console.warn(
1112
+ // NOSONAR - intentional SDK diagnostic, not user-controlled data
1113
+ "[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."
1114
+ );
1115
+ }
835
1116
  } else if (idempotencyStore.claim) {
836
1117
  const claim = await idempotencyStore.claim(dispatchId);
837
1118
  if (claim === "duplicate") {
838
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
839
- status: 200,
840
- headers: { "Content-Type": "application/json" }
841
- });
1119
+ return declared(200, { ok: true, duplicate: true });
842
1120
  }
843
1121
  } else {
844
1122
  const alreadySeen = await idempotencyStore.has(dispatchId);
845
1123
  if (alreadySeen) {
846
- return new Response(JSON.stringify({ ok: true, duplicate: true }), {
847
- status: 200,
848
- headers: { "Content-Type": "application/json" }
849
- });
1124
+ return declared(200, { ok: true, duplicate: true });
850
1125
  }
851
1126
  }
852
1127
  }
853
1128
  try {
854
- if (body.event === "address.updated") {
1129
+ if (body.event === "address.updated" || body.event === "contact.updated") {
1130
+ const wireEvent = body.event;
855
1131
  let event;
1132
+ enforceLoaPresence(body);
856
1133
  if (isD5Body(body)) {
857
- const d5 = await buildD5Pieces(body, partnerId);
1134
+ let d5;
1135
+ try {
1136
+ d5 = await buildD5Pieces(body, partnerId);
1137
+ } catch (err) {
1138
+ if (err instanceof InvalidUpdateTypesError) {
1139
+ return declared(422, {
1140
+ error: "invalid_update_types",
1141
+ 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."
1142
+ });
1143
+ }
1144
+ throw err;
1145
+ }
1146
+ const notAccepted = d5.updateTypes.filter((t) => !acceptedUpdateTypes.includes(t));
1147
+ if (notAccepted.length > 0) {
1148
+ return declared(422, {
1149
+ error: "update_type_not_accepted",
1150
+ update_types: notAccepted,
1151
+ 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."
1152
+ });
1153
+ }
858
1154
  event = {
859
- event: "address.updated",
1155
+ event: wireEvent,
860
1156
  version: body.oneaddress_version ?? body.version ?? "2.0",
861
1157
  id: body.id ?? "",
862
1158
  timestamp: tsNum,
863
1159
  partner_id: partnerId,
864
1160
  dispatchId,
865
1161
  customer: d5.customer,
1162
+ update_types: d5.updateTypes,
866
1163
  address: d5.address,
1164
+ new_phone: d5.newPhone,
1165
+ new_email: d5.newEmail,
867
1166
  loa: d5.loa,
868
1167
  loa_ref: d5.loa_ref,
869
1168
  id_verification: body.id_verification,
870
1169
  raw: d5.raw
871
1170
  };
872
1171
  } else {
1172
+ if (wireEvent === "contact.updated") {
1173
+ return declared(400, {
1174
+ error: "missing_session_envelope",
1175
+ detail: "contact.updated requires session_envelope + session_key_share"
1176
+ });
1177
+ }
873
1178
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
874
1179
  return new Response(JSON.stringify({ error: "Missing or invalid address_encrypted payload" }), {
875
1180
  status: 400,
@@ -877,19 +1182,25 @@ function createOneAddressHandler(options) {
877
1182
  });
878
1183
  }
879
1184
  const encrypted = body.address_encrypted;
880
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
1185
+ const rawAddress = await decryptAddress(
1186
+ encrypted,
1187
+ requirePemFor("legacy address_encrypted decryption", privateKeyPem),
1188
+ partnerId
1189
+ );
881
1190
  let loa;
882
1191
  let loa_ref;
883
1192
  if (body.loa_encrypted && typeof body.loa_encrypted === "object") {
884
1193
  loa = await decryptLoaEncrypted(
885
1194
  body.loa_encrypted,
886
1195
  privateKeyPem,
887
- partnerId
1196
+ partnerId,
1197
+ expectedAlg
888
1198
  );
889
1199
  loa_ref = d5LoaRef(loa);
890
1200
  if (loaPublicKeyPem && !await verifyD5LOA(loa, loaPublicKeyPem)) {
891
1201
  throw new Error("D5 LOA signature verification failed");
892
1202
  }
1203
+ assertLoaBoundToEnvelope(loa, rawAddress.update_uid);
893
1204
  }
894
1205
  const customer = {
895
1206
  email: "",
@@ -905,6 +1216,8 @@ function createOneAddressHandler(options) {
905
1216
  partner_id: partnerId,
906
1217
  dispatchId,
907
1218
  customer,
1219
+ // The legacy blob predates kinds and always carries an address.
1220
+ update_types: ["address"],
908
1221
  address: validateAddress(rawAddress),
909
1222
  loa,
910
1223
  loa_ref,
@@ -920,10 +1233,26 @@ function createOneAddressHandler(options) {
920
1233
  // NOSONAR
921
1234
  );
922
1235
  }
923
- return new Response(JSON.stringify({ ok: true, ...result }), {
924
- status: 200,
925
- headers: { "Content-Type": "application/json" }
926
- });
1236
+ if (confirm && dispatchId) {
1237
+ const status = result && typeof result === "object" && result.status ? result.status : "confirmed";
1238
+ void confirmUpdate({
1239
+ partnerId: confirm.partnerId,
1240
+ secret: confirm.confirmSecret,
1241
+ dispatchId,
1242
+ status,
1243
+ loaRef: event.loa_ref,
1244
+ ...confirm.oneAddressApi ? { appBaseUrl: confirm.oneAddressApi } : {},
1245
+ ...confirm.fetchImpl ? { fetchImpl: confirm.fetchImpl } : {}
1246
+ }).then(
1247
+ (r) => {
1248
+ if (!r.ok) console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} failed: HTTP ${r.status} ${r.error ?? ""}`);
1249
+ },
1250
+ // NOSONAR
1251
+ (err) => console.error(`[OneAddress SDK] confirm of dispatch ${dispatchId} threw:`, err)
1252
+ // NOSONAR
1253
+ );
1254
+ }
1255
+ return declared(200, { ok: true, ...result });
927
1256
  }
928
1257
  if (body.event === "address.verify" && onVerify) {
929
1258
  if (!body.address_encrypted || typeof body.address_encrypted !== "object") {
@@ -933,7 +1262,11 @@ function createOneAddressHandler(options) {
933
1262
  });
934
1263
  }
935
1264
  const encrypted = body.address_encrypted;
936
- const rawAddress = await decryptAddress(encrypted, privateKeyPem, partnerId);
1265
+ const rawAddress = await decryptAddress(
1266
+ encrypted,
1267
+ requirePemFor("address.verify decryption", privateKeyPem),
1268
+ partnerId
1269
+ );
937
1270
  const event = {
938
1271
  event: "address.verify",
939
1272
  version: body.oneaddress_version ?? body.version ?? "1",
@@ -966,23 +1299,21 @@ function createOneAddressHandler(options) {
966
1299
  batchId: body.batch_id ?? 0,
967
1300
  partnerId,
968
1301
  match: matched,
969
- note: result && typeof result.note === "string" ? result.note : void 0
1302
+ note: result && typeof result.note === "string" ? result.note : void 0,
1303
+ allowedCallbackHosts
970
1304
  });
971
1305
  } catch (err) {
972
1306
  console.error("[OneAddress SDK] verify-result callback failed:", err);
973
1307
  }
974
1308
  }
975
- return new Response(JSON.stringify({ ok: true, match: matched }), {
976
- status: 200,
977
- headers: { "Content-Type": "application/json" }
978
- });
1309
+ return declared(200, { ok: true, match: matched });
979
1310
  }
980
1311
  if (body.event === "account.verify" && onAccountVerify) {
981
1312
  let customer;
982
1313
  if (body.customer_encrypted && typeof body.customer_encrypted === "object") {
983
1314
  const raw = await decryptAddress(
984
1315
  body.customer_encrypted,
985
- privateKeyPem,
1316
+ requirePemFor("account.verify decryption", privateKeyPem),
986
1317
  partnerId
987
1318
  );
988
1319
  customer = {
@@ -1006,10 +1337,7 @@ function createOneAddressHandler(options) {
1006
1337
  raw: body
1007
1338
  };
1008
1339
  const result = await onAccountVerify(event);
1009
- return new Response(JSON.stringify({ ok: true, ...result }), {
1010
- status: 200,
1011
- headers: { "Content-Type": "application/json" }
1012
- });
1340
+ return declared(200, { ok: true, ...result });
1013
1341
  }
1014
1342
  if ((body.event === "address.test" || body.event === "address.test-dispatch") && onTest) {
1015
1343
  if (!isD5Body(body)) {
@@ -1019,6 +1347,7 @@ function createOneAddressHandler(options) {
1019
1347
  });
1020
1348
  }
1021
1349
  const d5 = await buildD5Pieces(body, partnerId);
1350
+ if (!d5.address) throw new Error("[OneAddress SDK] test record carries no address");
1022
1351
  await onTest({
1023
1352
  event: body.event,
1024
1353
  index: typeof body.index === "number" ? body.index : void 0,
@@ -1030,9 +1359,11 @@ function createOneAddressHandler(options) {
1030
1359
  address: d5.address,
1031
1360
  raw: d5.raw
1032
1361
  });
1033
- return new Response(JSON.stringify({ ok: true, test: true }), {
1034
- status: 200,
1035
- headers: { "Content-Type": "application/json" }
1362
+ return declared(200, {
1363
+ ok: true,
1364
+ test: true,
1365
+ verification: true,
1366
+ index: typeof body.index === "number" ? body.index : void 0
1036
1367
  });
1037
1368
  }
1038
1369
  const evt = typeof body.event === "string" ? body.event : "(none)";
@@ -1059,7 +1390,7 @@ function createOneAddressHandler(options) {
1059
1390
  // NOSONAR
1060
1391
  );
1061
1392
  }
1062
- return new Response(JSON.stringify({ ok: true, skipped: true, event: evt }), {
1393
+ return new Response(JSON.stringify({ ok: true, skipped: true, event: evt, accepted_update_types: acceptedUpdateTypes }), {
1063
1394
  status: 200,
1064
1395
  headers: { "Content-Type": "application/json" }
1065
1396
  });
@@ -1106,6 +1437,112 @@ function toExpressHandler(handler) {
1106
1437
  res.send(bodyText);
1107
1438
  };
1108
1439
  }
1440
+ async function buildSignedTestWebhook(opts) {
1441
+ const nowSecs = opts.timestamp ?? Math.floor(Date.now() / 1e3);
1442
+ const nowIso = new Date(nowSecs * 1e3).toISOString();
1443
+ const updateIdNum = crypto.randomInt(9e8, 901e6);
1444
+ const updateUid = opts.session?.update_uid ?? String(updateIdNum);
1445
+ const partnerKey = {
1446
+ partner_id: opts.partnerId,
1447
+ key_id: opts.keyId ?? "test-key-1",
1448
+ public_key_b64: pemToBase64(opts.publicKey),
1449
+ algorithm: opts.algorithm ?? "ECDH-P256-AES-GCM-256"
1450
+ };
1451
+ const kinds = readUpdateTypes(opts.session?.update_types) ?? ["address"];
1452
+ const sessionData = {
1453
+ v: 2,
1454
+ update_uid: updateUid,
1455
+ dispatch_timestamp: nowIso,
1456
+ verified_name: "Test Person",
1457
+ ...kinds.includes("address") ? { new_address: { street: "42 Collins Street", suburb: "Melbourne", state: "VIC", postcode: "3000", country: "AU" } } : {},
1458
+ ...kinds.includes("phone") ? { new_phone: "+61412345678" } : {},
1459
+ ...kinds.includes("email") ? { new_email: "test.person@example.com" } : {},
1460
+ account_number: "TEST-0001",
1461
+ id_verification_ref: crypto.randomUUID(),
1462
+ known_names: [],
1463
+ ...opts.session ?? {}
1464
+ };
1465
+ const envelope = await encryptSessionForPartner(sessionData, partnerKey);
1466
+ let loa;
1467
+ let loa_encrypted;
1468
+ if (opts.loa !== false) {
1469
+ loa = {
1470
+ consumer_name: sessionData.verified_name,
1471
+ authorisation_date: nowIso,
1472
+ scope: "Authority to update address records on file.",
1473
+ update_uid: updateUid,
1474
+ oneaddress_acn: "696 078 869",
1475
+ oneaddress_signature: "00".repeat(64),
1476
+ signature_algorithm: "ECDSA-P256",
1477
+ ...opts.loa ?? {}
1478
+ };
1479
+ if (opts.loaSigningKeyPem) {
1480
+ const key = await crypto.subtle.importKey(
1481
+ "pkcs8",
1482
+ pemToBuffer(opts.loaSigningKeyPem),
1483
+ { name: "ECDSA", namedCurve: "P-256" },
1484
+ false,
1485
+ ["sign"]
1486
+ );
1487
+ const sig2 = await crypto.subtle.sign(
1488
+ { name: "ECDSA", hash: "SHA-256" },
1489
+ key,
1490
+ new TextEncoder().encode(canonicalD5LoaForm(loa))
1491
+ );
1492
+ loa.oneaddress_signature = Buffer.from(sig2).toString("hex");
1493
+ }
1494
+ const sealed = await encryptEnvelopeForPartner(loa, partnerKey);
1495
+ loa_encrypted = { session_envelope: sealed.session_envelope, session_key_share: sealed.session_key_share };
1496
+ }
1497
+ const event = opts.event ?? (kinds.includes("address") ? "address.updated" : "contact.updated");
1498
+ const body = JSON.stringify({
1499
+ event,
1500
+ oneaddress_version: CURRENT_VERSION,
1501
+ // A NUMBER. The relay sends `user_updates.id`; `update_uid` inside the
1502
+ // envelope and the LOA is its string form, which is the relationship a
1503
+ // receiver uses to bind the decrypted authorisation to the update.
1504
+ update_id: updateIdNum,
1505
+ partner_id: opts.partnerId,
1506
+ user_id: opts.userId ?? "test:consumer",
1507
+ timestamp: nowIso,
1508
+ session_envelope: envelope.session_envelope,
1509
+ session_key_share: envelope.session_key_share,
1510
+ key_share_expiry: new Date((nowSecs + 90 * 24 * 3600) * 1e3).toISOString(),
1511
+ id_verification: { method: "identity_document", verified_at: nowIso, verified: true, platform: "oneaddress/v1" },
1512
+ ...loa_encrypted ? { loa_encrypted } : {},
1513
+ // On the wire with a `null` value when no PaymentIntent backed the update,
1514
+ // so the KEY is present either way.
1515
+ stripe_session_id: opts.stripeSessionId ?? null,
1516
+ // `id` and `crossover_key_ids` are crossover-only and therefore NOT emitted
1517
+ // by default. A test that needs them passes them through `extraBody`, which
1518
+ // is exactly the circumstance the relay emits them in.
1519
+ ...opts.extraBody ?? {}
1520
+ });
1521
+ const ts = String(nowSecs);
1522
+ const sig = crypto.createHmac("sha256", opts.webhookSecret).update(`${ts}.${body}`).digest("hex");
1523
+ const dispatchId = opts.dispatchId ?? "1";
1524
+ const headers = {
1525
+ "Content-Type": "application/json",
1526
+ "X-OneAddress-Event": event,
1527
+ "X-OneAddress-Partner": opts.partnerId,
1528
+ "X-OneAddress-Version": CURRENT_VERSION,
1529
+ "X-OneAddress-Timestamp": ts,
1530
+ "X-OneAddress-Signature": sig,
1531
+ ...dispatchId ? { "X-OneAddress-Dispatch": dispatchId } : {}
1532
+ };
1533
+ const lower = new Map(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
1534
+ return {
1535
+ body,
1536
+ headers,
1537
+ sessionData,
1538
+ loa,
1539
+ request: {
1540
+ text: async () => body,
1541
+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null }
1542
+ },
1543
+ toRequest: (url = "https://receiver.example/webhook") => new Request(url, { method: "POST", headers, body })
1544
+ };
1545
+ }
1109
1546
 
1110
1547
  export {
1111
1548
  CURRENT_VERSION,
@@ -1136,6 +1573,8 @@ export {
1136
1573
  formatAddressParts,
1137
1574
  compareAddresses,
1138
1575
  sendVerifyResult,
1576
+ _resetOnceWarningsForTests,
1139
1577
  createOneAddressHandler,
1140
- toExpressHandler
1578
+ toExpressHandler,
1579
+ buildSignedTestWebhook
1141
1580
  };