@oneaddress/partner-sdk 1.3.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -61,6 +61,19 @@ declare function normalizeForBlindIndex(field: BlindIndexField, value: string):
61
61
  */
62
62
  declare function computeBlindIndex(secret: string, field: BlindIndexField, value: string): Promise<string>;
63
63
 
64
+ /** True when a value looks like an email address rather than a person's name. */
65
+ declare function isEmailLike(value: string): boolean;
66
+ declare function namePoolMatches(providedNames: string[], storedName: string): boolean;
67
+ /**
68
+ * Find the first stored candidate (a customer's full name plus any known
69
+ * aliases) that the provided pool matches, or undefined if none does.
70
+ *
71
+ * Thin convenience wrapper - `namePoolMatches` takes the whole pool per call,
72
+ * so matching against a customer with several stored aliases means trying
73
+ * each one; this is that loop, shared so callers don't re-derive it.
74
+ */
75
+ declare function findMatchingStoredName(providedNames: string[], storedCandidates: readonly string[]): string | undefined;
76
+
64
77
  /**
65
78
  * @oneaddress/protocol
66
79
  *
@@ -88,7 +101,9 @@ declare const SUPPORTED_VERSIONS: readonly ["2026.1"];
88
101
  * webhookSecret: process.env.OA_WEBHOOK_SECRET!,
89
102
  * privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
90
103
  * async onUpdate(event) {
91
- * await db.updateAddress({ email: event.customer.email, ...event.address });
104
+ * // event.customer.email is always '' here - match on account_number / name.
105
+ * const record = await db.findByAccountNumber(event.customer.account_number);
106
+ * await db.updateAddress({ id: record.id, ...event.address });
92
107
  * },
93
108
  * });
94
109
  *
@@ -96,6 +111,21 @@ declare const SUPPORTED_VERSIONS: readonly ["2026.1"];
96
111
  * // Next.js: export { handler as POST };
97
112
  */
98
113
 
