@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,235 @@
|
|
|
1
|
+
# Local simulator
|
|
2
|
+
|
|
3
|
+
This page gives the complete synthetic configuration and trigger values needed to write your own local client and receiver. None of these values are real credentials or authorize a Facto environment. Run `facto-card simulator-config` to print the same values without starting a server; `facto-card simulator` also prints them after listening.
|
|
4
|
+
|
|
5
|
+
## Request client configuration
|
|
6
|
+
|
|
7
|
+
| Field | Synthetic value | Use |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| `environment` | `dev` | SDK client scope. |
|
|
10
|
+
| `apiBaseUrl` | `http://127.0.0.1:8787` | Loopback server; change the port only if you started another port. |
|
|
11
|
+
| `connectionId` | `pconn_SYNTHETIC00000001` | SDK program scope for ordinary authorization exercises. |
|
|
12
|
+
| `programId` | `synthetic-program` | SDK adds this reference to program requests. |
|
|
13
|
+
| `apiKeyId` | `synthetic-key` | Request-signing key identifier. |
|
|
14
|
+
| `apiKeySecret` | `SYNTHETIC-TEST-KEY-NOT-A-SECRET` | Request HMAC secret as a UTF-8 string; never use outside the simulator. |
|
|
15
|
+
| `external_card_id` | `synthetic-card` | A normal synthetic authorization. |
|
|
16
|
+
| `external_card_id` | `synthetic-terminal-card` | An example authorization whose first status query is pending and later queries are terminal synthetic success. |
|
|
17
|
+
| `external_card_id` | `synthetic-failed-card` | A synthetic authorization whose first status query is pending and later queries show a failed terminal receipt. |
|
|
18
|
+
| Target revision | `00000000-0000-4000-8000-000000000001` | Reconciliation target. |
|
|
19
|
+
| Default selection | `00000000-0000-4000-8000-000000000002` | Default reconciliation and history replay exercise. |
|
|
20
|
+
|
|
21
|
+
## Delivery verification configuration
|
|
22
|
+
|
|
23
|
+
The command prints `delivery_verification_config` before sending. Each scenario has its own trusted connection scope and key ID; all are synthetic. The secret is **UTF-8 text**, so encode `synthetic-delivery-test-key` with `TextEncoder`, not hexadecimal decoding. The hexadecimal derived key in the worked example in [deliveries](deliveries.md) is a separate test fixture.
|
|
24
|
+
|
|
25
|
+
| Scenario | `connectionId` | `keyId` | `selectionId` |
|
|
26
|
+
| --- | --- | --- | --- |
|
|
27
|
+
| `duplicate` | `pconn_SYNTHETIC00000001` | `synthetic-delivery-duplicate` | `00000000-0000-4000-8000-000000000101` |
|
|
28
|
+
| `outOfOrder` | `pconn_SYNTHETIC00000002` | `synthetic-delivery-outOfOrder` | `00000000-0000-4000-8000-000000000102` |
|
|
29
|
+
| `gap` | `pconn_SYNTHETIC00000003` | `synthetic-delivery-gap` | `00000000-0000-4000-8000-000000000103` |
|
|
30
|
+
| `nullableCard` | `pconn_SYNTHETIC00000004` | `synthetic-delivery-nullableCard` | `00000000-0000-4000-8000-000000000104` |
|
|
31
|
+
| `unsequenced` | `pconn_SYNTHETIC00000005` | `synthetic-delivery-unsequenced` | `00000000-0000-4000-8000-000000000105` |
|
|
32
|
+
|
|
33
|
+
Every entry uses `environment: dev`, `programId: cprog_SYNTHETIC00000001`, `targetRevision: 00000000-0000-4000-8000-000000000001`, `signerKeyVersion: 1`, `notBefore: 2020-01-01T00:00:00Z`, `expiresAt: 2099-01-01T00:00:00Z`, `status: active`, and `eventKinds: [card.binding.linked]`. A scenario's `expectedScope` uses its connection ID and these common environment, program and target values. Use the exact key ID to choose the corresponding trusted entry.
|
|
34
|
+
|
|
35
|
+
> **Never load these synthetic entries into a receiver that accepts real Facto traffic.** Their keys are published in this guide and valid until 2099, and they use the environment name `dev`, so anyone could sign a delivery that such a receiver would accept. Keep them in local test configuration only, separate from the registry you build from keys Facto registers with you.
|
|
36
|
+
|
|
37
|
+
For multiple connections, the unverified `facto-signature-key-id` header may select a candidate from your trusted configuration solely to choose the key and expected scope for verification. Do not make any other decision based on that header; reject if verification fails. The verifier accepts a registry with multiple entries but requires exactly one entry matching the key ID; duplicate matching IDs are rejected.
|
|
38
|
+
|
|
39
|
+
This tested multi-connection receiver demonstrates the selection and verification. Its in-memory store and credentials are synthetic and test-only. The SDK never reads the HTTP request: before verification the receiver itself caps the accumulated body at 1 MiB, answering 413 when it is exceeded (including a larger declared `Content-Length`), and sets `requestTimeout` and `headersTimeout` so that a slow sender cannot hold a connection. These limits belong to your HTTP layer; choose values that fit your infrastructure. Facto does not currently publish a maximum delivery body size; the synthetic events are a few kilobytes. Confirm the limit to configure with dev@facto.to.
|
|
40
|
+
|
|
41
|
+
<!-- example:local-receiver -->
|
|
42
|
+
```typescript
|
|
43
|
+
import { createServer, type ServerResponse } from 'node:http'
|
|
44
|
+
import { pathToFileURL } from 'node:url'
|
|
45
|
+
import { receiveEventDelivery, verifyEventDelivery, type DeliverySigningKey } from '@facto-to/card'
|
|
46
|
+
import { MemoryDeliveryInboxStore } from '@facto-to/card/testing'
|
|
47
|
+
|
|
48
|
+
// Synthetic local values only. Replace this testing store with durable storage in production.
|
|
49
|
+
export function startLocalReceiver(port = 8788) {
|
|
50
|
+
const names = ['duplicate', 'outOfOrder', 'gap', 'nullableCard', 'unsequenced', 'authorizationOutOfOrder', 'authorizationRedelivery', 'refundAwaitingChargeFinal', 'refundAwaitingFunds', 'refundPayable', 'refundPaid', 'refundFailed', 'refundNotPayable', 'chargeFailed'] as const
|
|
51
|
+
const store = new MemoryDeliveryInboxStore()
|
|
52
|
+
const processed: string[] = []
|
|
53
|
+
const sequences: (number | null)[] = []
|
|
54
|
+
const configs = names.map((name, index) => ({
|
|
55
|
+
name,
|
|
56
|
+
selectionId: `00000000-0000-4000-8000-${String(101 + index).padStart(12, '0')}`,
|
|
57
|
+
connectionId: `pconn_SYNTHETIC0000000${index + 1}`,
|
|
58
|
+
programId: 'cprog_SYNTHETIC00000001',
|
|
59
|
+
environment: 'dev' as const,
|
|
60
|
+
targetRevision: '00000000-0000-4000-8000-000000000001',
|
|
61
|
+
keyId: `synthetic-delivery-${name}`,
|
|
62
|
+
signerKeyVersion: 1,
|
|
63
|
+
notBefore: '2020-01-01T00:00:00Z',
|
|
64
|
+
expiresAt: '2099-01-01T00:00:00Z',
|
|
65
|
+
status: 'active' as const,
|
|
66
|
+
eventKinds: [index < 5 ? 'card.binding.linked' : 'card.authorization.updated'],
|
|
67
|
+
secret: new TextEncoder().encode('synthetic-delivery-test-key'),
|
|
68
|
+
}))
|
|
69
|
+
// The SDK never reads the HTTP request. Bound body size and request time here, before verification.
|
|
70
|
+
const maxBodyBytes = 1_048_576
|
|
71
|
+
const tooLarge = (response: ServerResponse) => { response.writeHead(413, { connection: 'close' }); response.end('body_too_large') }
|
|
72
|
+
const server = createServer(async (request, response) => {
|
|
73
|
+
try {
|
|
74
|
+
if (Number(request.headers['content-length']) > maxBodyBytes) { tooLarge(response); return }
|
|
75
|
+
const chunks: Buffer[] = []
|
|
76
|
+
let size = 0
|
|
77
|
+
for await (const chunk of request) {
|
|
78
|
+
size += chunk.length
|
|
79
|
+
if (size > maxBodyBytes) { tooLarge(response); return }
|
|
80
|
+
chunks.push(Buffer.from(chunk))
|
|
81
|
+
}
|
|
82
|
+
const headers: [string, string][] = []
|
|
83
|
+
for (let i = 0; i < request.rawHeaders.length; i += 2) headers.push([request.rawHeaders[i]!, request.rawHeaders[i + 1]!])
|
|
84
|
+
const keyId = headers.find(([name]) => name.toLowerCase() === 'facto-signature-key-id')?.[1]
|
|
85
|
+
const config = configs.find((entry) => entry.keyId === keyId)
|
|
86
|
+
if (!config) { response.writeHead(401); response.end(); return }
|
|
87
|
+
const key: DeliverySigningKey = config
|
|
88
|
+
const scope = { connectionId: config.connectionId, programId: config.programId, environment: config.environment, targetRevision: config.targetRevision }
|
|
89
|
+
const verified = verifyEventDelivery({ rawBody: Buffer.concat(chunks), headers, registry: [key], expectedScope: scope })
|
|
90
|
+
if (!verified.verified) { response.writeHead(401); response.end('verification_failed'); return }
|
|
91
|
+
const result = await receiveEventDelivery(verified, {
|
|
92
|
+
store,
|
|
93
|
+
handle: async (event, _transaction, metadata) => {
|
|
94
|
+
if (event.type === 'unknown') throw new Error('unknown_event')
|
|
95
|
+
processed.push(event.event.event_id)
|
|
96
|
+
sequences.push(metadata.connectionSequence)
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
// Both processed and already-confirmed matching duplicates acknowledge.
|
|
100
|
+
response.writeHead(200); response.end(result.status)
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error instanceof Error && error.message === 'event_id_conflict') { response.writeHead(409); response.end('delivery_conflict') }
|
|
103
|
+
else { response.writeHead(503); response.end('receiver_unavailable') }
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
server.requestTimeout = 15_000
|
|
107
|
+
server.headersTimeout = 10_000
|
|
108
|
+
server.listen(port, '127.0.0.1', () => console.log('receiver_listening'))
|
|
109
|
+
return { server, processed, sequences }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) startLocalReceiver()
|
|
113
|
+
```
|
|
114
|
+
<!-- /example:local-receiver -->
|
|
115
|
+
|
|
116
|
+
To run this receiver from the quickstart directory, save it as `local-receiver.ts` and compile it as an ES module. TypeScript and the Node.js type definitions are ordinary development tools from your usual registry; the SDK itself is installed from npm as shown in the quickstart:
|
|
117
|
+
|
|
118
|
+
```sh
|
|
119
|
+
npm pkg set type=module
|
|
120
|
+
npm install --save-dev typescript @types/node
|
|
121
|
+
printf '%s\n' '{ "compilerOptions": { "target": "es2022", "module": "nodenext", "moduleResolution": "nodenext", "strict": true, "outDir": "out", "types": ["node"] }, "files": ["local-receiver.ts"] }' > tsconfig.json
|
|
122
|
+
./node_modules/.bin/tsc -p tsconfig.json
|
|
123
|
+
node out/local-receiver.js > local-receiver.log 2>&1 & echo $! > local-receiver.pid
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Expected: `tsc` exits without output and `local-receiver.log` contains `receiver_listening`. Stop the minimal quickstart receiver first if it is still using port 8788. Then `./node_modules/.bin/facto-card deliveries http://127.0.0.1:8788/events` reports `vector_passed` for all shipped scenarios, with every delivery verified and passed through the inbox. Stop it with `kill "$(cat local-receiver.pid)"`.
|
|
127
|
+
|
|
128
|
+
## Trigger table
|
|
129
|
+
|
|
130
|
+
| Request | Simulator response | Tested example or vector |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `synthetic-card`, original asynchronous authorization | 200 with `processing` | `first-request` example; `authorization` vector |
|
|
133
|
+
| Same key and body | Same recorded authorization | `authorization_replay` |
|
|
134
|
+
| Same key with different bytes | 409 `integrity_conflict` | `byte_integrity_conflict` |
|
|
135
|
+
| `synthetic-declined-card` | Flat HTTP 402 `spending_limit_exceeded`; the SDK throws `FACTO_ENGINE_REQUEST_FAILED` with `retryable: false` | `simulator-triggers` example; `explicit_402` |
|
|
136
|
+
| `synthetic-retry-card` | First request for a key: 503; same key and body: 200 | `simulator-triggers`; `retry_503` |
|
|
137
|
+
| `synthetic-rate-limited-card` | Nested 429 `too_many_requests`, `Retry-After: 2` | `simulator-triggers`; `retry_after_429` |
|
|
138
|
+
| `synthetic-bad-gateway-card` | 502 non-JSON gateway response, `Retry-After: 2` | `simulator-triggers`; `invalid_502` |
|
|
139
|
+
| `synthetic-nested-500-card` | Nested 500 with Engine `retryable: false`; SDK `retryable: true` | `nested_500_hint_false` |
|
|
140
|
+
| Synchronous request before its deadline | 422 `sync_approval_admission_closed` | `simulator-triggers`; `sync_closed` |
|
|
141
|
+
| Synchronous request already past its effective deadline | 408 `decision_deadline_exceeded` | `simulator-triggers`; `sync_expired` |
|
|
142
|
+
| Clearing or another supported fact with an existing distinct predecessor | 200 `{operation_id, status: "recorded"}` | `simulator-triggers`; `clearing_fact` and other fact vectors |
|
|
143
|
+
| Fact without a predecessor | SDK rejects locally with `FACTO_CONFIG_INVALID`; a signed raw request is rejected with HTTP 400 | `simulator-triggers`; `fact_missing_predecessor` |
|
|
144
|
+
| Fact with unknown predecessor or reused version | 409 `integrity_conflict` | `simulator-triggers`; `fact_version_conflict` |
|
|
145
|
+
| Invalid signature, stale timestamp, or reused nonce | 401 `authentication_failed` | `bad_signature`, `expired_timestamp`, `nonce_replay` |
|
|
146
|
+
|
|
147
|
+
The `status_explicit_402` vector covers this simulator's recorded decline only. A live 402 response does not guarantee that the authorization appears as a resolved decline in a later lookup.
|
|
148
|
+
|
|
149
|
+
Each example uses a new synthetic authorization and stable per-operation keys. The following tested example exercises the error and fact triggers. It returns the individual results; call `runSimulatorTriggers()` after starting the simulator.
|
|
150
|
+
|
|
151
|
+
<!-- example:simulator-triggers -->
|
|
152
|
+
```typescript
|
|
153
|
+
import { randomUUID } from 'node:crypto'
|
|
154
|
+
import { CardError, createCardClient, type AuthorizationFactInput } from '@facto-to/card'
|
|
155
|
+
|
|
156
|
+
// Synthetic values below are only for the loopback simulator.
|
|
157
|
+
export async function runSimulatorTriggers(apiBaseUrl = 'http://127.0.0.1:8787') {
|
|
158
|
+
const card = createCardClient({
|
|
159
|
+
environment: 'dev',
|
|
160
|
+
apiBaseUrl,
|
|
161
|
+
connectionId: 'pconn_SYNTHETIC00000001',
|
|
162
|
+
programId: 'synthetic-program',
|
|
163
|
+
apiKeyId: 'synthetic-key',
|
|
164
|
+
apiKeySecret: { encoding: 'utf8', value: 'SYNTHETIC-TEST-KEY-NOT-A-SECRET' },
|
|
165
|
+
})
|
|
166
|
+
const id = randomUUID()
|
|
167
|
+
const original = {
|
|
168
|
+
external_card_id: 'synthetic-card',
|
|
169
|
+
external_authorization_id: `trigger-${id}`,
|
|
170
|
+
amount: '10.00',
|
|
171
|
+
currency: 'USD' as const,
|
|
172
|
+
resource_version: 'authorization-v1',
|
|
173
|
+
mapping_revision: 'mapping-v1',
|
|
174
|
+
cardholder_verification: { method: 'provider_attested' as const, verified_at: '2026-01-01T00:00:00Z', evidence_id: 'synthetic-evidence' },
|
|
175
|
+
}
|
|
176
|
+
await card.authorizations.create(original, { idempotencyKey: `initial-${id}` })
|
|
177
|
+
const separate = (suffix: string) => ({ ...original, external_authorization_id: `${original.external_authorization_id}-${suffix}` })
|
|
178
|
+
const attempt = async (externalCardId: string, key: string) => {
|
|
179
|
+
try { return await card.authorizations.create({ ...separate(externalCardId), external_card_id: externalCardId }, { idempotencyKey: key }) }
|
|
180
|
+
catch (error) { if (!(error instanceof CardError)) throw error; return error }
|
|
181
|
+
}
|
|
182
|
+
const refused = await attempt('synthetic-declined-card', `declined-${id}`)
|
|
183
|
+
const retryKey = `retry-${id}`
|
|
184
|
+
const unavailable = await attempt('synthetic-retry-card', retryKey)
|
|
185
|
+
const retried = await attempt('synthetic-retry-card', retryKey)
|
|
186
|
+
const throttled = await attempt('synthetic-rate-limited-card', `throttled-${id}`)
|
|
187
|
+
const gateway = await attempt('synthetic-bad-gateway-card', `gateway-${id}`)
|
|
188
|
+
const closed = await card.authorizations.create({ ...separate('sync'), decision_mode: 'synchronous' }, { idempotencyKey: `sync-${id}` })
|
|
189
|
+
const expired = await card.authorizations.create({ ...separate('expired'), decision_mode: 'synchronous', deadline_at: '2020-01-01T00:00:00Z' }, { idempotencyKey: `expired-${id}` })
|
|
190
|
+
const factBase = {
|
|
191
|
+
amount: original.amount,
|
|
192
|
+
currency: original.currency,
|
|
193
|
+
mapping_revision: original.mapping_revision,
|
|
194
|
+
recorded_at: '2026-01-01T01:00:00Z',
|
|
195
|
+
}
|
|
196
|
+
const clearing = await card.authorizations.recordFact(original.external_authorization_id, {
|
|
197
|
+
...factBase,
|
|
198
|
+
fact_type: 'clearing',
|
|
199
|
+
resource_version: 'clearing-v2',
|
|
200
|
+
predecessor_version: 'authorization-v1',
|
|
201
|
+
}, { idempotencyKey: `clearing-${id}` })
|
|
202
|
+
let missingPredecessor: unknown
|
|
203
|
+
try {
|
|
204
|
+
await card.authorizations.recordFact(original.external_authorization_id, {
|
|
205
|
+
...factBase,
|
|
206
|
+
fact_type: 'refund',
|
|
207
|
+
resource_version: 'refund-v3',
|
|
208
|
+
} as AuthorizationFactInput, { idempotencyKey: `missing-${id}` })
|
|
209
|
+
} catch (error) { missingPredecessor = error }
|
|
210
|
+
let versionConflict: unknown
|
|
211
|
+
try {
|
|
212
|
+
await card.authorizations.recordFact(original.external_authorization_id, {
|
|
213
|
+
...factBase,
|
|
214
|
+
fact_type: 'reversal',
|
|
215
|
+
resource_version: 'authorization-v1',
|
|
216
|
+
predecessor_version: 'clearing-v2',
|
|
217
|
+
}, { idempotencyKey: `conflict-${id}` })
|
|
218
|
+
} catch (error) { versionConflict = error }
|
|
219
|
+
return { refused, unavailable, retried, throttled, gateway, closed, expired, clearing, missingPredecessor, versionConflict }
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
<!-- /example:simulator-triggers -->
|
|
223
|
+
|
|
224
|
+
## Supported operations and limits
|
|
225
|
+
|
|
226
|
+
The simulator supports original authorization dispatch and status lookup, synchronous closure and deadline responses, the six fact kinds, delivery reconciliation and historical replay acceptance, and synthetic dead-letter and lifecycle responses. It validates request HMAC, clock window and nonce replay. Reconciliation returns metadata only. The `replay` CLI command first submits a synthetic history request, then separately models later redelivery to the callback over HTTP with the same event body and ID, a fresh timestamp and signature, and a new attempt number. A durable receiver should deduplicate an already confirmed event. This local orchestration is not an Engine delivery guarantee.
|
|
227
|
+
|
|
228
|
+
Additional synthetic delivery scenarios cover out-of-order authorization progress,
|
|
229
|
+
same-revision redelivery, each refund-case status and charge failure. These
|
|
230
|
+
exercise local handling only: no provider event, chain verification or funds
|
|
231
|
+
movement is implied.
|
|
232
|
+
|
|
233
|
+
The simulator does not connect to Facto or a card network, verify a real provider lifecycle assertion, move funds, emulate all Engine validation or establish production readiness. Its credentials, grants, responses, terminal outcome and histories are synthetic. All authorization, nonce and retry state is in memory and is lost whenever the simulator process stops or restarts.
|
|
234
|
+
|
|
235
|
+
The default in-memory limit is 1,000 entries per bounded collection (request keys, pending retry bodies, and nonces); each request body is limited to 1 MiB. Authorization and pending-retry records expire ten minutes after creation and are removed on a later request. Nonces remain until their timestamp can no longer pass the five-minute clock window. At capacity the simulator fails closed with HTTP 503 `internal_error` instead of evicting live state. Once an operation expires, its status is no longer observed. These are local simulation limits, not Engine retention rules.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Versioning and distribution
|
|
2
|
+
|
|
3
|
+
Pin a public beta version and handle compatible additions safely.
|
|
4
|
+
|
|
5
|
+
- **Distribution:** This guide accompanies `@facto-to/card@0.0.1-beta.2`. Install the exact version from npm when available, or use a digest-verified retained tarball for pre-release verification. Source documentation changes neither alter previously published bytes nor publish another version.
|
|
6
|
+
- **Pinning:** Retain the exact package version and integrity digest with your records.
|
|
7
|
+
- **Additive fields:** The SDK validates required response fields and constraints while tolerating additive fields. Returned objects can contain fields not declared by the SDK's types. Retain authenticated originals when needed for auditing.
|
|
8
|
+
- **Open vocabularies:** Card `status`, association `status`, reconciliation `delivery_state`, and nested error `category` and `code` may contain values not listed in this version. The SDK preserves them unchanged and types nested error codes as plain strings. Only take enabling actions for recognized values; include a safe `default` in exhaustive switches.
|
|
9
|
+
- **Closed authorization outcomes:** Unknown `resolution`, `processing_status`, `decision`, fact `kind` or `state`, and terminal receipt values make the SDK reject the response as invalid. Do not guess; follow the unknown-outcome recovery guidance in [errors](errors.md).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var we=Object.defineProperty;var En=Object.getOwnPropertyDescriptor;var Sn=Object.getOwnPropertyNames;var Tn=Object.prototype.hasOwnProperty;var xn=(e,n)=>{for(var t in n)we(e,t,{get:n[t],enumerable:!0})},kn=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Sn(n))!Tn.call(e,i)&&i!==t&&we(e,i,{get:()=>n[i],enumerable:!(r=En(n,i))||r.enumerable});return e};var On=e=>kn(we({},"__esModule",{value:!0}),e);var pr={};xn(pr,{CARD_BINDING_ASSERTION_TYP:()=>xe,CARD_EVENT_KINDS:()=>Le,CARD_INTENT_JWKS_PATH:()=>ve,CARD_REDELIVERY_REASONS:()=>Be,CardError:()=>w,FactoConnectServerError:()=>w,FactoIntentTokenError:()=>m,createCardClient:()=>dn,createDeliveryVerifier:()=>hn,decodeDeliveryEvent:()=>Ie,deriveAuthorizationIdempotencyKey:()=>Cn,getBusinessPayloadDigest:()=>bn,isCardErrorEnvelope:()=>de,isCardNestedErrorEnvelope:()=>ce,pollAuthorization:()=>An,receiveEventDelivery:()=>vn,signBindingAssertion:()=>le,signCardRequest:()=>_e,verifyCardIntentToken:()=>ln,verifyEventDelivery:()=>qe,withServerRetry:()=>Me});module.exports=On(pr);var tn=require("node:crypto");var ue=require("node:crypto");var Rn=new Set([400,401,402,403,404,410,412,422,423]),Nn=new Set(["idempotency_payload_mismatch","mapping_revision_not_approved","fact_type_not_allowed","managed_route_refused","ambiguous_lookup_selector"]);function Dn(e){if(typeof e!="object"||e===null||Array.isArray(e))return{engineCode:void 0,requestId:void 0};let n=e;if(typeof n.error=="string"&&n.error.length>0)return{engineCode:n.error,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0};if(typeof n.error=="object"&&n.error!==null&&!Array.isArray(n.error)){let t=n.error;return{engineCode:typeof t.code=="string"&&t.code.length>0?t.code:void 0,requestId:typeof t.request_id=="string"&&t.request_id.length>0?t.request_id:void 0}}return{engineCode:typeof n.code=="string"&&n.code.length>0?n.code:void 0,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0}}function zn(e,n,t){return e==="FACTO_CONFIG_INVALID"?"config_invalid":e==="FACTO_ENGINE_RESPONSE_INVALID"||e==="FACTO_REQUEST_ABORTED"||e==="FACTO_STATUS_POLL_ABORTED"||n===void 0?"unknown":Rn.has(n)||n===409&&t!==void 0&&Nn.has(t)?"refused":"unknown"}var Ee=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(n,t,r){super(t),this.name="FactoConnectServerError",this.code=n,this.retryable=r.retryable,this.status=r.status,this.details=r.details,this.retryAfterSeconds=r.retryAfterSeconds}},w=class extends Ee{outcome;engineCode;httpStatus;requestId;constructor(n,t,r){let i=r.httpStatus??r.status;super(n,t,{retryable:r.retryable,status:i,details:r.details,retryAfterSeconds:r.retryAfterSeconds}),this.name="CardError",this.httpStatus=i;let c=Dn(r.details);this.engineCode=r.engineCode??c.engineCode,this.requestId=r.requestId??c.requestId,this.outcome=r.outcome??zn(n,i,this.engineCode)}},Pn=6e4,Ve=2147483647;function Ln(e,n){return e<=0?Promise.resolve():new Promise((t,r)=>{if(n?.aborted){r(new w("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let i=setTimeout(()=>{n?.removeEventListener("abort",c),t()},e),c=()=>{clearTimeout(i),r(new w("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};n?.addEventListener("abort",c,{once:!0})})}function Me(e,n={}){return Fn(e,n,w)}async function Fn(e,n,t){let r=n.maxRetries??2,i=n.baseDelayMs??200,c=n.maxDelayMs??5e3,f=n.respectRetryAfter??!0,_=n.maxRetryAfterMs??Pn;if(!Number.isFinite(_)||_<0||_>Ve)throw new w("FACTO_CONFIG_INVALID",`maxRetryAfterMs must be a number from 0 to ${Ve}`,{retryable:!1});let o=n.sleep??Ln,s=0;for(;;)try{return await e()}catch(a){if(!(a instanceof t)||!a.retryable||s>=r)throw a;let l=f&&typeof a.retryAfterSeconds=="number"?a.retryAfterSeconds*1e3:void 0;if(l!==void 0&&!(l<=_))throw a;s+=1;let p=Math.min(c,i*2**(s-1)),g=p*.25*Math.random(),b=l??p+g;n.onRetry?.({attempt:s,error:a,delayMs:b}),await o(b,n.signal)}}function Y(e){let n=e.headers.get("retry-after");if(!(n===null||!/^[0-9]+$/.test(n)))return Number(n)}var Bn=1048576,Se=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ae=/^pconn_[A-Za-z0-9_-]{16,}$/,Te=/^[a-f0-9]{64}$/,se=/^sha256:[a-f0-9]{64}$/,$e=["environment","apiBaseUrl","timeoutMs","retry","maxResponseBytes","fetch"];function T(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function y(e,n=1,t=255){return typeof e=="string"&&[...e].length>=n&&[...e].length<=t}function j(e,n=1,t=255){return y(e,n,t)&&/^[\x21-\x7e]+$/.test(e)}function R(e){return typeof e=="string"&&Se.test(e)&&e!=="00000000-0000-0000-0000-000000000000"}function We(e){return typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=2147483647}function C(e){return typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(e)&&Number.isFinite(Date.parse(e))}function v(e,n,t=[]){return T(e)&&n.every(r=>Object.hasOwn(e,r))&&Object.keys(e).every(r=>n.includes(r)||t.includes(r))}function h(e,n,t=[]){return T(e)&&n.every(r=>Object.hasOwn(e,r))}function d(e,n){if(!e)throw new w("FACTO_CONFIG_INVALID",n,{retryable:!1})}function ie(e){return e===429||e>=500}function oe(e){let n=e?.headers.get("x-request-id")?.trim();return n&&n.length>0?n:void 0}function O(e,n){return new w("FACTO_ENGINE_RESPONSE_INVALID","Card API response does not match the producer contract",{retryable:ie(e),status:e,retryAfterSeconds:n?Y(n):void 0,requestId:oe(n)})}function Je(e,n){return new w("FACTO_ENGINE_RESPONSE_INVALID",`Card API response body exceeds maxResponseBytes (${n} bytes)`,{retryable:ie(e.status),status:e.status,details:{reason:"response_body_too_large",maxResponseBytes:n},retryAfterSeconds:Y(e),requestId:oe(e)})}async function Kn(e,n,t){let r=e.headers.get("content-length")?.trim();if(r!==void 0&&/^\d+$/.test(r)&&Number(r)>n)throw await e.body?.cancel().catch(()=>{}),Je(e,n);if(!e.body)return"";let i=e.body.getReader(),c=[],f=0;try{for(;;){let{done:s,value:a}=await i.read();if(s)break;if(f+=a.byteLength,f>n||t.aborted)throw await i.cancel().catch(()=>{}),t.aborted?new w("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1}):Je(e,n);c.push(a)}}finally{i.releaseLock()}let _=new Uint8Array(f),o=0;for(let s of c)_.set(s,o),o+=s.byteLength;return new TextDecoder().decode(_)}var qn=512;function de(e){return h(e,["error","message","request_id"])&&y(e.error,1,128)&&/^[a-z][a-z0-9_]*$/.test(e.error)&&y(e.message,1,qn)&&y(e.request_id,1,128)}function ce(e){if(!h(e,["error"])||!h(e.error,["category","code","message","request_id","retryable"],["details"]))return!1;let n=e.error;return!(typeof n.category!="string"||typeof n.code!="string"||typeof n.message!="string"||typeof n.request_id!="string"||typeof n.retryable!="boolean")}function Un(e){e!==void 0&&(d(T(e),"retry options must be an object"),e.maxRetries!==void 0&&d(typeof e.maxRetries=="number"&&Number.isSafeInteger(e.maxRetries)&&e.maxRetries>=0,"retry.maxRetries must be a non-negative integer"),e.baseDelayMs!==void 0&&d(typeof e.baseDelayMs=="number"&&Number.isFinite(e.baseDelayMs)&&e.baseDelayMs>=0,"retry.baseDelayMs must be non-negative"),e.maxDelayMs!==void 0&&d(typeof e.maxDelayMs=="number"&&Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0,"retry.maxDelayMs must be non-negative"),e.maxRetryAfterMs!==void 0&&d(typeof e.maxRetryAfterMs=="number"&&Number.isFinite(e.maxRetryAfterMs)&&e.maxRetryAfterMs>=0&&e.maxRetryAfterMs<=2147483647,"retry.maxRetryAfterMs is out of range"))}function Ge(e,n){d(typeof window>"u","Card API credentials require a server runtime"),d(e.environment==="dev"||e.environment==="production","An explicit dev or production environment is required"),Un(e.retry);let t={dev:"https://dev-api.facto.to",production:"https://api.facto.to"},r;d(e.environment!=="production"||typeof e.apiBaseUrl=="string","Production requires an explicit apiBaseUrl");try{r=new URL(e.apiBaseUrl??t.dev)}catch{throw new w("FACTO_CONFIG_INVALID","apiBaseUrl must be an absolute HTTP(S) origin",{retryable:!1})}d(!r.username&&!r.password&&!r.search&&!r.hash&&r.pathname==="/"&&(r.protocol==="https:"||r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname)),"apiBaseUrl must be an HTTPS origin or an explicit loopback HTTP origin");let i=`${r.protocol}//${r.hostname.replace(/\.+$/,"")}${r.port?`:${r.port}`:""}`;d(!Object.values(t).includes(i)||i===t[e.environment],"The published endpoint must match the client environment");let c=r.origin,f=e.timeoutMs??3e4;d(Number.isSafeInteger(f)&&f>0,"timeoutMs must be a positive integer");let _=e.maxResponseBytes??Bn;d(Number.isSafeInteger(_)&&_>0,"maxResponseBytes must be a positive integer");let o=e.fetch??globalThis.fetch?.bind(globalThis);return d(typeof o=="function","A server fetch implementation is required"),async function(a,u,l,p,g,b,D={}){let A=new AbortController,F=()=>A.abort();D.signal?.addEventListener("abort",F,{once:!0}),D.signal?.aborted&&F();let q=setTimeout(F,f),B,N=new Promise((I,H)=>{B=()=>H(new w("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1})),A.signal.addEventListener("abort",B,{once:!0}),A.signal.aborted&&B()});try{if(A.signal.aborted)return await N;l.set("accept","application/json"),p!==void 0&&l.set("content-type","application/json");let I=await Promise.race([o(`${c}${u}`,{method:a,headers:l,redirect:"error",signal:A.signal,...p!==void 0?{body:p}:{}}),N]),H=await Promise.race([Kn(I,_,A.signal),N]),z;try{z=JSON.parse(H)}catch{throw O(I.status,I)}if(g.includes(I.status)&&b(z,I.status))return z;if(!I.ok){if(de(z))throw new w("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${I.status}`,{retryable:ie(I.status),status:I.status,details:z,retryAfterSeconds:Y(I),requestId:z.request_id||oe(I)});if(ce(z))throw new w("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${I.status}`,{retryable:ie(I.status),status:I.status,details:z,retryAfterSeconds:Y(I),requestId:z.error.request_id||oe(I)})}throw O(I.status,I)}catch(I){throw I instanceof w?I:new w("FACTO_ENGINE_REQUEST_FAILED","Card API transport failed; inspect the original operation before any new action",{retryable:!1})}finally{clearTimeout(q),D.signal?.removeEventListener("abort",F),B&&A.signal.removeEventListener("abort",B)}}}var xe="facto-card-binding+jwt",jn=/^pc_[A-Za-z0-9_-]{16,}$/,Vn=/^cbs_[A-Za-z0-9_-]{16,}$/,Mn=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Jn=/^[A-Za-z0-9_-]+$/,$n=/^[0-9]{4}$/,He=300,Ze=600,Wn=["card.metadata.view","card.use_for_facto_payments"],Gn=["passkey","mfa","reauthenticated_session"],Hn=["provider_authenticated_app","device_bound_confirmation"],Zn={dev:"urn:facto:sandbox:card-program-connect:binding-proof",production:"urn:facto:production:card-program-connect:binding-proof"};function Ye(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Q(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1e9&&e<=9999999999}function Qe(e){return typeof e=="string"&&Jn.test(e)&&Buffer.from(e,"base64url").byteLength===32}function Yn(e){return/^[0-9]{12,19}$/.test(e)||/[0-9]{13}/.test(e)}function Qn(e,n){return d(T(e),"Binding assertion proof claim is required"),e.mode==="provider_reauthentication"?(d(v(e,["mode","authenticatedAtSeconds","assurance"])&&Q(e.authenticatedAtSeconds)&&e.authenticatedAtSeconds<=n&&n-e.authenticatedAtSeconds<=Ze&&Gn.includes(e.assurance),"Reauthentication proof requires valid authenticatedAtSeconds (within 600 seconds before issuedAtSeconds) and assurance"),{mode:"provider_reauthentication",authenticated_at:e.authenticatedAtSeconds,assurance:e.assurance}):(d(e.mode==="provider_second_channel"&&v(e,["mode","approvedAtSeconds","approvalRef","channelType"])&&Q(e.approvedAtSeconds)&&e.approvedAtSeconds<=n&&n-e.approvedAtSeconds<=Ze&&y(e.approvalRef,16,255)&&Hn.includes(e.channelType),"Second-channel proof requires valid approvedAtSeconds (within 600 seconds before issuedAtSeconds), approvalRef (16-255 chars), and channelType"),{mode:"provider_second_channel",approved_at:e.approvedAtSeconds,approval_ref:e.approvalRef,channel_type:e.channelType})}function Xn(e){d(Array.isArray(e)&&e.length>=1&&e.length<=20,"Binding assertion requires 1 to 20 asserted cards");let n=new Set,t=0;return e.map(r=>{d(v(r,["externalCardId"],["isEntryCard","display"])&&y(r.externalCardId,8,512)&&!Yn(r.externalCardId)&&(r.isEntryCard===void 0||typeof r.isEntryCard=="boolean"),"Each asserted card requires an opaque externalCardId (8-512 non-PAN chars) and optional boolean isEntryCard"),d(!n.has(r.externalCardId),"Asserted cards must have unique externalCardId values"),n.add(r.externalCardId),r.isEntryCard===!0&&(t+=1,d(t<=1,"At most one asserted card may set isEntryCard to true"));let i;if(r.display!==void 0){d(v(r.display,[],["network","cardType","last4"]),"Asserted card display accepts only network, cardType, and last4");let c=r.display;d((c.network===void 0||y(c.network,1,32))&&(c.cardType===void 0||y(c.cardType,1,32))&&(c.last4===void 0||typeof c.last4=="string"&&$n.test(c.last4)),"Asserted card display fields are out of contract bounds");let f={};c.network!==void 0&&(f.network=c.network),c.cardType!==void 0&&(f.card_type=c.cardType),c.last4!==void 0&&(f.last4=c.last4),Object.keys(f).length>0&&(i=f)}return{card_ref:r.externalCardId,relationship_type:"owner",...r.isEntryCard===!0?{is_entry_card:!0}:{},...i!==void 0?{display:i}:{}}})}async function et(e,n,t){if(typeof e=="function"){let r=await e(n);return d(r instanceof Uint8Array&&r.byteLength===64,"Binding assertion signer must return a 64-byte Ed25519 signature"),r}d(v(e,["kty","crv","x","d"],["kid","alg","use","key_ops","ext"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&(e.alg===void 0||e.alg==="EdDSA"||e.alg==="Ed25519")&&(e.use===void 0||e.use==="sig")&&(e.key_ops===void 0||Array.isArray(e.key_ops)&&e.key_ops.every(r=>typeof r=="string")&&e.key_ops.includes("sign"))&&(e.ext===void 0||typeof e.ext=="boolean")&&(e.kid===void 0||e.kid===t)&&Qe(e.x)&&Qe(e.d),"Binding assertion signer must be a valid Ed25519 private JWK (matching signingKeyId when kid is present) or async signing callback");try{let r=(0,ue.createPrivateKey)({key:{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d},format:"jwk"});return new Uint8Array((0,ue.sign)(null,n,r))}catch{throw new w("FACTO_CONFIG_INVALID","Invalid Ed25519 private JWK for binding assertion signing",{retryable:!1})}}async function le(e){d(v(e,["environment","providerConnectionId","programId","bindingSessionId","issuer","subject","jti","factoChallenge","sessionRequestDigest","requestedUserConsents","proof","cards","signingKeyId","signer"],["issuedAtSeconds","notBeforeSeconds","expiresAtSeconds"]),"Binding assertion input contains missing or unknown fields"),d(e.environment==="dev"||e.environment==="production","environment must be dev or production"),d(typeof e.providerConnectionId=="string"&&jn.test(e.providerConnectionId),"providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)"),d(y(e.programId,1,255),"programId must be 1 to 255 characters"),d(typeof e.bindingSessionId=="string"&&Vn.test(e.bindingSessionId),"bindingSessionId must be a cbs_ identifier"),d(y(e.issuer,1,512),"issuer is required"),d(y(e.subject,16,512),"subject must be a pairwise opaque identifier of 16 to 512 characters"),d(y(e.jti,16,255),"jti must be 16 to 255 characters"),d(y(e.factoChallenge,1,512),"factoChallenge is required"),d(typeof e.sessionRequestDigest=="string"&&se.test(e.sessionRequestDigest),"sessionRequestDigest must be a sha256:<hex> digest"),d(y(e.signingKeyId,1,255)&&e.signingKeyId.trim()===e.signingKeyId&&!e.signingKeyId.includes("\0"),"signingKeyId must be a non-empty trimmed identifier without NUL bytes");let n=e.requestedUserConsents;d(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(l=>Wn.includes(l)),"requestedUserConsents must be a non-empty unique set of supported consent purposes");let t=e.issuedAtSeconds??Math.floor(Date.now()/1e3),r=e.notBeforeSeconds??t,i=e.expiresAtSeconds??t+He;d(Q(t)&&Q(r)&&Q(i)&&r<=t&&t<=i&&i-t<=He,"Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds");let c=Qn(e.proof,t),f=Xn(e.cards),_=Ye({typ:xe,alg:"EdDSA",kid:e.signingKeyId}),o=Ye({iss:e.issuer,aud:Zn[e.environment],sub:e.subject,iat:t,nbf:r,exp:i,jti:e.jti,binding_session_id:e.bindingSessionId,facto_challenge:e.factoChallenge,session_request_digest:e.sessionRequestDigest,connection_id:e.providerConnectionId,environment:e.environment,program_ref:e.programId,proof:c,cards:f,requested_user_consents:[...n]}),s=new TextEncoder().encode(`${_}.${o}`),a=await et(e.signer,s,e.signingKeyId),u=`${_}.${o}.${Buffer.from(a).toString("base64url")}`;return d(u.length>=128&&u.length<=16384&&Mn.test(u),"Signed binding assertion exceeds compact JWS bounds"),u}var X=require("node:crypto");var nt=/^(?:[0-9a-fA-F]{2})+$/;function V(e){return new w("FACTO_CONFIG_INVALID",e,{retryable:!1})}function ke(e){if(typeof e=="string")throw V("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(e instanceof Uint8Array){if(e.byteLength===0)throw V("apiKeySecret Uint8Array must not be empty");return new Uint8Array(e)}if(typeof e!="object"||e===null||Array.isArray(e))throw V("apiKeySecret must be { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(Object.keys(e).length!==2||!Object.hasOwn(e,"encoding")||!Object.hasOwn(e,"value"))throw V("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }");let{encoding:t,value:r}=e;if(t==="utf8"){if(typeof r!="string"||r.length===0)throw V("apiKeySecret with encoding 'utf8' must have a non-empty string value");return new TextEncoder().encode(r)}if(t==="hex"){if(typeof r!="string"||!nt.test(r))throw V("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string");let i=new Uint8Array(r.length/2);for(let c=0;c<r.length;c+=2)i[c/2]=Number.parseInt(r.slice(c,c+2),16);return i}throw V("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")}function _e(e){let n=ke(e.secret),t=(0,X.createHash)("sha256").update(e.body).digest("hex"),r=["FACTO-HMAC-V2",e.method,e.target,String(e.timestamp),e.nonce,t].join(`
|
|
2
|
+
`),i=new Headers({"x-api-key":e.apiKeyId,"x-api-timestamp":String(e.timestamp),"x-api-nonce":e.nonce,"x-api-signature":(0,X.createHmac)("sha256",n).update(r,"utf8").digest("hex")});return e.idempotencyKey!==void 0&&i.set("Idempotency-Key",e.idempotencyKey),i}var te=/^cbs_[A-Za-z0-9_-]{16,}$/,me=/^cint_[A-Za-z0-9_-]{16,}$/,he=/^cb_[A-Za-z0-9_-]{16,}$/,Re=/^sha256:[a-fA-F0-9]{64}$/,rn=["authorization_updated","clearing","reversal","refund","chargeback","settlement"],ge=["authorization_requested",...rn],tt=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"],rt=["active","frozen","closed","replaced"],it=/^[A-Za-z0-9_.:-]{1,64}$/,ot=/^[0-9]+\.[0-9]{2,6}$/,at=/^-?[0-9]+\.[0-9]{2,6}$/;function E(e,n){return typeof e=="string"&&n.test(e)}function on(e){return e===null||typeof e=="string"}function ye(e,n=-2147483648){return typeof e=="number"&&Number.isInteger(e)&&e>=n&&e<=2147483647}function ne(e,n=128){return y(e,1,n)&&!/[0-9]{13}/.test(e)}function ee(e,n){return e==null||n(e)}function fe(e){return Array.isArray(e)&&e.every(n=>E(n,he))}function an(e){return h(e,["network","type","last4"])&&on(e.network)&&(e.type===null||["virtual","physical","unknown"].includes(String(e.type)))&&(e.last4===null||typeof e.last4=="string"&&/^[0-9]{4}$/.test(e.last4))}function K(e){return typeof e=="string"&&/^0x0{32}[0-9a-fA-F]{32}$/.test(e)}function st(e){return typeof e=="string"&&it.test(e)}function dt(e){return!h(e,["snapshot_token","snapshot_at","to_at","items","next_cursor","complete"])||!y(e.snapshot_token,16,4096)||!C(e.snapshot_at)||!C(e.to_at)||typeof e.complete!="boolean"||e.next_cursor!==null&&!y(e.next_cursor,1,4096)||e.complete&&e.next_cursor!==null||!Array.isArray(e.items)||e.items.length>100?!1:e.items.every(n=>h(n,["event_id","origin_connection_id","connection_sequence","event_sha256","target_revision","delivery_state"],["accepted_at"])&&R(n.event_id)&&typeof n.origin_connection_id=="string"&&ae.test(n.origin_connection_id)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&typeof n.event_sha256=="string"&&Te.test(n.event_sha256)&&R(n.target_revision)&&typeof n.delivery_state=="string"&&(n.accepted_at===void 0||C(n.accepted_at)))}function ct(e){return h(e,["replay_id","selection_id","target_revision","status"])&&R(e.replay_id)&&R(e.selection_id)&&R(e.target_revision)&&e.status==="accepted"}function ut(e){d(v(e,["target_revision","page_size"],["selection_id","from_at","to_at","snapshot_token","cursor"]),"Reconciliation requires only the generated query fields"),d(R(e.target_revision)&&typeof e.page_size=="number"&&Number.isInteger(e.page_size)&&e.page_size>=1&&e.page_size<=100,"Reconciliation target_revision and page_size are invalid"),d(R(e.selection_id)&&!Object.hasOwn(e,"from_at")&&!Object.hasOwn(e,"to_at")||!Object.hasOwn(e,"selection_id")&&C(e.from_at)&&C(e.to_at)&&Date.parse(e.from_at)<=Date.parse(e.to_at),"Select exactly one fixed selection or explicit time window"),d((e.snapshot_token===void 0||y(e.snapshot_token,16,4096))&&(e.cursor===void 0||y(e.cursor,16,4096)&&y(e.snapshot_token,16,4096)),"A cursor requires its original snapshot token")}function lt(e){d(T(e),"Authorization lookup requires criteria");let n=Object.hasOwn(e,"criteria")?(d(v(e,["criteria"])&&T(e.criteria),"Authorization lookup wrapper requires only criteria"),e.criteria):e;d(T(n),"Authorization lookup requires criteria");let t=n.by==="external_authorization_id"?v(n,["by","external_authorization_id","resource_version","mapping_revision"],["fact_type"])&&y(n.external_authorization_id,1,256)&&y(n.resource_version,1,255)&&y(n.mapping_revision,1,255)&&(n.fact_type===void 0||ge.includes(String(n.fact_type))):n.by==="supplier_transaction_id"?v(n,["by","supplier_transaction_id","resource_version","mapping_revision"],["fact_type"])&&typeof n.supplier_transaction_id=="string"&&y(n.supplier_transaction_id.trim(),1,256)&&y(n.resource_version,1,255)&&y(n.mapping_revision,1,255)&&(n.fact_type===void 0||ge.includes(String(n.fact_type))):n.by==="idempotency_key"?v(n,["by","idempotency_key","original_credential_key_id"],["operation"])&&y(n.idempotency_key,16,255)&&y(n.original_credential_key_id,1,255)&&(n.operation===void 0||n.operation==="create_authorization"):n.by==="charge_id"&&v(n,["by","charge_id"])&&K(n.charge_id);return d(t,"Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id"),n}function _t(e){d(v(e,["external_card_id","external_authorization_id","amount","currency","resource_version","mapping_revision","cardholder_verification"],["supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country","occurred_at","decision_mode","decision_timeout_ms","deadline_at"]),"Authorization create requires the complete generated request");let r=e.cardholder_verification;d(ne(e.external_card_id,512)&&y(e.external_authorization_id,1,256)&&E(e.amount,ot)&&(e.currency==="USD"||e.currency==="USDC")&&y(e.resource_version,1,255)&&y(e.mapping_revision,1,255)&&(e.merchant_name===void 0||y(e.merchant_name,0,256))&&(e.merchant_mcc===void 0||E(e.merchant_mcc,/^[0-9]{4}$/))&&(e.merchant_country===void 0||y(e.merchant_country,2,3))&&(e.occurred_at===void 0||C(e.occurred_at))&&[e.supplier_transaction_id,e.client_transaction_id].every(i=>i===void 0||typeof i=="string"&&y(i.trim(),1,256))&&(e.decision_mode===void 0||e.decision_mode==="asynchronous"||e.decision_mode==="synchronous")&&(e.decision_timeout_ms===void 0||e.decision_mode==="synchronous"&&typeof e.decision_timeout_ms=="number"&&Number.isInteger(e.decision_timeout_ms)&&e.decision_timeout_ms>=50&&e.decision_timeout_ms<=5e3)&&(e.deadline_at===void 0||e.decision_mode==="synchronous"&&C(e.deadline_at))&&v(r,["method","verified_at","evidence_id"])&&["pin","biometric","cdcvm","signature","no_cvm","provider_attested"].includes(String(r.method))&&C(r.verified_at)&&y(r.evidence_id,1,256),"Authorization fields, currency, mapping/version, or cardholder verification is invalid")}function pt(e,n){d(y(e,1,255)&&e!=="."&&e!==".."&&!e.includes("/"),"externalId must be a valid external authorization identifier"),d(v(n,["fact_type","amount","currency","resource_version","predecessor_version","mapping_revision","recorded_at"],["supplier_transaction_id","parent_supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country"]),"Authorization fact requires the complete generated request"),d(rn.includes(String(n.fact_type))&&E(n.amount,at)&&(n.currency==="USD"||n.currency==="USDC")&&y(n.resource_version,1,255)&&typeof n.predecessor_version=="string"&&y(n.predecessor_version.trim(),1,255)&&n.predecessor_version!==n.resource_version&&y(n.mapping_revision,1,255)&&C(n.recorded_at)&&(n.merchant_name===void 0||y(n.merchant_name,1,255))&&(n.merchant_mcc===void 0||E(n.merchant_mcc,/^[0-9]{4}$/))&&(n.merchant_country===void 0||y(n.merchant_country,2,3))&&[n.supplier_transaction_id,n.parent_supplier_transaction_id,n.client_transaction_id].every(i=>i===void 0||typeof i=="string"&&y(i.trim(),1,255)),"Authorization fact type, predecessor version, amount, or timestamp is invalid")}function sn(e){return Array.isArray(e)&&e.length===5&&e.every((n,t)=>h(n,["kind","state","recorded_at","source_system"],["observed_at","safe_code"])&&n.kind===tt[t]&&["unobserved","pending","confirmed","rejected","indeterminate"].includes(String(n.state))&&C(n.recorded_at)&&["facto","provider","chain"].includes(String(n.source_system))&&(n.safe_code===void 0||y(n.safe_code,1,64))&&(n.observed_at===void 0||C(n.observed_at))&&(n.state!=="confirmed"||C(n.observed_at))&&(n.state!=="unobserved"||!Object.hasOwn(n,"observed_at")))}function yt(e){return!h(e,["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"])||!R(e.receipt_event_id)||!K(e.charge_id)||!(y(e.external_authorization_id,1,256)||y(e.authorization_ref,1,256))||!y(e.mapping_revision,1,255)||!ge.includes(String(e.operation_type))||!y(e.resource_version,1,255)||!C(e.finalized_at)||!sn(e.facts_at_finality)||e.facts_at_finality[3].state!=="confirmed"?!1:e.terminal_action==="releaseFor"?e.execution_outcome==="succeeded"&&e.facts_at_finality[0].state==="confirmed"&&e.facts_at_finality[1].state==="confirmed":e.terminal_action==="cancelReservation"&&e.execution_outcome==="failed"}function ft(e){if(e===void 0)return!0;if(!T(e)||!T(e.issuer)||!Array.isArray(e.issuer.entries)||!Array.isArray(e.refund_cases))return!1;let n=e.issuer,t=n.entries;return["state","cleared_amount","reversed_amount","refunded_amount"].every(r=>typeof n[r]=="string")&&t.every(r=>T(r)&&["operation_type","resource_version","amount","currency","recorded_at","link_status"].every(i=>typeof r[i]=="string")&&r.currency==="USDC"&&(r.unlinked_reason===void 0||typeof r.unlinked_reason=="string"))&&e.refund_cases.every(r=>T(r)&&["case_id","source_operation_type","source_resource_version","status","amount","excess_amount","updated_at"].every(i=>typeof r[i]=="string")&&(r.paid_amount===void 0||typeof r.paid_amount=="string")&&(r.not_payable_reason===void 0||typeof r.not_payable_reason=="string"))}function gt(e,n){if(e===void 0)return!0;if(!T(e)||typeof e.fee_total!="string"||!T(e.fee_breakdown))return!1;let t=e.fee_breakdown;if(!["base_fee","fast_pay_fee","pooled_surcharge"].every(i=>typeof t[i]=="string"))return!1;let r=e.user_payment;return r!==void 0&&(!T(r)||!Number.isSafeInteger(r.chain_id)||typeof r.tx_hash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(r.tx_hash)||r.asset_symbol!==void 0&&typeof r.asset_symbol!="string")?!1:e.refund_payments===void 0||n&&Array.isArray(e.refund_payments)&&e.refund_payments.every(i=>T(i)&&Number.isSafeInteger(i.chain_id)&&typeof i.case_id=="string"&&typeof i.paid_amount=="string"&&typeof i.recorded_by=="string"&&typeof i.tx_hash=="string"&&/^0x[0-9a-fA-F]{64}$/.test(i.tx_hash))}function mt(e){if(!h(e,["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"])||!y(e.external_authorization_id,1,256)||typeof e.origin_connection_id!="string"||!ae.test(e.origin_connection_id)||!y(e.resource_version,1,255)||!y(e.mapping_revision,1,255)||e.charge_id!==void 0&&e.charge_id!==null&&!K(e.charge_id)||e.supplier_transaction_id!==void 0&&!y(e.supplier_transaction_id,1,256)||e.facts!==void 0&&!sn(e.facts)||e.revision!==void 0&&!We(e.revision)||e.operation_type!==void 0&&!ge.includes(String(e.operation_type))||e.decision!==void 0&&!["approved","declined","self_reversed_timeout"].includes(String(e.decision))||e.decline_reason_code!==void 0&&!st(e.decline_reason_code)||!ft(e.lifecycle)||!gt(e.payment_details,e.lifecycle!==void 0))return!1;if(e.processing_status==="succeeded"||e.processing_status==="failed"){if(Object.hasOwn(e,"final_receipt")&&e.final_receipt!==void 0){if(!K(e.charge_id)||!yt(e.final_receipt)||Object.hasOwn(e,"decline_reason_code"))return!1;let n=e.final_receipt,t=n.external_authorization_id??n.authorization_ref;return n.execution_outcome===e.processing_status&&n.charge_id===e.charge_id&&t===e.external_authorization_id&&n.mapping_revision===e.mapping_revision&&n.resource_version===e.resource_version&&(e.operation_type===void 0||n.operation_type===e.operation_type)}return e.processing_status==="succeeded"?!Object.hasOwn(e,"decline_reason_code")&&(e.charge_id===void 0||K(e.charge_id)):K(e.charge_id)||(e.charge_id===void 0||e.charge_id===null)&&(e.decision==="declined"||e.decision==="self_reversed_timeout"||e.decline_reason_code!==void 0)}return!Object.hasOwn(e,"final_receipt")&&!Object.hasOwn(e,"decline_reason_code")&&(e.processing_status==="processing"||e.processing_status==="indeterminate"&&(e.charge_id===void 0||e.charge_id===null))}function ht(e){return!h(e,["observed_at","resolution"],["authorization"])||!C(e.observed_at)?!1:e.resolution==="not_observed"?!Object.hasOwn(e,"authorization")||e.authorization===void 0:mt(e.authorization)?e.resolution==="resolved"?["succeeded","failed"].includes(e.authorization.processing_status):e.resolution==="pending"?e.authorization.processing_status==="processing":e.resolution==="unknown"&&e.authorization.processing_status==="indeterminate":!1}function bt(e){return h(e,["charge_id","status"])&&K(e.charge_id)&&["processing","approved","declined"].includes(String(e.status))&&!Object.hasOwn(e,"final_receipt")}function vt(e){return h(e,["operation_id","status"])&&R(e.operation_id)&&e.status==="recorded"}function At(e,n){return!h(e,["deadline_at","decision_id"])||!C(e.deadline_at)||!R(e.decision_id)?!1:n===200?e.decision==="approved"&&e.status==="approved"&&K(e.charge_id)&&C(e.decided_at):typeof e.error!="string"||typeof e.message!="string"||typeof e.request_id!="string"?!1:n===408&&e.error==="decision_deadline_exceeded"&&!Object.hasOwn(e,"decision")?!0:C(e.decided_at)&&(n===422&&e.decision==="declined"||n===408&&e.decision==="self_reversed_timeout")}function It(e){if(!h(e,["binding_session_id","status","binding_url","expires_at","proof_policy"])||!E(e.binding_session_id,te)||e.status!=="pending"||typeof e.binding_url!="string"||!C(e.expires_at))return!1;let n=e.proof_policy;return h(n,["allowed_modes","challenge_after_facto_auth","challenge_delivery"],["card_selection_supported"])&&Array.isArray(n.allowed_modes)&&n.allowed_modes.length>0&&new Set(n.allowed_modes).size===n.allowed_modes.length&&n.allowed_modes.every(t=>t==="provider_reauthentication"||t==="provider_second_channel")&&n.challenge_after_facto_auth===!0&&(n.challenge_delivery==="browser_handoff"||n.challenge_delivery==="provider_backend")&&(n.card_selection_supported===void 0||n.card_selection_supported===!0)}function Xe(e){if(!T(e)||!E(e.binding_session_id,te)||!C(e.expires_at))return!1;let n=["binding_session_id","status","expires_at"];return["pending","proof_pending","consent_pending"].includes(String(e.status))?h(e,n)&&!["outcome","binding_ids","failure_reason","completed_at"].some(t=>Object.hasOwn(e,t)):e.status==="completed"?Object.hasOwn(e,"completed_at")&&!C(e.completed_at)?!1:e.outcome==="bound"?h(e,[...n,"outcome","binding_ids"],["completed_at"])&&!Object.hasOwn(e,"failure_reason")&&fe(e.binding_ids):e.outcome==="declined"&&h(e,[...n,"outcome","failure_reason"],["completed_at"])&&!Object.hasOwn(e,"binding_ids")&&e.failure_reason==="declined_by_user":e.status==="cancelled"?h(e,n,["completed_at","failure_reason"])&&!["outcome","binding_ids"].some(t=>Object.hasOwn(e,t))&&(!Object.hasOwn(e,"completed_at")||C(e.completed_at))&&(!Object.hasOwn(e,"failure_reason")||["cancelled_by_user","cancelled_by_partner","proof_rejected","admission_closed","no_eligible_cards","integrity_conflict"].includes(String(e.failure_reason))):e.status==="expired"&&h(e,n,["failure_reason"])&&!["completed_at","outcome","binding_ids"].some(t=>Object.hasOwn(e,t))&&(!Object.hasOwn(e,"failure_reason")||e.failure_reason==="expired"||e.failure_reason==="proof_timeout")}function Ct(e){return h(e,["binding_session_id","status","proof_received_at"])&&E(e.binding_session_id,te)&&e.status==="consent_pending"&&C(e.proof_received_at)}function wt(e){return h(e,["binding_session_id","facto_challenge","session_request_digest","expires_at"])&&E(e.binding_session_id,te)&&y(e.facto_challenge,1,512)&&E(e.session_request_digest,se)&&C(e.expires_at)}function Et(e){d(v(e,["requested_user_consents","return_uri"]),"Binding session requires the generated consent and return URI fields");let n=e.requested_user_consents;d(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(t=>t==="card.metadata.view"||t==="card.use_for_facto_payments"),"Binding session consents are invalid"),d(typeof e.return_uri=="string"&&Buffer.byteLength(e.return_uri,"utf8")<=2048&&e.return_uri.startsWith("https://")&&!/[#\r\n]/.test(e.return_uri)&&e.return_uri.slice(8).split(/[/?]/,1)[0].length>0&&!e.return_uri.slice(8).split(/[/?]/,1)[0].includes("@"),"An exact registered HTTPS return URI is required")}function en(e){d(v(e,["proof_format","binding_assertion"])&&e.proof_format==="compact-jws"&&typeof e.binding_assertion=="string"&&e.binding_assertion.length>=128&&e.binding_assertion.length<=16384&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.binding_assertion),"The original compact JWS provider proof is required")}function St(e){return h(e,["id","revision","cards"])&&E(e.id,me)&&E(e.revision,Re)&&Array.isArray(e.cards)&&e.cards.every(n=>h(n,["binding_id","status","card"])&&E(n.binding_id,he)&&typeof n.status=="string"&&an(n.card))}function Tt(e){return h(e,["id","status","revision","added_binding_ids","removed_binding_ids","kept_binding_ids"])&&E(e.id,me)&&["applied","no_change"].includes(String(e.status))&&E(e.revision,Re)&&fe(e.added_binding_ids)&&fe(e.removed_binding_ids)&&fe(e.kept_binding_ids)}function xt(e){return h(e,["id","status"])&&E(e.id,me)&&e.status==="cancelled"}function kt(e){return e===void 0||h(e,["configured","state"],["reason"])&&typeof e.configured=="boolean"&&["ready","not_configured","unavailable"].includes(String(e.state))&&(e.reason===void 0||e.reason===null||typeof e.reason=="string")}function Ot(e){if(!h(e,["binding"],["found"])||e.found!==void 0&&typeof e.found!="boolean")return!1;let n=e.binding;return n===null?e.found!==!0:(e.found===void 0||e.found===!0)&&h(n,["id","status","revision","card"],["funding"])&&E(n.id,he)&&typeof n.status=="string"&&ye(n.revision,1)&&an(n.card)&&kt(n.funding)}function Rt(e){return h(e,["items"])&&Array.isArray(e.items)&&e.items.every(n=>h(n,["id","event_kind","binding_id","binding_revision","connection_sequence","delivery_attempts","last_delivery_error","dead_lettered_at","replay_count"])&&E(n.id,Se)&&typeof n.event_kind=="string"&&E(n.binding_id,he)&&ye(n.binding_revision,1)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&ye(n.delivery_attempts,1)&&on(n.last_delivery_error)&&(n.dead_lettered_at===null||C(n.dead_lettered_at))&&ye(n.replay_count,0))}function Nt(e){return h(e,["id","status"])&&R(e.id)&&e.status==="accepted"}function Dt(e){return h(e,["delivery_id","disposition","effect"])&&R(e.delivery_id)&&(e.disposition==="duplicate"?e.effect===null:e.disposition==="applied"&&["revoked","status_updated","released","none"].includes(String(e.effect)))}function zt(e){d(v(e,["intent_token","approval_id","approval_sha256","revision","cards"],["external_account_id"])&&j(e.intent_token,32,8192)&&y(e.approval_id,1,255)&&E(e.approval_sha256,Te)&&E(e.revision,Re)&&ee(e.external_account_id,n=>typeof n=="string"&&n.length>0&&Buffer.byteLength(n,"utf8")<=512),"Card replacement requires the original complete approved request"),d(Array.isArray(e.cards)&&e.cards.length<=50&&e.cards.every(n=>v(n,["external_card_id"],["network","type","last4"])&&ne(n.external_card_id,255)&&ee(n.network,t=>ne(t,40))&&ee(n.type,t=>t==="virtual"||t==="physical"||t==="unknown")&&ee(n.last4,t=>typeof t=="string"&&/^[0-9]{4}$/.test(t))),"Target cards must match the generated safe card projection")}function Pt(e){d(v(e,["delivery_id","kind","assertion_jws"],["external_card_id","lifecycle_status","external_account_id"])&&R(e.delivery_id)&&typeof e.assertion_jws=="string"&&e.assertion_jws.trim().length>=32,"Inbound event requires a UUID delivery_id and signed assertion_jws");let n=t=>t==null;d(e.kind==="account.released"?y(e.external_account_id,1,512)&&n(e.external_card_id)&&n(e.lifecycle_status):ne(e.external_card_id)&&n(e.external_account_id)&&(e.kind==="card.unbound"?n(e.lifecycle_status):e.kind==="card.lifecycle_changed"&&rt.includes(String(e.lifecycle_status))),"Inbound event fields must match the declared event kind")}function M(e){return d(e&&j(e.idempotencyKey,16,255),"An explicit original Idempotency-Key of 16 to 255 characters is required"),e.idempotencyKey}function pe(e){return d(E(e,te),"id must be the original binding session identifier"),`/api/card/connect/sessions/${e}`}function Oe(e){return d(E(e,me),"id must be the original connect intent identifier"),`/api/card/connect/intents/${e}`}function nn(e){return d(e?.rawBody===void 0||typeof e?.rawBody=="string","rawBody must preserve the original authenticated request bytes"),e?.rawBody}function dn(e){d(v(e,["environment","connectionId","programId","apiKeyId","apiKeySecret"],[...$e,"nowSeconds","createNonce"]),"Card client options cannot contain human session or arbitrary authentication fields"),d(typeof e.connectionId=="string"&&ae.test(e.connectionId),"connectionId must be a pconn_ connection identifier"),d(y(e.programId,1,128)&&j(e.apiKeyId),"programId and apiKeyId are required");let n=ke(e.apiKeySecret),t=Ge(e,"program"),r=Object.freeze({connectionId:e.connectionId,environment:e.environment,programId:e.programId}),i=e.apiKeyId,c=e.nowSeconds??(()=>Math.floor(Date.now()/1e3)),f=e.createNonce??tn.randomUUID;function _(o,s,a,u="POST"){let l=c(),p=f();return d(Number.isSafeInteger(l)&&l>=1e9&&l<=9999999999,"nowSeconds must return a ten-digit Unix timestamp in seconds"),d(j(p,1,128),"createNonce must return a bounded canonical nonce"),_e({secret:n,apiKeyId:i,method:u,target:o,timestamp:l,nonce:p,body:s,idempotencyKey:a})}return Object.freeze({scope:r,sessions:Object.freeze({async create(o,s){Et(o),d(v(s,["idempotencyKey"],["cardSelection","signal"]),"Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal");let a=M(s);d(s.cardSelection===void 0||typeof s.cardSelection=="boolean","cardSelection must be a boolean when provided");let u={...o,program_ref:r.programId},l=JSON.stringify(u),p="/api/card/connect/sessions",g=_(p,l,a);return s.cardSelection===!0&&g.set("x-facto-card-selection","1"),t("POST",p,g,l,[201],It,s)},async get(o,s){let a=pe(o),u=await t("GET",a,_(a,"",void 0,"GET"),void 0,[200],Xe,s);if(u.binding_session_id!==o)throw O(200);return u},async submitProof(o,s,a){let u=`${pe(o)}/provider-proof`,l=M(a);d(T(s),"Provider proof input is required");let p;if(Object.hasOwn(s,"proof_format")||Object.hasOwn(s,"binding_assertion"))en(s),p=s;else{d(!["environment","programId","bindingSessionId","connectionId"].some(q=>Object.hasOwn(s,q)),"Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)");let D=s,A=D.issuedAtSeconds??c();p={proof_format:"compact-jws",binding_assertion:await le({...D,environment:r.environment,programId:r.programId,bindingSessionId:o,issuedAtSeconds:A})},en(p)}let g=JSON.stringify(p),b=await t("POST",u,_(u,g,l),g,[202],Ct,a);if(b.binding_session_id!==o)throw O(202);return b},async getProofChallenge(o,s){let a=`${pe(o)}/proof-challenge`,u=await t("GET",a,_(a,"",void 0,"GET"),void 0,[200],wt,s);if(u.binding_session_id!==o)throw O(200);return u},async cancel(o,s){let a=`${pe(o)}/cancel`,u=M(s),l=nn(s)??"{}",p=await t("POST",a,_(a,l,u),l,[200],Xe,s);if(p.binding_session_id!==o)throw O(200);return p}}),intents:Object.freeze({async listCards(o,s){let a=`${Oe(o)}/cards`;d(v(s,["intentToken"],["signal"])&&j(s.intentToken,32,8192),"intentToken must be a valid HTTP header value of at least 32 characters");let u=_(a,"",void 0,"GET");u.set("x-facto-intent-token",s.intentToken);let l=await t("GET",a,u,void 0,[200],St,s);if(l.id!==o)throw O(200);return l},async replaceCards(o,s,a){let u=`${Oe(o)}/cards`;zt(s);let l=M(a),p=JSON.stringify(s),g=await t("PUT",u,_(u,p,l,"PUT"),p,[200],Tt,a);if(g.id!==o)throw O(200);return g},async cancel(o,s,a){let u=`${Oe(o)}/cancel`;d(v(s,["intent_token"])&&j(s.intent_token,32,8192),"Cancel requires the original intent_token body of at least 32 characters");let l=JSON.stringify(s),p=await t("POST",u,_(u,l),l,[200],xt,a);if(p.id!==o)throw O(200);return p}}),bindings:Object.freeze({async lookup(o,s){d(v(o,["external_card_id"])&&ne(o.external_card_id),"Binding lookup requires only an opaque external_card_id in its body");let a=JSON.stringify(o),u="/api/card/bindings/lookup";return t("POST",u,_(u,a),a,[200],Ot,s)}}),authorizations:Object.freeze({create:(async(o,s)=>{_t(o);let a=M(s),u={...o,program_id:r.programId},l=JSON.stringify(u),p="/api/card/authorizations";return o.decision_mode==="synchronous"?t("POST",p,_(p,l,a),l,[200,422,408],At,s):t("POST",p,_(p,l,a),l,[200],bt,s)}),async recordFact(o,s,a){pt(o,s);let u=M(a),l={...s,program_id:r.programId},p=JSON.stringify(l),g=`/api/card/authorizations/${encodeURIComponent(o)}/facts`;return t("POST",g,_(g,p,u),p,[200],vt,a)},async lookup(o,s){let a=lt(o),u={program_id:r.programId,criteria:a},l=JSON.stringify(u),p="/api/card/authorizations/lookup",g=await t("POST",p,_(p,l),l,[200],ht,s),b=g.authorization;if(b&&(b.origin_connection_id!==r.connectionId||a.by==="charge_id"&&b.charge_id?.toLowerCase()!==a.charge_id.toLowerCase()||a.by==="external_authorization_id"&&(b.external_authorization_id!==a.external_authorization_id||b.resource_version!==a.resource_version||b.mapping_revision!==a.mapping_revision||a.fact_type!==void 0&&b.operation_type!==void 0&&b.operation_type!==a.fact_type)||a.by==="supplier_transaction_id"&&(b.supplier_transaction_id!==a.supplier_transaction_id.trim()||b.resource_version!==a.resource_version||b.mapping_revision!==a.mapping_revision||a.fact_type!==void 0&&b.operation_type!==void 0&&b.operation_type!==a.fact_type)))throw O(200);return g}}),events:Object.freeze({async record(o,s){Pt(o);let a=JSON.stringify(o),u="/api/card/events",l=await t("POST",u,_(u,a),a,[200],Dt,s),p=o.kind==="card.unbound"?"revoked":o.kind==="card.lifecycle_changed"?"status_updated":"released";if(l.delivery_id!==o.delivery_id||l.disposition==="applied"&&l.effect!=="none"&&l.effect!==p)throw O(200);return l}}),deliveries:Object.freeze({async list(o,s){ut(o);let a={...o,program_id:r.programId},u=JSON.stringify(a),l="/api/card/deliveries/reconciliations/list",p=await t("POST",l,_(l,u),u,[200],dt,s);if(p.items.length>o.page_size)throw O(200);return p}}),deliveryReplays:Object.freeze({async create(o,s){d(v(o,["selection_id"])&&R(o.selection_id),"Delivery replay requires a fixed selection_id UUID");let a=M(s),u={...o,program_id:r.programId},l=JSON.stringify(u),p="/api/card/deliveries/replays",g=await t("POST",p,_(p,l,a),l,[202],ct,s);if(g.selection_id!==o.selection_id)throw O(202);return g}}),deadLetters:Object.freeze({async list(o,s){d(o===void 0||v(o,[],["limit"])&&ee(o.limit,p=>typeof p=="number"&&Number.isInteger(p)&&p>=1&&p<=100),"Dead-letter limit must be null, absent, or an integer from 1 to 100");let a=typeof o?.limit=="number"?o.limit:void 0,u=a!==void 0?`/api/card/deliveries/dead-letters?limit=${a}`:"/api/card/deliveries/dead-letters",l=await t("GET",u,_(u,"",void 0,"GET"),void 0,[200],Rt,s);if(l.items.length>(a??50))throw O(200);return l},async replay(o,s){d(R(o),"The dead-letter path identifier must be a UUID");let a=`/api/card/deliveries/dead-letters/${o}/replay`,u=nn(s),l=await t("POST",a,_(a,u??""),u,[202],Nt,s);if(l.id!==o)throw O(202);return l}})})}var ve="/.well-known/facto/card/connect/jwks.json",m=class extends Error{code;details;constructor(n,t,r={}){super(t),this.name="FactoIntentTokenError",this.code=n,this.details=r.details}},Lt="facto",Ft={dev:"https://dev-api.facto.to",sandbox:"https://dev-api.facto.to",production:"https://api.facto.to"},Bt=["dev","production"];function ln(e){return Kt(e,Bt)}async function Kt(e,n){if(e===null||typeof e!="object")throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","verifyCardIntentToken requires an input object");let t=De(e.intentToken,"intentToken"),r=De(e.audience,"audience"),i=e.issuer===void 0?Lt:De(e.issuer,"issuer"),c=Ht(e.clockToleranceSeconds),f=Math.floor(Zt(e.nowMs)/1e3),{headerB64:_,payloadB64:o,signature:s}=Ut(t),a=ze(cn(_,"header"),"FACTO_INTENT_TOKEN_MALFORMED","intent token header");if(a.alg!=="EdDSA")throw new m("FACTO_INTENT_TOKEN_UNSUPPORTED_ALG","intent token JWS alg must be EdDSA",{details:{alg:a.alg}});let u=typeof a.kid=="string"?a.kid:void 0,l=qt(e,n),p=await jt(l),g=$t(p,u),b=Qt(`${_}.${o}`);if(!await Wt(b,s,g))throw new m("FACTO_INTENT_TOKEN_SIGNATURE_INVALID","intent token signature does not verify against the Facto JWKS");let A=Gt(cn(o,"payload"));if(A.iss!==i)throw new m("FACTO_INTENT_TOKEN_ISSUER_MISMATCH","intent token issuer mismatch",{details:{expected:i,actual:A.iss}});if(A.aud!==r)throw new m("FACTO_INTENT_TOKEN_AUDIENCE_MISMATCH","intent token audience mismatch",{details:{expected:r,actual:A.aud}});if(f>A.exp+c)throw new m("FACTO_INTENT_TOKEN_EXPIRED","intent token has expired",{details:{exp:A.exp,now:f}});return{programId:A.program_id,pairwiseSubject:A.sub,nonce:A.nonce,expiresAt:new Date(A.exp*1e3).toISOString()}}function qt(e,n){if(e.jwks!==void 0&&e.jwks!==null)return e.jwks;if(typeof e.apiBaseUrl=="string"&&e.apiBaseUrl.length>0){let t;try{t=new URL(e.apiBaseUrl)}catch{throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`apiBaseUrl is not a valid URL: ${e.apiBaseUrl}`)}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID","apiBaseUrl must be a bare origin without path, query, or credentials");return`${t.origin}${ve}`}if(e.environment!==void 0){let t=n.find(r=>r===e.environment);if(t===void 0)throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID",`environment must be one of ${n.map(r=>`'${r}'`).join(", ")}`);return`${Ft[t]}${ve}`}throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","jwks, apiBaseUrl, or environment is required")}function Ut(e){let n=e.split(".");if(n.length!==3)throw new m("FACTO_INTENT_TOKEN_MALFORMED","intent token is not a compact JWS (expected three segments)");let[t,r,i]=n;if(!t||!r||!i)throw new m("FACTO_INTENT_TOKEN_MALFORMED","intent token has an empty JWS segment");return{headerB64:t,payloadB64:r,signature:_n(i,"signature")}}function cn(e,n){let t=new TextDecoder().decode(_n(e,n));try{return JSON.parse(t)}catch(r){throw new m("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${n} is not valid JSON`,{details:r})}}async function jt(e){return Ne(typeof e=="function"?await e():typeof e=="string"?await Mt(e):e)}var Vt=5e3,be=64*1024;async function Mt(e){let n;try{n=new URL(e)}catch{throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`JWKS url is not a valid URL: ${e}`)}if(n.protocol!=="https:")throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`JWKS url must use https: (got ${n.protocol})`,{details:{protocol:n.protocol}});let t=new AbortController,r=setTimeout(()=>t.abort(),Vt),i,c;try{try{i=await fetch(e,{method:"GET",headers:{accept:"application/json"},redirect:"follow",signal:t.signal})}catch(_){throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`failed to fetch Facto JWKS from ${e}`,{details:_})}if(!i.ok)throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS request failed with status ${i.status}`,{details:{status:i.status}});let f=Number(i.headers.get("content-length"));if(Number.isFinite(f)&&f>be)throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS response exceeds ${be} bytes`,{details:{contentLength:f}});try{c=await i.text()}catch(_){throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS response could not be read",{details:_})}}finally{clearTimeout(r)}if(c.length>be)throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",`Facto JWKS response exceeds ${be} bytes`,{details:{bytes:c.length}});try{return JSON.parse(c)}catch(f){throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS response was not valid JSON",{details:f})}}function Ne(e){let n=ze(e,"FACTO_INTENT_TOKEN_JWKS_INVALID","JWKS");if(!Array.isArray(n.keys))throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID",'JWKS "keys" must be an array');return{keys:n.keys.map(Jt)}}function Jt(e){let n=typeof e=="object"&&e!==null?e:{};return{kty:typeof n.kty=="string"?n.kty:"",crv:typeof n.crv=="string"?n.crv:"",x:typeof n.x=="string"?n.x:"",...typeof n.kid=="string"?{kid:n.kid}:{},...typeof n.alg=="string"?{alg:n.alg}:{},...typeof n.use=="string"?{use:n.use}:{}}}function $t(e,n){let t=e.keys.filter(r=>r.kty==="OKP"&&r.crv==="Ed25519"&&r.x.length>0);if(t.length===0)throw new m("FACTO_INTENT_TOKEN_JWKS_INVALID","Facto JWKS has no usable Ed25519 signing key");if(n!==void 0){let r=t.filter(i=>i.kid===n);if(r.length>0)return r}return t}async function Wt(e,n,t){let r=Xt();for(let i of t){let c;try{c=await r.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:i.x},{name:"Ed25519"},!1,["verify"])}catch{continue}try{if(await r.verify({name:"Ed25519"},c,n,e))return!0}catch{continue}}return!1}function Gt(e){let n=ze(e,"FACTO_INTENT_TOKEN_CLAIMS_INVALID","intent token claims"),t=n.program_id,r=n.program_ref;if(typeof t=="string"&&t.length>0&&typeof r=="string"&&r.length>0&&t!==r)throw new m("FACTO_INTENT_TOKEN_CLAIMS_INVALID",'intent token claims "program_id" and "program_ref" must match when both are present');let i=typeof t=="string"&&t.length>0?t:re(n,"program_ref");return{iss:re(n,"iss"),aud:re(n,"aud"),sub:re(n,"sub"),program_id:i,nonce:re(n,"nonce"),iat:un(n,"iat"),exp:un(n,"exp")}}function De(e,n){if(typeof e!="string"||e.length===0)throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID",`${n} must be a non-empty string`);return e}function Ht(e){if(e===void 0)return 0;if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","clockToleranceSeconds must be a non-negative finite number");return e}function Zt(e){if(e===void 0)return Date.now();if(e instanceof Date){let n=e.getTime();if(Number.isNaN(n))throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","nowMs is an invalid Date");return n}if(typeof e=="number"&&Number.isFinite(e))return e;throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","nowMs must be a Date or unix milliseconds number")}function ze(e,n,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(n,`${t} must be a JSON object`);return e}function re(e,n){let t=e[n];if(typeof t!="string"||t.length===0)throw new m("FACTO_INTENT_TOKEN_CLAIMS_INVALID",`intent token claim "${n}" must be a non-empty string`);return t}function un(e,n){let t=e[n];if(typeof t!="number"||!Number.isFinite(t))throw new m("FACTO_INTENT_TOKEN_CLAIMS_INVALID",`intent token claim "${n}" must be a finite number`);return t}function _n(e,n){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new m("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${n} is not valid base64url`);let t=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4);return Yt(t,n)}function Yt(e,n){let t=globalThis.atob;if(t){let i;try{i=t(e)}catch(f){throw new m("FACTO_INTENT_TOKEN_MALFORMED",`intent token ${n} is not valid base64url`,{details:f})}let c=new Uint8Array(i.length);for(let f=0;f<i.length;f+=1)c[f]=i.charCodeAt(f);return c}let r=globalThis.Buffer;if(r)return new Uint8Array(r.from(e,"base64"));throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","No base64 decoder is available in this runtime")}function Qt(e){let n=new TextEncoder().encode(e),t=new Uint8Array(n.length);return t.set(n),t}function Xt(){let e=globalThis.crypto;if(e?.subtle)return e.subtle;throw new m("FACTO_INTENT_TOKEN_INPUT_INVALID","Web Crypto (crypto.subtle) is not available in this runtime")}var $=require("node:crypto");var Le=["card.binding.linked","card.binding.relinked","card.binding.revoked","card.binding.route_changed","card.binding.limits_changed","card.binding.ownership_transferred","card.charge.finalized","card.charge.facts_updated","card.authorization.updated"],er=["card_program_id","program_connection_id","connect_intent_id","binding_session_id","card_type","envelope_expires_at","authorization_ref","redelivery"],nr=new Set(er);function G(e){if(e===null||typeof e!="object")return!1;if(Array.isArray(e))return e.some(n=>G(n));for(let[n,t]of Object.entries(e))if(nr.has(n)||G(t))return!0;return!1}var tr=new Set(["envelope_version","event_id","event_kind","environment","program_id","origin_connection_id","binding_id","binding_revision","connection_sequence","occurred_at","data"]),rr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ir=/^cprog_[A-Za-z0-9_-]{8,}$/,or=/^pconn_[A-Za-z0-9_-]{16,}$/,ar=/^cb_[A-Za-z0-9_-]{16,}$/;function k(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function J(e){return typeof e=="string"&&e.length>0}function Ae(e){return e===null||typeof e=="string"}function S(e,n){return n.every(t=>J(e[t]))}function x(e){return Number.isSafeInteger(e)}function pn(e){return Array.isArray(e)&&e.every(n=>k(n)&&S(n,["kind","state","recorded_at","source_system"])&&(n.observed_at===void 0||typeof n.observed_at=="string")&&(n.safe_code===void 0||typeof n.safe_code=="string"))}function P(e,n){return n.every(t=>e[t]===void 0||typeof e[t]=="string")}function yn(e,n){return n.every(t=>e[t]===void 0||e[t]===null||typeof e[t]=="string")}function Pe(e){return k(e)&&Object.hasOwn(e,"network")&&Object.hasOwn(e,"type")&&Object.hasOwn(e,"last4")&&Ae(e.network)&&Ae(e.type)&&Ae(e.last4)}function sr(e){if(!x(e.lifecycle_revision)||e.lifecycle_revision<1||!S(e,["operation_type","resource_version","external_authorization_id","mapping_revision"]))return!1;let{authorization:n,charge:t,issuer:r,refunds:i,change:c}=e;if(!k(n)||!S(n,["amount","currency"])||!P(n,["supplier_transaction_id","decision"])||!k(r)||!S(r,["state","cleared_amount","reversed_amount","refunded_amount"])||!P(r,["last_recorded_at"])||!x(r.entry_count)||r.entry_count<0||!x(r.unlinked_count)||r.unlinked_count<0||!k(i)||!x(i.case_count)||i.case_count<0||!S(i,["total_amount","total_paid_amount","total_excess_amount"])||!P(i,["last_updated_at"])||!k(i.status_counts)||!k(c)||!S(c,["type","at"])||!P(c,["ref"]))return!1;let f=i.status_counts;if(!["awaiting_charge_final","awaiting_funds","payable","paid","failed","not_payable"].every(_=>x(f[_])&&f[_]>=0)||c.type==="issuer_fact.recorded"&&c.issuer_fact===void 0||["refund_case.awaiting_charge_final","refund_case.awaiting_funds","refund_case.payable","refund_case.paid","refund_case.failed","refund_case.not_payable"].includes(String(c.type))&&c.refund_case===void 0||c.type==="refund_case.paid"&&(!k(c.refund_case)||!k(c.refund_case.refund_payment))||t!==null&&(!k(t)||!S(t,["charge_id","status","amount","fee_total","total_debited","currency","updated_at"])||!P(t,["failure_code"])||t.user_payment!==void 0&&(!k(t.user_payment)||!x(t.user_payment.chain_id)||!S(t.user_payment,["tx_hash"])||!P(t.user_payment,["asset_symbol"])))||c.issuer_fact!==void 0&&(!k(c.issuer_fact)||!S(c.issuer_fact,["operation_type","resource_version","amount","currency","recorded_at","link_status"])||!P(c.issuer_fact,["unlinked_reason"])))return!1;if(c.refund_case!==void 0){let _=c.refund_case;if(!k(_)||!S(_,["case_id","source_operation_type","status","amount","excess_amount","updated_at"])||!P(_,["paid_amount","not_payable_reason"])||_.refund_payment!==void 0&&(!k(_.refund_payment)||!x(_.refund_payment.chain_id)||!S(_.refund_payment,["tx_hash","paid_amount","recorded_by"])))return!1}return!0}function Ie(e){let n=JSON.parse(e.eventJson);if(!k(n)||n.event_id!==e.eventId||n.event_kind!==e.eventKind)throw new Error("invalid_card_event");if(!Le.includes(e.eventKind)){if(k(n.data)&&G(n.data))throw new Error("invalid_card_event");return{type:"unknown",eventKind:e.eventKind,rawJson:e.eventJson,event:n}}if(Object.keys(n).some(t=>!tr.has(t))||n.envelope_version!==2||!S(n,["event_id","event_kind","environment","program_id","occurred_at"])||!rr.test(n.event_id)||!ir.test(n.program_id)||n.environment!=="dev"&&n.environment!=="production"||n.origin_connection_id!==void 0&&(!J(n.origin_connection_id)||!or.test(n.origin_connection_id))||!(n.connection_sequence===null||x(n.connection_sequence)&&n.connection_sequence>=1)||!k(n.data)||G(n.data))throw new Error("invalid_card_event");if(e.eventKind.startsWith("card.binding.")){if(!J(n.binding_id)||!ar.test(n.binding_id)||!x(n.binding_revision)||n.binding_revision<1)throw new Error("invalid_card_event");let t=n.data,r=e.eventKind;if(r==="card.binding.linked"||r==="card.binding.relinked"){if(!S(t,["external_card_id","binding_id"])||!Pe(t.card)||!yn(t,["intent_id"])||t.ownership_transfer!==void 0&&typeof t.ownership_transfer!="boolean"||!P(t,["environment","subject_link_id","consent_revision","previous_binding_id"])||t.environment!==void 0&&t.environment!=="dev"&&t.environment!=="production"||t.approved_scopes!==void 0&&(!Array.isArray(t.approved_scopes)||!t.approved_scopes.every(i=>typeof i=="string")))throw new Error("invalid_card_event")}else if(r==="card.binding.revoked"){if(!S(t,["external_card_id","binding_id"])||!Pe(t.card)||!(J(t.reason_code)||J(t.revocation_source))||!yn(t,["intent_id"])||!P(t,["reason_code","revocation_source","environment"])||t.environment!==void 0&&t.environment!=="dev"&&t.environment!=="production"||t.binding_revision!==void 0&&(!x(t.binding_revision)||t.binding_revision<1)||t.payable_projections_closed!==void 0&&(!x(t.payable_projections_closed)||t.payable_projections_closed<0)||t.route_associations_detached!==void 0&&(!x(t.route_associations_detached)||t.route_associations_detached<0)||t.routes_detached!==void 0&&(!x(t.routes_detached)||t.routes_detached<0))throw new Error("invalid_card_event")}else if(r==="card.binding.route_changed"){if(!S(t,["binding_id"])||!(t.association_status==="associated"||t.association_status==="unassociated")||!P(t,["environment"])||t.environment!==void 0&&t.environment!=="dev"&&t.environment!=="production"||t.binding_revision!==void 0&&(!x(t.binding_revision)||t.binding_revision<1))throw new Error("invalid_card_event")}else if(r==="card.binding.limits_changed"){if(!S(t,["binding_id","per_tx_limit","period_limit","period"])||!Object.hasOwn(t,"expires_at")||!Ae(t.expires_at)||!P(t,["environment"])||t.environment!==void 0&&t.environment!=="dev"&&t.environment!=="production"||t.binding_revision!==void 0&&(!x(t.binding_revision)||t.binding_revision<1))throw new Error("invalid_card_event")}else if(r==="card.binding.ownership_transferred"&&(!S(t,["previous_binding_id","new_binding_id","external_card_id","transferred_at"])||!Pe(t.card)))throw new Error("invalid_card_event")}else if(e.eventKind==="card.authorization.updated"){if(n.binding_id!==void 0||n.binding_revision!==void 0||!x(n.connection_sequence)||n.connection_sequence<1||!J(n.origin_connection_id)||!sr(n.data))throw new Error("invalid_card_event")}else{let t=n.data;if(n.binding_id!==void 0||n.binding_revision!==void 0||!x(n.connection_sequence)||n.connection_sequence<1||!J(n.origin_connection_id)||!x(t.authorization_revision)||t.authorization_revision<1||!S(t,["operation_type","resource_version","external_authorization_id","mapping_revision"]))throw new Error("invalid_card_event");if(e.eventKind==="card.charge.finalized"){if(!k(t.final_receipt))throw new Error("invalid_card_event");let r=t.final_receipt;if(!S(r,["receipt_event_id","charge_id","external_authorization_id","mapping_revision","operation_type","resource_version","execution_outcome","terminal_action","finalized_at"])||!pn(r.facts_at_finality))throw new Error("invalid_card_event")}else if(!S(t,["charge_id","final_receipt_event_id"])||!x(t.previous_authorization_revision)||t.previous_authorization_revision<1||!pn(t.facts))throw new Error("invalid_card_event")}return{type:"known",event:n}}var Be=["retry","approved_replay","sandbox_replay","dead_letter_replay"],fn=["facto-signature","facto-signature-key-id","facto-event-id","facto-event-kind","facto-delivery-attempt"],dr=["facto-event-timestamp-seconds","facto-event-timestamp"],cr="facto-redelivery-reason",ur=new Set(Be),lr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,gn=/^[^\r\n\x00-\x1f\x7f]+$/;function L(e){return{verified:!1,reason:e}}function Ce(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var mn=new WeakSet;function Ke(e){return typeof e=="object"&&e!==null&&mn.has(e)}function qe(e){let n=new Map,t,r,i=0;for(let[Z,U]of e.headers){let W=Z.toLowerCase();if(W===cr){i+=1,typeof U=="string"&&gn.test(U)?r=U.trim():r=void 0;continue}let je=dr.includes(W),wn=fn.includes(W);if(!(!je&&!wn)){if(typeof U!="string"||!gn.test(U))return L("header_invalid");if(je){if(t!==void 0)return L("header_invalid");t=W,n.set("facto-event-timestamp-seconds",U);continue}if(n.has(W))return L("header_invalid");n.set(W,U)}}if(fn.some(Z=>!n.has(Z))||!n.has("facto-event-timestamp-seconds"))return L("missing_header");let c=n.get("facto-signature"),f=n.get("facto-signature-key-id"),_=n.get("facto-event-id"),o=n.get("facto-event-kind"),s=n.get("facto-event-timestamp-seconds"),a=n.get("facto-delivery-attempt");if(!/^v1=[0-9a-f]{64}$/.test(c)||f.length>255||f.trim()!==f||!lr.test(_)||o.length>120||o.trim()!==o||!/^(0|[1-9][0-9]{0,19})$/.test(s)||!Number.isSafeInteger(Number(s))||!/^[1-9][0-9]{0,9}$/.test(a)||Number(a)>2147483647)return L("header_invalid");let u=e.nowSeconds??Date.now()/1e3,l=e.toleranceSeconds??300;if(!Number.isFinite(u)||!Number.isFinite(l)||l<0||Math.abs(u-Number(s))>l)return L("timestamp_out_of_window");let p=e.registry.filter(Z=>Z.keyId===f);if(p.length!==1)return L("key_not_allowed");let g=p[0],b=Date.parse(g.notBefore)/1e3,D=Date.parse(g.expiresAt)/1e3;if(g.status!=="active"&&g.status!=="overlap"||!Number.isFinite(b)||!Number.isFinite(D)||b>=D||u<b||u>=D||Number(s)<b||Number(s)>=D||!(g.secret instanceof Uint8Array)||g.secret.byteLength===0||!Number.isSafeInteger(g.signerKeyVersion)||g.signerKeyVersion<1)return L("key_not_allowed");let A=(0,$.createHash)("sha256").update(e.rawBody).digest("hex"),F=["facto:card:outbound-delivery-signature","v1",_,o,s,A].join(`
|
|
3
|
+
`),q=(0,$.createHmac)("sha256",g.secret).update(F).digest();if(!(0,$.timingSafeEqual)(q,Buffer.from(c.slice(3),"hex")))return L("signature_invalid");let B,N;try{B=new TextDecoder("utf-8",{fatal:!0}).decode(e.rawBody),N=JSON.parse(B)}catch{return L("envelope_mismatch")}if(!Ce(N)||N.envelope_version!==2||N.event_id!==_||N.event_kind!==o||!Ce(N.data))return L("envelope_mismatch");let I=e.expectedScope,H=o==="card.charge.finalized"||o==="card.charge.facts_updated"||o==="card.authorization.updated";if(!g.eventKinds.includes(o)||g.connectionId!==I.connectionId||g.environment!==I.environment||g.programId!==I.programId||g.targetRevision!==I.targetRevision||N.environment!==g.environment||N.program_id!==g.programId||H&&N.origin_connection_id===void 0||N.origin_connection_id!==void 0&&N.origin_connection_id!==g.connectionId)return L("scope_mismatch");let z=i===1&&r!==void 0&&ur.has(r)?r:void 0,Ue=Object.freeze({verified:!0,scope:Object.freeze({connectionId:g.connectionId,environment:g.environment,programId:g.programId,targetRevision:g.targetRevision}),eventId:_,eventKind:o,bodyDigest:A,eventJson:B,...z!==void 0?{redeliveryReason:z}:{}});return mn.add(Ue),Ue}function hn(e){let n=[...e.registry],t={...e.expectedScope};return r=>qe({rawBody:r.rawBody,headers:r.headers,registry:n,expectedScope:t,nowSeconds:r.nowSeconds??e.nowSeconds?.(),toleranceSeconds:r.toleranceSeconds??e.toleranceSeconds})}function Fe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Fe(t)).join(",")}]`:`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${Fe(r)}`).join(",")}}`}function bn(e){if(!Ke(e))throw new Error("delivery_not_verified");let n=JSON.parse(e.eventJson);if(!Ce(n)||!Ce(n.data)||G(n.data))throw new Error("invalid_card_event");return(0,$.createHash)("sha256").update(Fe(n.data),"utf8").digest("hex")}async function vn(e,n){if(!Ke(e))throw new Error("delivery_not_verified");let t=Ie(e),r=t.event.connection_sequence,i=r===void 0&&t.type==="unknown"?null:r;if(!(i===null||typeof i=="number"&&Number.isSafeInteger(i)&&i>0))throw new Error("invalid_connection_sequence");let c=t.type!=="known"?null:"binding_revision"in t.event?{field:"binding_revision",value:t.event.binding_revision}:t.event.event_kind==="card.authorization.updated"?{field:"lifecycle_revision",value:t.event.data.lifecycle_revision}:{field:"authorization_revision",value:t.event.data.authorization_revision};return n.store.withConnection(e.scope,async f=>{let _=await f.getDigest(e.eventId);if(_!==void 0){if(_!==e.bodyDigest)throw new Error("event_id_conflict");return{status:"duplicate_ignored",connectionSequence:i,observedSequenceGap:null}}let o=await f.getObservedMaxSequence();if(o!==null&&(!Number.isSafeInteger(o)||o<1))throw new Error("invalid_observed_max_sequence");let s=i!==null&&o!==null&&i>o+1?{previousMaxSequence:o,currentSequence:i}:null;return await n.handle(t,f,{connectionSequence:i,eventRevision:c}),await f.markProcessed(e.eventId,e.bodyDigest,i),{status:"processed",connectionSequence:i,observedSequenceGap:s}})}function _r(e,n){return new Promise((t,r)=>{if(n?.aborted){r(n.reason);return}let i=()=>{clearTimeout(c),r(n.reason)},c=setTimeout(()=>{n?.removeEventListener("abort",i),t()},e);n?.addEventListener("abort",i,{once:!0})})}async function An(e,n,t){let{deadlineEpochMs:r,intervalMs:i,maxIntervalMs:c,backoffFactor:f,signal:_}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(c)||!Number.isFinite(f)||i<1||c<i||c>2147483647||f<1||f>10)throw new RangeError("invalid_polling_options");let o=t.nowMs??Date.now,s=t.sleep??_r;if(r-o()>2147483647)throw new RangeError("invalid_polling_deadline");let a=i;for(;;){if(_?.throwIfAborted(),o()>=r)return{status:"poll_deadline_exceeded"};let u=new AbortController,l=Symbol("poll_deadline_exceeded"),p=()=>u.abort(_?.reason);_?.addEventListener("abort",p,{once:!0});let g=setTimeout(()=>u.abort(l),Math.min(r-o(),2147483647)),b,D=new Promise((F,q)=>{b=()=>q(u.signal.reason),u.signal.addEventListener("abort",b,{once:!0})}),A;try{A=await Promise.race([e.authorizations.lookup(n,{signal:u.signal}),D])}catch(F){if(F===l)return{status:"poll_deadline_exceeded"};throw F}finally{clearTimeout(g),u.signal.removeEventListener("abort",b),_?.removeEventListener("abort",p)}if(_?.throwIfAborted(),o()>=r)return{status:"poll_deadline_exceeded"};if(A.resolution==="resolved")return{status:"resolved",result:A};await s(Math.min(a,r-o()),_),a=Math.min(c,a*f)}}var In=require("node:crypto");function Cn(e){let n=[e.connectionId,e.externalAuthorizationId,e.supplierTransactionId,e.clientTransactionId];if(typeof n[0]!="string"||n[0].trim()===""||typeof n[1]!="string"||n[1].trim()===""||n.some(r=>r!==void 0&&typeof r!="string"))throw new TypeError("Connection and authorization identity must be strings");let t=(0,In.createHash)("sha256").update("facto.card.authorization-idempotency.v1\0");for(let r of n)r===void 0?t.update("u;"):t.update(`s${Buffer.byteLength(r,"utf8")}:`).update(r);return`card_auth_${t.digest("hex")}`}
|