authfn 0.1.2 → 0.2.0
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/README.md +167 -292
- package/dist/core/account-linking.d.ts +30 -0
- package/dist/core/account-linking.d.ts.map +1 -0
- package/dist/core/account-linking.js +80 -0
- package/dist/core/account-linking.js.map +1 -0
- package/dist/core/account.d.ts +38 -0
- package/dist/core/account.d.ts.map +1 -0
- package/dist/core/account.js +164 -0
- package/dist/core/account.js.map +1 -0
- package/dist/core/admin-users.d.ts +50 -0
- package/dist/core/admin-users.d.ts.map +1 -0
- package/dist/core/admin-users.js +227 -0
- package/dist/core/admin-users.js.map +1 -0
- package/dist/core/api-keys.d.ts +40 -0
- package/dist/core/api-keys.d.ts.map +1 -0
- package/dist/core/api-keys.js +165 -0
- package/dist/core/api-keys.js.map +1 -0
- package/dist/core/cache.d.ts +18 -0
- package/dist/core/cache.d.ts.map +1 -0
- package/dist/core/cache.js +54 -0
- package/dist/core/cache.js.map +1 -0
- package/dist/core/cookies.d.ts +25 -0
- package/dist/core/cookies.d.ts.map +1 -0
- package/dist/core/cookies.js +89 -0
- package/dist/core/cookies.js.map +1 -0
- package/dist/core/delivery.d.ts +4 -0
- package/dist/core/delivery.d.ts.map +1 -0
- package/dist/core/delivery.js +37 -0
- package/dist/core/delivery.js.map +1 -0
- package/dist/core/environment.d.ts +4 -0
- package/dist/core/environment.d.ts.map +1 -0
- package/dist/core/environment.js +50 -0
- package/dist/core/environment.js.map +1 -0
- package/dist/core/errors.d.ts +120 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +428 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/gateway-routing.d.ts +88 -0
- package/dist/core/gateway-routing.d.ts.map +1 -0
- package/dist/core/gateway-routing.js +902 -0
- package/dist/core/gateway-routing.js.map +1 -0
- package/dist/core/oauth-accounts.d.ts +29 -0
- package/dist/core/oauth-accounts.d.ts.map +1 -0
- package/dist/core/oauth-accounts.js +104 -0
- package/dist/core/oauth-accounts.js.map +1 -0
- package/dist/core/observability.d.ts +4 -0
- package/dist/core/observability.d.ts.map +1 -0
- package/dist/core/observability.js +38 -0
- package/dist/core/observability.js.map +1 -0
- package/dist/core/passwords.d.ts +52 -0
- package/dist/core/passwords.d.ts.map +1 -0
- package/dist/core/passwords.js +449 -0
- package/dist/core/passwords.js.map +1 -0
- package/dist/core/plugin-runtime.d.ts +8 -0
- package/dist/core/plugin-runtime.d.ts.map +1 -0
- package/dist/core/plugin-runtime.js +15 -0
- package/dist/core/plugin-runtime.js.map +1 -0
- package/dist/core/rate-limit.d.ts +4 -0
- package/dist/core/rate-limit.d.ts.map +1 -0
- package/dist/core/rate-limit.js +177 -0
- package/dist/core/rate-limit.js.map +1 -0
- package/dist/core/regions.d.ts +47 -0
- package/dist/core/regions.d.ts.map +1 -0
- package/dist/core/regions.js +620 -0
- package/dist/core/regions.js.map +1 -0
- package/dist/core/session-responses.d.ts +10 -0
- package/dist/core/session-responses.d.ts.map +1 -0
- package/dist/core/session-responses.js +22 -0
- package/dist/core/session-responses.js.map +1 -0
- package/dist/core/sessions.d.ts +50 -0
- package/dist/core/sessions.d.ts.map +1 -0
- package/dist/core/sessions.js +421 -0
- package/dist/core/sessions.js.map +1 -0
- package/dist/core/two-factor.d.ts +34 -0
- package/dist/core/two-factor.d.ts.map +1 -0
- package/dist/core/two-factor.js +494 -0
- package/dist/core/two-factor.js.map +1 -0
- package/dist/core/users.d.ts +12 -0
- package/dist/core/users.d.ts.map +1 -0
- package/dist/core/users.js +71 -0
- package/dist/core/users.js.map +1 -0
- package/dist/core/verifications.d.ts +52 -0
- package/dist/core/verifications.d.ts.map +1 -0
- package/dist/core/verifications.js +521 -0
- package/dist/core/verifications.js.map +1 -0
- package/dist/http/envelopes.d.ts +10 -0
- package/dist/http/envelopes.d.ts.map +1 -0
- package/dist/http/envelopes.js +99 -0
- package/dist/http/envelopes.js.map +1 -0
- package/dist/http/router.d.ts +16 -0
- package/dist/http/router.d.ts.map +1 -0
- package/dist/http/router.js +347 -0
- package/dist/http/router.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +106 -0
- package/dist/index.js.map +1 -0
- package/dist/openapi.d.ts +4 -0
- package/dist/openapi.d.ts.map +1 -0
- package/dist/openapi.js +43 -0
- package/dist/openapi.js.map +1 -0
- package/dist/plugin-runner.d.ts +12 -0
- package/dist/plugin-runner.d.ts.map +1 -0
- package/dist/plugin-runner.js +206 -0
- package/dist/plugin-runner.js.map +1 -0
- package/dist/plugin-types.d.ts +205 -0
- package/dist/plugin-types.d.ts.map +1 -0
- package/dist/plugin-types.js +2 -0
- package/dist/plugin-types.js.map +1 -0
- package/dist/schema.d.ts +7 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +120 -0
- package/dist/schema.js.map +1 -0
- package/dist/types.d.ts +444 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +85 -59
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { AuthFnConfigError, AuthFnPlacementDirectoryUnavailableError, AuthFnPlacementMovingError, AuthFnRegionMismatchError, AuthFnRegionNotFoundError, AuthFnRoutingAssertionInvalidError, AuthFnRoutingCellUnavailableError, AuthFnValidationError } from './errors.js';
|
|
3
|
+
import { jsonError, resolveRequestId } from '../http/envelopes.js';
|
|
4
|
+
import { emitAuthEvent, eventRequestId } from './observability.js';
|
|
5
|
+
const ASSERTION_HEADER = 'x-authfn-routing-assertion';
|
|
6
|
+
const MISMATCH_HEADER = 'x-authfn-routing-mismatch';
|
|
7
|
+
const INTERNAL_HEADER_PREFIX = 'x-authfn-routing-';
|
|
8
|
+
const PLACEMENT_KEY_PREFIX = 'authfn:placement:';
|
|
9
|
+
const verifiedRoutingIdentityKeys = new WeakMap();
|
|
10
|
+
export function createInMemoryAuthFnPlacementDirectory(initial = []) {
|
|
11
|
+
for (const record of initial)
|
|
12
|
+
validatePlacement(record);
|
|
13
|
+
const records = new Map(initial.map((record) => [record.identityKey, clonePlacement(record)]));
|
|
14
|
+
return {
|
|
15
|
+
async get(identityKey) {
|
|
16
|
+
const record = records.get(identityKey);
|
|
17
|
+
return record ? clonePlacement(record) : null;
|
|
18
|
+
},
|
|
19
|
+
async putIfAbsent(placement) {
|
|
20
|
+
validatePlacement(placement);
|
|
21
|
+
const existing = records.get(placement.identityKey);
|
|
22
|
+
if (existing)
|
|
23
|
+
return { inserted: false, existing: clonePlacement(existing) };
|
|
24
|
+
records.set(placement.identityKey, clonePlacement(placement));
|
|
25
|
+
return { inserted: true };
|
|
26
|
+
},
|
|
27
|
+
async compareAndSet(input) {
|
|
28
|
+
validatePlacement(input.placement);
|
|
29
|
+
if (input.placement.identityKey !== input.identityKey) {
|
|
30
|
+
throw new AuthFnValidationError('Placement identity key must match the compare-and-set key');
|
|
31
|
+
}
|
|
32
|
+
const existing = records.get(input.identityKey);
|
|
33
|
+
if (!existing
|
|
34
|
+
|| existing.epoch !== input.expectedEpoch
|
|
35
|
+
|| existing.state !== input.expectedState) {
|
|
36
|
+
return { updated: false, existing: existing ? clonePlacement(existing) : undefined };
|
|
37
|
+
}
|
|
38
|
+
records.set(input.identityKey, clonePlacement(input.placement));
|
|
39
|
+
return { updated: true };
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Composes placement semantics over any atomic KV adapter, including the
|
|
45
|
+
* repository DynamoDB and Cloudflare Durable Object lookup-store adapters.
|
|
46
|
+
*/
|
|
47
|
+
export function createStoreBackedAuthFnPlacementDirectory(store) {
|
|
48
|
+
if (!store.compareAndSet) {
|
|
49
|
+
throw new AuthFnConfigError('AuthFn placement requires compareAndSet support');
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
async get(identityKey) {
|
|
53
|
+
return parsePlacement(await store.get(placementKey(identityKey)));
|
|
54
|
+
},
|
|
55
|
+
async putIfAbsent(placement) {
|
|
56
|
+
validatePlacement(placement);
|
|
57
|
+
const result = await store.setIfAbsent({
|
|
58
|
+
key: placementKey(placement.identityKey),
|
|
59
|
+
value: serializePlacement(placement)
|
|
60
|
+
});
|
|
61
|
+
return {
|
|
62
|
+
inserted: result.inserted,
|
|
63
|
+
existing: parsePlacement(result.existing) ?? undefined
|
|
64
|
+
};
|
|
65
|
+
},
|
|
66
|
+
async compareAndSet(input) {
|
|
67
|
+
validatePlacement(input.placement);
|
|
68
|
+
if (input.placement.identityKey !== input.identityKey) {
|
|
69
|
+
throw new AuthFnValidationError('Placement identity key must match the compare-and-set key');
|
|
70
|
+
}
|
|
71
|
+
const key = placementKey(input.identityKey);
|
|
72
|
+
const existingRaw = await store.get(key);
|
|
73
|
+
const existing = parsePlacement(existingRaw);
|
|
74
|
+
if (!existingRaw
|
|
75
|
+
|| !existing
|
|
76
|
+
|| existing.epoch !== input.expectedEpoch
|
|
77
|
+
|| existing.state !== input.expectedState) {
|
|
78
|
+
return { updated: false, existing: existing ?? undefined };
|
|
79
|
+
}
|
|
80
|
+
const result = await store.compareAndSet({
|
|
81
|
+
key,
|
|
82
|
+
expected: existingRaw,
|
|
83
|
+
value: serializePlacement(input.placement)
|
|
84
|
+
});
|
|
85
|
+
return {
|
|
86
|
+
updated: result.updated,
|
|
87
|
+
existing: parsePlacement(result.existing) ?? undefined
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export function createInMemoryAuthFnRoutingReplayStore(now = () => new Date()) {
|
|
93
|
+
const claims = new Map();
|
|
94
|
+
return {
|
|
95
|
+
async claim(nonce, expiresAt) {
|
|
96
|
+
const current = Math.floor(now().getTime() / 1000);
|
|
97
|
+
for (const [key, expiry] of claims) {
|
|
98
|
+
if (expiry < current)
|
|
99
|
+
claims.delete(key);
|
|
100
|
+
}
|
|
101
|
+
if (claims.has(nonce))
|
|
102
|
+
return false;
|
|
103
|
+
claims.set(nonce, expiresAt);
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export function classifyAuthFnRoute(request, basePath = '/auth') {
|
|
109
|
+
const path = stripBasePath(new URL(request.url).pathname, basePath);
|
|
110
|
+
if (request.method === 'GET'
|
|
111
|
+
&& (path === '/environment'
|
|
112
|
+
|| path === '/discovery'
|
|
113
|
+
|| path === '/.well-known'
|
|
114
|
+
|| path.startsWith('/.well-known/'))) {
|
|
115
|
+
return { scope: 'global', family: 'discovery' };
|
|
116
|
+
}
|
|
117
|
+
if (request.method === 'POST' && path === '/regions/lookup') {
|
|
118
|
+
return { scope: 'global', family: 'region-lookup' };
|
|
119
|
+
}
|
|
120
|
+
if (path.startsWith('/otp/') || path.includes('password/reset'))
|
|
121
|
+
return { scope: 'identity', family: 'otp' };
|
|
122
|
+
if (path.startsWith('/sessions') || path === '/session' || path === '/sign-out') {
|
|
123
|
+
return { scope: 'identity', family: 'session' };
|
|
124
|
+
}
|
|
125
|
+
if (path.startsWith('/api-keys'))
|
|
126
|
+
return { scope: 'identity', family: 'api-key' };
|
|
127
|
+
if (path.startsWith('/oauth') || path.startsWith('/social'))
|
|
128
|
+
return { scope: 'identity', family: 'oauth' };
|
|
129
|
+
if (path.startsWith('/handoff'))
|
|
130
|
+
return { scope: 'identity', family: 'handoff' };
|
|
131
|
+
if (path.startsWith('/account'))
|
|
132
|
+
return { scope: 'identity', family: 'account' };
|
|
133
|
+
return { scope: 'identity', family: 'auth' };
|
|
134
|
+
}
|
|
135
|
+
export function createAuthFnCanonicalGateway(options) {
|
|
136
|
+
validateKeyring(options.keyring);
|
|
137
|
+
const publicAuthority = normalizeAuthority(options.publicAuthority);
|
|
138
|
+
const basePath = normalizeBasePath(options.basePath ?? '/auth');
|
|
139
|
+
const now = options.now ?? (() => new Date());
|
|
140
|
+
const assertionTtlSeconds = options.assertionTtlSeconds ?? 20;
|
|
141
|
+
const placementCacheTtlMs = options.placementCacheTtlMs ?? 5_000;
|
|
142
|
+
const placementCacheMaxEntries = options.placementCacheMaxEntries ?? 10_000;
|
|
143
|
+
const clockSkewSeconds = options.clockSkewSeconds ?? 5;
|
|
144
|
+
if (!Number.isSafeInteger(assertionTtlSeconds) || assertionTtlSeconds < 1 || assertionTtlSeconds > 300) {
|
|
145
|
+
throw new AuthFnConfigError('AuthFn assertionTtlSeconds must be between 1 and 300');
|
|
146
|
+
}
|
|
147
|
+
if (!Number.isFinite(placementCacheTtlMs) || placementCacheTtlMs < 0) {
|
|
148
|
+
throw new AuthFnConfigError('AuthFn placementCacheTtlMs must be non-negative');
|
|
149
|
+
}
|
|
150
|
+
if (!Number.isSafeInteger(placementCacheMaxEntries) || placementCacheMaxEntries < 1) {
|
|
151
|
+
throw new AuthFnConfigError('AuthFn placementCacheMaxEntries must be a positive integer');
|
|
152
|
+
}
|
|
153
|
+
if (!Number.isSafeInteger(clockSkewSeconds) || clockSkewSeconds < 0 || clockSkewSeconds > 60) {
|
|
154
|
+
throw new AuthFnConfigError('AuthFn clockSkewSeconds must be between 0 and 60');
|
|
155
|
+
}
|
|
156
|
+
const cache = new Map();
|
|
157
|
+
function cachePlacement(identityKey, placement) {
|
|
158
|
+
const currentTime = now().getTime();
|
|
159
|
+
cache.delete(identityKey);
|
|
160
|
+
while (cache.size >= placementCacheMaxEntries) {
|
|
161
|
+
const oldest = cache.keys().next().value;
|
|
162
|
+
if (!oldest)
|
|
163
|
+
break;
|
|
164
|
+
cache.delete(oldest);
|
|
165
|
+
}
|
|
166
|
+
cache.set(identityKey, {
|
|
167
|
+
placement: clonePlacement(placement),
|
|
168
|
+
expiresAt: currentTime + placementCacheTtlMs
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
async function loadPlacement(identityKey, bypassCache) {
|
|
172
|
+
const cached = cache.get(identityKey);
|
|
173
|
+
if (!bypassCache && cached && cached.expiresAt > now().getTime())
|
|
174
|
+
return cached.placement;
|
|
175
|
+
let placement;
|
|
176
|
+
try {
|
|
177
|
+
placement = await options.placementDirectory.get(identityKey);
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
throw new AuthFnPlacementDirectoryUnavailableError();
|
|
181
|
+
}
|
|
182
|
+
if (placement)
|
|
183
|
+
cachePlacement(identityKey, placement);
|
|
184
|
+
else
|
|
185
|
+
cache.delete(identityKey);
|
|
186
|
+
return placement;
|
|
187
|
+
}
|
|
188
|
+
async function resolveOrClaimPlacement(identity, request, bypassCache) {
|
|
189
|
+
const existing = await loadPlacement(identity.identityKey, bypassCache);
|
|
190
|
+
if (existing)
|
|
191
|
+
return requireActivePlacement(existing);
|
|
192
|
+
if (!identity.allowInitialPlacement) {
|
|
193
|
+
throw new AuthFnRegionNotFoundError('Identity placement is not active');
|
|
194
|
+
}
|
|
195
|
+
let regionId;
|
|
196
|
+
try {
|
|
197
|
+
regionId = await options.selectInitialRegion({ identity, request });
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
throw new AuthFnRoutingCellUnavailableError('Initial region selection failed');
|
|
201
|
+
}
|
|
202
|
+
if (!regionId)
|
|
203
|
+
throw new AuthFnRoutingCellUnavailableError('Initial region selection returned no cell');
|
|
204
|
+
const claimed = {
|
|
205
|
+
identityKey: identity.identityKey,
|
|
206
|
+
regionId,
|
|
207
|
+
epoch: 1,
|
|
208
|
+
state: 'active',
|
|
209
|
+
updatedAt: now().toISOString()
|
|
210
|
+
};
|
|
211
|
+
let result;
|
|
212
|
+
try {
|
|
213
|
+
result = await options.placementDirectory.putIfAbsent(claimed);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
throw new AuthFnPlacementDirectoryUnavailableError();
|
|
217
|
+
}
|
|
218
|
+
const placement = result.inserted ? claimed : result.existing;
|
|
219
|
+
if (!placement)
|
|
220
|
+
throw new AuthFnPlacementDirectoryUnavailableError('Placement claim returned no record');
|
|
221
|
+
cachePlacement(identity.identityKey, placement);
|
|
222
|
+
await emit(options, request, result.inserted ? 'authfn.routing.placement_claimed' : 'authfn.routing.placement_lookup', {
|
|
223
|
+
outcome: result.inserted ? 'success' : 'validated',
|
|
224
|
+
regionId: placement.regionId,
|
|
225
|
+
epoch: placement.epoch
|
|
226
|
+
});
|
|
227
|
+
return requireActivePlacement(placement);
|
|
228
|
+
}
|
|
229
|
+
async function forward(request, identity, placement, attempt) {
|
|
230
|
+
let cell;
|
|
231
|
+
try {
|
|
232
|
+
cell = await options.resolveCell(placement.regionId);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
cell = null;
|
|
236
|
+
}
|
|
237
|
+
if (!cell || cell.regionId !== placement.regionId) {
|
|
238
|
+
await emit(options, request, 'authfn.routing.cell_unavailable', {
|
|
239
|
+
outcome: 'rejected',
|
|
240
|
+
regionId: placement.regionId,
|
|
241
|
+
epoch: placement.epoch
|
|
242
|
+
});
|
|
243
|
+
return jsonError(request, new AuthFnRoutingCellUnavailableError());
|
|
244
|
+
}
|
|
245
|
+
const issuedAt = Math.floor(now().getTime() / 1000);
|
|
246
|
+
const requestId = resolveRequestId(request);
|
|
247
|
+
const requestUrl = new URL(request.url);
|
|
248
|
+
const assertion = {
|
|
249
|
+
kind: 'request',
|
|
250
|
+
keyId: options.keyring.active.keyId,
|
|
251
|
+
identityKey: identity.identityKey,
|
|
252
|
+
regionId: placement.regionId,
|
|
253
|
+
epoch: placement.epoch,
|
|
254
|
+
requestId,
|
|
255
|
+
method: request.method,
|
|
256
|
+
path: `${requestUrl.pathname}${requestUrl.search}`,
|
|
257
|
+
audience: cell.audience,
|
|
258
|
+
issuedAt,
|
|
259
|
+
expiresAt: issuedAt + assertionTtlSeconds,
|
|
260
|
+
nonce: randomBytes(16).toString('base64url'),
|
|
261
|
+
bodySha256: await requestBodyDigest(request)
|
|
262
|
+
};
|
|
263
|
+
const routedRequest = withRoutingAssertion(request, signPayload(assertion, options.keyring), requestId);
|
|
264
|
+
let response;
|
|
265
|
+
try {
|
|
266
|
+
response = await options.dispatch(cell.target, routedRequest);
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
await emit(options, request, 'authfn.routing.cell_unavailable', {
|
|
270
|
+
outcome: 'unknown',
|
|
271
|
+
regionId: placement.regionId,
|
|
272
|
+
epoch: placement.epoch
|
|
273
|
+
});
|
|
274
|
+
return jsonError(request, new AuthFnRoutingCellUnavailableError());
|
|
275
|
+
}
|
|
276
|
+
await emit(options, request, 'authfn.routing.forwarded', {
|
|
277
|
+
outcome: 'success',
|
|
278
|
+
regionId: placement.regionId,
|
|
279
|
+
epoch: placement.epoch,
|
|
280
|
+
family: classifyAuthFnRoute(request, basePath).family,
|
|
281
|
+
attempt
|
|
282
|
+
});
|
|
283
|
+
const mismatchToken = response.headers.get(MISMATCH_HEADER);
|
|
284
|
+
if (attempt === 0 && mismatchToken) {
|
|
285
|
+
let mismatch = null;
|
|
286
|
+
try {
|
|
287
|
+
const verified = verifyPayload(mismatchToken, options.keyring, now, clockSkewSeconds);
|
|
288
|
+
mismatch = verified.kind === 'mismatch' ? verified : null;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
mismatch = null;
|
|
292
|
+
}
|
|
293
|
+
if (mismatch
|
|
294
|
+
&& mismatch.executionStarted === false
|
|
295
|
+
&& mismatch.identityKey === identity.identityKey
|
|
296
|
+
&& mismatch.requestId === requestId
|
|
297
|
+
&& mismatch.receivedRegionId === placement.regionId
|
|
298
|
+
&& mismatch.receivedEpoch === placement.epoch) {
|
|
299
|
+
await emit(options, request, 'authfn.routing.mismatch', {
|
|
300
|
+
outcome: 'pre-execution',
|
|
301
|
+
receivedRegionId: mismatch.receivedRegionId,
|
|
302
|
+
receivedEpoch: mismatch.receivedEpoch,
|
|
303
|
+
expectedRegionId: mismatch.expectedRegionId,
|
|
304
|
+
expectedEpoch: mismatch.expectedEpoch,
|
|
305
|
+
executionStarted: false
|
|
306
|
+
});
|
|
307
|
+
cache.delete(identity.identityKey);
|
|
308
|
+
const refreshed = await resolveOrClaimPlacement(identity, request, true);
|
|
309
|
+
await emit(options, request, 'authfn.routing.retry', {
|
|
310
|
+
outcome: 'started',
|
|
311
|
+
regionId: refreshed.regionId,
|
|
312
|
+
epoch: refreshed.epoch,
|
|
313
|
+
attempt: 1
|
|
314
|
+
});
|
|
315
|
+
return forward(request, identity, refreshed, 1);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return stripInternalResponseHeaders(response);
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
async handle(request) {
|
|
322
|
+
if (new URL(request.url).origin !== publicAuthority) {
|
|
323
|
+
return jsonError(request, new AuthFnValidationError('AuthFn gateway accepts only its public authority'));
|
|
324
|
+
}
|
|
325
|
+
const classification = classifyAuthFnRoute(request, basePath);
|
|
326
|
+
try {
|
|
327
|
+
const sanitizedRequest = stripClientRoutingHeaders(request);
|
|
328
|
+
if (classification.scope === 'global') {
|
|
329
|
+
if (!options.handleGlobal) {
|
|
330
|
+
return jsonError(request, new AuthFnRegionNotFoundError('Global AuthFn route is not configured'));
|
|
331
|
+
}
|
|
332
|
+
const response = await options.handleGlobal(sanitizedRequest, classification);
|
|
333
|
+
return stripInternalResponseHeaders(response);
|
|
334
|
+
}
|
|
335
|
+
const identity = await options.resolveIdentity(sanitizedRequest.clone(), classification);
|
|
336
|
+
if (!identity?.identityKey?.trim()) {
|
|
337
|
+
return jsonError(request, new AuthFnValidationError('A trusted identity routing key is required'));
|
|
338
|
+
}
|
|
339
|
+
const normalizedIdentity = { ...identity, identityKey: identity.identityKey.trim() };
|
|
340
|
+
const placement = await resolveOrClaimPlacement(normalizedIdentity, sanitizedRequest, false);
|
|
341
|
+
return forward(sanitizedRequest, normalizedIdentity, placement, 0);
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
const code = readErrorCode(error);
|
|
345
|
+
const eventType = code === 'AUTHFN_PLACEMENT_DIRECTORY_UNAVAILABLE'
|
|
346
|
+
? 'authfn.routing.directory_unavailable'
|
|
347
|
+
: code === 'AUTHFN_ROUTING_CELL_UNAVAILABLE'
|
|
348
|
+
? 'authfn.routing.cell_unavailable'
|
|
349
|
+
: code === 'AUTHFN_PLACEMENT_MOVING' || code === 'AUTHFN_REGION_NOT_FOUND'
|
|
350
|
+
? 'authfn.routing.placement_lookup'
|
|
351
|
+
: null;
|
|
352
|
+
if (eventType) {
|
|
353
|
+
await emit(options, request, eventType, {
|
|
354
|
+
errorType: code,
|
|
355
|
+
outcome: 'rejected'
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
return jsonError(request, error);
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
invalidate(identityKey) {
|
|
362
|
+
cache.delete(identityKey);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
/** Runs before rate limiting and every AuthFn route handler in a regional cell. */
|
|
367
|
+
export function createAuthFnCellPlacementMiddleware(config, pluginConfig) {
|
|
368
|
+
const routing = pluginConfig.routing;
|
|
369
|
+
if (routing?.mode !== 'gateway')
|
|
370
|
+
return null;
|
|
371
|
+
const directory = routing.placementDirectory;
|
|
372
|
+
if (!directory) {
|
|
373
|
+
throw new AuthFnConfigError('Gateway-mode AuthFn requires placementDirectory configuration');
|
|
374
|
+
}
|
|
375
|
+
const cell = routing.cell;
|
|
376
|
+
if (!cell) {
|
|
377
|
+
return async (request, _context, next) => classifyAuthFnRoute(request, config.basePath).scope === 'global'
|
|
378
|
+
? next()
|
|
379
|
+
: jsonError(request, new AuthFnRoutingCellUnavailableError());
|
|
380
|
+
}
|
|
381
|
+
validateKeyring(cell.keyring);
|
|
382
|
+
if (!cell.regionId.trim() || !cell.audience.trim()) {
|
|
383
|
+
throw new AuthFnConfigError('Gateway-mode AuthFn cells require regionId and audience');
|
|
384
|
+
}
|
|
385
|
+
const skew = cell.clockSkewSeconds ?? 5;
|
|
386
|
+
if (!Number.isSafeInteger(skew) || skew < 0 || skew > 60) {
|
|
387
|
+
throw new AuthFnConfigError('AuthFn cell clockSkewSeconds must be between 0 and 60');
|
|
388
|
+
}
|
|
389
|
+
return async (request, _context, next) => {
|
|
390
|
+
if (classifyAuthFnRoute(request, config.basePath).scope === 'global')
|
|
391
|
+
return next();
|
|
392
|
+
try {
|
|
393
|
+
const token = request.headers.get(ASSERTION_HEADER);
|
|
394
|
+
if (!token)
|
|
395
|
+
throw new AuthFnRoutingAssertionInvalidError('Gateway routing assertion is required');
|
|
396
|
+
const assertion = verifyPayload(token, cell.keyring, () => new Date(), skew);
|
|
397
|
+
if (assertion.kind !== 'request')
|
|
398
|
+
throw new AuthFnRoutingAssertionInvalidError();
|
|
399
|
+
await validateRequestAssertion(assertion, request, cell.audience);
|
|
400
|
+
if (!await cell.replayStore.claim(assertion.nonce, assertion.expiresAt + skew)) {
|
|
401
|
+
throw new AuthFnRoutingAssertionInvalidError('Gateway routing assertion was replayed');
|
|
402
|
+
}
|
|
403
|
+
let placement;
|
|
404
|
+
try {
|
|
405
|
+
placement = await directory.get(assertion.identityKey);
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
throw new AuthFnPlacementDirectoryUnavailableError();
|
|
409
|
+
}
|
|
410
|
+
if (!placement || placement.state === 'tombstoned') {
|
|
411
|
+
throw new AuthFnRegionNotFoundError('Identity placement is not active');
|
|
412
|
+
}
|
|
413
|
+
if (placement.state === 'moving' || placement.state === 'deleting') {
|
|
414
|
+
throw new AuthFnPlacementMovingError(undefined, { executionStarted: false });
|
|
415
|
+
}
|
|
416
|
+
if (placement.regionId !== cell.regionId
|
|
417
|
+
|| assertion.regionId !== cell.regionId
|
|
418
|
+
|| assertion.epoch !== placement.epoch) {
|
|
419
|
+
const mismatch = createMismatchAssertion(assertion, placement, cell.keyring, () => new Date());
|
|
420
|
+
const response = jsonError(request, new AuthFnRegionMismatchError('Gateway routing placement is stale', { executionStarted: false }));
|
|
421
|
+
const headers = new Headers(response.headers);
|
|
422
|
+
headers.set(MISMATCH_HEADER, signPayload(mismatch, cell.keyring));
|
|
423
|
+
await emitAuthEvent(config, {
|
|
424
|
+
type: 'authfn.routing.mismatch',
|
|
425
|
+
requestId: eventRequestId(request),
|
|
426
|
+
regionId: cell.regionId,
|
|
427
|
+
outcome: 'pre-execution',
|
|
428
|
+
metadata: {
|
|
429
|
+
receivedEpoch: assertion.epoch,
|
|
430
|
+
expectedEpoch: placement.epoch,
|
|
431
|
+
executionStarted: false
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
return new Response(response.body, { status: response.status, headers });
|
|
435
|
+
}
|
|
436
|
+
await emitAuthEvent(config, {
|
|
437
|
+
type: 'authfn.routing.placement_lookup',
|
|
438
|
+
requestId: eventRequestId(request),
|
|
439
|
+
regionId: cell.regionId,
|
|
440
|
+
outcome: 'validated',
|
|
441
|
+
metadata: { epoch: placement.epoch }
|
|
442
|
+
});
|
|
443
|
+
verifiedRoutingIdentityKeys.set(request, assertion.identityKey);
|
|
444
|
+
return next().finally(() => verifiedRoutingIdentityKeys.delete(request));
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
verifiedRoutingIdentityKeys.delete(request);
|
|
448
|
+
const code = readErrorCode(error);
|
|
449
|
+
await emitAuthEvent(config, {
|
|
450
|
+
type: code === 'AUTHFN_ROUTING_ASSERTION_INVALID'
|
|
451
|
+
? 'authfn.routing.assertion_rejected'
|
|
452
|
+
: code === 'AUTHFN_PLACEMENT_DIRECTORY_UNAVAILABLE'
|
|
453
|
+
? 'authfn.routing.directory_unavailable'
|
|
454
|
+
: 'authfn.routing.placement_lookup',
|
|
455
|
+
requestId: eventRequestId(request),
|
|
456
|
+
regionId: cell.regionId,
|
|
457
|
+
outcome: 'rejected',
|
|
458
|
+
metadata: { errorType: code }
|
|
459
|
+
});
|
|
460
|
+
return jsonError(request, error);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
/** Returns the identity key cryptographically bound to this routed request. */
|
|
465
|
+
export function authFnVerifiedRoutingIdentityKey(request) {
|
|
466
|
+
return request ? verifiedRoutingIdentityKeys.get(request) ?? null : null;
|
|
467
|
+
}
|
|
468
|
+
/** Fences an identity with increasing epochs while migration side effects run. */
|
|
469
|
+
export async function moveAuthFnIdentityPlacement(directory, input) {
|
|
470
|
+
const now = input.now ?? (() => new Date());
|
|
471
|
+
const current = await directory.get(input.identityKey);
|
|
472
|
+
if (!current || current.state !== 'active' || current.regionId !== input.sourceRegionId) {
|
|
473
|
+
throw new AuthFnRegionMismatchError('Identity is not active in the migration source');
|
|
474
|
+
}
|
|
475
|
+
const moving = {
|
|
476
|
+
...current,
|
|
477
|
+
epoch: current.epoch + 1,
|
|
478
|
+
state: 'moving',
|
|
479
|
+
movingToRegionId: input.targetRegionId,
|
|
480
|
+
previousRegionId: input.sourceRegionId,
|
|
481
|
+
updatedAt: now().toISOString()
|
|
482
|
+
};
|
|
483
|
+
const fenced = await directory.compareAndSet({
|
|
484
|
+
identityKey: input.identityKey,
|
|
485
|
+
expectedEpoch: current.epoch,
|
|
486
|
+
expectedState: 'active',
|
|
487
|
+
placement: moving
|
|
488
|
+
});
|
|
489
|
+
if (!fenced.updated)
|
|
490
|
+
throw new AuthFnRegionMismatchError('Identity placement changed during migration');
|
|
491
|
+
let targetResumeStarted = false;
|
|
492
|
+
try {
|
|
493
|
+
await input.callbacks.quiesceSource();
|
|
494
|
+
await input.callbacks.drainSource();
|
|
495
|
+
await input.callbacks.copyToTarget();
|
|
496
|
+
await input.callbacks.validateTarget();
|
|
497
|
+
await input.callbacks.warmTarget();
|
|
498
|
+
targetResumeStarted = true;
|
|
499
|
+
await input.callbacks.resumeTarget();
|
|
500
|
+
const active = {
|
|
501
|
+
identityKey: input.identityKey,
|
|
502
|
+
regionId: input.targetRegionId,
|
|
503
|
+
epoch: moving.epoch + 1,
|
|
504
|
+
state: 'active',
|
|
505
|
+
previousRegionId: input.sourceRegionId,
|
|
506
|
+
updatedAt: now().toISOString()
|
|
507
|
+
};
|
|
508
|
+
const activationResult = await directory.compareAndSet({
|
|
509
|
+
identityKey: input.identityKey,
|
|
510
|
+
expectedEpoch: moving.epoch,
|
|
511
|
+
expectedState: 'moving',
|
|
512
|
+
placement: active
|
|
513
|
+
});
|
|
514
|
+
if (!activationResult.updated)
|
|
515
|
+
throw new AuthFnRegionMismatchError('Identity placement changed before activation');
|
|
516
|
+
return active;
|
|
517
|
+
}
|
|
518
|
+
catch (error) {
|
|
519
|
+
if (targetResumeStarted)
|
|
520
|
+
throw error;
|
|
521
|
+
if (!input.callbacks.resumeSource)
|
|
522
|
+
throw error;
|
|
523
|
+
await input.callbacks.resumeSource();
|
|
524
|
+
const rollback = {
|
|
525
|
+
identityKey: input.identityKey,
|
|
526
|
+
regionId: input.sourceRegionId,
|
|
527
|
+
epoch: moving.epoch + 1,
|
|
528
|
+
state: 'active',
|
|
529
|
+
previousRegionId: input.targetRegionId,
|
|
530
|
+
updatedAt: now().toISOString()
|
|
531
|
+
};
|
|
532
|
+
const rolledBack = await directory.compareAndSet({
|
|
533
|
+
identityKey: input.identityKey,
|
|
534
|
+
expectedEpoch: moving.epoch,
|
|
535
|
+
expectedState: 'moving',
|
|
536
|
+
placement: rollback
|
|
537
|
+
});
|
|
538
|
+
if (!rolledBack.updated) {
|
|
539
|
+
throw new AuthFnRegionMismatchError('Identity placement rollback lost its compare-and-set race');
|
|
540
|
+
}
|
|
541
|
+
throw error;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
export async function tombstoneAuthFnIdentityPlacement(directory, identityKey, now = () => new Date()) {
|
|
545
|
+
const current = await directory.get(identityKey);
|
|
546
|
+
if (!current || current.state === 'tombstoned')
|
|
547
|
+
return current;
|
|
548
|
+
const tombstoned = {
|
|
549
|
+
...current,
|
|
550
|
+
epoch: current.epoch + 1,
|
|
551
|
+
state: 'tombstoned',
|
|
552
|
+
movingToRegionId: undefined,
|
|
553
|
+
updatedAt: now().toISOString()
|
|
554
|
+
};
|
|
555
|
+
const result = await directory.compareAndSet({
|
|
556
|
+
identityKey,
|
|
557
|
+
expectedEpoch: current.epoch,
|
|
558
|
+
expectedState: current.state,
|
|
559
|
+
placement: tombstoned
|
|
560
|
+
});
|
|
561
|
+
if (!result.updated)
|
|
562
|
+
throw new AuthFnRegionMismatchError('Identity placement changed before tombstoning');
|
|
563
|
+
return tombstoned;
|
|
564
|
+
}
|
|
565
|
+
/** Fences an identity before destructive account deletion begins. */
|
|
566
|
+
export async function fenceAuthFnIdentityDeletion(directory, identityKey, now = () => new Date()) {
|
|
567
|
+
const current = await directory.get(identityKey);
|
|
568
|
+
if (current?.state === 'deleting') {
|
|
569
|
+
throw new AuthFnRegionMismatchError('Identity placement is already fenced for account deletion', { deletionFenceAcquired: false });
|
|
570
|
+
}
|
|
571
|
+
if (!current || current.state !== 'active') {
|
|
572
|
+
throw new AuthFnRegionMismatchError('Identity placement is not active before account deletion', { deletionFenceAcquired: false });
|
|
573
|
+
}
|
|
574
|
+
const deleting = {
|
|
575
|
+
...current,
|
|
576
|
+
epoch: current.epoch + 1,
|
|
577
|
+
state: 'deleting',
|
|
578
|
+
movingToRegionId: undefined,
|
|
579
|
+
updatedAt: now().toISOString()
|
|
580
|
+
};
|
|
581
|
+
const result = await directory.compareAndSet({
|
|
582
|
+
identityKey,
|
|
583
|
+
expectedEpoch: current.epoch,
|
|
584
|
+
expectedState: 'active',
|
|
585
|
+
placement: deleting
|
|
586
|
+
});
|
|
587
|
+
if (!result.updated) {
|
|
588
|
+
throw new AuthFnRegionMismatchError('Identity placement changed while fencing account deletion', { deletionFenceAcquired: false });
|
|
589
|
+
}
|
|
590
|
+
return deleting;
|
|
591
|
+
}
|
|
592
|
+
/** Finalizes a durable deletion fence after the account cascade succeeds. */
|
|
593
|
+
export async function finalizeAuthFnIdentityDeletion(directory, identityKey, now = () => new Date(), expectedFenceEpoch) {
|
|
594
|
+
const current = await directory.get(identityKey);
|
|
595
|
+
if (expectedFenceEpoch !== undefined
|
|
596
|
+
&& (current?.state !== 'deleting' || current.epoch !== expectedFenceEpoch)) {
|
|
597
|
+
throw new AuthFnRegionMismatchError('Owned deletion fence changed before finalization');
|
|
598
|
+
}
|
|
599
|
+
if (current?.state === 'tombstoned')
|
|
600
|
+
return current;
|
|
601
|
+
if (!current || current.state !== 'deleting') {
|
|
602
|
+
throw new AuthFnRegionMismatchError('Identity placement is not fenced for account deletion');
|
|
603
|
+
}
|
|
604
|
+
const tombstoned = {
|
|
605
|
+
...current,
|
|
606
|
+
epoch: current.epoch + 1,
|
|
607
|
+
state: 'tombstoned',
|
|
608
|
+
movingToRegionId: undefined,
|
|
609
|
+
updatedAt: now().toISOString()
|
|
610
|
+
};
|
|
611
|
+
const result = await directory.compareAndSet({
|
|
612
|
+
identityKey,
|
|
613
|
+
expectedEpoch: current.epoch,
|
|
614
|
+
expectedState: 'deleting',
|
|
615
|
+
placement: tombstoned
|
|
616
|
+
});
|
|
617
|
+
if (!result.updated) {
|
|
618
|
+
throw new AuthFnRegionMismatchError('Identity placement changed before deletion finalization');
|
|
619
|
+
}
|
|
620
|
+
return tombstoned;
|
|
621
|
+
}
|
|
622
|
+
/** Restores ownership when destructive account deletion aborts. */
|
|
623
|
+
export async function restoreAuthFnIdentityDeletion(directory, identityKey, now = () => new Date(), expectedFenceEpoch) {
|
|
624
|
+
const current = await directory.get(identityKey);
|
|
625
|
+
if (expectedFenceEpoch !== undefined
|
|
626
|
+
&& (current?.state !== 'deleting' || current.epoch !== expectedFenceEpoch)) {
|
|
627
|
+
throw new AuthFnRegionMismatchError('Owned deletion fence changed before rollback');
|
|
628
|
+
}
|
|
629
|
+
if (current?.state === 'active')
|
|
630
|
+
return current;
|
|
631
|
+
if (!current || current.state !== 'deleting') {
|
|
632
|
+
throw new AuthFnRegionMismatchError('Identity placement is not fenced for account deletion');
|
|
633
|
+
}
|
|
634
|
+
const active = {
|
|
635
|
+
...current,
|
|
636
|
+
epoch: current.epoch + 1,
|
|
637
|
+
state: 'active',
|
|
638
|
+
movingToRegionId: undefined,
|
|
639
|
+
updatedAt: now().toISOString()
|
|
640
|
+
};
|
|
641
|
+
const result = await directory.compareAndSet({
|
|
642
|
+
identityKey,
|
|
643
|
+
expectedEpoch: current.epoch,
|
|
644
|
+
expectedState: 'deleting',
|
|
645
|
+
placement: active
|
|
646
|
+
});
|
|
647
|
+
if (!result.updated) {
|
|
648
|
+
throw new AuthFnRegionMismatchError('Identity placement changed before deletion rollback');
|
|
649
|
+
}
|
|
650
|
+
return active;
|
|
651
|
+
}
|
|
652
|
+
function createMismatchAssertion(assertion, placement, keyring, now) {
|
|
653
|
+
const issuedAt = Math.floor(now().getTime() / 1000);
|
|
654
|
+
return {
|
|
655
|
+
kind: 'mismatch',
|
|
656
|
+
keyId: keyring.active.keyId,
|
|
657
|
+
identityKey: assertion.identityKey,
|
|
658
|
+
requestId: assertion.requestId,
|
|
659
|
+
receivedRegionId: assertion.regionId,
|
|
660
|
+
receivedEpoch: assertion.epoch,
|
|
661
|
+
expectedRegionId: placement.regionId,
|
|
662
|
+
expectedEpoch: placement.epoch,
|
|
663
|
+
executionStarted: false,
|
|
664
|
+
issuedAt,
|
|
665
|
+
expiresAt: issuedAt + 20,
|
|
666
|
+
nonce: randomBytes(16).toString('base64url')
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
async function validateRequestAssertion(assertion, request, audience) {
|
|
670
|
+
if (assertion.audience !== audience
|
|
671
|
+
|| assertion.requestId !== resolveRequestId(request)
|
|
672
|
+
|| assertion.method !== request.method
|
|
673
|
+
|| assertion.path !== requestPathAndQuery(request)
|
|
674
|
+
|| assertion.bodySha256 !== await requestBodyDigest(request)) {
|
|
675
|
+
throw new AuthFnRoutingAssertionInvalidError('Gateway routing assertion does not match the request');
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function signPayload(payload, keyring) {
|
|
679
|
+
const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url');
|
|
680
|
+
const signature = createHmac('sha256', keyring.active.secret).update(encoded).digest('base64url');
|
|
681
|
+
return `${encoded}.${signature}`;
|
|
682
|
+
}
|
|
683
|
+
function verifyPayload(token, keyring, now, clockSkewSeconds = 0) {
|
|
684
|
+
const [encoded, signature, extra] = token.split('.');
|
|
685
|
+
if (!encoded || !signature || extra)
|
|
686
|
+
throw new AuthFnRoutingAssertionInvalidError();
|
|
687
|
+
let payload;
|
|
688
|
+
try {
|
|
689
|
+
payload = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
|
|
690
|
+
}
|
|
691
|
+
catch {
|
|
692
|
+
throw new AuthFnRoutingAssertionInvalidError();
|
|
693
|
+
}
|
|
694
|
+
if (!isSignedRoutingPayload(payload))
|
|
695
|
+
throw new AuthFnRoutingAssertionInvalidError();
|
|
696
|
+
const key = [keyring.active, ...(keyring.previous ?? [])].find((candidate) => candidate.keyId === payload.keyId);
|
|
697
|
+
if (!key)
|
|
698
|
+
throw new AuthFnRoutingAssertionInvalidError('Gateway routing assertion key is unknown');
|
|
699
|
+
const expected = createHmac('sha256', key.secret).update(encoded).digest();
|
|
700
|
+
const actual = Buffer.from(signature, 'base64url');
|
|
701
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
|
702
|
+
throw new AuthFnRoutingAssertionInvalidError();
|
|
703
|
+
}
|
|
704
|
+
const current = Math.floor(now().getTime() / 1000);
|
|
705
|
+
if (payload.issuedAt > current + clockSkewSeconds || payload.expiresAt < current - clockSkewSeconds) {
|
|
706
|
+
throw new AuthFnRoutingAssertionInvalidError('Gateway routing assertion is expired');
|
|
707
|
+
}
|
|
708
|
+
return payload;
|
|
709
|
+
}
|
|
710
|
+
function withRoutingAssertion(request, assertion, requestId) {
|
|
711
|
+
const headers = strippedRoutingHeaders(request.headers);
|
|
712
|
+
headers.set(ASSERTION_HEADER, assertion);
|
|
713
|
+
headers.set('x-request-id', requestId);
|
|
714
|
+
return new Request(request.clone(), { headers });
|
|
715
|
+
}
|
|
716
|
+
function stripClientRoutingHeaders(request) {
|
|
717
|
+
return new Request(request.clone(), { headers: strippedRoutingHeaders(request.headers) });
|
|
718
|
+
}
|
|
719
|
+
function strippedRoutingHeaders(input) {
|
|
720
|
+
const headers = new Headers(input);
|
|
721
|
+
const keys = [];
|
|
722
|
+
headers.forEach((_value, key) => keys.push(key));
|
|
723
|
+
for (const key of keys) {
|
|
724
|
+
if (key.toLowerCase().startsWith(INTERNAL_HEADER_PREFIX))
|
|
725
|
+
headers.delete(key);
|
|
726
|
+
}
|
|
727
|
+
return headers;
|
|
728
|
+
}
|
|
729
|
+
function stripInternalResponseHeaders(response) {
|
|
730
|
+
const headers = new Headers(response.headers);
|
|
731
|
+
const keys = [];
|
|
732
|
+
headers.forEach((_value, key) => keys.push(key));
|
|
733
|
+
for (const key of keys) {
|
|
734
|
+
if (key.toLowerCase().startsWith(INTERNAL_HEADER_PREFIX))
|
|
735
|
+
headers.delete(key);
|
|
736
|
+
}
|
|
737
|
+
return new Response(response.body, {
|
|
738
|
+
status: response.status,
|
|
739
|
+
statusText: response.statusText,
|
|
740
|
+
headers
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
async function requestBodyDigest(request) {
|
|
744
|
+
const body = request.method === 'GET' || request.method === 'HEAD'
|
|
745
|
+
? new Uint8Array()
|
|
746
|
+
: new Uint8Array(await request.clone().arrayBuffer());
|
|
747
|
+
return createHash('sha256').update(body).digest('base64url');
|
|
748
|
+
}
|
|
749
|
+
function requestPathAndQuery(request) {
|
|
750
|
+
const url = new URL(request.url);
|
|
751
|
+
return `${url.pathname}${url.search}`;
|
|
752
|
+
}
|
|
753
|
+
function requireActivePlacement(placement) {
|
|
754
|
+
if (placement.state === 'moving' || placement.state === 'deleting') {
|
|
755
|
+
throw new AuthFnPlacementMovingError(undefined, { executionStarted: false });
|
|
756
|
+
}
|
|
757
|
+
if (placement.state !== 'active')
|
|
758
|
+
throw new AuthFnRegionNotFoundError('Identity placement is not active');
|
|
759
|
+
return placement;
|
|
760
|
+
}
|
|
761
|
+
function validatePlacement(placement) {
|
|
762
|
+
if (!placement.identityKey.trim()
|
|
763
|
+
|| !placement.regionId.trim()
|
|
764
|
+
|| !Number.isSafeInteger(placement.epoch)
|
|
765
|
+
|| placement.epoch < 1
|
|
766
|
+
|| !isPlacementState(placement.state)
|
|
767
|
+
|| (typeof placement.updatedAt !== 'string' && !(placement.updatedAt instanceof Date))) {
|
|
768
|
+
throw new AuthFnValidationError('Identity placement is invalid');
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
function clonePlacement(placement) {
|
|
772
|
+
return { ...placement };
|
|
773
|
+
}
|
|
774
|
+
function placementKey(identityKey) {
|
|
775
|
+
return `${PLACEMENT_KEY_PREFIX}${encodeURIComponent(identityKey)}`;
|
|
776
|
+
}
|
|
777
|
+
function serializePlacement(placement) {
|
|
778
|
+
return JSON.stringify(placement);
|
|
779
|
+
}
|
|
780
|
+
function parsePlacement(value) {
|
|
781
|
+
if (!value)
|
|
782
|
+
return null;
|
|
783
|
+
try {
|
|
784
|
+
const parsed = JSON.parse(value);
|
|
785
|
+
if (typeof parsed.identityKey !== 'string'
|
|
786
|
+
|| typeof parsed.regionId !== 'string'
|
|
787
|
+
|| !Number.isSafeInteger(parsed.epoch)
|
|
788
|
+
|| !isPlacementState(parsed.state)
|
|
789
|
+
|| (typeof parsed.updatedAt !== 'string' && !(parsed.updatedAt instanceof Date)))
|
|
790
|
+
return null;
|
|
791
|
+
const placement = parsed;
|
|
792
|
+
validatePlacement(placement);
|
|
793
|
+
return placement;
|
|
794
|
+
}
|
|
795
|
+
catch {
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
function isPlacementState(value) {
|
|
800
|
+
return value === 'active' || value === 'moving' || value === 'deleting' || value === 'tombstoned';
|
|
801
|
+
}
|
|
802
|
+
function isSignedRoutingPayload(value) {
|
|
803
|
+
if (!value || typeof value !== 'object')
|
|
804
|
+
return false;
|
|
805
|
+
const payload = value;
|
|
806
|
+
if (typeof payload.keyId !== 'string'
|
|
807
|
+
|| typeof payload.issuedAt !== 'number'
|
|
808
|
+
|| !Number.isSafeInteger(payload.issuedAt)
|
|
809
|
+
|| typeof payload.expiresAt !== 'number'
|
|
810
|
+
|| !Number.isSafeInteger(payload.expiresAt)
|
|
811
|
+
|| typeof payload.nonce !== 'string'
|
|
812
|
+
|| payload.nonce.length < 16
|
|
813
|
+
|| payload.expiresAt < payload.issuedAt
|
|
814
|
+
|| payload.expiresAt - payload.issuedAt > 300)
|
|
815
|
+
return false;
|
|
816
|
+
if (payload.kind === 'request') {
|
|
817
|
+
return typeof payload.identityKey === 'string'
|
|
818
|
+
&& typeof payload.regionId === 'string'
|
|
819
|
+
&& typeof payload.epoch === 'number'
|
|
820
|
+
&& Number.isSafeInteger(payload.epoch)
|
|
821
|
+
&& payload.epoch >= 1
|
|
822
|
+
&& typeof payload.requestId === 'string'
|
|
823
|
+
&& typeof payload.method === 'string'
|
|
824
|
+
&& typeof payload.path === 'string'
|
|
825
|
+
&& typeof payload.audience === 'string'
|
|
826
|
+
&& typeof payload.bodySha256 === 'string';
|
|
827
|
+
}
|
|
828
|
+
if (payload.kind === 'mismatch') {
|
|
829
|
+
return typeof payload.identityKey === 'string'
|
|
830
|
+
&& typeof payload.requestId === 'string'
|
|
831
|
+
&& typeof payload.receivedRegionId === 'string'
|
|
832
|
+
&& typeof payload.receivedEpoch === 'number'
|
|
833
|
+
&& Number.isSafeInteger(payload.receivedEpoch)
|
|
834
|
+
&& typeof payload.expectedRegionId === 'string'
|
|
835
|
+
&& typeof payload.expectedEpoch === 'number'
|
|
836
|
+
&& Number.isSafeInteger(payload.expectedEpoch)
|
|
837
|
+
&& payload.executionStarted === false;
|
|
838
|
+
}
|
|
839
|
+
return false;
|
|
840
|
+
}
|
|
841
|
+
function stripBasePath(path, basePath) {
|
|
842
|
+
const normalizedBase = normalizeBasePath(basePath);
|
|
843
|
+
if (normalizedBase === '/')
|
|
844
|
+
return path;
|
|
845
|
+
return path === normalizedBase || path.startsWith(`${normalizedBase}/`)
|
|
846
|
+
? path.slice(normalizedBase.length) || '/'
|
|
847
|
+
: path;
|
|
848
|
+
}
|
|
849
|
+
function normalizeBasePath(basePath) {
|
|
850
|
+
const normalized = basePath.length > 1 && basePath.endsWith('/')
|
|
851
|
+
? basePath.slice(0, -1)
|
|
852
|
+
: basePath;
|
|
853
|
+
if (!normalized.startsWith('/') || normalized.includes('?') || normalized.includes('#')) {
|
|
854
|
+
throw new AuthFnConfigError('AuthFn basePath must be an absolute URL path');
|
|
855
|
+
}
|
|
856
|
+
return normalized;
|
|
857
|
+
}
|
|
858
|
+
function normalizeAuthority(authority) {
|
|
859
|
+
try {
|
|
860
|
+
return new URL(authority).origin;
|
|
861
|
+
}
|
|
862
|
+
catch {
|
|
863
|
+
throw new AuthFnConfigError('AuthFn publicAuthority must be a valid origin');
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
function validateKeyring(keyring) {
|
|
867
|
+
const keys = [keyring.active, ...(keyring.previous ?? [])];
|
|
868
|
+
const ids = new Set();
|
|
869
|
+
for (const key of keys) {
|
|
870
|
+
const byteLength = typeof key.secret === 'string'
|
|
871
|
+
? Buffer.byteLength(key.secret)
|
|
872
|
+
: key.secret.byteLength;
|
|
873
|
+
if (!key.keyId.trim() || byteLength < 32) {
|
|
874
|
+
throw new AuthFnConfigError('AuthFn routing keys require a keyId and at least 32 bytes of secret material');
|
|
875
|
+
}
|
|
876
|
+
if (ids.has(key.keyId)) {
|
|
877
|
+
throw new AuthFnConfigError('AuthFn routing key IDs must be unique');
|
|
878
|
+
}
|
|
879
|
+
ids.add(key.keyId);
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
async function emit(options, request, type, metadata) {
|
|
883
|
+
try {
|
|
884
|
+
const { outcome, ...eventMetadata } = metadata;
|
|
885
|
+
await options.onEvent?.({
|
|
886
|
+
type,
|
|
887
|
+
requestId: resolveRequestId(request),
|
|
888
|
+
outcome: typeof outcome === 'string' ? outcome : undefined,
|
|
889
|
+
metadata: eventMetadata
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
catch {
|
|
893
|
+
// Routing correctness must not depend on telemetry availability.
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
function readErrorCode(error) {
|
|
897
|
+
if (!error || typeof error !== 'object')
|
|
898
|
+
return 'AUTHFN_INTERNAL_ERROR';
|
|
899
|
+
const code = error.code;
|
|
900
|
+
return typeof code === 'string' ? code : 'AUTHFN_INTERNAL_ERROR';
|
|
901
|
+
}
|
|
902
|
+
//# sourceMappingURL=gateway-routing.js.map
|