114
+ /**
115
+ * What you can tell OneAddress about a dispatch you have handled.
116
+ *
117
+ * `confirmed` you applied the change
118
+ * `already_current` you hold that address already; there was nothing to write
119
+ * `failed` you could not process it
120
+ *
121
+ * `already_current` (August 2026) is SUCCESS-class: to the consumer, "they
122
+ * have my new address" is true either way and both show as up to date. It is
123
+ * not a soft failure and triggers no retry. Send it only when your system of
124
+ * record can actually tell you nothing changed - if you cannot cheaply know,
125
+ * `confirmed` remains correct and is what every pre-existing integration
126
+ * sends.
127
+ */
128
+ type OneAddressConfirmStatus = 'confirmed' | 'already_current' | 'failed';
99
129
  interface OneAddressAddress {
100
130
  street: string;
101
131
  suburb: string;
@@ -200,12 +230,14 @@ interface OneAddressUpdateEvent {
200
230
  * Deduplicating on `(partner_id, dispatchId)` prevents double-processing.
201
231
  */
202
232
  dispatchId: string;
203
- /** Cleartext matching block. Present by default; ABSENT for partners who
204
- * enabled blind-index matching (see `customer_match`). Exactly one of
205
- * `customer` / `customer_match` is present on any given dispatch. */
233
+ /** Identity, decrypted for you (from the D5 `session_envelope` or the
234
+ * legacy `address_encrypted` payload - never cleartext on the wire). */
206
235
  customer?: OneAddressCustomer;
207
- /** Blind-index matching block — present instead of `customer` for blind-index
208
- * partners. See {@link OneAddressCustomerMatch}. */
236
+ /** ALWAYS undefined on this event. Blind-index matching was superseded by
237
+ * the "no cleartext" mandate for `address.updated` before this SDK version
238
+ * shipped D5 support - this field is never populated by the handler.
239
+ * Kept on the type for backwards compatibility with older payload shapes;
240
+ * do not rely on it. See {@link OneAddressCustomerMatch}. */
209
241
  customer_match?: OneAddressCustomerMatch;
210
242
  address: OneAddressAddress;
211
243
  /** The Letter of Authority. On D5 dispatches this is the structured
@@ -286,12 +318,13 @@ interface OneAddressAccountVerifyEvent {
286
318
  /** Unique dispatch ID from `X-OneAddress-Dispatch`. Falls back to `''` if header is absent — guard before using as idempotency key. */
287
319
  dispatchId: string;
288
320
  user_id: string;
289
- /** Cleartext matching block. Present by default; ABSENT for partners who
290
- * enabled blind-index matching (see `customer_match`). Exactly one of
291
- * `customer` / `customer_match` is present on any given dispatch. */
321
+ /** Identity, decrypted for you from `customer_encrypted` (or the cleartext
322
+ * `customer` block on payloads that pre-date encryption). */
292
323
  customer?: OneAddressCustomer;
293
- /** Blind-index matching block — present instead of `customer` for blind-index
294
- * partners. See {@link OneAddressCustomerMatch}. */
324
+ /** ALWAYS undefined on this event - `account.verify` does not support
325
+ * blind-index matching; the handler never reads or populates this field.
326
+ * Kept on the type for shape consistency with the other event types; do
327
+ * not rely on it. See {@link OneAddressCustomerMatch}. */
295
328
  customer_match?: OneAddressCustomerMatch;
296
329
  raw: Record<string, unknown>;
297
330
  }
@@ -329,20 +362,45 @@ interface OneAddressHandlerOptions {
329
362
  privateKeyPem: string;
330
363
  /**
331
364
  * OPTIONAL — OneAddress's ECDSA P-256 LOA signing public key (SPKI PEM), from
332
- * {@link fetchLoaPublicKey}. When set, the handler decrypts `loa_encrypted`,
333
- * verifies the signed D5 LOA, and REJECTS the dispatch (500) if the signature
334
- * is invalid — you never process an update whose consent proof doesn't verify.
335
- * When unset, the decrypted LOA is still passed to your handler as
336
- * `event.loa` (and `event.loa_ref`) for you to verify yourself. Cache the key;
337
- * it only changes on a planned rotation.
365
+ * {@link fetchLoaPublicKey}. Applies to `address.updated` ONLY (both the D5
366
+ * and legacy sub-paths, wherever `loa_encrypted` is present). When set, the
367
+ * handler decrypts `loa_encrypted`, verifies the signed D5 LOA, and REJECTS
368
+ * the dispatch (500) if the signature is invalid - you never process an
369
+ * update whose consent proof doesn't verify. When unset, the decrypted LOA
370
+ * is still passed to your handler as `event.loa` (and `event.loa_ref`) for
371
+ * you to verify yourself. Cache the key; it only changes on a planned rotation.
372
+ *
373
+ * `address.verify`'s `event.loa` is a separate, still-cleartext legacy
374
+ * shape ({@link OneAddressLOA}) read directly off the wire - this option
375
+ * does NOT apply to it. Verify it yourself with {@link verifyLOA} if needed.
338
376
  */
339
377
  loaPublicKeyPem?: string;
340
378
  /**
341
379
  * Called when a consumer dispatches an address update to you.
342
- * Return an object with optional `status` and `reference` for the confirmation callback.
380
+ *
381
+ * Return an object with an optional `status` and `reference` for the
382
+ * confirmation callback. Omitting `status` means `'confirmed'`, which is
383
+ * what every handler written before August 2026 does and remains correct.
384
+ *
385
+ * Three statuses are accepted ({@link OneAddressConfirmStatus}):
386
+ *
387
+ * `confirmed` you applied the change
388
+ * `already_current` you hold that address already; nothing to write
389
+ * `failed` you could not process it
390
+ *
391
+ * `already_current` exists because two values was one short: a receiver
392
+ * handed a correct dispatch for an address it already held otherwise has to
393
+ * claim either a change it never made or a failure that never happened. It
394
+ * is SUCCESS-class - the consumer is shown as up to date either way - and
395
+ * carries no retry. Return it only when you can actually tell; guessing is
396
+ * worse than returning `confirmed`.
397
+ *
398
+ * The status is now a union rather than a bare `string`: `/api/confirm`
399
+ * rejects anything outside the three with a 400, and a typo used to surface
400
+ * as an unexplained rejection at runtime instead of a compile error.
343
401
  */
344
402
  onUpdate: (event: OneAddressUpdateEvent) => Promise<{
345
- status?: string;
403
+ status?: OneAddressConfirmStatus;
346
404
  reference?: string;
347
405
  } | void>;
348
406
  /**
@@ -365,6 +423,32 @@ interface OneAddressHandlerOptions {
365
423
  status: 'match' | 'no_match' | 'no_account';
366
424
  note?: string;
367
425
  }>;
426
+ /**
427
+ * Connection-verification test records (`address.test`).
428
+ *
429
+ * OneAddress sends five of these before a partner goes live: real signed,
430
+ * ECDH-encrypted dispatches carrying fabricated TEST identities, which you
431
+ * decrypt and relay back so both sides can confirm the pipe works end to end.
432
+ *
433
+ * ── WHY THIS IS A SEPARATE CALLBACK AND NOT `onUpdate` ─────────────────────
434
+ *
435
+ * A test record must never reach the code path that writes a customer's
436
+ * address. The names and addresses in it are fabricated, so routing them
437
+ * through `onUpdate` would write fictitious data into real records — which is
438
+ * exactly the mistake the distinct event type exists to prevent.
439
+ *
440
+ * ── IF YOU DO NOT IMPLEMENT IT ─────────────────────────────────────────────
441
+ *
442
+ * `address.test` is acknowledged with 200 and skipped, and the SDK logs a
443
+ * warning naming this option. That combination was the defect in
444
+ * marlowe-reports#125: the skip was correct, the silence was not. Five test
445
+ * records were skipped, the partner saw five clean 200s, and the only way it
446
+ * surfaced was somebody decrypting the raw bodies by hand.
447
+ *
448
+ * Implement it if you intend to complete connection verification through the
449
+ * SDK rather than by hand.
450
+ */
451
+ onTest?: (event: OneAddressTestEvent) => void | Promise<void>;
368
452
  /**
369
453
  * Timestamp tolerance in seconds (default: 300 = 5 minutes).
370
454
  * Requests with timestamps outside this window are rejected as potential replays.
@@ -377,9 +461,12 @@ interface OneAddressHandlerOptions {
377
461
  * more than once. Without deduplication your `onUpdate` handler will process
378
462
  * the same address update multiple times.
379
463
  *
380
- * Implement two methods:
381
- * `has(dispatchId)` — return `true` if this dispatch was already processed.
382
- * `set(dispatchId)` — record that this dispatch has been processed.
464
+ * **Prefer `claim` + `complete`.** The older `has` + `set` pair still works and
465
+ * is still honoured, but it cannot be made correct under concurrency: `has`
466
+ * and `set` are two round-trips, so two retries arriving at once both observe
467
+ * "not seen" and both apply the update. `claim` is a single atomic operation
468
+ * and has no such window. See {@link createSqlIdempotencyStore} for a ready
469
+ * implementation over any SQL database.
383
470
  *
384
471
  * **Required in test mode** (`NODE_ENV=test`): if a request with a non-empty
385
472
  * `X-OneAddress-Dispatch` header arrives and `idempotencyStore` is not wired,
@@ -387,22 +474,102 @@ interface OneAddressHandlerOptions {
387
474
  * not in production.
388
475
  *
389
476
  * @example
390
- * const seen = new Set<string>();
477
+ * import { createSqlIdempotencyStore } from '@oneaddress/partner-sdk';
478
+ *
391
479
  * const handler = createOneAddressHandler({
392
480
  * webhookSecret: process.env.OA_WEBHOOK_SECRET!,
393
481
  * privateKeyPem: process.env.OA_PRIVATE_KEY_PEM!,
394
- * idempotencyStore: {
395
- * has: async (id) => seen.has(id),
396
- * set: async (id) => { seen.add(id); },
397
- * },
482
+ * idempotencyStore: createSqlIdempotencyStore({
483
+ * query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
484
+ * }),
398
485
  * async onUpdate(event) { ... },
399
486
  * });
400
487
  */
401
- idempotencyStore?: {
402
- has(dispatchId: string): Promise<boolean>;
403
- set(dispatchId: string): Promise<void>;
404
- };
488
+ idempotencyStore?: IdempotencyStore;
405
489
  }
490
+ /**
491
+ * What a {@link IdempotencyStore.claim} call found.
492
+ *
493
+ * - `fresh` — never seen. Process it.
494
+ * - `retry-after-incomplete` — seen, but a previous attempt never reported
495
+ * completion. **Process it again.** This is the case a naive "seen set" gets
496
+ * wrong: if the first attempt died after being recorded, skipping the retry
497
+ * loses the update permanently while both sides report success.
498
+ * - `duplicate` — seen and completed. Skip; the handler responds
499
+ * `200 { ok: true, duplicate: true }`.
500
+ */
501
+ type IdempotencyClaim = 'fresh' | 'retry-after-incomplete' | 'duplicate';
502
+ interface IdempotencyStore {
503
+ /**
504
+ * Legacy check. Ignored when {@link IdempotencyStore.claim} is present.
505
+ * Return `true` if this dispatch was already processed.
506
+ */
507
+ has(dispatchId: string): Promise<boolean>;
508
+ /**
509
+ * Legacy record. Ignored when {@link IdempotencyStore.complete} is present.
510
+ * Called only AFTER your handler returns, never before.
511
+ */
512
+ set(dispatchId: string): Promise<void>;
513
+ /**
514
+ * Atomically claim a dispatch for processing. Preferred over `has`.
515
+ *
516
+ * Must be a single atomic operation (an `INSERT … ON CONFLICT DO NOTHING`,
517
+ * a Redis `SET NX`, a conditional write) — otherwise concurrent retries can
518
+ * both claim the same dispatch.
519
+ */
520
+ claim?(dispatchId: string): Promise<IdempotencyClaim>;
521
+ /**
522
+ * Mark a claimed dispatch complete. Called only after your handler returns
523
+ * successfully; a throwing handler deliberately leaves the dispatch
524
+ * incomplete so the next retry re-processes it.
525
+ */
526
+ complete?(dispatchId: string): Promise<void>;
527
+ }
528
+ /**
529
+ * A SQL-backed {@link IdempotencyStore} with an atomic claim, over whatever
530
+ * driver you already use.
531
+ *
532
+ * The SDK deliberately ships no database dependency — you pass a `query`
533
+ * function that runs parameterised SQL and returns rows. That keeps the SDK
534
+ * dependency-free and lets you reuse your existing pool, credentials and
535
+ * observability.
536
+ *
537
+ * Create the table once:
538
+ *
539
+ * ```sql
540
+ * CREATE TABLE oneaddress_dispatches (
541
+ * dispatch_id TEXT PRIMARY KEY,
542
+ * received_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
543
+ * completed_at TIMESTAMP
544
+ * );
545
+ * ```
546
+ *
547
+ * @example Postgres (node-postgres)
548
+ * createSqlIdempotencyStore({
549
+ * query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
550
+ * })
551
+ *
552
+ * @example MySQL (mysql2/promise)
553
+ * createSqlIdempotencyStore({
554
+ * placeholder: () => '?',
555
+ * query: (sql, params) => conn.execute(sql, params).then(([rows]) => rows as Record<string, unknown>[]),
556
+ * })
557
+ */
558
+ declare function createSqlIdempotencyStore(opts: {
559
+ /**
560
+ * Run parameterised SQL and return the result rows. Must not swallow errors —
561
+ * a store that silently fails is worse than no store, because the handler
562
+ * then cannot tell a duplicate from a fresh dispatch.
563
+ */
564
+ query: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
565
+ /** Table name. Defaults to `oneaddress_dispatches`. */
566
+ table?: string;
567
+ /**
568
+ * Positional placeholder for parameter `n` (1-based). Defaults to Postgres
569
+ * style (`$1`); pass `() => '?'` for MySQL, SQLite and SQL Server.
570
+ */
571
+ placeholder?: (n: number) => string;
572
+ }): IdempotencyStore;
406
573
  /**
407
574
  * Verify the HMAC-SHA256 webhook signature.
408
575
  * OneAddress signs: `${timestamp}.${rawBody}` with the webhook secret.
@@ -491,12 +658,49 @@ interface SessionKeyShare {
491
658
  * use the envelope's embedded fields, when present, as the audit-grade
492
659
  * source of truth.
493
660
  */
661
+ /**
662
+ * The kinds of changed detail an envelope can carry.
663
+ *
664
+ * The vocabulary is closed. Treat an unrecognised value as "something newer
665
+ * than this SDK understands" and ignore that kind rather than failing the whole
666
+ * envelope — the fields you DO understand are still valid.
667
+ */
668
+ type SessionUpdateType = 'address' | 'phone' | 'email';
494
669
  interface SessionData {
495
670
  v: 2;
496
671
  update_uid?: string;
497
672
  dispatch_timestamp?: string;
498
673
  verified_name: string;
499
- new_address: {
674
+ /**
675
+ * Which kinds of detail this envelope concerns.
676
+ *
677
+ * ABSENT MEANS `['address']`. Every envelope written before this field
678
+ * existed carried an address and nothing else, so the absent case is defined
679
+ * to be correct — you do not need to handle it as an error or a special case.
680
+ *
681
+ * Read this rather than inferring from which fields are present. The two
682
+ * agree, but only this one distinguishes "this update does not concern your
683
+ * record of my phone number" from "it does and the value went missing". The
684
+ * first is routine; the second you should reject.
685
+ */
686
+ update_types?: SessionUpdateType[];
687
+ /**
688
+ * The new postal address, when this update concerns one.
689
+ *
690
+ * OPTIONAL SINCE SDK 1.4.0 (11 Aug 2026). It was required for as long as an
691
+ * address was the only thing OneAddress could transmit. A consumer can now
692
+ * ask to update a telephone number or email address on its own, and such an
693
+ * envelope genuinely has no address — sending an empty or stale one would be
694
+ * worse, since you could not tell a placeholder from an instruction to
695
+ * overwrite.
696
+ *
697
+ * **You will not receive an address-less envelope unless you have told
698
+ * OneAddress you accept that kind of update.** Acceptance is per-kind and
699
+ * defaults to address-only, so existing integrations are unaffected until
700
+ * someone on your side opts in. If you have opted in, check `update_types`
701
+ * (or simply check this field for undefined) before dereferencing it.
702
+ */
703
+ new_address?: {
500
704
  street: string;
501
705
  suburb: string;
502
706
  state: string;
@@ -508,6 +712,23 @@ interface SessionData {
508
712
  accountReference?: string;
509
713
  addressType?: 'residential' | 'postal' | 'both';
510
714
  };
715
+ /**
716
+ * The new telephone number, when this update concerns one. Canonical E.164
717
+ * (`+61412345678`), always — never a locally-formatted string, so you can
718
+ * compare it against your own record without re-parsing.
719
+ *
720
+ * OneAddress has verified that the consumer holds this number, by sending a
721
+ * one-time code to it, in addition to the identity verification that
722
+ * authorises every dispatch. Those are separate checks and both passed.
723
+ */
724
+ new_phone?: string;
725
+ /**
726
+ * The new email address, when this update concerns one. Lowercased, for the
727
+ * same comparability reason as E.164 above.
728
+ *
729
+ * OneAddress has verified that the consumer receives mail at this address.
730
+ */
731
+ new_email?: string;
511
732
  account_number: string;
512
733
  id_verification_ref: string;
513
734
  known_names?: string[];
@@ -643,6 +864,90 @@ declare function transformAddress(payload: EncryptedPayload, privateKeyPem: stri
643
864
  * await db.storeEncryptedAddress(body.customer.email, kmsBlob);
644
865
  */
645
866
  declare function transformSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string, partnerId: string, recipientSpkiPem: string): Promise<EncryptedPayload>;
867
+ /**
868
+ * Options for {@link confirmUpdate}.
869
+ */
870
+ interface ConfirmUpdateOptions {
871
+ /** Your partner UUID, from the Partner Portal. */
872
+ partnerId: string;
873
+ /**
874
+ * Your **confirm secret** if you have minted one, otherwise your webhook
875
+ * signing secret.
876
+ *
877
+ * Once a confirm secret exists on your account it is the ONLY thing
878
+ * `/api/confirm` accepts — the webhook secret stops working here, by design,
879
+ * so that a leaked webhook secret cannot forge confirmations. If you mint one
880
+ * and this keeps returning 401, that is why.
881
+ */
882
+ secret: string;
883
+ /**
884
+ * From the `X-OneAddress-Dispatch` header on the webhook you are confirming.
885
+ *
886
+ * Not in the body and not in the envelope: capture it when the request
887
+ * arrives. `createOneAddressHandler` surfaces it as `event.dispatch_id`.
888
+ */
889
+ dispatchId: number | string;
890
+ /** Defaults to `'confirmed'`. See {@link OneAddressConfirmStatus}. */
891
+ status?: OneAddressConfirmStatus;
892
+ /** Free text shown to our support staff. Never shown to the consumer. */
893
+ note?: string;
894
+ /** Echo of `event.loa_ref`, proving you decrypted the signed consent. */
895
+ loaRef?: string;
896
+ /** The name you matched in your own records, if you want it recorded. */
897
+ memberName?: string;
898
+ /** Override the consumer-app base URL. Defaults to https://oneaddress.io */
899
+ appBaseUrl?: string;
900
+ /** Inject a fetch implementation, mainly for tests. */
901
+ fetchImpl?: typeof fetch;
902
+ }
903
+ /** What {@link confirmUpdate} reports back. Never throws on an HTTP status. */
904
+ interface ConfirmUpdateResult {
905
+ /** True only on a 2xx. */
906
+ ok: boolean;
907
+ /** HTTP status, or 0 if the request never completed. */
908
+ status: number;
909
+ /** Our error message, or the transport failure, when `ok` is false. */
910
+ error?: string;
911
+ }
912
+ /**
913
+ * Confirm that you have applied (or could not apply) a dispatched update.
914
+ *
915
+ * ## Why this exists
916
+ *
917
+ * Until this helper, the SDK did everything for RECEIVING a dispatch and
918
+ * nothing at all for answering one — and answering is half the protocol. The
919
+ * README's own example had a `/* …auth… *\/` comment sitting exactly where the
920
+ * difficult part is, leaving every partner to re-derive a timestamped HMAC over
921
+ * bytes they must not re-serialise.
922
+ *
923
+ * That is not a fair thing to ask, and the consequence of getting it wrong is
924
+ * invisible from the partner's side: the update looks applied in their system,
925
+ * and the consumer's dashboard simply never turns green.
926
+ *
927
+ * ## The three things it gets right for you
928
+ *
929
+ * 1. **The body is serialised ONCE and those exact bytes are both signed and
930
+ * sent.** Signing a JSON string and then sending a re-serialised one is the
931
+ * classic way to produce a valid-looking request that fails on signature,
932
+ * and key order or whitespace is enough to do it.
933
+ * 2. **The timestamp is seconds, not milliseconds.** Milliseconds are outside
934
+ * the ±300s replay window by a factor of a thousand and fail as
935
+ * `401 Stale or future request`, which reads like an auth error.
936
+ * 3. **A non-2xx is RETURNED, not thrown.** A confirm failing must be
937
+ * something your code can see and log; an exception in a fire-and-forget
938
+ * `.catch()` is how a dropped confirmation stays invisible.
939
+ *
940
+ * @example
941
+ * const res = await confirmUpdate({
942
+ * partnerId: process.env.OA_PARTNER_ID!,
943
+ * secret: process.env.OA_CONFIRM_SECRET!,
944
+ * dispatchId: event.dispatch_id,
945
+ * status: 'confirmed',
946
+ * note: 'Address updated in CRM',
947
+ * });
948
+ * if (!res.ok) console.error('[oneaddress] confirm failed', res.status, res.error);
949
+ */
950
+ declare function confirmUpdate(opts: ConfirmUpdateOptions): Promise<ConfirmUpdateResult>;
646
951
  /**
647
952
  * Fetch OneAddress's ECDSA P-256 LOA signing public key from the well-known endpoint.
648
953
  *
@@ -760,6 +1065,38 @@ declare function decryptLoaEncrypted(loaEncrypted: {
760
1065
  * await db.updateAddress(address);
761
1066
  */
762
1067
  declare function validateAddress(raw: unknown): OneAddressAddress;
1068
+ /**
1069
+ * The canonical address parts, extracted from a decrypted payload regardless of
1070
+ * which field-name spelling it uses.
1071
+ */
1072
+ interface AddressParts {
1073
+ line1: string;
1074
+ suburb: string;
1075
+ state: string;
1076
+ postcode: string;
1077
+ country: string;
1078
+ }
1079
+ /**
1080
+ * Read the canonical address parts out of a decrypted payload, tolerating the
1081
+ * field-name variants above. Missing parts come back as `''` (except `country`,
1082
+ * which defaults to `'AU'`), so callers can use `||` to fall back to a stored
1083
+ * value without null-juggling.
1084
+ *
1085
+ * Exists because every reference receiver had hand-rolled the same
1086
+ * `a.line1 ?? a.address_line1 ?? a.street ?? …` ladder, which meant a fix to
1087
+ * one copy silently left the others behind. Prefer this over re-implementing it.
1088
+ *
1089
+ * @example
1090
+ * const data = await decryptSession(share, envelope, privateKeyPem, partnerId);
1091
+ * const parts = readAddressParts(data.new_address);
1092
+ * await db.updateAddress({ id, line1: parts.line1 || row.line1, ... });
1093
+ */
1094
+ declare function readAddressParts(raw: unknown): AddressParts;
1095
+ /**
1096
+ * One-line human-readable summary of an address, for logs and confirm notes.
1097
+ * Skips empty parts so a partial address doesn't render with dangling commas.
1098
+ */
1099
+ declare function formatAddressParts(parts: AddressParts): string;
763
1100
  /**
764
1101
  * Address shape accepted by `compareAddresses`. Mirrors `OneAddressAddress`
765
1102
  * but every field is optional so partners can pass either their stored row
@@ -810,6 +1147,37 @@ interface ComparableAddress {
810
1147
  * ```
811
1148
  */
812
1149
  declare function compareAddresses(a: ComparableAddress, b: ComparableAddress): boolean;
1150
+ /** Parameters for {@link sendVerifyResult}. */
1151
+ interface VerifyResultCallbackParams {
1152
+ /** The `callback_url` from the inbound `address.verify` webhook body. */
1153
+ callbackUrl: string;
1154
+ /** The `callback_token` from the inbound `address.verify` webhook body. */
1155
+ callbackToken: string;
1156
+ /** The `batch_id` from the inbound `address.verify` webhook body. */
1157
+ batchId: number | string;
1158
+ /** Your OneAddress partner id. */
1159
+ partnerId: string;
1160
+ /** `true` if the submitted address matches what you hold on file. */
1161
+ match: boolean;
1162
+ /** Optional free-text note (recorded by OneAddress; not shown to the consumer). */
1163
+ note?: string;
1164
+ }
1165
+ /**
1166
+ * POST an `address.verify` result back to OneAddress, closing the verify loop.
1167
+ *
1168
+ * OneAddress ingests the verify outcome from THIS callback (a POST to the
1169
+ * `callback_url`, `/api/verify-result`), **not** from the webhook's HTTP
1170
+ * response body — unlike `account.verify`, which is read synchronously. On a
1171
+ * match, OneAddress marks the service "already in sync" and skips the
1172
+ * `address.updated` dispatch entirely.
1173
+ *
1174
+ * `createOneAddressHandler` calls this for you automatically whenever you
1175
+ * provide an `onVerify` handler. Call it directly only if you handle
1176
+ * `address.verify` without the SDK handler.
1177
+ *
1178
+ * Throws if the callback POST returns a non-2xx status.
1179
+ */
1180
+ declare function sendVerifyResult(params: VerifyResultCallbackParams): Promise<void>;
813
1181
  type HandlerRequest = {
814
1182
  text(): Promise<string>;
815
1183
  headers: {
@@ -817,11 +1185,100 @@ type HandlerRequest = {
817
1185
  };
818
1186
  };
819
1187
  type HandlerResponse = Response;
1188
+ /**
1189
+ * A connection-verification test record, decrypted.
1190
+ *
1191
+ * Deliberately a distinct type from {@link OneAddressUpdateEvent} rather than a
1192
+ * flag on it: nothing that accepts an update event should silently accept one
1193
+ * of these, and the compiler is a better guard against that than a comment.
1194
+ */
1195
+ interface OneAddressTestEvent {
1196
+ event: 'address.test';
1197
+ /** 1-based position within this verification run. */
1198
+ index?: number;
1199
+ /** How many records this run sends in total. */
1200
+ total?: number;
1201
+ /** The verification this record belongs to. */
1202
+ verification_id?: string;
1203
+ timestamp: number;
1204
+ partner_id: string;
1205
+ /** Fabricated identity. NOT a real customer — never write this to a record. */
1206
+ customer: OneAddressCustomer;
1207
+ /** Fabricated address. NOT a real address. */
1208
+ address: Record<string, unknown>;
1209
+ raw: Record<string, unknown>;
1210
+ }
820
1211
  /**
821
1212
  * Create a framework-agnostic OneAddress webhook handler.
822
1213
  * Returns a function compatible with Next.js App Router route handlers,
823
1214
  * Express (with raw body middleware), and Cloudflare Workers.
824
1215
  */
825
1216
  declare function createOneAddressHandler(options: OneAddressHandlerOptions): (req: HandlerRequest) => Promise<HandlerResponse>;
1217
+ /**
1218
+ * The Express shapes this needs, structurally typed.
1219
+ *
1220
+ * Deliberately NOT `import type { Request } from 'express'`: the SDK has no
1221
+ * runtime or type dependency on Express and should not acquire one to support
1222
+ * it. Anything with these members works, which also covers Connect, Restify
1223
+ * and the several frameworks that copy the API.
1224
+ */
1225
+ interface ExpressLikeRequest {
1226
+ method?: string;
1227
+ headers: Record<string, string | string[] | undefined>;
1228
+ body?: unknown;
1229
+ }
1230
+ interface ExpressLikeResponse {
1231
+ status(code: number): ExpressLikeResponse;
1232
+ setHeader(name: string, value: string): unknown;
1233
+ send(body: string): unknown;
1234
+ }
1235
+ /**
1236
+ * Adapt a OneAddress handler to Express's `(req, res)` signature.
1237
+ *
1238
+ * ── WHY THIS EXISTS (marlowe-reports#123) ──────────────────────────────────
1239
+ *
1240
+ * `createOneAddressHandler` returns a FETCH-style function: it calls
1241
+ * `req.text()` and `req.headers.get()`, and returns a `Response`. Express
1242
+ * gives you neither - its `req` has no `.text()`, and its `res` is mutated
1243
+ * rather than returned. The README used to suggest, in a comment, that
1244
+ * `express.raw` was the only adjustment needed:
1245
+ *
1246
+ * // app.post('/webhook/oneaddress', express.raw(...), handler);
1247
+ *
1248
+ * Passing Express's `req` straight in crashes on the first delivery with
1249
+ * `TypeError: req.text is not a function`. The first person outside the
1250
+ * company to follow that line hit it on their very first real webhook.
1251
+ *
1252
+ * The Fetch contract is intentional - it is what makes the handler work
1253
+ * unchanged on Next.js App Router, Cloudflare Workers, Deno and Bun - so the
1254
+ * fix is an adapter rather than a change of contract, and shipping it here
1255
+ * means Express partners are not each hand-rolling header conversion.
1256
+ *
1257
+ * ── THE RAW-BODY REQUIREMENT IS ENFORCED, NOT ASSUMED ──────────────────────
1258
+ *
1259
+ * The signature is an HMAC over the RAW request bytes. If `express.json()` has
1260
+ * already parsed the body, those bytes are gone, and re-serialising the object
1261
+ * produces different bytes for the same data - a different key order or one
1262
+ * space of whitespace is enough. The result is a 401 that looks like a wrong
1263
+ * secret and is nothing of the kind.
1264
+ *
1265
+ * So a non-Buffer body is refused HERE, by name, rather than being allowed to
1266
+ * become a mystery signature failure downstream.
1267
+ *
1268
+ * @example
1269
+ * ```js
1270
+ * import express from 'express';
1271
+ * import { createOneAddressHandler, toExpressHandler } from '@oneaddress/partner-sdk';
1272
+ *
1273
+ * const handler = createOneAddressHandler({ ... });
1274
+ *
1275
+ * app.post(
1276
+ * '/webhook/oneaddress',
1277
+ * express.raw({ type: 'application/json' }), // required: preserves raw bytes
1278
+ * toExpressHandler(handler),
1279
+ * );
1280
+ * ```
1281
+ */
1282
+ declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
826
1283
 
827
- export { type BlindIndexField, CURRENT_VERSION, type ComparableAddress, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressUpdateEvent, type OneAddressVerifyEvent, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, canonicalD5LoaForm, compareAddresses, computeBlindIndex, createOneAddressHandler, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, isFreshTimestamp, normalizeForBlindIndex, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1284
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };