@oneaddress/partner-sdk 2.7.0 → 2.8.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
@@ -150,19 +150,6 @@ declare function normalizeForBlindIndex(field: BlindIndexField, value: string):
150
150
  */
151
151
  declare function computeBlindIndex(secret: string, field: BlindIndexField, value: string): Promise<string>;
152
152
 
153
- /** True when a value looks like an email address rather than a person's name. */
154
- declare function isEmailLike(value: string): boolean;
155
- declare function namePoolMatches(providedNames: string[], storedName: string): boolean;
156
- /**
157
- * Find the first stored candidate (a customer's full name plus any known
158
- * aliases) that the provided pool matches, or undefined if none does.
159
- *
160
- * Thin convenience wrapper - `namePoolMatches` takes the whole pool per call,
161
- * so matching against a customer with several stored aliases means trying
162
- * each one; this is that loop, shared so callers don't re-derive it.
163
- */
164
- declare function findMatchingStoredName(providedNames: string[], storedCandidates: readonly string[]): string | undefined;
165
-
166
153
  /**
167
154
  * @oneaddress/protocol
168
155
  *
@@ -178,6 +165,67 @@ declare const CURRENT_VERSION: "2026.1";
178
165
  /** All protocol versions this build of the SDK recognises. */
179
166
  declare const SUPPORTED_VERSIONS: readonly ["2026.1"];
180
167
 
168
+ /** The most typed aliases a v2 record carries. A longer list is malformed. */
169
+ declare const LOA_MAX_TYPED_ALIASES = 3;
170
+ /** The name normalisation every SDK applies before comparing. See the module notes. */
171
+ declare function normaliseLoaName(name: string): string;
172
+ /** The last token of the normalised name, or `''` for a name with none. */
173
+ declare function loaSurname(name: string): string;
174
+ /** The first token of the normalised name, or `''` for a name with none. */
175
+ declare function loaFirstName(name: string): string;
176
+ /** True when the two names are equal after {@link normaliseLoaName}, and not empty. */
177
+ declare function loaNamesMatch(a: string, b: string): boolean;
178
+ /** The shortest first name {@link isAcceptableAlias} treats as a short form. */
179
+ declare const LOA_MIN_SHORT_FORM_LETTERS = 3;
180
+ /**
181
+ * Whether `alias` may stand beside `verifiedName` as a typed alias, compared
182
+ * after {@link normaliseLoaName}:
183
+ *
184
+ * 1. the alias first name (first word) equals the verified first name, OR
185
+ * 2. one first name is a prefix of the other and the shorter has at least
186
+ * {@link LOA_MIN_SHORT_FORM_LETTERS} letters (Tim/Timothy yes, Al/Alexander no).
187
+ *
188
+ * A shared surname alone no longer admits an alias (24 Oct 2026): "Robert
189
+ * Hooper" beside "Timothy Hooper" names a relative as readily as the consumer,
190
+ * and a married or changed surname is the case aliases exist for, which keeps
191
+ * the first name. A single word is its own first name. An empty name on
192
+ * either side is never acceptable. "Letters" are Unicode code points of the
193
+ * normalised token, so every language counts the same way.
194
+ */
195
+ declare function isAcceptableAlias(verifiedName: string, alias: string): boolean;
196
+ /**
197
+ * The typed aliases a record may carry, in their original order and spelling:
198
+ * strings only, not the verified name itself, no duplicates (compared
199
+ * normalised), encodable by {@link canonicalLoaV2}, admitted by
200
+ * {@link isAcceptableAlias}, then the first {@link LOA_MAX_TYPED_ALIASES}.
201
+ *
202
+ * Filter first, then cap, so a refused alias never takes a slot. Every caller
203
+ * (the browser before sealing, the relay before signing, every SDK before
204
+ * handing names to a recipient) runs this one function, so the three agree on
205
+ * the same input. Dropped, never refused: a stale or wrong alias is the
206
+ * consumer's typing and not an attack on the update.
207
+ */
208
+ declare function acceptTypedAliases(verifiedName: string, aliases: readonly unknown[] | null | undefined): string[];
209
+ /**
210
+ * Codes an SDK refuses a v2 LOA with. Shared so a recipient's logs read the same
211
+ * whichever language received the dispatch.
212
+ */
213
+ declare const LOA_V2_REFUSALS: readonly ["loa_v2_malformed", "loa_v2_signature_invalid", "loa_v2_partner_mismatch", "loa_v2_update_mismatch", "loa_v2_envelope_mismatch", "loa_v2_name_mismatch"];
214
+ type LoaV2Refusal = typeof LOA_V2_REFUSALS[number];
215
+
216
+ /** True when a value looks like an email address rather than a person's name. */
217
+ declare function isEmailLike(value: string): boolean;
218
+ declare function namePoolMatches(providedNames: string[], storedName: string): boolean;
219
+ /**
220
+ * Find the first stored candidate (a customer's full name plus any known
221
+ * aliases) that the provided pool matches, or undefined if none does.
222
+ *
223
+ * Thin convenience wrapper - `namePoolMatches` takes the whole pool per call,
224
+ * so matching against a customer with several stored aliases means trying
225
+ * each one; this is that loop, shared so callers don't re-derive it.
226
+ */
227
+ declare function findMatchingStoredName(providedNames: string[], storedCandidates: readonly string[]): string | undefined;
228
+
181
229
  /**
182
230
  * Draining the outbox.
183
231
  *
@@ -616,6 +664,8 @@ interface OneAddressAddress {
616
664
  }
617
665
  interface OneAddressCustomer {
618
666
  email: string;
667
+ /** The name the consumer gave. Consumer-supplied and unverified; see
668
+ * `known_names` for how to use it. */
619
669
  name: string;
