@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.
- package/CHANGELOG.md +20 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +63 -2
- package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
- package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
- package/dist/chunk-KBS2PWM4.js +2 -0
- package/dist/cli/index.js +6 -0
- package/dist/docs/README.md +9 -0
- package/dist/docs/authentication.md +96 -0
- package/dist/docs/authorization-binding.md +182 -0
- package/dist/docs/authorizations.md +182 -0
- package/dist/docs/concepts.md +36 -0
- package/dist/docs/deliveries.md +170 -0
- package/dist/docs/errors.md +100 -0
- package/dist/docs/getting-access.md +56 -0
- package/dist/docs/idempotency.md +78 -0
- package/dist/docs/integration-checklist.md +15 -0
- package/dist/docs/integration.zh.md +59 -0
- package/dist/docs/interlace-adapter-v1.md +87 -0
- package/dist/docs/interlace-adapter-v1.zh.md +87 -0
- package/dist/docs/not-yet-available.md +13 -0
- package/dist/docs/quickstart.md +126 -0
- package/dist/docs/reconciliation.md +86 -0
- package/dist/docs/reference/api.md +2541 -0
- package/dist/docs/reference/events.md +639 -0
- package/dist/docs/reference/schemas.json +6603 -0
- package/dist/docs/reference/schemas.md +1001 -0
- package/dist/docs/simulator.md +235 -0
- package/dist/docs/versioning.md +9 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +987 -0
- package/dist/index.d.ts +987 -0
- package/dist/index.js +2 -0
- package/dist/source/build.mjs +5 -0
- package/dist/source/package.json +16 -0
- package/dist/source/src/connect/cli/deliveries.ts +48 -0
- package/dist/source/src/connect/cli/index.ts +57 -0
- package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
- package/dist/source/src/connect/server/card-client.ts +1018 -0
- package/dist/source/src/connect/server/card-delivery.ts +301 -0
- package/dist/source/src/connect/server/card-events.ts +473 -0
- package/dist/source/src/connect/server/card-idempotency.ts +27 -0
- package/dist/source/src/connect/server/card-inbox.ts +82 -0
- package/dist/source/src/connect/server/card-intent-token.ts +588 -0
- package/dist/source/src/connect/server/card-polling.ts +69 -0
- package/dist/source/src/connect/server/card-signing.ts +115 -0
- package/dist/source/src/connect/server/card-transport.ts +282 -0
- package/dist/source/src/connect/server/errors.ts +280 -0
- package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
- package/dist/source/src/connect/server/retry-after.ts +12 -0
- package/dist/source/src/connect/testing/card-inbox.ts +124 -0
- package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
- package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
- package/dist/source/src/connect/testing/card-simulator.ts +531 -0
- package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
- package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
- package/dist/source/src/connect/wire.d.ts +544 -0
- package/dist/source/src/index.ts +163 -0
- package/dist/source/src/testing-browser.ts +24 -0
- package/dist/source/src/testing.ts +26 -0
- package/dist/source/tsconfig.json +20 -0
- package/dist/testing-browser.d.ts +220 -0
- package/dist/testing-browser.js +5 -0
- package/dist/testing.cjs +6 -0
- package/dist/testing.d.cts +199 -0
- package/dist/testing.d.ts +199 -0
- package/dist/testing.js +5 -0
- package/package.json +60 -4
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import type { EventDeliveryVerification } from './card-delivery'
|
|
2
|
+
|
|
3
|
+
export const CARD_EVENT_KINDS = [
|
|
4
|
+
'card.binding.linked',
|
|
5
|
+
'card.binding.relinked',
|
|
6
|
+
'card.binding.revoked',
|
|
7
|
+
'card.binding.route_changed',
|
|
8
|
+
'card.binding.limits_changed',
|
|
9
|
+
'card.binding.ownership_transferred',
|
|
10
|
+
'card.charge.finalized',
|
|
11
|
+
'card.charge.facts_updated',
|
|
12
|
+
'card.authorization.updated',
|
|
13
|
+
] as const
|
|
14
|
+
|
|
15
|
+
export type CardEventKind = (typeof CARD_EVENT_KINDS)[number]
|
|
16
|
+
type BindingKind = Extract<CardEventKind, `card.binding.${string}`>
|
|
17
|
+
type JsonObject = Readonly<Record<string, unknown>>
|
|
18
|
+
type CardUsdcAmount = string
|
|
19
|
+
|
|
20
|
+
/** Legacy and transport keys prohibited anywhere inside Envelope v2 `data`. */
|
|
21
|
+
export const BANNED_ENVELOPE_V2_DATA_KEYS = [
|
|
22
|
+
'card_program_id',
|
|
23
|
+
'program_connection_id',
|
|
24
|
+
'connect_intent_id',
|
|
25
|
+
'binding_session_id',
|
|
26
|
+
'card_type',
|
|
27
|
+
'envelope_expires_at',
|
|
28
|
+
'authorization_ref',
|
|
29
|
+
'redelivery',
|
|
30
|
+
] as const
|
|
31
|
+
|
|
32
|
+
const BANNED_ENVELOPE_V2_DATA_KEY_SET: ReadonlySet<string> = new Set(BANNED_ENVELOPE_V2_DATA_KEYS)
|
|
33
|
+
|
|
34
|
+
/** Recursively check whether an Envelope v2 `data` payload contains any prohibited legacy or transport key. */
|
|
35
|
+
export function containsBannedEnvelopeV2DataKey(value: unknown): boolean {
|
|
36
|
+
if (value === null || typeof value !== 'object') return false
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
return value.some((item) => containsBannedEnvelopeV2DataKey(item))
|
|
39
|
+
}
|
|
40
|
+
for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {
|
|
41
|
+
if (BANNED_ENVELOPE_V2_DATA_KEY_SET.has(key)) return true
|
|
42
|
+
if (containsBannedEnvelopeV2DataKey(nested)) return true
|
|
43
|
+
}
|
|
44
|
+
return false
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface DeliveredCardDisplay {
|
|
48
|
+
readonly network: string | null
|
|
49
|
+
readonly type: 'virtual' | 'physical' | 'unknown' | (string & {}) | null
|
|
50
|
+
readonly last4: string | null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface Envelope<K extends string> {
|
|
54
|
+
readonly envelope_version: 2
|
|
55
|
+
readonly event_id: string
|
|
56
|
+
readonly event_kind: K
|
|
57
|
+
readonly environment: 'dev' | 'production'
|
|
58
|
+
readonly program_id: string
|
|
59
|
+
readonly origin_connection_id?: string
|
|
60
|
+
readonly connection_sequence: number | null
|
|
61
|
+
readonly occurred_at: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type BindingData<K extends BindingKind> =
|
|
65
|
+
K extends 'card.binding.linked' | 'card.binding.relinked' ? {
|
|
66
|
+
readonly external_card_id: string
|
|
67
|
+
readonly binding_id: string
|
|
68
|
+
readonly card: DeliveredCardDisplay
|
|
69
|
+
readonly intent_id?: string | null
|
|
70
|
+
readonly environment?: 'dev' | 'production'
|
|
71
|
+
readonly subject_link_id?: string
|
|
72
|
+
readonly approved_scopes?: readonly string[]
|
|
73
|
+
readonly consent_revision?: string
|
|
74
|
+
readonly ownership_transfer?: boolean
|
|
75
|
+
readonly previous_binding_id?: string
|
|
76
|
+
} : K extends 'card.binding.revoked' ? {
|
|
77
|
+
readonly external_card_id: string
|
|
78
|
+
readonly binding_id: string
|
|
79
|
+
readonly card: DeliveredCardDisplay
|
|
80
|
+
readonly environment?: 'dev' | 'production'
|
|
81
|
+
readonly binding_revision?: number
|
|
82
|
+
readonly intent_id?: string | null
|
|
83
|
+
readonly reason_code?: string
|
|
84
|
+
readonly revocation_source?: string
|
|
85
|
+
readonly payable_projections_closed?: number
|
|
86
|
+
readonly routes_detached?: number
|
|
87
|
+
readonly route_associations_detached?: number
|
|
88
|
+
} : K extends 'card.binding.route_changed' ? {
|
|
89
|
+
readonly binding_id: string
|
|
90
|
+
readonly association_status: 'associated' | 'unassociated'
|
|
91
|
+
readonly environment?: 'dev' | 'production'
|
|
92
|
+
readonly binding_revision?: number
|
|
93
|
+
} : K extends 'card.binding.limits_changed' ? {
|
|
94
|
+
readonly binding_id: string
|
|
95
|
+
readonly per_tx_limit: CardUsdcAmount
|
|
96
|
+
readonly period_limit: CardUsdcAmount
|
|
97
|
+
readonly period: string
|
|
98
|
+
readonly expires_at: string | null
|
|
99
|
+
readonly environment?: 'dev' | 'production'
|
|
100
|
+
readonly binding_revision?: number
|
|
101
|
+
} : {
|
|
102
|
+
readonly previous_binding_id: string
|
|
103
|
+
readonly new_binding_id: string
|
|
104
|
+
readonly external_card_id: string
|
|
105
|
+
readonly card: DeliveredCardDisplay
|
|
106
|
+
readonly transferred_at: string
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export type CardBindingEvent<K extends BindingKind = BindingKind> = Envelope<K> & {
|
|
110
|
+
readonly binding_id: string
|
|
111
|
+
readonly binding_revision: number
|
|
112
|
+
readonly data: BindingData<K>
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface ChargeFact {
|
|
116
|
+
readonly kind: string
|
|
117
|
+
readonly state: string
|
|
118
|
+
readonly recorded_at: string
|
|
119
|
+
readonly source_system: string
|
|
120
|
+
readonly observed_at?: string
|
|
121
|
+
readonly safe_code?: string
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface DeliveredChargeFinalReceipt {
|
|
125
|
+
readonly receipt_event_id: string
|
|
126
|
+
readonly charge_id: string
|
|
127
|
+
readonly external_authorization_id: string
|
|
128
|
+
readonly mapping_revision: string
|
|
129
|
+
readonly operation_type: string
|
|
130
|
+
readonly resource_version: string
|
|
131
|
+
readonly execution_outcome: string
|
|
132
|
+
readonly terminal_action: string
|
|
133
|
+
readonly finalized_at: string
|
|
134
|
+
readonly facts_at_finality: readonly ChargeFact[]
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
interface SequencedEnvelope<K extends string> extends Envelope<K> {
|
|
138
|
+
readonly connection_sequence: number
|
|
139
|
+
readonly origin_connection_id: string
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export type ChargeFinalizedEvent = SequencedEnvelope<'card.charge.finalized'> & {
|
|
143
|
+
readonly data: {
|
|
144
|
+
readonly authorization_revision: number
|
|
145
|
+
readonly operation_type: string
|
|
146
|
+
readonly resource_version: string
|
|
147
|
+
readonly external_authorization_id: string
|
|
148
|
+
readonly mapping_revision: string
|
|
149
|
+
readonly final_receipt: DeliveredChargeFinalReceipt
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export type ChargeFactsUpdatedEvent = SequencedEnvelope<'card.charge.facts_updated'> & {
|
|
154
|
+
readonly data: {
|
|
155
|
+
readonly authorization_revision: number
|
|
156
|
+
readonly operation_type: string
|
|
157
|
+
readonly resource_version: string
|
|
158
|
+
readonly external_authorization_id: string
|
|
159
|
+
readonly mapping_revision: string
|
|
160
|
+
readonly charge_id: string
|
|
161
|
+
readonly final_receipt_event_id: string
|
|
162
|
+
readonly previous_authorization_revision: number
|
|
163
|
+
readonly facts: readonly ChargeFact[]
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export interface CipLifecycleSummary {
|
|
168
|
+
readonly state: string
|
|
169
|
+
readonly cleared_amount: CardUsdcAmount
|
|
170
|
+
readonly reversed_amount: CardUsdcAmount
|
|
171
|
+
readonly refunded_amount: CardUsdcAmount
|
|
172
|
+
readonly entry_count: number
|
|
173
|
+
readonly unlinked_count: number
|
|
174
|
+
readonly last_recorded_at?: string
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface RefundSummary {
|
|
178
|
+
readonly case_count: number
|
|
179
|
+
readonly status_counts: Readonly<{
|
|
180
|
+
awaiting_charge_final: number
|
|
181
|
+
awaiting_funds: number
|
|
182
|
+
payable: number
|
|
183
|
+
paid: number
|
|
184
|
+
failed: number
|
|
185
|
+
not_payable: number
|
|
186
|
+
}>
|
|
187
|
+
readonly total_amount: CardUsdcAmount
|
|
188
|
+
readonly total_paid_amount: CardUsdcAmount
|
|
189
|
+
readonly total_excess_amount: CardUsdcAmount
|
|
190
|
+
readonly last_updated_at?: string
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export interface AuthorizationChange {
|
|
194
|
+
readonly type: string
|
|
195
|
+
readonly at: string
|
|
196
|
+
readonly ref?: string
|
|
197
|
+
readonly issuer_fact?: Readonly<{
|
|
198
|
+
operation_type: string
|
|
199
|
+
resource_version: string
|
|
200
|
+
amount: CardUsdcAmount
|
|
201
|
+
currency: string
|
|
202
|
+
recorded_at: string
|
|
203
|
+
link_status: string
|
|
204
|
+
unlinked_reason?: string
|
|
205
|
+
}>
|
|
206
|
+
readonly refund_case?: Readonly<{
|
|
207
|
+
case_id: string
|
|
208
|
+
source_operation_type: string
|
|
209
|
+
status: string
|
|
210
|
+
amount: CardUsdcAmount
|
|
211
|
+
excess_amount: CardUsdcAmount
|
|
212
|
+
paid_amount?: CardUsdcAmount
|
|
213
|
+
not_payable_reason?: string
|
|
214
|
+
updated_at: string
|
|
215
|
+
refund_payment?: Readonly<{
|
|
216
|
+
chain_id: number
|
|
217
|
+
tx_hash: string
|
|
218
|
+
paid_amount: CardUsdcAmount
|
|
219
|
+
recorded_by: string
|
|
220
|
+
}>
|
|
221
|
+
}>
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface AuthorizationUpdateData {
|
|
225
|
+
readonly lifecycle_revision: number
|
|
226
|
+
readonly operation_type: string
|
|
227
|
+
readonly resource_version: string
|
|
228
|
+
readonly external_authorization_id: string
|
|
229
|
+
readonly mapping_revision: string
|
|
230
|
+
readonly authorization: Readonly<{
|
|
231
|
+
supplier_transaction_id?: string
|
|
232
|
+
amount: CardUsdcAmount
|
|
233
|
+
currency: string
|
|
234
|
+
decision?: string
|
|
235
|
+
}>
|
|
236
|
+
readonly charge: Readonly<{
|
|
237
|
+
charge_id: string
|
|
238
|
+
status: string
|
|
239
|
+
amount: CardUsdcAmount
|
|
240
|
+
fee_total: CardUsdcAmount
|
|
241
|
+
total_debited: CardUsdcAmount
|
|
242
|
+
currency: string
|
|
243
|
+
user_payment?: Readonly<{ chain_id: number; asset_symbol?: string; tx_hash: string }>
|
|
244
|
+
failure_code?: string
|
|
245
|
+
updated_at: string
|
|
246
|
+
}> | null
|
|
247
|
+
readonly issuer: CipLifecycleSummary
|
|
248
|
+
readonly refunds: RefundSummary
|
|
249
|
+
readonly change: AuthorizationChange
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export type AuthorizationUpdatedEvent = SequencedEnvelope<'card.authorization.updated'> & {
|
|
253
|
+
readonly data: AuthorizationUpdateData
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export type CardKnownEvent =
|
|
257
|
+
| { [K in BindingKind]: CardBindingEvent<K> }[BindingKind]
|
|
258
|
+
| ChargeFinalizedEvent
|
|
259
|
+
| ChargeFactsUpdatedEvent
|
|
260
|
+
| AuthorizationUpdatedEvent
|
|
261
|
+
|
|
262
|
+
export type DecodedDeliveryEvent =
|
|
263
|
+
| { readonly type: 'known'; readonly event: CardKnownEvent }
|
|
264
|
+
| { readonly type: 'unknown'; readonly eventKind: string; readonly rawJson: string; readonly event: JsonObject }
|
|
265
|
+
|
|
266
|
+
const ENVELOPE_KEYS = new Set([
|
|
267
|
+
'envelope_version',
|
|
268
|
+
'event_id',
|
|
269
|
+
'event_kind',
|
|
270
|
+
'environment',
|
|
271
|
+
'program_id',
|
|
272
|
+
'origin_connection_id',
|
|
273
|
+
'binding_id',
|
|
274
|
+
'binding_revision',
|
|
275
|
+
'connection_sequence',
|
|
276
|
+
'occurred_at',
|
|
277
|
+
'data',
|
|
278
|
+
])
|
|
279
|
+
|
|
280
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
281
|
+
const PROGRAM_ID_PATTERN = /^cprog_[A-Za-z0-9_-]{8,}$/
|
|
282
|
+
const CONNECTION_ID_PATTERN = /^pconn_[A-Za-z0-9_-]{16,}$/
|
|
283
|
+
const BINDING_ID_PATTERN = /^cb_[A-Za-z0-9_-]{16,}$/
|
|
284
|
+
|
|
285
|
+
function object(value: unknown): value is Record<string, unknown> {
|
|
286
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
287
|
+
}
|
|
288
|
+
function nonEmptyString(value: unknown): value is string {
|
|
289
|
+
return typeof value === 'string' && value.length > 0
|
|
290
|
+
}
|
|
291
|
+
function nullableString(value: unknown): boolean {
|
|
292
|
+
return value === null || typeof value === 'string'
|
|
293
|
+
}
|
|
294
|
+
function strings(value: Record<string, unknown>, names: readonly string[]): boolean {
|
|
295
|
+
return names.every((name) => nonEmptyString(value[name]))
|
|
296
|
+
}
|
|
297
|
+
function integer(value: unknown): value is number { return Number.isSafeInteger(value) }
|
|
298
|
+
function facts(value: unknown): boolean {
|
|
299
|
+
return Array.isArray(value) && value.every((fact) =>
|
|
300
|
+
object(fact) &&
|
|
301
|
+
strings(fact, ['kind', 'state', 'recorded_at', 'source_system']) &&
|
|
302
|
+
(fact.observed_at === undefined || typeof fact.observed_at === 'string') &&
|
|
303
|
+
(fact.safe_code === undefined || typeof fact.safe_code === 'string'))
|
|
304
|
+
}
|
|
305
|
+
function optionalStrings(value: Record<string, unknown>, names: readonly string[]): boolean {
|
|
306
|
+
return names.every((name) => value[name] === undefined || typeof value[name] === 'string')
|
|
307
|
+
}
|
|
308
|
+
function optionalNullableStrings(value: Record<string, unknown>, names: readonly string[]): boolean {
|
|
309
|
+
return names.every((name) => value[name] === undefined || value[name] === null || typeof value[name] === 'string')
|
|
310
|
+
}
|
|
311
|
+
function validCardDisplay(value: unknown): boolean {
|
|
312
|
+
return (
|
|
313
|
+
object(value) &&
|
|
314
|
+
Object.hasOwn(value, 'network') && Object.hasOwn(value, 'type') && Object.hasOwn(value, 'last4') &&
|
|
315
|
+
nullableString(value.network) &&
|
|
316
|
+
nullableString(value.type) &&
|
|
317
|
+
nullableString(value.last4)
|
|
318
|
+
)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function authorizationUpdate(data: Record<string, unknown>): boolean {
|
|
322
|
+
if (
|
|
323
|
+
!integer(data.lifecycle_revision) || data.lifecycle_revision < 1 ||
|
|
324
|
+
!strings(data, ['operation_type', 'resource_version', 'external_authorization_id', 'mapping_revision'])
|
|
325
|
+
) return false
|
|
326
|
+
const { authorization, charge, issuer, refunds, change } = data
|
|
327
|
+
if (
|
|
328
|
+
!object(authorization) || !strings(authorization, ['amount', 'currency']) || !optionalStrings(authorization, ['supplier_transaction_id', 'decision']) ||
|
|
329
|
+
!object(issuer) || !strings(issuer, ['state', 'cleared_amount', 'reversed_amount', 'refunded_amount']) ||
|
|
330
|
+
!optionalStrings(issuer, ['last_recorded_at']) || !integer(issuer.entry_count) || issuer.entry_count < 0 ||
|
|
331
|
+
!integer(issuer.unlinked_count) || issuer.unlinked_count < 0 ||
|
|
332
|
+
!object(refunds) || !integer(refunds.case_count) || refunds.case_count < 0 ||
|
|
333
|
+
!strings(refunds, ['total_amount', 'total_paid_amount', 'total_excess_amount']) || !optionalStrings(refunds, ['last_updated_at']) ||
|
|
334
|
+
!object(refunds.status_counts) ||
|
|
335
|
+
!object(change) || !strings(change, ['type', 'at']) || !optionalStrings(change, ['ref'])
|
|
336
|
+
) return false
|
|
337
|
+
const counts = refunds.status_counts
|
|
338
|
+
if (!['awaiting_charge_final', 'awaiting_funds', 'payable', 'paid', 'failed', 'not_payable'].every((key) => integer(counts[key]) && (counts[key] as number) >= 0)) return false
|
|
339
|
+
if (change.type === 'issuer_fact.recorded' && change.issuer_fact === undefined) return false
|
|
340
|
+
if (['refund_case.awaiting_charge_final', 'refund_case.awaiting_funds', 'refund_case.payable', 'refund_case.paid', 'refund_case.failed', 'refund_case.not_payable'].includes(String(change.type)) && change.refund_case === undefined) return false
|
|
341
|
+
if (change.type === 'refund_case.paid' && (!object(change.refund_case) || !object(change.refund_case.refund_payment))) return false
|
|
342
|
+
if (charge !== null) {
|
|
343
|
+
if (
|
|
344
|
+
!object(charge) || !strings(charge, ['charge_id', 'status', 'amount', 'fee_total', 'total_debited', 'currency', 'updated_at']) ||
|
|
345
|
+
!optionalStrings(charge, ['failure_code']) ||
|
|
346
|
+
(charge.user_payment !== undefined && (!object(charge.user_payment) || !integer(charge.user_payment.chain_id) || !strings(charge.user_payment, ['tx_hash']) || !optionalStrings(charge.user_payment, ['asset_symbol'])))
|
|
347
|
+
) return false
|
|
348
|
+
}
|
|
349
|
+
if (
|
|
350
|
+
change.issuer_fact !== undefined &&
|
|
351
|
+
(!object(change.issuer_fact) || !strings(change.issuer_fact, ['operation_type', 'resource_version', 'amount', 'currency', 'recorded_at', 'link_status']) || !optionalStrings(change.issuer_fact, ['unlinked_reason']))
|
|
352
|
+
) return false
|
|
353
|
+
if (change.refund_case !== undefined) {
|
|
354
|
+
const c = change.refund_case
|
|
355
|
+
if (
|
|
356
|
+
!object(c) || !strings(c, ['case_id', 'source_operation_type', 'status', 'amount', 'excess_amount', 'updated_at']) ||
|
|
357
|
+
!optionalStrings(c, ['paid_amount', 'not_payable_reason']) ||
|
|
358
|
+
(c.refund_payment !== undefined && (!object(c.refund_payment) || !integer(c.refund_payment.chain_id) || !strings(c.refund_payment, ['tx_hash', 'paid_amount', 'recorded_by'])))
|
|
359
|
+
) return false
|
|
360
|
+
}
|
|
361
|
+
return true
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Decode only a successful signature verification. Unknown additive `data` fields are retained; banned legacy/transport keys fail closed. */
|
|
365
|
+
export function decodeDeliveryEvent(delivery: Extract<EventDeliveryVerification, { verified: true }>): DecodedDeliveryEvent {
|
|
366
|
+
const value: unknown = JSON.parse(delivery.eventJson)
|
|
367
|
+
if (!object(value) || value.event_id !== delivery.eventId || value.event_kind !== delivery.eventKind) throw new Error('invalid_card_event')
|
|
368
|
+
if (!(CARD_EVENT_KINDS as readonly string[]).includes(delivery.eventKind)) {
|
|
369
|
+
if (object(value.data) && containsBannedEnvelopeV2DataKey(value.data)) {
|
|
370
|
+
throw new Error('invalid_card_event')
|
|
371
|
+
}
|
|
372
|
+
return { type: 'unknown', eventKind: delivery.eventKind, rawJson: delivery.eventJson, event: value }
|
|
373
|
+
}
|
|
374
|
+
if (
|
|
375
|
+
Object.keys(value).some((key) => !ENVELOPE_KEYS.has(key)) ||
|
|
376
|
+
value.envelope_version !== 2 ||
|
|
377
|
+
!strings(value, ['event_id', 'event_kind', 'environment', 'program_id', 'occurred_at']) ||
|
|
378
|
+
!UUID_PATTERN.test(value.event_id as string) ||
|
|
379
|
+
!PROGRAM_ID_PATTERN.test(value.program_id as string) ||
|
|
380
|
+
(value.environment !== 'dev' && value.environment !== 'production') ||
|
|
381
|
+
(value.origin_connection_id !== undefined && (!nonEmptyString(value.origin_connection_id) || !CONNECTION_ID_PATTERN.test(value.origin_connection_id))) ||
|
|
382
|
+
!(value.connection_sequence === null || (integer(value.connection_sequence) && value.connection_sequence >= 1)) ||
|
|
383
|
+
!object(value.data) ||
|
|
384
|
+
containsBannedEnvelopeV2DataKey(value.data)
|
|
385
|
+
) throw new Error('invalid_card_event')
|
|
386
|
+
|
|
387
|
+
if (delivery.eventKind.startsWith('card.binding.')) {
|
|
388
|
+
if (
|
|
389
|
+
!nonEmptyString(value.binding_id) ||
|
|
390
|
+
!BINDING_ID_PATTERN.test(value.binding_id) ||
|
|
391
|
+
!integer(value.binding_revision) ||
|
|
392
|
+
value.binding_revision < 1
|
|
393
|
+
) {
|
|
394
|
+
throw new Error('invalid_card_event')
|
|
395
|
+
}
|
|
396
|
+
const data = value.data
|
|
397
|
+
const kind = delivery.eventKind
|
|
398
|
+
if (kind === 'card.binding.linked' || kind === 'card.binding.relinked') {
|
|
399
|
+
if (
|
|
400
|
+
!strings(data, ['external_card_id', 'binding_id']) ||
|
|
401
|
+
!validCardDisplay(data.card) ||
|
|
402
|
+
!optionalNullableStrings(data, ['intent_id']) ||
|
|
403
|
+
(data.ownership_transfer !== undefined && typeof data.ownership_transfer !== 'boolean') ||
|
|
404
|
+
!optionalStrings(data, ['environment', 'subject_link_id', 'consent_revision', 'previous_binding_id']) ||
|
|
405
|
+
(data.environment !== undefined && data.environment !== 'dev' && data.environment !== 'production') ||
|
|
406
|
+
(data.approved_scopes !== undefined && (!Array.isArray(data.approved_scopes) || !data.approved_scopes.every((scope) => typeof scope === 'string')))
|
|
407
|
+
) throw new Error('invalid_card_event')
|
|
408
|
+
} else if (kind === 'card.binding.revoked') {
|
|
409
|
+
if (
|
|
410
|
+
!strings(data, ['external_card_id', 'binding_id']) ||
|
|
411
|
+
!validCardDisplay(data.card) ||
|
|
412
|
+
!(nonEmptyString(data.reason_code) || nonEmptyString(data.revocation_source)) ||
|
|
413
|
+
!optionalNullableStrings(data, ['intent_id']) ||
|
|
414
|
+
!optionalStrings(data, ['reason_code', 'revocation_source', 'environment']) ||
|
|
415
|
+
(data.environment !== undefined && data.environment !== 'dev' && data.environment !== 'production') ||
|
|
416
|
+
(data.binding_revision !== undefined && (!integer(data.binding_revision) || data.binding_revision < 1)) ||
|
|
417
|
+
(data.payable_projections_closed !== undefined && (!integer(data.payable_projections_closed) || data.payable_projections_closed < 0)) ||
|
|
418
|
+
(data.route_associations_detached !== undefined && (!integer(data.route_associations_detached) || data.route_associations_detached < 0)) ||
|
|
419
|
+
(data.routes_detached !== undefined && (!integer(data.routes_detached) || data.routes_detached < 0))
|
|
420
|
+
) throw new Error('invalid_card_event')
|
|
421
|
+
} else if (kind === 'card.binding.route_changed') {
|
|
422
|
+
if (
|
|
423
|
+
!strings(data, ['binding_id']) ||
|
|
424
|
+
!(data.association_status === 'associated' || data.association_status === 'unassociated') ||
|
|
425
|
+
!optionalStrings(data, ['environment']) ||
|
|
426
|
+
(data.environment !== undefined && data.environment !== 'dev' && data.environment !== 'production') ||
|
|
427
|
+
(data.binding_revision !== undefined && (!integer(data.binding_revision) || data.binding_revision < 1))
|
|
428
|
+
) throw new Error('invalid_card_event')
|
|
429
|
+
} else if (kind === 'card.binding.limits_changed') {
|
|
430
|
+
if (
|
|
431
|
+
!strings(data, ['binding_id', 'per_tx_limit', 'period_limit', 'period']) ||
|
|
432
|
+
!Object.hasOwn(data, 'expires_at') || !nullableString(data.expires_at) ||
|
|
433
|
+
!optionalStrings(data, ['environment']) ||
|
|
434
|
+
(data.environment !== undefined && data.environment !== 'dev' && data.environment !== 'production') ||
|
|
435
|
+
(data.binding_revision !== undefined && (!integer(data.binding_revision) || data.binding_revision < 1))
|
|
436
|
+
) throw new Error('invalid_card_event')
|
|
437
|
+
} else if (kind === 'card.binding.ownership_transferred') {
|
|
438
|
+
if (
|
|
439
|
+
!strings(data, ['previous_binding_id', 'new_binding_id', 'external_card_id', 'transferred_at']) ||
|
|
440
|
+
!validCardDisplay(data.card)
|
|
441
|
+
) throw new Error('invalid_card_event')
|
|
442
|
+
}
|
|
443
|
+
} else if (delivery.eventKind === 'card.authorization.updated') {
|
|
444
|
+
if (
|
|
445
|
+
value.binding_id !== undefined || value.binding_revision !== undefined ||
|
|
446
|
+
!integer(value.connection_sequence) || value.connection_sequence < 1 ||
|
|
447
|
+
!nonEmptyString(value.origin_connection_id) ||
|
|
448
|
+
!authorizationUpdate(value.data)
|
|
449
|
+
) throw new Error('invalid_card_event')
|
|
450
|
+
} else {
|
|
451
|
+
const data = value.data
|
|
452
|
+
if (
|
|
453
|
+
value.binding_id !== undefined || value.binding_revision !== undefined ||
|
|
454
|
+
!integer(value.connection_sequence) || value.connection_sequence < 1 ||
|
|
455
|
+
!nonEmptyString(value.origin_connection_id) ||
|
|
456
|
+
!integer(data.authorization_revision) || data.authorization_revision < 1 ||
|
|
457
|
+
!strings(data, ['operation_type', 'resource_version', 'external_authorization_id', 'mapping_revision'])
|
|
458
|
+
) throw new Error('invalid_card_event')
|
|
459
|
+
if (delivery.eventKind === 'card.charge.finalized') {
|
|
460
|
+
if (!object(data.final_receipt)) throw new Error('invalid_card_event')
|
|
461
|
+
const receipt = data.final_receipt
|
|
462
|
+
if (
|
|
463
|
+
!strings(receipt, ['receipt_event_id', 'charge_id', 'external_authorization_id', 'mapping_revision', 'operation_type', 'resource_version', 'execution_outcome', 'terminal_action', 'finalized_at']) ||
|
|
464
|
+
!facts(receipt.facts_at_finality)
|
|
465
|
+
) throw new Error('invalid_card_event')
|
|
466
|
+
} else if (
|
|
467
|
+
!strings(data, ['charge_id', 'final_receipt_event_id']) ||
|
|
468
|
+
!integer(data.previous_authorization_revision) || data.previous_authorization_revision < 1 ||
|
|
469
|
+
!facts(data.facts)
|
|
470
|
+
) throw new Error('invalid_card_event')
|
|
471
|
+
}
|
|
472
|
+
return { type: 'known', event: value as unknown as CardKnownEvent }
|
|
473
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/** Stable business identifiers for one authorization, scoped to a connection. */
|
|
4
|
+
export interface AuthorizationIdentity {
|
|
5
|
+
readonly connectionId: string
|
|
6
|
+
readonly externalAuthorizationId: string
|
|
7
|
+
readonly supplierTransactionId?: string
|
|
8
|
+
readonly clientTransactionId?: string
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Derive a replay key without including delivery or transaction timestamps. */
|
|
12
|
+
export function deriveAuthorizationIdempotencyKey(identity: AuthorizationIdentity): string {
|
|
13
|
+
const fields = [identity.connectionId, identity.externalAuthorizationId, identity.supplierTransactionId, identity.clientTransactionId]
|
|
14
|
+
if (
|
|
15
|
+
typeof fields[0] !== 'string' || fields[0].trim() === '' ||
|
|
16
|
+
typeof fields[1] !== 'string' || fields[1].trim() === '' ||
|
|
17
|
+
fields.some((field) => field !== undefined && typeof field !== 'string')
|
|
18
|
+
) {
|
|
19
|
+
throw new TypeError('Connection and authorization identity must be strings')
|
|
20
|
+
}
|
|
21
|
+
const hash = createHash('sha256').update('facto.card.authorization-idempotency.v1\0')
|
|
22
|
+
for (const field of fields) {
|
|
23
|
+
if (field === undefined) hash.update('u;')
|
|
24
|
+
else hash.update(`s${Buffer.byteLength(field, 'utf8')}:`).update(field)
|
|
25
|
+
}
|
|
26
|
+
return `card_auth_${hash.digest('hex')}`
|
|
27
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { decodeDeliveryEvent, type DecodedDeliveryEvent } from './card-events'
|
|
2
|
+
import { isVerifiedEventDelivery, type EventDeliveryVerification, type DeliveryScope } from './card-delivery'
|
|
3
|
+
|
|
4
|
+
type Verified = Extract<EventDeliveryVerification, { verified: true }>
|
|
5
|
+
|
|
6
|
+
/** The application transaction is shared by business writes and inbox confirmation. */
|
|
7
|
+
export interface DeliveryInboxTransaction<Context = unknown> {
|
|
8
|
+
readonly context: Context
|
|
9
|
+
/** Monotonically increasing token; downstream nontransactional writes must fence it. */
|
|
10
|
+
readonly fence: number
|
|
11
|
+
getDigest(eventId: string): Promise<string | undefined>
|
|
12
|
+
/** Maximum confirmed sequence observed so far; null when none is known. */
|
|
13
|
+
getObservedMaxSequence(): Promise<number | null>
|
|
14
|
+
/** Atomically confirm and retain max(previous maximum, sequence), if non-null. */
|
|
15
|
+
markProcessed(eventId: string, digest: string, sequence: number | null): Promise<void>
|
|
16
|
+
}
|
|
17
|
+
export interface DeliveryInboxStore<Context = unknown> {
|
|
18
|
+
/**
|
|
19
|
+
* Serialize each connection across processes while a lease is live; reject or
|
|
20
|
+
* wait boundedly for competing claims. Bound transaction duration and roll
|
|
21
|
+
* back on failure or process death. After expiry, reclaim with a larger fence;
|
|
22
|
+
* reject stale confirmation and fence business writes from a resumed holder.
|
|
23
|
+
* A timed-out handler may still be running, so external effects need their own
|
|
24
|
+
* idempotency or fencing.
|
|
25
|
+
*/
|
|
26
|
+
withConnection<T>(scope: Readonly<DeliveryScope>, operation: (transaction: DeliveryInboxTransaction<Context>) => Promise<T>): Promise<T>
|
|
27
|
+
}
|
|
28
|
+
export type DeliveryEventRevision =
|
|
29
|
+
| { readonly field: 'binding_revision' | 'authorization_revision' | 'lifecycle_revision'; readonly value: number }
|
|
30
|
+
| null
|
|
31
|
+
export interface DeliveryInboxMetadata {
|
|
32
|
+
readonly connectionSequence: number | null
|
|
33
|
+
/** Revision belongs to the event's resource; it is not a generic discard rule. */
|
|
34
|
+
readonly eventRevision: DeliveryEventRevision
|
|
35
|
+
}
|
|
36
|
+
export interface DeliveryInboxOptions<Context = unknown> {
|
|
37
|
+
readonly store: DeliveryInboxStore<Context>
|
|
38
|
+
readonly handle: (event: DecodedDeliveryEvent, transaction: DeliveryInboxTransaction<Context>, metadata: DeliveryInboxMetadata) => Promise<void>
|
|
39
|
+
}
|
|
40
|
+
export interface ObservedSequenceGap {
|
|
41
|
+
readonly previousMaxSequence: number
|
|
42
|
+
readonly currentSequence: number
|
|
43
|
+
}
|
|
44
|
+
export type DeliveryInboxResult = {
|
|
45
|
+
readonly status: 'processed' | 'duplicate_ignored'
|
|
46
|
+
readonly connectionSequence: number | null
|
|
47
|
+
/** Observation only, not evidence of a missing event. Never emitted for duplicates. */
|
|
48
|
+
readonly observedSequenceGap: ObservedSequenceGap | null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Receive only a successful verifyEventDelivery result; any other object,
|
|
53
|
+
* including a structurally identical copy, is rejected with `delivery_not_verified`.
|
|
54
|
+
* Process in admitted arrival order; sequence observations do not establish order or completeness.
|
|
55
|
+
*/
|
|
56
|
+
export async function receiveEventDelivery<Context>(delivery: Verified, options: DeliveryInboxOptions<Context>): Promise<DeliveryInboxResult> {
|
|
57
|
+
if (!isVerifiedEventDelivery(delivery)) throw new Error('delivery_not_verified')
|
|
58
|
+
const decoded = decodeDeliveryEvent(delivery)
|
|
59
|
+
const rawSequence = decoded.event.connection_sequence
|
|
60
|
+
const sequence = rawSequence === undefined && decoded.type === 'unknown' ? null : rawSequence
|
|
61
|
+
if (!(sequence === null || (typeof sequence === 'number' && Number.isSafeInteger(sequence) && sequence > 0))) throw new Error('invalid_connection_sequence')
|
|
62
|
+
const eventRevision: DeliveryEventRevision = decoded.type !== 'known' ? null
|
|
63
|
+
: 'binding_revision' in decoded.event ? { field: 'binding_revision', value: decoded.event.binding_revision }
|
|
64
|
+
: decoded.event.event_kind === 'card.authorization.updated'
|
|
65
|
+
? { field: 'lifecycle_revision', value: decoded.event.data.lifecycle_revision }
|
|
66
|
+
: { field: 'authorization_revision', value: decoded.event.data.authorization_revision }
|
|
67
|
+
return options.store.withConnection(delivery.scope, async (tx) => {
|
|
68
|
+
const previous = await tx.getDigest(delivery.eventId)
|
|
69
|
+
if (previous !== undefined) {
|
|
70
|
+
if (previous !== delivery.bodyDigest) throw new Error('event_id_conflict')
|
|
71
|
+
return { status: 'duplicate_ignored', connectionSequence: sequence, observedSequenceGap: null }
|
|
72
|
+
}
|
|
73
|
+
const maximum = await tx.getObservedMaxSequence()
|
|
74
|
+
if (maximum !== null && (!Number.isSafeInteger(maximum) || maximum < 1)) throw new Error('invalid_observed_max_sequence')
|
|
75
|
+
// Unsubscribed events and retries can account for a jump; never call it loss.
|
|
76
|
+
const observedSequenceGap = sequence !== null && maximum !== null && sequence > maximum + 1
|
|
77
|
+
? { previousMaxSequence: maximum, currentSequence: sequence } : null
|
|
78
|
+
await options.handle(decoded, tx, { connectionSequence: sequence, eventRevision })
|
|
79
|
+
await tx.markProcessed(delivery.eventId, delivery.bodyDigest, sequence)
|
|
80
|
+
return { status: 'processed', connectionSequence: sequence, observedSequenceGap }
|
|
81
|
+
})
|
|
82
|
+
}
|