@oneaddress/partner-sdk 1.7.0 → 2.0.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/edge.mjs CHANGED
@@ -20,13 +20,13 @@ import {
20
20
  verifyLOA,
21
21
  verifySignature,
22
22
  verifyWithGrace
23
- } from "./chunk-MNVGYXWH.mjs";
23
+ } from "./chunk-UPJU4HFR.mjs";
24
24
  import {
25
25
  DEFAULT_REPLAY_WINDOW_SECS,
26
26
  computeBlindIndex,
27
27
  isFreshTimestamp,
28
28
  normalizeForBlindIndex
29
- } from "./chunk-TAZD6PFZ.mjs";
29
+ } from "./chunk-DUVPNFU6.mjs";
30
30
  export {
31
31
  CURRENT_VERSION,
32
32
  DEFAULT_REPLAY_WINDOW_SECS,
package/dist/index.d.mts CHANGED
@@ -37,6 +37,73 @@ 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 private-key half of `decryptSession`, delegated to whatever holds the key.
42
+ *
43
+ * ── WHY THIS EXISTS, AND WHY IT IS NOT SIMPLY "RETURN THE KEY" ──────────────
44
+ *
45
+ * A recipient large enough to have a security review will not put an unwrapped
46
+ * private key in an environment variable or on a disk, which is what a PEM is.
47
+ * They keep it in a KMS or an HSM, and the entire value of doing so is that the
48
+ * key **cannot be exported**. So a key source that answers "here is the PEM"
49
+ * cannot be backed by a KMS at all: the two designs are mutually exclusive, not
50
+ * merely inconvenient together.
51
+ *
52
+ * What a KMS DOES offer is the operation rather than the key, so that is what
53
+ * this interface asks for. The cut is deliberately at the smallest possible
54
+ * step - the one operation that genuinely requires the private key - and
55
+ * everything after it (HKDF, the AES-GCM unwrap, the envelope decrypt) stays
56
+ * here, in one implementation, exercised by the canonical vectors.
57
+ *
58
+ * The tempting alternative is to let the delegate return SK_n and be done. It
59
+ * is worse: the ECDH path would then have to reproduce the HKDF derivation and
60
+ * the unwrap on the far side of the interface, so every implementer would be
61
+ * re-implementing this file's crypto from its docstring, and a mistake there
62
+ * fails as an auth-tag error indistinguishable from a wrong key.
63
+ *
64
+ * ── WHAT EACH METHOD COSTS THE HOLDER ──────────────────────────────────────
65
+ *
66
+ * These are not equally protective, and a recipient choosing between wrap
67
+ * algorithms should know which they are buying:
68
+ *
69
+ * - `decryptRsaOaep` is the strongest. SK_n is recovered INSIDE the KMS and
70
+ * only SK_n comes back. Neither the private key nor any long-lived secret
71
+ * ever exists in the receiver's memory.
72
+ * - `deriveSharedSecret` is weaker but still sound. The private key never
73
+ * leaves the KMS, but the per-dispatch ECDH shared secret does come back,
74
+ * and anyone holding it can derive that one dispatch's wrap key. It is
75
+ * scoped to a single dispatch and useless for any other.
76
+ *
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.
81
+ *
82
+ * Implementations MUST NOT log, cache or persist anything they return.
83
+ */
84
+ interface PrivateKeyOperations {
85
+ /** Names the backing source, for error messages only. Never a credential. */
86
+ readonly name: string;
87
+ /**
88
+ * ECDH-ES: the raw shared secret for `epkSpki`, exactly as WebCrypto's
89
+ * `deriveBits({name:'ECDH', public}, priv, 256)` would return it - the X
90
+ * coordinate of the shared point, 32 bytes for P-256, with NO KDF applied.
91
+ *
92
+ * AWS KMS `DeriveSharedSecret` returns precisely this, which is what makes
93
+ * the two interchangeable. A KMS that applied its own KDF first would not be
94
+ * usable here and would fail as an auth-tag error, so the "no KDF" part is a
95
+ * requirement rather than a description.
96
+ *
97
+ * @param epkSpki The ephemeral public key from the share, DER SPKI encoded.
98
+ */
99
+ deriveSharedSecret?(epkSpki: Uint8Array): Promise<Uint8Array>;
100
+ /**
101
+ * RSA-OAEP-SHA256: unwrap `wrappedKey` to SK_n directly.
102
+ *
103
+ * @param wrappedKey The raw `wrapped_key` bytes from the share.
104
+ */
105
+ decryptRsaOaep?(wrappedKey: Uint8Array): Promise<Uint8Array>;
106
+ }
40
107
  /** Fields that can be turned into a blind index. */
41
108
  type BlindIndexField = 'email' | 'name' | 'account_number';
42
109
  /**
@@ -362,7 +429,14 @@ interface OneAddressIdVerification {
362
429
  platform: string;
363
430
  }
364
431
  interface OneAddressUpdateEvent {
365
- event: 'address.updated';
432
+ /**
433
+ * `address.updated` when the dispatch carries an address (alone or beside a
434
+ * contact detail); `contact.updated` when it carries no address at all. Both
435
+ * reach `onUpdate`: from a receiver's side each means "apply these new values
436
+ * to this customer", and two callbacks invite an integration that implements
437
+ * one and quietly ignores the other. Route on `update_types`, not on this.
438
+ */
439
+ event: 'address.updated' | 'contact.updated';
366
440
  version: string;
367
441
  id: string;
368
442
  timestamp: number;
@@ -395,7 +469,36 @@ interface OneAddressUpdateEvent {
395
469
  * Kept on the type for backwards compatibility with older payload shapes;
396
470
  * do not rely on it. See {@link OneAddressCustomerMatch}. */
397
471
  customer_match?: OneAddressCustomerMatch;
398
- address: OneAddressAddress;
472
+ /**
473
+ * Which kinds of detail this dispatch carries, read LITERALLY off the
474
+ * decrypted envelope. Absent on the wire means `['address']`: every envelope
475
+ * written before the field existed carried an address and nothing else.
476
+ *
477
+ * A phone-only update is `['phone']`, not `['address', 'phone']`; widening it
478
+ * would tell you an address changed when it did not. You only ever receive a
479
+ * kind you declared in {@link OneAddressHandlerOptions.acceptedUpdateTypes};
480
+ * anything else is refused with 422 before this callback runs.
481
+ */
482
+ update_types: SessionUpdateType[];
483
+ /**
484
+ * The new postal address, decrypted. Present when `update_types` includes
485
+ * `'address'`, which is every dispatch that existed before September 2026.
486
+ *
487
+ * OPTIONAL because a contact-only update (`contact.updated`) genuinely has
488
+ * none, and an empty or stale placeholder would be worse: you could not tell
489
+ * it from an instruction to overwrite. If your integration accepts addresses
490
+ * only (the default) it will never see the absent case, so narrow once:
491
+ * `const address = event.address; if (!address) throw new Error('no address');`
492
+ */
493
+ address?: OneAddressAddress;
494
+ /** The new telephone number, E.164 (`+61412345678`). Present exactly when
495
+ * `update_types` includes `'phone'`, which requires you to have declared it.
496
+ * OneAddress has confirmed the consumer holds this number. */
497
+ new_phone?: string;
498
+ /** The new email address, lowercased. Present exactly when `update_types`
499
+ * includes `'email'`, which requires you to have declared it. OneAddress has
500
+ * confirmed the consumer receives mail there. */
501
+ new_email?: string;
399
502
  /** The Letter of Authority. On D5 dispatches this is the structured
400
503
  * {@link OneAddressD5LOA} recovered by decrypting `loa_encrypted`; on legacy
401
504
  * dispatches it is the freeform {@link OneAddressLOA}. Verify with
@@ -516,6 +619,29 @@ interface OneAddressHandlerOptions {
516
619
  webhookSecretGraceUntil?: string | number;
517
620
  /** PKCS#8 PEM-encoded ECDH P-256 private key for address decryption */
518
621
  privateKeyPem: string;
622
+ /**
623
+ * OPTIONAL — the `key_id` of the private key you hold (shown in the Partner
624
+ * Portal next to your encryption key). Set this to make key-rotation crossovers
625
+ * seamless.
626
+ *
627
+ * During a rotation OneAddress briefly sends the SAME update twice — once
628
+ * sealed to your OLD key and once to your NEW key — so a copy always arrives in
629
+ * a form you can open regardless of which key your receiver currently holds.
630
+ * Each copy names the other key_ids the update was also sent to
631
+ * (`crossover_key_ids`). When set, this handler SKIP-ACKS (200) a copy whose
632
+ * `session_key_share.key_id` is not yours **iff** your `keyId` is listed among
633
+ * those siblings — because a copy sealed to YOUR key is then guaranteed to
634
+ * arrive too. A single dispatch to a key_id you do not hold that names no such
635
+ * sibling still errors loudly, exactly as before, so a genuine
636
+ * misconfiguration is never silently swallowed.
637
+ *
638
+ * Leave it unset and behaviour is unchanged: a copy sealed to a key you do not
639
+ * hold fails to decrypt and returns 500 (OneAddress retries), which is today's
640
+ * behaviour — the verify-gate protects the cutover regardless. Set it to the
641
+ * key_id you actually hold; a value you do not hold a key for would cause every
642
+ * crossover copy naming it to be skipped with none arriving.
643
+ */
644
+ keyId?: string;
519
645
  /**
520
646
  * OPTIONAL — OneAddress's ECDSA P-256 LOA signing public key (SPKI PEM), from
521
647
  * {@link fetchLoaPublicKey}. Applies to `address.updated` ONLY (both the D5
@@ -580,11 +706,15 @@ interface OneAddressHandlerOptions {
580
706
  note?: string;
581
707
  }>;
582
708
  /**
583
- * Connection-verification test records (`address.test`).
709
+ * Connection-verification and stress-test records (`address.test` and
710
+ * `address.test-dispatch`).
584
711
  *
585
- * OneAddress sends five of these before a partner goes live: real signed,
586
- * ECDH-encrypted dispatches carrying fabricated TEST identities, which you
587
- * decrypt and relay back so both sides can confirm the pipe works end to end.
712
+ * OneAddress sends five `address.test` records before a partner goes live:
713
+ * real signed, ECDH-encrypted dispatches carrying fabricated TEST identities,
714
+ * which you decrypt and relay back so both sides can confirm the pipe works
715
+ * end to end. The admin stress test sends `address.test-dispatch`, which is
716
+ * the SAME shape (a fabricated, encrypted test record) — both arrive here, and
717
+ * `event` tells them apart if you want to count stress dispatches separately.
588
718
  *
589
719
  * ── WHY THIS IS A SEPARATE CALLBACK AND NOT `onUpdate` ─────────────────────
590
720
  *
@@ -595,11 +725,11 @@ interface OneAddressHandlerOptions {
595
725
  *
596
726
  * ── IF YOU DO NOT IMPLEMENT IT ─────────────────────────────────────────────
597
727
  *
598
- * `address.test` is acknowledged with 200 and skipped, and the SDK logs a
599
- * warning naming this option. That combination was the defect in
600
- * marlowe-reports#125: the skip was correct, the silence was not. Five test
601
- * records were skipped, the partner saw five clean 200s, and the only way it
602
- * surfaced was somebody decrypting the raw bodies by hand.
728
+ * `address.test` / `address.test-dispatch` are acknowledged with 200 and
729
+ * skipped, and the SDK logs a warning naming this option. That combination was
730
+ * the defect in marlowe-reports#125: the skip was correct, the silence was
731
+ * not. Five test records were skipped, the partner saw five clean 200s, and
732
+ * the only way it surfaced was somebody decrypting the raw bodies by hand.
603
733
  *
604
734
  * Implement it if you intend to complete connection verification through the
605
735
  * SDK rather than by hand.
@@ -642,6 +772,54 @@ interface OneAddressHandlerOptions {
642
772
  * });
643
773
  */
644
774
  idempotencyStore?: IdempotencyStore;
775
+ /**
776
+ * The kinds of changed detail this receiver's CODE can handle. Default
777
+ * `['address']`, so every integration written before September 2026 is
778
+ * unchanged.
779
+ *
780
+ * ── THIS IS A DECLARATION THE RELAY READS, NOT A FILTER ──────────────────
781
+ *
782
+ * The handler puts it in the body of every authenticated 2xx acknowledgement
783
+ * as `accepted_update_types`. The conformance run reads it off the first
784
+ * check, probes each kind you declared with a real contact-only envelope,
785
+ * probes one kind you did NOT declare and requires a refusal, and records the
786
+ * result. So the partner portal cannot promise a kind this code does not
787
+ * handle: what you ACCEPT in the portal is consent, what you declare HERE is
788
+ * capability, and a kind is dispatched only where both hold.
789
+ *
790
+ * ── WHAT HAPPENS TO A KIND YOU DID NOT DECLARE ───────────────────────────
791
+ *
792
+ * It is refused with `422 update_type_not_accepted` and `onUpdate` never
793
+ * runs. Acknowledging it would look identical to success on both sides while
794
+ * the consumer has already paid. The 4xx also leaves the dispatch incomplete
795
+ * in your idempotency store, so a retry after you widen this list is
796
+ * reprocessed rather than dismissed as a duplicate.
797
+ *
798
+ * `address` is always included whatever you pass, and a value the protocol
799
+ * does not define is dropped. Declare a kind only once `onUpdate` reads
800
+ * `event.new_phone` or `event.new_email` AND your storage has a column for it:
801
+ * the conformance run proves the envelope was accepted, not that the value
802
+ * was written.
803
+ *
804
+ * @example
805
+ * createOneAddressHandler({
806
+ * webhookSecret, privateKeyPem,
807
+ * acceptedUpdateTypes: ['address', 'phone'],
808
+ * async onUpdate(event) {
809
+ * const account = event.customer?.account_number;
810
+ * if (!account) throw new Error('no account number');
811
+ * if (event.new_phone) await db.updatePhone(account, event.new_phone);
812
+ * if (event.address) await db.updateAddress(account, event.address);
813
+ * },
814
+ * });
815
+ */
816
+ acceptedUpdateTypes?: readonly SessionUpdateType[];
817
+ /**
818
+ * Extra hostnames `sendVerifyResult` may POST an `address.verify` result to,
819
+ * beside `oneaddress.io` and its subdomains. For a staging or self-hosted
820
+ * relay ONLY. See {@link VerifyResultCallbackParams.allowedCallbackHosts}.
821
+ */
822
+ allowedCallbackHosts?: readonly string[];
645
823
  }
646
824
  /**
647
825
  * What a {@link IdempotencyStore.claim} call found.
@@ -818,9 +996,12 @@ interface SessionKeyShare {
818
996
  /**
819
997
  * The kinds of changed detail an envelope can carry.
820
998
  *
821
- * The vocabulary is closed. Treat an unrecognised value as "something newer
822
- * than this SDK understands" and ignore that kind rather than failing the whole
823
- * envelope — the fields you DO understand are still valid.
999
+ * The vocabulary is closed. `createOneAddressHandler` REFUSES an envelope that
1000
+ * names a kind this build does not know (`422 invalid_update_types`) rather
1001
+ * than dropping the kind and processing the rest: a dropped kind is a dispatch
1002
+ * that charges the consumer, reports success and delivers less than they asked
1003
+ * for, and the 4xx is what makes OneAddress retry it once you have updated the
1004
+ * SDK. If you decrypt envelopes yourself with `decryptSession`, do the same.
824
1005
  */
825
1006
  type SessionUpdateType = 'address' | 'phone' | 'email';
826
1007
  interface SessionData {
@@ -921,6 +1102,12 @@ interface SessionData {
921
1102
  * @param envelopeB64 - The `session_envelope` base64url string from the webhook.
922
1103
  * @param privateKeyPem - Your PKCS#8 PEM private key whose key_id matches `share.key_id`.
923
1104
  * @param partnerId - Your partner UUID (from the outer webhook payload).
1105
+ * @param expectedAlg - OPTIONAL. The wrap algorithm this key was provisioned
1106
+ * for. When supplied, a `share.alg` that differs is refused
1107
+ * up front as an algorithm downgrade. The webhook HMAC
1108
+ * already binds `share.alg` on the wire, so this is a
1109
+ * belt-and-suspenders pin; leaving it unset preserves the
1110
+ * pre-existing behaviour.
924
1111
  * @returns The decrypted `SessionData`.
925
1112
  * @throws AES-GCM authentication-tag error if:
926
1113
  * - the wrong private key was supplied for `share.key_id`,
@@ -944,7 +1131,7 @@ interface SessionData {
944
1131
  * );
945
1132
  * // data.new_address.street, data.account_number, etc.
946
1133
  */
947
- declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string, partnerId: string): Promise<SessionData>;
1134
+ declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string, expectedAlg?: SessionKeyShare['alg'] | null): Promise<SessionData>;
948
1135
  /**
949
1136
  * Decrypt a OneAddress payload and immediately re-encrypt it to a different
950
1137
  * ECDH P-256 public key — for example, your internal KMS or HSM public key.
@@ -1212,7 +1399,7 @@ declare function verifyD5LOA(loa: OneAddressD5LOA, publicKeyPem: string): Promis
1212
1399
  declare function decryptLoaEncrypted(loaEncrypted: {
1213
1400
  session_envelope: string;
1214
1401
  session_key_share: SessionKeyShare;
1215
- }, privateKeyPem: string, partnerId: string): Promise<OneAddressD5LOA>;
1402
+ }, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<OneAddressD5LOA>;
1216
1403
  /**
1217
1404
  * Validate and narrow the decrypted address payload to `OneAddressAddress`.
1218
1405
  *
@@ -1325,6 +1512,14 @@ interface VerifyResultCallbackParams {
1325
1512
  match: boolean;
1326
1513
  /** Optional free-text note (recorded by OneAddress; not shown to the consumer). */
1327
1514
  note?: string;
1515
+ /**
1516
+ * Extra hostnames the callback may be POSTed to, beside `oneaddress.io` and
1517
+ * its subdomains. `OA_CALLBACK_HOST_ALLOWLIST` (comma-separated) does the
1518
+ * same from the environment. Both are for a staging or self-hosted relay
1519
+ * ONLY: `callback_url` arrives on the wire, so every host added here is a
1520
+ * host a forged `address.verify` could send your callback token to.
1521
+ */
1522
+ allowedCallbackHosts?: readonly string[];
1328
1523
  }
1329
1524
  /**
1330
1525
  * POST an `address.verify` result back to OneAddress, closing the verify loop.
@@ -1357,7 +1552,14 @@ type HandlerResponse = Response;
1357
1552
  * of these, and the compiler is a better guard against that than a comment.
1358
1553
  */
1359
1554
  interface OneAddressTestEvent {
1360
- event: 'address.test';
1555
+ /**
1556
+ * `address.test` is a single-partner connection-verification ping;
1557
+ * `address.test-dispatch` is the same fabricated, encrypted test record sent
1558
+ * by the admin stress test. Both route here — NEVER to `onUpdate` — because
1559
+ * the identity and address inside are fabricated. The field tells them apart
1560
+ * for a handler that wants to (e.g. count stress dispatches separately).
1561
+ */
1562
+ event: 'address.test' | 'address.test-dispatch';
1361
1563
  /** 1-based position within this verification run. */
1362
1564
  index?: number;
1363
1565
  /** How many records this run sends in total. */
@@ -1445,4 +1647,4 @@ interface ExpressLikeResponse {
1445
1647
  */
1446
1648
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1447
1649
 
1448
- 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, 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 };
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 };