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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +63 -2
  5. package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
  6. package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
  7. package/dist/chunk-KBS2PWM4.js +2 -0
  8. package/dist/cli/index.js +6 -0
  9. package/dist/docs/README.md +9 -0
  10. package/dist/docs/authentication.md +96 -0
  11. package/dist/docs/authorization-binding.md +182 -0
  12. package/dist/docs/authorizations.md +182 -0
  13. package/dist/docs/concepts.md +36 -0
  14. package/dist/docs/deliveries.md +170 -0
  15. package/dist/docs/errors.md +100 -0
  16. package/dist/docs/getting-access.md +56 -0
  17. package/dist/docs/idempotency.md +78 -0
  18. package/dist/docs/integration-checklist.md +15 -0
  19. package/dist/docs/integration.zh.md +59 -0
  20. package/dist/docs/interlace-adapter-v1.md +87 -0
  21. package/dist/docs/interlace-adapter-v1.zh.md +87 -0
  22. package/dist/docs/not-yet-available.md +13 -0
  23. package/dist/docs/quickstart.md +126 -0
  24. package/dist/docs/reconciliation.md +86 -0
  25. package/dist/docs/reference/api.md +2541 -0
  26. package/dist/docs/reference/events.md +639 -0
  27. package/dist/docs/reference/schemas.json +6603 -0
  28. package/dist/docs/reference/schemas.md +1001 -0
  29. package/dist/docs/simulator.md +235 -0
  30. package/dist/docs/versioning.md +9 -0
  31. package/dist/index.cjs +3 -0
  32. package/dist/index.d.cts +987 -0
  33. package/dist/index.d.ts +987 -0
  34. package/dist/index.js +2 -0
  35. package/dist/source/build.mjs +5 -0
  36. package/dist/source/package.json +16 -0
  37. package/dist/source/src/connect/cli/deliveries.ts +48 -0
  38. package/dist/source/src/connect/cli/index.ts +57 -0
  39. package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
  40. package/dist/source/src/connect/server/card-client.ts +1018 -0
  41. package/dist/source/src/connect/server/card-delivery.ts +301 -0
  42. package/dist/source/src/connect/server/card-events.ts +473 -0
  43. package/dist/source/src/connect/server/card-idempotency.ts +27 -0
  44. package/dist/source/src/connect/server/card-inbox.ts +82 -0
  45. package/dist/source/src/connect/server/card-intent-token.ts +588 -0
  46. package/dist/source/src/connect/server/card-polling.ts +69 -0
  47. package/dist/source/src/connect/server/card-signing.ts +115 -0
  48. package/dist/source/src/connect/server/card-transport.ts +282 -0
  49. package/dist/source/src/connect/server/errors.ts +280 -0
  50. package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
  51. package/dist/source/src/connect/server/retry-after.ts +12 -0
  52. package/dist/source/src/connect/testing/card-inbox.ts +124 -0
  53. package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
  54. package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
  55. package/dist/source/src/connect/testing/card-simulator.ts +531 -0
  56. package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
  57. package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
  58. package/dist/source/src/connect/wire.d.ts +544 -0
  59. package/dist/source/src/index.ts +163 -0
  60. package/dist/source/src/testing-browser.ts +24 -0
  61. package/dist/source/src/testing.ts +26 -0
  62. package/dist/source/tsconfig.json +20 -0
  63. package/dist/testing-browser.d.ts +220 -0
  64. package/dist/testing-browser.js +5 -0
  65. package/dist/testing.cjs +6 -0
  66. package/dist/testing.d.cts +199 -0
  67. package/dist/testing.d.ts +199 -0
  68. package/dist/testing.js +5 -0
  69. package/package.json +60 -4
