@oneaddress/partner-sdk 1.6.3 → 1.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.ts 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
  /**
@@ -89,6 +156,142 @@ declare const CURRENT_VERSION: "2026.1";
89
156
  /** All protocol versions this build of the SDK recognises. */
90
157
  declare const SUPPORTED_VERSIONS: readonly ["2026.1"];
91
158
 
159
+ /**
160
+ * Draining the outbox.
161
+ *
162
+ * The receiver writes each delivered update into a table and stamps
163
+ * `written_at`. It never stamps `processed_at` — that column belongs to you,
164
+ * and the gap between the two is what makes the backlog metric mean anything.
165
+ * Until now the SDK gave you no help crossing that gap, so every integrator
166
+ * wrote their own polling loop and rediscovered the same three problems.
167
+ *
168
+ * ── WHY THIS IS NOT A `SELECT ... WHERE processed_at IS NULL` ────────────────
169
+ *
170
+ * That query is correct with exactly one consumer and quietly wrong with two.
171
+ * Both read the same rows, both apply the same address, and whichever finishes
172
+ * second overwrites the first. On a CRM that fires side effects on write — a
173
+ * confirmation email, an audit entry, a downstream sync — the duplicate is
174
+ * visible to the customer.
175
+ *
176
+ * So a claim has to be atomic against other consumers, which is dialect
177
+ * territory: `FOR UPDATE SKIP LOCKED` on postgres, `READPAST` on SQL Server,
178
+ * a lock-and-reread on MySQL (whose UPDATE cannot reference its own table in a
179
+ * subquery, and has no RETURNING). Getting that right is the work, and it is
180
+ * the part an integrator should not have to do twice.
181
+ *
182
+ * ── A CLAIM IS A LEASE, NOT A LOCK ──────────────────────────────────────────
183
+ *
184
+ * A consumer that dies mid-batch must not strand its rows forever. So a claim
185
+ * writes `oa_claimed_at` and expires: once `leaseSeconds` have passed the row
186
+ * is claimable again. That is why the handler must be idempotent — a lease that
187
+ * expires while the handler is still running means the row can be claimed
188
+ * twice, and no timeout is long enough to make that impossible.
189
+ *
190
+ * ── THE COLUMNS ARE OURS AND ARE PREFIXED ───────────────────────────────────
191
+ *
192
+ * `oa_claimed_at`, `oa_claim_token` and `oa_attempts` are added by
193
+ * {@link OutboxConsumer.ensureSchema}. They carry the `oa_` prefix because this
194
+ * consumer is also useful over a table you wrote yourself, where a bare
195
+ * `claimed_at` could already mean something.
196
+ */
197
+ /** The databases the receiver supports, and therefore the ones this drains. */
198
+ type OutboxDialect = 'postgres' | 'mysql' | 'sqlite' | 'mssql';
199
+ /** Run parameterised SQL and return the result rows. Your pool, your driver. */
200
+ type OutboxQueryFn = (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
201
+ interface OutboxRow {
202
+ dispatchId: string;
203
+ event: string;
204
+ /** Every column the row carries, as the driver returned it. */
205
+ fields: Record<string, unknown>;
206
+ /** How many times a handler has already failed on this row. */
207
+ attempts: number;
208
+ }
209
+ interface OutboxBacklog {
210
+ /** Written, not yet processed. The number to graph. */
211
+ pending: number;
212
+ /** Age of the oldest unprocessed row. The number to alert on. */
213
+ oldestPendingAgeSeconds: number | null;
214
+ /** Rows parked because they hit `maxAttempts`. Zero unless you set it. */
215
+ stuck: number;
216
+ }
217
+ /** The lease columns, in the order `ensureSchema` adds them. */
218
+ declare const OUTBOX_LEASE_COLUMNS: readonly ["oa_claimed_at", "oa_claim_token", "oa_attempts"];
219
+ /**
220
+ * Bind a timestamp in the form the column will accept.
221
+ *
222
+ * An ISO-8601 string is the obvious thing and it is wrong on MySQL: a
223
+ * `DATETIME` rejects `2026-08-01T19:13:40.590Z` outright in strict mode,
224
+ * because it wants `YYYY-MM-DD HH:MM:SS` with a space and no zone. Everything
225
+ * is normalised to UTC first — a zone-less column carries no offset, so the
226
+ * only way two processes agree on what a stored value means is to agree that
227
+ * it is always UTC.
228
+ *
229
+ * This is deliberately identical to the receiver's own `toDbTimestamp`, and a
230
+ * guard in this repo fails if the two ever disagree. They cannot be one module:
231
+ * the receiver is not published and this package is.
232
+ */
233
+ declare function toOutboxTimestamp(dialect: OutboxDialect, when: Date | number): string;
234
+ /**
235
+ * Read a timestamp back, and the reason this is not `Date.parse`.
236
+ *
237
+ * The binder above agrees that a zone-less column is always UTC. `Date.parse`
238
+ * does not hold up the other half of that agreement: ECMA-262 mandates that a
239
+ * date-time form with NO offset is read as LOCAL time. So a row stamped in UTC
240
+ * and read on a UTC+8 host comes back eight hours in the past, which skews the
241
+ * oldest-pending age by the deployment's whole offset — inflating it east of
242
+ * Greenwich (the alert screams and gets muted) and making it negative to the
243
+ * west (the alert can never fire, and a stuck outbox looks permanently
244
+ * healthy). CI never catches it, because CI runs UTC and the skew is exactly
245
+ * zero there.
246
+ */
247
+ declare function fromOutboxTimestamp(raw: unknown): number | null;
248
+ interface OutboxConsumerOptions {
249
+ query: OutboxQueryFn;
250
+ /** Defaults to `postgres`, matching the rest of this SDK. */
251
+ dialect?: OutboxDialect;
252
+ /** Defaults to `oneaddress_updates`, which is what the receiver writes. */
253
+ table?: string;
254
+ /** Rows per claim. Defaults to 50. */
255
+ batchSize?: number;
256
+ /**
257
+ * How long a claim is held before another consumer may take the row.
258
+ * Defaults to 300 (five minutes). Set it comfortably longer than your
259
+ * slowest handler: an expired lease means the row gets processed twice.
260
+ */
261
+ leaseSeconds?: number;
262
+ /**
263
+ * Stop claiming a row after this many failed handler runs. Defaults to `0`,
264
+ * meaning never stop, and that default is deliberate — giving up on a row is
265
+ * an address that never reaches your system, which is worse than a loop you
266
+ * can see. Set it only once you are alerting on `backlog().stuck`.
267
+ */
268
+ maxAttempts?: number;
269
+ /** Injectable clock, for tests. */
270
+ now?: () => number;
271
+ }
272
+ interface OutboxConsumer {
273
+ /** Add the lease columns if they are absent. Safe to call on every boot. */
274
+ ensureSchema(): Promise<{
275
+ added: string[];
276
+ }>;
277
+ /** Atomically take up to `batchSize` rows. Other consumers skip them. */
278
+ claimBatch(): Promise<OutboxRow[]>;
279
+ /** Done. Stamps `processed_at` and releases the claim. */
280
+ markProcessed(dispatchId: string): Promise<void>;
281
+ /** Failed. Records the reason, counts the attempt, releases for a retry. */
282
+ markFailed(dispatchId: string, error: unknown): Promise<void>;
283
+ /** Put a row back untouched — for a clean shutdown mid-batch. */
284
+ release(dispatchId: string): Promise<void>;
285
+ /** Claim a batch, run `handler` per row, and mark each one. */
286
+ process(handler: (row: OutboxRow) => Promise<void> | void): Promise<{
287
+ processed: number;
288
+ failed: number;
289
+ }>;
290
+ /** The numbers to graph and alert on. */
291
+ backlog(): Promise<OutboxBacklog>;
292
+ }
293
+ declare function createOutboxConsumer(opts: OutboxConsumerOptions): OutboxConsumer;
294
+
92
295
  /**
93
296
  * @oneaddress/partner-sdk
94
297
  *
@@ -444,11 +647,15 @@ interface OneAddressHandlerOptions {
444
647
  note?: string;
445
648
  }>;
446
649
  /**
447
- * Connection-verification test records (`address.test`).
650
+ * Connection-verification and stress-test records (`address.test` and
651
+ * `address.test-dispatch`).
448
652
  *
449
- * OneAddress sends five of these before a partner goes live: real signed,
450
- * ECDH-encrypted dispatches carrying fabricated TEST identities, which you
451
- * decrypt and relay back so both sides can confirm the pipe works end to end.
653
+ * OneAddress sends five `address.test` records before a partner goes live:
654
+ * real signed, ECDH-encrypted dispatches carrying fabricated TEST identities,
655
+ * which you decrypt and relay back so both sides can confirm the pipe works
656
+ * end to end. The admin stress test sends `address.test-dispatch`, which is
657
+ * the SAME shape (a fabricated, encrypted test record) — both arrive here, and
658
+ * `event` tells them apart if you want to count stress dispatches separately.
452
659
  *
453
660
  * ── WHY THIS IS A SEPARATE CALLBACK AND NOT `onUpdate` ─────────────────────
454
661
  *
@@ -459,11 +666,11 @@ interface OneAddressHandlerOptions {
459
666
  *
460
667
  * ── IF YOU DO NOT IMPLEMENT IT ─────────────────────────────────────────────
461
668
  *
462
- * `address.test` is acknowledged with 200 and skipped, and the SDK logs a
463
- * warning naming this option. That combination was the defect in
464
- * marlowe-reports#125: the skip was correct, the silence was not. Five test
465
- * records were skipped, the partner saw five clean 200s, and the only way it
466
- * surfaced was somebody decrypting the raw bodies by hand.
669
+ * `address.test` / `address.test-dispatch` are acknowledged with 200 and
670
+ * skipped, and the SDK logs a warning naming this option. That combination was
671
+ * the defect in marlowe-reports#125: the skip was correct, the silence was
672
+ * not. Five test records were skipped, the partner saw five clean 200s, and
673
+ * the only way it surfaced was somebody decrypting the raw bodies by hand.
467
674
  *
468
675
  * Implement it if you intend to complete connection verification through the
469
676
  * SDK rather than by hand.
@@ -545,6 +752,7 @@ interface IdempotencyStore {
545
752
  */
546
753
  complete?(dispatchId: string): Promise<void>;
547
754
  }