620
670
  /** Account/policy/membership number the customer provided for this service.
621
671
  * Null when the guest did not enter an account ref, or for account-flow
@@ -623,8 +673,13 @@ interface OneAddressCustomer {
623
673
  * your records. */
624
674
  account_number: string | null;
625
675
  /** Additional names the customer is known by (maiden name, nickname, etc.).
626
- * Always an array; empty when no aliases were provided. Partners should
627
- * check `name` and each entry in `known_names` when matching their records. */
676
+ * Always an array; empty when no aliases were provided.
677
+ *
678
+ * `name` and `known_names` are CONSUMER-SUPPLIED: typed by the consumer and
679
+ * sealed in their browser, not checked by OneAddress against any document.
680
+ * Find the record by your own key (the account number you issued), then
681
+ * match these against the name on it with {@link namePoolMatches}. Never
682
+ * pick a record because one of these names matched it. */
628
683
  known_names: string[];
629
684
  }
630
685
  /**
@@ -641,7 +696,7 @@ interface OneAddressCustomer {
641
696
  * Nothing about the consumer is knowable before decryption, so match on the
642
697
  * decrypted payload. Which field holds the ciphertext depends on the event: a
643
698
  * D5 dispatch carries `session_envelope`, whose `SessionData` gives the
644
- * verified name, known names and account number; the legacy-shaped
699
+ * consumer-supplied name, known names and account number; the legacy-shaped
645
700
  * `address.verify` carries `address_encrypted` instead, which this SDK decrypts
646
701
  * for you (see {@link OneAddressVerifyEvent.raw}).
647
702
  *
@@ -911,8 +966,11 @@ interface HandlerConfirmOptions {
911
966
  * confirm secret is the ONLY thing accepted once it exists.
912
967
  */
913
968
  confirmSecret: string;
914
- /** Override the OneAddress base URL. Defaults to https://oneaddress.io */
969
+ /** Override the OneAddress base URL. Defaults to https://oneaddress.io.
970
+ * Checked as {@link ConfirmUpdateOptions.appBaseUrl} is. */
915
971
  oneAddressApi?: string;
972
+ /** Extra hosts `oneAddressApi` may name. See {@link ConfirmUpdateOptions.allowedHosts}. */
973
+ allowedHosts?: readonly string[];
916
974
  /** Inject a fetch implementation, mainly for tests. */
917
975
  fetchImpl?: typeof fetch;
918
976
  }