@@ -0,0 +1,182 @@
1
+ # Authorizations
2
+
3
+ This page shows how to submit an asynchronous authorization, recover its status, and report later transaction facts.
4
+
5
+ ## Asynchronous-first admission boundary
6
+
7
+ Initial card integrations use **asynchronous admission only**:
8
+
9
+ 1. **Pre-admission refusal (`HTTP 402`)**: If synchronous spending-limit, on-chain balance, or yield-source preconditions fail before admission (`spending_limit_exceeded`, `onchain_insufficient_balance`, `yield_source_underfunded`), `POST /api/card/authorizations` returns HTTP `402` (`CardError.outcome === 'refused'`) without creating a charge row or emitting a webhook.
10
+ 2. **Asynchronous admission (`HTTP 200 processing`)**: Once preconditions pass, Facto persists the authorization and returns `{ charge_id, status: "processing" }`. Processing is admission only, not chain finality or supplier settlement.
11
+ 3. **Finality confirmation**: Observe terminal on-chain execution through outbound Envelope v2 webhooks (`card.charge.finalized` / `card.authorization.updated`) or bounded read-only polling via `POST /api/card/authorizations/lookup`.
12
+
13
+ Real-time synchronous approval (`decision_mode: "synchronous"`) is **closed across all environments** pending shared-ledger rollout and is excluded from initial integration paths.
14
+
15
+ ## From submission to terminal outcome
16
+
17
+ 1. Ensure the card is bound and the original mapping is available. Persist the original identity, exact request body and idempotency key.
18
+ 2. Submit `authorization_requested`. An asynchronous `{charge_id, status: "processing"}` means processing was accepted, not that a payment settled.
19
+ 3. Poll the original identity with a bounded deadline. Preserve the original key and credential key ID for recovery.
20
+ 4. When the result is terminal, inspect its final receipt or decline evidence and facts. Do not infer chain finality or provider settlement from admission alone.
21
+
22
+ The following tested example creates the stable key, persists the original bytes, dispatches, polls, and reads the same operation with all four lookup modes. Supply your own approved identifiers, evidence, and durable persistence callback. The simulator's terminal outcome is synthetic and does not prove any funds moved.
23
+
24
+ <!-- example:authorization -->
25
+ ```typescript
26
+ import { deriveAuthorizationIdempotencyKey, pollAuthorization, type CardClient } from '@facto-to/card'
27
+
28
+ export async function authorizeAndReconcile(card: CardClient, input: {
29
+ connectionId: string
30
+ externalAuthorizationId: string
31
+ externalCardId: string
32
+ originalCredentialKeyId: string
33
+ supplierTransactionId: string
34
+ verificationTime: string
35
+ verificationEvidenceId: string
36
+ }, persistOriginal: (key: string, body: string) => Promise<void>) {
37
+ const authorization = {
38
+ external_card_id: input.externalCardId,
39
+ external_authorization_id: input.externalAuthorizationId,
40
+ supplier_transaction_id: input.supplierTransactionId,
41
+ amount: '10.00',
42
+ currency: 'USD' as const,
43
+ resource_version: 'authorization-v1',
44
+ mapping_revision: 'mapping-v1',
45
+ cardholder_verification: {
46
+ method: 'provider_attested' as const,
47
+ verified_at: input.verificationTime,
48
+ evidence_id: input.verificationEvidenceId,
49
+ },
50
+ }
51
+ const key = deriveAuthorizationIdempotencyKey({
52
+ connectionId: input.connectionId,
53
+ externalAuthorizationId: input.externalAuthorizationId,
54
+ supplierTransactionId: input.supplierTransactionId,
55
+ })
56
+ // The SDK appends program_id to these fields before JSON serialization.
57
+ const rawBody = JSON.stringify({ ...authorization, program_id: card.scope.programId })
58
+ await persistOriginal(key, rawBody)
59
+ const accepted = await card.authorizations.create(authorization, { idempotencyKey: key })
60
+ const original = { resource_version: authorization.resource_version, mapping_revision: authorization.mapping_revision }
61
+ const criteria = { by: 'external_authorization_id' as const, external_authorization_id: input.externalAuthorizationId, ...original }
62
+ const terminal = await pollAuthorization(card, criteria, { deadlineEpochMs: Date.now() + 30_000, intervalMs: 1_000, maxIntervalMs: 5_000, backoffFactor: 2 })
63
+ const byKey = await card.authorizations.lookup({ by: 'idempotency_key', idempotency_key: key, original_credential_key_id: input.originalCredentialKeyId })
64
+ const bySupplier = await card.authorizations.lookup({ by: 'supplier_transaction_id', supplier_transaction_id: input.supplierTransactionId, ...original })
65
+ const byCharge = await card.authorizations.lookup({ by: 'charge_id', charge_id: accepted.charge_id })
66
+ return { accepted, terminal, bySupplier, byKey, byCharge, key, authorization }
67
+ }
68
+ ```
69
+ <!-- /example:authorization -->
70
+
71
+ ## Status interpretation
72
+
73
+ | Situation | `resolution` / `processing_status` | `charge_id` | Final receipt | Decline reason | `decision` | Partner action |
74
+ | --- | --- | --- | --- | --- | --- | --- |
75
+ | Unsealed synchronous approval with no admission (currently unavailable) | `unknown` / `indeterminate` | Absent | Absent | Absent | Absent | Keep the original identity and investigate; do not infer approval. |
76
+ | Admitted and processing | `pending` / `processing` | Present | Absent | Absent | Absent | Continue bounded polling or consume later facts. |
77
+ | Asynchronous successful terminal outcome | `resolved` / `succeeded` | Present | Present and matching | Absent | — | Inspect the receipt and facts; distinguish execution from settlement. |
78
+ | Asynchronous failed terminal outcome | `resolved` / `failed` | Present | Present and matching | Absent | — | Inspect the failure receipt and reconcile the transaction. |
79
+ | Pre-dispatch refusal | `resolved` / `failed` | Present | Absent | Optional | — | Record the reason if supplied and treat this authorization as refused. |
80
+ | Sealed synchronous approval (currently unavailable) | `pending` / `processing` | Present | May appear after terminal outcome | — | `approved` | Do not infer chain finality from the decision; inspect later status. |
81
+ | Synchronous decline | `resolved` / `failed` | May be absent | Absent | Optional | `declined` | Record the reason if supplied and treat this authorization as refused. |
82
+ | Synchronous deadline self-reversal | `resolved` / `failed` | May be absent | Absent | Optional | `self_reversed_timeout` | Record the timeout and follow the reversal guidance. |
83
+ | Recorded fact without an original funds action | `unknown` / `indeterminate` | Absent | Absent | Absent | Absent | Record the fact; do not infer any funds movement. |
84
+ | Not observed | `not_observed`; no authorization object | — | — | — | — | Reconcile the scoped identity; absence does not prove a separate system did nothing. |
85
+
86
+ Every existing projection contains five `facts`; `supplier_transaction_id` may be absent. The `decision` comes from an independent decision record and alone does not establish chain finality. A status query reflects available evidence; do not assume every rejection produces the same projection.
87
+
88
+ The five facts are independent observations, not a progress ladder:
89
+
90
+ | `kind` | Evidence represented |
91
+ | --- | --- |
92
+ | `facto_admission` | Facto's admission decision, not legal responsibility. |
93
+ | `durable_commit` | Technical persistence, not irreversible payment. |
94
+ | `provider_authorization` | Provider approval of this consumption. |
95
+ | `chain_finality` | Observation of terminal-action finality. |
96
+ | `provider_settlement` | Provider settlement observation, independent of action finality. |
97
+
98
+ Each `state` is `unobserved` (no authoritative observation), `pending` (work begun, not confirmed), `confirmed` (authoritative evidence and observation time), `rejected` (owner rejected it), or `indeterminate` (owner cannot establish the result). A processing response can precede a separate admission observation, so even `facto_admission` can remain `unobserved`; do not infer a fact from another status or fact.
99
+
100
+ If queries continue to return `not_observed`, stop automatic polling after a bounded number of attempts, retain the original key and exact body, mark the operation for reconciliation, and use the onboarding channel. `not_observed` does not prove Engine did not receive it.
101
+
102
+ ## Four lookup modes
103
+
104
+ | `criteria.by` | Required original fields |
105
+ | --- | --- |
106
+ | `external_authorization_id` | `external_authorization_id`, `fact_type`, `resource_version`, `mapping_revision` |
107
+ | `supplier_transaction_id` | `supplier_transaction_id`, `fact_type`, `resource_version`, `mapping_revision` |
108
+ | `idempotency_key` | `operation: create_authorization`, original `idempotency_key`, `original_credential_key_id` |
109
+ | `charge_id` | Public `charge_id` returned for the original operation |
110
+
111
+ `original_credential_key_id` is the key ID used to sign the original authorization request, not necessarily the current key after rotation. Persist it with the original idempotency key.
112
+
113
+ The issuer may also provide `parent_supplier_transaction_id` and `client_transaction_id`. These preserve transaction lineage and correlation; none alone proves settlement.
114
+
115
+ ## Synchronous decision (closed)
116
+
117
+ Real-time synchronous approval (`decision_mode: "synchronous"`) is closed in all environments pending shared-ledger rollout and is not part of initial onboarding: synchronous requests are declined with `422 sync_approval_admission_closed`; an already expired deadline instead produces `408 decision_deadline_exceeded`. Do not build initial partner flows around synchronous approval.
118
+
119
+ Engine accepts `decision_timeout_ms` from 50 to 5000 ms, defaulting to 2000 ms, and optionally `deadline_at`. The earlier deadline applies, and a retry cannot extend the first deadline.
120
+
121
+ The issuer or card network has its own reply deadline. For example, Interlace's public real-time authorization decision documentation requires a response in approximately two seconds and treats a timeout as a decline. Set your timeout within your network's deadline and leave margin for round trips.
122
+
123
+ The protocol has three decision outcomes: 200 approved, 422 declined, and 408 timeout. The 408 body may omit `decision`, or include `decision: self_reversed_timeout` and `decided_at`. Both carry a decision ID and deadline. Approval is not currently available. Even when a server sends 200, it cannot guarantee arrival before the peer's timeout; after the peer times out, report an authenticated `reversal` fact on the same transaction lineage.
124
+
125
+ ## Subsequent facts
126
+
127
+ All six fact operations require the external authorization ID, `fact_type`, `amount`, `currency`, `mapping_revision`, `recorded_at`, a new `resource_version`, and an existing distinct `predecessor_version`. Give each fact its own stable idempotency key; retain that key and exact body when retrying. Reusing a version across operation types causes `integrity_conflict`.
128
+
129
+ | `fact_type` | When to report |
130
+ | --- | --- |
131
+ | `authorization_updated` | The provider reports a later authorization update. |
132
+ | `clearing` | The provider reports clearing. |
133
+ | `reversal` | The provider reports a reversal on the same lineage. |
134
+ | `refund` | The provider reports a refund fact. |
135
+ | `chargeback` | The provider reports a chargeback. |
136
+ | `settlement` | The provider reports settlement as a fact. |
137
+
138
+ A successful submission returns `{operation_id, status: "recorded"}`. Engine only records these facts; it does not use them to execute a refund, additional debit, or other money movement.
139
+
140
+ Authorization progress deliveries contain bounded current summaries and one change; they are not a complete history. An independently approved `lifecycle` query may include issuer entries and refund cases. `payment_details` is a separate approval and may expose the total and three fee components plus the user-payment hash; refund-payment hashes additionally require `lifecycle`. The two disclosed hash classes are the user payment and the refund payment. A manually recorded refund is not a chain verification. Missing approval does not imply that history can be recovered, and administrative hold reasons are not partner delivery data.
141
+
142
+
143
+ <!-- example:decisions-and-facts -->
144
+ ```typescript
145
+ import type { AuthorizationCreateInput, CardClient } from '@facto-to/card'
146
+
147
+ export async function decisionsAndFacts(card: CardClient, original: AuthorizationCreateInput, keys: { sync: string; expired: string; clearing: string; refund: string }) {
148
+ // Each decision is a separate network authorization, not a retry of original.
149
+ const separate = (suffix: string) => ({
150
+ ...original,
151
+ external_authorization_id: `${original.external_authorization_id}-${suffix}`,
152
+ ...(original.supplier_transaction_id ? { supplier_transaction_id: `${original.supplier_transaction_id}-${suffix}` } : {}),
153
+ })
154
+ const closed = await card.authorizations.create({ ...separate('sync'), decision_mode: 'synchronous' }, { idempotencyKey: keys.sync })
155
+ if (!('error' in closed) || closed.error !== 'sync_approval_admission_closed') throw new Error('unexpected_synchronous_result')
156
+ // This deliberately expired timestamp demonstrates the timeout shape only.
157
+ const expired = await card.authorizations.create({ ...separate('expired'), decision_mode: 'synchronous', deadline_at: '2020-01-01T00:00:00Z' }, { idempotencyKey: keys.expired })
158
+ if (!('error' in expired) || expired.error !== 'decision_deadline_exceeded') throw new Error('unexpected_deadline_result')
159
+ const recordedAt = '2026-01-01T01:00:00Z'
160
+ const factBase = {
161
+ amount: original.amount,
162
+ currency: original.currency,
163
+ mapping_revision: original.mapping_revision,
164
+ recorded_at: recordedAt,
165
+ ...(original.supplier_transaction_id ? { supplier_transaction_id: original.supplier_transaction_id } : {}),
166
+ }
167
+ const clearing = await card.authorizations.recordFact(original.external_authorization_id, {
168
+ ...factBase,
169
+ fact_type: 'clearing',
170
+ resource_version: 'clearing-v2',
171
+ predecessor_version: original.resource_version,
172
+ }, { idempotencyKey: keys.clearing })
173
+ const refund = await card.authorizations.recordFact(original.external_authorization_id, {
174
+ ...factBase,
175
+ fact_type: 'refund',
176
+ resource_version: 'refund-v3',
177
+ predecessor_version: 'clearing-v2',
178
+ }, { idempotencyKey: keys.refund })
179
+ return { closed, expired, clearing, refund }
180
+ }
181
+ ```
182
+ <!-- /example:decisions-and-facts -->
@@ -0,0 +1,36 @@
1
+ # Concepts and object model
2
+
3
+ This page explains the identities you must keep so that a card operation, its facts, and its deliveries can be correlated without guessing.
4
+
5
+ ## Access and binding
6
+
7
+ | Term | Created by | Meaning and lifecycle |
8
+ | --- | --- | --- |
9
+ | Program | Facto and the partner during onboarding | The card program under which users and cards are connected. Its program reference scopes machine requests. |
10
+ | Program connection | Facto during onboarding | An environment-specific relationship and credential scope for one program integration. Do not reuse its identifiers across environments. |
11
+ | Binding session | Partner backend via `card.sessions.create` | A hosted authorization binding session (`cbs_...`) with a one-time `binding_url`, server-determined `proof_policy`, challenge-bound provider proof, and Facto hosted user consent. See [authorization binding](authorization-binding.md). |
12
+ | Connect intent | Facto user handoff | An optional short-lived, signed connect intent (`cint_...`) for program-owned connect pages to list, replace, or cancel user-approved card bindings after verifying the intent token via JWKS. |
13
+ | Card binding | The binding process | The connection between a provider card and the user's Facto context. Its state and revision change as the relationship changes. |
14
+
15
+ ## Authorization identity and lineage
16
+
17
+ | Term | Created by | Meaning and lifecycle |
18
+ | --- | --- | --- |
19
+ | `external_authorization_id` | Provider | Stable identity for one original authorization and its subsequent facts. Preserve it across the transaction lineage. |
20
+ | `resource_version` | Provider | Identifies one operation version within that lineage. Different operations must not reuse a version. |
21
+ | `predecessor_version` | Provider | Identifies an existing, distinct earlier version when reporting a subsequent fact. It is absent for the original authorization. |
22
+ | `mapping_revision` | Provider integration | Identifies the original approved mapping used for the operation; carry the original value when querying or reporting facts. |
23
+ | `supplier_transaction_id` | Provider | Optional reference for the provider's transaction for this operation. It can be used as a status lookup. |
24
+ | `parent_supplier_transaction_id` | Provider | Optional provider reference linking this operation to its parent transaction. |
25
+ | `client_transaction_id` | Caller | Optional caller correlation identifier retained as operation evidence; it does not itself prove payment. |
26
+ | Charge | Engine | A charge identity created for an admitted original authorization. Processing is not a terminal outcome or settlement. |
27
+ | Fact | Provider or Engine | An observation about an operation. Subsequent provider facts are recorded; they do not themselves execute money movement. |
28
+
29
+ ## Deliveries
30
+
31
+ | Term | Created by | Meaning and lifecycle |
32
+ | --- | --- | --- |
33
+ | Delivery event | Engine | A signed event delivered to the registered receiver. Delivery is at least once; the same event can arrive again. |
34
+ | `connection_sequence` | Engine | A nullable per-connection diagnostic sequence. Gaps can be permanent and deliveries can arrive out of order; do not wait for missing numbers or infer loss from a jump. |
35
+
36
+ Continue with [access](getting-access.md), [authentication](authentication.md), then [authorizations](authorizations.md) and [deliveries](deliveries.md).
@@ -0,0 +1,170 @@
1
+ # Deliveries
2
+
3
+ This page explains how to authenticate deliveries, recognize their kinds, and respond to delivery attempts safely.
4
+
5
+ ## Delivery headers
6
+
7
+ | Header | Purpose |
8
+ | --- | --- |
9
+ | `facto-signature` | `v1=` followed by lowercase HMAC-SHA256 hex. |
10
+ | `facto-signature-key-id` | Selects the registered delivery key. |
11
+ | `facto-event-id` | Event identifier; also present in the body. |
12
+ | `facto-event-kind` | Event kind; also present in the body. |
13
+ | `facto-event-timestamp-seconds` | Unix seconds used in the signature. |
14
+ | `facto-delivery-attempt` | Positive attempt number; not part of the signature input. |
15
+ | `facto-redelivery-reason` | Optional unsigned diagnostic header (`retry`, `approved_replay`, `sandbox_replay`, or `dead_letter_replay`); never part of the v1 signature input. |
16
+
17
+ Preserve exact body bytes and raw header pairs; reject duplicate security headers. Hash the bytes with SHA-256. Join the following UTF-8 lines with LF: `facto:card:outbound-delivery-signature`, `v1`, event ID, event kind, timestamp, and lowercase body digest. Compute HMAC-SHA256 using the registered delivery key. The optional `facto-redelivery-reason` header is unsigned and surfaced on the verified delivery as `redeliveryReason` without changing v1 signature verification.
18
+
19
+ ### Synthetic verification calculation
20
+
21
+ The SDK verification tests exercise a public synthetic fixture. Its event ID is `00000000-0000-4000-8000-000000000070`, kind is `card.charge.finalized`, timestamp is `1792713624`, and the exact body digest is `9fd73e0b184d58d6cd17ac58db01c5da61e773aafa1f11ee3348c412a744351e`. With the test-only derived key `7da911bc6b4a1efc469332f1d1c59c1e0673222067b4bd3fd975ff90c2c3a682` in hex, the signature is `v1=6d4ec0a5abe5d9c8948043049a7b54ef3f3e3c811826f577fa3976eaeb418951`. These are not credentials.
22
+
23
+ The verifier defaults to a 300-second tolerance and requires a unique matching active or overlap key, valid key lifetime, authorized kind, and expected connection, environment, program and target revision. Verify before acknowledging or applying an effect; never log secrets.
24
+
25
+ The target revision is selected from your trusted verification registry and expected scope; it is not itself a signed header or body field. Load both from your approved configuration, not from an untrusted request.
26
+
27
+ Delivery keys are registered with you through the agreed secure channel; see [key compromise, revocation and rotation](getting-access.md#key-compromise-revocation-and-rotation) for what to do when one is exposed.
28
+
29
+ ### Receiver HTTP limits
30
+
31
+ `verifyEventDelivery` receives body bytes you have already read; the SDK never reads the HTTP request. Your HTTP layer is therefore responsible for bounding the request before verification: cap the accumulated body size and answer 413 when it is exceeded, and set request and header timeouts so a slow sender cannot hold connections open. The tested [local receiver](simulator.md#delivery-verification-configuration) shows a 1 MiB cap with 413 and Node.js `requestTimeout`/`headersTimeout` settings. Facto does not currently publish a maximum delivery body size; confirm the value to configure with dev@facto.to. Engine sends each attempt with a 15-second timeout, so a receiver timeout well above that does not cut off a legitimate attempt.
32
+
33
+ ### Implementing verification yourself
34
+
35
+ If you verify deliveries without this SDK, for example in another language, implement all of the following in addition to the signature construction above:
36
+
37
+ 1. **Constant-time comparison.** Decode the 64 lowercase hex characters after `v1=` and compare the 32 bytes with a constant-time function (for example `MessageDigest.isEqual`, `hmac.compare_digest` or `crypto/subtle.ConstantTimeCompare`), never with string equality.
38
+ 2. **A two-sided time window.** Reject unless `|now − facto-event-timestamp-seconds| ≤ 300` seconds; a timestamp too far in the future is as invalid as one too far in the past. Also require the timestamp and the current time to fall inside the selected key's `notBefore`/`expiresAt` validity.
39
+ 3. **Scope check after the signature.** After the signature verifies, parse the body and require `event_id` and `event_kind` to equal the headers, `environment` and `program_id` to equal the key entry's environment and card program, and `origin_connection_id`, when present (it is required for charge events), to equal the key entry's program connection. Also require the event kind to be among the key entry's approved kinds and the key entry to match the scope you expect for this receiver. A valid signature alone does not establish which program or connection an event belongs to, especially when one key is registered for several scopes.
40
+
41
+ ## Event kinds
42
+
43
+ | Kind | When | Key fields |
44
+ | --- | --- | --- |
45
+ | `card.binding.linked` | A binding is linked | Binding ID, provider card ID, approved scopes |
46
+ | `card.binding.relinked` | A binding is linked again | Binding ID, provider card ID, approved scopes |
47
+ | `card.binding.revoked` | A binding is revoked | Binding ID, reason or source |
48
+ | `card.binding.route_changed` | Route association changes | Binding ID, association status |
49
+ | `card.binding.limits_changed` | Spend envelope changes | Limits, period, optional expiry |
50
+ | `card.binding.ownership_transferred` | Ownership transfer is recorded | Previous and new binding IDs |
51
+ | `card.charge.finalized` | Charge execution reaches a final outcome | Charge ID, final receipt and facts |
52
+ | `card.charge.facts_updated` | Later charge facts are recorded | Charge ID, prior receipt and updated facts |
53
+
54
+ The [event reference](reference/events.md) gives complete field tables and examples. Envelope v2 `data` carries only pure business fields: binding card display fields live under `data.card` (`{ network, type, last4 }`, each nullable), limits use `expires_at`, and charge receipts use `external_authorization_id`. Legacy and transport keys (`card_program_id`, `program_connection_id`, `connect_intent_id`, `binding_session_id`, `card_type`, `envelope_expires_at`, `authorization_ref`, `redelivery`) are prohibited inside Envelope v2 `data` and fail closed during decoding. Unknown event kinds are returned as authenticated raw JSON: quarantine or explicitly handle them rather than treating them as a known event.
55
+
56
+ ## Verify and process
57
+
58
+ Preserve the raw headers and body; verify the signature and scope before decoding or applying business effects. Deduplicate by authenticated `event_id` and compare the authenticated body digest. Engine retries of the same send increment `facto-delivery-attempt`; the same event can also arrive again for other reasons without a larger attempt. Timestamp and signature may change. Do not deduplicate by attempt, timestamp or signature.
59
+
60
+ Deliveries can arrive out of order. `connection_sequence` is assigned per connection, but events outside your approved or subscribed kinds also consume sequence numbers without being delivered to you. Gaps can therefore be permanent: do not interpret a jump as a lost event or wait for missing sequence numbers. Use event identity and appropriate business evidence rather than assuming transport order.
61
+
62
+ ## Inbox helper
63
+
64
+ `receiveEventDelivery` takes an already verified delivery, a store, and a handler. It accepts only the exact object returned by a successful `verifyEventDelivery` call in the same process; a copy, a deserialized value or any object built to look like one is rejected with `delivery_not_verified` before your store or handler runs, so verify every delivery, including redeliveries, in the request that receives it. The returned result is frozen. It delivers to your handler at least once in arrival order; duplicates are suppressed after acknowledgement; it provides no ordering or completeness guarantee. It does not verify signatures, fetch missing events, provide a durable queue, or stop on a sequence jump.
65
+
66
+ The handler receives `metadata.connectionSequence` and, for a recognized event, an `eventRevision` naming `binding_revision`, `authorization_revision`, or `lifecycle_revision`. The result may report an `observedSequenceGap` relative to the largest previously confirmed sequence. This diagnostic is not evidence that a delivery is missing; the first sequenced event, duplicates and unsequenced events do not report a jump. Lower sequences can arrive later. For order-sensitive processing, compare revisions within the relevant resource and event semantics, and reconcile uncertainty using authorized reads. Do not blindly discard every lower revision: different event kinds can contain independently meaningful facts.
67
+
68
+ `card.authorization.updated` carries bounded current summaries and one change, not complete history. Record each change under the authorization identity and lifecycle revision in the same transaction as inbox confirmation; retain late changes, but only a strictly newer revision replaces the current summary. Because Envelope v2 `data` excludes transport redelivery metadata (carried instead in the optional unsigned `facto-redelivery-reason` header), call `getBusinessPayloadDigest(verified)` directly on the verified delivery to compare business data across redeliveries and reject mismatches as integrity conflicts. For ergonomic startup wiring, `createDeliveryVerifier({ registry, expectedScope })` binds your receiver configuration once and returns a verifier function for each incoming request. A read requires its own approval; historical recovery is not guaranteed.
69
+
70
+ This tested example verifies and decodes the delivery before handing it to the inbox. Supply your durable store and business handler:
71
+
72
+ <!-- example:delivery -->
73
+ ```typescript
74
+ import {
75
+ decodeDeliveryEvent,
76
+ getBusinessPayloadDigest,
77
+ receiveEventDelivery,
78
+ verifyEventDelivery,
79
+ type AuthorizationUpdatedEvent,
80
+ type DeliveryInboxOptions,
81
+ type DeliveryInboxStore,
82
+ type VerifiedEventDelivery,
83
+ type VerifyEventDeliveryInput,
84
+ } from '@facto-to/card'
85
+ import { MemoryDeliveryInboxStore } from '@facto-to/card/testing'
86
+
87
+ // Local tests only; production needs a durable store.
88
+ export const testInbox = new MemoryDeliveryInboxStore()
89
+
90
+ export async function receiveVerifiedDelivery(
91
+ incoming: VerifyEventDeliveryInput,
92
+ store: DeliveryInboxStore,
93
+ handle: DeliveryInboxOptions['handle'],
94
+ ) {
95
+ const verified = verifyEventDelivery(incoming)
96
+ if (!verified.verified) throw new Error(`delivery_rejected:${verified.reason}`)
97
+ const decoded = decodeDeliveryEvent(verified)
98
+ const result = await receiveEventDelivery(verified, { store, handle })
99
+ return { verified, decoded, result }
100
+ }
101
+
102
+ // Implement these operations in the same durable transaction as inbox confirmation.
103
+ export interface AuthorizationProgressTransaction {
104
+ getChange(identity: string, revision: number): Promise<string | undefined>
105
+ putChange(identity: string, revision: number, businessPayloadDigest: string): Promise<void>
106
+ getCurrentRevision(identity: string): Promise<number | undefined>
107
+ putCurrent(identity: string, event: AuthorizationUpdatedEvent): Promise<void>
108
+ }
109
+
110
+ // verified must be the verified delivery returned by verifyEventDelivery for this event.
111
+ export async function applyAuthorizationProgress(
112
+ tx: AuthorizationProgressTransaction,
113
+ event: AuthorizationUpdatedEvent,
114
+ verified: VerifiedEventDelivery,
115
+ ): Promise<void> {
116
+ const { lifecycle_revision, resource_version, external_authorization_id, mapping_revision } = event.data
117
+ const identity = JSON.stringify([event.environment, event.program_id, event.origin_connection_id, resource_version, external_authorization_id, mapping_revision])
118
+ const digest = getBusinessPayloadDigest(verified)
119
+ const existing = await tx.getChange(identity, lifecycle_revision)
120
+ if (existing !== undefined) {
121
+ if (existing !== digest) throw new Error('authorization_revision_conflict')
122
+ return
123
+ }
124
+ await tx.putChange(identity, lifecycle_revision, digest)
125
+ const current = await tx.getCurrentRevision(identity)
126
+ if (current === undefined || lifecycle_revision > current) await tx.putCurrent(identity, event)
127
+ }
128
+ ```
129
+ <!-- /example:delivery -->
130
+
131
+ ### Business payload digest canonicalization
132
+
133
+ `getBusinessPayloadDigest` is a receiver-local deduplication aid. It is **not** the Engine's reconciliation `event_sha256` and not `bodyDigest`: both of those hash the exact delivered body bytes, including envelope fields such as `event_id`, so they differ between deliveries of the same business data. The business digest covers only the envelope's `data` member and is defined as follows, so a receiver in any language can reproduce it:
134
+
135
+ 1. Decode the verified body as UTF-8 and parse it as JSON. Take the top-level `data` member; it must be an object. Envelope fields outside `data` (`event_id`, `event_kind`, `occurred_at`, `connection_sequence`, `environment`, `program_id`, `origin_connection_id` and any others) and all HTTP headers, including `facto-redelivery-reason`, are excluded. If `data`, at any depth, has a member named `card_program_id`, `program_connection_id`, `connect_intent_id`, `binding_session_id`, `card_type`, `envelope_expires_at`, `authorization_ref` or `redelivery`, the SDK throws `invalid_card_event` instead of returning a digest.
136
+ 2. Serialize the parsed value without any whitespace:
137
+ - **Object:** members sorted by key, comparing keys as sequences of UTF-16 code units (not Unicode code points and not UTF-8 bytes; for example U+1F600 sorts before U+FF61 because its first surrogate, `0xD83D`, is lower). Each member is written as the serialized key string, `:`, then the serialized value, joined with `,` inside `{` and `}`. When the parsed JSON repeats a key, only its last value is kept.
138
+ - **Array:** elements in their original order, serialized recursively, joined with `,` inside `[` and `]`.
139
+ - **String (keys and values):** ECMAScript `JSON.stringify` escaping: `"` → `\"`, `\` → `\\`, U+0008/U+0009/U+000A/U+000C/U+000D → `\b` `\t` `\n` `\f` `\r`, any other code point below U+0020 → `\u00XX` with lowercase hexadecimal, an unpaired surrogate → `\uXXXX` with lowercase hexadecimal. Every other character, including `/`, U+2028, U+2029 and all non-ASCII text, is written unescaped as UTF-8.
140
+ - **Number:** parsed to an IEEE-754 binary64 value and written with ECMAScript `Number.prototype.toString` (shortest round-trip form): `1.0` → `1`, `1e2` → `100`, `-0` → `0`, `1e21` → `1e+21`, `0.0000001` → `1e-7`. Integers outside ±2^53 and over-precise decimals therefore lose precision before hashing.
141
+ - **`true`, `false`, `null`:** written literally.
142
+ 3. Hash the UTF-8 bytes of the serialization with SHA-256 and encode the result as 64 lowercase hexadecimal characters, without a `sha256:` prefix.
143
+
144
+ Published test vector (asserted by the SDK unit tests):
145
+
146
+ | Step | Value |
147
+ | --- | --- |
148
+ | `data` as it appears in the body | `{"b":[3,{"z":1.0,"a":"x/y"}],"a":1e2,"\u00e9":"\u00e9\u0001","\ud83d\ude00":true,"\uff61":null,"B":-0,"n":0.1}` |
149
+ | Canonical serialization | `{"B":0,"a":100,"b":[3,{"a":"x/y","z":1}],"n":0.1,"é":"é\u0001","😀":true,"。":null}` |
150
+ | Canonical UTF-8 bytes (hexadecimal) | `7b2242223a302c2261223a3130302c2262223a5b332c7b2261223a22782f79222c227a223a317d5d2c226e223a302e312c22c3a9223a22c3a95c7530303031222c22f09f9880223a747275652c22efbda1223a6e756c6c7d` |
151
+ | Business payload digest | `4220801cc16965debf235f8305e351d9e1eba9eb6f1f450cbe15ee0e0e5c70bb` |
152
+
153
+ ## HTTP acknowledgement
154
+
155
+ Engine checks the HTTP status only, not the response body. Any 2xx means the receiver accepted this event; every other status is treated as failure.
156
+
157
+ | Situation | Response |
158
+ | --- | --- |
159
+ | `processed`: business handling and confirmation durably committed | 2xx |
160
+ | `duplicate_ignored`: previously confirmed event with matching digest | 2xx; do not repeat the business effect |
161
+ | Temporarily unable to persist or process, including storage outage, an active claim, or a full queue | Non-2xx such as 503 so Engine can retry; retries are finite |
162
+ | Invalid signature or same `event_id` with different content | Reject and alert. Engine still retries failures; a particular 4xx does not stop retries. |
163
+
164
+ Explicit non-2xx failures enter `dead_lettered` after retries are exhausted. Unknown send outcomes, such as timeouts, are `indeterminate` and no further attempt is scheduled once the budget is exhausted; they do not necessarily become dead letters. Both require operational intervention. Current implementation behavior is at most eight attempts, with intervals increasing from 15 seconds to a 600-second cap over roughly 26 minutes, and a 15-second timeout per request. These values are not contractual and may change; there is no end-to-end delivery-time guarantee.
165
+
166
+ ## Durable processing
167
+
168
+ For local tests, import `MemoryDeliveryInboxStore` from `@facto-to/card/testing`. It is non-durable and single-process; implement a durable store for production.
169
+
170
+ Implement `withConnection` as an exclusive cross-process transaction for the connection, environment and card program; retain deduplication records (`event_id`, authenticated digest and confirmation) and the maximum confirmed sequence for diagnostics. Coordinate claims with leases and monotonically increasing fencing tokens so an expired claim can be taken over and a stale confirmation is rejected. Commit business state and the event confirmation atomically before returning 2xx. A late handler may already have run even after its lease expires, so external side effects require their own idempotency or fence checks. At-least-once delivery is effectively once only within the stated atomic boundary. The included in-memory store is for testing, not durable or cross-process.
@@ -0,0 +1,100 @@
1
+ # Errors and uncertain results
2
+
3
+ This page helps you distinguish an accepted operation, an explicit response, and an outcome that remains unknown.
4
+
5
+ ## Status and action
6
+
7
+ | HTTP status | Meaning | Partner action |
8
+ | --- | --- | --- |
9
+ | 2xx | Successful response; asynchronous acceptance is not settlement. | Record identifiers and query status. |
10
+ | 400, 401, 403, 404 | Explicit error response when the body is a valid error envelope. | Correct the request, credentials or scope; record the code. |
11
+ | 402 | Authorization refused by a spending limit or funding precondition. Known examples are `spending_limit_exceeded`, `onchain_insufficient_balance`, and `yield_source_underfunded`. | Preserve the original code; this is not acceptance or settlement. |
12
+ | 408 | A synchronous decision can return a typed timeout result. | Do not treat it as payment completion; follow the deadline and reversal guidance. |
13
+ | 409 | `integrity_conflict` can mean different bytes under a key or another immutable identity conflict. | Reconcile the original operation; this response does not establish whether it was previously accepted. |
14
+ | 422 | A normal refusal or a typed synchronous decline. | Handle the returned shape; synchronous approval is closed. |
15
+ | 423 | New funds admission is closed. | Do not infer the status of an older operation. |
16
+ | 429 | Rate limit; `Retry-After` may be present. | Respect the delay and recover the same request or query status, considering any Engine hint. |
17
+ | 5xx | Outcome may be unknown, including gateway errors whose body is not JSON. | Recover the same request or query the original status. |
18
+ | Other 4xx | May be an explicit envelope, but the status alone does not describe the business outcome. | Inspect the original code and reconcile where necessary. |
19
+
20
+ ## `CardError` and `.outcome` classification
21
+
22
+ `@facto-to/card` throws `CardError` (and retains a deprecated compatibility alias `FactoConnectServerError`). Every `CardError` exposes `.outcome`, `.engineCode`, `.httpStatus` (aliased to `.status`), `.requestId`, `.details`, `.retryable`, and, when a valid `Retry-After` header is present, `.retryAfterSeconds`:
23
+
24
+ | `CardError.outcome` | Exact trigger conditions | Partner action |
25
+ | --- | --- | --- |
26
+ | `'config_invalid'` | Local SDK configuration or argument validation failure (`FACTO_CONFIG_INVALID`: bare-string secret, malformed/odd-length hex, cross-environment `apiBaseUrl`, invalid input shape). | Fix configuration or input; do not retry. |
27
+ | `'refused'` | Deterministic server refusal: HTTP `400`, `401`, `402`, `403`, `404`, `410`, `412`, `422`, `423`, and HTTP `409` with `idempotency_payload_mismatch`, `mapping_revision_not_approved`, `fact_type_not_allowed`, `managed_route_refused`, or `ambiguous_lookup_selector`. | Treat this attempt as refused; fix inputs or allocate a new `external_authorization_id` and new `Idempotency-Key` for a new operation. Exception: after `409 idempotency_payload_mismatch`, always call `POST /api/card/authorizations/lookup` first and allocate new identifiers only when lookup shows no admitted authorization (see [`idempotency_payload_mismatch` requires lookup](#idempotency_payload_mismatch-requires-lookup)). |
28
+ | `'unknown'` | Uncertain or transient outcome: HTTP `408`, `429`, `5xx`, network/abort/timeout/invalid-response errors, and HTTP `409` with `version_already_recorded` or unclassified `integrity_conflict`. | Never start a second authorization; retry with the original `Idempotency-Key` and identical bytes or call `POST /api/card/authorizations/lookup`. |
29
+
30
+ ## Three result classes
31
+
32
+ 1. **Success:** retain the returned operation identity; asynchronous `200 processing` is admission only, not chain finality or settlement.
33
+ 2. **Explicit refusal (`error.outcome === 'refused'`):** `FACTO_ENGINE_REQUEST_FAILED` with a deterministic refusal status or deterministic `409` code. Record `error.engineCode` and `error.requestId`. Treat an explicit refusal as final for that attempt; for `idempotency_payload_mismatch`, first complete the lookup described below.
34
+ 3. **Unknown (`error.outcome === 'unknown'`):** HTTP `408`, `429`, `5xx`, `409 version_already_recorded` / unclassified `integrity_conflict`, a transport error without `httpStatus`, a timeout/abort, or `FACTO_ENGINE_RESPONSE_INVALID`. Recover using the same key and exact body, or query original status via `POST /api/card/authorizations/lookup`.
35
+
36
+ For persistent 429 responses, respect `retryAfterSeconds` and stop automatic retries after a finite configured number of attempts. Preserve the original idempotency key and exact body, mark the operation for reconciliation, and use authorized status/reconciliation queries or the onboarding channel. Apply the same stopping rule when status remains `not_observed`; that result does not prove Engine never received the request.
37
+
38
+ After an explicit refusal, the result of resending the same key and body is not guaranteed by the contract; do not depend on it. A later attempt is a new authorization with a new network authorization reference and a new idempotency key; after `idempotency_payload_mismatch`, start one only once lookup shows no admitted authorization. Resend the same key and body only to recover an unknown result. Pre-admission HTTP `402` refusals do not create a charge row or emit a webhook.
39
+
40
+ `CardError` (`outcome: 'config_invalid'`, `code: 'FACTO_CONFIG_INVALID'`) is a local validation or configuration failure, not an Engine response. Correct it rather than treating the missing status alone as proof that a request reached the network.
41
+
42
+ Error shapes differ:
43
+
44
+ | Response body | SDK classification and reason |
45
+ | --- | --- |
46
+ | Flat `{ "error": "spending_limit_exceeded", "message": "…", "request_id": "…" }` | `FACTO_ENGINE_REQUEST_FAILED`; `isCardErrorEnvelope(error.details)` narrows the reason to `error.details.error`. |
47
+ | Nested `{ "error": { "category": "rate_limited", "code": "too_many_requests", "message": "…", "request_id": "…", "retryable": true } }` | `FACTO_ENGINE_REQUEST_FAILED`; `isCardNestedErrorEnvelope(error.details)` narrows the reason to `error.details.error.code`. The independent Engine hint remains at `error.details.error.retryable`. |
48
+ | Non-JSON, empty or unrecognized body | `FACTO_ENGINE_RESPONSE_INVALID`; `status` and a valid `retryAfterSeconds` are preserved, for example for a 502 HTML gateway page. |
49
+ | Body larger than `maxResponseBytes` (default 1 MiB, set on the client options) | `FACTO_ENGINE_RESPONSE_INVALID` with `details.reason` `response_body_too_large`. The client stops reading as soon as the limit is passed. Treat the outcome as unknown and recover as above. The largest documented responses, a 100-item reconciliation page or dead-letter page, are far below the default. |
50
+
51
+ For all three HTTP response shapes, the SDK error object's `retryable` is determined only by status: true for 429 or 5xx, false otherwise. The nested Engine hint is separate: `details.error.retryable: false` means do not retry blindly; query the original operation first. It is not proof of an explicit refusal. A 500 remains an unknown outcome even when that hint is false.
52
+
53
+ The tested `engineErrorReason` example below extracts both flat and nested codes. Unknown codes and additional fields remain available. The [authorization operation](reference/api.md#post-apicardauthorizations) describes HTTP 402 as the flat envelope. The generated [known error table](reference/api.md#known-machine-error-codes) lists examples, not an exhaustive vocabulary: preserve unknown codes rather than depending on a fixed list.
54
+
55
+ ### `idempotency_payload_mismatch` requires lookup
56
+
57
+ `409 idempotency_payload_mismatch` keeps `outcome: 'refused'`: the server deterministically refused *this request's bytes* under that `Idempotency-Key`. The response by itself proves that the key already exists on the server, so an earlier request under that key was received and may have been admitted. This holds whether or not your process remembers an earlier attempt: a crash after sending but before recording the outcome, or a supplier redelivery of the same card transaction re-driven with rebuilt body bytes, looks like a first attempt locally. The refusal is therefore not final for the authorization:
58
+
59
+ 1. Do not allocate a new `external_authorization_id` or a new `Idempotency-Key` yet.
60
+ 2. Call `POST /api/card/authorizations/lookup` for the original authorization identity and act on its result.
61
+ 3. Only when lookup shows no admitted authorization for that card transaction may you start a new authorization with new identifiers.
62
+
63
+ To avoid the case, persist the exact request bytes before the first send and resend those bytes on every recovery instead of rebuilding the input.
64
+
65
+ ### Intent token verification errors
66
+
67
+ `verifyCardIntentToken` throws `FactoIntentTokenError` (with `code: FactoIntentTokenErrorCode`, for example `FACTO_INTENT_TOKEN_SIGNATURE_INVALID` or `FACTO_INTENT_TOKEN_EXPIRED`), not `CardError`. It verifies the token locally against the Facto JWKS and sends no Engine request, so the `.outcome` table above does not apply. Reject the token and have the user start a new connect intent. `FACTO_INTENT_TOKEN_JWKS_INVALID` reports a JWKS configuration, fetch or format problem; it does not show the token is forged, so fix the JWKS source or verify again later.
68
+
69
+ ## Retrying safely
70
+
71
+ `withServerRetry` invokes the supplied closure again; it does not snapshot its arguments. It uses the SDK's status-based flag and may retry without first inspecting the Engine hint. Do not use it when your policy requires querying the original operation first. Keep the input and original idempotency key unchanged. Each attempt gets a new signing nonce, while body and key must remain byte-identical. It does not make an unkeyed write safe. Authorization status and delivery reconciliation queries are read-only and may be retried. Valid synchronous 408 and 422 decisions are typed results, not thrown errors.
72
+
73
+ When the error carries `retryAfterSeconds`, `withServerRetry` waits exactly that long, but never longer than `maxRetryAfterMs` (default 60000 ms). If the server asks for a longer wait, it makes no further attempt and rethrows the error unchanged, so you can schedule recovery yourself from `retryAfterSeconds`. The SDK reads `Retry-After` only as a whole number of seconds written in decimal digits. Any other value, including signs, decimals, exponents such as `1e7`, hexadecimal, words and the HTTP-date form, is treated as missing: `retryAfterSeconds` is absent and `withServerRetry` falls back to exponential backoff capped by `maxDelayMs`. Neither case causes an immediate retry.
74
+
75
+ <!-- example:errors -->
76
+ ```typescript
77
+ import { CardError, isCardErrorEnvelope, isCardNestedErrorEnvelope, type AuthorizationCreateInput, type CardClient } from '@facto-to/card'
78
+
79
+ export function engineErrorReason(error: CardError): string | undefined {
80
+ if (error.engineCode !== undefined) return error.engineCode
81
+ if (isCardErrorEnvelope(error.details)) return error.details.error
82
+ if (isCardNestedErrorEnvelope(error.details)) return error.details.error.code
83
+ return undefined
84
+ }
85
+
86
+ export async function submitWithRecovery(card: CardClient, input: AuthorizationCreateInput, originalKey: string) {
87
+ try {
88
+ const accepted = await card.authorizations.create(input, { idempotencyKey: originalKey })
89
+ return { outcome: 'accepted' as const, accepted }
90
+ } catch (error) {
91
+ if (!(error instanceof CardError)) throw error
92
+ if (error.outcome === 'config_invalid') throw error
93
+ if (error.outcome === 'refused') {
94
+ return { outcome: 'explicit_response' as const, status: error.httpStatus, reason: engineErrorReason(error) }
95
+ }
96
+ return { outcome: 'unknown' as const }
97
+ }
98
+ }
99
+ ```
100
+ <!-- /example:errors -->
@@ -0,0 +1,56 @@
1
+ # Getting access
2
+
3
+ This page explains what to prepare for onboarding, how to keep environment access separate, and what to do when a key is exposed. Contact dev@facto.to for access and security reports. Provisioning and credentials require approval; never send secrets in ordinary correspondence.
4
+
5
+ ## Provide to Facto
6
+
7
+ | Item | What to prepare |
8
+ | --- | --- |
9
+ | Callback URL | An HTTPS endpoint you operate for signed event delivery. |
10
+ | Delivery signing key registration | Agree on the delivery key identifier, secure registration and rotation procedure. Do not send secrets in ordinary correspondence. |
11
+ | Event and integration scope | Identify the events and operations required for your integration. |
12
+
13
+ ## Receive from Facto
14
+
15
+ | Item | How it is used |
16
+ | --- | --- |
17
+ | Program reference and connection identifier | Scope requests and delivery verification to your integration. |
18
+ | Credential key ID and signing credential | Sign outbound requests from your trusted backend. |
19
+ | Delivery verification registry | Obtain or register the delivery key ID, key material and signer key version through the agreed secure channel. Record the environment, program connection, card program, target revision, and approved event kinds covered by each key. |
20
+ | Delivery key lifetime | Record `notBefore`, `expiresAt`, and active or overlap status. Agree on rotation and a bounded overlap period so both valid versions can be verified during the transition. |
21
+ | Environment endpoints and grants | Configure the authorized API origin and allowed operations for each environment. |
22
+ | Approved mapping revision | Obtain the integration's approved `mapping_revision` through onboarding for each applicable scope. Store the original value alongside each authorization; use that same value for its status queries and later facts, not a newly guessed revision. |
23
+
24
+ ## Environments
25
+
26
+ | Environment | Purpose | Scope |
27
+ | --- | --- | --- |
28
+ | Local simulator | Offline integration exercises | Synthetic data and test credentials only; not evidence of production behavior. |
29
+ | Test | Integration and validation | Set `environment: 'dev'` and explicit `apiBaseUrl: 'https://test-api.facto.to'`; use separately issued Test scope, credentials and grants. |
30
+ | External dev | Integration and validation | Set `environment: 'dev'`; the default is `https://dev-api.facto.to`. This is not Test. |
31
+ | Production | Approved live operations | Set `environment: 'production'` and a separately approved `apiBaseUrl`; no production URL is established. |
32
+
33
+ Production requires an explicit `apiBaseUrl`. The client refuses an `apiBaseUrl` that names the other environment's published Facto origin, including when it is written with a trailing dot. Delivery verification rejects mismatched environment scopes; the backend is responsible for credential validation.
34
+
35
+ Development or sandbox endpoints may use real mainnet assets and can incur real charges. Confirm the assigned environment's funding and settlement behavior before sending any operation; use only synthetic data and the local simulator for the exercises in this kit.
36
+
37
+ Never move credentials, grants or delivery registrations between deployments. Confirm rotation and enabled event kinds before accepting traffic.
38
+
39
+ ## Key compromise, revocation and rotation
40
+
41
+ There are two kinds of keys: the **request-signing credential** (`apiKeyId` and secret) that your backend uses to sign requests to Facto, and the **delivery keys** in your verification registry that Facto uses to sign deliveries to you. Neither can be revoked or rotated through an API in this integration; both are changed by Facto. Contact dev@facto.to for every step below, and never send key material in ordinary correspondence.
42
+
43
+ ### Request-signing credential exposed
44
+
45
+ 1. Stop signing with the exposed credential and ask Facto to revoke it and issue a replacement. Engine checks the credential's status on every request, so a revocation applies to the next request it receives.
46
+ 2. Configure the replacement credential. Whether the old and new credentials can be used concurrently during a planned rotation, and for how long, is not provided as a fixed contract: agree the switchover time with Facto for each rotation, and expect binding and write operations to accept only one credential for a program connection at a time.
47
+ 3. Keep every retired `apiKeyId`. Status lookups `by: 'idempotency_key'` use the `original_credential_key_id` that signed the original request, and Engine keeps those records without an expiry; you sign the lookup with your current credential. Retain the original key ID with each authorization for as long as you may need to query it.
48
+ 4. Reconcile operations sent during the exposure window with authorized status and reconciliation queries before taking further action.
49
+
50
+ ### Delivery key exposed
51
+
52
+ 1. Remove the exposed entry from your verification registry, or set its `status` to `revoked`. `verifyEventDelivery` then rejects deliveries signed with it as `key_not_allowed`; your receiver answers non-2xx, and Engine retries within its finite budget.
53
+ 2. Ask Facto to register a replacement key and add its entry to your registry as soon as you receive it. Engine signs each new delivery attempt only with the connection's current key, so after the switch no new attempt uses the exposed key.
54
+ 3. Recover deliveries that were refused during the gap with [reconciliation and history replay](reconciliation.md); replayed deliveries are signed with the current key. The original delivery and its replays share one sending budget for the same event and target, so an event whose budget was exhausted during the gap is not sent again by replay. For those events, contact dev@facto.to and reconcile them with authorized reads before acting on them.
55
+
56
+ For a planned rotation, add the new entry before Facto switches to it. Facto marks the previous key `overlap`; it remains valid only until its own `expiresAt` and that window is never extended, so keep the previous entry as `overlap` until then and remove it afterwards. Facto retains every key ID it has used in its delivery records; keep retired key IDs in your audit records as well, without their secrets.