@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,588 @@
|
|
|
1
|
+
import type { CardEnvironment } from './card-transport'
|
|
2
|
+
|
|
3
|
+
/** Canonical public JWKS path for verifying Facto-issued Card connect intent tokens. */
|
|
4
|
+
export const CARD_INTENT_JWKS_PATH = '/.well-known/facto/card/connect/jwks.json' as const
|
|
5
|
+
|
|
6
|
+
/** A public Ed25519 JWK (OKP) as served by the Facto Card connect JWKS. */
|
|
7
|
+
export interface CardIntentJwk {
|
|
8
|
+
kty: string
|
|
9
|
+
crv: string
|
|
10
|
+
x: string
|
|
11
|
+
kid?: string
|
|
12
|
+
alg?: string
|
|
13
|
+
use?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The Facto Card connect JWK set, served (public, no auth) at
|
|
18
|
+
* `GET /.well-known/facto/card/connect/jwks.json`.
|
|
19
|
+
*/
|
|
20
|
+
export interface CardIntentJwks {
|
|
21
|
+
keys: CardIntentJwk[]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* How the caller supplies the Facto JWKS: an in-memory `{ keys }` set, a JWKS URL
|
|
26
|
+
* string to fetch (public GET, no auth), or a resolver that returns the set.
|
|
27
|
+
*/
|
|
28
|
+
export type CardIntentJwksInput =
|
|
29
|
+
| CardIntentJwks
|
|
30
|
+
| string
|
|
31
|
+
| (() => CardIntentJwks | Promise<CardIntentJwks>)
|
|
32
|
+
|
|
33
|
+
export interface VerifyCardIntentTokenInput {
|
|
34
|
+
/** The compact EdDSA JWS intent token the Facto user handed the partner. */
|
|
35
|
+
intentToken: string
|
|
36
|
+
/**
|
|
37
|
+
* The Facto JWKS: an in-memory `{ keys }` set, a JWKS URL to fetch, or a resolver.
|
|
38
|
+
* When omitted, `apiBaseUrl` or `environment` resolves `${origin}/.well-known/facto/card/connect/jwks.json`.
|
|
39
|
+
*/
|
|
40
|
+
jwks?: CardIntentJwksInput
|
|
41
|
+
/** Optional Facto API origin used to construct the default JWKS URL when `jwks` is omitted. */
|
|
42
|
+
apiBaseUrl?: string
|
|
43
|
+
/**
|
|
44
|
+
* Optional Facto environment used to construct the default JWKS URL when `jwks` and `apiBaseUrl` are omitted.
|
|
45
|
+
* Only selects the JWKS origin; the intent token itself carries no environment claim.
|
|
46
|
+
*/
|
|
47
|
+
environment?: CardEnvironment
|
|
48
|
+
/**
|
|
49
|
+
* The partner's own connection audience — its environment-unique program code.
|
|
50
|
+
* The token's `aud` MUST equal this; a mismatch is rejected.
|
|
51
|
+
*/
|
|
52
|
+
audience: string
|
|
53
|
+
/** Expected issuer. Defaults to `'facto'`. */
|
|
54
|
+
issuer?: string
|
|
55
|
+
/** Verification clock (unix milliseconds or `Date`). Defaults to `Date.now()`. */
|
|
56
|
+
nowMs?: number | Date
|
|
57
|
+
/** Clock-skew tolerance in seconds applied to the expiry check. Defaults to `0`. */
|
|
58
|
+
clockToleranceSeconds?: number
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Input accepted by the merchant connect server entrypoint's re-export of
|
|
63
|
+
* `verifyCardIntentToken`, which keeps that entrypoint's `'sandbox'` spelling of
|
|
64
|
+
* the dev environment. The Card package accepts only {@link CardEnvironment}.
|
|
65
|
+
*/
|
|
66
|
+
export interface ConnectVerifyCardIntentTokenInput extends Omit<VerifyCardIntentTokenInput, 'environment'> {
|
|
67
|
+
environment?: CardEnvironment | 'sandbox'
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface VerifiedCardIntentToken {
|
|
71
|
+
/** The opaque program ID the intent token is scoped to (`cprog_...`). */
|
|
72
|
+
programId: string
|
|
73
|
+
/** Pairwise-opaque subject (`facto-user:<hex>`); NEVER the raw Facto user id. */
|
|
74
|
+
pairwiseSubject: string
|
|
75
|
+
/** Single-use nonce; the caller MUST enforce single-use against its own store. */
|
|
76
|
+
nonce: string
|
|
77
|
+
/** Absolute expiry (`exp`) as an RFC 3339 / ISO-8601 timestamp. */
|
|
78
|
+
expiresAt: string
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type FactoIntentTokenErrorCode =
|
|
82
|
+
| 'FACTO_INTENT_TOKEN_INPUT_INVALID'
|
|
83
|
+
| 'FACTO_INTENT_TOKEN_JWKS_INVALID'
|
|
84
|
+
| 'FACTO_INTENT_TOKEN_MALFORMED'
|
|
85
|
+
| 'FACTO_INTENT_TOKEN_UNSUPPORTED_ALG'
|
|
86
|
+
| 'FACTO_INTENT_TOKEN_SIGNATURE_INVALID'
|
|
87
|
+
| 'FACTO_INTENT_TOKEN_ISSUER_MISMATCH'
|
|
88
|
+
| 'FACTO_INTENT_TOKEN_AUDIENCE_MISMATCH'
|
|
89
|
+
| 'FACTO_INTENT_TOKEN_EXPIRED'
|
|
90
|
+
| 'FACTO_INTENT_TOKEN_CLAIMS_INVALID'
|
|
91
|
+
|
|
92
|
+
export class FactoIntentTokenError extends Error {
|
|
93
|
+
readonly code: FactoIntentTokenErrorCode
|
|
94
|
+
readonly details?: unknown
|
|
95
|
+
|
|
96
|
+
constructor(
|
|
97
|
+
code: FactoIntentTokenErrorCode,
|
|
98
|
+
message: string,
|
|
99
|
+
options: { details?: unknown } = {},
|
|
100
|
+
) {
|
|
101
|
+
super(message)
|
|
102
|
+
this.name = 'FactoIntentTokenError'
|
|
103
|
+
this.code = code
|
|
104
|
+
this.details = options.details
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const DEFAULT_INTENT_TOKEN_ISSUER = 'facto'
|
|
109
|
+
const INTENT_JWKS_DEFAULT_ORIGINS = {
|
|
110
|
+
dev: 'https://dev-api.facto.to',
|
|
111
|
+
sandbox: 'https://dev-api.facto.to',
|
|
112
|
+
production: 'https://api.facto.to',
|
|
113
|
+
} as const
|
|
114
|
+
|
|
115
|
+
type IntentJwksEnvironment = keyof typeof INTENT_JWKS_DEFAULT_ORIGINS
|
|
116
|
+
|
|
117
|
+
const CARD_INTENT_ENVIRONMENTS: readonly IntentJwksEnvironment[] = ['dev', 'production']
|
|
118
|
+
const CONNECT_INTENT_ENVIRONMENTS: readonly IntentJwksEnvironment[] = ['dev', 'sandbox', 'production']
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Verify a Facto-issued Card connect intent token.
|
|
122
|
+
*
|
|
123
|
+
* Validates the Ed25519 signature against the Facto JWKS, enforces `iss` / `aud`
|
|
124
|
+
* / `exp`, accepts `program_id` or `program_ref` in JWS claims, and returns the
|
|
125
|
+
* verified claims. Failures throw {@link FactoIntentTokenError}, not `CardError`:
|
|
126
|
+
* this is local token verification, not an Engine request outcome.
|
|
127
|
+
*/
|
|
128
|
+
export function verifyCardIntentToken(input: VerifyCardIntentTokenInput): Promise<VerifiedCardIntentToken> {
|
|
129
|
+
return verifyIntentToken(input, CARD_INTENT_ENVIRONMENTS)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Merchant connect server variant of {@link verifyCardIntentToken} that also
|
|
134
|
+
* accepts `environment: 'sandbox'` (an alias of `dev`).
|
|
135
|
+
*/
|
|
136
|
+
export function verifyCardIntentTokenForConnect(input: ConnectVerifyCardIntentTokenInput): Promise<VerifiedCardIntentToken> {
|
|
137
|
+
return verifyIntentToken(input, CONNECT_INTENT_ENVIRONMENTS)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function verifyIntentToken(
|
|
141
|
+
input: ConnectVerifyCardIntentTokenInput,
|
|
142
|
+
environments: readonly IntentJwksEnvironment[],
|
|
143
|
+
): Promise<VerifiedCardIntentToken> {
|
|
144
|
+
if (input === null || typeof input !== 'object') {
|
|
145
|
+
throw new FactoIntentTokenError(
|
|
146
|
+
'FACTO_INTENT_TOKEN_INPUT_INVALID',
|
|
147
|
+
'verifyCardIntentToken requires an input object',
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
const intentToken = requireIntentTokenString(input.intentToken, 'intentToken')
|
|
151
|
+
const audience = requireIntentTokenString(input.audience, 'audience')
|
|
152
|
+
const issuer =
|
|
153
|
+
input.issuer === undefined
|
|
154
|
+
? DEFAULT_INTENT_TOKEN_ISSUER
|
|
155
|
+
: requireIntentTokenString(input.issuer, 'issuer')
|
|
156
|
+
const clockToleranceSeconds = resolveClockTolerance(input.clockToleranceSeconds)
|
|
157
|
+
const nowSeconds = Math.floor(resolveVerificationNowMs(input.nowMs) / 1000)
|
|
158
|
+
|
|
159
|
+
const { headerB64, payloadB64, signature } = splitCompactJws(intentToken)
|
|
160
|
+
const header = asIntentTokenRecord(
|
|
161
|
+
decodeIntentTokenSegment(headerB64, 'header'),
|
|
162
|
+
'FACTO_INTENT_TOKEN_MALFORMED',
|
|
163
|
+
'intent token header',
|
|
164
|
+
)
|
|
165
|
+
if (header.alg !== 'EdDSA') {
|
|
166
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_UNSUPPORTED_ALG', 'intent token JWS alg must be EdDSA', {
|
|
167
|
+
details: { alg: header.alg },
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
const kid = typeof header.kid === 'string' ? header.kid : undefined
|
|
171
|
+
|
|
172
|
+
const jwksSource = resolveDefaultIntentJwksInput(input, environments)
|
|
173
|
+
const jwks = await resolveIntentTokenJwks(jwksSource)
|
|
174
|
+
const keys = selectIntentTokenKeys(jwks, kid)
|
|
175
|
+
|
|
176
|
+
const signingInput = utf8ToBytes(`${headerB64}.${payloadB64}`)
|
|
177
|
+
const verified = await verifyIntentTokenSignature(signingInput, signature, keys)
|
|
178
|
+
if (!verified) {
|
|
179
|
+
throw new FactoIntentTokenError(
|
|
180
|
+
'FACTO_INTENT_TOKEN_SIGNATURE_INVALID',
|
|
181
|
+
'intent token signature does not verify against the Facto JWKS',
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const claims = parseIntentTokenClaims(decodeIntentTokenSegment(payloadB64, 'payload'))
|
|
186
|
+
if (claims.iss !== issuer) {
|
|
187
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_ISSUER_MISMATCH', 'intent token issuer mismatch', {
|
|
188
|
+
details: { expected: issuer, actual: claims.iss },
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
if (claims.aud !== audience) {
|
|
192
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_AUDIENCE_MISMATCH', 'intent token audience mismatch', {
|
|
193
|
+
details: { expected: audience, actual: claims.aud },
|
|
194
|
+
})
|
|
195
|
+
}
|
|
196
|
+
if (nowSeconds > claims.exp + clockToleranceSeconds) {
|
|
197
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_EXPIRED', 'intent token has expired', {
|
|
198
|
+
details: { exp: claims.exp, now: nowSeconds },
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
programId: claims.program_id,
|
|
204
|
+
pairwiseSubject: claims.sub,
|
|
205
|
+
nonce: claims.nonce,
|
|
206
|
+
expiresAt: new Date(claims.exp * 1000).toISOString(),
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
interface IntentTokenClaims {
|
|
211
|
+
iss: string
|
|
212
|
+
aud: string
|
|
213
|
+
sub: string
|
|
214
|
+
program_id: string
|
|
215
|
+
nonce: string
|
|
216
|
+
iat: number
|
|
217
|
+
exp: number
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function resolveDefaultIntentJwksInput(
|
|
221
|
+
input: ConnectVerifyCardIntentTokenInput,
|
|
222
|
+
environments: readonly IntentJwksEnvironment[],
|
|
223
|
+
): CardIntentJwksInput {
|
|
224
|
+
if (input.jwks !== undefined && input.jwks !== null) return input.jwks
|
|
225
|
+
if (typeof input.apiBaseUrl === 'string' && input.apiBaseUrl.length > 0) {
|
|
226
|
+
let parsed: URL
|
|
227
|
+
try {
|
|
228
|
+
parsed = new URL(input.apiBaseUrl)
|
|
229
|
+
} catch {
|
|
230
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', `apiBaseUrl is not a valid URL: ${input.apiBaseUrl}`)
|
|
231
|
+
}
|
|
232
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash || (parsed.pathname !== '/' && parsed.pathname !== '')) {
|
|
233
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', 'apiBaseUrl must be a bare origin without path, query, or credentials')
|
|
234
|
+
}
|
|
235
|
+
return `${parsed.origin}${CARD_INTENT_JWKS_PATH}`
|
|
236
|
+
}
|
|
237
|
+
if (input.environment !== undefined) {
|
|
238
|
+
const environment = environments.find((candidate) => candidate === input.environment)
|
|
239
|
+
if (environment === undefined) {
|
|
240
|
+
throw new FactoIntentTokenError(
|
|
241
|
+
'FACTO_INTENT_TOKEN_INPUT_INVALID',
|
|
242
|
+
`environment must be one of ${environments.map((candidate) => `'${candidate}'`).join(', ')}`,
|
|
243
|
+
)
|
|
244
|
+
}
|
|
245
|
+
return `${INTENT_JWKS_DEFAULT_ORIGINS[environment]}${CARD_INTENT_JWKS_PATH}`
|
|
246
|
+
}
|
|
247
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_INPUT_INVALID', 'jwks, apiBaseUrl, or environment is required')
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function splitCompactJws(token: string): {
|
|
251
|
+
headerB64: string
|
|
252
|
+
payloadB64: string
|
|
253
|
+
signature: Uint8Array<ArrayBuffer>
|
|
254
|
+
} {
|
|
255
|
+
const segments = token.split('.')
|
|
256
|
+
if (segments.length !== 3) {
|
|
257
|
+
throw new FactoIntentTokenError(
|
|
258
|
+
'FACTO_INTENT_TOKEN_MALFORMED',
|
|
259
|
+
'intent token is not a compact JWS (expected three segments)',
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
const [headerB64, payloadB64, signatureB64] = segments
|
|
263
|
+
if (!headerB64 || !payloadB64 || !signatureB64) {
|
|
264
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_MALFORMED', 'intent token has an empty JWS segment')
|
|
265
|
+
}
|
|
266
|
+
return { headerB64, payloadB64, signature: base64UrlToBytes(signatureB64, 'signature') }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function decodeIntentTokenSegment(segment: string, label: string): unknown {
|
|
270
|
+
const text = new TextDecoder().decode(base64UrlToBytes(segment, label))
|
|
271
|
+
try {
|
|
272
|
+
return JSON.parse(text)
|
|
273
|
+
} catch (error) {
|
|
274
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_MALFORMED', `intent token ${label} is not valid JSON`, {
|
|
275
|
+
details: error,
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function resolveIntentTokenJwks(
|
|
281
|
+
input: CardIntentJwksInput,
|
|
282
|
+
): Promise<CardIntentJwks> {
|
|
283
|
+
if (typeof input === 'function') {
|
|
284
|
+
return normalizeIntentTokenJwks(await input())
|
|
285
|
+
}
|
|
286
|
+
if (typeof input === 'string') {
|
|
287
|
+
return normalizeIntentTokenJwks(await fetchIntentTokenJwks(input))
|
|
288
|
+
}
|
|
289
|
+
return normalizeIntentTokenJwks(input)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Give up on a JWKS endpoint rather than hang the partner's request path. */
|
|
293
|
+
const INTENT_TOKEN_JWKS_TIMEOUT_MS = 5_000
|
|
294
|
+
|
|
295
|
+
/** A Facto JWKS is a few hundred bytes; anything past this is not one. */
|
|
296
|
+
const INTENT_TOKEN_JWKS_MAX_BYTES = 64 * 1024
|
|
297
|
+
|
|
298
|
+
async function fetchIntentTokenJwks(url: string): Promise<unknown> {
|
|
299
|
+
let parsed: URL
|
|
300
|
+
try {
|
|
301
|
+
parsed = new URL(url)
|
|
302
|
+
} catch {
|
|
303
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', `JWKS url is not a valid URL: ${url}`)
|
|
304
|
+
}
|
|
305
|
+
if (parsed.protocol !== 'https:') {
|
|
306
|
+
throw new FactoIntentTokenError(
|
|
307
|
+
'FACTO_INTENT_TOKEN_JWKS_INVALID',
|
|
308
|
+
`JWKS url must use https: (got ${parsed.protocol})`,
|
|
309
|
+
{ details: { protocol: parsed.protocol } },
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const controller = new AbortController()
|
|
314
|
+
const timer = setTimeout(() => controller.abort(), INTENT_TOKEN_JWKS_TIMEOUT_MS)
|
|
315
|
+
let response: Response
|
|
316
|
+
let body: string
|
|
317
|
+
try {
|
|
318
|
+
try {
|
|
319
|
+
response = await fetch(url, {
|
|
320
|
+
method: 'GET',
|
|
321
|
+
headers: { accept: 'application/json' },
|
|
322
|
+
redirect: 'follow',
|
|
323
|
+
signal: controller.signal,
|
|
324
|
+
})
|
|
325
|
+
} catch (error) {
|
|
326
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', `failed to fetch Facto JWKS from ${url}`, {
|
|
327
|
+
details: error,
|
|
328
|
+
})
|
|
329
|
+
}
|
|
330
|
+
if (!response.ok) {
|
|
331
|
+
throw new FactoIntentTokenError(
|
|
332
|
+
'FACTO_INTENT_TOKEN_JWKS_INVALID',
|
|
333
|
+
`Facto JWKS request failed with status ${response.status}`,
|
|
334
|
+
{ details: { status: response.status } },
|
|
335
|
+
)
|
|
336
|
+
}
|
|
337
|
+
const declaredLength = Number(response.headers.get('content-length'))
|
|
338
|
+
if (Number.isFinite(declaredLength) && declaredLength > INTENT_TOKEN_JWKS_MAX_BYTES) {
|
|
339
|
+
throw new FactoIntentTokenError(
|
|
340
|
+
'FACTO_INTENT_TOKEN_JWKS_INVALID',
|
|
341
|
+
`Facto JWKS response exceeds ${INTENT_TOKEN_JWKS_MAX_BYTES} bytes`,
|
|
342
|
+
{ details: { contentLength: declaredLength } },
|
|
343
|
+
)
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
body = await response.text()
|
|
347
|
+
} catch (error) {
|
|
348
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', 'Facto JWKS response could not be read', {
|
|
349
|
+
details: error,
|
|
350
|
+
})
|
|
351
|
+
}
|
|
352
|
+
} finally {
|
|
353
|
+
clearTimeout(timer)
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
if (body.length > INTENT_TOKEN_JWKS_MAX_BYTES) {
|
|
357
|
+
throw new FactoIntentTokenError(
|
|
358
|
+
'FACTO_INTENT_TOKEN_JWKS_INVALID',
|
|
359
|
+
`Facto JWKS response exceeds ${INTENT_TOKEN_JWKS_MAX_BYTES} bytes`,
|
|
360
|
+
{ details: { bytes: body.length } },
|
|
361
|
+
)
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
return JSON.parse(body)
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', 'Facto JWKS response was not valid JSON', {
|
|
367
|
+
details: error,
|
|
368
|
+
})
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function normalizeIntentTokenJwks(raw: unknown): CardIntentJwks {
|
|
373
|
+
const record = asIntentTokenRecord(raw, 'FACTO_INTENT_TOKEN_JWKS_INVALID', 'JWKS')
|
|
374
|
+
if (!Array.isArray(record.keys)) {
|
|
375
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_JWKS_INVALID', 'JWKS "keys" must be an array')
|
|
376
|
+
}
|
|
377
|
+
return { keys: record.keys.map(normalizeIntentTokenJwk) }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function normalizeIntentTokenJwk(raw: unknown): CardIntentJwk {
|
|
381
|
+
const record = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {}
|
|
382
|
+
return {
|
|
383
|
+
kty: typeof record.kty === 'string' ? record.kty : '',
|
|
384
|
+
crv: typeof record.crv === 'string' ? record.crv : '',
|
|
385
|
+
x: typeof record.x === 'string' ? record.x : '',
|
|
386
|
+
...(typeof record.kid === 'string' ? { kid: record.kid } : {}),
|
|
387
|
+
...(typeof record.alg === 'string' ? { alg: record.alg } : {}),
|
|
388
|
+
...(typeof record.use === 'string' ? { use: record.use } : {}),
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function selectIntentTokenKeys(
|
|
393
|
+
jwks: CardIntentJwks,
|
|
394
|
+
kid: string | undefined,
|
|
395
|
+
): CardIntentJwk[] {
|
|
396
|
+
const usable = jwks.keys.filter(
|
|
397
|
+
(key) => key.kty === 'OKP' && key.crv === 'Ed25519' && key.x.length > 0,
|
|
398
|
+
)
|
|
399
|
+
if (usable.length === 0) {
|
|
400
|
+
throw new FactoIntentTokenError(
|
|
401
|
+
'FACTO_INTENT_TOKEN_JWKS_INVALID',
|
|
402
|
+
'Facto JWKS has no usable Ed25519 signing key',
|
|
403
|
+
)
|
|
404
|
+
}
|
|
405
|
+
if (kid !== undefined) {
|
|
406
|
+
const matched = usable.filter((key) => key.kid === kid)
|
|
407
|
+
if (matched.length > 0) return matched
|
|
408
|
+
}
|
|
409
|
+
return usable
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function verifyIntentTokenSignature(
|
|
413
|
+
signingInput: Uint8Array<ArrayBuffer>,
|
|
414
|
+
signature: Uint8Array<ArrayBuffer>,
|
|
415
|
+
keys: CardIntentJwk[],
|
|
416
|
+
): Promise<boolean> {
|
|
417
|
+
const subtle = resolveSubtleCrypto()
|
|
418
|
+
for (const jwk of keys) {
|
|
419
|
+
let key: CryptoKey
|
|
420
|
+
try {
|
|
421
|
+
key = await subtle.importKey(
|
|
422
|
+
'jwk',
|
|
423
|
+
{ kty: 'OKP', crv: 'Ed25519', x: jwk.x },
|
|
424
|
+
{ name: 'Ed25519' },
|
|
425
|
+
false,
|
|
426
|
+
['verify'],
|
|
427
|
+
)
|
|
428
|
+
} catch {
|
|
429
|
+
continue
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
if (await subtle.verify({ name: 'Ed25519' }, key, signature, signingInput)) return true
|
|
433
|
+
} catch {
|
|
434
|
+
continue
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return false
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function parseIntentTokenClaims(payload: unknown): IntentTokenClaims {
|
|
441
|
+
const record = asIntentTokenRecord(payload, 'FACTO_INTENT_TOKEN_CLAIMS_INVALID', 'intent token claims')
|
|
442
|
+
const rawProgramId = record.program_id
|
|
443
|
+
const rawProgramRef = record.program_ref
|
|
444
|
+
if (
|
|
445
|
+
typeof rawProgramId === 'string' && rawProgramId.length > 0
|
|
446
|
+
&& typeof rawProgramRef === 'string' && rawProgramRef.length > 0
|
|
447
|
+
&& rawProgramId !== rawProgramRef
|
|
448
|
+
) {
|
|
449
|
+
throw new FactoIntentTokenError(
|
|
450
|
+
'FACTO_INTENT_TOKEN_CLAIMS_INVALID',
|
|
451
|
+
'intent token claims "program_id" and "program_ref" must match when both are present',
|
|
452
|
+
)
|
|
453
|
+
}
|
|
454
|
+
const programId = typeof rawProgramId === 'string' && rawProgramId.length > 0
|
|
455
|
+
? rawProgramId
|
|
456
|
+
: readClaimString(record, 'program_ref')
|
|
457
|
+
return {
|
|
458
|
+
iss: readClaimString(record, 'iss'),
|
|
459
|
+
aud: readClaimString(record, 'aud'),
|
|
460
|
+
sub: readClaimString(record, 'sub'),
|
|
461
|
+
program_id: programId,
|
|
462
|
+
nonce: readClaimString(record, 'nonce'),
|
|
463
|
+
iat: readClaimNumber(record, 'iat'),
|
|
464
|
+
exp: readClaimNumber(record, 'exp'),
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function requireIntentTokenString(value: unknown, field: string): string {
|
|
469
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
470
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_INPUT_INVALID', `${field} must be a non-empty string`)
|
|
471
|
+
}
|
|
472
|
+
return value
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function resolveClockTolerance(value: number | undefined): number {
|
|
476
|
+
if (value === undefined) return 0
|
|
477
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
|
|
478
|
+
throw new FactoIntentTokenError(
|
|
479
|
+
'FACTO_INTENT_TOKEN_INPUT_INVALID',
|
|
480
|
+
'clockToleranceSeconds must be a non-negative finite number',
|
|
481
|
+
)
|
|
482
|
+
}
|
|
483
|
+
return value
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function resolveVerificationNowMs(now: number | Date | undefined): number {
|
|
487
|
+
if (now === undefined) return Date.now()
|
|
488
|
+
if (now instanceof Date) {
|
|
489
|
+
const ms = now.getTime()
|
|
490
|
+
if (Number.isNaN(ms)) {
|
|
491
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_INPUT_INVALID', 'nowMs is an invalid Date')
|
|
492
|
+
}
|
|
493
|
+
return ms
|
|
494
|
+
}
|
|
495
|
+
if (typeof now === 'number' && Number.isFinite(now)) return now
|
|
496
|
+
throw new FactoIntentTokenError(
|
|
497
|
+
'FACTO_INTENT_TOKEN_INPUT_INVALID',
|
|
498
|
+
'nowMs must be a Date or unix milliseconds number',
|
|
499
|
+
)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function asIntentTokenRecord(
|
|
503
|
+
value: unknown,
|
|
504
|
+
code: FactoIntentTokenErrorCode,
|
|
505
|
+
label: string,
|
|
506
|
+
): Record<string, unknown> {
|
|
507
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
508
|
+
throw new FactoIntentTokenError(code, `${label} must be a JSON object`)
|
|
509
|
+
}
|
|
510
|
+
return value as Record<string, unknown>
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function readClaimString(record: Record<string, unknown>, key: string): string {
|
|
514
|
+
const value = record[key]
|
|
515
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
516
|
+
throw new FactoIntentTokenError(
|
|
517
|
+
'FACTO_INTENT_TOKEN_CLAIMS_INVALID',
|
|
518
|
+
`intent token claim "${key}" must be a non-empty string`,
|
|
519
|
+
)
|
|
520
|
+
}
|
|
521
|
+
return value
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function readClaimNumber(record: Record<string, unknown>, key: string): number {
|
|
525
|
+
const value = record[key]
|
|
526
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
527
|
+
throw new FactoIntentTokenError(
|
|
528
|
+
'FACTO_INTENT_TOKEN_CLAIMS_INVALID',
|
|
529
|
+
`intent token claim "${key}" must be a finite number`,
|
|
530
|
+
)
|
|
531
|
+
}
|
|
532
|
+
return value
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function base64UrlToBytes(value: string, label: string): Uint8Array<ArrayBuffer> {
|
|
536
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value)) {
|
|
537
|
+
throw new FactoIntentTokenError('FACTO_INTENT_TOKEN_MALFORMED', `intent token ${label} is not valid base64url`)
|
|
538
|
+
}
|
|
539
|
+
const base64 = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (value.length % 4)) % 4)
|
|
540
|
+
return base64ToBytes(base64, label)
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function base64ToBytes(base64: string, label: string): Uint8Array<ArrayBuffer> {
|
|
544
|
+
const maybeAtob = (globalThis as typeof globalThis & { atob?: (input: string) => string }).atob
|
|
545
|
+
if (maybeAtob) {
|
|
546
|
+
let binary: string
|
|
547
|
+
try {
|
|
548
|
+
binary = maybeAtob(base64)
|
|
549
|
+
} catch (error) {
|
|
550
|
+
throw new FactoIntentTokenError(
|
|
551
|
+
'FACTO_INTENT_TOKEN_MALFORMED',
|
|
552
|
+
`intent token ${label} is not valid base64url`,
|
|
553
|
+
{ details: error },
|
|
554
|
+
)
|
|
555
|
+
}
|
|
556
|
+
const bytes = new Uint8Array(binary.length)
|
|
557
|
+
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
|
|
558
|
+
return bytes
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const maybeBuffer = (
|
|
562
|
+
globalThis as typeof globalThis & {
|
|
563
|
+
Buffer?: { from(input: string, encoding: 'base64'): Uint8Array }
|
|
564
|
+
}
|
|
565
|
+
).Buffer
|
|
566
|
+
if (maybeBuffer) return new Uint8Array(maybeBuffer.from(base64, 'base64'))
|
|
567
|
+
|
|
568
|
+
throw new FactoIntentTokenError(
|
|
569
|
+
'FACTO_INTENT_TOKEN_INPUT_INVALID',
|
|
570
|
+
'No base64 decoder is available in this runtime',
|
|
571
|
+
)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function utf8ToBytes(value: string): Uint8Array<ArrayBuffer> {
|
|
575
|
+
const encoded = new TextEncoder().encode(value)
|
|
576
|
+
const bytes = new Uint8Array(encoded.length)
|
|
577
|
+
bytes.set(encoded)
|
|
578
|
+
return bytes
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function resolveSubtleCrypto(): SubtleCrypto {
|
|
582
|
+
const cryptoRef = (globalThis as typeof globalThis & { crypto?: Crypto }).crypto
|
|
583
|
+
if (cryptoRef?.subtle) return cryptoRef.subtle
|
|
584
|
+
throw new FactoIntentTokenError(
|
|
585
|
+
'FACTO_INTENT_TOKEN_INPUT_INVALID',
|
|
586
|
+
'Web Crypto (crypto.subtle) is not available in this runtime',
|
|
587
|
+
)
|
|
588
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { AuthorizationLookupClientInput, CardAuthorizationsApi, AuthorizationLookupResult } from './card-client'
|
|
2
|
+
|
|
3
|
+
export interface AuthorizationPollingOptions {
|
|
4
|
+
readonly deadlineEpochMs: number
|
|
5
|
+
readonly intervalMs: number
|
|
6
|
+
readonly maxIntervalMs: number
|
|
7
|
+
readonly backoffFactor: number
|
|
8
|
+
readonly signal?: AbortSignal
|
|
9
|
+
readonly nowMs?: () => number
|
|
10
|
+
readonly sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type AuthorizationPollingResult =
|
|
14
|
+
| { readonly status: 'resolved'; readonly result: AuthorizationLookupResult }
|
|
15
|
+
| { readonly status: 'poll_deadline_exceeded' }
|
|
16
|
+
|
|
17
|
+
function defaultSleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
|
|
18
|
+
return new Promise((resolve, reject) => {
|
|
19
|
+
if (signal?.aborted) { reject(signal.reason); return }
|
|
20
|
+
const abort = () => { clearTimeout(timer); reject(signal!.reason) }
|
|
21
|
+
const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve() }, milliseconds)
|
|
22
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Poll the original lookup criteria; no authorization is submitted or retried. */
|
|
27
|
+
export async function pollAuthorization(
|
|
28
|
+
client: { readonly authorizations: Pick<CardAuthorizationsApi, 'lookup'> },
|
|
29
|
+
input: AuthorizationLookupClientInput,
|
|
30
|
+
options: AuthorizationPollingOptions,
|
|
31
|
+
): Promise<AuthorizationPollingResult> {
|
|
32
|
+
const { deadlineEpochMs, intervalMs, maxIntervalMs, backoffFactor, signal } = options
|
|
33
|
+
if (!Number.isFinite(deadlineEpochMs) || !Number.isFinite(intervalMs) || !Number.isFinite(maxIntervalMs) ||
|
|
34
|
+
!Number.isFinite(backoffFactor) || intervalMs < 1 || maxIntervalMs < intervalMs || maxIntervalMs > 2_147_483_647 || backoffFactor < 1 || backoffFactor > 10) throw new RangeError('invalid_polling_options')
|
|
35
|
+
const now = options.nowMs ?? Date.now
|
|
36
|
+
const sleep = options.sleep ?? defaultSleep
|
|
37
|
+
if (deadlineEpochMs - now() > 2_147_483_647) throw new RangeError('invalid_polling_deadline')
|
|
38
|
+
let interval = intervalMs
|
|
39
|
+
while (true) {
|
|
40
|
+
signal?.throwIfAborted()
|
|
41
|
+
if (now() >= deadlineEpochMs) return { status: 'poll_deadline_exceeded' }
|
|
42
|
+
const controller = new AbortController()
|
|
43
|
+
const deadlineReason = Symbol('poll_deadline_exceeded')
|
|
44
|
+
const forwardAbort = () => controller.abort(signal?.reason)
|
|
45
|
+
signal?.addEventListener('abort', forwardAbort, { once: true })
|
|
46
|
+
const timer = setTimeout(() => controller.abort(deadlineReason), Math.min(deadlineEpochMs - now(), 2_147_483_647))
|
|
47
|
+
let onAbort!: () => void
|
|
48
|
+
const cancelled = new Promise<never>((_, reject) => {
|
|
49
|
+
onAbort = () => reject(controller.signal.reason)
|
|
50
|
+
controller.signal.addEventListener('abort', onAbort, { once: true })
|
|
51
|
+
})
|
|
52
|
+
let result: AuthorizationLookupResult
|
|
53
|
+
try {
|
|
54
|
+
result = await Promise.race([client.authorizations.lookup(input, { signal: controller.signal }), cancelled])
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error === deadlineReason) return { status: 'poll_deadline_exceeded' }
|
|
57
|
+
throw error
|
|
58
|
+
} finally {
|
|
59
|
+
clearTimeout(timer)
|
|
60
|
+
controller.signal.removeEventListener('abort', onAbort)
|
|
61
|
+
signal?.removeEventListener('abort', forwardAbort)
|
|
62
|
+
}
|
|
63
|
+
signal?.throwIfAborted()
|
|
64
|
+
if (now() >= deadlineEpochMs) return { status: 'poll_deadline_exceeded' }
|
|
65
|
+
if (result.resolution === 'resolved') return { status: 'resolved', result }
|
|
66
|
+
await sleep(Math.min(interval, deadlineEpochMs - now()), signal)
|
|
67
|
+
interval = Math.min(maxIntervalMs, interval * backoffFactor)
|
|
68
|
+
}
|
|
69
|
+
}
|