@@ -986,12 +1044,19 @@ interface OneAddressHandlerOptions {
986
1044
  /**
987
1045
  * OPTIONAL — OneAddress's ECDSA P-256 LOA signing public key (SPKI PEM), from
988
1046
  * {@link fetchLoaPublicKey}. Applies to `address.updated` ONLY (both the D5
989
- * and legacy sub-paths, wherever `loa_encrypted` is present). When set, the
990
- * handler decrypts `loa_encrypted`, verifies the signed D5 LOA, and REJECTS
991
- * the dispatch (500) if the signature is invalid - you never process an
992
- * update whose consent proof doesn't verify. When unset, the decrypted LOA
993
- * is still passed to your handler as `event.loa` (and `event.loa_ref`) for
994
- * you to verify yourself. Cache the key; it only changes on a planned rotation.
1047
+ * and legacy sub-paths, wherever `loa_encrypted` is present). The handler
1048
+ * decrypts `loa_encrypted`, verifies the signed D5 LOA, and REJECTS the
1049
+ * dispatch (500) if the signature is invalid - you never process an update
1050
+ * whose consent proof doesn't verify.
1051
+ *
1052
+ * WHEN UNSET (2.8.0), the handler fetches the published key from
1053
+ * `{loaPublicKeyBaseUrl}/.well-known/oneaddress-loa-key.pem` on first use and
1054
+ * caches it for a day, because {@link OneAddressHandlerOptions.requireLoa} is
1055
+ * now on by default and a required consent proof that nobody checks is not a
1056
+ * control. An unreachable key refuses the dispatch (500, so OneAddress
1057
+ * retries) with an error naming both ways out. Pin it here to avoid the
1058
+ * fetch. Only with `requireLoa: false` and no key is the LOA left unverified,
1059
+ * passed to your handler as `event.loa` for you to check yourself.
995
1060
  *
996
1061
  * `address.verify`'s `event.loa` is a separate, still-cleartext legacy
997
1062
  * shape ({@link OneAddressLOA}) read directly off the wire - this option
@@ -1006,9 +1071,16 @@ interface OneAddressHandlerOptions {
1006
1071
  loaPublicKeyPem?: string;
1007
1072
  /**
1008
1073
  * Refuse an `address.updated` / `contact.updated` dispatch that carries no
1009
- * `loa_encrypted` at all. Defaults to `true` when `loaPublicKeyPem` is set
1010
- * and `false` otherwise.
1011
- *
1074
+ * `loa_encrypted` at all, or one whose LOA does not verify against
1075
+ * OneAddress's key. **Defaults to `true` (2.8.0).** It used to default to
1076
+ * `true` only when `loaPublicKeyPem` was set, so a receiver configured with
1077
+ * a webhook secret and nothing else accepted any dispatch that secret
1078
+ * signed: whoever held the secret could impersonate OneAddress. With it on,
1079
+ * a dispatch also needs a consent proof signed by OneAddress's offline LOA
1080
+ * key, which the webhook secret cannot produce. Opt out only with an
1081
+ * explicit `requireLoa: false`.
1082
+ *
1083
+ * BEFORE 2.8.0 the default followed the key:
1012
1084
  * WHY THE DEFAULT FOLLOWS THE KEY. Until 2.1.0 setting `loaPublicKeyPem`
1013
1085
  * verified the consent proof only when one arrived: a dispatch with the
1014
1086
  * block simply omitted was processed with no check at all, so "verified"
@@ -1024,6 +1096,13 @@ interface OneAddressHandlerOptions {
1024
1096
  * in the log rather than silent.
1025
1097
  */
1026
1098
  requireLoa?: boolean;
1099
+ /**
1100
+ * Where the handler fetches OneAddress's LOA public key from when
1101
+ * `loaPublicKeyPem` is unset and `requireLoa` is on. Default
1102
+ * `https://oneaddress.io`. Held to the same host allowlist and https rule as
1103
+ * {@link fetchLoaPublicKey}; a disallowed value throws at construction.
1104
+ */
1105
+ loaPublicKeyBaseUrl?: string;
1027
1106
  /**
1028
1107
  * OPTIONAL. Close the confirm loop from inside the handler.
1029
1108
  *
@@ -1042,6 +1121,13 @@ interface OneAddressHandlerOptions {
1042
1121
  * count against you.
1043
1122
  */
1044
1123
  confirm?: HandlerConfirmOptions;
1124
+ /**
1125
+ * Your partner UUID. Optional. When set (or when `confirm.partnerId` is), a
1126
+ * v2 LOA must have been signed for exactly this id; otherwise it is compared
1127
+ * with the `partner_id` of the HMAC-signed body, which is what every decrypt
1128
+ * step already uses. Setting it is the stronger check.
1129
+ */
1130
+ partnerId?: string;
1045
1131
  /**
1046
1132
  * Called when a consumer dispatches an address update to you.
1047
1133
  *
@@ -1153,6 +1239,21 @@ interface OneAddressHandlerOptions {
1153
1239
  * else is refused at construction, since `NaN` here accepts every timestamp.
1154
1240
  */
1155
1241
  timestampToleranceSecs?: number;
1242
+ /**
1243
+ * The largest request body the handler will read, in bytes. Default
1244
+ * 1 MiB (1048576); a real dispatch is a few kilobytes.
1245
+ *
1246
+ * WHY IT EXISTS. The signature is an HMAC over the whole body, so the body
1247
+ * has to be read before anyone knows whether the sender holds the secret.
1248
+ * Until this option the handler read it with no cap at all, which let an
1249
+ * unauthenticated caller make the receiver buffer and hash as much as it
1250
+ * cared to send. Now a declared `Content-Length` over the cap is refused
1251
+ * before reading, and the stream is read with the cap enforced as it
1252
+ * arrives, both BEFORE the HMAC. Either answers `413`.
1253
+ *
1254
+ * Refused at construction unless it is a positive integer.
1255
+ */
1256
+ maxBodyBytes?: number;
1156
1257
  /**
1157
1258
  * Idempotency store for deduplicating repeated webhook deliveries.
1158
1259
  *
@@ -1243,10 +1344,26 @@ interface OneAddressHandlerOptions {
1243
1344
  * completion. **Process it again.** This is the case a naive "seen set" gets
1244
1345
  * wrong: if the first attempt died after being recorded, skipping the retry
1245
1346
  * loses the update permanently while both sides report success.
1347
+ * - `in-progress` - seen, not completed, and the earlier claim is still
1348
+ * inside its lease: another delivery of the same dispatch is being
1349
+ * processed right now. **Do not process it.** The handler answers
1350
+ * `503 dispatch_in_progress` with `Retry-After`, so OneAddress comes back
1351
+ * once the first attempt has either completed (the retry is then a
1352
+ * `duplicate`) or died (the lease expires and the retry is a
1353
+ * `retry-after-incomplete`).
1246
1354
  * - `duplicate` — seen and completed. Skip; the handler responds
1247
1355
  * `200 { ok: true, duplicate: true }`.
1356
+ *
1357
+ * WHY `in-progress` EXISTS (Oct 2026 audit). Without it a store could only say
1358
+ * "incomplete", and incomplete covers two different states: an attempt that
1359
+ * died, and an attempt that is still running. Both were answered
1360
+ * `retry-after-incomplete`, so a second delivery arriving while the first was
1361
+ * mid-`onUpdate` (OneAddress times a slow receiver out at about ten seconds
1362
+ * and retries) ran the update a second time, concurrently. A lease is what
1363
+ * tells the two apart. A store written before this value existed never returns
1364
+ * it and behaves exactly as it did.
1248
1365
  */
1249
- type IdempotencyClaim = 'fresh' | 'retry-after-incomplete' | 'duplicate';
1366
+ type IdempotencyClaim = 'fresh' | 'retry-after-incomplete' | 'in-progress' | 'duplicate';
1250
1367
  interface IdempotencyStore {
1251
1368
  /**
1252
1369
  * Legacy check. Ignored when {@link IdempotencyStore.claim} is present.
@@ -1263,7 +1380,12 @@ interface IdempotencyStore {
1263
1380
  *
1264
1381
  * Must be a single atomic operation (an `INSERT … ON CONFLICT DO NOTHING`,
1265
1382
  * a Redis `SET NX`, a conditional write) — otherwise concurrent retries can
1266
- * both claim the same dispatch.
1383
+ * both claim the same dispatch. Taking over a STALE claim must be atomic
1384
+ * too (a conditional update on the claim time), or two retries arriving
1385
+ * after a crash both take it over.
1386
+ *
1387
+ * Return `in-progress` for a claim that is incomplete and still inside its
1388
+ * lease; see {@link IdempotencyClaim}.
1267
1389
  */
1268
1390
  claim?(dispatchId: string): Promise<IdempotencyClaim>;
1269
1391
  /**
@@ -1272,6 +1394,18 @@ interface IdempotencyStore {
1272
1394
  * incomplete so the next retry re-processes it.
1273
1395
  */
1274
1396
  complete?(dispatchId: string): Promise<void>;
1397
+ /**
1398
+ * OPTIONAL. Give up a claim that did not complete, so the next delivery can
1399
+ * take it at once instead of waiting out the lease. The handler calls it on
1400
+ * every exit after a successful `claim` that did not reach `complete`: a
1401
+ * throwing `onUpdate` (500), a refused update kind (422), a missing key
1402
+ * (503), and the events that never complete a claim at all.
1403
+ *
1404
+ * Without it a lease-keeping store makes the retry of a failed attempt wait
1405
+ * for the lease to expire, answering `in-progress` meanwhile. That is safe
1406
+ * (nothing runs twice) and only slower.
1407
+ */
1408
+ release?(dispatchId: string): Promise<void>;
1275
1409
  }
1276
1410
 
1277
1411
  /**
@@ -1311,6 +1445,8 @@ interface IdempotencyStore {
1311
1445
  */
1312
1446
  /** The databases {@link createSqlIdempotencyStore} generates SQL for. */
1313
1447
  type IdempotencyDialect = 'postgres' | 'sqlite' | 'mysql' | 'mssql';
1448
+ /** Default `leaseSeconds` for {@link createSqlIdempotencyStore}. */
1449
+ declare const DEFAULT_IDEMPOTENCY_LEASE_SECS = 120;
1314
1450
  declare function createSqlIdempotencyStore(opts: {
1315
1451
  /**
1316
1452
  * Run parameterised SQL and return the result rows. Must not swallow errors —
@@ -1337,6 +1473,24 @@ declare function createSqlIdempotencyStore(opts: {
1337
1473
  * for mssql). Override only if your driver rewrites placeholders.
1338
1474
  */
1339
1475
  placeholder?: (n: number) => string;
1476
+ /**
1477
+ * How long an incomplete claim is presumed still running, in seconds.
1478
+ * Default 120. Inside it a second delivery of the same dispatch is answered
1479
+ * `in-progress` (the handler says `503` with `Retry-After`) instead of being
1480
+ * processed alongside the first; past it the claim is presumed dead and the
1481
+ * next delivery takes it over as `retry-after-incomplete`.
1482
+ *
1483
+ * Set it above the longest your `onUpdate` can run. `0` turns the lease off
1484
+ * and restores the behaviour before it existed, where every incomplete
1485
+ * claim was retried at once, including one still running.
1486
+ *
1487
+ * THE CLAIM TIME IS `received_at`, the column the table already has, so no
1488
+ * schema change is needed: a fresh claim stamps it by its `DEFAULT`, and a
1489
+ * takeover re-stamps it in the same conditional `UPDATE` that decides who
1490
+ * won. All the time arithmetic runs in the database, against the same clock
1491
+ * that wrote the column.
1492
+ */
1493
+ leaseSeconds?: number;
1340
1494
  }): IdempotencyStore;
1341
1495
  /**
1342
1496
  * Verify the HMAC-SHA256 webhook signature.
@@ -1457,6 +1611,16 @@ interface SessionData {
1457
1611
  v: 2;
1458
1612
  update_uid?: string;
1459
1613
  dispatch_timestamp?: string;
1614
+ /**
1615
+ * The name the consumer gave, for you to match against YOUR record.
1616
+ *
1617
+ * NOT VERIFIED, whatever the field is called (the name is wire format and
1618
+ * stays). The envelope is sealed in the consumer's browser, so this is
1619
+ * whatever they typed. Identity verification proves who authorised the
1620
+ * dispatch; it does not prove this string is the name on your account.
1621
+ * Look the account up by your own key and compare with
1622
+ * {@link namePoolMatches}; never use this to choose the record.
1623
+ */
1460
1624
  verified_name: string;
1461
1625
  /**
1462
1626
  * Which kinds of detail this envelope concerns.
@@ -1518,6 +1682,11 @@ interface SessionData {
1518
1682
  new_email?: string;
1519
1683
  account_number: string;
1520
1684
  id_verification_ref: string;
1685
+ /**
1686
+ * Other names the consumer says they go by. Consumer-supplied and
1687
+ * unverified, exactly as {@link SessionData.verified_name} is: a pool to
1688
+ * match against your own record, never a key to look one up by.
1689
+ */
1521
1690
  known_names?: string[];
1522
1691
  }