755
+
548
756
  /**
549
757
  * A SQL-backed {@link IdempotencyStore} with an atomic claim, over whatever
550
758
  * driver you already use.
@@ -807,7 +1015,7 @@ interface SessionData {
807
1015
  * );
808
1016
  * // data.new_address.street, data.account_number, etc.
809
1017
  */
810
- declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string, partnerId: string): Promise<SessionData>;
1018
+ declare function decryptSession(share: SessionKeyShare, envelopeB64: string, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<SessionData>;
811
1019
  /**
812
1020
  * Decrypt a OneAddress payload and immediately re-encrypt it to a different
813
1021
  * ECDH P-256 public key — for example, your internal KMS or HSM public key.
@@ -1075,7 +1283,7 @@ declare function verifyD5LOA(loa: OneAddressD5LOA, publicKeyPem: string): Promis
1075
1283
  declare function decryptLoaEncrypted(loaEncrypted: {
1076
1284
  session_envelope: string;
1077
1285
  session_key_share: SessionKeyShare;
1078
- }, privateKeyPem: string, partnerId: string): Promise<OneAddressD5LOA>;
1286
+ }, privateKeyPem: string | PrivateKeyOperations, partnerId: string): Promise<OneAddressD5LOA>;
1079
1287
  /**
1080
1288
  * Validate and narrow the decrypted address payload to `OneAddressAddress`.
1081
1289
  *
@@ -1220,7 +1428,14 @@ type HandlerResponse = Response;
1220
1428
  * of these, and the compiler is a better guard against that than a comment.
1221
1429
  */
1222
1430
  interface OneAddressTestEvent {
1223
- event: 'address.test';
1431
+ /**
1432
+ * `address.test` is a single-partner connection-verification ping;
1433
+ * `address.test-dispatch` is the same fabricated, encrypted test record sent
1434
+ * by the admin stress test. Both route here — NEVER to `onUpdate` — because
1435
+ * the identity and address inside are fabricated. The field tells them apart
1436
+ * for a handler that wants to (e.g. count stress dispatches separately).
1437
+ */
1438
+ event: 'address.test' | 'address.test-dispatch';
1224
1439
  /** 1-based position within this verification run. */
1225
1440
  index?: number;
1226
1441
  /** How many records this run sends in total. */
@@ -1308,4 +1523,4 @@ interface ExpressLikeResponse {
1308
1523
  */
1309
1524
  declare function toExpressHandler(handler: (req: HandlerRequest) => Promise<HandlerResponse>): (req: ExpressLikeRequest, res: ExpressLikeResponse) => Promise<void>;
1310
1525
 
1311
- export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };
1526
+ export { type AddressParts, type BlindIndexField, CURRENT_VERSION, type ComparableAddress, type ConfirmUpdateOptions, type ConfirmUpdateResult, DEFAULT_REPLAY_WINDOW_SECS, type EncryptedPayload, type ExpressLikeRequest, type ExpressLikeResponse, type IdempotencyClaim, type IdempotencyStore, OUTBOX_LEASE_COLUMNS, type OneAddressAccountVerifyEvent, type OneAddressAddress, type OneAddressConfirmStatus, type OneAddressCustomer, type OneAddressCustomerMatch, type OneAddressD5LOA, type OneAddressHandlerOptions, type OneAddressIdVerification, type OneAddressLOA, type OneAddressTestEvent, type OneAddressUpdateEvent, type OneAddressVerifyEvent, type OutboxBacklog, type OutboxConsumer, type OutboxConsumerOptions, type OutboxDialect, type OutboxQueryFn, type OutboxRow, type PrivateKeyOperations, SUPPORTED_VERSIONS, type SessionData, type SessionKeyShare, type SessionUpdateType, type VerifyResultCallbackParams, canonicalD5LoaForm, compareAddresses, computeBlindIndex, confirmUpdate, createOneAddressHandler, createOutboxConsumer, createSqlIdempotencyStore, d5LoaRef, decryptAddress as decrypt, decryptAddress, decryptLoaEncrypted, decryptSession, fetchLoaPublicKey, findMatchingStoredName, formatAddressParts, fromOutboxTimestamp, isEmailLike, isFreshTimestamp, namePoolMatches, normalizeForBlindIndex, readAddressParts, sendVerifyResult, toExpressHandler, toOutboxTimestamp, transformAddress as transform, transformAddress, transformSession, validateAddress, verifySignature as verify, verifyD5LOA, verifyWithGrace as verifyGrace, verifyLOA, verifySignature, verifyWithGrace };