@oneaddress/partner-sdk 1.8.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -37,6 +37,12 @@ declare const DEFAULT_REPLAY_WINDOW_SECS = 300;
37
37
  */
38
38
  declare function isFreshTimestamp(timestampHeader: string | null | undefined, toleranceSecs?: number, nowSecs?: number): boolean;
39
39
 
40
+ /**
41
+ * The partner-key scheme as recorded in `partner_keys.algorithm` and returned
42
+ * by `/api/partner-keys/active`. Selects which wrap the consumer browser uses.
43
+ * Absent/unknown is treated as ECDH-P256 for back-compat.
44
+ */
45
+ type PartnerKeyAlgorithm = 'ECDH-P256-AES-GCM-256' | 'RSA-OAEP-256-AES-GCM-256' | 'MLKEM768X25519-AES-GCM-256';
40
46
  /**
41
47
  * The private-key half of `decryptSession`, delegated to whatever holds the key.
42
48
  *
@@ -74,10 +80,14 @@ declare function isFreshTimestamp(timestampHeader: string | null | undefined, to
74
80
  * and anyone holding it can derive that one dispatch's wrap key. It is
75
81
  * scoped to a single dispatch and useless for any other.
76
82
  *
77
- * There is deliberately no method for the post-quantum X-Wing path. No
78
- * mainstream KMS implements ML-KEM decapsulation, so a delegate cannot honestly
79
- * offer it, and `decryptSession` refuses that combination with a message saying
80
- * so rather than falling back to something the operator did not ask for.
83
+ * - `decapsulateXWing` is the post-quantum counterpart of
84
+ * `deriveSharedSecret`, and costs the same. The X-Wing key never leaves the
85
+ * KMS, but the per-dispatch KEM shared secret comes back, scoped to that one
86
+ * dispatch. Google Cloud KMS offers it (`KEM_XWING` keys, `Decapsulate`).
87
+ *
88
+ * A delegate that does not offer the method a share needs is refused by name,
89
+ * including a post-quantum share reaching a source with no `decapsulateXWing`,
90
+ * rather than falling back to something the operator did not ask for.
81
91
  *
82
92
  * Implementations MUST NOT log, cache or persist anything they return.
83
93
  */
@@ -103,6 +113,18 @@ interface PrivateKeyOperations {
103
113
  * @param wrappedKey The raw `wrapped_key` bytes from the share.
104
114
  */
105
115
  decryptRsaOaep?(wrappedKey: Uint8Array): Promise<Uint8Array>;
116
+ /**
117
+ * X-Wing (ML-KEM-768 + X25519) decapsulation: the raw 32-byte KEM shared
118
+ * secret for `kemCiphertext`, with NO KDF applied, exactly as
119
+ * `XWing.decapsulate(ciphertext, seed)` would return it. The HKDF and the
120
+ * unwrap of SK_n stay here, as they do for ECDH.
121
+ *
122
+ * Google Cloud KMS `Decapsulate` on a `KEM_XWING` key returns precisely this.
123
+ *
124
+ * @param kemCiphertext The share's `epk`, decoded: the 1120-byte X-Wing
125
+ * ciphertext.
126
+ */
127
+ decapsulateXWing?(kemCiphertext: Uint8Array): Promise<Uint8Array>;
106
128
  }
107
129
  /** Fields that can be turned into a blind index. */
108
130
  type BlindIndexField = 'email' | 'name' | 'account_number';
@@ -276,11 +298,18 @@ interface OutboxConsumer {
276
298
  }>;
277
299
  /** Atomically take up to `batchSize` rows. Other consumers skip them. */
278
300
  claimBatch(): Promise<OutboxRow[]>;
279
- /** Done. Stamps `processed_at` and releases the claim. */
301
+ /**
302
+ * Done. Stamps `processed_at` and releases the claim.
303
+ *
304
+ * Matches on the claim token THIS consumer holds for the row as well as
305
+ * the id, so a write that arrives after the lease expired and another
306
+ * consumer re-claimed the row touches nothing. A row this consumer never
307
+ * claimed has no token and is matched on id alone.
308
+ */
280
309
  markProcessed(dispatchId: string): Promise<void>;
281
- /** Failed. Records the reason, counts the attempt, releases for a retry. */
310
+ /** Failed. Records the reason, counts the attempt, releases for a retry. Token-scoped like `markProcessed`. */
282
311
  markFailed(dispatchId: string, error: unknown): Promise<void>;
283
- /** Put a row back untouched — for a clean shutdown mid-batch. */
312
+ /** Put a row back untouched, for a clean shutdown mid-batch. Token-scoped like `markProcessed`. */
284
313
  release(dispatchId: string): Promise<void>;
285
314
  /** Claim a batch, run `handler` per row, and mark each one. */