1523
1692
  /**
@@ -1566,10 +1735,18 @@ interface SessionData {
1566
1735
  * - or the share was forged.
1567
1736
  *
1568
1737
  * @example
1569
- * import { decryptSession } from '@oneaddress/partner-sdk';
1738
+ * import { decryptSession, isFreshTimestamp, verifySignature } from '@oneaddress/partner-sdk';
1570
1739
  *
1571
1740
  * // Body of an address.updated webhook.
1572
- * const body = await req.json();
1741
+ * // Freshness and signature FIRST, over the raw bytes. Decrypting a body
1742
+ * // you have not verified trusts whoever sent it.
1743
+ * const rawBody = await req.text();
1744
+ * const ts = req.headers.get('x-oneaddress-timestamp') ?? '';
1745
+ * const sig = req.headers.get('x-oneaddress-signature') ?? '';
1746
+ * if (!isFreshTimestamp(ts) || !verifySignature(rawBody, sig, ts, process.env.OA_WEBHOOK_SECRET!)) {
1747
+ * return new Response('invalid signature', { status: 401 });
1748
+ * }
1749
+ * const body = JSON.parse(rawBody);
1573
1750
  * const myPrivateKey = keyStore.get(body.session_key_share.key_id);
1574
1751
  * if (!myPrivateKey) throw new Error(`No private key for ${body.session_key_share.key_id}`);
1575
1752
  *
@@ -1579,7 +1756,8 @@ interface SessionData {
1579
1756
  * myPrivateKey,
1580
1757
  * body.partner_id,
1581
1758
  * );
1582
- * // data.new_address.street, data.account_number, etc.
1759
+ * // data.new_address.street, data.account_number, etc. data.verified_name and
1760
+ * // data.known_names are consumer-supplied: match them against your record.
1583
1761
  */
