@facto-to/card 0.0.0-stage → 0.0.1-beta.2

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +63 -2
  5. package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
  6. package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
  7. package/dist/chunk-KBS2PWM4.js +2 -0
  8. package/dist/cli/index.js +6 -0
  9. package/dist/docs/README.md +9 -0
  10. package/dist/docs/authentication.md +96 -0
  11. package/dist/docs/authorization-binding.md +182 -0
  12. package/dist/docs/authorizations.md +182 -0
  13. package/dist/docs/concepts.md +36 -0
  14. package/dist/docs/deliveries.md +170 -0
  15. package/dist/docs/errors.md +100 -0
  16. package/dist/docs/getting-access.md +56 -0
  17. package/dist/docs/idempotency.md +78 -0
  18. package/dist/docs/integration-checklist.md +15 -0
  19. package/dist/docs/integration.zh.md +59 -0
  20. package/dist/docs/interlace-adapter-v1.md +87 -0
  21. package/dist/docs/interlace-adapter-v1.zh.md +87 -0
  22. package/dist/docs/not-yet-available.md +13 -0
  23. package/dist/docs/quickstart.md +126 -0
  24. package/dist/docs/reconciliation.md +86 -0
  25. package/dist/docs/reference/api.md +2541 -0
  26. package/dist/docs/reference/events.md +639 -0
  27. package/dist/docs/reference/schemas.json +6603 -0
  28. package/dist/docs/reference/schemas.md +1001 -0
  29. package/dist/docs/simulator.md +235 -0
  30. package/dist/docs/versioning.md +9 -0
  31. package/dist/index.cjs +3 -0
  32. package/dist/index.d.cts +987 -0
  33. package/dist/index.d.ts +987 -0
  34. package/dist/index.js +2 -0
  35. package/dist/source/build.mjs +5 -0
  36. package/dist/source/package.json +16 -0
  37. package/dist/source/src/connect/cli/deliveries.ts +48 -0
  38. package/dist/source/src/connect/cli/index.ts +57 -0
  39. package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
  40. package/dist/source/src/connect/server/card-client.ts +1018 -0
  41. package/dist/source/src/connect/server/card-delivery.ts +301 -0
  42. package/dist/source/src/connect/server/card-events.ts +473 -0
  43. package/dist/source/src/connect/server/card-idempotency.ts +27 -0
  44. package/dist/source/src/connect/server/card-inbox.ts +82 -0
  45. package/dist/source/src/connect/server/card-intent-token.ts +588 -0
  46. package/dist/source/src/connect/server/card-polling.ts +69 -0
  47. package/dist/source/src/connect/server/card-signing.ts +115 -0
  48. package/dist/source/src/connect/server/card-transport.ts +282 -0
  49. package/dist/source/src/connect/server/errors.ts +280 -0
  50. package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
  51. package/dist/source/src/connect/server/retry-after.ts +12 -0
  52. package/dist/source/src/connect/testing/card-inbox.ts +124 -0
  53. package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
  54. package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
  55. package/dist/source/src/connect/testing/card-simulator.ts +531 -0
  56. package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
  57. package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
  58. package/dist/source/src/connect/wire.d.ts +544 -0
  59. package/dist/source/src/index.ts +163 -0
  60. package/dist/source/src/testing-browser.ts +24 -0
  61. package/dist/source/src/testing.ts +26 -0
  62. package/dist/source/tsconfig.json +20 -0
  63. package/dist/testing-browser.d.ts +220 -0
  64. package/dist/testing-browser.js +5 -0
  65. package/dist/testing.cjs +6 -0
  66. package/dist/testing.d.cts +199 -0
  67. package/dist/testing.d.ts +199 -0
  68. package/dist/testing.js +5 -0
  69. package/package.json +60 -4
