@authfn/oauth-provider 0.1.1 → 0.3.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 +62 -2
- package/dist/authorize/index.d.ts.map +1 -1
- package/dist/authorize/index.js +6 -6
- package/dist/authorize/index.js.map +1 -1
- package/dist/device/index.d.ts +39 -0
- package/dist/device/index.d.ts.map +1 -0
- package/dist/device/index.js +409 -0
- package/dist/device/index.js.map +1 -0
- package/dist/device/store.d.ts +129 -0
- package/dist/device/store.d.ts.map +1 -0
- package/dist/device/store.js +325 -0
- package/dist/device/store.js.map +1 -0
- package/dist/device/types.d.ts +87 -0
- package/dist/device/types.d.ts.map +1 -0
- package/dist/device/types.js +3 -0
- package/dist/device/types.js.map +1 -0
- package/dist/http.d.ts +2 -2
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +2 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -5
- package/dist/index.js.map +1 -1
- package/dist/metadata/index.d.ts.map +1 -1
- package/dist/metadata/index.js +7 -1
- package/dist/metadata/index.js.map +1 -1
- package/dist/registration/document.d.ts +53 -0
- package/dist/registration/document.d.ts.map +1 -0
- package/dist/registration/document.js +173 -0
- package/dist/registration/document.js.map +1 -0
- package/dist/registration/index.d.ts +38 -0
- package/dist/registration/index.d.ts.map +1 -0
- package/dist/registration/index.js +264 -0
- package/dist/registration/index.js.map +1 -0
- package/dist/registration/metadata.d.ts +27 -0
- package/dist/registration/metadata.d.ts.map +1 -0
- package/dist/registration/metadata.js +74 -0
- package/dist/registration/metadata.js.map +1 -0
- package/dist/registration/store.d.ts +86 -0
- package/dist/registration/store.d.ts.map +1 -0
- package/dist/registration/store.js +187 -0
- package/dist/registration/store.js.map +1 -0
- package/dist/revocation/index.js +1 -1
- package/dist/revocation/index.js.map +1 -1
- package/dist/runtime.d.ts +10 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -1
- package/dist/runtime.js.map +1 -1
- package/dist/store.d.ts +34 -5
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +37 -14
- package/dist/store.js.map +1 -1
- package/dist/token/index.d.ts.map +1 -1
- package/dist/token/index.js +6 -2
- package/dist/token/index.js.map +1 -1
- package/dist/types.d.ts +44 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import { AuthFnConfigError, AuthFnValidationError } from 'authfn/core/errors';
|
|
2
|
+
import { assertValidCsrf, getCookieSessionState, requireCookieSession } from 'authfn/core/sessions';
|
|
3
|
+
import { jsonSuccess } from 'authfn/http/envelopes';
|
|
4
|
+
import { createAuthFnRouteMeta, readOptionalJson } from 'authfn/http/router';
|
|
5
|
+
import { authenticateClient, handleOAuth, OAuthError, oauthJson, readSingleParams, requireParam } from '../http.js';
|
|
6
|
+
import { BodyTimeoutError, declaresMoreThan, readCappedBody } from '../registration/document.js';
|
|
7
|
+
import { REGISTRATION_BODY_TIMEOUT_MS } from '../registration/index.js';
|
|
8
|
+
import { isPlainObject } from '../registration/metadata.js';
|
|
9
|
+
import { admitRegistrationEvent } from '../registration/store.js';
|
|
10
|
+
import { requireResource, resolveEndpoints, resolveRequestedScopes } from '../runtime.js';
|
|
11
|
+
import { createGrant, findLiveGrant, readGeneration, revokeGrant, stageTokens } from '../store.js';
|
|
12
|
+
import { admitPoll, claimDecision, claimDeviceCode, closeExpiredDeviceCode, createDeviceCode, EXPIRED_CLAIM_PREFIX, findByUserCode, findDeviceCode, normalizeUserCode, pruneDeviceCodes, OAUTH_DEVICE_CODE_TTL_SECONDS, OAUTH_DEVICE_POLL_INTERVAL_SECONDS } from './store.js';
|
|
13
|
+
export { createDeviceSchema, OAUTH_DEVICE_CODE_TTL_SECONDS, OAUTH_DEVICE_POLL_INTERVAL_SECONDS } from './store.js';
|
|
14
|
+
export * from './types.js';
|
|
15
|
+
export const OAUTH_DEVICE_AUTHORIZATION_PATH = '/oauth/device_authorization';
|
|
16
|
+
export const OAUTH_DEVICE_VERIFICATION_PATH = '/oauth/device';
|
|
17
|
+
const DEFAULT_RATE_LIMIT = { perUser: 10, global: 1000, windowSeconds: 600 };
|
|
18
|
+
const DEFAULT_AUTHORIZATION_RATE_LIMIT = { perIp: 20, global: 1000, windowSeconds: 600 };
|
|
19
|
+
/** True when `limits` is absent or an object of positive integers named in `names`. */
|
|
20
|
+
function validLimits(limits, names) {
|
|
21
|
+
return limits === undefined || (isPlainObject(limits) && Object.entries(limits).every(([name, value]) => names.includes(name) &&
|
|
22
|
+
(value === undefined || (typeof value === 'number' && Number.isSafeInteger(value) && value > 0))));
|
|
23
|
+
}
|
|
24
|
+
/** The configured limits over the defaults; an `undefined` value keeps the default. */
|
|
25
|
+
function limitsWithDefaults(defaults, configured) {
|
|
26
|
+
return { ...defaults, ...Object.fromEntries(Object.entries(configured ?? {}).filter(([, value]) => value !== undefined)) };
|
|
27
|
+
}
|
|
28
|
+
/** Rejects a malformed `pluginRuntime.oauthProvider.deviceAuthorization` at startup. */
|
|
29
|
+
export function validateDeviceConfig(device) {
|
|
30
|
+
if (device === undefined) {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const invalid = (message) => new AuthFnConfigError(`pluginRuntime.oauthProvider.deviceAuthorization ${message}`);
|
|
34
|
+
if (!isPlainObject(device) || typeof device.verification !== 'function') {
|
|
35
|
+
throw invalid('needs a verification hook');
|
|
36
|
+
}
|
|
37
|
+
const { rateLimit, authorizationRateLimit, resolveClientIp } = device;
|
|
38
|
+
if (!validLimits(rateLimit, ['perUser', 'global', 'windowSeconds'])) {
|
|
39
|
+
throw invalid('rateLimit takes positive integers perUser, global and windowSeconds');
|
|
40
|
+
}
|
|
41
|
+
if (!validLimits(authorizationRateLimit, ['perIp', 'global', 'windowSeconds'])) {
|
|
42
|
+
throw invalid('authorizationRateLimit takes positive integers perIp, global and windowSeconds');
|
|
43
|
+
}
|
|
44
|
+
if (resolveClientIp !== undefined && typeof resolveClientIp !== 'function') {
|
|
45
|
+
throw invalid('resolveClientIp must be a function');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** The largest device authorization request body; its parameters are a few short strings. */
|
|
49
|
+
const MAX_DEVICE_AUTHORIZATION_BODY_BYTES = 8 * 1024;
|
|
50
|
+
/**
|
|
51
|
+
* Reads the form body of an anonymous device authorization request, bounded
|
|
52
|
+
* before anything else runs: a declared or streamed body over 8 KB, or one
|
|
53
|
+
* that has not arrived within 5 seconds, is an `invalid_request` and the
|
|
54
|
+
* stream is cancelled.
|
|
55
|
+
*/
|
|
56
|
+
async function readCappedFormBody(request) {
|
|
57
|
+
const contentType = request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
|
|
58
|
+
if (contentType !== 'application/x-www-form-urlencoded') {
|
|
59
|
+
throw new OAuthError('invalid_request', 'Request body must be application/x-www-form-urlencoded');
|
|
60
|
+
}
|
|
61
|
+
const tooLarge = new OAuthError('invalid_request', 'Request body must be at most 8 KB');
|
|
62
|
+
if (declaresMoreThan(request.headers, MAX_DEVICE_AUTHORIZATION_BODY_BYTES)) {
|
|
63
|
+
await request.body?.cancel().catch(() => undefined);
|
|
64
|
+
throw tooLarge;
|
|
65
|
+
}
|
|
66
|
+
let bytes = new Uint8Array();
|
|
67
|
+
try {
|
|
68
|
+
if (request.body) {
|
|
69
|
+
bytes = await readCappedBody(request.body.getReader(), MAX_DEVICE_AUTHORIZATION_BODY_BYTES, REGISTRATION_BODY_TIMEOUT_MS);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (error instanceof BodyTimeoutError) {
|
|
74
|
+
throw new OAuthError('invalid_request', 'Request body must arrive within 5 seconds');
|
|
75
|
+
}
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
if (!bytes) {
|
|
79
|
+
throw tooLarge;
|
|
80
|
+
}
|
|
81
|
+
return readSingleParams(new URLSearchParams(new TextDecoder().decode(bytes)));
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Counts one device authorization request per client IP and overall, or
|
|
85
|
+
* throws a 429 `temporarily_unavailable` before anything is stored.
|
|
86
|
+
*/
|
|
87
|
+
async function admitDeviceAuthorization(runtime, device, request) {
|
|
88
|
+
const resolve = device.resolveClientIp ?? runtime.ctx.config.rateLimit?.resolveClientIp;
|
|
89
|
+
const ip = (await resolve?.(request))?.trim() || undefined;
|
|
90
|
+
const { perIp, global, windowSeconds } = limitsWithDefaults(DEFAULT_AUTHORIZATION_RATE_LIMIT, device.authorizationRateLimit);
|
|
91
|
+
const result = await admitRegistrationEvent(runtime.store, {
|
|
92
|
+
kind: 'device_code',
|
|
93
|
+
ip,
|
|
94
|
+
now: runtime.now(),
|
|
95
|
+
limits: { perIp, global, windowSeconds }
|
|
96
|
+
});
|
|
97
|
+
if (!result.admitted) {
|
|
98
|
+
throw new OAuthError('temporarily_unavailable', 'Too many device authorization requests; try again later', 429, {
|
|
99
|
+
'retry-after': String(result.retryAfterSeconds)
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Counts one user code lookup by `user`, or reports the seconds until the
|
|
105
|
+
* window ends. Lookups share the windowed event store of client registration.
|
|
106
|
+
*/
|
|
107
|
+
async function admitUserCodeLookup(runtime, device, user) {
|
|
108
|
+
const { perUser, global, windowSeconds } = limitsWithDefaults(DEFAULT_RATE_LIMIT, device.rateLimit);
|
|
109
|
+
const result = await admitRegistrationEvent(runtime.store, {
|
|
110
|
+
kind: 'user_code',
|
|
111
|
+
ip: `user:${user.id}`,
|
|
112
|
+
now: runtime.now(),
|
|
113
|
+
limits: { perIp: perUser, global, windowSeconds }
|
|
114
|
+
});
|
|
115
|
+
return result.admitted ? null : result.retryAfterSeconds;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Finds the pending device authorization a user code names, after counting
|
|
119
|
+
* the lookup. A code that is decided, unknown or whose client is no longer
|
|
120
|
+
* configured is `invalid_user_code`.
|
|
121
|
+
*/
|
|
122
|
+
async function lookUpUserCode(runtime, device, user, userCode) {
|
|
123
|
+
const retryAfterSeconds = await admitUserCodeLookup(runtime, device, user);
|
|
124
|
+
if (retryAfterSeconds !== null) {
|
|
125
|
+
return { ok: false, error: 'too_many_attempts', retryAfterSeconds };
|
|
126
|
+
}
|
|
127
|
+
const record = userCode ? await findByUserCode(runtime.store, userCode) : null;
|
|
128
|
+
const client = record ? runtime.findClient(record.clientId) : undefined;
|
|
129
|
+
if (!record || !client || record.decidedAt) {
|
|
130
|
+
return { ok: false, error: 'invalid_user_code' };
|
|
131
|
+
}
|
|
132
|
+
if (record.expiresAt.getTime() <= runtime.now().getTime()) {
|
|
133
|
+
return { ok: false, error: 'expired_user_code' };
|
|
134
|
+
}
|
|
135
|
+
return { ok: true, record, client };
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Approves a pending device authorization for `user`: creates its grant,
|
|
139
|
+
* checks the disconnect generation, and only then records the decision,
|
|
140
|
+
* which makes the code exchangeable and which only one decision wins. As for
|
|
141
|
+
* an authorization code, the generation is read before the grant is created
|
|
142
|
+
* and again after: a disconnect in between revokes the new grant and records
|
|
143
|
+
* the request as denied, so the device gets `access_denied`. A disconnect
|
|
144
|
+
* after the second read finds the grant, which already exists, and revokes
|
|
145
|
+
* it; the device then also gets `access_denied` (see `exchangeDeviceCode`).
|
|
146
|
+
* Expiry is checked before the decision is recorded and again after: an
|
|
147
|
+
* approval that crosses it revokes its grant and throws `invalid_grant`. One
|
|
148
|
+
* that crossed before the write records nothing. One that crossed after it
|
|
149
|
+
* spends the code with an expiry claim, unless an exchange claimed it first:
|
|
150
|
+
* an exchange judges expiry with a clock read after it read the approval, so
|
|
151
|
+
* its winning claim proves the approval was published before expiry, and the
|
|
152
|
+
* approval stands. An approval interrupted anywhere before the decision
|
|
153
|
+
* leaves the request pending.
|
|
154
|
+
* Returns whether the device will receive tokens.
|
|
155
|
+
*/
|
|
156
|
+
async function approve(runtime, record, user) {
|
|
157
|
+
const { store } = runtime;
|
|
158
|
+
const triple = { userId: user.id, clientId: record.clientId, resource: record.resource };
|
|
159
|
+
const generation = await readGeneration(store, triple);
|
|
160
|
+
const grant = await createGrant(store, { ...triple, scopes: record.scopes, now: runtime.now() });
|
|
161
|
+
if (await readGeneration(store, triple) !== generation) {
|
|
162
|
+
await revokeGrant(store, grant.id, 'consent_withdrawn', runtime.now());
|
|
163
|
+
await claimDecision(store, record.id, { decision: 'denied', userId: user.id, now: runtime.now() });
|
|
164
|
+
return 'withdrawn';
|
|
165
|
+
}
|
|
166
|
+
const now = runtime.now();
|
|
167
|
+
if (record.expiresAt.getTime() <= now.getTime()) {
|
|
168
|
+
await revokeGrant(store, grant.id, 'device_code_expired', now);
|
|
169
|
+
throw new OAuthError('invalid_grant', 'The user code has expired');
|
|
170
|
+
}
|
|
171
|
+
if (!(await claimDecision(store, record.id, { decision: 'approved', userId: user.id, grantId: grant.id, now }))) {
|
|
172
|
+
await revokeGrant(store, grant.id, 'device_decided', runtime.now());
|
|
173
|
+
return 'decided';
|
|
174
|
+
}
|
|
175
|
+
// Expired by the time the decision was written: spend the code so nothing
|
|
176
|
+
// can exchange it, unless an exchange that found it unexpired already did.
|
|
177
|
+
if (record.expiresAt.getTime() <= runtime.now().getTime() && await closeExpiredDeviceCode(store, record.id, runtime.now())) {
|
|
178
|
+
await revokeGrant(store, grant.id, 'device_code_expired', runtime.now());
|
|
179
|
+
throw new OAuthError('invalid_grant', 'The user code has expired');
|
|
180
|
+
}
|
|
181
|
+
return 'approved';
|
|
182
|
+
}
|
|
183
|
+
function deviceConfig(runtime) {
|
|
184
|
+
return runtime.config.deviceAuthorization;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The device authorization endpoint (RFC 8628 3.1, 3.2), the verification
|
|
188
|
+
* page with its decision endpoint (3.3), when `deviceAuthorization` is
|
|
189
|
+
* configured. The token endpoint accepts the device code grant through
|
|
190
|
+
* `exchangeDeviceCode`.
|
|
191
|
+
*/
|
|
192
|
+
export function createDeviceRoutes(runtime) {
|
|
193
|
+
const device = deviceConfig(runtime);
|
|
194
|
+
if (!device) {
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
return [
|
|
198
|
+
{
|
|
199
|
+
method: 'POST',
|
|
200
|
+
path: OAUTH_DEVICE_AUTHORIZATION_PATH,
|
|
201
|
+
meta: createAuthFnRouteMeta('oauthDeviceAuthorization', 'OAuth 2.0 device authorization endpoint', { mode: 'none' }),
|
|
202
|
+
handler: (request) => handleOAuth(async () => {
|
|
203
|
+
const params = await readCappedFormBody(request);
|
|
204
|
+
const client = await authenticateClient(runtime, request, params);
|
|
205
|
+
if (!runtime.findClient(client.clientId)) {
|
|
206
|
+
throw new OAuthError('unauthorized_client', 'This client may not use the device authorization grant');
|
|
207
|
+
}
|
|
208
|
+
const resource = requireResource(runtime, params.get('resource'));
|
|
209
|
+
const scopes = resolveRequestedScopes(resource, params.get('scope'));
|
|
210
|
+
await admitDeviceAuthorization(runtime, device, request);
|
|
211
|
+
await pruneDeviceCodes(runtime.store, runtime.now());
|
|
212
|
+
const { deviceCode, userCode } = await createDeviceCode(runtime.store, {
|
|
213
|
+
clientId: client.clientId,
|
|
214
|
+
resource: resource.resource,
|
|
215
|
+
scopes,
|
|
216
|
+
now: runtime.now()
|
|
217
|
+
});
|
|
218
|
+
const verificationUri = (await resolveEndpoints(runtime, request)).deviceVerification;
|
|
219
|
+
return oauthJson({
|
|
220
|
+
device_code: deviceCode,
|
|
221
|
+
user_code: userCode,
|
|
222
|
+
verification_uri: verificationUri,
|
|
223
|
+
verification_uri_complete: `${verificationUri}?${new URLSearchParams({ user_code: userCode })}`,
|
|
224
|
+
expires_in: OAUTH_DEVICE_CODE_TTL_SECONDS,
|
|
225
|
+
interval: OAUTH_DEVICE_POLL_INTERVAL_SECONDS
|
|
226
|
+
});
|
|
227
|
+
})
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
method: 'GET',
|
|
231
|
+
path: OAUTH_DEVICE_VERIFICATION_PATH,
|
|
232
|
+
meta: createAuthFnRouteMeta('oauthDeviceVerification', 'OAuth 2.0 device verification page', { mode: 'hybrid' }),
|
|
233
|
+
handler: async (request) => {
|
|
234
|
+
const state = await getCookieSessionState(runtime.ctx.config, request);
|
|
235
|
+
if (!state.session || !state.user) {
|
|
236
|
+
return runtime.config.loginRequired({ request, returnTo: request.url });
|
|
237
|
+
}
|
|
238
|
+
const user = { id: state.user.id, primaryEmail: state.user.primaryEmail };
|
|
239
|
+
const endpoints = await resolveEndpoints(runtime, request);
|
|
240
|
+
const input = {
|
|
241
|
+
request,
|
|
242
|
+
user,
|
|
243
|
+
verificationUrl: endpoints.deviceVerification,
|
|
244
|
+
decisionUrl: endpoints.deviceVerification
|
|
245
|
+
};
|
|
246
|
+
const entered = new URL(request.url).searchParams.getAll('user_code');
|
|
247
|
+
if (entered.length === 0) {
|
|
248
|
+
return device.verification(input);
|
|
249
|
+
}
|
|
250
|
+
const userCode = entered.length === 1 ? normalizeUserCode(entered[0]) : null;
|
|
251
|
+
const lookup = await lookUpUserCode(runtime, device, user, userCode);
|
|
252
|
+
input.userCode = userCode ?? undefined;
|
|
253
|
+
if (lookup.ok) {
|
|
254
|
+
input.authorization = {
|
|
255
|
+
client: { clientId: lookup.client.clientId, name: lookup.client.name, trusted: lookup.client.trusted === true },
|
|
256
|
+
resource: lookup.record.resource,
|
|
257
|
+
scopes: [...lookup.record.scopes]
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
input.error = lookup.error;
|
|
262
|
+
if (lookup.error === 'too_many_attempts') {
|
|
263
|
+
input.retryAfterSeconds = lookup.retryAfterSeconds;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return device.verification(input);
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
{
|
|
270
|
+
method: 'POST',
|
|
271
|
+
path: OAUTH_DEVICE_VERIFICATION_PATH,
|
|
272
|
+
meta: createAuthFnRouteMeta('oauthDeviceDecision', 'Record the decision for an OAuth device authorization', {
|
|
273
|
+
mode: 'cookie-session',
|
|
274
|
+
csrf: true
|
|
275
|
+
}),
|
|
276
|
+
handler: (request) => handleOAuth(async () => {
|
|
277
|
+
const session = await requireCookieSession(runtime.ctx.config, request);
|
|
278
|
+
assertValidCsrf(request, session);
|
|
279
|
+
let body;
|
|
280
|
+
try {
|
|
281
|
+
body = await readOptionalJson(request);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (error instanceof AuthFnValidationError) {
|
|
285
|
+
throw new OAuthError('invalid_request', 'The decision body must be valid JSON');
|
|
286
|
+
}
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
if (!isPlainObject(body) || typeof body.user_code !== 'string' ||
|
|
290
|
+
(body.decision !== 'approve' && body.decision !== 'deny')) {
|
|
291
|
+
throw new OAuthError('invalid_request', 'The decision body must be { user_code, decision: approve | deny }');
|
|
292
|
+
}
|
|
293
|
+
const user = { id: session.user.id, primaryEmail: session.user.primaryEmail };
|
|
294
|
+
const lookup = await lookUpUserCode(runtime, device, user, normalizeUserCode(body.user_code));
|
|
295
|
+
if (!lookup.ok) {
|
|
296
|
+
if (lookup.error === 'too_many_attempts') {
|
|
297
|
+
throw new OAuthError('temporarily_unavailable', 'Too many user code attempts; try again later', 429, {
|
|
298
|
+
'retry-after': String(lookup.retryAfterSeconds)
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
throw new OAuthError('invalid_grant', lookup.error === 'expired_user_code'
|
|
302
|
+
? 'The user code has expired'
|
|
303
|
+
: 'The user code is invalid or was already used');
|
|
304
|
+
}
|
|
305
|
+
let outcome;
|
|
306
|
+
if (body.decision === 'approve') {
|
|
307
|
+
outcome = await approve(runtime, lookup.record, user);
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
const denied = await claimDecision(runtime.store, lookup.record.id, { decision: 'denied', userId: user.id, now: runtime.now() });
|
|
311
|
+
outcome = denied ? 'denied' : 'decided';
|
|
312
|
+
}
|
|
313
|
+
if (outcome === 'decided') {
|
|
314
|
+
throw new OAuthError('invalid_grant', 'The user code is invalid or was already used');
|
|
315
|
+
}
|
|
316
|
+
if (outcome === 'withdrawn') {
|
|
317
|
+
throw new OAuthError('access_denied', 'The authorization was withdrawn while it was being approved');
|
|
318
|
+
}
|
|
319
|
+
return jsonSuccess(request, { decision: outcome }, { headers: { 'cache-control': 'no-store' } });
|
|
320
|
+
})
|
|
321
|
+
}
|
|
322
|
+
];
|
|
323
|
+
}
|
|
324
|
+
function deviceError(error, description) {
|
|
325
|
+
return new OAuthError(error, description);
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Device access token request (RFC 8628 3.4, 3.5). The device polls with its
|
|
329
|
+
* device code: `authorization_pending` until the user decides, `slow_down`
|
|
330
|
+
* for a poll within the interval of the previous one (which adds 5 seconds
|
|
331
|
+
* to it), `access_denied` after a denial or once the approved grant was
|
|
332
|
+
* revoked (the app was disconnected, or the user disabled) and
|
|
333
|
+
* `expired_token` after 10 minutes. A `resource` other than the requested
|
|
334
|
+
* one is `invalid_target` and leaves the code as it was. A poll that loses to
|
|
335
|
+
* 16 concurrent polls, or cannot tell whether it was stored, is a 429
|
|
336
|
+
* `temporarily_unavailable` whose `Retry-After` is the time left until the
|
|
337
|
+
* stored last poll time plus the stored interval (none once that has passed),
|
|
338
|
+
* plus 5 seconds when its own `slow_down` may count.
|
|
339
|
+
* An approval yields the same tokens as an authorization code: an
|
|
340
|
+
* access token for the approved scopes and a refresh token under the grant.
|
|
341
|
+
* The exchange is judged unexpired with a clock read after the row read that
|
|
342
|
+
* showed the approval, and its tokens are issued at that time; tokens whose
|
|
343
|
+
* exchange was judged in time stay valid even when the claim commits later.
|
|
344
|
+
* The device code works once; when its client presents it again after the
|
|
345
|
+
* exchange, the grant is revoked, as for a replayed authorization code.
|
|
346
|
+
*/
|
|
347
|
+
export async function exchangeDeviceCode(runtime, client, params) {
|
|
348
|
+
const deviceCode = requireParam(params, 'device_code');
|
|
349
|
+
const now = runtime.now();
|
|
350
|
+
const record = await findDeviceCode(runtime.store, deviceCode);
|
|
351
|
+
if (record?.clientId !== client.clientId) {
|
|
352
|
+
throw deviceError('invalid_grant', 'Device code is invalid');
|
|
353
|
+
}
|
|
354
|
+
if (record.consumedAt) {
|
|
355
|
+
if (record.claimId?.startsWith(`${EXPIRED_CLAIM_PREFIX}_`)) {
|
|
356
|
+
throw deviceError('expired_token', 'Device code has expired');
|
|
357
|
+
}
|
|
358
|
+
if (record.grantId) {
|
|
359
|
+
await revokeGrant(runtime.store, record.grantId, 'code_replay', now);
|
|
360
|
+
}
|
|
361
|
+
throw deviceError('invalid_grant', 'Device code has already been used');
|
|
362
|
+
}
|
|
363
|
+
if (record.expiresAt.getTime() <= now.getTime()) {
|
|
364
|
+
throw deviceError('expired_token', 'Device code has expired');
|
|
365
|
+
}
|
|
366
|
+
const resource = params.get('resource');
|
|
367
|
+
if (resource !== undefined && resource !== record.resource) {
|
|
368
|
+
throw new OAuthError('invalid_target', 'resource does not match the device authorization request');
|
|
369
|
+
}
|
|
370
|
+
const poll = await admitPoll(runtime.store, record, now);
|
|
371
|
+
if (poll.outcome === 'busy' || poll.outcome === 'unknown') {
|
|
372
|
+
throw new OAuthError('temporarily_unavailable', 'Too many concurrent polls of this device code; try again later', 429, {
|
|
373
|
+
'retry-after': String(poll.retryAfterSeconds)
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
if (poll.outcome === 'slow_down') {
|
|
377
|
+
throw deviceError('slow_down', 'Polling too fast; wait longer between requests');
|
|
378
|
+
}
|
|
379
|
+
if (!record.decidedAt) {
|
|
380
|
+
throw deviceError('authorization_pending', 'The user has not yet completed the authorization');
|
|
381
|
+
}
|
|
382
|
+
if (record.decision !== 'approved' || !record.grantId) {
|
|
383
|
+
throw deviceError('access_denied', 'The user denied the authorization request');
|
|
384
|
+
}
|
|
385
|
+
const grant = await findLiveGrant(runtime.store, record.grantId);
|
|
386
|
+
if (!grant) {
|
|
387
|
+
throw deviceError('access_denied', 'The authorization was withdrawn');
|
|
388
|
+
}
|
|
389
|
+
// `now` was read before the row, so the approval may have been published
|
|
390
|
+
// after it. Expiry is judged again with a clock read after the row showed
|
|
391
|
+
// the approval: only then does a committed exchange prove the approval was
|
|
392
|
+
// published in time, which `approve` relies on when its close loses.
|
|
393
|
+
const issuedAt = runtime.now();
|
|
394
|
+
if (record.expiresAt.getTime() <= issuedAt.getTime()) {
|
|
395
|
+
throw deviceError('expired_token', 'Device code has expired');
|
|
396
|
+
}
|
|
397
|
+
// As for a code: the staged tokens become valid only when the claim on the
|
|
398
|
+
// device code commits, and a concurrent exchange that loses is a replay.
|
|
399
|
+
const { tokens, claimId } = await stageTokens(runtime.store, grant, grant.scopes, issuedAt, record.id);
|
|
400
|
+
if (!(await claimDeviceCode(runtime.store, record.id, issuedAt, claimId))) {
|
|
401
|
+
await revokeGrant(runtime.store, record.grantId, 'code_replay', issuedAt);
|
|
402
|
+
throw deviceError('invalid_grant', 'Device code has already been used');
|
|
403
|
+
}
|
|
404
|
+
if (!(await findLiveGrant(runtime.store, record.grantId))) {
|
|
405
|
+
throw deviceError('invalid_grant', 'Authorization grant is no longer valid');
|
|
406
|
+
}
|
|
407
|
+
return tokens;
|
|
408
|
+
}
|
|
409
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/device/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACpG,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAA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,CAAC,EAAE,CAAC;QAC1D,MAAM,WAAW,CAAC,eAAe,EAAE,wCAAwC,CAAC,CAAC;IAC/E,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { type AuthFnRuntimeConfig, type AuthFnSchemaDefinition } from 'authfn';
|
|
2
|
+
interface DeviceStore {
|
|
3
|
+
database: AuthFnRuntimeConfig['database'];
|
|
4
|
+
namespace?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare const DEVICE_CODE_MODEL = "oauth_provider_device_codes";
|
|
7
|
+
/** The record ID prefix; tokens issued for a device code name it as their source. */
|
|
8
|
+
export declare const DEVICE_CODE_ID_PREFIX = "odv";
|
|
9
|
+
/** Device codes and user codes are valid for 10 minutes. */
|
|
10
|
+
export declare const OAUTH_DEVICE_CODE_TTL_SECONDS: number;
|
|
11
|
+
/** The minimum seconds between polls; each `slow_down` adds 5 for that device code (RFC 8628 3.5). */
|
|
12
|
+
export declare const OAUTH_DEVICE_POLL_INTERVAL_SECONDS = 5;
|
|
13
|
+
export declare function createDeviceSchema(): AuthFnSchemaDefinition['schemas'];
|
|
14
|
+
export type OAuthDeviceDecision = 'approved' | 'denied';
|
|
15
|
+
export interface DeviceCodeRecord {
|
|
16
|
+
id: string;
|
|
17
|
+
deviceCodeHash: string;
|
|
18
|
+
userCodeHash: string;
|
|
19
|
+
clientId: string;
|
|
20
|
+
resource: string;
|
|
21
|
+
scopes: string[];
|
|
22
|
+
expiresAt: Date;
|
|
23
|
+
pruneKey: string;
|
|
24
|
+
interval: number;
|
|
25
|
+
pollClaim: string;
|
|
26
|
+
decisionClaimId?: string | null;
|
|
27
|
+
decision?: OAuthDeviceDecision | null;
|
|
28
|
+
decidedAt?: Date | null;
|
|
29
|
+
userId?: string | null;
|
|
30
|
+
grantId?: string | null;
|
|
31
|
+
consumedAt?: Date | null;
|
|
32
|
+
claimId?: string | null;
|
|
33
|
+
createdAt: Date;
|
|
34
|
+
}
|
|
35
|
+
/** A random user code, shown as `XXXX-XXXX`. */
|
|
36
|
+
export declare function createUserCode(): string;
|
|
37
|
+
/**
|
|
38
|
+
* The canonical `XXXX-XXXX` form of a code the user typed: case, spaces and
|
|
39
|
+
* dashes are ignored (RFC 8628 6.1). Null when it cannot be a user code.
|
|
40
|
+
*/
|
|
41
|
+
export declare function normalizeUserCode(value: string | null | undefined): string | null;
|
|
42
|
+
/**
|
|
43
|
+
* Stores a pending device authorization and returns its codes. Only hashes
|
|
44
|
+
* are stored. When the insert throws, the row is read back by its device code:
|
|
45
|
+
* an insert that committed before its acknowledgement was lost is returned.
|
|
46
|
+
* Only a user code confirmed taken by another row (the unique index) is
|
|
47
|
+
* replaced with a fresh one, up to three tries; any other failure is thrown.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createDeviceCode(store: DeviceStore, input: {
|
|
50
|
+
clientId: string;
|
|
51
|
+
resource: string;
|
|
52
|
+
scopes: string[];
|
|
53
|
+
now: Date;
|
|
54
|
+
}): Promise<{
|
|
55
|
+
deviceCode: string;
|
|
56
|
+
userCode: string;
|
|
57
|
+
}>;
|
|
58
|
+
/**
|
|
59
|
+
* Deletes device codes no longer needed for more than one code lifetime
|
|
60
|
+
* (`pruneKey`). A code never exchanged is deleted once expired. An exchanged
|
|
61
|
+
* one backs the tokens issued for it until they expire, and after that its
|
|
62
|
+
* replay still revokes the grant and the refreshed tokens under it, so it is
|
|
63
|
+
* kept while its grant is unrevoked and holds an unexpired refresh token not
|
|
64
|
+
* yet rotated or revoked: its `pruneKey` then moves to the latest such
|
|
65
|
+
* token's expiry. The extra code lifetime leaves a request that read a code
|
|
66
|
+
* just before it expired time to finish.
|
|
67
|
+
*/
|
|
68
|
+
export declare function pruneDeviceCodes(store: DeviceStore, now: Date): Promise<void>;
|
|
69
|
+
export declare function findDeviceCode(store: DeviceStore, deviceCode: string): Promise<DeviceCodeRecord | null>;
|
|
70
|
+
/**
|
|
71
|
+
* The device authorization a normalized user code names. Null when no row
|
|
72
|
+
* or, where the adapter does not enforce the unique index, more than one
|
|
73
|
+
* row has it: an ambiguous code is never decided.
|
|
74
|
+
*/
|
|
75
|
+
export declare function findByUserCode(store: DeviceStore, userCode: string): Promise<DeviceCodeRecord | null>;
|
|
76
|
+
/**
|
|
77
|
+
* `busy`: the poll lost every round to concurrent polls of the code and
|
|
78
|
+
* changed nothing. `unknown`: it cannot tell whether its write committed.
|
|
79
|
+
* Both carry the seconds the client should wait, from the latest stored poll
|
|
80
|
+
* state (see `retryAfter`).
|
|
81
|
+
*/
|
|
82
|
+
export type PollOutcome = {
|
|
83
|
+
outcome: 'admitted' | 'slow_down';
|
|
84
|
+
} | {
|
|
85
|
+
outcome: 'busy' | 'unknown';
|
|
86
|
+
retryAfterSeconds: number;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Judges one poll of `record` against the last poll (RFC 8628 3.5). A poll
|
|
90
|
+
* within the current interval is `slow_down`: it adds 5 seconds to the
|
|
91
|
+
* interval and counts as the last poll, so a client that keeps polling early
|
|
92
|
+
* keeps being slowed. The last poll time never moves backwards: a poll that
|
|
93
|
+
* arrives with an earlier `now` than the stored one is too fast.
|
|
94
|
+
*
|
|
95
|
+
* Each poll has one outcome, stored once. Its update is conditional on the
|
|
96
|
+
* poll state it read and appends its own ID to the IDs of the last committed
|
|
97
|
+
* polls, then reads the row back. Its ID in that history means it committed,
|
|
98
|
+
* even if later polls overwrote the state since; the state it read still in
|
|
99
|
+
* the history without it means it lost to a concurrent poll, so it reads
|
|
100
|
+
* again and is judged against the winner. Adapter row counts are not used.
|
|
101
|
+
* Only when 16 or more polls committed between its read and its read-back
|
|
102
|
+
* can it not tell; it is then `unknown`, never admitted or slowed.
|
|
103
|
+
*/
|
|
104
|
+
export declare function admitPoll(store: DeviceStore, record: DeviceCodeRecord, now: Date): Promise<PollOutcome>;
|
|
105
|
+
/**
|
|
106
|
+
* Records the user's decision once; false when the code was already decided.
|
|
107
|
+
* An approval stores the user and the grant created for it.
|
|
108
|
+
*/
|
|
109
|
+
export declare function claimDecision(store: DeviceStore, recordId: string, decision: {
|
|
110
|
+
decision: OAuthDeviceDecision;
|
|
111
|
+
userId: string;
|
|
112
|
+
grantId?: string;
|
|
113
|
+
now: Date;
|
|
114
|
+
}): Promise<boolean>;
|
|
115
|
+
/**
|
|
116
|
+
* Spends an approved device code with `claimId`, which commits the tokens
|
|
117
|
+
* staged under it, and keeps the row until they expire; false when another
|
|
118
|
+
* exchange already did.
|
|
119
|
+
*/
|
|
120
|
+
/** The claim ID prefix that marks a code closed because it expired before its approval completed. */
|
|
121
|
+
export declare const EXPIRED_CLAIM_PREFIX = "odx";
|
|
122
|
+
/**
|
|
123
|
+
* Spends an approved code that expired while its approval ran, so that no
|
|
124
|
+
* exchange can commit after it; false when an exchange committed first.
|
|
125
|
+
*/
|
|
126
|
+
export declare function closeExpiredDeviceCode(store: DeviceStore, recordId: string, now: Date): Promise<boolean>;
|
|
127
|
+
export declare function claimDeviceCode(store: DeviceStore, recordId: string, now: Date, claimId: string): Promise<boolean>;
|
|
128
|
+
export {};
|
|
129
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/device/store.ts"],"names":[],"mappings":"AACA,OAAO,EAA2C,KAAK,mBAAmB,EAAE,KAAK,sBAAsB,EAAE,MAAM,QAAQ,CAAC;AAMxH,UAAU,WAAW;IACnB,QAAQ,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,iBAAiB,gCAAgC,CAAC;AAC/D,qFAAqF;AACrF,eAAO,MAAM,qBAAqB,QAAQ,CAAC;AAE3C,4DAA4D;AAC5D,eAAO,MAAM,6BAA6B,QAAU,CAAC;AACrD,sGAAsG;AACtG,eAAO,MAAM,kCAAkC,IAAI,CAAC;AAUpD,wBAAgB,kBAAkB,IAA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