1584
1762
  declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string, expectedAlg?: SessionKeyShare['alg'] | null): Promise<SessionData>;
1585
1763
  /**
@@ -1602,16 +1780,27 @@ declare function decryptSession(share: SessionKeyShare, envelopeB64: string, pri
1602
1780
  * @returns A fresh `EncryptedPayload` encrypted to `recipientSpkiPem`
1603
1781
  *
1604
1782
  * @example
1783
+ * // From your own route, on the raw webhook body. Inside `onUpdate` the
1784
+ * // payload is already decrypted and `event.raw` holds plaintext, not this.
1785
+ * // Freshness and signature FIRST, over the raw bytes. Decrypting a body
1786
+ * // you have not verified trusts whoever sent it.
1787
+ * const rawBody = await req.text();
1788
+ * const ts = req.headers.get('x-oneaddress-timestamp') ?? '';
1789
+ * const sig = req.headers.get('x-oneaddress-signature') ?? '';
1790
+ * if (!isFreshTimestamp(ts) || !verifySignature(rawBody, sig, ts, process.env.OA_WEBHOOK_SECRET!)) {
1791
+ * return new Response('invalid signature', { status: 401 });
1792
+ * }
1793
+ * const body = JSON.parse(rawBody);
1605
1794
  * const kmsBlob = await transformAddress(
1606
- * event.raw.address_encrypted as EncryptedPayload,
1795
+ * body.address_encrypted as EncryptedPayload,
1607
1796
  * process.env.OA_PRIVATE_KEY_PEM!,
1608
- * event.partner_id,
1797
+ * body.partner_id,
1609
1798
  * process.env.KMS_PUBLIC_KEY_SPKI_PEM!,
1610
1799
  * );
1611
- * // Key on the account number, NOT on `customer.email`: that field is always
1612
- * // '' on a dispatch, so keying on it files every partner's addresses under
1613
- * // one empty-string row, silently and without an error.
1614
- * await db.storeEncryptedAddress(event.customer?.account_number, kmsBlob);
1800
+ * // File by dispatch, NOT on `customer.email`: that field is always '' on a
1801
+ * // dispatch, so keying on it files every partner's addresses under one
1802
+ * // empty-string row, silently and without an error.
1803
+ * await db.storeEncryptedAddress(body.dispatch_id, kmsBlob);
1615
1804
  */
1616
1805
  declare function transformAddress(payload: EncryptedPayload, privateKeyPem: string, partnerId: string, recipientSpkiPem: string): Promise<EncryptedPayload>;
1617
1806
  /**
@@ -1647,9 +1836,17 @@ declare function transformAddress(payload: EncryptedPayload, privateKeyPem: stri
1647
1836
  * @returns A fresh `EncryptedPayload` encrypted to `recipientSpkiPem`.
1648
1837
  *
1649
1838
  * @example
1650
- * import { transformSession } from '@oneaddress/partner-sdk';
1651
- *
1652
- * const body = await req.json();
1839
+ * import { transformSession, isFreshTimestamp, verifySignature } from '@oneaddress/partner-sdk';
1840
+ *
1841
+ * // Freshness and signature FIRST, over the raw bytes. Decrypting a body
1842
+ * // you have not verified trusts whoever sent it.
1843
+ * const rawBody = await req.text();
1844
+ * const ts = req.headers.get('x-oneaddress-timestamp') ?? '';
1845
+ * const sig = req.headers.get('x-oneaddress-signature') ?? '';
1846
+ * if (!isFreshTimestamp(ts) || !verifySignature(rawBody, sig, ts, process.env.OA_WEBHOOK_SECRET!)) {
1847
+ * return new Response('invalid signature', { status: 401 });
1848
+ * }
1849
+ * const body = JSON.parse(rawBody);
1653
1850
  * const myPrivateKey = keyStore.get(body.session_key_share.key_id);
1654
1851
  * const kmsBlob = await transformSession(
1655
1852
  * body.session_key_share,
@@ -1658,7 +1855,8 @@ declare function transformAddress(payload: EncryptedPayload, privateKeyPem: stri
1658
1855
  * body.partner_id,
1659
1856
  * process.env.KMS_PUBLIC_KEY_SPKI_PEM!,
1660
1857
  * );
1661
- * await db.storeEncryptedAddress(body.customer.email, kmsBlob);
1858
+ * // No cleartext customer block exists under D5: file by dispatch.
1859
+ * await db.storeEncryptedAddress(body.dispatch_id, kmsBlob);
1662
1860
  */
1663
1861
  declare function transformSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string, recipientSpkiPem: string): Promise<EncryptedPayload>;
1664
1862
  /**
@@ -1704,8 +1902,18 @@ interface ConfirmUpdateOptions {
1704
1902
  loaRef?: string;
1705
1903
  /** The name you matched in your own records, if you want it recorded. */
1706
1904
  memberName?: string;
1707
- /** Override the consumer-app base URL. Defaults to https://oneaddress.io */
1905
+ /**
1906
+ * Override the consumer-app base URL. Defaults to https://oneaddress.io.
1907
+ * Must be https on `oneaddress.io` or `app.oneaddress.io` (or a host in
1908
+ * `allowedHosts`); plain http is accepted for localhost outside production
1909
+ * only. Anything else is refused before the secret leaves the process.
1910
+ */
1708
1911
  appBaseUrl?: string;