@@ -0,0 +1,1018 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type {
3
+ BindingProofChallenge,
4
+ BindingSessionCreate,
5
+ BindingSessionCreated,
6
+ BindingSessionStatus,
7
+ ProviderProofAccepted,
8
+ ProviderProofSubmitPayload,
9
+ CardDisplayFacts,
10
+ IntentCardItem as WireIntentCardItem,
11
+ IntentCardList as WireIntentCardList,
12
+ IntentCardsReplaceInput,
13
+ IntentCardsReplaced,
14
+ IntentCancelInput,
15
+ IntentCancelled,
16
+ BindingLookupInput,
17
+ BindingSummary as WireBindingSummary,
18
+ BindingLookupResult as WireBindingLookupResult,
19
+ AuthorizationOperationType,
20
+ AuthorizationCreateInput as AuthorizationSubmitInput,
21
+ AuthorizationAccepted,
22
+ SynchronousAuthorizationApproved,
23
+ SynchronousAuthorizationDeclined,
24
+ AuthorizationDeadlineExceeded,
25
+ AuthorizationFactInput as AuthorizationFactRecordInput,
26
+ AuthorizationFactReceipt,
27
+ AuthorizationProjection as WireAuthorizationProjection,
28
+ AuthorizationLookupResult as WireAuthorizationLookupResult,
29
+ ChargeFinalReceipt as CardFinalReceipt,
30
+ AuthorizationLifecycle as CardAuthorizationLifecycle,
31
+ AuthorizationFacts,
32
+ CardInboundEventInput,
33
+ CardInboundEventReceipt,
34
+ DeliveryReconciliationListInput,
35
+ DeliveryItem as WireDeliveryItem,
36
+ DeliveryPage as WireDeliveryPage,
37
+ DeliveryReplayCreateInput,
38
+ DeliveryReplayAccepted,
39
+ DeadLetterPage,
40
+ DeadLetterReplayAccepted,
41
+ } from '../wire'
42
+ import { signBindingAssertion, type SignBindingAssertionInput } from './card-binding-assertion'
43
+ import { resolveCardApiKeySecret, signCardRequest, type CardApiKeySecret } from './card-signing'
44
+ import {
45
+ closed, config, digestPattern, header, invalidResponse, object, pconnPattern, responseFields, revision,
46
+ sha256HexPattern, text, time, transport, transportKeys, uuid, uuidPattern,
47
+ type CardEnvironment, type CardRequestOptions, type OpenVocabulary, type TransportOptions,
48
+ } from './card-transport'
49
+
50
+ export {
51
+ isCardErrorEnvelope,
52
+ isCardNestedErrorEnvelope,
53
+ type CardAuthorizationErrorCode,
54
+ type CardEnvironment,
55
+ type CardErrorEnvelope,
56
+ type CardNestedErrorEnvelope,
57
+ type CardRequestOptions,
58
+ } from './card-transport'
59
+
60
+ export type { CardApiKeySecret } from './card-signing'
61
+
62
+ export type {
63
+ BindingProofChallenge,
64
+ BindingProofPolicy,
65
+ BindingSessionCreate,
66
+ BindingSessionCreated,
67
+ BindingSessionStatus,
68
+ ProviderProofAccepted,
69
+ ProviderProofSubmitPayload,
70
+ CardDisplayFacts,
71
+ TargetCardInput,
72
+ IntentCardsReplaceInput,
73
+ IntentCardsReplaced,
74
+ IntentCancelInput,
75
+ IntentCancelled,
76
+ BindingLookupInput,
77
+ BindingFundingProjection as BindingFundingSummary,
78
+ CardholderVerification,
79
+ AuthorizationCreateInput as AuthorizationSubmitInput,
80
+ AuthorizationAccepted,
81
+ SynchronousAuthorizationApproved,
82
+ SynchronousAuthorizationDeclined,
83
+ AuthorizationDeadlineExceeded,
84
+ AuthorizationFactInput as AuthorizationFactRecordInput,
85
+ AuthorizationFactReceipt,
86
+ ChargeFinalReceipt as CardFinalReceipt,
87
+ AuthorizationLifecycle as CardAuthorizationLifecycle,
88
+ AuthorizationPaymentDetails as CardPaymentDetails,
89
+ AuthorizationFacts,
90
+ CardInboundEventInput,
91
+ CardInboundEventReceipt,
92
+ DeliveryReconciliationListInput,
93
+ DeliveryReplayCreateInput,
94
+ DeliveryReplayAccepted,
95
+ DeadLetterItem,
96
+ DeadLetterPage,
97
+ DeadLetterReplayAccepted,
98
+ } from '../wire'
99
+
100
+ export type AuthorizationLookupCriteria =
101
+ | {
102
+ readonly by: 'external_authorization_id'
103
+ readonly external_authorization_id: string
104
+ readonly fact_type?: AuthorizationOperationType
105
+ readonly mapping_revision: string
106
+ readonly resource_version: string
107
+ }
108
+ | {
109
+ readonly by: 'supplier_transaction_id'
110
+ readonly supplier_transaction_id: string
111
+ readonly fact_type?: AuthorizationOperationType
112
+ readonly mapping_revision: string
113
+ readonly resource_version: string
114
+ }
115
+ | {
116
+ readonly by: 'idempotency_key'
117
+ readonly idempotency_key: string
118
+ readonly original_credential_key_id: string
119
+ readonly operation?: 'create_authorization'
120
+ }
121
+ | {
122
+ readonly by: 'charge_id'
123
+ readonly charge_id: string
124
+ }
125
+
126
+ export interface AuthorizationLookupInput {
127
+ readonly program_id: string
128
+ readonly criteria: AuthorizationLookupCriteria
129
+ }
130
+
131
+ type OpenLifecycle = Omit<CardAuthorizationLifecycle, 'issuer' | 'refund_cases'> & {
132
+ issuer: Omit<CardAuthorizationLifecycle['issuer'], 'entries'> & {
133
+ entries: Array<Omit<CardAuthorizationLifecycle['issuer']['entries'][number], 'operation_type' | 'link_status'> & { operation_type: OpenVocabulary<AuthorizationOperationType>; link_status: OpenVocabulary<'linked' | 'unlinked'> }>
134
+ }
135
+ refund_cases: Array<Omit<CardAuthorizationLifecycle['refund_cases'][number], 'source_operation_type'> & { source_operation_type: OpenVocabulary<AuthorizationOperationType> }>
136
+ }
137
+
138
+ type AuthorizationProjectionBase = Omit<
139
+ WireAuthorizationProjection,
140
+ 'processing_status' | 'charge_id' | 'final_receipt' | 'decline_reason_code' | 'lifecycle' | 'facts' | 'operation_type' | 'revision'
141
+ > & {
142
+ facts?: AuthorizationFacts
143
+ operation_type?: OpenVocabulary<AuthorizationOperationType>
144
+ revision?: number
145
+ lifecycle?: OpenLifecycle
146
+ }
147
+
148
+ export type AuthorizationProjection = AuthorizationProjectionBase & (
149
+ | { processing_status: 'succeeded'; charge_id?: string | null; final_receipt?: CardFinalReceipt & { execution_outcome: 'succeeded' }; decline_reason_code?: never }
150
+ | { processing_status: 'failed'; charge_id: string; final_receipt: CardFinalReceipt & { execution_outcome: 'failed' }; decline_reason_code?: never }
151
+ | ({ processing_status: 'failed'; final_receipt?: never; decline_reason_code?: string } & (
152
+ | { charge_id: string }
153
+ | { charge_id?: null; decision?: 'declined' | 'self_reversed_timeout' }
154
+ ))
155
+ | { processing_status: 'processing'; charge_id?: string | null; final_receipt?: never; decline_reason_code?: never }
156
+ | { processing_status: 'indeterminate'; charge_id?: null; final_receipt?: never; decline_reason_code?: never }
157
+ )
158
+
159
+ export type AuthorizationLookupResult = Omit<WireAuthorizationLookupResult, 'resolution' | 'authorization'> & (
160
+ | { resolution: 'not_observed'; authorization?: never }
161
+ | { resolution: 'unknown'; authorization: Extract<AuthorizationProjection, { processing_status: 'indeterminate' }> }
162
+ | { resolution: 'pending'; authorization: Extract<AuthorizationProjection, { processing_status: 'processing' }> }
163
+ | { resolution: 'resolved'; authorization: Extract<AuthorizationProjection, { processing_status: 'succeeded' | 'failed' }> }
164
+ )
165
+
166
+ export type IntentCardItem = Omit<WireIntentCardItem, 'status'> & {
167
+ status: OpenVocabulary<WireIntentCardItem['status']>
168
+ }
169
+ export type IntentCardList = Omit<WireIntentCardList, 'cards'> & { cards: IntentCardItem[] }
170
+
171
+ export type BindingSummary = Omit<WireBindingSummary, 'status'> & {
172
+ status: OpenVocabulary<WireBindingSummary['status']>
173
+ }
174
+ export type BindingLookupResult = Omit<WireBindingLookupResult, 'binding'> & { binding: BindingSummary | null }
175
+
176
+ export type DeliveryItem = Omit<WireDeliveryItem, 'delivery_state'> & {
177
+ delivery_state: OpenVocabulary<WireDeliveryItem['delivery_state']>
178
+ }
179
+ export type DeliveryPage = Omit<WireDeliveryPage, 'items'> & { items: DeliveryItem[] }
180
+
181
+ export interface CardClientOptions extends TransportOptions {
182
+ readonly connectionId: string
183
+ readonly programId: string
184
+ readonly apiKeyId: string
185
+ readonly apiKeySecret: CardApiKeySecret
186
+ readonly nowSeconds?: () => number
187
+ readonly createNonce?: () => string
188
+ }
189
+
190
+ export interface CardIdempotentRequestOptions extends CardRequestOptions {
191
+ readonly idempotencyKey: string
192
+ }
193
+
194
+ /** Preserve authenticated bytes for routes whose handler does not decode a JSON body. */
195
+ export interface CardOpaqueRequestOptions extends CardRequestOptions {
196
+ readonly rawBody?: string
197
+ }
198
+
199
+ export interface IntentCardsListOptions extends CardRequestOptions {
200
+ readonly intentToken: string
201
+ }
202
+
203
+ /** A scoped view of the generated request, preserving its exclusive selection modes. */
204
+ export type DeliveryReconciliationInput = Omit<
205
+ DeliveryReconciliationListInput,
206
+ 'program_id' | 'selection_id' | 'from_at' | 'to_at'
207
+ > & (
208
+ | { readonly selection_id: string; readonly from_at?: never; readonly to_at?: never }
209
+ | { readonly selection_id?: never; readonly from_at: string; readonly to_at: string }
210
+ )
211
+
212
+ export type DeliveryReplayInput = Omit<DeliveryReplayCreateInput, 'program_id'>
213
+
214
+ export interface DeadLetterListParams {
215
+ readonly limit?: number | null
216
+ }
217
+
218
+ export type AuthorizationLookupClientInput =
219
+ | Omit<AuthorizationLookupInput, 'program_id'>
220
+ | AuthorizationLookupCriteria
221
+
222
+ export type AuthorizationCreateInput = Omit<
223
+ AuthorizationSubmitInput,
224
+ 'program_id' | 'decision_mode' | 'decision_timeout_ms' | 'deadline_at'
225
+ > & {
226
+ readonly decision_mode?: 'asynchronous'
227
+ }
228
+
229
+ export type SynchronousAuthorizationCreateInput = Omit<AuthorizationCreateInput, 'decision_mode'> & {
230
+ readonly decision_mode: 'synchronous'
231
+ readonly decision_timeout_ms?: number
232
+ readonly deadline_at?: string
233
+ }
234
+
235
+ export type SynchronousAuthorizationResult =
236
+ | SynchronousAuthorizationApproved
237
+ | SynchronousAuthorizationDeclined
238
+ | AuthorizationDeadlineExceeded
239
+
240
+ export type AuthorizationFactInput = Omit<AuthorizationFactRecordInput, 'program_id'>
241
+
242
+ export type BindingSessionCreateInput = Omit<BindingSessionCreate, 'program_ref'>
243
+
244
+ export interface BindingSessionCreateOptions extends CardIdempotentRequestOptions {
245
+ /** Opt in to the candidate-selection decision branch by sending `x-facto-card-selection: 1`. */
246
+ readonly cardSelection?: boolean
247
+ }
248
+
249
+ export type SessionProofAssertionInput = Omit<
250
+ SignBindingAssertionInput,
251
+ 'environment' | 'programId' | 'bindingSessionId'
252
+ >
253
+
254
+ export type BindingProofSubmitInput = ProviderProofSubmitPayload | SessionProofAssertionInput
255
+
256
+ export type BindingSessionCancelOptions = CardIdempotentRequestOptions & CardOpaqueRequestOptions
257
+
258
+ export interface CardSessionsApi {
259
+ /** Create a partner-initiated hosted binding session for the scoped program and return its one-time binding URL and proof policy. */
260
+ create(input: BindingSessionCreateInput, options: BindingSessionCreateOptions): Promise<BindingSessionCreated>
261
+ /** Read the current state-safe projection of a hosted binding session. */
262
+ get(id: string, options?: CardRequestOptions): Promise<BindingSessionStatus>
263
+ /** Submit a challenge-bound compact-JWS provider proof, either pre-signed or signed in-SDK from asserted cards. */
264
+ submitProof(id: string, input: BindingProofSubmitInput, options: CardIdempotentRequestOptions): Promise<ProviderProofAccepted>
265
+ /** Read the active proof challenge of a proof_pending hosted binding session for a provider_backend connection. */
266
+ getProofChallenge(id: string, options?: CardRequestOptions): Promise<BindingProofChallenge>
267
+ /** Cancel a nonterminal hosted binding session as the partner; already-terminal sessions return unchanged. */
268
+ cancel(id: string, options: BindingSessionCancelOptions): Promise<BindingSessionStatus>
269
+ }
270
+
271
+ export interface CardIntentsApi {
272
+ /** List currently bound cards and the optimistic concurrency revision for an active connect intent. */
273
+ listCards(id: string, options: IntentCardsListOptions): Promise<IntentCardList>
274
+ /** Atomically replace the cardholder-approved target card set for an active connect intent. */
275
+ replaceCards(id: string, input: IntentCardsReplaceInput, options: CardIdempotentRequestOptions): Promise<IntentCardsReplaced>
276
+ /** Cancel an active connect intent when the cardholder aborts selection. */
277
+ cancel(id: string, input: IntentCancelInput, options?: CardRequestOptions): Promise<IntentCancelled>
278
+ }
279
+
280
+ export interface CardBindingsApi {
281
+ /** Look up the current Facto card binding projection by opaque external_card_id. */
282
+ lookup(input: BindingLookupInput, options?: CardRequestOptions): Promise<BindingLookupResult>
283
+ }
284
+
285
+ export interface CardAuthorizationsApi {
286
+ /** Submit an initial card swipe authorization for synchronous admission and settlement execution. */
287
+ create(
288
+ input: SynchronousAuthorizationCreateInput,
289
+ options: CardIdempotentRequestOptions,
290
+ ): Promise<SynchronousAuthorizationResult>
291
+ /** Submit an initial card swipe authorization for asynchronous admission and settlement execution. */
292
+ create(
293
+ input: AuthorizationCreateInput,
294
+ options: CardIdempotentRequestOptions,
295
+ ): Promise<AuthorizationAccepted>
296
+ create(
297
+ input: AuthorizationCreateInput | SynchronousAuthorizationCreateInput,
298
+ options: CardIdempotentRequestOptions,
299
+ ): Promise<AuthorizationAccepted | SynchronousAuthorizationResult>
300
+ /** Record a subsequent clearing, reversal, refund, chargeback, or settlement lifecycle fact. */
301
+ recordFact(
302
+ externalId: string,
303
+ input: AuthorizationFactInput,
304
+ options: CardIdempotentRequestOptions,
305
+ ): Promise<AuthorizationFactReceipt>
306
+ /** Read the current authorization projection without resubmitting or deriving new authority. */
307
+ lookup(
308
+ input: AuthorizationLookupClientInput,
309
+ options?: CardRequestOptions,
310
+ ): Promise<AuthorizationLookupResult>
311
+ }
312
+
313
+ export interface CardEventsApi {
314
+ /** Record a signed inbound card lifecycle or account release event. */
315
+ record(input: CardInboundEventInput, options?: CardRequestOptions): Promise<CardInboundEventReceipt>
316
+ }
317
+
318
+ export interface CardDeliveriesApi {
319
+ /** List paginated webhook delivery reconciliation items within a bounded snapshot. */
320
+ list(input: DeliveryReconciliationInput, options?: CardRequestOptions): Promise<DeliveryPage>
321
+ }
322
+
323
+ export interface CardDeliveryReplaysApi {
324
+ /** Create an asynchronous replay job for an approved historical event selection. */
325
+ create(input: DeliveryReplayInput, options: CardIdempotentRequestOptions): Promise<DeliveryReplayAccepted>
326
+ }
327
+
328
+ export interface CardDeadLettersApi {
329
+ /** List webhook delivery dead-letter records for the authenticated connection. */
330
+ list(params?: DeadLetterListParams, options?: CardRequestOptions): Promise<DeadLetterPage>
331
+ /** Accept a single dead-lettered webhook delivery for asynchronous redelivery. */
332
+ replay(id: string, options?: CardOpaqueRequestOptions): Promise<DeadLetterReplayAccepted>
333
+ }
334
+
335
+ export interface CardClient {
336
+ readonly scope: Readonly<{
337
+ connectionId: string
338
+ environment: CardEnvironment
339
+ programId: string
340
+ }>
341
+ readonly sessions: CardSessionsApi
342
+ readonly intents: CardIntentsApi
343
+ readonly bindings: CardBindingsApi
344
+ readonly authorizations: CardAuthorizationsApi
345
+ readonly events: CardEventsApi
346
+ readonly deliveries: CardDeliveriesApi
347
+ readonly deliveryReplays: CardDeliveryReplaysApi
348
+ readonly deadLetters: CardDeadLettersApi
349
+ }
350
+
351
+ const sessionPattern = /^cbs_[A-Za-z0-9_-]{16,}$/
352
+ const intentPattern = /^cint_[A-Za-z0-9_-]{16,}$/
353
+ const bindingPattern = /^cb_[A-Za-z0-9_-]{16,}$/
354
+ const intentDigestPattern = /^sha256:[a-fA-F0-9]{64}$/
355
+ const factTypes = ['authorization_updated', 'clearing', 'reversal', 'refund', 'chargeback', 'settlement']
356
+ const allFactTypes = ['authorization_requested', ...factTypes]
357
+ const factKinds = ['facto_admission', 'durable_commit', 'provider_authorization', 'chain_finality', 'provider_settlement']
358
+ const lifecycleStates = ['active', 'frozen', 'closed', 'replaced']
359
+ const declineReasonCodePattern = /^[A-Za-z0-9_.:-]{1,64}$/
360
+ const decimalAmountPattern = /^[0-9]+\.[0-9]{2,6}$/
361
+ const signedDecimalAmountPattern = /^-?[0-9]+\.[0-9]{2,6}$/
362
+
363
+ function matches(value: unknown, pattern: RegExp): value is string {
364
+ return typeof value === 'string' && pattern.test(value)
365
+ }
366
+
367
+ function nullableString(value: unknown): boolean {
368
+ return value === null || typeof value === 'string'
369
+ }
370
+
371
+ function int32(value: unknown, min = -2147483648): boolean {
372
+ return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= 2147483647
373
+ }
374
+
375
+ function safeExternalCardId(value: unknown, max = 128): value is string {
376
+ return text(value, 1, max) && !/[0-9]{13}/.test(value)
377
+ }
378
+
379
+ function optionalValue(value: unknown, predicate: (value: unknown) => boolean): boolean {
380
+ return value === undefined || value === null || predicate(value)
381
+ }
382
+
383
+ function bindingIds(value: unknown): boolean {
384
+ return Array.isArray(value) && value.every((id) => matches(id, bindingPattern))
385
+ }
386
+
387
+ function cardDisplayFacts(value: unknown): value is CardDisplayFacts {
388
+ return responseFields(value, ['network', 'type', 'last4'])
389
+ && nullableString(value.network)
390
+ && (value.type === null || ['virtual', 'physical', 'unknown'].includes(String(value.type)))
391
+ && (value.last4 === null || (typeof value.last4 === 'string' && /^[0-9]{4}$/.test(value.last4)))
392
+ }
393
+
394
+ function chargeId(value: unknown): value is string {
395
+ // The public bytes32 encoding has a zero high half; never accept a storage UUID.
396
+ return typeof value === 'string' && /^0x0{32}[0-9a-fA-F]{32}$/.test(value)
397
+ }
398
+
399
+ function declineReasonCode(value: unknown): value is string {
400
+ return typeof value === 'string' && declineReasonCodePattern.test(value)
401
+ }
402
+
403
+ function deliveryPage(value: unknown): value is DeliveryPage {
404
+ if (!responseFields(value, ['snapshot_token', 'snapshot_at', 'to_at', 'items', 'next_cursor', 'complete'])
405
+ || !text(value.snapshot_token, 16, 4096) || !time(value.snapshot_at) || !time(value.to_at)
406
+ || typeof value.complete !== 'boolean' || (value.next_cursor !== null && !text(value.next_cursor, 1, 4096))
407
+ || (value.complete && value.next_cursor !== null) || !Array.isArray(value.items) || value.items.length > 100) return false
408
+ return value.items.every((item) => responseFields(item, ['event_id', 'origin_connection_id', 'connection_sequence', 'event_sha256', 'target_revision', 'delivery_state'], ['accepted_at'])
409
+ && uuid(item.event_id) && typeof item.origin_connection_id === 'string' && pconnPattern.test(item.origin_connection_id)
410
+ && (item.connection_sequence === null || (typeof item.connection_sequence === 'number' && Number.isSafeInteger(item.connection_sequence) && item.connection_sequence >= 1))
411
+ && typeof item.event_sha256 === 'string' && sha256HexPattern.test(item.event_sha256) && uuid(item.target_revision)
412
+ && typeof item.delivery_state === 'string'
413
+ && (item.accepted_at === undefined || time(item.accepted_at)))
414
+ }
415
+
416
+ function deliveryReplayAccepted(value: unknown): value is DeliveryReplayAccepted {
417
+ return responseFields(value, ['replay_id', 'selection_id', 'target_revision', 'status'])
418
+ && uuid(value.replay_id) && uuid(value.selection_id) && uuid(value.target_revision) && value.status === 'accepted'
419
+ }
420
+
421
+ function validateReconciliation(input: unknown): asserts input is DeliveryReconciliationInput {
422
+ config(closed(input, ['target_revision', 'page_size'], ['selection_id', 'from_at', 'to_at', 'snapshot_token', 'cursor']), 'Reconciliation requires only the generated query fields')
423
+ config(uuid(input.target_revision) && typeof input.page_size === 'number' && Number.isInteger(input.page_size) && input.page_size >= 1 && input.page_size <= 100, 'Reconciliation target_revision and page_size are invalid')
424
+ config((uuid(input.selection_id) && !Object.hasOwn(input, 'from_at') && !Object.hasOwn(input, 'to_at'))
425
+ || (!Object.hasOwn(input, 'selection_id') && time(input.from_at) && time(input.to_at) && Date.parse(input.from_at) <= Date.parse(input.to_at)), 'Select exactly one fixed selection or explicit time window')
426
+ config((input.snapshot_token === undefined || text(input.snapshot_token, 16, 4096))
427
+ && (input.cursor === undefined || (text(input.cursor, 16, 4096) && text(input.snapshot_token, 16, 4096))), 'A cursor requires its original snapshot token')
428
+ }
429
+
430
+ function normalizeLookupCriteria(input: unknown): AuthorizationLookupCriteria {
431
+ config(object(input), 'Authorization lookup requires criteria')
432
+ const candidate = Object.hasOwn(input, 'criteria')
433
+ ? (config(closed(input, ['criteria']) && object(input.criteria), 'Authorization lookup wrapper requires only criteria'), input.criteria)
434
+ : input
435
+ config(object(candidate), 'Authorization lookup requires criteria')
436
+ const valid = candidate.by === 'external_authorization_id'
437
+ ? closed(candidate, ['by', 'external_authorization_id', 'resource_version', 'mapping_revision'], ['fact_type'])
438
+ && text(candidate.external_authorization_id, 1, 256)
439
+ && text(candidate.resource_version, 1, 255) && text(candidate.mapping_revision, 1, 255)
440
+ && (candidate.fact_type === undefined || allFactTypes.includes(String(candidate.fact_type)))
441
+ : candidate.by === 'supplier_transaction_id'
442
+ ? closed(candidate, ['by', 'supplier_transaction_id', 'resource_version', 'mapping_revision'], ['fact_type'])
443
+ && typeof candidate.supplier_transaction_id === 'string' && text(candidate.supplier_transaction_id.trim(), 1, 256)
444
+ && text(candidate.resource_version, 1, 255) && text(candidate.mapping_revision, 1, 255)
445
+ && (candidate.fact_type === undefined || allFactTypes.includes(String(candidate.fact_type)))
446
+ : candidate.by === 'idempotency_key'
447
+ ? closed(candidate, ['by', 'idempotency_key', 'original_credential_key_id'], ['operation'])
448
+ && text(candidate.idempotency_key, 16, 255)
449
+ && text(candidate.original_credential_key_id, 1, 255)
450
+ && (candidate.operation === undefined || candidate.operation === 'create_authorization')
451
+ : candidate.by === 'charge_id' && closed(candidate, ['by', 'charge_id']) && chargeId(candidate.charge_id)
452
+ config(valid, 'Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id')
453
+ return candidate as unknown as AuthorizationLookupCriteria
454
+ }
455
+
456
+ function validateAuthorizationCreate(input: unknown): asserts input is AuthorizationCreateInput | SynchronousAuthorizationCreateInput {
457
+ const required = ['external_card_id', 'external_authorization_id', 'amount', 'currency', 'resource_version', 'mapping_revision', 'cardholder_verification']
458
+ const optional = ['supplier_transaction_id', 'client_transaction_id', 'merchant_name', 'merchant_mcc', 'merchant_country', 'occurred_at', 'decision_mode', 'decision_timeout_ms', 'deadline_at']
459
+ config(closed(input, required, optional), 'Authorization create requires the complete generated request')
460
+ const cvm = input.cardholder_verification
461
+ config(safeExternalCardId(input.external_card_id, 512) && text(input.external_authorization_id, 1, 256)
462
+ && matches(input.amount, decimalAmountPattern)
463
+ && (input.currency === 'USD' || input.currency === 'USDC')
464
+ && text(input.resource_version, 1, 255) && text(input.mapping_revision, 1, 255)
465
+ && (input.merchant_name === undefined || text(input.merchant_name, 0, 256))
466
+ && (input.merchant_mcc === undefined || matches(input.merchant_mcc, /^[0-9]{4}$/))
467
+ && (input.merchant_country === undefined || text(input.merchant_country, 2, 3))
468
+ && (input.occurred_at === undefined || time(input.occurred_at))
469
+ && [input.supplier_transaction_id, input.client_transaction_id].every((value) => value === undefined || (typeof value === 'string' && text(value.trim(), 1, 256)))
470
+ && (input.decision_mode === undefined || input.decision_mode === 'asynchronous' || input.decision_mode === 'synchronous')
471
+ && (input.decision_timeout_ms === undefined || (input.decision_mode === 'synchronous' && typeof input.decision_timeout_ms === 'number' && Number.isInteger(input.decision_timeout_ms) && input.decision_timeout_ms >= 50 && input.decision_timeout_ms <= 5000))
472
+ && (input.deadline_at === undefined || (input.decision_mode === 'synchronous' && time(input.deadline_at)))
473
+ && closed(cvm, ['method', 'verified_at', 'evidence_id'])
474
+ && ['pin', 'biometric', 'cdcvm', 'signature', 'no_cvm', 'provider_attested'].includes(String(cvm.method))
475
+ && time(cvm.verified_at) && text(cvm.evidence_id, 1, 256), 'Authorization fields, currency, mapping/version, or cardholder verification is invalid')
476
+ }
477
+
478
+ function validateAuthorizationFact(externalId: unknown, input: unknown): asserts input is AuthorizationFactInput {
479
+ config(text(externalId, 1, 255) && externalId !== '.' && externalId !== '..' && !externalId.includes('/'), 'externalId must be a valid external authorization identifier')
480
+ const required = ['fact_type', 'amount', 'currency', 'resource_version', 'predecessor_version', 'mapping_revision', 'recorded_at']
481
+ const optional = ['supplier_transaction_id', 'parent_supplier_transaction_id', 'client_transaction_id', 'merchant_name', 'merchant_mcc', 'merchant_country']
482
+ config(closed(input, required, optional), 'Authorization fact requires the complete generated request')
483
+ config(factTypes.includes(String(input.fact_type))
484
+ && matches(input.amount, signedDecimalAmountPattern)
485
+ && (input.currency === 'USD' || input.currency === 'USDC')
486
+ && text(input.resource_version, 1, 255)
487
+ && typeof input.predecessor_version === 'string' && text(input.predecessor_version.trim(), 1, 255)
488
+ && input.predecessor_version !== input.resource_version
489
+ && text(input.mapping_revision, 1, 255)
490
+ && time(input.recorded_at)
491
+ && (input.merchant_name === undefined || text(input.merchant_name, 1, 255))
492
+ && (input.merchant_mcc === undefined || matches(input.merchant_mcc, /^[0-9]{4}$/))
493
+ && (input.merchant_country === undefined || text(input.merchant_country, 2, 3))
494
+ && [input.supplier_transaction_id, input.parent_supplier_transaction_id, input.client_transaction_id].every((value) => value === undefined || (typeof value === 'string' && text(value.trim(), 1, 255))),
495
+ 'Authorization fact type, predecessor version, amount, or timestamp is invalid')
496
+ }
497
+
498
+ function authorizationFacts(value: unknown): value is AuthorizationFacts {
499
+ return Array.isArray(value) && value.length === 5 && value.every((fact, index) =>
500
+ responseFields(fact, ['kind', 'state', 'recorded_at', 'source_system'], ['observed_at', 'safe_code'])
501
+ && fact.kind === factKinds[index] && ['unobserved', 'pending', 'confirmed', 'rejected', 'indeterminate'].includes(String(fact.state))
502
+ && time(fact.recorded_at) && ['facto', 'provider', 'chain'].includes(String(fact.source_system))
503
+ && (fact.safe_code === undefined || text(fact.safe_code, 1, 64))
504
+ && (fact.observed_at === undefined || time(fact.observed_at))
505
+ && (fact.state !== 'confirmed' || time(fact.observed_at))
506
+ && (fact.state !== 'unobserved' || !Object.hasOwn(fact, 'observed_at')))
507
+ }
508
+
509
+ function finalReceipt(value: unknown): value is CardFinalReceipt {
510
+ if (!responseFields(value, ['receipt_event_id', 'charge_id', 'mapping_revision', 'operation_type', 'resource_version', 'execution_outcome', 'terminal_action', 'finalized_at', 'facts_at_finality'], ['external_authorization_id', 'authorization_ref'])
511
+ || !uuid(value.receipt_event_id) || !chargeId(value.charge_id)
512
+ || !(text(value.external_authorization_id, 1, 256) || text(value.authorization_ref, 1, 256))
513
+ || !text(value.mapping_revision, 1, 255) || !allFactTypes.includes(String(value.operation_type))
514
+ || !text(value.resource_version, 1, 255) || !time(value.finalized_at)
515
+ || !authorizationFacts(value.facts_at_finality) || value.facts_at_finality[3].state !== 'confirmed') return false
516
+ return value.terminal_action === 'releaseFor'
517
+ ? value.execution_outcome === 'succeeded' && value.facts_at_finality[0].state === 'confirmed' && value.facts_at_finality[1].state === 'confirmed'
518
+ : value.terminal_action === 'cancelReservation' && value.execution_outcome === 'failed'
519
+ }
520
+
521
+ function optionalLifecycle(value: unknown): boolean {
522
+ if (value === undefined) return true
523
+ if (!object(value) || !object(value.issuer) || !Array.isArray(value.issuer.entries) || !Array.isArray(value.refund_cases)) return false
524
+ const issuer = value.issuer
525
+ const entries = issuer.entries as unknown[]
526
+ return ['state', 'cleared_amount', 'reversed_amount', 'refunded_amount'].every((key) => typeof issuer[key] === 'string')
527
+ && entries.every((entry: unknown) => object(entry)
528
+ && ['operation_type', 'resource_version', 'amount', 'currency', 'recorded_at', 'link_status'].every((key) => typeof entry[key] === 'string')
529
+ && entry.currency === 'USDC'
530
+ && (entry.unlinked_reason === undefined || typeof entry.unlinked_reason === 'string'))
531
+ && value.refund_cases.every((entry: unknown) => object(entry)
532
+ && ['case_id', 'source_operation_type', 'source_resource_version', 'status', 'amount', 'excess_amount', 'updated_at'].every((key) => typeof entry[key] === 'string')
533
+ && (entry.paid_amount === undefined || typeof entry.paid_amount === 'string')
534
+ && (entry.not_payable_reason === undefined || typeof entry.not_payable_reason === 'string'))
535
+ }
536
+
537
+ function optionalPaymentDetails(value: unknown, hasLifecycle: boolean): boolean {
538
+ if (value === undefined) return true
539
+ if (!object(value) || typeof value.fee_total !== 'string' || !object(value.fee_breakdown)) return false
540
+ const fees = value.fee_breakdown
541
+ if (!['base_fee', 'fast_pay_fee', 'pooled_surcharge'].every((key) => typeof fees[key] === 'string')) return false
542
+ const payment = value.user_payment
543
+ if (payment !== undefined && (!object(payment) || !Number.isSafeInteger(payment.chain_id)
544
+ || typeof payment.tx_hash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(payment.tx_hash)
545
+ || (payment.asset_symbol !== undefined && typeof payment.asset_symbol !== 'string'))) return false
546
+ return value.refund_payments === undefined || (hasLifecycle && Array.isArray(value.refund_payments)
547
+ && value.refund_payments.every((entry: unknown) => object(entry) && Number.isSafeInteger(entry.chain_id)
548
+ && typeof entry.case_id === 'string' && typeof entry.paid_amount === 'string' && typeof entry.recorded_by === 'string'
549
+ && typeof entry.tx_hash === 'string' && /^0x[0-9a-fA-F]{64}$/.test(entry.tx_hash)))
550
+ }
551
+
552
+ function authorizationProjection(value: unknown): value is AuthorizationProjection {
553
+ if (!responseFields(value, ['external_authorization_id', 'processing_status', 'origin_connection_id', 'resource_version', 'mapping_revision'], ['charge_id', 'final_receipt', 'decline_reason_code', 'supplier_transaction_id', 'facts', 'revision', 'operation_type', 'decision', 'lifecycle', 'payment_details'])
554
+ || !text(value.external_authorization_id, 1, 256)
555
+ || typeof value.origin_connection_id !== 'string' || !pconnPattern.test(value.origin_connection_id)
556
+ || !text(value.resource_version, 1, 255) || !text(value.mapping_revision, 1, 255)
557
+ || (value.charge_id !== undefined && value.charge_id !== null && !chargeId(value.charge_id))
558
+ || (value.supplier_transaction_id !== undefined && !text(value.supplier_transaction_id, 1, 256))
559
+ || (value.facts !== undefined && !authorizationFacts(value.facts))
560
+ || (value.revision !== undefined && !revision(value.revision))
561
+ || (value.operation_type !== undefined && !allFactTypes.includes(String(value.operation_type)))
562
+ || (value.decision !== undefined && !['approved', 'declined', 'self_reversed_timeout'].includes(String(value.decision)))
563
+ || (value.decline_reason_code !== undefined && !declineReasonCode(value.decline_reason_code))
564
+ || !optionalLifecycle(value.lifecycle)
565
+ || !optionalPaymentDetails(value.payment_details, value.lifecycle !== undefined)) return false
566
+ if (value.processing_status === 'succeeded' || value.processing_status === 'failed') {
567
+ if (Object.hasOwn(value, 'final_receipt') && value.final_receipt !== undefined) {
568
+ if (!chargeId(value.charge_id) || !finalReceipt(value.final_receipt) || Object.hasOwn(value, 'decline_reason_code')) return false
569
+ const receipt = value.final_receipt
570
+ const receiptAuthId = (receipt as { external_authorization_id?: string; authorization_ref?: string }).external_authorization_id
571
+ ?? (receipt as { authorization_ref?: string }).authorization_ref
572
+ return receipt.execution_outcome === value.processing_status
573
+ && receipt.charge_id === value.charge_id
574
+ && receiptAuthId === value.external_authorization_id
575
+ && receipt.mapping_revision === value.mapping_revision
576
+ && receipt.resource_version === value.resource_version
577
+ && (value.operation_type === undefined || receipt.operation_type === value.operation_type)
578
+ }
579
+ if (value.processing_status === 'succeeded') {
580
+ return !Object.hasOwn(value, 'decline_reason_code') && (value.charge_id === undefined || chargeId(value.charge_id))
581
+ }
582
+ return chargeId(value.charge_id)
583
+ || ((value.charge_id === undefined || value.charge_id === null)
584
+ && (value.decision === 'declined' || value.decision === 'self_reversed_timeout' || value.decline_reason_code !== undefined))
585
+ }
586
+ return !Object.hasOwn(value, 'final_receipt') && !Object.hasOwn(value, 'decline_reason_code')
587
+ && (value.processing_status === 'processing'
588
+ || (value.processing_status === 'indeterminate' && (value.charge_id === undefined || value.charge_id === null)))
589
+ }
590
+
591
+ function authorizationLookupResult(value: unknown): value is AuthorizationLookupResult {
592
+ if (!responseFields(value, ['observed_at', 'resolution'], ['authorization']) || !time(value.observed_at)) return false
593
+ if (value.resolution === 'not_observed') return !Object.hasOwn(value, 'authorization') || value.authorization === undefined
594
+ if (!authorizationProjection(value.authorization)) return false
595
+ return value.resolution === 'resolved' ? ['succeeded', 'failed'].includes(value.authorization.processing_status)
596
+ : value.resolution === 'pending' ? value.authorization.processing_status === 'processing'
597
+ : value.resolution === 'unknown' && value.authorization.processing_status === 'indeterminate'
598
+ }
599
+
600
+ function authorizationAccepted(value: unknown): value is AuthorizationAccepted {
601
+ return responseFields(value, ['charge_id', 'status'])
602
+ && chargeId(value.charge_id)
603
+ && ['processing', 'approved', 'declined'].includes(String(value.status))
604
+ && !Object.hasOwn(value, 'final_receipt')
605
+ }
606
+
607
+ function authorizationFactRecorded(value: unknown): value is AuthorizationFactReceipt {
608
+ return responseFields(value, ['operation_id', 'status'])
609
+ && uuid(value.operation_id) && value.status === 'recorded'
610
+ }
611
+
612
+ function synchronousAuthorization(value: unknown, status: number): value is SynchronousAuthorizationResult {
613
+ if (!responseFields(value, ['deadline_at', 'decision_id']) || !time(value.deadline_at) || !uuid(value.decision_id)) return false
614
+ if (status === 200) {
615
+ return value.decision === 'approved' && value.status === 'approved' && chargeId(value.charge_id) && time(value.decided_at)
616
+ }
617
+ if (typeof value.error !== 'string' || typeof value.message !== 'string' || typeof value.request_id !== 'string') return false
618
+ if (status === 408 && value.error === 'decision_deadline_exceeded' && !Object.hasOwn(value, 'decision')) return true
619
+ return time(value.decided_at) && ((status === 422 && value.decision === 'declined')
620
+ || (status === 408 && value.decision === 'self_reversed_timeout'))
621
+ }
622
+
623
+ function bindingCreated(value: unknown): value is BindingSessionCreated {
624
+ if (!responseFields(value, ['binding_session_id', 'status', 'binding_url', 'expires_at', 'proof_policy'])
625
+ || !matches(value.binding_session_id, sessionPattern) || value.status !== 'pending'
626
+ || typeof value.binding_url !== 'string' || !time(value.expires_at)) return false
627
+ const policy = value.proof_policy
628
+ return responseFields(policy, ['allowed_modes', 'challenge_after_facto_auth', 'challenge_delivery'], ['card_selection_supported'])
629
+ && Array.isArray(policy.allowed_modes) && policy.allowed_modes.length > 0
630
+ && new Set(policy.allowed_modes).size === policy.allowed_modes.length
631
+ && policy.allowed_modes.every((mode) => mode === 'provider_reauthentication' || mode === 'provider_second_channel')
632
+ && policy.challenge_after_facto_auth === true
633
+ && (policy.challenge_delivery === 'browser_handoff' || policy.challenge_delivery === 'provider_backend')
634
+ && (policy.card_selection_supported === undefined || policy.card_selection_supported === true)
635
+ }
636
+
637
+ function bindingStatus(value: unknown): value is BindingSessionStatus {
638
+ if (!object(value) || !matches(value.binding_session_id, sessionPattern) || !time(value.expires_at)) return false
639
+ const base = ['binding_session_id', 'status', 'expires_at']
640
+ if (['pending', 'proof_pending', 'consent_pending'].includes(String(value.status))) {
641
+ return responseFields(value, base)
642
+ && !['outcome', 'binding_ids', 'failure_reason', 'completed_at'].some((key) => Object.hasOwn(value, key))
643
+ }
644
+ if (value.status === 'completed') {
645
+ if (Object.hasOwn(value, 'completed_at') && !time(value.completed_at)) return false
646
+ return value.outcome === 'bound'
647
+ ? responseFields(value, [...base, 'outcome', 'binding_ids'], ['completed_at'])
648
+ && !Object.hasOwn(value, 'failure_reason') && bindingIds(value.binding_ids)
649
+ : value.outcome === 'declined' && responseFields(value, [...base, 'outcome', 'failure_reason'], ['completed_at'])
650
+ && !Object.hasOwn(value, 'binding_ids')
651
+ && value.failure_reason === 'declined_by_user'
652
+ }
653
+ if (value.status === 'cancelled') {
654
+ return responseFields(value, base, ['completed_at', 'failure_reason'])
655
+ && !['outcome', 'binding_ids'].some((key) => Object.hasOwn(value, key))
656
+ && (!Object.hasOwn(value, 'completed_at') || time(value.completed_at))
657
+ && (!Object.hasOwn(value, 'failure_reason') || ['cancelled_by_user', 'cancelled_by_partner', 'proof_rejected', 'admission_closed', 'no_eligible_cards', 'integrity_conflict'].includes(String(value.failure_reason)))
658
+ }
659
+ return value.status === 'expired' && responseFields(value, base, ['failure_reason'])
660
+ && !['completed_at', 'outcome', 'binding_ids'].some((key) => Object.hasOwn(value, key))
661
+ && (!Object.hasOwn(value, 'failure_reason') || value.failure_reason === 'expired' || value.failure_reason === 'proof_timeout')
662
+ }
663
+
664
+ function proofAccepted(value: unknown): value is ProviderProofAccepted {
665
+ return responseFields(value, ['binding_session_id', 'status', 'proof_received_at'])
666
+ && matches(value.binding_session_id, sessionPattern) && value.status === 'consent_pending' && time(value.proof_received_at)
667
+ }
668
+
669
+ function proofChallenge(value: unknown): value is BindingProofChallenge {
670
+ return responseFields(value, ['binding_session_id', 'facto_challenge', 'session_request_digest', 'expires_at'])
671
+ && matches(value.binding_session_id, sessionPattern)
672
+ && text(value.facto_challenge, 1, 512)
673
+ && matches(value.session_request_digest, digestPattern)
674
+ && time(value.expires_at)
675
+ }
676
+
677
+ function validateSessionCreate(input: unknown): asserts input is BindingSessionCreateInput {
678
+ config(closed(input, ['requested_user_consents', 'return_uri']), 'Binding session requires the generated consent and return URI fields')
679
+ const consents = input.requested_user_consents
680
+ config(Array.isArray(consents) && consents.length > 0 && new Set(consents).size === consents.length
681
+ && consents.every((item) => item === 'card.metadata.view' || item === 'card.use_for_facto_payments'), 'Binding session consents are invalid')
682
+ config(typeof input.return_uri === 'string' && Buffer.byteLength(input.return_uri, 'utf8') <= 2048
683
+ && input.return_uri.startsWith('https://') && !/[#\r\n]/.test(input.return_uri)
684
+ && input.return_uri.slice(8).split(/[/?]/, 1)[0].length > 0 && !input.return_uri.slice(8).split(/[/?]/, 1)[0].includes('@'), 'An exact registered HTTPS return URI is required')
685
+ }
686
+
687
+ function validateProofPayload(input: unknown): asserts input is ProviderProofSubmitPayload {
688
+ config(closed(input, ['proof_format', 'binding_assertion']) && input.proof_format === 'compact-jws'
689
+ && typeof input.binding_assertion === 'string' && input.binding_assertion.length >= 128 && input.binding_assertion.length <= 16384
690
+ && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(input.binding_assertion), 'The original compact JWS provider proof is required')
691
+ }
692
+
693
+ function intentCardList(value: unknown): value is IntentCardList {
694
+ return responseFields(value, ['id', 'revision', 'cards'])
695
+ && matches(value.id, intentPattern) && matches(value.revision, intentDigestPattern)
696
+ && Array.isArray(value.cards) && value.cards.every((item) =>
697
+ responseFields(item, ['binding_id', 'status', 'card'])
698
+ && matches(item.binding_id, bindingPattern) && typeof item.status === 'string'
699
+ && cardDisplayFacts(item.card))
700
+ }
701
+
702
+ function intentCardsReplaced(value: unknown): value is IntentCardsReplaced {
703
+ return responseFields(value, ['id', 'status', 'revision', 'added_binding_ids', 'removed_binding_ids', 'kept_binding_ids'])
704
+ && matches(value.id, intentPattern) && ['applied', 'no_change'].includes(String(value.status))
705
+ && matches(value.revision, intentDigestPattern) && bindingIds(value.added_binding_ids)
706
+ && bindingIds(value.removed_binding_ids) && bindingIds(value.kept_binding_ids)
707
+ }
708
+
709
+ function intentCancelled(value: unknown): value is IntentCancelled {
710
+ return responseFields(value, ['id', 'status']) && matches(value.id, intentPattern) && value.status === 'cancelled'
711
+ }
712
+
713
+ function bindingFunding(value: unknown): boolean {
714
+ return value === undefined || (responseFields(value, ['configured', 'state'], ['reason'])
715
+ && typeof value.configured === 'boolean'
716
+ && ['ready', 'not_configured', 'unavailable'].includes(String(value.state))
717
+ && (value.reason === undefined || value.reason === null || typeof value.reason === 'string'))
718
+ }
719
+
720
+ function bindingLookupResult(value: unknown): value is BindingLookupResult {
721
+ if (!responseFields(value, ['binding'], ['found'])) return false
722
+ if (value.found !== undefined && typeof value.found !== 'boolean') return false
723
+ const binding = value.binding
724
+ if (binding === null) return value.found !== true
725
+ return (value.found === undefined || value.found === true)
726
+ && responseFields(binding, ['id', 'status', 'revision', 'card'], ['funding'])
727
+ && matches(binding.id, bindingPattern) && typeof binding.status === 'string'
728
+ && int32(binding.revision, 1) && cardDisplayFacts(binding.card)
729
+ && bindingFunding(binding.funding)
730
+ }
731
+
732
+ function deadLetterPage(value: unknown): value is DeadLetterPage {
733
+ return responseFields(value, ['items']) && Array.isArray(value.items) && value.items.every((item) =>
734
+ responseFields(item, ['id', 'event_kind', 'binding_id', 'binding_revision', 'connection_sequence', 'delivery_attempts', 'last_delivery_error', 'dead_lettered_at', 'replay_count'])
735
+ && matches(item.id, uuidPattern) && typeof item.event_kind === 'string' && matches(item.binding_id, bindingPattern)
736
+ && int32(item.binding_revision, 1)
737
+ && (item.connection_sequence === null || (typeof item.connection_sequence === 'number' && Number.isSafeInteger(item.connection_sequence) && item.connection_sequence >= 1))
738
+ && int32(item.delivery_attempts, 1) && nullableString(item.last_delivery_error)
739
+ && (item.dead_lettered_at === null || time(item.dead_lettered_at)) && int32(item.replay_count, 0))
740
+ }
741
+
742
+ function deadLetterReplayAccepted(value: unknown): value is DeadLetterReplayAccepted {
743
+ return responseFields(value, ['id', 'status']) && uuid(value.id) && value.status === 'accepted'
744
+ }
745
+
746
+ function inboundEventReceipt(value: unknown): value is CardInboundEventReceipt {
747
+ return responseFields(value, ['delivery_id', 'disposition', 'effect']) && uuid(value.delivery_id)
748
+ && (value.disposition === 'duplicate' ? value.effect === null
749
+ : value.disposition === 'applied' && ['revoked', 'status_updated', 'released', 'none'].includes(String(value.effect)))
750
+ }
751
+
752
+ function validateReplaceCards(input: unknown): asserts input is IntentCardsReplaceInput {
753
+ config(closed(input, ['intent_token', 'approval_id', 'approval_sha256', 'revision', 'cards'], ['external_account_id'])
754
+ && header(input.intent_token, 32, 8192) && text(input.approval_id, 1, 255)
755
+ && matches(input.approval_sha256, sha256HexPattern) && matches(input.revision, intentDigestPattern)
756
+ && optionalValue(input.external_account_id, (value) => typeof value === 'string' && value.length > 0 && Buffer.byteLength(value, 'utf8') <= 512),
757
+ 'Card replacement requires the original complete approved request')
758
+ config(Array.isArray(input.cards) && input.cards.length <= 50
759
+ && input.cards.every((card) => closed(card, ['external_card_id'], ['network', 'type', 'last4'])
760
+ && safeExternalCardId(card.external_card_id, 255)
761
+ && optionalValue(card.network, (value) => safeExternalCardId(value, 40))
762
+ && optionalValue(card.type, (value) => value === 'virtual' || value === 'physical' || value === 'unknown')
763
+ && optionalValue(card.last4, (value) => typeof value === 'string' && /^[0-9]{4}$/.test(value))),
764
+ 'Target cards must match the generated safe card projection')
765
+ }
766
+
767
+ function validateInboundEvent(input: unknown): asserts input is CardInboundEventInput {
768
+ config(closed(input, ['delivery_id', 'kind', 'assertion_jws'], ['external_card_id', 'lifecycle_status', 'external_account_id'])
769
+ && uuid(input.delivery_id) && typeof input.assertion_jws === 'string' && input.assertion_jws.trim().length >= 32,
770
+ 'Inbound event requires a UUID delivery_id and signed assertion_jws')
771
+ const absent = (value: unknown) => value === undefined || value === null
772
+ config(input.kind === 'account.released'
773
+ ? text(input.external_account_id, 1, 512) && absent(input.external_card_id) && absent(input.lifecycle_status)
774
+ : safeExternalCardId(input.external_card_id) && absent(input.external_account_id)
775
+ && (input.kind === 'card.unbound' ? absent(input.lifecycle_status)
776
+ : input.kind === 'card.lifecycle_changed' && lifecycleStates.includes(String(input.lifecycle_status))),
777
+ 'Inbound event fields must match the declared event kind')
778
+ }
779
+
780
+ function originalKey(options: CardIdempotentRequestOptions): string {
781
+ config(options && header(options.idempotencyKey, 16, 255), 'An explicit original Idempotency-Key of 16 to 255 characters is required')
782
+ return options.idempotencyKey
783
+ }
784
+
785
+ function sessionPath(id: string): string {
786
+ config(matches(id, sessionPattern), 'id must be the original binding session identifier')
787
+ return `/api/card/connect/sessions/${id}`
788
+ }
789
+
790
+ function intentPath(id: string): string {
791
+ config(matches(id, intentPattern), 'id must be the original connect intent identifier')
792
+ return `/api/card/connect/intents/${id}`
793
+ }
794
+
795
+ function opaqueBody(options?: CardOpaqueRequestOptions): string | undefined {
796
+ config(options?.rawBody === undefined || typeof options?.rawBody === 'string', 'rawBody must preserve the original authenticated request bytes')
797
+ return options?.rawBody
798
+ }
799
+
800
+ /** Card machine client for SCP and CIP backends; never a browser or human session facade. */
801
+ export function createCardClient(options: CardClientOptions): CardClient {
802
+ config(closed(options, ['environment', 'connectionId', 'programId', 'apiKeyId', 'apiKeySecret'], [...transportKeys, 'nowSeconds', 'createNonce']), 'Card client options cannot contain human session or arbitrary authentication fields')
803
+ config(typeof options.connectionId === 'string' && pconnPattern.test(options.connectionId), 'connectionId must be a pconn_ connection identifier')
804
+ config(text(options.programId, 1, 128) && header(options.apiKeyId), 'programId and apiKeyId are required')
805
+ const secret = resolveCardApiKeySecret(options.apiKeySecret)
806
+ const request = transport(options, 'program')
807
+ const scope = Object.freeze({ connectionId: options.connectionId, environment: options.environment, programId: options.programId })
808
+ const keyId = options.apiKeyId
809
+ const now = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000))
810
+ const nonce = options.createNonce ?? randomUUID
811
+
812
+ function signed(path: string, body: string, idempotencyKey?: string, method: 'GET' | 'PUT' | 'POST' = 'POST'): Headers {
813
+ const timestamp = now()
814
+ const requestNonce = nonce()
815
+ config(Number.isSafeInteger(timestamp) && timestamp >= 1_000_000_000 && timestamp <= 9_999_999_999, 'nowSeconds must return a ten-digit Unix timestamp in seconds')
816
+ config(header(requestNonce, 1, 128), 'createNonce must return a bounded canonical nonce')
817
+ return signCardRequest({ secret, apiKeyId: keyId, method, target: path, timestamp, nonce: requestNonce, body, idempotencyKey })
818
+ }
819
+
820
+ return Object.freeze({
821
+ scope,
822
+ sessions: Object.freeze<CardSessionsApi>({
823
+ async create(input, requestOptions) {
824
+ validateSessionCreate(input)
825
+ config(closed(requestOptions, ['idempotencyKey'], ['cardSelection', 'signal']), 'Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal')
826
+ const key = originalKey(requestOptions)
827
+ config(requestOptions.cardSelection === undefined || typeof requestOptions.cardSelection === 'boolean', 'cardSelection must be a boolean when provided')
828
+ const body: BindingSessionCreate = { ...input, program_ref: scope.programId }
829
+ const raw = JSON.stringify(body)
830
+ const path = '/api/card/connect/sessions'
831
+ const headers = signed(path, raw, key)
832
+ if (requestOptions.cardSelection === true) headers.set('x-facto-card-selection', '1')
833
+ return request('POST', path, headers, raw, [201], bindingCreated, requestOptions)
834
+ },
835
+ async get(id, requestOptions) {
836
+ const path = sessionPath(id)
837
+ const result = await request('GET', path, signed(path, '', undefined, 'GET'), undefined, [200], bindingStatus, requestOptions)
838
+ if (result.binding_session_id !== id) throw invalidResponse(200)
839
+ return result
840
+ },
841
+ async submitProof(id, input, requestOptions) {
842
+ const path = `${sessionPath(id)}/provider-proof`
843
+ const key = originalKey(requestOptions)
844
+ config(object(input), 'Provider proof input is required')
845
+ let payload: ProviderProofSubmitPayload
846
+ if (Object.hasOwn(input, 'proof_format') || Object.hasOwn(input, 'binding_assertion')) {
847
+ validateProofPayload(input)
848
+ payload = input
849
+ } else {
850
+ config(
851
+ !['environment', 'programId', 'bindingSessionId', 'connectionId'].some((field) => Object.hasOwn(input, field)),
852
+ 'Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)',
853
+ )
854
+ const assertionInput = input as SessionProofAssertionInput
855
+ const issuedAtSeconds = assertionInput.issuedAtSeconds ?? now()
856
+ const binding_assertion = await signBindingAssertion({
857
+ ...assertionInput,
858
+ environment: scope.environment,
859
+ programId: scope.programId,
860
+ bindingSessionId: id,
861
+ issuedAtSeconds,
862
+ })
863
+ payload = { proof_format: 'compact-jws', binding_assertion }
864
+ validateProofPayload(payload)
865
+ }
866
+ const raw = JSON.stringify(payload)
867
+ const result = await request('POST', path, signed(path, raw, key), raw, [202], proofAccepted, requestOptions)
868
+ if (result.binding_session_id !== id) throw invalidResponse(202)
869
+ return result
870
+ },
871
+ async getProofChallenge(id, requestOptions) {
872
+ const path = `${sessionPath(id)}/proof-challenge`
873
+ const result = await request('GET', path, signed(path, '', undefined, 'GET'), undefined, [200], proofChallenge, requestOptions)
874
+ if (result.binding_session_id !== id) throw invalidResponse(200)
875
+ return result
876
+ },
877
+ async cancel(id, requestOptions) {
878
+ const path = `${sessionPath(id)}/cancel`
879
+ const key = originalKey(requestOptions)
880
+ const raw = opaqueBody(requestOptions) ?? '{}'
881
+ const result = await request('POST', path, signed(path, raw, key), raw, [200], bindingStatus, requestOptions)
882
+ if (result.binding_session_id !== id) throw invalidResponse(200)
883
+ return result
884
+ },
885
+ }),
886
+ intents: Object.freeze<CardIntentsApi>({
887
+ async listCards(id, requestOptions) {
888
+ const path = `${intentPath(id)}/cards`
889
+ config(closed(requestOptions, ['intentToken'], ['signal']) && header(requestOptions.intentToken, 32, 8192), 'intentToken must be a valid HTTP header value of at least 32 characters')
890
+ const headers = signed(path, '', undefined, 'GET')
891
+ headers.set('x-facto-intent-token', requestOptions.intentToken)
892
+ const result = await request('GET', path, headers, undefined, [200], intentCardList, requestOptions)
893
+ if (result.id !== id) throw invalidResponse(200)
894
+ return result
895
+ },
896
+ async replaceCards(id, input, requestOptions) {
897
+ const path = `${intentPath(id)}/cards`
898
+ validateReplaceCards(input)
899
+ const key = originalKey(requestOptions)
900
+ const raw = JSON.stringify(input)
901
+ const result = await request('PUT', path, signed(path, raw, key, 'PUT'), raw, [200], intentCardsReplaced, requestOptions)
902
+ if (result.id !== id) throw invalidResponse(200)
903
+ return result
904
+ },
905
+ async cancel(id, input, requestOptions) {
906
+ const path = `${intentPath(id)}/cancel`
907
+ config(closed(input, ['intent_token']) && header(input.intent_token, 32, 8192), 'Cancel requires the original intent_token body of at least 32 characters')
908
+ const raw = JSON.stringify(input)
909
+ const result = await request('POST', path, signed(path, raw), raw, [200], intentCancelled, requestOptions)
910
+ if (result.id !== id) throw invalidResponse(200)
911
+ return result
912
+ },
913
+ }),
914
+ bindings: Object.freeze<CardBindingsApi>({
915
+ async lookup(input, requestOptions) {
916
+ config(closed(input, ['external_card_id']) && safeExternalCardId(input.external_card_id), 'Binding lookup requires only an opaque external_card_id in its body')
917
+ const raw = JSON.stringify(input)
918
+ const path = '/api/card/bindings/lookup'
919
+ return request('POST', path, signed(path, raw), raw, [200], bindingLookupResult, requestOptions)
920
+ },
921
+ }),
922
+ authorizations: Object.freeze<CardAuthorizationsApi>({
923
+ create: (async (input: AuthorizationCreateInput | SynchronousAuthorizationCreateInput, requestOptions: CardIdempotentRequestOptions) => {
924
+ validateAuthorizationCreate(input)
925
+ const key = originalKey(requestOptions)
926
+ const body: AuthorizationSubmitInput = { ...input, program_id: scope.programId }
927
+ const raw = JSON.stringify(body)
928
+ const path = '/api/card/authorizations'
929
+ if (input.decision_mode === 'synchronous') {
930
+ return request('POST', path, signed(path, raw, key), raw, [200, 422, 408], synchronousAuthorization, requestOptions)
931
+ }
932
+ return request('POST', path, signed(path, raw, key), raw, [200], authorizationAccepted, requestOptions)
933
+ }) as CardAuthorizationsApi['create'],
934
+ async recordFact(externalId, input, requestOptions) {
935
+ validateAuthorizationFact(externalId, input)
936
+ const key = originalKey(requestOptions)
937
+ const body: AuthorizationFactRecordInput = { ...input, program_id: scope.programId }
938
+ const raw = JSON.stringify(body)
939
+ const path = `/api/card/authorizations/${encodeURIComponent(externalId)}/facts`
940
+ return request('POST', path, signed(path, raw, key), raw, [200], authorizationFactRecorded, requestOptions)
941
+ },
942
+ async lookup(input, requestOptions) {
943
+ const criteria = normalizeLookupCriteria(input)
944
+ const body: AuthorizationLookupInput = { program_id: scope.programId, criteria }
945
+ const raw = JSON.stringify(body)
946
+ const path = '/api/card/authorizations/lookup'
947
+ const result = await request('POST', path, signed(path, raw), raw, [200], authorizationLookupResult, requestOptions)
948
+ const authorization = result.authorization
949
+ if (authorization) {
950
+ if (authorization.origin_connection_id !== scope.connectionId
951
+ || (criteria.by === 'charge_id' && authorization.charge_id?.toLowerCase() !== criteria.charge_id.toLowerCase())
952
+ || (criteria.by === 'external_authorization_id' && (authorization.external_authorization_id !== criteria.external_authorization_id
953
+ || authorization.resource_version !== criteria.resource_version
954
+ || authorization.mapping_revision !== criteria.mapping_revision
955
+ || (criteria.fact_type !== undefined && authorization.operation_type !== undefined && authorization.operation_type !== criteria.fact_type)))
956
+ || (criteria.by === 'supplier_transaction_id' && (authorization.supplier_transaction_id !== criteria.supplier_transaction_id.trim()
957
+ || authorization.resource_version !== criteria.resource_version
958
+ || authorization.mapping_revision !== criteria.mapping_revision
959
+ || (criteria.fact_type !== undefined && authorization.operation_type !== undefined && authorization.operation_type !== criteria.fact_type)))) throw invalidResponse(200)
960
+ }
961
+ return result
962
+ },
963
+ }),
964
+ events: Object.freeze<CardEventsApi>({
965
+ async record(input, requestOptions) {
966
+ validateInboundEvent(input)
967
+ const raw = JSON.stringify(input)
968
+ const path = '/api/card/events'
969
+ const result = await request('POST', path, signed(path, raw), raw, [200], inboundEventReceipt, requestOptions)
970
+ const expectedEffect = input.kind === 'card.unbound' ? 'revoked' : input.kind === 'card.lifecycle_changed' ? 'status_updated' : 'released'
971
+ if (result.delivery_id !== input.delivery_id || (result.disposition === 'applied' && result.effect !== 'none' && result.effect !== expectedEffect)) throw invalidResponse(200)
972
+ return result
973
+ },
974
+ }),
975
+ deliveries: Object.freeze<CardDeliveriesApi>({
976
+ async list(input, requestOptions) {
977
+ validateReconciliation(input)
978
+ const body: DeliveryReconciliationListInput = { ...input, program_id: scope.programId }
979
+ const raw = JSON.stringify(body)
980
+ const path = '/api/card/deliveries/reconciliations/list'
981
+ const result = await request('POST', path, signed(path, raw), raw, [200], deliveryPage, requestOptions)
982
+ if (result.items.length > input.page_size) throw invalidResponse(200)
983
+ return result
984
+ },
985
+ }),
986
+ deliveryReplays: Object.freeze<CardDeliveryReplaysApi>({
987
+ async create(input, requestOptions) {
988
+ config(closed(input, ['selection_id']) && uuid(input.selection_id), 'Delivery replay requires a fixed selection_id UUID')
989
+ const key = originalKey(requestOptions)
990
+ const body: DeliveryReplayCreateInput = { ...input, program_id: scope.programId }
991
+ const raw = JSON.stringify(body)
992
+ const path = '/api/card/deliveries/replays'
993
+ const result = await request('POST', path, signed(path, raw, key), raw, [202], deliveryReplayAccepted, requestOptions)
994
+ if (result.selection_id !== input.selection_id) throw invalidResponse(202)
995
+ return result
996
+ },
997
+ }),
998
+ deadLetters: Object.freeze<CardDeadLettersApi>({
999
+ async list(params, requestOptions) {
1000
+ config(params === undefined || (closed(params, [], ['limit'])
1001
+ && optionalValue(params.limit, (limit) => typeof limit === 'number' && Number.isInteger(limit) && limit >= 1 && limit <= 100)), 'Dead-letter limit must be null, absent, or an integer from 1 to 100')
1002
+ const limit = typeof params?.limit === 'number' ? params.limit : undefined
1003
+ const path = limit !== undefined ? `/api/card/deliveries/dead-letters?limit=${limit}` : '/api/card/deliveries/dead-letters'
1004
+ const result = await request('GET', path, signed(path, '', undefined, 'GET'), undefined, [200], deadLetterPage, requestOptions)
1005
+ if (result.items.length > (limit ?? 50)) throw invalidResponse(200)
1006
+ return result
1007
+ },
1008
+ async replay(id, requestOptions) {
1009
+ config(uuid(id), 'The dead-letter path identifier must be a UUID')
1010
+ const path = `/api/card/deliveries/dead-letters/${id}/replay`
1011
+ const raw = opaqueBody(requestOptions)
1012
+ const result = await request('POST', path, signed(path, raw ?? ''), raw, [202], deadLetterReplayAccepted, requestOptions)
1013
+ if (result.id !== id) throw invalidResponse(202)
1014
+ return result
1015
+ },
1016
+ }),
1017
+ } satisfies CardClient)
1018
+ }