@udibo/oauth2 0.47.0 → 0.49.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/dist/adapters/hono/identity.d.ts +34 -3
- package/dist/adapters/hono/identity.js +25 -11
- package/dist/identity/lockout.d.ts +24 -0
- package/dist/identity/lockout.js +26 -2
- package/dist/identity/mod.d.ts +1 -1
- package/dist/identity/service.d.ts +27 -1
- package/dist/identity/service.js +16 -2
- package/dist/identity/token-flow.d.ts +24 -3
- package/dist/identity/token-flow.js +24 -6
- package/dist/server/grants/device-authorization.d.ts +6 -0
- package/dist/server/grants/device-authorization.js +25 -4
- package/dist/server/services/device-authorization.d.ts +17 -1
- package/dist/server/services/token.d.ts +17 -0
- package/dist/testing/contract/device-authorization.js +83 -0
- package/dist/testing/contract/device-code-exchange.d.ts +112 -0
- package/dist/testing/contract/device-code-exchange.js +242 -0
- package/dist/testing/contract/lockout-store.d.ts +10 -0
- package/dist/testing/contract/lockout-store.js +62 -1
- package/dist/testing/contract/mod.d.ts +6 -0
- package/dist/testing/contract/mod.js +6 -0
- package/dist/testing/contract/token-flow-store.d.ts +10 -0
- package/dist/testing/contract/token-flow-store.js +47 -0
- package/dist/testing/services.d.ts +26 -6
- package/dist/testing/services.js +55 -14
- package/package.json +1 -1
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* Session creation stays in your app: the `signup`/`signin` routes call your
|
|
30
30
|
* `onAuthenticated(c, user)` hook on success, where you mint your session and
|
|
31
31
|
* return a `Response` (e.g. a redirect via `bff.loginContinuation`). Omit the
|
|
32
|
-
* hook to
|
|
32
|
+
* hook to leave those two routes unmounted. `/email/verify` reads your session
|
|
33
|
+
* through the `sessionUserId(c)` option and is mounted only when you pass it.
|
|
33
34
|
*
|
|
34
35
|
* Accepts JSON or form-encoded bodies. Responses are simple JSON
|
|
35
36
|
* (`{ ok: true }` / `{ error }`); render your own UI around them. Because a
|
|
@@ -52,7 +53,10 @@ export interface HonoIdentityPaths {
|
|
|
52
53
|
requestPasswordReset?: string;
|
|
53
54
|
/** `POST` password reset (consume token). Default `/password/reset`. */
|
|
54
55
|
resetPassword?: string;
|
|
55
|
-
/**
|
|
56
|
+
/**
|
|
57
|
+
* `POST` email verification (consume token), mounted only with
|
|
58
|
+
* {@link HonoIdentityOptions.sessionUserId}. Default `/email/verify`.
|
|
59
|
+
*/
|
|
56
60
|
verifyEmail?: string;
|
|
57
61
|
}
|
|
58
62
|
/**
|
|
@@ -114,11 +118,38 @@ export interface HonoIdentityOptions<User extends IdentityUser> {
|
|
|
114
118
|
onAuthenticated?: (c: Context, user: User, action: "signUp" | "signIn") => Response | Promise<Response>;
|
|
115
119
|
/** Override the default paths. */
|
|
116
120
|
paths?: HonoIdentityPaths;
|
|
121
|
+
/**
|
|
122
|
+
* Reads the id of the user your app has signed in on this request, or
|
|
123
|
+
* `null`/`undefined` when there is no session. **Required to mount the
|
|
124
|
+
* `/email/verify` route**, which passes it to
|
|
125
|
+
* {@link IdentityService.verifyEmail}: a link verifies only for the account
|
|
126
|
+
* it was minted for. A live link posted with no session answers `401`
|
|
127
|
+
* `{ error: "sign_in_required" }`, and with another account's session `403`
|
|
128
|
+
* `{ error: "wrong_account" }`; both leave the link unspent, so send the
|
|
129
|
+
* person to sign in and post the same token again.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```ts
|
|
133
|
+
* import { honoIdentityRoutes } from "@udibo/oauth2/hono/identity";
|
|
134
|
+
* import type { IdentityService } from "@udibo/oauth2/identity";
|
|
135
|
+
* import type { Context } from "hono";
|
|
136
|
+
*
|
|
137
|
+
* declare const identity: IdentityService<{ id: string }>;
|
|
138
|
+
* declare function readSession(c: Context): { userId: string } | undefined;
|
|
139
|
+
*
|
|
140
|
+
* honoIdentityRoutes(identity, {
|
|
141
|
+
* sessionUserId: (c) => readSession(c)?.userId,
|
|
142
|
+
* });
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
sessionUserId?: (c: Context) => string | null | undefined | Promise<string | null | undefined>;
|
|
117
146
|
}
|
|
118
147
|
/**
|
|
119
148
|
* Build a Hono app mounting the password-credential endpoints
|
|
120
149
|
* (`/signup`, `/signin`, `/password/reset-request`, `/password/reset`,
|
|
121
|
-
* `/email/verify`) over `service`.
|
|
150
|
+
* `/email/verify`) over `service`. `/signup` and `/signin` need
|
|
151
|
+
* {@link HonoIdentityOptions.onAuthenticated}, and `/email/verify` needs
|
|
152
|
+
* {@link HonoIdentityOptions.sessionUserId}. Mount it wherever you like, e.g.
|
|
122
153
|
* `app.route("/auth", honoIdentityRoutes(service, …))`.
|
|
123
154
|
*
|
|
124
155
|
* A JSON body keeps each field's type except `password`, `identifier`, `email`,
|
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* Session creation stays in your app: the `signup`/`signin` routes call your
|
|
30
30
|
* `onAuthenticated(c, user)` hook on success, where you mint your session and
|
|
31
31
|
* return a `Response` (e.g. a redirect via `bff.loginContinuation`). Omit the
|
|
32
|
-
* hook to
|
|
32
|
+
* hook to leave those two routes unmounted. `/email/verify` reads your session
|
|
33
|
+
* through the `sessionUserId(c)` option and is mounted only when you pass it.
|
|
33
34
|
*
|
|
34
35
|
* Accepts JSON or form-encoded bodies. Responses are simple JSON
|
|
35
36
|
* (`{ ok: true }` / `{ error }`); render your own UI around them. Because a
|
|
@@ -141,7 +142,9 @@ function sameOriginGuard(options) {
|
|
|
141
142
|
/**
|
|
142
143
|
* Build a Hono app mounting the password-credential endpoints
|
|
143
144
|
* (`/signup`, `/signin`, `/password/reset-request`, `/password/reset`,
|
|
144
|
-
* `/email/verify`) over `service`.
|
|
145
|
+
* `/email/verify`) over `service`. `/signup` and `/signin` need
|
|
146
|
+
* {@link HonoIdentityOptions.onAuthenticated}, and `/email/verify` needs
|
|
147
|
+
* {@link HonoIdentityOptions.sessionUserId}. Mount it wherever you like, e.g.
|
|
145
148
|
* `app.route("/auth", honoIdentityRoutes(service, …))`.
|
|
146
149
|
*
|
|
147
150
|
* A JSON body keeps each field's type except `password`, `identifier`, `email`,
|
|
@@ -172,7 +175,7 @@ export function honoIdentityRoutes(service, options = {}) {
|
|
|
172
175
|
verifyEmail: "/email/verify",
|
|
173
176
|
...options.paths,
|
|
174
177
|
};
|
|
175
|
-
const onAuthenticated = options
|
|
178
|
+
const { onAuthenticated, sessionUserId } = options;
|
|
176
179
|
if (options.csrf !== false) {
|
|
177
180
|
app.use("*", sameOriginGuard(options.csrf ?? {}));
|
|
178
181
|
}
|
|
@@ -211,13 +214,24 @@ export function honoIdentityRoutes(service, options = {}) {
|
|
|
211
214
|
? c.json({ ok: true })
|
|
212
215
|
: c.json({ error: "invalid_token" }, 400);
|
|
213
216
|
}));
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
217
|
+
if (sessionUserId) {
|
|
218
|
+
app.post(paths.verifyEmail, handle(async (c) => {
|
|
219
|
+
const body = await readBody(c, maxBodyBytes);
|
|
220
|
+
const result = await service.verifyEmail({
|
|
221
|
+
token: String(body.token ?? ""),
|
|
222
|
+
sessionUserId: (await sessionUserId(c)) ?? null,
|
|
223
|
+
});
|
|
224
|
+
switch (result.status) {
|
|
225
|
+
case "success":
|
|
226
|
+
return c.json({ ok: true, userId: result.userId });
|
|
227
|
+
case "sign-in-required":
|
|
228
|
+
return c.json({ error: "sign_in_required" }, 401);
|
|
229
|
+
case "wrong-account":
|
|
230
|
+
return c.json({ error: "wrong_account" }, 403);
|
|
231
|
+
default:
|
|
232
|
+
return c.json({ error: `token_${result.status}` }, 400);
|
|
233
|
+
}
|
|
234
|
+
}));
|
|
235
|
+
}
|
|
222
236
|
return app;
|
|
223
237
|
}
|
|
@@ -51,6 +51,23 @@ export interface LockoutStore {
|
|
|
51
51
|
* merging: a record with no `lockedUntil` leaves the account unlocked.
|
|
52
52
|
*/
|
|
53
53
|
set(userId: string, record: LockoutRecord): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Optional: lock the account until `record.lockedUntil` only while its stored
|
|
56
|
+
* count is still at least `record.failures`, keeping the stored count, and
|
|
57
|
+
* resolve whether the lock was written. It must be one conditional write
|
|
58
|
+
* (`UPDATE … SET locked_until = $until WHERE failures >= $failures`, checking
|
|
59
|
+
* the row count), never a read then a write. `now` is the clock `increment`
|
|
60
|
+
* was given, for a store that expires records.
|
|
61
|
+
*
|
|
62
|
+
* `AccountLockout` calls it instead of {@link LockoutStore.set} when an
|
|
63
|
+
* attempt's count reaches `maxAttempts`. Without it, the lock is an
|
|
64
|
+
* unconditional `set` after `increment`, so an over-budget attempt whose
|
|
65
|
+
* lock lands after a concurrent {@link LockoutStore.clear} re-locks an
|
|
66
|
+
* account that just signed in, and no lockout event reports it.
|
|
67
|
+
*/
|
|
68
|
+
lock?(userId: string, record: LockoutRecord & {
|
|
69
|
+
lockedUntil: number;
|
|
70
|
+
}, now: number): Promise<boolean>;
|
|
54
71
|
/** Clear the account's record (successful sign-in or unlock). */
|
|
55
72
|
clear(userId: string): Promise<void>;
|
|
56
73
|
}
|
|
@@ -253,6 +270,13 @@ export declare class MemoryLockoutStore implements LockoutStore {
|
|
|
253
270
|
* record for an account with none is timed from now.
|
|
254
271
|
*/
|
|
255
272
|
set(userId: string, record: LockoutRecord): Promise<void>;
|
|
273
|
+
/**
|
|
274
|
+
* Lock `userId` until `record.lockedUntil` when its live record still
|
|
275
|
+
* counts at least `record.failures`; resolves whether it did.
|
|
276
|
+
*/
|
|
277
|
+
lock(userId: string, record: LockoutRecord & {
|
|
278
|
+
lockedUntil: number;
|
|
279
|
+
}, now: number): Promise<boolean>;
|
|
256
280
|
/** Drop `userId`'s record. */
|
|
257
281
|
clear(userId: string): Promise<void>;
|
|
258
282
|
}
|
package/dist/identity/lockout.js
CHANGED
|
@@ -73,7 +73,7 @@ export class AccountLockout {
|
|
|
73
73
|
reserveAttempt(userId, now = Date.now()) {
|
|
74
74
|
return this.#count(userId, now);
|
|
75
75
|
}
|
|
76
|
-
async #count(userId, now = Date.now()) {
|
|
76
|
+
async #count(userId, now = Date.now(), recounted = false) {
|
|
77
77
|
const record = await this.#store.increment(userId, now);
|
|
78
78
|
const { failures } = record;
|
|
79
79
|
if (record.lockedUntil !== undefined && record.lockedUntil > now) {
|
|
@@ -86,7 +86,11 @@ export class AccountLockout {
|
|
|
86
86
|
}
|
|
87
87
|
if (failures >= this.#maxAttempts) {
|
|
88
88
|
const lockedUntil = now + this.#lockDurationMs;
|
|
89
|
-
await this.#
|
|
89
|
+
if (!(await this.#lock(userId, { failures, lockedUntil }, now))) {
|
|
90
|
+
if (!recounted)
|
|
91
|
+
return this.#count(userId, now, true);
|
|
92
|
+
return { failures, locked: false, justLocked: false };
|
|
93
|
+
}
|
|
90
94
|
// Concurrent attempts can overshoot the threshold before the lock lands;
|
|
91
95
|
// only the attempt that hits it exactly reports justLocked, so the
|
|
92
96
|
// lockout event (and any unlock email) fires once.
|
|
@@ -99,6 +103,12 @@ export class AccountLockout {
|
|
|
99
103
|
}
|
|
100
104
|
return { failures, locked: false, justLocked: false };
|
|
101
105
|
}
|
|
106
|
+
async #lock(userId, record, now) {
|
|
107
|
+
if (this.#store.lock)
|
|
108
|
+
return this.#store.lock(userId, record, now);
|
|
109
|
+
await this.#store.set(userId, record);
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
102
112
|
/** Clear the account's failures and any lock (successful sign-in, unlock). */
|
|
103
113
|
reset(userId) {
|
|
104
114
|
return this.#store.clear(userId);
|
|
@@ -195,6 +205,20 @@ export class MemoryLockoutStore {
|
|
|
195
205
|
this.#collect(userId, touchedAt);
|
|
196
206
|
return Promise.resolve();
|
|
197
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Lock `userId` until `record.lockedUntil` when its live record still
|
|
210
|
+
* counts at least `record.failures`; resolves whether it did.
|
|
211
|
+
*/
|
|
212
|
+
lock(userId, record, now) {
|
|
213
|
+
const entry = this.#entries.get(userId);
|
|
214
|
+
if (!entry ||
|
|
215
|
+
this.#expired(entry, now) ||
|
|
216
|
+
entry.record.failures < record.failures) {
|
|
217
|
+
return Promise.resolve(false);
|
|
218
|
+
}
|
|
219
|
+
entry.record = { ...entry.record, lockedUntil: record.lockedUntil };
|
|
220
|
+
return Promise.resolve(true);
|
|
221
|
+
}
|
|
198
222
|
/** Drop `userId`'s record. */
|
|
199
223
|
clear(userId) {
|
|
200
224
|
this.#entries.delete(userId);
|
package/dist/identity/mod.d.ts
CHANGED
|
@@ -53,7 +53,7 @@ export { classifyIdentifier, createIdentifierResolver, type IdentifierKind, type
|
|
|
53
53
|
export { type CreatedToken, type CreateTokenOptions, MemoryTokenFlowStore, type ResolvedToken, type TokenFlowRecord, TokenFlowService, type TokenFlowStore, TokenPurpose, type TokenStatus, } from "./token-flow.ts";
|
|
54
54
|
export { buildResetUrl, buildSignInUrl, buildTokenUrl, buildUnlockUrl, buildVerificationUrl, type CodeDeliveryHook, type CodeDeliveryMessage, type DeliveryHook, type DeliveryHooks, type DeliveryMessage, } from "./delivery.ts";
|
|
55
55
|
export { isRecentlyAuthenticated, type ListableSessionService, type RevocableSessionService, type SessionSummary, supportsSessionListing, } from "./session.ts";
|
|
56
|
-
export { type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
|
|
56
|
+
export { type ConsumeSignInLinkResult, type IdentityRateLimiters, IdentityService, type IdentityServiceOptions, type IdentityUser, type IdentityUserStore, type UnlockAccountResult, type VerifyEmailInput, type VerifyEmailResult, type VerifySignInCodeResult, } from "./service.ts";
|
|
57
57
|
export { EmailOtpService, type EmailOtpServiceOptions, MemoryOtpStore, type OtpRecord, type OtpStore, type RequestedOtp, type RequestOtpOptions, type VerifyOtpOptions, type VerifyOtpResult, } from "./otp.ts";
|
|
58
58
|
export { AccountLockout, type AccountLockoutLike, type AccountLockoutOptions, type LockoutFailureResult, type LockoutRecord, type LockoutStatus, type LockoutStore, MemoryLockoutStore, type MemoryLockoutStoreOptions, } from "./lockout.ts";
|
|
59
59
|
export type { IdentityEvent, IdentityEventHook, SignInCodeFailureReason, SignInFailureReason, } from "./events.ts";
|
|
@@ -361,6 +361,12 @@ export interface IdentityServiceOptions<User extends IdentityUser> {
|
|
|
361
361
|
* Outcome of {@link IdentityService.verifyEmail}. `success` carries the verified
|
|
362
362
|
* user; `expired` and `invalid` are distinguished so the UI can offer to resend
|
|
363
363
|
* an expired link rather than showing one generic error.
|
|
364
|
+
*
|
|
365
|
+
* `sign-in-required` (no session) and `wrong-account` (a session for a
|
|
366
|
+
* different user) answer a live link that was not presented by the account it
|
|
367
|
+
* was minted for. The link stays unspent and the address stays unverified, so
|
|
368
|
+
* show a sign-in prompt and let the person retry the same link once signed in
|
|
369
|
+
* as that account.
|
|
364
370
|
*/
|
|
365
371
|
export type VerifyEmailResult = {
|
|
366
372
|
status: "success";
|
|
@@ -370,7 +376,22 @@ export type VerifyEmailResult = {
|
|
|
370
376
|
status: "expired";
|
|
371
377
|
} | {
|
|
372
378
|
status: "invalid";
|
|
379
|
+
} | {
|
|
380
|
+
status: "sign-in-required";
|
|
381
|
+
} | {
|
|
382
|
+
status: "wrong-account";
|
|
373
383
|
};
|
|
384
|
+
/** Input to {@link IdentityService.verifyEmail}. */
|
|
385
|
+
export interface VerifyEmailInput {
|
|
386
|
+
/** The token from the emailed verification link. */
|
|
387
|
+
token: string;
|
|
388
|
+
/**
|
|
389
|
+
* The id of the user signed in on the request presenting the link, or
|
|
390
|
+
* `null` when it carries no session. Only that user's own link verifies;
|
|
391
|
+
* read it from your session, never from the request body.
|
|
392
|
+
*/
|
|
393
|
+
sessionUserId: string | null;
|
|
394
|
+
}
|
|
374
395
|
/**
|
|
375
396
|
* Outcome of {@link IdentityService.consumeSignInLink}. `expired` and
|
|
376
397
|
* `invalid` are distinguished so the UI can offer a fresh link for an expired
|
|
@@ -551,6 +572,11 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
551
572
|
/**
|
|
552
573
|
* Consume a verification token and mark the user's email verified.
|
|
553
574
|
*
|
|
575
|
+
* The token verifies only for a request signed in as the user it was minted
|
|
576
|
+
* for: pass that session's user id as `sessionUserId`. A live token with no
|
|
577
|
+
* session reports `sign-in-required`, and with another user's session
|
|
578
|
+
* `wrong-account`; both leave it unspent and the address unverified.
|
|
579
|
+
*
|
|
554
580
|
* Returns a discriminated {@link VerifyEmailResult} so the UI can tell an
|
|
555
581
|
* **expired** link (offer to resend) from a generically **invalid** one — the
|
|
556
582
|
* `inspect()` distinction, surfaced through the flow. A `valid` token is
|
|
@@ -566,7 +592,7 @@ export declare class IdentityService<User extends IdentityUser> {
|
|
|
566
592
|
* store that predicates on both never verifies an address the link was not
|
|
567
593
|
* minted for.
|
|
568
594
|
*/
|
|
569
|
-
verifyEmail(
|
|
595
|
+
verifyEmail(input: VerifyEmailInput): Promise<VerifyEmailResult>;
|
|
570
596
|
/**
|
|
571
597
|
* Mint + deliver a single-use account-unlock link after a lockout. Call it
|
|
572
598
|
* with the locked account's email (typically from your `lockout` event
|
package/dist/identity/service.js
CHANGED
|
@@ -32,6 +32,11 @@ const DEFAULT_VERIFY_TTL = 24 * 60 * 60 * 1000;
|
|
|
32
32
|
const DEFAULT_UNLOCK_TTL = 60 * 60 * 1000;
|
|
33
33
|
const DEFAULT_SIGNIN_LINK_TTL = 15 * 60 * 1000;
|
|
34
34
|
const DEFAULT_FAILED_SIGN_IN_FLOOR_MS = 250;
|
|
35
|
+
function sessionRefusal(sessionUserId, subject) {
|
|
36
|
+
if (!sessionUserId)
|
|
37
|
+
return "sign-in-required";
|
|
38
|
+
return sessionUserId === subject ? null : "wrong-account";
|
|
39
|
+
}
|
|
35
40
|
function foldEmail(email) {
|
|
36
41
|
return email.trim().toLowerCase();
|
|
37
42
|
}
|
|
@@ -394,6 +399,11 @@ export class IdentityService {
|
|
|
394
399
|
/**
|
|
395
400
|
* Consume a verification token and mark the user's email verified.
|
|
396
401
|
*
|
|
402
|
+
* The token verifies only for a request signed in as the user it was minted
|
|
403
|
+
* for: pass that session's user id as `sessionUserId`. A live token with no
|
|
404
|
+
* session reports `sign-in-required`, and with another user's session
|
|
405
|
+
* `wrong-account`; both leave it unspent and the address unverified.
|
|
406
|
+
*
|
|
397
407
|
* Returns a discriminated {@link VerifyEmailResult} so the UI can tell an
|
|
398
408
|
* **expired** link (offer to resend) from a generically **invalid** one — the
|
|
399
409
|
* `inspect()` distinction, surfaced through the flow. A `valid` token is
|
|
@@ -409,13 +419,14 @@ export class IdentityService {
|
|
|
409
419
|
* store that predicates on both never verifies an address the link was not
|
|
410
420
|
* minted for.
|
|
411
421
|
*/
|
|
412
|
-
async verifyEmail(
|
|
422
|
+
async verifyEmail(input) {
|
|
413
423
|
const tokens = this.#requireTokens("verifyEmail");
|
|
414
424
|
const result = await this.#consumeToken({
|
|
415
425
|
tokens,
|
|
416
426
|
purpose: TokenPurpose.EmailVerification,
|
|
417
|
-
token,
|
|
427
|
+
token: input.token,
|
|
418
428
|
failed: (reason) => ({ type: "email_verification.failed", reason }),
|
|
429
|
+
refuse: (subject) => sessionRefusal(input.sessionUserId, subject),
|
|
419
430
|
beforeConsume: (subject, data) => this.#users.markEmailVerified?.(subject, emailFromData(data)),
|
|
420
431
|
});
|
|
421
432
|
if (result.status !== "success")
|
|
@@ -860,6 +871,9 @@ export class IdentityService {
|
|
|
860
871
|
await this.#emit(input.failed("invalid"));
|
|
861
872
|
return { status: "invalid" };
|
|
862
873
|
}
|
|
874
|
+
const refusal = input.refuse?.(status.subject);
|
|
875
|
+
if (refusal)
|
|
876
|
+
return { status: refusal };
|
|
863
877
|
await input.beforeConsume?.(status.subject, status.data);
|
|
864
878
|
const resolved = await tokens.consume(purpose, token);
|
|
865
879
|
if (!resolved) {
|
|
@@ -78,6 +78,20 @@ export interface TokenFlowStore {
|
|
|
78
78
|
* really was used, instead of the generic `invalid`.
|
|
79
79
|
*/
|
|
80
80
|
deleteBySubject?(purpose: string, subject: string): Promise<void>;
|
|
81
|
+
/**
|
|
82
|
+
* Optional: delete every still-pending record for `(record.purpose,
|
|
83
|
+
* record.subject)` and save `record`, as one atomic step. Concurrent calls
|
|
84
|
+
* for one pair must leave exactly one of their records pending, so serialize
|
|
85
|
+
* them on the pair (a row lock or advisory lock taken before the delete, or
|
|
86
|
+
* a unique index on pending rows): two transactions that each delete and
|
|
87
|
+
* then insert under read committed both leave their row behind. Keep
|
|
88
|
+
* consumed records, as {@link TokenFlowStore.deleteBySubject} does.
|
|
89
|
+
*
|
|
90
|
+
* {@link TokenFlowService.create} calls it for `invalidateExisting` when
|
|
91
|
+
* present. Without it, the service deletes and then saves in two calls, so
|
|
92
|
+
* concurrent requests for one pair each leave a live link.
|
|
93
|
+
*/
|
|
94
|
+
replacePending?(record: TokenFlowRecord): Promise<void>;
|
|
81
95
|
}
|
|
82
96
|
/** Options for {@link TokenFlowService.create}. */
|
|
83
97
|
export interface CreateTokenOptions {
|
|
@@ -90,9 +104,11 @@ export interface CreateTokenOptions {
|
|
|
90
104
|
/** Lifetime in milliseconds. */
|
|
91
105
|
ttlMs: number;
|
|
92
106
|
/**
|
|
93
|
-
* Invalidate any existing pending tokens for this `(purpose, subject)
|
|
94
|
-
*
|
|
95
|
-
* {@link TokenFlowStore.
|
|
107
|
+
* Invalidate any existing pending tokens for this `(purpose, subject)`,
|
|
108
|
+
* atomically with saving the new one when the store implements
|
|
109
|
+
* {@link TokenFlowStore.replacePending}. Silently skipped when the store
|
|
110
|
+
* implements neither it nor {@link TokenFlowStore.deleteBySubject}. Defaults
|
|
111
|
+
* to `false`.
|
|
96
112
|
*/
|
|
97
113
|
invalidateExisting?: boolean;
|
|
98
114
|
}
|
|
@@ -211,4 +227,9 @@ export declare class MemoryTokenFlowStore implements TokenFlowStore {
|
|
|
211
227
|
* still report `consumed` rather than the generic `invalid`.
|
|
212
228
|
*/
|
|
213
229
|
deleteBySubject(purpose: string, subject: string): Promise<void>;
|
|
230
|
+
/**
|
|
231
|
+
* Drop the pending records for the record's `(purpose, subject)` and save
|
|
232
|
+
* it, in one synchronous step.
|
|
233
|
+
*/
|
|
234
|
+
replacePending(record: TokenFlowRecord): Promise<void>;
|
|
214
235
|
}
|
|
@@ -59,20 +59,26 @@ export class TokenFlowService {
|
|
|
59
59
|
}
|
|
60
60
|
/** Mint a token; stores its hash and returns the raw token (once). */
|
|
61
61
|
async create(opts) {
|
|
62
|
-
if (opts.invalidateExisting) {
|
|
63
|
-
await this.invalidate(opts.purpose, opts.subject);
|
|
64
|
-
}
|
|
65
62
|
const token = randomToken();
|
|
66
63
|
const now = Date.now();
|
|
67
64
|
const expiresAt = now + opts.ttlMs;
|
|
68
|
-
|
|
65
|
+
const record = {
|
|
69
66
|
tokenHash: await sha256Hash(token),
|
|
70
67
|
purpose: opts.purpose,
|
|
71
68
|
subject: opts.subject,
|
|
72
69
|
data: opts.data,
|
|
73
70
|
expiresAt,
|
|
74
71
|
createdAt: now,
|
|
75
|
-
}
|
|
72
|
+
};
|
|
73
|
+
if (opts.invalidateExisting && this.#store.replacePending) {
|
|
74
|
+
await this.#store.replacePending(record);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
if (opts.invalidateExisting) {
|
|
78
|
+
await this.invalidate(opts.purpose, opts.subject);
|
|
79
|
+
}
|
|
80
|
+
await this.#store.save(record);
|
|
81
|
+
}
|
|
76
82
|
return { token, expiresAt };
|
|
77
83
|
}
|
|
78
84
|
/**
|
|
@@ -161,6 +167,19 @@ export class MemoryTokenFlowStore {
|
|
|
161
167
|
* still report `consumed` rather than the generic `invalid`.
|
|
162
168
|
*/
|
|
163
169
|
deleteBySubject(purpose, subject) {
|
|
170
|
+
this.#deletePending(purpose, subject);
|
|
171
|
+
return Promise.resolve();
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Drop the pending records for the record's `(purpose, subject)` and save
|
|
175
|
+
* it, in one synchronous step.
|
|
176
|
+
*/
|
|
177
|
+
replacePending(record) {
|
|
178
|
+
this.#deletePending(record.purpose, record.subject);
|
|
179
|
+
this.#byHash.set(record.tokenHash, record);
|
|
180
|
+
return Promise.resolve();
|
|
181
|
+
}
|
|
182
|
+
#deletePending(purpose, subject) {
|
|
164
183
|
for (const [hash, record] of this.#byHash) {
|
|
165
184
|
if (record.purpose === purpose &&
|
|
166
185
|
record.subject === subject &&
|
|
@@ -168,6 +187,5 @@ export class MemoryTokenFlowStore {
|
|
|
168
187
|
this.#byHash.delete(hash);
|
|
169
188
|
}
|
|
170
189
|
}
|
|
171
|
-
return Promise.resolve();
|
|
172
190
|
}
|
|
173
191
|
}
|
|
@@ -80,6 +80,12 @@ export declare class DeviceAuthorizationGrant<Client extends ClientInterface, Us
|
|
|
80
80
|
*
|
|
81
81
|
* The device code is claimed by revoking it once the user has approved, so
|
|
82
82
|
* concurrent polls of one approved device code cannot both receive a token.
|
|
83
|
+
* When the token service implements
|
|
84
|
+
* {@linkcode TokenServiceInterface.exchangeDeviceCode}, the claim and the
|
|
85
|
+
* token's save are that one call, and a save that fails leaves the approval
|
|
86
|
+
* for the next poll; otherwise the grant revokes and then saves, and a
|
|
87
|
+
* failed save spends the approval. A token that cannot be generated spends
|
|
88
|
+
* it either way.
|
|
83
89
|
* Recording the poll time is bookkeeping for `slow_down` only: it is skipped
|
|
84
90
|
* on every outcome that revokes the authorization. When the store **raises**
|
|
85
91
|
* for the vanished record — as it must, if a lost race is to be
|
|
@@ -75,6 +75,12 @@ export class DeviceAuthorizationGrant extends AbstractGrant {
|
|
|
75
75
|
*
|
|
76
76
|
* The device code is claimed by revoking it once the user has approved, so
|
|
77
77
|
* concurrent polls of one approved device code cannot both receive a token.
|
|
78
|
+
* When the token service implements
|
|
79
|
+
* {@linkcode TokenServiceInterface.exchangeDeviceCode}, the claim and the
|
|
80
|
+
* token's save are that one call, and a save that fails leaves the approval
|
|
81
|
+
* for the next poll; otherwise the grant revokes and then saves, and a
|
|
82
|
+
* failed save spends the approval. A token that cannot be generated spends
|
|
83
|
+
* it either way.
|
|
78
84
|
* Recording the poll time is bookkeeping for `slow_down` only: it is skipped
|
|
79
85
|
* on every outcome that revokes the authorization. When the store **raises**
|
|
80
86
|
* for the vanished record — as it must, if a lost race is to be
|
|
@@ -129,11 +135,26 @@ export class DeviceAuthorizationGrant extends AbstractGrant {
|
|
|
129
135
|
throw new AuthorizationPendingError("authorization request is pending user approval");
|
|
130
136
|
}
|
|
131
137
|
const { user, scope } = authorization;
|
|
132
|
-
|
|
133
|
-
|
|
138
|
+
const exchangeDeviceCode = tokenService.exchangeDeviceCode?.bind(tokenService);
|
|
139
|
+
if (!exchangeDeviceCode) {
|
|
140
|
+
if (!(await deviceAuthorizationService.revoke(authorization))) {
|
|
141
|
+
throw new InvalidGrantError("device_code already used");
|
|
142
|
+
}
|
|
143
|
+
const token = await this.generateToken(client, user, scope, tokenService);
|
|
144
|
+
return await tokenService.save(token);
|
|
145
|
+
}
|
|
146
|
+
let token;
|
|
147
|
+
try {
|
|
148
|
+
token = await this.generateToken(client, user, scope, tokenService);
|
|
134
149
|
}
|
|
135
|
-
|
|
136
|
-
|
|
150
|
+
catch (error) {
|
|
151
|
+
await deviceAuthorizationService.revoke(authorization);
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
const saved = await exchangeDeviceCode(authorization, token);
|
|
155
|
+
if (!saved)
|
|
156
|
+
throw new InvalidGrantError("device_code already used");
|
|
157
|
+
return saved;
|
|
137
158
|
}
|
|
138
159
|
async #recordPoll(deviceAuthorizationService, authorization, deviceCode) {
|
|
139
160
|
try {
|
|
@@ -14,7 +14,7 @@ import type { AbstractScope } from "../../models/scope.ts";
|
|
|
14
14
|
* - Generating and storing device codes and user codes
|
|
15
15
|
* - Looking up device codes for polling
|
|
16
16
|
* - Looking up user codes for user authorization
|
|
17
|
-
* - Marking codes as authorized or denied
|
|
17
|
+
* - Marking pending codes as authorized or denied, once
|
|
18
18
|
* - Cleaning up expired codes
|
|
19
19
|
*
|
|
20
20
|
* **Every method taking a `DeviceAuthorization` must accept the records this
|
|
@@ -82,6 +82,17 @@ export interface DeviceAuthorizationServiceInterface<Client extends ClientInterf
|
|
|
82
82
|
/**
|
|
83
83
|
* Marks a device authorization as authorized by the user.
|
|
84
84
|
*
|
|
85
|
+
* **Approve only a pending authorization, in one conditional write.** The
|
|
86
|
+
* record must still be stored, unexpired, and neither approved nor denied;
|
|
87
|
+
* otherwise reject and change nothing. In SQL this is an `UPDATE ... WHERE
|
|
88
|
+
* device_code = $1 AND NOT authorized AND NOT denied AND expires_at > now()`
|
|
89
|
+
* whose affected-row count decides. Never re-create a record that is gone:
|
|
90
|
+
* the grant claims an authorization by revoking it, so an upsert here
|
|
91
|
+
* after the claim makes the spent device code redeemable for a second
|
|
92
|
+
* token. A second approval must not re-bind the device to another user. To
|
|
93
|
+
* withdraw an approval before the device claims it, call
|
|
94
|
+
* {@linkcode DeviceAuthorizationServiceInterface.revoke}.
|
|
95
|
+
*
|
|
85
96
|
* @param authorization The authorization to approve
|
|
86
97
|
* @param user The user who approved the request
|
|
87
98
|
* @param scope Optional scope (may be narrower than originally requested)
|
|
@@ -89,6 +100,11 @@ export interface DeviceAuthorizationServiceInterface<Client extends ClientInterf
|
|
|
89
100
|
approve(authorization: DeviceAuthorization<Client, User, Scope>, user: User, scope?: Scope | null): Promise<DeviceAuthorization<Client, User, Scope>>;
|
|
90
101
|
/**
|
|
91
102
|
* Marks a device authorization as denied by the user.
|
|
103
|
+
*
|
|
104
|
+
* The same precondition as
|
|
105
|
+
* {@linkcode DeviceAuthorizationServiceInterface.approve} applies: deny only
|
|
106
|
+
* a stored, unexpired authorization that is neither approved nor denied, in
|
|
107
|
+
* one conditional write, and reject otherwise without re-creating it.
|
|
92
108
|
*/
|
|
93
109
|
deny(authorization: DeviceAuthorization<Client, User, Scope>): Promise<DeviceAuthorization<Client, User, Scope>>;
|
|
94
110
|
/**
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ClientInterface } from "../../models/client.ts";
|
|
2
2
|
import type { AuthenticationContext } from "../../models/authentication.ts";
|
|
3
3
|
import type { AuthorizationCode } from "../../models/authorization-code.ts";
|
|
4
|
+
import type { DeviceAuthorization } from "../../models/device-authorization.ts";
|
|
4
5
|
import type { RefreshToken, Token } from "../../models/token.ts";
|
|
5
6
|
import type { AbstractScope, BasicScope } from "../../models/scope.ts";
|
|
6
7
|
import type { ClientServiceInterface } from "./client.ts";
|
|
@@ -236,6 +237,22 @@ export interface TokenServiceInterface<Client extends ClientInterface, User, Sco
|
|
|
236
237
|
* the store's barrier wired between its claim and its insert.
|
|
237
238
|
*/
|
|
238
239
|
exchangeCode?(authorizationCode: AuthorizationCode<Client, User, Scope>, token: Token<Client, User, Scope>): Promise<Token<Client, User, Scope> | undefined>;
|
|
240
|
+
/**
|
|
241
|
+
* Redeems an approved device authorization in one atomic step: claims
|
|
242
|
+
* `authorization` as `DeviceAuthorizationServiceInterface.revoke` would,
|
|
243
|
+
* removing it by both of its codes, and persists `token`, the token issued
|
|
244
|
+
* from it, or does neither. Resolves the saved token, or `undefined` with
|
|
245
|
+
* nothing persisted when the authorization was already claimed or never
|
|
246
|
+
* stored. Concurrent calls for one device code persist exactly one token.
|
|
247
|
+
*
|
|
248
|
+
* When implemented, the device authorization grant calls it instead of
|
|
249
|
+
* claiming with `revoke` and saving with {@linkcode save}. Without it, the
|
|
250
|
+
* grant claims and then saves in two calls, so a save that fails after the
|
|
251
|
+
* claim spends the user's approval and the device must start over. A failed
|
|
252
|
+
* insert must leave the authorization claimable; committing the delete and
|
|
253
|
+
* the insert in one database transaction meets this.
|
|
254
|
+
*/
|
|
255
|
+
exchangeDeviceCode?(authorization: DeviceAuthorization<Client, User, Scope>, token: Token<Client, User, Scope>): Promise<Token<Client, User, Scope> | undefined>;
|
|
239
256
|
/**
|
|
240
257
|
* Looks up a refresh token that has already been revoked/rotated out. The
|
|
241
258
|
* refresh grant's reuse detection reads it, and so does the revocation
|