1912
+ /**
1913
+ * Extra hostnames `appBaseUrl` may name, for a staging or self-hosted relay
1914
+ * ONLY. Every host added here is a host your confirm secret is sent to.
1915
+ */
1916
+ allowedHosts?: readonly string[];
1709
1917
  /** Inject a fetch implementation, mainly for tests. */
1710
1918
  fetchImpl?: typeof fetch;
1711
1919
  }
@@ -1788,6 +1996,23 @@ declare function confirmUpdate(opts: ConfirmUpdateOptions): Promise<ConfirmUpdat
1788
1996
  * const ok = await verifyLOA(event.loa, loaPublicKey);
1789
1997
  */
1790
1998
  declare function fetchLoaPublicKey(appBaseUrl?: string): Promise<string>;
1999
+ /** How long a fetched LOA key is reused before it is fetched again. */
2000
+ declare const LOA_PUBLIC_KEY_CACHE_MS: number;
2001
+ /** Thrown when the handler needs OneAddress's LOA key and cannot get it. */
2002
+ declare class LoaPublicKeyUnavailableError extends Error {
2003
+ readonly from: string;
2004
+ constructor(from: string, cause: string);
2005
+ }
2006
+ /**
2007
+ * The LOA key for `appBaseUrl`, fetched once and reused for
2008
+ * {@link LOA_PUBLIC_KEY_CACHE_MS}. Concurrent first calls share one fetch. A
2009
+ * failed refresh falls back to the key already held, because the key changes
2010
+ * only on an announced rotation and an outage of our well-known endpoint
2011
+ * should not stop a receiver that already holds it. Never caches a failure.
2012
+ */
2013
+ declare function cachedLoaPublicKey(appBaseUrl?: string, now?: number): Promise<string>;
2014
+ /** Forget every cached LOA key. Exported for the SDK's own tests. */
2015
+ declare function _resetLoaKeyCacheForTests(): void;
1791
2016
  /**
1792
2017
  * Verify the ECDSA P-256 signature on a OneAddress Letter of Authority.
1793
2018
  *
@@ -1831,13 +2056,42 @@ declare function verifyLOA(loa: OneAddressLOA, publicKeyPem: string): Promise<bo
1831
2056
  * key — it never travels in cleartext.
1832
2057
  */
1833
2058
  interface OneAddressD5LOA {
2059
+ /**
2060
+ * The identity-verified legal name of the person who authorised the update.
2061
+ * Since 24 Oct 2026 OneAddress fills this from the identity check, never from
2062
+ * anything the consumer typed. Compare the envelope's `verified_name` with it
2063
+ * through {@link loaNamesMatch}; the handler does so whenever v2 is present.
2064
+ */
1834
2065
  consumer_name: string;
1835
2066
  authorisation_date: string;
1836
2067
  scope: string;
1837
2068
  update_uid: string;
1838
2069
  oneaddress_acn: string;
2070
+ /** Version 1 signature, over {@link canonicalD5LoaForm}. Always present. */
1839
2071
  oneaddress_signature: string;
1840
2072
  signature_algorithm: 'ECDSA-P256' | 'HMAC-SHA256';
2073
+ /**
2074
+ * VERSION 2 (24 Oct 2026). Present on every LOA OneAddress signs from that
2075
+ * date; absent on earlier ones, which verify exactly as before.
2076
+ *
2077
+ * v2 is signed once per recipient and binds the recipient (`partner_id`) and
2078
+ * the envelope it travels beside (`envelope_sha256`), so a genuine LOA cannot
2079
+ * be reused at another recipient or beside a different envelope. See
2080
+ * {@link checkLoaV2} for what is checked and in which order.
2081
+ */
2082
+ partner_id?: string;
2083
+ /** Lowercase hex SHA-256 of the envelope as received. See {@link loaEnvelopeSha256}. */
2084
+ envelope_sha256?: string;
2085
+ /**
2086
+ * Names the CONSUMER typed, never verified: at most three, admitted by the
2087
+ * alias rule (same first name, or a short form of it of at least three letters). Always
2088
+ * present on a v2 LOA, possibly empty. Kept apart from `consumer_name` so a
2089
+ * typed alias can never be read as the verified name. Read them through
2090
+ * {@link typedAliasesOf}, which re-applies the rule.
2091
+ */
2092
+ consumer_typed_aliases?: string[];
2093
+ /** Signature over {@link canonicalD5LoaFormV2}, same key and encoding as v1. */
2094
+ oneaddress_signature_v2?: string;
1841
2095
  }
1842
2096
  /**
1843
2097
  * The exact canonical string OneAddress signs for a D5 LOA — must be
@@ -1877,12 +2131,97 @@ declare function decryptLoaEncrypted(loaEncrypted: {
1877
2131
  }, privateKeyPem: string | PrivateKeyOperations, partnerId: string,
1878
2132
  /** Same pin as {@link decryptSession}'s `expectedAlg`; the LOA is wrapped to the same key. */
1879
2133
  expectedAlg?: SessionKeyShare['alg'] | null): Promise<OneAddressD5LOA>;
