@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,301 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { containsBannedEnvelopeV2DataKey } from './card-events'
|
|
3
|
+
|
|
4
|
+
/** Local receiver configuration, not an Engine request or response DTO. */
|
|
5
|
+
export interface DeliveryScope {
|
|
6
|
+
readonly connectionId: string
|
|
7
|
+
readonly environment: 'dev' | 'production'
|
|
8
|
+
readonly programId: string
|
|
9
|
+
readonly targetRevision: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Only trusted, currently authorized receiver keys belong in this registry. */
|
|
13
|
+
export interface DeliverySigningKey extends DeliveryScope {
|
|
14
|
+
readonly keyId: string
|
|
15
|
+
/** The per-key delivery secret, not the outbound root or an inbound credential. */
|
|
16
|
+
readonly secret: Uint8Array
|
|
17
|
+
readonly signerKeyVersion: number
|
|
18
|
+
readonly notBefore: string
|
|
19
|
+
readonly expiresAt: string
|
|
20
|
+
readonly status: 'active' | 'overlap' | 'revoked' | 'expired'
|
|
21
|
+
readonly eventKinds: readonly string[]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type DeliveryVerificationFailureReason =
|
|
25
|
+
| 'missing_header'
|
|
26
|
+
| 'header_invalid'
|
|
27
|
+
| 'key_not_allowed'
|
|
28
|
+
| 'timestamp_out_of_window'
|
|
29
|
+
| 'signature_invalid'
|
|
30
|
+
| 'envelope_mismatch'
|
|
31
|
+
| 'scope_mismatch'
|
|
32
|
+
|
|
33
|
+
export const CARD_REDELIVERY_REASONS = [
|
|
34
|
+
'retry',
|
|
35
|
+
'approved_replay',
|
|
36
|
+
'sandbox_replay',
|
|
37
|
+
'dead_letter_replay',
|
|
38
|
+
] as const
|
|
39
|
+
|
|
40
|
+
export type CardRedeliveryReason = (typeof CARD_REDELIVERY_REASONS)[number]
|
|
41
|
+
|
|
42
|
+
export interface VerifyEventDeliveryInput {
|
|
43
|
+
readonly rawBody: Uint8Array
|
|
44
|
+
/** Raw header pairs preserve duplicates; do not normalize them through Headers first. */
|
|
45
|
+
readonly headers: readonly (readonly [string, string])[]
|
|
46
|
+
readonly registry: readonly DeliverySigningKey[]
|
|
47
|
+
readonly expectedScope: DeliveryScope
|
|
48
|
+
/** Unix seconds, injectable for offline tests. */
|
|
49
|
+
readonly nowSeconds?: number
|
|
50
|
+
readonly toleranceSeconds?: number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type VerifiedEventDelivery = {
|
|
54
|
+
readonly verified: true
|
|
55
|
+
readonly scope: Readonly<DeliveryScope>
|
|
56
|
+
readonly eventId: string
|
|
57
|
+
readonly eventKind: string
|
|
58
|
+
/** SHA-256 of exactly the authenticated public body bytes. Not a storage evidence digest. */
|
|
59
|
+
readonly bodyDigest: string
|
|
60
|
+
/** Authenticated JSON, not a decoded business DTO or a durable acceptance receipt. */
|
|
61
|
+
readonly eventJson: string
|
|
62
|
+
/** Optional unsigned diagnostic header value when sent by the delivery worker. */
|
|
63
|
+
readonly redeliveryReason?: CardRedeliveryReason
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type EventDeliveryVerification =
|
|
67
|
+
| { readonly verified: false; readonly reason: DeliveryVerificationFailureReason }
|
|
68
|
+
| VerifiedEventDelivery
|
|
69
|
+
|
|
70
|
+
export interface CreateDeliveryVerifierOptions {
|
|
71
|
+
readonly registry: readonly DeliverySigningKey[]
|
|
72
|
+
readonly expectedScope: DeliveryScope
|
|
73
|
+
readonly nowSeconds?: () => number
|
|
74
|
+
readonly toleranceSeconds?: number
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface DeliveryVerifierInput {
|
|
78
|
+
readonly rawBody: Uint8Array
|
|
79
|
+
readonly headers: readonly (readonly [string, string])[]
|
|
80
|
+
readonly nowSeconds?: number
|
|
81
|
+
readonly toleranceSeconds?: number
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export type DeliveryVerifier = (input: DeliveryVerifierInput) => EventDeliveryVerification
|
|
85
|
+
|
|
86
|
+
const REQUIRED_NON_TIMESTAMP_HEADERS = [
|
|
87
|
+
'facto-signature',
|
|
88
|
+
'facto-signature-key-id',
|
|
89
|
+
'facto-event-id',
|
|
90
|
+
'facto-event-kind',
|
|
91
|
+
'facto-delivery-attempt',
|
|
92
|
+
] as const
|
|
93
|
+
const TIMESTAMP_HEADERS = [
|
|
94
|
+
'facto-event-timestamp-seconds',
|
|
95
|
+
'facto-event-timestamp',
|
|
96
|
+
] as const
|
|
97
|
+
const REDELIVERY_REASON_HEADER = 'facto-redelivery-reason'
|
|
98
|
+
const REDELIVERY_REASON_SET: ReadonlySet<string> = new Set(CARD_REDELIVERY_REASONS)
|
|
99
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
100
|
+
const LINE = /^[^\r\n\x00-\x1f\x7f]+$/
|
|
101
|
+
|
|
102
|
+
function failure(reason: DeliveryVerificationFailureReason): EventDeliveryVerification {
|
|
103
|
+
return { verified: false, reason }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
107
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Module-private brand: only results created by verifyEventDelivery below
|
|
111
|
+
// are members, so a structurally identical object built elsewhere is not.
|
|
112
|
+
const verifiedDeliveries = new WeakSet<object>()
|
|
113
|
+
|
|
114
|
+
/** True only for a successful result returned by verifyEventDelivery. Not a public export. */
|
|
115
|
+
export function isVerifiedEventDelivery(value: unknown): boolean {
|
|
116
|
+
return typeof value === 'object' && value !== null && verifiedDeliveries.has(value)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Verify outbound Card delivery authentication and receiver scope only.
|
|
121
|
+
* No network, read grant, historical membership, store, dedupe, money or ACK side effects.
|
|
122
|
+
*/
|
|
123
|
+
export function verifyEventDelivery(
|
|
124
|
+
input: VerifyEventDeliveryInput,
|
|
125
|
+
): EventDeliveryVerification {
|
|
126
|
+
const headers = new Map<string, string>()
|
|
127
|
+
let seenTimestampHeader: string | undefined
|
|
128
|
+
let redeliveryReasonRaw: string | undefined
|
|
129
|
+
let redeliveryReasonCount = 0
|
|
130
|
+
for (const [name, value] of input.headers) {
|
|
131
|
+
const lower = name.toLowerCase()
|
|
132
|
+
if (lower === REDELIVERY_REASON_HEADER) {
|
|
133
|
+
redeliveryReasonCount += 1
|
|
134
|
+
if (typeof value === 'string' && LINE.test(value)) {
|
|
135
|
+
redeliveryReasonRaw = value.trim()
|
|
136
|
+
} else {
|
|
137
|
+
redeliveryReasonRaw = undefined
|
|
138
|
+
}
|
|
139
|
+
continue
|
|
140
|
+
}
|
|
141
|
+
const isTimestamp = (TIMESTAMP_HEADERS as readonly string[]).includes(lower)
|
|
142
|
+
const isRequiredOther = (REQUIRED_NON_TIMESTAMP_HEADERS as readonly string[]).includes(lower)
|
|
143
|
+
if (!isTimestamp && !isRequiredOther) continue
|
|
144
|
+
if (typeof value !== 'string' || !LINE.test(value)) {
|
|
145
|
+
return failure('header_invalid')
|
|
146
|
+
}
|
|
147
|
+
if (isTimestamp) {
|
|
148
|
+
if (seenTimestampHeader !== undefined) return failure('header_invalid')
|
|
149
|
+
seenTimestampHeader = lower
|
|
150
|
+
headers.set('facto-event-timestamp-seconds', value)
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
if (headers.has(lower)) return failure('header_invalid')
|
|
154
|
+
headers.set(lower, value)
|
|
155
|
+
}
|
|
156
|
+
if (REQUIRED_NON_TIMESTAMP_HEADERS.some((name) => !headers.has(name)) || !headers.has('facto-event-timestamp-seconds')) {
|
|
157
|
+
return failure('missing_header')
|
|
158
|
+
}
|
|
159
|
+
const signature = headers.get('facto-signature')!
|
|
160
|
+
const keyId = headers.get('facto-signature-key-id')!
|
|
161
|
+
const eventId = headers.get('facto-event-id')!
|
|
162
|
+
const eventKind = headers.get('facto-event-kind')!
|
|
163
|
+
const timestamp = headers.get('facto-event-timestamp-seconds')!
|
|
164
|
+
const attempt = headers.get('facto-delivery-attempt')!
|
|
165
|
+
if (
|
|
166
|
+
!/^v1=[0-9a-f]{64}$/.test(signature) ||
|
|
167
|
+
keyId.length > 255 || keyId.trim() !== keyId ||
|
|
168
|
+
!UUID.test(eventId) || eventKind.length > 120 || eventKind.trim() !== eventKind ||
|
|
169
|
+
!/^(0|[1-9][0-9]{0,19})$/.test(timestamp) || !Number.isSafeInteger(Number(timestamp)) ||
|
|
170
|
+
!/^[1-9][0-9]{0,9}$/.test(attempt) || Number(attempt) > 2147483647
|
|
171
|
+
) return failure('header_invalid')
|
|
172
|
+
|
|
173
|
+
const now = input.nowSeconds ?? Date.now() / 1000
|
|
174
|
+
const tolerance = input.toleranceSeconds ?? 300
|
|
175
|
+
if (
|
|
176
|
+
!Number.isFinite(now) || !Number.isFinite(tolerance) || tolerance < 0 ||
|
|
177
|
+
Math.abs(now - Number(timestamp)) > tolerance
|
|
178
|
+
) return failure('timestamp_out_of_window')
|
|
179
|
+
|
|
180
|
+
const keys = input.registry.filter((entry) => entry.keyId === keyId)
|
|
181
|
+
if (keys.length !== 1) return failure('key_not_allowed')
|
|
182
|
+
const key = keys[0]!
|
|
183
|
+
const start = Date.parse(key.notBefore) / 1000
|
|
184
|
+
const end = Date.parse(key.expiresAt) / 1000
|
|
185
|
+
if (
|
|
186
|
+
(key.status !== 'active' && key.status !== 'overlap') ||
|
|
187
|
+
!Number.isFinite(start) || !Number.isFinite(end) || start >= end ||
|
|
188
|
+
now < start || now >= end || Number(timestamp) < start || Number(timestamp) >= end ||
|
|
189
|
+
!(key.secret instanceof Uint8Array) || key.secret.byteLength === 0 ||
|
|
190
|
+
!Number.isSafeInteger(key.signerKeyVersion) || key.signerKeyVersion < 1
|
|
191
|
+
) {
|
|
192
|
+
return failure('key_not_allowed')
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const bodyDigest = createHash('sha256').update(input.rawBody).digest('hex')
|
|
196
|
+
const canonical = [
|
|
197
|
+
'facto:card:outbound-delivery-signature',
|
|
198
|
+
'v1', eventId, eventKind, timestamp, bodyDigest,
|
|
199
|
+
].join('\n')
|
|
200
|
+
const expected = createHmac('sha256', key.secret).update(canonical).digest()
|
|
201
|
+
if (!timingSafeEqual(expected, Buffer.from(signature.slice(3), 'hex'))) {
|
|
202
|
+
return failure('signature_invalid')
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
let eventJson: string
|
|
206
|
+
let event: unknown
|
|
207
|
+
try {
|
|
208
|
+
eventJson = new TextDecoder('utf-8', { fatal: true }).decode(input.rawBody)
|
|
209
|
+
event = JSON.parse(eventJson)
|
|
210
|
+
} catch {
|
|
211
|
+
return failure('envelope_mismatch')
|
|
212
|
+
}
|
|
213
|
+
if (
|
|
214
|
+
!record(event) || event.envelope_version !== 2 ||
|
|
215
|
+
event.event_id !== eventId || event.event_kind !== eventKind || !record(event.data)
|
|
216
|
+
) {
|
|
217
|
+
return failure('envelope_mismatch')
|
|
218
|
+
}
|
|
219
|
+
const scope = input.expectedScope
|
|
220
|
+
const requiresOrigin =
|
|
221
|
+
eventKind === 'card.charge.finalized' ||
|
|
222
|
+
eventKind === 'card.charge.facts_updated' ||
|
|
223
|
+
eventKind === 'card.authorization.updated'
|
|
224
|
+
if (
|
|
225
|
+
!key.eventKinds.includes(eventKind) ||
|
|
226
|
+
key.connectionId !== scope.connectionId ||
|
|
227
|
+
key.environment !== scope.environment || key.programId !== scope.programId ||
|
|
228
|
+
key.targetRevision !== scope.targetRevision ||
|
|
229
|
+
event.environment !== key.environment || event.program_id !== key.programId ||
|
|
230
|
+
(requiresOrigin && event.origin_connection_id === undefined) ||
|
|
231
|
+
(event.origin_connection_id !== undefined && event.origin_connection_id !== key.connectionId)
|
|
232
|
+
) {
|
|
233
|
+
return failure('scope_mismatch')
|
|
234
|
+
}
|
|
235
|
+
const redeliveryReason: CardRedeliveryReason | undefined =
|
|
236
|
+
redeliveryReasonCount === 1 && redeliveryReasonRaw !== undefined && REDELIVERY_REASON_SET.has(redeliveryReasonRaw)
|
|
237
|
+
? (redeliveryReasonRaw as CardRedeliveryReason)
|
|
238
|
+
: undefined
|
|
239
|
+
const verified: VerifiedEventDelivery = Object.freeze({
|
|
240
|
+
verified: true as const,
|
|
241
|
+
scope: Object.freeze({
|
|
242
|
+
connectionId: key.connectionId,
|
|
243
|
+
environment: key.environment,
|
|
244
|
+
programId: key.programId,
|
|
245
|
+
targetRevision: key.targetRevision,
|
|
246
|
+
}),
|
|
247
|
+
eventId,
|
|
248
|
+
eventKind,
|
|
249
|
+
bodyDigest,
|
|
250
|
+
eventJson,
|
|
251
|
+
...(redeliveryReason !== undefined ? { redeliveryReason } : {}),
|
|
252
|
+
})
|
|
253
|
+
verifiedDeliveries.add(verified)
|
|
254
|
+
return verified
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Ergonomic factory binding receiver registry and expected scope once at startup. */
|
|
258
|
+
export function createDeliveryVerifier(options: CreateDeliveryVerifierOptions): DeliveryVerifier {
|
|
259
|
+
const registry = [...options.registry]
|
|
260
|
+
const expectedScope = { ...options.expectedScope }
|
|
261
|
+
return (input: DeliveryVerifierInput) =>
|
|
262
|
+
verifyEventDelivery({
|
|
263
|
+
rawBody: input.rawBody,
|
|
264
|
+
headers: input.headers,
|
|
265
|
+
registry,
|
|
266
|
+
expectedScope,
|
|
267
|
+
nowSeconds: input.nowSeconds ?? options.nowSeconds?.(),
|
|
268
|
+
toleranceSeconds: input.toleranceSeconds ?? options.toleranceSeconds,
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function canonicalJson(value: unknown): string {
|
|
273
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value)
|
|
274
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`
|
|
275
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
276
|
+
.filter(([, entryValue]) => entryValue !== undefined)
|
|
277
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
278
|
+
return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${canonicalJson(entryValue)}`).join(',')}}`
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Compute the lowercase 64-hex SHA-256 digest of clean Envelope v2 `data`
|
|
283
|
+
* for an already verified delivery. Stable across transport redeliveries
|
|
284
|
+
* because redelivery metadata lives in the optional `facto-redelivery-reason` header.
|
|
285
|
+
*
|
|
286
|
+
* Canonical form: `data` is re-serialized without whitespace, object keys sorted
|
|
287
|
+
* by UTF-16 code unit, strings escaped and numbers formatted as ECMAScript
|
|
288
|
+
* `JSON.stringify` does. This is a receiver-local deduplication aid, not the
|
|
289
|
+
* Engine's `event_sha256` (which covers the whole body). The exact rule and a
|
|
290
|
+
* test vector are in the Card deliveries guide.
|
|
291
|
+
*/
|
|
292
|
+
export function getBusinessPayloadDigest(verifiedDelivery: VerifiedEventDelivery): string {
|
|
293
|
+
if (!isVerifiedEventDelivery(verifiedDelivery)) {
|
|
294
|
+
throw new Error('delivery_not_verified')
|
|
295
|
+
}
|
|
296
|
+
const parsed: unknown = JSON.parse(verifiedDelivery.eventJson)
|
|
297
|
+
if (!record(parsed) || !record(parsed.data) || containsBannedEnvelopeV2DataKey(parsed.data)) {
|
|
298
|
+
throw new Error('invalid_card_event')
|
|
299
|
+
}
|
|
300
|
+
return createHash('sha256').update(canonicalJson(parsed.data), 'utf8').digest('hex')
|
|
301
|
+
}
|