@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,531 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { createServer, type Server } from 'node:http'
|
|
3
|
+
import { verifyCardRequest } from '../server/card-signing'
|
|
4
|
+
import { deliveryInboxVectors } from './card-inbox'
|
|
5
|
+
import { simulatorDeliveryConfig, simulatorDeliveryKinds, simulatorDeliveryScenario } from './card-scenarios'
|
|
6
|
+
|
|
7
|
+
// Synthetic local test credentials only; never use these outside the simulator.
|
|
8
|
+
export const simulatorIdentity = {
|
|
9
|
+
connectionId: 'pconn_SYNTHETIC00000001',
|
|
10
|
+
programId: 'synthetic-program',
|
|
11
|
+
apiKeyId: 'synthetic-key',
|
|
12
|
+
apiKeySecret: { encoding: 'utf8', value: 'SYNTHETIC-TEST-KEY-NOT-A-SECRET' },
|
|
13
|
+
} as const
|
|
14
|
+
export const simulatorTarget = '00000000-0000-4000-8000-000000000001'
|
|
15
|
+
export const simulatorSelection = '00000000-0000-4000-8000-000000000002'
|
|
16
|
+
|
|
17
|
+
type SimulatorOperation = {
|
|
18
|
+
externalAuthorizationId: string
|
|
19
|
+
factType: string
|
|
20
|
+
body: Record<string, unknown>
|
|
21
|
+
normalized: string
|
|
22
|
+
identity: string
|
|
23
|
+
lineageVersion: string
|
|
24
|
+
supplierIdentity?: string
|
|
25
|
+
chargeId: string
|
|
26
|
+
operationId: string
|
|
27
|
+
keys: Set<string>
|
|
28
|
+
deadline?: number
|
|
29
|
+
decision?: 'declined' | 'self_reversed_timeout'
|
|
30
|
+
expiresAt: number
|
|
31
|
+
statusReads: number
|
|
32
|
+
finalizedAt?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
36
|
+
const intentRegex = /^cint_[A-Za-z0-9_-]{16,}$/
|
|
37
|
+
|
|
38
|
+
/** Start an isolated, bounded in-memory simulator on IPv4 loopback only. */
|
|
39
|
+
export async function startCardSimulator(
|
|
40
|
+
port = 0,
|
|
41
|
+
options: { capacity?: number; ttlMs?: number; nowMs?: () => number } = {},
|
|
42
|
+
): Promise<{ server: Server; url: string }> {
|
|
43
|
+
const capacity = options.capacity ?? 1000, ttlMs = options.ttlMs ?? 600_000, clock = options.nowMs ?? Date.now
|
|
44
|
+
if (!Number.isSafeInteger(capacity) || capacity < 1 || !Number.isSafeInteger(ttlMs) || ttlMs < 1) throw new Error('Invalid simulator limits')
|
|
45
|
+
const operations = new Map<string, { raw: Buffer; operation: SimulatorOperation }>()
|
|
46
|
+
const identities = new Map<string, SimulatorOperation>(), versions = new Map<string, SimulatorOperation>()
|
|
47
|
+
const suppliers = new Map<string, SimulatorOperation>(), charges = new Map<string, SimulatorOperation>()
|
|
48
|
+
const retryBodies = new Map<string, { raw: Buffer; expiresAt: number }>()
|
|
49
|
+
const nonces = new Map<string, number>()
|
|
50
|
+
|
|
51
|
+
const identityOf = (externalAuthId: unknown, resourceVersion: unknown) =>
|
|
52
|
+
JSON.stringify([externalAuthId, resourceVersion])
|
|
53
|
+
const versionOf = (externalAuthId: unknown, version: unknown) =>
|
|
54
|
+
JSON.stringify([externalAuthId, version])
|
|
55
|
+
const supplierOf = (supplierTxId: unknown, resourceVersion: unknown) =>
|
|
56
|
+
JSON.stringify([typeof supplierTxId === 'string' ? supplierTxId.trim() : supplierTxId, resourceVersion])
|
|
57
|
+
|
|
58
|
+
const normalizedCreateOf = (body: Record<string, unknown>) => {
|
|
59
|
+
const amount = typeof body.amount === 'string' ? body.amount.trim().match(/^(\d+)(?:\.(\d{1,6}))?$/) : null
|
|
60
|
+
const verification = body.cardholder_verification as Record<string, unknown> | undefined
|
|
61
|
+
const references = body.supplier_transaction_id !== undefined || body.client_transaction_id !== undefined
|
|
62
|
+
const detailed = body.supplier_transaction_id !== undefined || body.decision_mode === 'synchronous'
|
|
63
|
+
const trim = (value: unknown) => typeof value === 'string' ? value.trim() : null
|
|
64
|
+
return JSON.stringify({
|
|
65
|
+
card: body.external_card_id,
|
|
66
|
+
currency: body.currency,
|
|
67
|
+
amount: amount ? (BigInt(amount[1]!) * 1_000_000n + BigInt((amount[2] ?? '').padEnd(6, '0'))).toString() : body.amount,
|
|
68
|
+
...(references ? { supplier: trim(body.supplier_transaction_id), client: trim(body.client_transaction_id) } : {}),
|
|
69
|
+
...(detailed ? { merchant: body.merchant_name ?? null, mcc: body.merchant_mcc ?? null, method: verification?.method, verifiedAt: verification?.verified_at, evidence: verification?.evidence_id } : {}),
|
|
70
|
+
...(body.decision_mode === 'synchronous' ? { mode: 'synchronous', timeout: body.decision_timeout_ms ?? 2000, deadline: body.deadline_at ?? null } : {}),
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const normalizedFactOf = (externalAuthId: string, body: Record<string, unknown>) => {
|
|
75
|
+
const trim = (value: unknown) => typeof value === 'string' ? value.trim() : null
|
|
76
|
+
return JSON.stringify({
|
|
77
|
+
externalAuthId,
|
|
78
|
+
factType: body.fact_type,
|
|
79
|
+
currency: body.currency,
|
|
80
|
+
amount: body.amount,
|
|
81
|
+
predecessor: body.predecessor_version,
|
|
82
|
+
supplier: trim(body.supplier_transaction_id),
|
|
83
|
+
parent: trim(body.parent_supplier_transaction_id),
|
|
84
|
+
client: trim(body.client_transaction_id),
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function expire(now: number) {
|
|
89
|
+
for (const [nonce, until] of nonces) if (until <= now) nonces.delete(nonce)
|
|
90
|
+
for (const [key, item] of retryBodies) if (item.expiresAt <= now) retryBodies.delete(key)
|
|
91
|
+
for (const [identity, item] of identities) if (item.expiresAt <= now) {
|
|
92
|
+
identities.delete(identity); versions.delete(item.lineageVersion); charges.delete(item.chargeId)
|
|
93
|
+
if (item.supplierIdentity) suppliers.delete(item.supplierIdentity)
|
|
94
|
+
for (const key of item.keys) operations.delete(key)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const server = createServer(async (req, res) => {
|
|
99
|
+
const respond = (status: number, data: unknown, extra: Record<string, string> = {}) => {
|
|
100
|
+
res.writeHead(status, { 'content-type': 'application/json', ...extra })
|
|
101
|
+
res.end(JSON.stringify(data))
|
|
102
|
+
}
|
|
103
|
+
const error = (status: number, code: string, extra?: Record<string, string>) =>
|
|
104
|
+
respond(status, { error: code, message: 'Synthetic simulator response', request_id: 'synthetic-request' }, extra)
|
|
105
|
+
const chunks: Buffer[] = []
|
|
106
|
+
let length = 0
|
|
107
|
+
for await (const chunk of req) {
|
|
108
|
+
const part = Buffer.from(chunk)
|
|
109
|
+
length += part.length
|
|
110
|
+
if (length > 1024 * 1024) { error(413, 'invalid_request'); return }
|
|
111
|
+
chunks.push(part)
|
|
112
|
+
}
|
|
113
|
+
const bytes = Buffer.concat(chunks)
|
|
114
|
+
const time = clock()
|
|
115
|
+
expire(time)
|
|
116
|
+
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
117
|
+
const pathname = parsedUrl.pathname
|
|
118
|
+
const ts = req.headers['x-api-timestamp'], nonce = req.headers['x-api-nonce'], received = req.headers['x-api-signature']
|
|
119
|
+
const method = req.method === 'POST' || req.method === 'PUT' || req.method === 'GET' ? req.method : null
|
|
120
|
+
if (
|
|
121
|
+
!method
|
|
122
|
+
|| req.headers['x-api-key'] !== simulatorIdentity.apiKeyId
|
|
123
|
+
|| typeof ts !== 'string' || !/^\d{10}$/.test(ts)
|
|
124
|
+
|| Math.abs(Math.floor(time / 1000) - Number(ts)) > 300
|
|
125
|
+
|| typeof nonce !== 'string' || !nonce || nonces.has(nonce)
|
|
126
|
+
|| typeof received !== 'string' || !/^[0-9a-f]{64}$/.test(received)
|
|
127
|
+
) { error(401, 'authentication_failed'); return }
|
|
128
|
+
const headers = new Headers()
|
|
129
|
+
for (const [name, value] of Object.entries(req.headers)) if (typeof value === 'string') headers.set(name, value)
|
|
130
|
+
if (!verifyCardRequest({ secret: simulatorIdentity.apiKeySecret, apiKeyId: simulatorIdentity.apiKeyId, method, target: req.url ?? '', body: bytes, headers })) {
|
|
131
|
+
error(401, 'authentication_failed'); return
|
|
132
|
+
}
|
|
133
|
+
if (nonces.size >= capacity) { error(503, 'internal_error'); return }
|
|
134
|
+
nonces.set(nonce, (Number(ts) + 301) * 1000)
|
|
135
|
+
|
|
136
|
+
if (method === 'GET' && pathname === '/api/card/deliveries/dead-letters') {
|
|
137
|
+
if (bytes.length > 0) { error(400, 'invalid_request'); return }
|
|
138
|
+
const limitParam = parsedUrl.searchParams.get('limit')
|
|
139
|
+
for (const [keyName] of parsedUrl.searchParams) if (keyName !== 'limit') { error(400, 'invalid_request'); return }
|
|
140
|
+
if (parsedUrl.searchParams.getAll('limit').length > 1) { error(400, 'invalid_request'); return }
|
|
141
|
+
if (limitParam !== null && (!/^\d+$/.test(limitParam) || Number(limitParam) < 1 || Number(limitParam) > 100)) { error(400, 'invalid_request'); return }
|
|
142
|
+
respond(200, { items: [] }); return
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const validIntentToken = (value: unknown) =>
|
|
146
|
+
typeof value === 'string' && [...value].length >= 32 && [...value].length <= 8192 && /^[\x21-\x7e]+$/.test(value)
|
|
147
|
+
|
|
148
|
+
const intentCardsMatch = pathname.match(/^\/api\/card\/connect\/intents\/([^/]+)\/cards$/)
|
|
149
|
+
if (intentCardsMatch) {
|
|
150
|
+
const intentId = decodeURIComponent(intentCardsMatch[1]!)
|
|
151
|
+
if (!intentRegex.test(intentId)) { error(400, 'invalid_request'); return }
|
|
152
|
+
if (method === 'GET') {
|
|
153
|
+
const token = req.headers['x-facto-intent-token']
|
|
154
|
+
if (bytes.length > 0 || !validIntentToken(token)) { error(400, 'invalid_request'); return }
|
|
155
|
+
respond(200, { id: intentId, revision: `sha256:${'0'.repeat(64)}`, cards: [] }); return
|
|
156
|
+
}
|
|
157
|
+
if (method === 'PUT') {
|
|
158
|
+
const key = req.headers['idempotency-key']
|
|
159
|
+
if (typeof key !== 'string' || key.length < 16) { error(400, 'invalid_request'); return }
|
|
160
|
+
let body: Record<string, unknown>
|
|
161
|
+
try { body = JSON.parse(bytes.toString('utf8')) as Record<string, unknown> } catch { error(400, 'invalid_request'); return }
|
|
162
|
+
if (
|
|
163
|
+
!validIntentToken(body.intent_token)
|
|
164
|
+
|| typeof body.approval_id !== 'string' || body.approval_id.length === 0
|
|
165
|
+
|| typeof body.approval_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(body.approval_sha256)
|
|
166
|
+
|| typeof body.revision !== 'string' || !/^sha256:[a-fA-F0-9]{64}$/.test(body.revision)
|
|
167
|
+
) { error(400, 'invalid_request'); return }
|
|
168
|
+
const cards = Array.isArray(body.cards) ? body.cards : []
|
|
169
|
+
respond(200, {
|
|
170
|
+
id: intentId,
|
|
171
|
+
status: 'applied',
|
|
172
|
+
revision: `sha256:${'f'.repeat(64)}`,
|
|
173
|
+
added_binding_ids: cards.map((_, idx) => `cb_SYNTHETIC0000000${idx + 1}`),
|
|
174
|
+
removed_binding_ids: [],
|
|
175
|
+
kept_binding_ids: [],
|
|
176
|
+
})
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
error(404, 'not_found'); return
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const intentCancelMatch = pathname.match(/^\/api\/card\/connect\/intents\/([^/]+)\/cancel$/)
|
|
183
|
+
if (method === 'POST' && intentCancelMatch) {
|
|
184
|
+
const intentId = decodeURIComponent(intentCancelMatch[1]!)
|
|
185
|
+
if (!intentRegex.test(intentId)) { error(400, 'invalid_request'); return }
|
|
186
|
+
let cancelBody: Record<string, unknown>
|
|
187
|
+
try { cancelBody = JSON.parse(bytes.toString('utf8')) as Record<string, unknown> } catch { error(400, 'invalid_request'); return }
|
|
188
|
+
if (!cancelBody || typeof cancelBody !== 'object' || Array.isArray(cancelBody) || !validIntentToken(cancelBody.intent_token)) {
|
|
189
|
+
error(400, 'invalid_request'); return
|
|
190
|
+
}
|
|
191
|
+
respond(200, { id: intentId, status: 'cancelled' }); return
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const deadLetterReplayMatch = pathname.match(/^\/api\/card\/deliveries\/dead-letters\/([^/]+)\/replay$/)
|
|
195
|
+
if (method === 'POST' && deadLetterReplayMatch) {
|
|
196
|
+
const deadLetterId = decodeURIComponent(deadLetterReplayMatch[1]!)
|
|
197
|
+
if (!uuidRegex.test(deadLetterId)) { error(404, 'not_found'); return }
|
|
198
|
+
respond(202, { id: deadLetterId, status: 'accepted' }); return
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (method !== 'POST') { error(404, 'not_found'); return }
|
|
202
|
+
|
|
203
|
+
let body: Record<string, unknown>
|
|
204
|
+
try {
|
|
205
|
+
body = JSON.parse(bytes.length ? bytes.toString('utf8') : '{}') as Record<string, unknown>
|
|
206
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error()
|
|
207
|
+
} catch { error(400, 'invalid_request'); return }
|
|
208
|
+
|
|
209
|
+
if (typeof body.supplier_transaction_id === 'string') body.supplier_transaction_id = body.supplier_transaction_id.trim()
|
|
210
|
+
|
|
211
|
+
const factMatch = pathname.match(/^\/api\/card\/authorizations\/([^/]+)\/facts$/)
|
|
212
|
+
if (factMatch) {
|
|
213
|
+
const externalAuthId = decodeURIComponent(factMatch[1]!)
|
|
214
|
+
if (body.program_id !== simulatorIdentity.programId) { error(403, 'program_grant_denied'); return }
|
|
215
|
+
const key = req.headers['idempotency-key']
|
|
216
|
+
if (typeof key !== 'string' || key.length < 16) { error(400, 'invalid_request'); return }
|
|
217
|
+
const factTypes = ['authorization_updated', 'clearing', 'reversal', 'refund', 'chargeback', 'settlement']
|
|
218
|
+
if (
|
|
219
|
+
!factTypes.includes(String(body.fact_type))
|
|
220
|
+
|| typeof body.predecessor_version !== 'string' || !body.predecessor_version
|
|
221
|
+
|| body.predecessor_version === body.resource_version
|
|
222
|
+
|| typeof body.recorded_at !== 'string' || !Number.isFinite(Date.parse(body.recorded_at))
|
|
223
|
+
) { error(400, 'invalid_request'); return }
|
|
224
|
+
const raw = bytes
|
|
225
|
+
const prior = operations.get(key)
|
|
226
|
+
if (prior && !prior.raw.equals(raw)) { error(409, 'integrity_conflict'); return }
|
|
227
|
+
const identity = identityOf(externalAuthId, body.resource_version)
|
|
228
|
+
const normalized = normalizedFactOf(externalAuthId, body)
|
|
229
|
+
const existing = identities.get(identity)
|
|
230
|
+
if (existing && existing.normalized !== normalized) { error(409, 'integrity_conflict'); return }
|
|
231
|
+
if (!versions.has(versionOf(externalAuthId, body.predecessor_version))) { error(409, 'integrity_conflict'); return }
|
|
232
|
+
const version = versionOf(externalAuthId, body.resource_version), occupied = versions.get(version)
|
|
233
|
+
if (occupied && occupied.identity !== identity) { error(409, 'integrity_conflict'); return }
|
|
234
|
+
const supplier = body.supplier_transaction_id ? suppliers.get(supplierOf(body.supplier_transaction_id, body.resource_version)) : undefined
|
|
235
|
+
if (supplier && supplier.identity !== identity) { error(409, 'integrity_conflict'); return }
|
|
236
|
+
if (!prior && operations.size >= capacity) { error(503, 'internal_error'); return }
|
|
237
|
+
let operation = prior?.operation ?? existing
|
|
238
|
+
if (!operation) {
|
|
239
|
+
const operationId = randomUUID(), chargeId = `0x${'0'.repeat(32)}${operationId.replaceAll('-', '')}`
|
|
240
|
+
operation = {
|
|
241
|
+
externalAuthorizationId: externalAuthId,
|
|
242
|
+
factType: String(body.fact_type),
|
|
243
|
+
body: { ...body, external_authorization_id: externalAuthId },
|
|
244
|
+
identity,
|
|
245
|
+
normalized,
|
|
246
|
+
lineageVersion: version,
|
|
247
|
+
chargeId,
|
|
248
|
+
operationId,
|
|
249
|
+
expiresAt: time + ttlMs,
|
|
250
|
+
keys: new Set(),
|
|
251
|
+
statusReads: 0,
|
|
252
|
+
...(body.supplier_transaction_id ? { supplierIdentity: supplierOf(body.supplier_transaction_id, body.resource_version) } : {}),
|
|
253
|
+
}
|
|
254
|
+
identities.set(identity, operation); versions.set(version, operation)
|
|
255
|
+
if (operation.supplierIdentity) suppliers.set(operation.supplierIdentity, operation)
|
|
256
|
+
}
|
|
257
|
+
if (!prior) { operations.set(key, { raw, operation }); operation.keys.add(key) }
|
|
258
|
+
respond(200, { operation_id: operation.operationId, status: 'recorded' }); return
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const programRoutes = [
|
|
262
|
+
'/api/card/authorizations',
|
|
263
|
+
'/api/card/authorizations/lookup',
|
|
264
|
+
'/api/card/deliveries/reconciliations/list',
|
|
265
|
+
'/api/card/deliveries/replays',
|
|
266
|
+
]
|
|
267
|
+
if (programRoutes.includes(pathname) && body.program_id !== simulatorIdentity.programId) {
|
|
268
|
+
error(403, 'program_grant_denied'); return
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const raw = bytes, now = new Date(time).toISOString(), key = req.headers['idempotency-key']
|
|
272
|
+
switch (pathname) {
|
|
273
|
+
case '/api/card/authorizations': {
|
|
274
|
+
if (typeof key !== 'string' || key.length < 16) { error(400, 'invalid_request'); return }
|
|
275
|
+
if (
|
|
276
|
+
body.decision_mode === 'synchronous'
|
|
277
|
+
&& ((body.decision_timeout_ms !== undefined && (typeof body.decision_timeout_ms !== 'number' || !Number.isInteger(body.decision_timeout_ms) || body.decision_timeout_ms < 50 || body.decision_timeout_ms > 5000))
|
|
278
|
+
|| (body.deadline_at !== undefined && (typeof body.deadline_at !== 'string' || !Number.isFinite(Date.parse(body.deadline_at)))))
|
|
279
|
+
) { error(400, 'invalid_request'); return }
|
|
280
|
+
if (body.decision_mode !== 'synchronous' && (body.decision_timeout_ms !== undefined || body.deadline_at !== undefined)) {
|
|
281
|
+
error(400, 'invalid_request'); return
|
|
282
|
+
}
|
|
283
|
+
if (typeof body.external_authorization_id !== 'string' || !body.external_authorization_id || typeof body.external_card_id !== 'string' || !body.external_card_id) {
|
|
284
|
+
error(400, 'invalid_request'); return
|
|
285
|
+
}
|
|
286
|
+
const prior = operations.get(key)
|
|
287
|
+
if (prior && !prior.raw.equals(raw)) { error(409, 'integrity_conflict'); return }
|
|
288
|
+
const identity = identityOf(body.external_authorization_id, body.resource_version)
|
|
289
|
+
const normalized = normalizedCreateOf(body)
|
|
290
|
+
const existing = identities.get(identity)
|
|
291
|
+
if (existing && existing.normalized !== normalized) { error(409, 'integrity_conflict'); return }
|
|
292
|
+
if (body.decision_mode !== 'synchronous' && body.external_card_id === 'synthetic-rate-limited-card') {
|
|
293
|
+
respond(429, { error: { category: 'rate_limited', code: 'too_many_requests', message: 'Synthetic rate limit', request_id: 'synthetic-request', retryable: true } }, { 'retry-after': '2' }); return
|
|
294
|
+
}
|
|
295
|
+
if (body.decision_mode !== 'synchronous' && body.external_card_id === 'synthetic-bad-gateway-card') {
|
|
296
|
+
res.writeHead(502, { 'content-type': 'text/html', 'retry-after': '2' }); res.end('<html>Synthetic gateway error</html>'); return
|
|
297
|
+
}
|
|
298
|
+
if (body.decision_mode !== 'synchronous' && body.external_card_id === 'synthetic-nested-500-card') {
|
|
299
|
+
respond(500, { error: { category: 'internal', code: 'synthetic_unavailable', message: 'Synthetic failure', request_id: 'synthetic-request', retryable: false } }); return
|
|
300
|
+
}
|
|
301
|
+
if (body.decision_mode !== 'synchronous' && body.external_card_id === 'synthetic-retry-card' && !prior) {
|
|
302
|
+
const first = retryBodies.get(key)
|
|
303
|
+
if (!first) {
|
|
304
|
+
if (retryBodies.size >= capacity) { error(503, 'internal_error'); return }
|
|
305
|
+
retryBodies.set(key, { raw, expiresAt: time + ttlMs }); error(503, 'internal_error'); return
|
|
306
|
+
}
|
|
307
|
+
if (!first.raw.equals(raw)) { error(409, 'integrity_conflict'); return }
|
|
308
|
+
retryBodies.delete(key)
|
|
309
|
+
}
|
|
310
|
+
const version = versionOf(body.external_authorization_id, body.resource_version), occupied = versions.get(version)
|
|
311
|
+
if (occupied && occupied.identity !== identity) { error(409, 'integrity_conflict'); return }
|
|
312
|
+
const supplier = body.supplier_transaction_id ? suppliers.get(supplierOf(body.supplier_transaction_id, body.resource_version)) : undefined
|
|
313
|
+
if (supplier && supplier.identity !== identity) { error(409, 'integrity_conflict'); return }
|
|
314
|
+
if (!prior && operations.size >= capacity) { error(503, 'internal_error'); return }
|
|
315
|
+
let operation = prior?.operation ?? existing
|
|
316
|
+
if (!operation) {
|
|
317
|
+
const deadline = body.decision_mode === 'synchronous'
|
|
318
|
+
? Math.min(
|
|
319
|
+
time + (typeof body.decision_timeout_ms === 'number' ? body.decision_timeout_ms : 2000),
|
|
320
|
+
typeof body.deadline_at === 'string' ? Date.parse(body.deadline_at) : Infinity,
|
|
321
|
+
)
|
|
322
|
+
: undefined
|
|
323
|
+
const operationId = randomUUID(), chargeId = `0x${'0'.repeat(32)}${operationId.replaceAll('-', '')}`
|
|
324
|
+
operation = {
|
|
325
|
+
externalAuthorizationId: body.external_authorization_id,
|
|
326
|
+
factType: 'authorization_requested',
|
|
327
|
+
body,
|
|
328
|
+
identity,
|
|
329
|
+
normalized,
|
|
330
|
+
lineageVersion: version,
|
|
331
|
+
chargeId,
|
|
332
|
+
operationId,
|
|
333
|
+
deadline,
|
|
334
|
+
expiresAt: time + ttlMs,
|
|
335
|
+
keys: new Set(),
|
|
336
|
+
statusReads: 0,
|
|
337
|
+
...(deadline !== undefined ? { decision: deadline <= time ? 'self_reversed_timeout' : 'declined' } : {}),
|
|
338
|
+
...(body.supplier_transaction_id ? { supplierIdentity: supplierOf(body.supplier_transaction_id, body.resource_version) } : {}),
|
|
339
|
+
}
|
|
340
|
+
identities.set(identity, operation); versions.set(version, operation)
|
|
341
|
+
if (operation.supplierIdentity) suppliers.set(operation.supplierIdentity, operation)
|
|
342
|
+
if (body.decision_mode !== 'synchronous') charges.set(chargeId, operation)
|
|
343
|
+
}
|
|
344
|
+
if (!prior) { operations.set(key, { raw, operation }); operation.keys.add(key) }
|
|
345
|
+
if (body.decision_mode === 'synchronous') {
|
|
346
|
+
const expired = operation.deadline !== undefined && operation.deadline <= time
|
|
347
|
+
respond(expired ? 408 : 422, {
|
|
348
|
+
...(expired ? {} : { decision: 'declined', decided_at: now }),
|
|
349
|
+
error: expired ? 'decision_deadline_exceeded' : 'sync_approval_admission_closed',
|
|
350
|
+
message: 'Synthetic simulator decision',
|
|
351
|
+
request_id: 'synthetic-request',
|
|
352
|
+
decision_id: operation.operationId,
|
|
353
|
+
deadline_at: new Date(operation.deadline!).toISOString(),
|
|
354
|
+
})
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
if (body.external_card_id === 'synthetic-declined-card') { error(402, 'spending_limit_exceeded'); return }
|
|
358
|
+
respond(200, { charge_id: operation.chargeId, status: 'processing' }); return
|
|
359
|
+
}
|
|
360
|
+
case '/api/card/authorizations/lookup': {
|
|
361
|
+
const criteria = body.criteria as Record<string, unknown> | undefined
|
|
362
|
+
const found = criteria?.by === 'idempotency_key' && criteria.original_credential_key_id === simulatorIdentity.apiKeyId && typeof criteria.idempotency_key === 'string'
|
|
363
|
+
? operations.get(criteria.idempotency_key)?.operation
|
|
364
|
+
: criteria?.by === 'charge_id' && typeof criteria.charge_id === 'string'
|
|
365
|
+
? charges.get(criteria.charge_id)
|
|
366
|
+
: criteria?.by === 'external_authorization_id'
|
|
367
|
+
? identities.get(identityOf(criteria.external_authorization_id, criteria.resource_version))
|
|
368
|
+
: criteria?.by === 'supplier_transaction_id'
|
|
369
|
+
? suppliers.get(supplierOf(criteria.supplier_transaction_id, criteria.resource_version))
|
|
370
|
+
: undefined
|
|
371
|
+
if (
|
|
372
|
+
!found
|
|
373
|
+
|| ((criteria?.by === 'external_authorization_id' || criteria?.by === 'supplier_transaction_id')
|
|
374
|
+
&& (criteria.mapping_revision !== found.body.mapping_revision
|
|
375
|
+
|| (criteria.fact_type !== undefined && criteria.fact_type !== found.factType)))
|
|
376
|
+
) {
|
|
377
|
+
respond(200, { observed_at: now, resolution: 'not_observed' }); return
|
|
378
|
+
}
|
|
379
|
+
const item = found.body
|
|
380
|
+
const reads = found.statusReads++
|
|
381
|
+
if (['synthetic-terminal-card', 'synthetic-failed-card'].includes(String(item.external_card_id)) && found.factType === 'authorization_requested' && reads > 0) {
|
|
382
|
+
const finalized = found.finalizedAt ?? now
|
|
383
|
+
found.finalizedAt = finalized
|
|
384
|
+
const facts = ['facto_admission', 'durable_commit', 'provider_authorization', 'chain_finality', 'provider_settlement'].map((kind) =>
|
|
385
|
+
kind.startsWith('provider_')
|
|
386
|
+
? { kind, state: 'unobserved', source_system: 'provider', recorded_at: finalized }
|
|
387
|
+
: { kind, state: 'confirmed', source_system: kind === 'chain_finality' ? 'chain' : 'facto', recorded_at: finalized, observed_at: finalized },
|
|
388
|
+
)
|
|
389
|
+
const identity = {
|
|
390
|
+
resource_version: item.resource_version,
|
|
391
|
+
mapping_revision: item.mapping_revision,
|
|
392
|
+
external_authorization_id: found.externalAuthorizationId,
|
|
393
|
+
charge_id: found.chargeId,
|
|
394
|
+
}
|
|
395
|
+
const failed = item.external_card_id === 'synthetic-failed-card'
|
|
396
|
+
const final_receipt = {
|
|
397
|
+
receipt_event_id: found.operationId,
|
|
398
|
+
charge_id: found.chargeId,
|
|
399
|
+
authorization_ref: found.externalAuthorizationId,
|
|
400
|
+
mapping_revision: item.mapping_revision,
|
|
401
|
+
operation_type: found.factType,
|
|
402
|
+
resource_version: item.resource_version,
|
|
403
|
+
execution_outcome: failed ? 'failed' : 'succeeded',
|
|
404
|
+
terminal_action: failed ? 'cancelReservation' : 'releaseFor',
|
|
405
|
+
finalized_at: finalized,
|
|
406
|
+
facts_at_finality: facts,
|
|
407
|
+
}
|
|
408
|
+
respond(200, {
|
|
409
|
+
observed_at: now,
|
|
410
|
+
resolution: 'resolved',
|
|
411
|
+
authorization: {
|
|
412
|
+
...identity,
|
|
413
|
+
operation_type: found.factType,
|
|
414
|
+
origin_connection_id: simulatorIdentity.connectionId,
|
|
415
|
+
processing_status: failed ? 'failed' : 'succeeded',
|
|
416
|
+
facts,
|
|
417
|
+
revision: 2,
|
|
418
|
+
final_receipt,
|
|
419
|
+
...(item.supplier_transaction_id ? { supplier_transaction_id: item.supplier_transaction_id } : {}),
|
|
420
|
+
},
|
|
421
|
+
})
|
|
422
|
+
return
|
|
423
|
+
}
|
|
424
|
+
const original = found.factType === 'authorization_requested'
|
|
425
|
+
const declined = found.decision || item.external_card_id === 'synthetic-declined-card'
|
|
426
|
+
const facts = ['facto_admission', 'durable_commit', 'provider_authorization', 'chain_finality', 'provider_settlement'].map((kind) => {
|
|
427
|
+
const confirmed = kind === 'durable_commit' || (kind === 'facto_admission' && original && !declined)
|
|
428
|
+
return {
|
|
429
|
+
kind,
|
|
430
|
+
state: confirmed ? 'confirmed' : 'unobserved',
|
|
431
|
+
source_system: kind.startsWith('provider_') ? 'provider' : kind === 'chain_finality' ? 'chain' : 'facto',
|
|
432
|
+
recorded_at: now,
|
|
433
|
+
...(confirmed ? { observed_at: now } : {}),
|
|
434
|
+
}
|
|
435
|
+
})
|
|
436
|
+
respond(200, {
|
|
437
|
+
observed_at: now,
|
|
438
|
+
resolution: declined ? 'resolved' : original ? 'pending' : 'unknown',
|
|
439
|
+
authorization: {
|
|
440
|
+
origin_connection_id: simulatorIdentity.connectionId,
|
|
441
|
+
processing_status: declined ? 'failed' : original ? 'processing' : 'indeterminate',
|
|
442
|
+
facts,
|
|
443
|
+
revision: 1,
|
|
444
|
+
operation_type: found.factType,
|
|
445
|
+
resource_version: item.resource_version,
|
|
446
|
+
mapping_revision: item.mapping_revision,
|
|
447
|
+
external_authorization_id: found.externalAuthorizationId,
|
|
448
|
+
...(original && !found.decision ? { charge_id: found.chargeId } : {}),
|
|
449
|
+
...(found.decision
|
|
450
|
+
? { decision: found.decision, decline_reason_code: found.decision === 'declined' ? 'sync_approval_admission_closed' : 'decision_deadline_exceeded' }
|
|
451
|
+
: item.external_card_id === 'synthetic-declined-card'
|
|
452
|
+
? { decline_reason_code: 'spending_limit_exceeded' }
|
|
453
|
+
: {}),
|
|
454
|
+
...(item.supplier_transaction_id ? { supplier_transaction_id: item.supplier_transaction_id } : {}),
|
|
455
|
+
},
|
|
456
|
+
})
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
case '/api/card/deliveries/reconciliations/list': {
|
|
460
|
+
const scenarioName = simulatorDeliveryKinds.find((name) => simulatorDeliveryConfig(name).selectionId === body.selection_id)
|
|
461
|
+
if (scenarioName && body.target_revision === simulatorTarget) {
|
|
462
|
+
const scenario = simulatorDeliveryScenario(scenarioName)
|
|
463
|
+
const unique = new Map<string, { event_id: string; origin_connection_id: string; connection_sequence: number | null; event_sha256: string; target_revision: string; delivery_state: string }>()
|
|
464
|
+
for (const delivery of scenario.deliveries) {
|
|
465
|
+
const event = JSON.parse(new TextDecoder().decode(delivery.rawBody)) as { event_id: string; connection_sequence: number | null }
|
|
466
|
+
unique.set(event.event_id, {
|
|
467
|
+
event_id: event.event_id,
|
|
468
|
+
origin_connection_id: scenario.config.connectionId,
|
|
469
|
+
connection_sequence: event.connection_sequence,
|
|
470
|
+
event_sha256: createHash('sha256').update(delivery.rawBody).digest('hex'),
|
|
471
|
+
target_revision: scenario.config.targetRevision,
|
|
472
|
+
delivery_state: 'accepted',
|
|
473
|
+
})
|
|
474
|
+
}
|
|
475
|
+
const all = [...unique.values()].sort((a, b) => (a.connection_sequence ?? 0) - (b.connection_sequence ?? 0))
|
|
476
|
+
const offset = typeof body.cursor === 'string' ? Number(body.cursor.slice('synthetic-cursor-'.length)) : 0
|
|
477
|
+
const pageSize = typeof body.page_size === 'number' ? body.page_size : 100
|
|
478
|
+
const items = all.slice(offset, offset + pageSize)
|
|
479
|
+
const complete = offset + items.length >= all.length
|
|
480
|
+
respond(200, {
|
|
481
|
+
snapshot_token: 'synthetic-snapshot-token',
|
|
482
|
+
snapshot_at: now,
|
|
483
|
+
to_at: typeof body.to_at === 'string' ? body.to_at : now,
|
|
484
|
+
items,
|
|
485
|
+
next_cursor: complete ? null : `synthetic-cursor-${offset + items.length}`,
|
|
486
|
+
complete,
|
|
487
|
+
})
|
|
488
|
+
return
|
|
489
|
+
}
|
|
490
|
+
const fixture = deliveryInboxVectors.duplicate.deliveries[0]
|
|
491
|
+
const eventId = fixture.headers.find(([name]) => name === 'facto-event-id')?.[1]
|
|
492
|
+
const items = body.selection_id === simulatorSelection && body.target_revision === simulatorTarget
|
|
493
|
+
? [{
|
|
494
|
+
event_id: eventId,
|
|
495
|
+
origin_connection_id: fixture.expectedScope.connectionId,
|
|
496
|
+
connection_sequence: 1,
|
|
497
|
+
event_sha256: createHash('sha256').update(fixture.rawBody).digest('hex'),
|
|
498
|
+
target_revision: fixture.expectedScope.targetRevision,
|
|
499
|
+
delivery_state: 'accepted',
|
|
500
|
+
}]
|
|
501
|
+
: []
|
|
502
|
+
respond(200, {
|
|
503
|
+
snapshot_token: 'synthetic-snapshot-token',
|
|
504
|
+
snapshot_at: now,
|
|
505
|
+
to_at: typeof body.to_at === 'string' ? body.to_at : now,
|
|
506
|
+
items,
|
|
507
|
+
next_cursor: null,
|
|
508
|
+
complete: true,
|
|
509
|
+
})
|
|
510
|
+
return
|
|
511
|
+
}
|
|
512
|
+
case '/api/card/deliveries/replays':
|
|
513
|
+
if (typeof key !== 'string' || key.length < 16) { error(400, 'invalid_request'); return }
|
|
514
|
+
respond(202, { replay_id: randomUUID(), selection_id: body.selection_id, target_revision: simulatorTarget, status: 'accepted' }); return
|
|
515
|
+
case '/api/card/bindings/lookup':
|
|
516
|
+
respond(200, { binding: null }); return
|
|
517
|
+
case '/api/card/events':
|
|
518
|
+
respond(200, { delivery_id: body.delivery_id, disposition: 'applied', effect: 'none' }); return
|
|
519
|
+
default:
|
|
520
|
+
error(404, 'not_found')
|
|
521
|
+
}
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
await new Promise<void>((resolve, reject) => {
|
|
525
|
+
server.once('error', reject)
|
|
526
|
+
server.listen(port, '127.0.0.1', () => { server.off('error', reject); resolve() })
|
|
527
|
+
})
|
|
528
|
+
const address = server.address()
|
|
529
|
+
if (!address || typeof address === 'string') throw new Error('Simulator listener unavailable')
|
|
530
|
+
return { server, url: `http://127.0.0.1:${address.port}` }
|
|
531
|
+
}
|