2134
+ /** True when this LOA carries a v2 signature, so {@link checkLoaV2} applies. */
2135
+ declare function hasLoaV2(loa: OneAddressD5LOA): boolean;
2136
+ /**
2137
+ * The exact string OneAddress signs for a v2 LOA: length-prefixed rather than
2138
+ * pipe-joined, so no field can shift another's boundary. Throws when a field is
2139
+ * missing or contains a control character, which {@link checkLoaV2} reports as
2140
+ * `loa_v2_malformed`. The definition and its test vectors live in
2141
+ * `@oneaddress/protocol` and every SDK reproduces them byte for byte.
2142
+ */
2143
+ declare function canonicalD5LoaFormV2(loa: OneAddressD5LOA): string;
2144
+ /**
2145
+ * `envelope_sha256` for what you received: the `session_envelope` string exactly
2146
+ * as it arrived, or for a legacy dispatch the `address_encrypted` object's four
2147
+ * fields in a fixed encoding. Lowercase hex.
2148
+ */
2149
+ declare function loaEnvelopeSha256(envelope: string | EncryptedPayload): string;
2150
+ /** Verify the v2 signature. `false` for an invalid signature, a malformed LOA, or HMAC. */
2151
+ declare function verifyD5LOAv2(loa: OneAddressD5LOA, publicKeyPem: string): Promise<boolean>;
2152
+ /** What {@link checkLoaV2} compares a v2 LOA against. */
2153
+ interface LoaV2Context {
2154
+ /** The partner id this receiver is configured as. */
2155
+ partnerId: string;
2156
+ /** `update_id` from the signed webhook body, as parsed. */
2157
+ updateId: unknown;
2158
+ /** The envelope as received: `session_envelope`, or the legacy `address_encrypted`. */
2159
+ envelope: string | EncryptedPayload;
2160
+ /** The decrypted envelope's name: `verified_name`, or the legacy blob's `fullName`. */
2161
+ envelopeVerifiedName: unknown;
2162
+ /** OneAddress's LOA key. Omit and the signature is not checked; the bindings still are. */
2163
+ publicKeyPem?: string;
2164
+ }
2165
+ /**
2166
+ * The typed aliases a recipient may rely on, from a v2 LOA: its signed
2167
+ * `consumer_typed_aliases`, re-checked against the verified name by the shared
2168
+ * rule and capped at three. The envelope's `known_names` are NOT used for a v2
2169
+ * LOA: the signed list is the one OneAddress vouches for. `[]` for a v1 LOA.
2170
+ */
2171
+ declare function typedAliasesOf(loa: OneAddressD5LOA): string[];
2172
+ /**
2173
+ * Every check a v2 LOA must pass, in the shared order, returning the first
2174
+ * refusal or `null`:
2175
+ *
2176
+ * 1. `loa_v2_malformed` a v2 field missing, or one the form refuses
2177
+ * 2. `loa_v2_signature_invalid` when `publicKeyPem` is given
2178
+ * 3. `loa_v2_partner_mismatch` signed for another recipient
2179
+ * 4. `loa_v2_update_mismatch` `update_uid` is not the body's `update_id`
2180
+ * 5. `loa_v2_envelope_mismatch` signed beside a different envelope
2181
+ * 6. `loa_v2_name_mismatch` the envelope's verified name is not the LOA's
2182
+ *
2183
+ * The name comparison is {@link loaNamesMatch}: case, whitespace and diacritics
2184
+ * are folded, nothing else is. Only the VERIFIED name is compared here: a typed
2185
+ * alias never satisfies it. Aliases come second, from {@link typedAliasesOf},
2186
+ * and are dropped rather than refused. The handler runs this whenever
2187
+ * {@link hasLoaV2}, and an LOA without v2 is handled exactly as it was before
2188
+ * v2 existed.
2189
+ */
2190
+ declare function checkLoaV2(loa: OneAddressD5LOA, ctx: LoaV2Context): Promise<LoaV2Refusal | null>;
2191
+ /** Thrown by the handler for a v2 LOA that fails {@link checkLoaV2}; carries the refusal code. */
2192
+ declare class LoaV2RefusedError extends Error {
2193
+ readonly code: LoaV2Refusal;
2194
+ constructor(code: LoaV2Refusal);
2195
+ }
1880
2196
  /**
1881
- * Validate and narrow the decrypted address payload to `OneAddressAddress`.
2197
+ * The longest value any one address field may carry, in characters.
1882
2198
  *
1883
- * Throws a descriptive `Error` if any required field is absent or not a string.
1884
- * Call this after `decryptAddress()` when you want explicit failure rather than
1885
- * silently receiving `undefined` for a missing field.
2199
+ * Generous for any real street line, and far short of what a consumer could
2200
+ * otherwise seal into the blob for a receiver to write into a VARCHAR column,
2201
+ * a log line or a CRM field. A field over it is refused, not truncated: a
2202
+ * truncated street is a different address that still looks like one.
2203
+ */
2204
+ declare const MAX_ADDRESS_FIELD_CHARS = 512;
2205
+ /**
2206
+ * Validate the decrypted address payload and return a NEW `OneAddressAddress`
2207
+ * built from its six named fields and nothing else.
2208
+ *
2209
+ * Throws a descriptive `Error` if any required field is absent, not a string,
2210
+ * or longer than {@link MAX_ADDRESS_FIELD_CHARS}. `updated_at` is optional on
2211
+ * the way in (a string or a number; absent reads as `''`).
2212
+ *
2213
+ * ── WHY IT COPIES RATHER THAN NARROWS (Oct 2026 audit) ─────────────────────
2214
+ *
2215
+ * Until this release it returned the object it was given, cast. On the legacy
2216
+ * `address_encrypted` paths that object is the whole decrypted blob, and the
2217
+ * blob is sealed in the CONSUMER's browser, so every key in it is the
2218
+ * consumer's choice. The README's own examples then spread it into the
2219
+ * partner's row, `{ id: record.id, ...event.address }`, and a blob carrying
2220
+ * `id` or `accountNumber` redirected the write to another customer's record.
2221
+ * The D5 path always built the address from named fields; every path now
2222
+ * does, so `event.address` holds exactly the six keys its type names. The
2223
+ * whole blob is still on `event.raw` for anyone who needs it, and is
2224
+ * consumer-supplied there too.
1886
2225
  *
1887
2226
  * `createOneAddressHandler` runs this automatically before calling `onUpdate`
1888
2227
  * and `onVerify`, so SDK users get validation for free.
@@ -1890,7 +2229,7 @@ expectedAlg?: SessionKeyShare['alg'] | null): Promise<OneAddressD5LOA>;
1890
2229
  * @example
1891
2230
  * const raw = await decryptAddress(payload, privateKeyPem, partnerId);
1892
2231
  * const address = validateAddress(raw); // throws if malformed
1893
- * await db.updateAddress(address);
2232
+ * await db.updateAddress(customerId, address);
1894
2233
  */