286
315
  process(handler: (row: OutboxRow) => Promise<void> | void): Promise<{
@@ -340,6 +369,7 @@ declare function createOutboxConsumer(opts: OutboxConsumerOptions): OutboxConsum
340
369
  * `confirmed` you applied the change
341
370
  * `already_current` you hold that address already; there was nothing to write
342
371
  * `failed` you could not process it
372
+ * `no_match` this person is not a customer of yours
343
373
  *
344
374
  * `already_current` (August 2026) is SUCCESS-class: to the consumer, "they
345
375
  * have my new address" is true either way and both show as up to date. It is
@@ -347,8 +377,24 @@ declare function createOutboxConsumer(opts: OutboxConsumerOptions): OutboxConsum
347
377
  * record can actually tell you nothing changed - if you cannot cheaply know,
348
378
  * `confirmed` remains correct and is what every pre-existing integration
349
379
  * sends.
380
+ *
381
+ * `no_match` (September 2026) is the one that changes what the CONSUMER is
382
+ * told, which is why it is worth the care. `failed` says YOUR SYSTEM broke:
383
+ * OneAddress retries, and a run of them makes the update our fault and
384
+ * refunds the consumer's $5. `no_match` says nothing broke - you looked, and
385
+ * the person simply is not on your books. Retrying cannot help, so the
386
+ * consumer is shown "check your account number with this provider" rather
387
+ * than a promise to try again, and no refund is triggered.
388
+ *
389
+ * The two ways to get it wrong are not symmetric. Sending `failed` for a
390
+ * stranger bills a refund against a receiver that behaved perfectly and tells
391
+ * a consumer to wait for something that will never arrive. Sending `no_match`
392
+ * during a real outage tells a genuine customer to go and fix an account
393
+ * number that was never wrong. **When you cannot tell the two apart, send
394
+ * `failed`** - it is the one that is safe to be wrong about, because the
395
+ * retry either clears it or the refund makes the consumer whole.
350
396
  */
351
- type OneAddressConfirmStatus = 'confirmed' | 'already_current' | 'failed';
397
+ type OneAddressConfirmStatus = 'confirmed' | 'already_current' | 'failed' | 'no_match';
352
398
  interface OneAddressAddress {
353
399
  street: string;
354
400
  suburb: string;
@@ -414,8 +460,8 @@ interface OneAddressLOA {
414
460
  * from this outer block — quote it back to OneAddress support to trace an
415
461
  * update back to the underlying verification.
416
462
  *
417
- * Absent on test-mode dispatches that bypass the credit (BYPASS_STRIPE
418
- * dev flows). Production dispatches always include it.
463
+ * Absent on sandbox dispatches, where no identity-verification credit was
464
+ * consumed. Production dispatches always include it.
419
465
  */
420
466
  interface OneAddressIdVerification {
421
467
  /** Verification method — `identity_document` for a completed document +
@@ -429,7 +475,14 @@ interface OneAddressIdVerification {
429
475
  platform: string;
430
476
  }
431
477
  interface OneAddressUpdateEvent {
432
- event: 'address.updated';
478
+ /**
479
+ * `address.updated` when the dispatch carries an address (alone or beside a
480
+ * contact detail); `contact.updated` when it carries no address at all. Both
481
+ * reach `onUpdate`: from a receiver's side each means "apply these new values
482
+ * to this customer", and two callbacks invite an integration that implements
483
+ * one and quietly ignores the other. Route on `update_types`, not on this.
484
+ */
485
+ event: 'address.updated' | 'contact.updated';
433
486
  version: string;
434
487
  id: string;
435
488
  timestamp: number;
@@ -462,7 +515,36 @@ interface OneAddressUpdateEvent {
462
515
  * Kept on the type for backwards compatibility with older payload shapes;
463
516
  * do not rely on it. See {@link OneAddressCustomerMatch}. */
464
517
  customer_match?: OneAddressCustomerMatch;
465
- address: OneAddressAddress;
518
+ /**
519
+ * Which kinds of detail this dispatch carries, read LITERALLY off the
520
+ * decrypted envelope. Absent on the wire means `['address']`: every envelope
521
+ * written before the field existed carried an address and nothing else.
522
+ *
523
+ * A phone-only update is `['phone']`, not `['address', 'phone']`; widening it
524
+ * would tell you an address changed when it did not. You only ever receive a
525
+ * kind you declared in {@link OneAddressHandlerOptions.acceptedUpdateTypes};
526
+ * anything else is refused with 422 before this callback runs.
527
+ */
528
+ update_types: SessionUpdateType[];
529
+ /**
530
+ * The new postal address, decrypted. Present when `update_types` includes
531
+ * `'address'`, which is every dispatch that existed before September 2026.
532
+ *
533
+ * OPTIONAL because a contact-only update (`contact.updated`) genuinely has
534
+ * none, and an empty or stale placeholder would be worse: you could not tell
535
+ * it from an instruction to overwrite. If your integration accepts addresses
536
+ * only (the default) it will never see the absent case, so narrow once:
537
+ * `const address = event.address; if (!address) throw new Error('no address');`
538
+ */
539
+ address?: OneAddressAddress;
540
+ /** The new telephone number, E.164 (`+61412345678`). Present exactly when
541
+ * `update_types` includes `'phone'`, which requires you to have declared it.
542
+ * OneAddress has confirmed the consumer holds this number. */
543
+ new_phone?: string;
544
+ /** The new email address, lowercased. Present exactly when `update_types`
545
+ * includes `'email'`, which requires you to have declared it. OneAddress has
546
+ * confirmed the consumer receives mail there. */
547
+ new_email?: string;
466
548
  /** The Letter of Authority. On D5 dispatches this is the structured
467
549
  * {@link OneAddressD5LOA} recovered by decrypting `loa_encrypted`; on legacy
468
550
  * dispatches it is the freeform {@link OneAddressLOA}. Verify with
@@ -474,8 +556,8 @@ interface OneAddressUpdateEvent {
474
556
  loa_ref?: string;
475
557
  /**
476
558
  * Identity-verification attestation for the customer behind this update.
477
- * Present on every production dispatch; absent on BYPASS_STRIPE test
478
- * flows. See {@link OneAddressIdVerification}.
559
+ * Present on every production dispatch; absent on sandbox dispatches.
560
+ * See {@link OneAddressIdVerification}.
479
561
  */
480
562
  id_verification?: OneAddressIdVerification;
481
563
  /** Raw decrypted + parsed payload (in case fields are extended) */
@@ -510,8 +592,8 @@ interface OneAddressVerifyEvent {
510
592
  loa_ref?: string;
511
593
  /**
512
594
  * Identity-verification attestation for the customer behind this verify
513
- * request. Present on every production dispatch; absent on BYPASS_STRIPE
514
- * test flows. See {@link OneAddressIdVerification}.
595
+ * request. Present on every production dispatch; absent on sandbox
596
+ * dispatches. See {@link OneAddressIdVerification}.
515
597
  */
516
598
  id_verification?: OneAddressIdVerification;
517
599
  raw: Record<string, unknown>;
@@ -565,8 +647,30 @@ interface EncryptedPayload {
565
647
  */
566
648
  hkdfSalt?: string;
567
649
  }
650
+ /**
651
+ * Closes the confirm loop from inside the handler. See
652
+ * {@link OneAddressHandlerOptions.confirm}.
653
+ */
654
+ interface HandlerConfirmOptions {
655
+ /** Your partner UUID, from the Partner Portal. */
656
+ partnerId: string;
657
+ /**
658
+ * Your confirm secret if you have minted one, otherwise your webhook
659
+ * signing secret. See {@link ConfirmUpdateOptions.secret} for why a minted
660
+ * confirm secret is the ONLY thing accepted once it exists.
661
+ */
662
+ confirmSecret: string;
663
+ /** Override the OneAddress base URL. Defaults to https://oneaddress.io */
664
+ oneAddressApi?: string;
665
+ /** Inject a fetch implementation, mainly for tests. */
666
+ fetchImpl?: typeof fetch;
667
+ }
568
668
  interface OneAddressHandlerOptions {
569
- /** HMAC-SHA256 webhook secret — shown in the OneAddress Partner Portal */
669
+ /**
670
+ * HMAC-SHA256 webhook secret, shown in the OneAddress Partner Portal.
671
+ * Refused at construction when empty: an empty secret verifies nothing,
672
+ * and the first sign of it was a receiver accepting every delivery.
673
+ */
570
674
  webhookSecret: string;
571
675
  /**
572
676
  * Previous webhook secret, valid during the 24-hour grace window after a
@@ -581,8 +685,53 @@ interface OneAddressHandlerOptions {
581
685
  * webhook secret — it will be exactly 24 hours after the rotation time.
582
686
  */
583
687
  webhookSecretGraceUntil?: string | number;
584
- /** PKCS#8 PEM-encoded ECDH P-256 private key for address decryption */
585
- privateKeyPem: string;
688
+ /**
689
+ * PKCS#8 PEM-encoded ECDH P-256 private key for address decryption (or the
690
+ * raw PKCS#8 base64, or a 32-byte X-Wing seed for a post-quantum key).
691
+ *
692
+ * OR a {@link PrivateKeyOperations} delegate for a key held in a KMS or HSM
693
+ * that will not export it. The name is kept for compatibility. A delegate
694
+ * covers the session-envelope paths (`address.updated`, `contact.updated`,
695
+ * the test events and `loa_encrypted`); the legacy single-blob paths
696
+ * (`address_encrypted` on `address.verify`, `customer_encrypted` on
697
+ * `account.verify`) need the raw key and are refused with a named error
698
+ * (500) when a delegate is supplied.
699
+ *
700
+ * A PEM that does not import is refused at construction rather than on the
701
+ * first delivery, where it surfaces as a 500 and a retry storm.
702
+ */
703
+ privateKeyPem: string | PrivateKeyOperations;
704
+ /**
705
+ * OPTIONAL. Pin the wrap algorithm this key was provisioned for. A
706
+ * `session_key_share.alg` that differs is refused before any unwrap, as an
707
+ * algorithm downgrade, with an error naming the mismatch. Passed straight
708
+ * through to {@link decryptSession}. Leave unset to keep the pre-existing
709
+ * behaviour, which routes on whatever the share says.
710
+ */
711
+ expectedAlg?: SessionKeyShare['alg'];
712
+ /**
713
+ * OPTIONAL — the `key_id` of the private key you hold (shown in the Partner
714
+ * Portal next to your encryption key). Set this to make key-rotation crossovers
715
+ * seamless.
716
+ *
717
+ * During a rotation OneAddress briefly sends the SAME update twice — once
718
+ * sealed to your OLD key and once to your NEW key — so a copy always arrives in
719
+ * a form you can open regardless of which key your receiver currently holds.
720
+ * Each copy names the other key_ids the update was also sent to
721
+ * (`crossover_key_ids`). When set, this handler SKIP-ACKS (200) a copy whose
722
+ * `session_key_share.key_id` is not yours **iff** your `keyId` is listed among
723
+ * those siblings — because a copy sealed to YOUR key is then guaranteed to
724
+ * arrive too. A single dispatch to a key_id you do not hold that names no such
725
+ * sibling still errors loudly, exactly as before, so a genuine
726
+ * misconfiguration is never silently swallowed.
727
+ *
728
+ * Leave it unset and behaviour is unchanged: a copy sealed to a key you do not
729
+ * hold fails to decrypt and returns 500 (OneAddress retries), which is today's
730
+ * behaviour — the verify-gate protects the cutover regardless. Set it to the
731
+ * key_id you actually hold; a value you do not hold a key for would cause every
732
+ * crossover copy naming it to be skipped with none arriving.
733
+ */
734
+ keyId?: string;
586
735
  /**
587
736
  * OPTIONAL — OneAddress's ECDSA P-256 LOA signing public key (SPKI PEM), from
588
737
  * {@link fetchLoaPublicKey}. Applies to `address.updated` ONLY (both the D5
@@ -596,20 +745,75 @@ interface OneAddressHandlerOptions {
596
745
  * `address.verify`'s `event.loa` is a separate, still-cleartext legacy
597
746
  * shape ({@link OneAddressLOA}) read directly off the wire - this option
598
747
  * does NOT apply to it. Verify it yourself with {@link verifyLOA} if needed.
748
+ *
749
+ * The check is PRESENT and VERIFIED and BOUND, not merely verified: see
750
+ * {@link OneAddressHandlerOptions.requireLoa} for the presence half, and
751
+ * note that a decrypted LOA whose `update_uid` differs from the session
752
+ * envelope's is refused too, so a genuine consent for one update cannot be
753
+ * replayed beside the envelope of another.
599
754
  */
600
755
  loaPublicKeyPem?: string;
756
+ /**
757
+ * Refuse an `address.updated` / `contact.updated` dispatch that carries no
758
+ * `loa_encrypted` at all. Defaults to `true` when `loaPublicKeyPem` is set
759
+ * and `false` otherwise.
760
+ *
761
+ * WHY THE DEFAULT FOLLOWS THE KEY. Until 2.1.0 setting `loaPublicKeyPem`
762
+ * verified the consent proof only when one arrived: a dispatch with the
763
+ * block simply omitted was processed with no check at all, so "verified"
764
+ * meant "verified if present", which is not a control. A relay that could
765
+ * strip the block could strip the verification with it.
766
+ *
767
+ * The refusal is a 500 rather than a 200-and-skip, on purpose: a 500 makes
768
+ * OneAddress retry and record the failure, where a 200 would report a
769
+ * delivery whose consent proof nobody saw.
770
+ *
771
+ * Set `false` to keep processing without a proof. The handler then warns
772
+ * ONCE per process that consent is unverified, so the decision is visible
773
+ * in the log rather than silent.
774
+ */
775
+ requireLoa?: boolean;
776
+ /**
777
+ * OPTIONAL. Close the confirm loop from inside the handler.
778
+ *
779
+ * WHY THIS EXISTS. `onUpdate`'s return value was spread into the 200 body
780
+ * and went no further: OneAddress reads nothing from that body, so a
781
+ * receiver that returned `{ status: 'confirmed' }` and never called
782
+ * {@link confirmUpdate} left the consumer's dashboard on "dispatched"
783
+ * forever while every line of its own code looked right. When this is set,
784
+ * the handler calls `confirmUpdate` after `onUpdate` returns, with the
785
+ * `status` it returned (`confirmed` when omitted) and `event.loa_ref`.
786
+ *
787
+ * Fire-and-forget: a failed confirm is logged and never turns the 200 into
788
+ * an error, because retrying the webhook would re-run `onUpdate`. A
789
+ * THROWING `onUpdate` sends nothing, correctly: the 500 makes OneAddress
790
+ * retry, and confirming `failed` for an attempt that will be retried would
791
+ * count against you.
792
+ */
793
+ confirm?: HandlerConfirmOptions;
601
794
  /**
602
795
  * Called when a consumer dispatches an address update to you.
603
796
  *
604
- * Return an object with an optional `status` and `reference` for the
605
- * confirmation callback. Omitting `status` means `'confirmed'`, which is
606
- * what every handler written before August 2026 does and remains correct.
797
+ * ── THE RETURN VALUE DOES NOT REACH ONEADDRESS ON ITS OWN ─────────────────
798
+ *
799
+ * It is spread into the 200 response body, and OneAddress reads nothing
800
+ * from that body. Closing the loop is a separate call to
801
+ * {@link confirmUpdate}, made by you, or by the handler when you pass
802
+ * {@link OneAddressHandlerOptions.confirm}. Until 2.1.0 this docstring said
803
+ * the return value was "for the confirmation callback", and a receiver that
804
+ * believed it returned `{ status: 'confirmed' }` and left the consumer's
805
+ * dashboard on "dispatched" indefinitely.
607
806
  *
608
- * Three statuses are accepted ({@link OneAddressConfirmStatus}):
807
+ * Return an object with an optional `status`. Omitting `status` means
808
+ * `'confirmed'`, which is what every handler written before August 2026
809
+ * does and remains correct.
810
+ *
811
+ * Four statuses are accepted ({@link OneAddressConfirmStatus}):
609
812
  *
610
813
  * `confirmed` you applied the change
611
814
  * `already_current` you hold that address already; nothing to write
612
815
  * `failed` you could not process it
816
+ * `no_match` this person is not a customer of yours
613
817
  *
614
818
  * `already_current` exists because two values was one short: a receiver
615
819
  * handed a correct dispatch for an address it already held otherwise has to
@@ -618,9 +822,18 @@ interface OneAddressHandlerOptions {
618
822
  * carries no retry. Return it only when you can actually tell; guessing is
619
823
  * worse than returning `confirmed`.
620
824
  *
621
- * The status is now a union rather than a bare `string`: `/api/confirm`
622
- * rejects anything outside the three with a 400, and a typo used to surface
623
- * as an unexplained rejection at runtime instead of a compile error.
825
+ * `no_match` splits the other half. Until September 2026 "I have no record
826
+ * of this person" and "my database is down" were the same value, so a
827
+ * receiver that correctly refused a stranger was recorded as having broken,
828
+ * and enough of those make the consumer's update refundable at your
829
+ * expense. Return `no_match` when you looked the person up and they are not
830
+ * there; return `failed` when you could not look. **If you cannot tell the
831
+ * two apart, return `failed`** - see {@link OneAddressConfirmStatus} for why
832
+ * the two mistakes are not symmetric.
833
+ *
834
+ * The status is a union rather than a bare `string`: `/api/confirm` rejects
835
+ * anything outside the four with a 400, and a typo used to surface as an
836
+ * unexplained rejection at runtime instead of a compile error.
624
837
  */
625
838
  onUpdate: (event: OneAddressUpdateEvent) => Promise<{
626
839
  status?: OneAddressConfirmStatus;
@@ -679,6 +892,8 @@ interface OneAddressHandlerOptions {
679
892
  /**
680
893
  * Timestamp tolerance in seconds (default: 300 = 5 minutes).
681
894
  * Requests with timestamps outside this window are rejected as potential replays.
895
+ * Must be a positive finite number no larger than one day (86400); anything
896
+ * else is refused at construction, since `NaN` here accepts every timestamp.
682
897
  */
683
898
  timestampToleranceSecs?: number;
684
899
  /**
@@ -698,7 +913,8 @@ interface OneAddressHandlerOptions {
698
913
  * **Required in test mode** (`NODE_ENV=test`): if a request with a non-empty
699
914
  * `X-OneAddress-Dispatch` header arrives and `idempotencyStore` is not wired,
700
915
  * the handler throws immediately so the oversight is caught at development time,
701
- * not in production.
916
+ * not in production. Outside test mode the same situation is logged ONCE per
917
+ * process, naming `createSqlIdempotencyStore`, and the dispatch is processed.
702
918
  *
703
919
  * @example
704
920
  * import { createSqlIdempotencyStore } from '@oneaddress/partner-sdk';
@@ -713,6 +929,54 @@ interface OneAddressHandlerOptions {
713
929
  * });
714
930
  */
715
931
  idempotencyStore?: IdempotencyStore;
932
+ /**
933
+ * The kinds of changed detail this receiver's CODE can handle. Default
934
+ * `['address']`, so every integration written before September 2026 is
935
+ * unchanged.
936
+ *
937
+ * ── THIS IS A DECLARATION THE RELAY READS, NOT A FILTER ──────────────────
938
+ *
939
+ * The handler puts it in the body of every authenticated 2xx acknowledgement
940
+ * as `accepted_update_types`. The conformance run reads it off the first
941
+ * check, probes each kind you declared with a real contact-only envelope,
942
+ * probes one kind you did NOT declare and requires a refusal, and records the
943
+ * result. So the partner portal cannot promise a kind this code does not
944
+ * handle: what you ACCEPT in the portal is consent, what you declare HERE is
945
+ * capability, and a kind is dispatched only where both hold.
946
+ *
947
+ * ── WHAT HAPPENS TO A KIND YOU DID NOT DECLARE ───────────────────────────
948
+ *
949
+ * It is refused with `422 update_type_not_accepted` and `onUpdate` never
950
+ * runs. Acknowledging it would look identical to success on both sides while
951
+ * the consumer has already paid. The 4xx also leaves the dispatch incomplete
952
+ * in your idempotency store, so a retry after you widen this list is
953
+ * reprocessed rather than dismissed as a duplicate.
954
+ *
955
+ * `address` is always included whatever you pass, and a value the protocol
956
+ * does not define is dropped. Declare a kind only once `onUpdate` reads
957
+ * `event.new_phone` or `event.new_email` AND your storage has a column for it:
958
+ * the conformance run proves the envelope was accepted, not that the value
959
+ * was written.
960
+ *
961
+ * @example
962
+ * createOneAddressHandler({
963
+ * webhookSecret, privateKeyPem,
964
+ * acceptedUpdateTypes: ['address', 'phone'],
965
+ * async onUpdate(event) {
966
+ * const account = event.customer?.account_number;
967
+ * if (!account) throw new Error('no account number');
968
+ * if (event.new_phone) await db.updatePhone(account, event.new_phone);
969
+ * if (event.address) await db.updateAddress(account, event.address);
970
+ * },
971
+ * });
972
+ */
973
+ acceptedUpdateTypes?: readonly SessionUpdateType[];
974
+ /**
975
+ * Extra hostnames `sendVerifyResult` may POST an `address.verify` result to,
976
+ * beside `oneaddress.io` and its subdomains. For a staging or self-hosted
977
+ * relay ONLY. See {@link VerifyResultCallbackParams.allowedCallbackHosts}.
978
+ */
979
+ allowedCallbackHosts?: readonly string[];
716
980
  }
717
981
  /**
718
982
  * What a {@link IdempotencyStore.claim} call found.
@@ -762,7 +1026,7 @@ interface IdempotencyStore {
762
1026
  * dependency-free and lets you reuse your existing pool, credentials and
763
1027
  * observability.
764
1028
  *
765
- * Create the table once:
1029
+ * Create the table once. Postgres and SQLite:
766
1030
  *
767
1031
  * ```sql
768
1032
  * CREATE TABLE oneaddress_dispatches (
@@ -772,6 +1036,11 @@ interface IdempotencyStore {
772
1036
  * );
773
1037
  * ```
774
1038
  *
1039
+ * MySQL and SQL Server need one more column, `claim_token VARCHAR(64) NULL`,
1040
+ * because neither has `ON CONFLICT DO NOTHING RETURNING`: the claim there is
1041
+ * an insert-if-absent carrying a per-call token, then a read-back that asks
1042
+ * whose token is on the row. See {@link createSqlIdempotencyStore} `dialect`.
1043
+ *
775
1044
  * @example Postgres (node-postgres)
776
1045
  * createSqlIdempotencyStore({
777
1046
  * query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
@@ -779,10 +1048,12 @@ interface IdempotencyStore {
779
1048
  *
780
1049
  * @example MySQL (mysql2/promise)
781
1050
  * createSqlIdempotencyStore({
782
- * placeholder: () => '?',
783
- * query: (sql, params) => conn.execute(sql, params).then(([rows]) => rows as Record<string, unknown>[]),
1051
+ * dialect: 'mysql',
1052
+ * query: (sql, params) => conn.query(sql, params).then(([rows]) => (Array.isArray(rows) ? rows : []) as Record<string, unknown>[]),
784
1053
  * })
785
1054
  */
1055
+ /** The databases {@link createSqlIdempotencyStore} generates SQL for. */
1056
+ type IdempotencyDialect = 'postgres' | 'sqlite' | 'mysql' | 'mssql';
786
1057
  declare function createSqlIdempotencyStore(opts: {
787
1058
  /**
788
1059
  * Run parameterised SQL and return the result rows. Must not swallow errors —
@@ -793,8 +1064,20 @@ declare function createSqlIdempotencyStore(opts: {
793
1064
  /** Table name. Defaults to `oneaddress_dispatches`. */
794
1065
  table?: string;
795
1066
  /**
796
- * Positional placeholder for parameter `n` (1-based). Defaults to Postgres
797
- * style (`$1`); pass `() => '?'` for MySQL, SQLite and SQL Server.
1067
+ * Which database the SQL is for. Defaults to `postgres`.
1068
+ *
1069
+ * Until 2.1.0 there was no such option and the README said MySQL and SQL
1070
+ * Server "just change the placeholder". They do not: the claim statement
1071
+ * was `INSERT ... ON CONFLICT (dispatch_id) DO NOTHING RETURNING`, which
1072
+ * only Postgres and SQLite accept, so a MySQL receiver following the README
1073
+ * failed on its first claim. Each dialect now gets a claim its server runs,
1074
+ * mirroring {@link createOutboxConsumer}.
1075
+ */
1076
+ dialect?: IdempotencyDialect;
1077
+ /**
1078
+ * Positional placeholder for parameter `n` (1-based). Defaults to the
1079
+ * dialect's own style (`$1` for postgres, `?` for mysql and sqlite, `@p1`
1080
+ * for mssql). Override only if your driver rewrites placeholders.
798
1081
  */
799
1082
  placeholder?: (n: number) => string;
800
1083
  }): IdempotencyStore;
@@ -889,9 +1172,12 @@ interface SessionKeyShare {
889
1172
  /**
890
1173
  * The kinds of changed detail an envelope can carry.
891
1174
  *
892
- * The vocabulary is closed. Treat an unrecognised value as "something newer
893
- * than this SDK understands" and ignore that kind rather than failing the whole
894
- * envelope — the fields you DO understand are still valid.
1175
+ * The vocabulary is closed. `createOneAddressHandler` REFUSES an envelope that
1176
+ * names a kind this build does not know (`422 invalid_update_types`) rather
1177
+ * than dropping the kind and processing the rest: a dropped kind is a dispatch
1178
+ * that charges the consumer, reports success and delivers less than they asked
1179
+ * for, and the 4xx is what makes OneAddress retry it once you have updated the
1180
+ * SDK. If you decrypt envelopes yourself with `decryptSession`, do the same.
895
1181
  */
896
1182
  type SessionUpdateType = 'address' | 'phone' | 'email';
897
1183
  interface SessionData {
@@ -992,6 +1278,12 @@ interface SessionData {
992
1278
  * @param envelopeB64 - The `session_envelope` base64url string from the webhook.
993
1279
  * @param privateKeyPem - Your PKCS#8 PEM private key whose key_id matches `share.key_id`.
994
1280
  * @param partnerId - Your partner UUID (from the outer webhook payload).
1281
+ * @param expectedAlg - OPTIONAL. The wrap algorithm this key was provisioned
1282
+ * for. When supplied, a `share.alg` that differs is refused
1283
+ * up front as an algorithm downgrade. The webhook HMAC
1284
+ * already binds `share.alg` on the wire, so this is a
1285
+ * belt-and-suspenders pin; leaving it unset preserves the
1286
+ * pre-existing behaviour.
995
1287
  * @returns The decrypted `SessionData`.
996
1288
  * @throws AES-GCM authentication-tag error if:
997
1289
  * - the wrong private key was supplied for `share.key_id`,
@@ -1015,7 +1307,7 @@ interface SessionData {
1015
1307
  * );
1016
1308
  * // data.new_address.street, data.account_number, etc.
1017
1309
  */
1018
- declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<SessionData>;
1310
+ declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string, expectedAlg?: SessionKeyShare['alg'] | null): Promise<SessionData>;
1019
1311
  /**
1020
1312
  * Decrypt a OneAddress payload and immediately re-encrypt it to a different
1021
1313
  * ECDH P-256 public key — for example, your internal KMS or HSM public key.
@@ -1094,7 +1386,7 @@ declare function transformAddress(payload: EncryptedPayload, privateKeyPem: stri
1094
1386
  * );
1095
1387
  * await db.storeEncryptedAddress(body.customer.email, kmsBlob);
1096
1388
  */
1097
- declare function transformSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string, partnerId: string, recipientSpkiPem: string): Promise<EncryptedPayload>;
1389
+ declare function transformSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string, recipientSpkiPem: string): Promise<EncryptedPayload>;
1098
1390
  /**
1099
1391
  * Options for {@link confirmUpdate}.
1100
1392
  */
@@ -1124,7 +1416,15 @@ interface ConfirmUpdateOptions {
1124
1416
  dispatchId: number | string;
1125
1417
  /** Defaults to `'confirmed'`. See {@link OneAddressConfirmStatus}. */
1126
1418
  status?: OneAddressConfirmStatus;
1127
- /** Free text shown to our support staff. Never shown to the consumer. */
1419
+ /**
1420
+ * Free text shown to our support staff. Never shown to the consumer.
1421
+ *
1422
+ * NEVER put the address, or any other decrypted detail, in it. The note
1423
+ * travels back to OneAddress in cleartext and is stored on our side, which
1424
+ * would undo the whole point of encrypting the address to you. Say what
1425
+ * happened ("applied to CRM record", "account closed"), not what the
1426
+ * address was.
1427
+ */
1128
1428
  note?: string;
1129
1429
  /** Echo of `event.loa_ref`, proving you decrypted the signed consent. */
1130
1430
  loaRef?: string;
@@ -1283,7 +1583,9 @@ declare function verifyD5LOA(loa: OneAddressD5LOA, publicKeyPem: string): Promis
1283
1583
  declare function decryptLoaEncrypted(loaEncrypted: {
1284
1584
  session_envelope: string;
1285
1585
  session_key_share: SessionKeyShare;
1286
- }, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<OneAddressD5LOA>;
1586
+ }, privateKeyPem: string | PrivateKeyOperations, partnerId: string,
1587
+ /** Same pin as {@link decryptSession}'s `expectedAlg`; the LOA is wrapped to the same key. */
1588
+ expectedAlg?: SessionKeyShare['alg'] | null): Promise<OneAddressD5LOA>;
1287
1589
  /**
1288
1590
  * Validate and narrow the decrypted address payload to `OneAddressAddress`.
1289
1591
  *
@@ -1328,8 +1630,16 @@ interface AddressParts {
1328
1630
  */
1329
1631
  declare function readAddressParts(raw: unknown): AddressParts;
1330
1632
  /**
1331
- * One-line human-readable summary of an address, for logs and confirm notes.
1633
+ * One-line human-readable summary of an address, for display to a person who
1634
+ * is entitled to see it: a review screen, a customer-facing confirmation.
1332
1635
  * Skips empty parts so a partial address doesn't render with dangling commas.
1636
+ *
1637
+ * NOT for logs and NOT for a confirm `note`. It renders the decrypted
1638
+ * address in the clear, so anywhere it goes the address goes. A log line is a
1639
+ * copy of the plaintext at rest that outlives every retention rule you set
1640
+ * for the record itself, and a confirm note is sent back to OneAddress. This
1641
+ * docstring used to say "for logs and confirm notes", and the reference
1642
+ * receiver did exactly that.
1333
1643
  */
1334
1644
  declare function formatAddressParts(parts: AddressParts): string;
1335
1645
  /**
@@ -1396,6 +1706,14 @@ interface VerifyResultCallbackParams {
1396
1706
  match: boolean;
1397
1707
  /** Optional free-text note (recorded by OneAddress; not shown to the consumer). */
1398
1708
  note?: string;
1709
+ /**
1710
+ * Extra hostnames the callback may be POSTed to, beside `oneaddress.io` and
1711
+ * its subdomains. `OA_CALLBACK_HOST_ALLOWLIST` (comma-separated) does the
1712
+ * same from the environment. Both are for a staging or self-hosted relay
1713
+ * ONLY: `callback_url` arrives on the wire, so every host added here is a
1714
+ * host a forged `address.verify` could send your callback token to.
1715
+ */
1716
+ allowedCallbackHosts?: readonly string[];
1399
1717
  }
1400
1718
  /**
1401
1719
  * POST an `address.verify` result back to OneAddress, closing the verify loop.
@@ -1413,12 +1731,19 @@ interface VerifyResultCallbackParams {
1413
1731
  * Throws if the callback POST returns a non-2xx status.
1414
1732
  */
1415
1733
  declare function sendVerifyResult(params: VerifyResultCallbackParams): Promise<void>;
1734
+ /**
1735
+ * What the handler reads from a request: the raw body text and a header
1736
+ * getter. A Fetch `Request` satisfies it, and so does the object
1737
+ * {@link toExpressHandler} and {@link buildSignedTestWebhook} construct.
1738
+ * Exported (2.1.0) so a partner can type their own adapter or test double.
1739
+ */
1416
1740
  type HandlerRequest = {
1417
1741
  text(): Promise<string>;
1418
1742
  headers: {
1419
1743
  get(name: string): string | null;
1420
1744
  };
1421
1745
  };
1746
+ /** What the handler returns: a Fetch `Response`. */
1422
1747
  type HandlerResponse = Response;
1423
1748
  /**
1424
1749
  * A connection-verification test record, decrypted.
@@ -1450,6 +1775,8 @@ interface OneAddressTestEvent {
1450
1775
  address: Record<string, unknown>;
1451
1776
  raw: Record<string, unknown>;
1452
1777
  }
1778
+ /** Reset the once-per-process warning flags. Exported for the SDK's own tests. */
1779
+ declare function _resetOnceWarningsForTests(): void;
1453
1780
  /**
1454
1781
  * Create a framework-agnostic OneAddress webhook handler.
1455
1782
  * Returns a function compatible with Next.js App Router route handlers,
@@ -1522,5 +1849,124 @@ interface ExpressLikeResponse {
1522
1849
  * ```
1523
1850
  */
1524
1851
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1852
+ /** What {@link buildSignedTestWebhook} takes. Only the first three are required. */
1853
+ interface SignedTestWebhookOptions {
1854
+ /** The secret your handler was built with. The body is signed with it. */
1855
+ webhookSecret: string;
1856
+ /** Your partner UUID. Bound into the envelope's key derivation, as on the wire. */
1857
+ partnerId: string;
1858
+ /**
1859
+ * The PUBLIC half of the key your handler holds: SPKI, as base64 or PEM.
1860
+ * For a unit test, generate a throwaway pair and give the handler the
1861
+ * private half.
1862
+ */
1863
+ publicKey: string;
1864
+ /** `session_key_share.key_id`. Defaults to `test-key-1`. Match your handler's `keyId` if you set one. */
1865
+ keyId?: string;
1866
+ /** Wrap scheme for `publicKey`. Defaults to ECDH P-256. */
1867
+ algorithm?: PartnerKeyAlgorithm;
1868
+ /**
1869
+ * Overrides for what is sealed inside the envelope. Defaults to an
1870
+ * address-only update for a fabricated person. A contact-only
1871
+ * `update_types` drops the default address, as the relay would.
1872
+ */
1873
+ session?: Partial<SessionData>;
1874
+ /**
1875
+ * The Letter of Authority. Default: a structurally valid LOA bound to the
1876
+ * envelope's `update_uid`, with a PLACEHOLDER signature that fails
1877
+ * {@link verifyD5LOA}. Pass `loaSigningKeyPem` to sign it for real, or
1878
+ * `false` to omit `loa_encrypted` entirely (to test `requireLoa`).
1879
+ */
1880
+ loa?: false | Partial<OneAddressD5LOA>;
1881
+ /**
1882
+ * An ECDSA P-256 private key (PKCS#8 PEM). When set, the LOA is signed with
1883
+ * it, so a handler given the matching public key as `loaPublicKeyPem`
1884
+ * accepts the dispatch. Generate a pair in your test; OneAddress's real
1885
+ * signing key never leaves OneAddress.
1886
+ */
1887
+ loaSigningKeyPem?: string;
1888
+ /** The `X-OneAddress-Dispatch` header. Defaults to `'1'`. Pass `''` to omit the header. */
1889
+ dispatchId?: string;
1890
+ /** Event name. Defaults to `address.updated`, or `contact.updated` when the session carries no address. */
1891
+ event?: 'address.updated' | 'contact.updated' | 'address.test' | 'address.test-dispatch';
1892
+ /** Unix SECONDS for the timestamp header and the body. Defaults to now. */
1893
+ timestamp?: number;
1894
+ /**
1895
+ * The consumer subject on `user_id`. Defaults to `test:consumer`.
1896
+ *
1897
+ * On the wire this is the real consumer's id (an account id, or
1898
+ * `guest:<uuid>`). It is always present, so this helper always sends it: a
1899
+ * simulator that omits a field the relay always sends teaches a handler that
1900
+ * the field is optional.
1901
+ */
1902
+ userId?: string;
1903
+ /**
1904
+ * `stripe_session_id`. Defaults to `null`, which is what the relay sends when
1905
+ * no PaymentIntent backed the update — the KEY is present either way, and
1906
+ * `'stripe_session_id' in body` is a different question from
1907
+ * `body.stripe_session_id != null`.
1908
+ */
1909
+ stripeSessionId?: string | null;
1910
+ /**
1911
+ * Extra top-level body fields, merged last.
1912
+ *
1913
+ * This is where `id` and `crossover_key_ids` belong. They are NOT sent by
1914
+ * default, because the relay sends them only on a key-crossover copy — an
1915
+ * always-present `id` is what taught handlers to use it as an idempotency key
1916
+ * and then hand `undefined` to their store in production. Also the place for
1917
+ * forward-compat probes (`index`, `total`, unknown fields).
1918
+ */
1919
+ extraBody?: Record<string, unknown>;
1920
+ }
1921
+ /** What {@link buildSignedTestWebhook} returns. */
1922
+ interface SignedTestWebhook {
1923
+ /** The exact bytes that were signed. Send these, not a re-serialisation. */
1924
+ body: string;
1925
+ /** Every header the relay sends, signature included. */
1926
+ headers: Record<string, string>;
1927
+ /** Ready to pass to the function `createOneAddressHandler` returned. */
1928
+ request: HandlerRequest;
1929
+ /** A Fetch `Request`, for a framework that takes one (Next.js, Workers, Hono). */
1930
+ toRequest(url?: string): Request;
1931
+ /** What was sealed inside the envelope, so a test can assert on what `onUpdate` saw. */
1932
+ sessionData: SessionData;
1933
+ /** The LOA that was sealed, or undefined when `loa: false`. */
1934
+ loa?: OneAddressD5LOA;
1935
+ }
1936
+ /**
1937
+ * Build a correctly signed, correctly encrypted dispatch for a partner's own
1938
+ * unit tests, so a receiver can be tested end to end without a network, a
1939
+ * portal, or the conformance CLI.
1940
+ *
1941
+ * Lifted from the conformance suite's body builder, which is the shape the
1942
+ * relay actually sends: identity and address INSIDE the session envelope, the
1943
+ * signed consent INSIDE `loa_encrypted`, nothing about the consumer in the
1944
+ * clear. Until 2.1.0 the only way to get one of these was to run the
1945
+ * conformance CLI against a live URL, so partners' unit tests either mocked
1946
+ * the SDK away or did not exist.
1947
+ *
1948
+ * @example
1949
+ * import { generateKeyPairSync } from 'node:crypto';
1950
+ * import { createOneAddressHandler, buildSignedTestWebhook } from '@oneaddress/partner-sdk';
1951
+ *
1952
+ * const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
1953
+ * const handler = createOneAddressHandler({
1954
+ * webhookSecret: 'test-secret',
1955
+ * privateKeyPem: privateKey.export({ type: 'pkcs8', format: 'pem' }) as string,
1956
+ * idempotencyStore: memoryStore,
1957
+ * async onUpdate(event) { seen.push(event); },
1958
+ * });
1959
+ *
1960
+ * const hook = await buildSignedTestWebhook({
1961
+ * webhookSecret: 'test-secret',
1962
+ * partnerId: '11111111-1111-1111-1111-111111111111',
1963
+ * publicKey: publicKey.export({ type: 'spki', format: 'pem' }) as string,
1964
+ * session: { account_number: 'ACME-42' },
1965
+ * });
1966
+ * const res = await handler(hook.request);
1967
+ * expect(res.status).toBe(200);
1968
+ * expect(seen[0].customer?.account_number).toBe('ACME-42');
1969
+ */
1970
+ declare function buildSignedTestWebhook(opts: SignedTestWebhookOptions): Promise<SignedTestWebhook>;
1525
1971
 
1526
- 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, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, type PrivateKeyOperations, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1972
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type HandlerConfirmOptions, type HandlerRequest, type HandlerResponse, type IdempotencyClaim, type IdempotencyDialect, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, type PrivateKeyOperations, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type SignedTestWebhook, type SignedTestWebhookOptions, type VerifyResultCallbackParams, _resetOnceWarningsForTests, buildSignedTestWebhook, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };