@oneaddress/partner-sdk 2.0.0 → 2.2.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.ts 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 +
@@ -510,8 +556,8 @@ interface OneAddressUpdateEvent {
510
556
  loa_ref?: string;
511
557
  /**
512
558
  * Identity-verification attestation for the customer behind this update.
513
- * Present on every production dispatch; absent on BYPASS_STRIPE test
514
- * flows. See {@link OneAddressIdVerification}.
559
+ * Present on every production dispatch; absent on sandbox dispatches.
560
+ * See {@link OneAddressIdVerification}.
515
561
  */
516
562
  id_verification?: OneAddressIdVerification;
517
563
  /** Raw decrypted + parsed payload (in case fields are extended) */
@@ -546,8 +592,8 @@ interface OneAddressVerifyEvent {
546
592
  loa_ref?: string;
547
593
  /**
548
594
  * Identity-verification attestation for the customer behind this verify
549
- * request. Present on every production dispatch; absent on BYPASS_STRIPE
550
- * test flows. See {@link OneAddressIdVerification}.
595
+ * request. Present on every production dispatch; absent on sandbox
596
+ * dispatches. See {@link OneAddressIdVerification}.
551
597
  */
552
598
  id_verification?: OneAddressIdVerification;
553
599
  raw: Record<string, unknown>;
@@ -601,8 +647,30 @@ interface EncryptedPayload {
601
647
  */
602
648
  hkdfSalt?: string;
603
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
+ }
604
668
  interface OneAddressHandlerOptions {
605
- /** 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
+ */
606
674
  webhookSecret: string;
607
675
  /**
608
676
  * Previous webhook secret, valid during the 24-hour grace window after a
@@ -617,8 +685,30 @@ interface OneAddressHandlerOptions {
617
685
  * webhook secret — it will be exactly 24 hours after the rotation time.
618
686
  */
619
687
  webhookSecretGraceUntil?: string | number;
620
- /** PKCS#8 PEM-encoded ECDH P-256 private key for address decryption */
621
- 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'];
622
712
  /**
623
713
  * OPTIONAL — the `key_id` of the private key you hold (shown in the Partner
624
714
  * Portal next to your encryption key). Set this to make key-rotation crossovers
@@ -655,20 +745,75 @@ interface OneAddressHandlerOptions {
655
745
  * `address.verify`'s `event.loa` is a separate, still-cleartext legacy
656
746
  * shape ({@link OneAddressLOA}) read directly off the wire - this option
657
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.
658
754
  */
659
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;
660
794
  /**
661
795
  * Called when a consumer dispatches an address update to you.
662
796
  *
663
- * Return an object with an optional `status` and `reference` for the
664
- * confirmation callback. Omitting `status` means `'confirmed'`, which is
665
- * 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.
806
+ *
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.
666
810
  *
667
- * Three statuses are accepted ({@link OneAddressConfirmStatus}):
811
+ * Four statuses are accepted ({@link OneAddressConfirmStatus}):
668
812
  *
669
813
  * `confirmed` you applied the change
670
814
  * `already_current` you hold that address already; nothing to write
671
815
  * `failed` you could not process it
816
+ * `no_match` this person is not a customer of yours
672
817
  *
673
818
  * `already_current` exists because two values was one short: a receiver
674
819
  * handed a correct dispatch for an address it already held otherwise has to
@@ -677,9 +822,18 @@ interface OneAddressHandlerOptions {
677
822
  * carries no retry. Return it only when you can actually tell; guessing is
678
823
  * worse than returning `confirmed`.
679
824
  *
680
- * The status is now a union rather than a bare `string`: `/api/confirm`
681
- * rejects anything outside the three with a 400, and a typo used to surface
682
- * 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.
683
837
  */
684
838
  onUpdate: (event: OneAddressUpdateEvent) => Promise<{
685
839
  status?: OneAddressConfirmStatus;
@@ -738,6 +892,8 @@ interface OneAddressHandlerOptions {
738
892
  /**
739
893
  * Timestamp tolerance in seconds (default: 300 = 5 minutes).
740
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.
741
897
  */
742
898
  timestampToleranceSecs?: number;
743
899
  /**
@@ -757,7 +913,8 @@ interface OneAddressHandlerOptions {
757
913
  * **Required in test mode** (`NODE_ENV=test`): if a request with a non-empty
758
914
  * `X-OneAddress-Dispatch` header arrives and `idempotencyStore` is not wired,
759
915
  * the handler throws immediately so the oversight is caught at development time,
760
- * 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.
761
918
  *
762
919
  * @example
763
920
  * import { createSqlIdempotencyStore } from '@oneaddress/partner-sdk';
@@ -869,7 +1026,7 @@ interface IdempotencyStore {
869
1026
  * dependency-free and lets you reuse your existing pool, credentials and
870
1027
  * observability.
871
1028
  *
872
- * Create the table once:
1029
+ * Create the table once. Postgres and SQLite:
873
1030
  *
874
1031
  * ```sql
875
1032
  * CREATE TABLE oneaddress_dispatches (
@@ -879,6 +1036,11 @@ interface IdempotencyStore {
879
1036
  * );
880
1037
  * ```
881
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
+ *
882
1044
  * @example Postgres (node-postgres)
883
1045
  * createSqlIdempotencyStore({
884
1046
  * query: (sql, params) => pool.query(sql, params).then((r) => r.rows),
@@ -886,10 +1048,12 @@ interface IdempotencyStore {
886
1048
  *
887
1049
  * @example MySQL (mysql2/promise)
888
1050
  * createSqlIdempotencyStore({
889
- * placeholder: () => '?',
890
- * 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>[]),
891
1053
  * })
892
1054
  */
1055
+ /** The databases {@link createSqlIdempotencyStore} generates SQL for. */
1056
+ type IdempotencyDialect = 'postgres' | 'sqlite' | 'mysql' | 'mssql';
893
1057
  declare function createSqlIdempotencyStore(opts: {
894
1058
  /**
895
1059
  * Run parameterised SQL and return the result rows. Must not swallow errors —
@@ -900,8 +1064,20 @@ declare function createSqlIdempotencyStore(opts: {
900
1064
  /** Table name. Defaults to `oneaddress_dispatches`. */
901
1065
  table?: string;
902
1066
  /**
903
- * Positional placeholder for parameter `n` (1-based). Defaults to Postgres
904
- * 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.
905
1081
  */
906
1082
  placeholder?: (n: number) => string;
907
1083
  }): IdempotencyStore;
@@ -1210,7 +1386,7 @@ declare function transformAddress(payload: EncryptedPayload, privateKeyPem: stri
1210
1386
  * );
1211
1387
  * await db.storeEncryptedAddress(body.customer.email, kmsBlob);
1212
1388
  */
1213
- 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>;
1214
1390
  /**
1215
1391
  * Options for {@link confirmUpdate}.
1216
1392
  */
@@ -1240,7 +1416,15 @@ interface ConfirmUpdateOptions {
1240
1416
  dispatchId: number | string;
1241
1417
  /** Defaults to `'confirmed'`. See {@link OneAddressConfirmStatus}. */
1242
1418
  status?: OneAddressConfirmStatus;
1243
- /** 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
+ */
1244
1428
  note?: string;
1245
1429
  /** Echo of `event.loa_ref`, proving you decrypted the signed consent. */
1246
1430
  loaRef?: string;
@@ -1399,7 +1583,9 @@ declare function verifyD5LOA(loa: OneAddressD5LOA, publicKeyPem: string): Promis
1399
1583
  declare function decryptLoaEncrypted(loaEncrypted: {
1400
1584
  session_envelope: string;
1401
1585
  session_key_share: SessionKeyShare;
1402
- }, 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>;
1403
1589
  /**
1404
1590
  * Validate and narrow the decrypted address payload to `OneAddressAddress`.
1405
1591
  *
@@ -1444,8 +1630,16 @@ interface AddressParts {
1444
1630
  */
1445
1631
  declare function readAddressParts(raw: unknown): AddressParts;
1446
1632
  /**
1447
- * 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.
1448
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.
1449
1643
  */
1450
1644
  declare function formatAddressParts(parts: AddressParts): string;
1451
1645
  /**
@@ -1537,12 +1731,19 @@ interface VerifyResultCallbackParams {
1537
1731
  * Throws if the callback POST returns a non-2xx status.
1538
1732
  */
1539
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
+ */
1540
1740
  type HandlerRequest = {
1541
1741
  text(): Promise<string>;
1542
1742
  headers: {
1543
1743
  get(name: string): string | null;
1544
1744
  };
1545
1745
  };
1746
+ /** What the handler returns: a Fetch `Response`. */
1546
1747
  type HandlerResponse = Response;
1547
1748
  /**
1548
1749
  * A connection-verification test record, decrypted.
@@ -1574,6 +1775,8 @@ interface OneAddressTestEvent {
1574
1775
  address: Record<string, unknown>;
1575
1776
  raw: Record<string, unknown>;
1576
1777
  }
1778
+ /** Reset the once-per-process warning flags. Exported for the SDK's own tests. */
1779
+ declare function _resetOnceWarningsForTests(): void;
1577
1780
  /**
1578
1781
  * Create a framework-agnostic OneAddress webhook handler.
1579
1782
  * Returns a function compatible with Next.js App Router route handlers,
@@ -1646,5 +1849,140 @@ interface ExpressLikeResponse {
1646
1849
  * ```
1647
1850
  */
1648
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
+ * The retention window to advertise as `key_share_expiry`, in days.
1912
+ *
1913
+ * Defaults to 90, which is the default of `partners.retention_period_days` and
1914
+ * therefore what an unconfigured recipient really receives. The relay derives
1915
+ * this PER RECIPIENT from that column (14 to 365, chosen by the recipient on
1916
+ * the portal's Data Retention card), so it is not a constant on the wire and a
1917
+ * handler must not treat it as one.
1918
+ *
1919
+ * Pass your OWN configured window to rehearse the horizon you will actually
1920
+ * get. Worth doing rather than skipping: a handler that hard-codes "the expiry
1921
+ * is 90 days out" passes against this helper's default and then mis-handles its
1922
+ * own 14-day window in production, which is the same class of mistake as
1923
+ * assuming the body always carries an `id`.
1924
+ */
1925
+ retentionPeriodDays?: number | null;
1926
+ /**
1927
+ * Extra top-level body fields, merged last.
1928
+ *
1929
+ * This is where `id` and `crossover_key_ids` belong. They are NOT sent by
1930
+ * default, because the relay sends them only on a key-crossover copy — an
1931
+ * always-present `id` is what taught handlers to use it as an idempotency key
1932
+ * and then hand `undefined` to their store in production. Also the place for
1933
+ * forward-compat probes (`index`, `total`, unknown fields).
1934
+ */
1935
+ extraBody?: Record<string, unknown>;
1936
+ }
1937
+ /** What {@link buildSignedTestWebhook} returns. */
1938
+ interface SignedTestWebhook {
1939
+ /** The exact bytes that were signed. Send these, not a re-serialisation. */
1940
+ body: string;
1941
+ /** Every header the relay sends, signature included. */
1942
+ headers: Record<string, string>;
1943
+ /** Ready to pass to the function `createOneAddressHandler` returned. */
1944
+ request: HandlerRequest;
1945
+ /** A Fetch `Request`, for a framework that takes one (Next.js, Workers, Hono). */
1946
+ toRequest(url?: string): Request;
1947
+ /** What was sealed inside the envelope, so a test can assert on what `onUpdate` saw. */
1948
+ sessionData: SessionData;
1949
+ /** The LOA that was sealed, or undefined when `loa: false`. */
1950
+ loa?: OneAddressD5LOA;
1951
+ }
1952
+ /**
1953
+ * Build a correctly signed, correctly encrypted dispatch for a partner's own
1954
+ * unit tests, so a receiver can be tested end to end without a network, a
1955
+ * portal, or the conformance CLI.
1956
+ *
1957
+ * Lifted from the conformance suite's body builder, which is the shape the
1958
+ * relay actually sends: identity and address INSIDE the session envelope, the
1959
+ * signed consent INSIDE `loa_encrypted`, nothing about the consumer in the
1960
+ * clear. Until 2.1.0 the only way to get one of these was to run the
1961
+ * conformance CLI against a live URL, so partners' unit tests either mocked
1962
+ * the SDK away or did not exist.
1963
+ *
1964
+ * @example
1965
+ * import { generateKeyPairSync } from 'node:crypto';
1966
+ * import { createOneAddressHandler, buildSignedTestWebhook } from '@oneaddress/partner-sdk';
1967
+ *
1968
+ * const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
1969
+ * const handler = createOneAddressHandler({
1970
+ * webhookSecret: 'test-secret',
1971
+ * privateKeyPem: privateKey.export({ type: 'pkcs8', format: 'pem' }) as string,
1972
+ * idempotencyStore: memoryStore,
1973
+ * async onUpdate(event) { seen.push(event); },
1974
+ * });
1975
+ *
1976
+ * const hook = await buildSignedTestWebhook({
1977
+ * webhookSecret: 'test-secret',
1978
+ * partnerId: '11111111-1111-1111-1111-111111111111',
1979
+ * publicKey: publicKey.export({ type: 'spki', format: 'pem' }) as string,
1980
+ * session: { account_number: 'ACME-42' },
1981
+ * });
1982
+ * const res = await handler(hook.request);
1983
+ * expect(res.status).toBe(200);
1984
+ * expect(seen[0].customer?.account_number).toBe('ACME-42');
1985
+ */
1986
+ declare function buildSignedTestWebhook(opts: SignedTestWebhookOptions): Promise<SignedTestWebhook>;
1649
1987
 
1650
- 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 };
1988
+ 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 };