1895
2234
  declare function validateAddress(raw: unknown): OneAddressAddress;
1896
2235
  /**
@@ -1915,6 +2254,7 @@ interface AddressParts {
1915
2254
  * one copy silently left the others behind. Prefer this over re-implementing it.
1916
2255
  *
1917
2256
  * @example
2257
+ * // Only after verifySignature has passed on the raw body; see decryptSession.
1918
2258
  * const data = await decryptSession(share, envelope, privateKeyPem, partnerId);
1919
2259
  * const parts = readAddressParts(data.new_address);
1920
2260
  * await db.updateAddress({ id, line1: parts.line1 || row.line1, ... });
@@ -2068,6 +2408,8 @@ interface OneAddressTestEvent {
2068
2408
  }
2069
2409
  /** Reset the once-per-process warning flags. Exported for the SDK's own tests. */
2070
2410
  declare function _resetOnceWarningsForTests(): void;
2411
+ /** Default {@link OneAddressHandlerOptions.maxBodyBytes}: 1 MiB. */
2412
+ declare const DEFAULT_MAX_BODY_BYTES = 1048576;
2071
2413
  /**
2072
2414
  * Create a framework-agnostic OneAddress webhook handler.
2073
2415
  * Returns a function compatible with Next.js App Router route handlers,
@@ -2167,6 +2509,12 @@ interface SignedTestWebhookOptions {
2167
2509
  * envelope's `update_uid`, with a PLACEHOLDER signature that fails
2168
2510
  * {@link verifyD5LOA}. Pass `loaSigningKeyPem` to sign it for real, or
2169
2511
  * `false` to omit `loa_encrypted` entirely (to test `requireLoa`).
2512
+ *
2513
+ * Carries v2 by default, as the relay has since 24 Oct 2026: bound to
2514
+ * `partnerId` and to this envelope's digest, both signatures placeholders
2515
+ * unless `loaSigningKeyPem` is given. Pass
2516
+ * `{ oneaddress_signature_v2: undefined }` to send a v1-only LOA, the shape
2517
+ * of every dispatch before that date.
2170
2518
  */
2171
2519
  loa?: false | Partial<OneAddressD5LOA>;
2172
2520
  /**
@@ -2192,10 +2540,9 @@ interface SignedTestWebhookOptions {
2192
2540
  */
2193
2541
  userId?: string;
2194
2542
  /**
2195
- * `stripe_session_id`. Defaults to `null`, which is what the relay sends when
2196
- * no PaymentIntent backed the update — the KEY is present either way, and
2197
- * `'stripe_session_id' in body` is a different question from
2198
- * `body.stripe_session_id != null`.
2543
+ * @deprecated Ignored since 2.8.0. The relay no longer sends
2544
+ * `stripe_session_id` (it was the same PaymentIntent id at every recipient of
2545
+ * one update), so the builder does not either.
2199
2546
  */
2200
2547
  stripeSessionId?: string | null;
2201
2548
  /**
@@ -2276,4 +2623,4 @@ interface SignedTestWebhook {
2276
2623
  */
2277
2624
  declare function buildSignedTestWebhook(opts: SignedTestWebhookOptions): Promise<SignedTestWebhook>;
2278
2625
 
2279
- 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 PinnedRegistryRoot, type PrivateKeyOperations, type RegistryHeadCheckOptions, type RegistryHeadCheckResult, type RegistryHeadCheckVerdict, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type SignedTestWebhook, type SignedTestWebhookOptions, type VerifyResultCallbackParams, _resetOnceWarningsForTests, buildSignedTestWebhook, canonicalD5LoaForm, checkRegistryHead, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, parsePinnedRegistryRoots, readAddressParts, sendVerifyResult, signPullRequest, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
2626
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_IDEMPOTENCY_LEASE_SECS, DEFAULT_MAX_BODY_BYTES, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type HandlerConfirmOptions, type HandlerRequest, type HandlerResponse, type IdempotencyClaim, type IdempotencyDialect, type IdempotencyStore, LOA_MAX_TYPED_ALIASES, LOA_MIN_SHORT_FORM_LETTERS, LOA_PUBLIC_KEY_CACHE_MS, LOA_V2_REFUSALS, LoaPublicKeyUnavailableError, type LoaV2Context, type LoaV2Refusal, LoaV2RefusedError, MAX_ADDRESS_FIELD_CHARS, 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 PinnedRegistryRoot, type PrivateKeyOperations, type RegistryHeadCheckOptions, type RegistryHeadCheckResult, type RegistryHeadCheckVerdict, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type SignedTestWebhook, type SignedTestWebhookOptions, type VerifyResultCallbackParams, _resetLoaKeyCacheForTests, _resetOnceWarningsForTests, acceptTypedAliases, buildSignedTestWebhook, cachedLoaPublicKey, canonicalD5LoaForm, canonicalD5LoaFormV2, checkLoaV2, checkRegistryHead, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, hasLoaV2, isAcceptableAlias, isEmailLike, isFreshTimestamp, loaEnvelopeSha256, loaFirstName, loaNamesMatch, loaSurname, namePoolMatches, normaliseLoaName, normalizeForBlindIndex, parsePinnedRegistryRoots, readAddressParts, sendVerifyResult, signPullRequest, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, typedAliasesOf, validateAddress, verifySignature as verify, verifyD5LOA, verifyD5LOAv2, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };