@rebasepro/server 0.29.3 → 0.30.1
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/{access-BihomvkO.js → access-1wrvwWls.js} +2 -2
- package/dist/{access-BihomvkO.js.map → access-1wrvwWls.js.map} +1 -1
- package/dist/auth/auth-hooks.d.ts +3 -2
- package/dist/auth/builtin-auth-adapter.d.ts +2 -0
- package/dist/auth/capabilities.d.ts +2 -0
- package/dist/auth/device-login-routes.d.ts +100 -0
- package/dist/auth/device-login-store.d.ts +102 -0
- package/dist/auth/routes.d.ts +7 -0
- package/dist/{auth-C-RJT4VO.js → auth-Bzb_b1KY.js} +232 -7
- package/dist/auth-Bzb_b1KY.js.map +1 -0
- package/dist/auth_adapter-HFv5axIT.js.map +1 -1
- package/dist/backend/options.d.ts +32 -9
- package/dist/{backup-D-ds7wml.js → backup-PN6AM4UK.js} +2 -2
- package/dist/{backup-D-ds7wml.js.map → backup-PN6AM4UK.js.map} +1 -1
- package/dist/dist--rf-rq-r.js +19359 -0
- package/dist/dist--rf-rq-r.js.map +1 -0
- package/dist/index.es.js +287 -30
- package/dist/index.es.js.map +1 -1
- package/dist/{jwt-C3dwSo1U.js → jwt-DOyYtP0w.js} +3 -3
- package/dist/{jwt-C3dwSo1U.js.map → jwt-DOyYtP0w.js.map} +1 -1
- package/dist/{rls-simulator-routes-C7C3f57E.js → rls-simulator-routes-BTB1cjU4.js} +2 -2
- package/dist/{rls-simulator-routes-C7C3f57E.js.map → rls-simulator-routes-BTB1cjU4.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-C-RJT4VO.js.map +0 -1
- package/dist/dist-BCMr0NfI.js +0 -19359
- package/dist/dist-BCMr0NfI.js.map +0 -1
|
@@ -44,7 +44,7 @@ import type { AuthResponsePayload, TransformAuthResponseContext } from "@rebasep
|
|
|
44
44
|
/**
|
|
45
45
|
* Authentication method identifier for lifecycle hooks.
|
|
46
46
|
*/
|
|
47
|
-
export type AuthMethod = "login" | "register" | "oauth" | "refresh" | "password-reset" | "anonymous" | "magic-link" | "otp" | "mfa";
|
|
47
|
+
export type AuthMethod = "login" | "register" | "oauth" | "refresh" | "password-reset" | "anonymous" | "magic-link" | "otp" | "mfa" | "device";
|
|
48
48
|
/**
|
|
49
49
|
* Hook specific parts of the built-in Rebase auth implementation.
|
|
50
50
|
*
|
|
@@ -98,7 +98,8 @@ export interface AuthHooks {
|
|
|
98
98
|
* (`login`), registration (`register`), an OAuth sign-in (`oauth`), a
|
|
99
99
|
* token refresh (`refresh`), a password reset (`password-reset`), a
|
|
100
100
|
* guest session (`anonymous`), a magic link (`magic-link`), an email code
|
|
101
|
-
* (`otp`)
|
|
101
|
+
* (`otp`), a second factor (`mfa`) and a device sign-in approved in a
|
|
102
|
+
* browser (`device`). Every value of {@link AuthMethod}
|
|
102
103
|
* is passed by some route.
|
|
103
104
|
*
|
|
104
105
|
* Use for audit logging, syncing external state, updating
|
|
@@ -81,6 +81,8 @@ export interface BuiltinAuthAdapterConfig {
|
|
|
81
81
|
/** Enable magic link (passwordless email) login. Requires email service. */
|
|
82
82
|
enableMagicLink?: boolean;
|
|
83
83
|
enableEmailOtp?: boolean;
|
|
84
|
+
/** Device sign-in, a terminal signing in through a browser: where it keeps its state and the approval page. */
|
|
85
|
+
deviceLogin?: import("./device-login-routes.js").DeviceLoginRoutesConfig;
|
|
84
86
|
/** Opt-in httpOnly cookie mode for refresh tokens. */
|
|
85
87
|
cookieAuth?: import("./routes.js").CookieAuthConfig;
|
|
86
88
|
/** Refuse password sign-in until the address is verified; confirm-first registration. */
|
|
@@ -31,6 +31,8 @@ export interface BuiltinAuthCapabilityInputs {
|
|
|
31
31
|
enableMagicLink?: boolean;
|
|
32
32
|
/** Email one-time codes. Needs an email service, as magic link does. */
|
|
33
33
|
enableEmailOtp?: boolean;
|
|
34
|
+
/** Device sign-in. Needs no email: the approval happens in a signed-in browser. */
|
|
35
|
+
enableDeviceLogin?: boolean;
|
|
34
36
|
/**
|
|
35
37
|
* Whether an email service is configured.
|
|
36
38
|
*
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device sign-in: a terminal, or anything else without a browser of its own,
|
|
3
|
+
* signs in through one. Modelled on RFC 8628, the OAuth 2.0 device
|
|
4
|
+
* authorization grant, and answering with the session every other sign-in
|
|
5
|
+
* door answers with.
|
|
6
|
+
*
|
|
7
|
+
* 1. The device asks `POST /auth/device` for a pending sign-in and gets a
|
|
8
|
+
* secret device code, a short user code and the page to approve it on.
|
|
9
|
+
* 2. It shows the page and the code, and polls `POST /auth/device/token`.
|
|
10
|
+
* 3. The person opens the page in a browser where they are signed in — or
|
|
11
|
+
* signs in there, with any method the app offers — sees the code the
|
|
12
|
+
* device showed, and approves (`POST /auth/device/approve`) or denies.
|
|
13
|
+
* 4. The next poll is answered with a session for that account, once.
|
|
14
|
+
*
|
|
15
|
+
* ## What keeps it safe
|
|
16
|
+
*
|
|
17
|
+
* - **Approval is a signed-in act.** Describing, approving and denying take a
|
|
18
|
+
* live session, so a code is worth nothing to someone with no account, and
|
|
19
|
+
* the account approving is the account the device gets.
|
|
20
|
+
* - **The second factor is inherited, never skipped.** The session minted for
|
|
21
|
+
* the device carries the approving session's assurance level. An account
|
|
22
|
+
* with a verified factor can only approve from an `aal2` session, so a
|
|
23
|
+
* device sign-in never yields a session the account's 2FA did not stand
|
|
24
|
+
* behind.
|
|
25
|
+
* - **Short-lived and single-use.** A pending sign-in lives ten minutes, is
|
|
26
|
+
* decided once, and hands out its session once.
|
|
27
|
+
* - **The person can see what they are approving.** The approval page shows
|
|
28
|
+
* the code, what the device calls itself, and where the request came from,
|
|
29
|
+
* because the attack on this grant is a stranger sending someone a link to
|
|
30
|
+
* approve the stranger's terminal.
|
|
31
|
+
* - **Polling is paced.** A device that polls faster than its interval is
|
|
32
|
+
* answered `slow_down` and its interval grows, as RFC 8628 §3.5 has it.
|
|
33
|
+
*
|
|
34
|
+
* @module
|
|
35
|
+
*/
|
|
36
|
+
import { Hono } from "hono";
|
|
37
|
+
import type { MiddlewareHandler } from "hono";
|
|
38
|
+
import { z } from "zod";
|
|
39
|
+
import type { AuthResponsePayload, TransformAuthResponseContext } from "@rebasepro/types";
|
|
40
|
+
import type { HonoEnv } from "../api/types.js";
|
|
41
|
+
import type { ResolvedAuthHooks } from "./auth-hooks.js";
|
|
42
|
+
import type { DeviceLoginStore } from "./device-login-store.js";
|
|
43
|
+
import { type AuthLimiters } from "./rate-limiter.js";
|
|
44
|
+
import type { AuthModuleConfig, CreateSessionAndTokens } from "./routes.js";
|
|
45
|
+
/** How long a pending device sign-in lives: RFC 8628's example, and long enough to sign in from scratch. */
|
|
46
|
+
export declare const DEVICE_LOGIN_TTL_SECONDS: number;
|
|
47
|
+
/** The interval a device is told to poll at, RFC 8628's default. */
|
|
48
|
+
export declare const DEVICE_LOGIN_INTERVAL_SECONDS = 5;
|
|
49
|
+
/** How much each `slow_down` adds to the interval (RFC 8628 §3.5). */
|
|
50
|
+
export declare const DEVICE_LOGIN_SLOW_DOWN_SECONDS = 5;
|
|
51
|
+
/** A user code as it is shown: `BCDF-GHJK`. */
|
|
52
|
+
export declare function formatUserCode(code: string): string;
|
|
53
|
+
/**
|
|
54
|
+
* A user code as typed or pasted — any case, with or without the dash or
|
|
55
|
+
* spaces — in the form it is stored in, or null when it cannot be one.
|
|
56
|
+
*/
|
|
57
|
+
export declare function normalizeUserCode(input: string): string | null;
|
|
58
|
+
export declare function generateUserCode(): string;
|
|
59
|
+
/** What a device calls itself, made safe to store and show: one line, printable, at most 100 characters. */
|
|
60
|
+
export declare function cleanClientName(input: string | undefined): string;
|
|
61
|
+
/**
|
|
62
|
+
* Polls per address per window. A device polling every five seconds for its
|
|
63
|
+
* whole ten minutes makes 120; this leaves room for a few at once behind one
|
|
64
|
+
* address (an office, a CI runner) without letting one address hammer it.
|
|
65
|
+
*/
|
|
66
|
+
export declare const DEVICE_POLL_LIMIT: {
|
|
67
|
+
name: string;
|
|
68
|
+
windowMs: number;
|
|
69
|
+
limit: number;
|
|
70
|
+
};
|
|
71
|
+
/** Where device sign-in keeps its state and sends people. */
|
|
72
|
+
export interface DeviceLoginRoutesConfig {
|
|
73
|
+
store: DeviceLoginStore;
|
|
74
|
+
/**
|
|
75
|
+
* The page that approves a device sign-in, on the app the person signs in
|
|
76
|
+
* to: `https://app.example.com/device`. It is handed the code as `?code=`
|
|
77
|
+
* and calls `/auth/device/:code`, then `/auth/device/approve` or `/deny`.
|
|
78
|
+
*/
|
|
79
|
+
verificationUrl: string;
|
|
80
|
+
}
|
|
81
|
+
export declare function mountDeviceLoginRoutes(deps: {
|
|
82
|
+
router: Hono<HonoEnv>;
|
|
83
|
+
config: AuthModuleConfig;
|
|
84
|
+
deviceLogin: DeviceLoginRoutesConfig;
|
|
85
|
+
limiters: AuthLimiters;
|
|
86
|
+
ops: ResolvedAuthHooks;
|
|
87
|
+
parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T;
|
|
88
|
+
requireLiveSession: MiddlewareHandler<HonoEnv>;
|
|
89
|
+
buildAuthResponse: (user: {
|
|
90
|
+
id: string;
|
|
91
|
+
email: string;
|
|
92
|
+
displayName?: string | null;
|
|
93
|
+
photoUrl?: string | null;
|
|
94
|
+
emailVerified?: boolean;
|
|
95
|
+
isAnonymous?: boolean;
|
|
96
|
+
metadata?: Record<string, unknown> | null;
|
|
97
|
+
}, roleIds: string[], accessToken: string, refreshToken: string, providerId: string) => unknown;
|
|
98
|
+
createSessionAndTokens: CreateSessionAndTokens;
|
|
99
|
+
applyTransformHook: (response: AuthResponsePayload, method: TransformAuthResponseContext["method"], request: Request, uid: string) => Promise<AuthResponsePayload>;
|
|
100
|
+
}): void;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistence for device sign-in: RFC 8628's device authorization grant, the
|
|
3
|
+
* way a terminal signs in through a browser.
|
|
4
|
+
*
|
|
5
|
+
* One table in the `rebase` schema, revoked from `rebase_user` like every
|
|
6
|
+
* other internal table: a live row is a pending sign-in, and the role RLS
|
|
7
|
+
* scopes must never be able to read or approve one.
|
|
8
|
+
*
|
|
9
|
+
* The device code — the secret the polling client holds — is stored as its
|
|
10
|
+
* SHA-256 and looked up by it, so a database disclosure yields nothing a
|
|
11
|
+
* poller could present. The user code is stored as it is: it is shown on two
|
|
12
|
+
* screens by design, is useless without a signed-in browser to approve it,
|
|
13
|
+
* and lives ten minutes.
|
|
14
|
+
*
|
|
15
|
+
* Every decision that must happen once is a conditional `UPDATE`: approving or
|
|
16
|
+
* denying flips a `pending` row, and handing out the session flips an
|
|
17
|
+
* `approved` one to `consumed`. Two requests racing for either find one row
|
|
18
|
+
* to change between them, so one wins and the other is told it lost.
|
|
19
|
+
*
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
import type { DataDriver } from "@rebasepro/types";
|
|
23
|
+
/** Where a device sign-in stands. */
|
|
24
|
+
export type DeviceLoginStatus = "pending" | "approved" | "denied" | "consumed";
|
|
25
|
+
/** What starting a device sign-in stores. */
|
|
26
|
+
export interface NewDeviceLogin {
|
|
27
|
+
userCode: string;
|
|
28
|
+
/** What the device calls itself — shown on the approval page. */
|
|
29
|
+
clientName: string;
|
|
30
|
+
requestIp: string;
|
|
31
|
+
requestUserAgent: string;
|
|
32
|
+
expiresAt: Date;
|
|
33
|
+
intervalSeconds: number;
|
|
34
|
+
}
|
|
35
|
+
/** A device sign-in as the approval page describes it. */
|
|
36
|
+
export interface DeviceLoginRecord {
|
|
37
|
+
userCode: string;
|
|
38
|
+
clientName: string;
|
|
39
|
+
requestIp: string;
|
|
40
|
+
requestUserAgent: string;
|
|
41
|
+
status: DeviceLoginStatus;
|
|
42
|
+
createdAt: Date;
|
|
43
|
+
expiresAt: Date;
|
|
44
|
+
/** Whether it has expired, by the database's clock. */
|
|
45
|
+
expired: boolean;
|
|
46
|
+
}
|
|
47
|
+
/** What one poll found, by the database's clock. */
|
|
48
|
+
export interface DeviceLoginPoll {
|
|
49
|
+
status: DeviceLoginStatus;
|
|
50
|
+
expired: boolean;
|
|
51
|
+
intervalSeconds: number;
|
|
52
|
+
/** Seconds since the poll before this one, or null for the first poll. */
|
|
53
|
+
secondsSincePreviousPoll: number | null;
|
|
54
|
+
}
|
|
55
|
+
/** The account a device sign-in was approved for, handed out once. */
|
|
56
|
+
export interface ApprovedDeviceLogin {
|
|
57
|
+
uid: string;
|
|
58
|
+
aal: "aal1" | "aal2";
|
|
59
|
+
}
|
|
60
|
+
export interface DeviceLoginStore {
|
|
61
|
+
ensureTables(): Promise<void>;
|
|
62
|
+
/** Store a pending sign-in under the SHA-256 of `deviceCode`. False when the user code is taken. */
|
|
63
|
+
create(deviceCode: string, login: NewDeviceLogin): Promise<boolean>;
|
|
64
|
+
/** The sign-in a user code names, in any state, or null. */
|
|
65
|
+
findByUserCode(userCode: string): Promise<DeviceLoginRecord | null>;
|
|
66
|
+
/**
|
|
67
|
+
* Approve or deny a pending, unexpired sign-in. False when it is not
|
|
68
|
+
* pending any more — decided already, or expired — or does not exist.
|
|
69
|
+
*/
|
|
70
|
+
decide(userCode: string, decision: {
|
|
71
|
+
approve: true;
|
|
72
|
+
uid: string;
|
|
73
|
+
aal: "aal1" | "aal2";
|
|
74
|
+
} | {
|
|
75
|
+
approve: false;
|
|
76
|
+
uid: string;
|
|
77
|
+
}): Promise<boolean>;
|
|
78
|
+
/** Record a poll and report what it found. Null for a device code nobody issued. */
|
|
79
|
+
poll(deviceCode: string): Promise<DeviceLoginPoll | null>;
|
|
80
|
+
/** Lengthen the interval a too-eager poller is held to. */
|
|
81
|
+
slowDown(deviceCode: string, byStepSeconds: number): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Take an approved sign-in's account, once. Null when it was not approved,
|
|
84
|
+
* was already taken, or has expired.
|
|
85
|
+
*/
|
|
86
|
+
consume(deviceCode: string): Promise<ApprovedDeviceLogin | null>;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A store backed by the driver's SQL escape hatch, or null when the driver
|
|
90
|
+
* cannot run SQL. Device sign-in is then not offered at all: a grant whose
|
|
91
|
+
* pending state cannot be kept would hand a session to whoever polls first.
|
|
92
|
+
*/
|
|
93
|
+
export declare function createDeviceLoginStore(
|
|
94
|
+
/** Only its SQL escape hatch is read. */
|
|
95
|
+
driver: Pick<DataDriver, "admin">, options?: {
|
|
96
|
+
/**
|
|
97
|
+
* Default `true`. `false` is a backend that changes nothing in its
|
|
98
|
+
* database: `ensureTables` creates nothing, and throws when the table
|
|
99
|
+
* is not already there.
|
|
100
|
+
*/
|
|
101
|
+
provision?: boolean;
|
|
102
|
+
}): DeviceLoginStore | null;
|
package/dist/auth/routes.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { EmailService, EmailConfig } from "../email/index.js";
|
|
|
6
6
|
import { HonoEnv } from "../api/types.js";
|
|
7
7
|
import { type AuthLimiters } from "./rate-limiter.js";
|
|
8
8
|
import { type CaptchaConfig } from "./captcha.js";
|
|
9
|
+
import { type DeviceLoginRoutesConfig } from "./device-login-routes.js";
|
|
9
10
|
import { type AccessControl } from "./access.js";
|
|
10
11
|
import { isDeliverableAddress } from "./deliverable-address.js";
|
|
11
12
|
export { isDeliverableAddress };
|
|
@@ -74,6 +75,12 @@ export interface AuthModuleConfig {
|
|
|
74
75
|
* Requires email to be configured, as magic link does.
|
|
75
76
|
*/
|
|
76
77
|
enableEmailOtp?: boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Device sign-in: `POST /auth/device` and the routes that poll, describe,
|
|
80
|
+
* approve and deny it, for a terminal that signs in through a browser.
|
|
81
|
+
* Off when absent. See `device-login-routes.ts`.
|
|
82
|
+
*/
|
|
83
|
+
deviceLogin?: DeviceLoginRoutesConfig;
|
|
77
84
|
/**
|
|
78
85
|
* Opt-in httpOnly cookie mode for refresh tokens.
|
|
79
86
|
*
|
|
@@ -7,19 +7,19 @@ import { G as isPostgresCollectionConfig, H as rewriteLegacyRlsFunctions, _ as s
|
|
|
7
7
|
import { n as isAnonymousUid, r as policy, t as ANONYMOUS_USER_ID } from "./policy-PdzX-Opd.js";
|
|
8
8
|
import { n as isSQLAdmin } from "./backend-CaG_Jyso.js";
|
|
9
9
|
import { t as AUTH_FLOW_HEADER } from "./auth_adapter-HFv5axIT.js";
|
|
10
|
-
import { $ as accessTokenRefusalError, C as queryTokenAuth, E as requireAuth, G as isApiKeyToken, J as extractBearerToken, K as resolveApiKey, L as applySimulation, P as applyImpersonation, T as requireAdmin, X as SERVICE_IDENTITY, Y as safeCompare, Z as scopeDataDriver, _ as createAuthMiddleware, a as assertMayManageAccount, at as httpMethodToOperation, b as fileTokenAuth, c as configureAccess, f as processAccessControl, h as requireScopeByMethod, i as assertMayGrantRoles, l as getAccessModel, m as requireScope, n as accessModelFromCollections, nt as replaceUserPassword, o as callerIsAdmin, p as readRoleNames, q as validateApiKey, r as accessOf, rt as revokeAllSessions, s as callerScopes, t as AccessModelError, tt as judgeAccessToken, u as hasScope, v as createRequireAuth, w as refuse, x as optionalAuth, y as extractUserFromToken } from "./access-
|
|
10
|
+
import { $ as accessTokenRefusalError, C as queryTokenAuth, E as requireAuth, G as isApiKeyToken, J as extractBearerToken, K as resolveApiKey, L as applySimulation, P as applyImpersonation, T as requireAdmin, X as SERVICE_IDENTITY, Y as safeCompare, Z as scopeDataDriver, _ as createAuthMiddleware, a as assertMayManageAccount, at as httpMethodToOperation, b as fileTokenAuth, c as configureAccess, f as processAccessControl, h as requireScopeByMethod, i as assertMayGrantRoles, l as getAccessModel, m as requireScope, n as accessModelFromCollections, nt as replaceUserPassword, o as callerIsAdmin, p as readRoleNames, q as validateApiKey, r as accessOf, rt as revokeAllSessions, s as callerScopes, t as AccessModelError, tt as judgeAccessToken, u as hasScope, v as createRequireAuth, w as refuse, x as optionalAuth, y as extractUserFromToken } from "./access-1wrvwWls.js";
|
|
11
11
|
import { o as resolveListLimitParam } from "./query-parser-mFFiGEFV.js";
|
|
12
12
|
import { a as logger } from "./logger-SigQ2oZJ.js";
|
|
13
13
|
import { r as toSnakeCase } from "./strings.es-B7QLnHh2.js";
|
|
14
14
|
import { i as revokeInternalTableSql, n as REQUEST_ROLE_CANDIDATES_SQL } from "./internal-tables-BmN-5QQr.js";
|
|
15
15
|
import { t as firstSqlRow } from "./sql-rows-CIThkmuF.js";
|
|
16
|
-
import { _ as verifyAccessToken, a as generateAccessToken, c as getAccessTokenExpiry, d as hasAsymmetricSigningKey, f as hashRefreshToken, h as processJwtService, i as customClaimsOf, l as getJwks, m as jwtOf, n as configureJwt, o as generateDownloadToken, p as isJwtConfigured, s as generateRefreshToken, t as MAX_COOKIE_AGE_MS, u as getRefreshTokenExpiry, v as verifyDownloadToken, w as randomInt$
|
|
16
|
+
import { _ as verifyAccessToken, a as generateAccessToken, c as getAccessTokenExpiry, d as hasAsymmetricSigningKey, f as hashRefreshToken, h as processJwtService, i as customClaimsOf, l as getJwks, m as jwtOf, n as configureJwt, o as generateDownloadToken, p as isJwtConfigured, s as generateRefreshToken, t as MAX_COOKIE_AGE_MS, u as getRefreshTokenExpiry, v as verifyDownloadToken, w as randomInt$2, x as require_jsonwebtoken } from "./jwt-DOyYtP0w.js";
|
|
17
17
|
import { c as provisioningExec, n as SchemaChangeRefusedError, r as createDdlBootstrapper } from "./ddl-bootstrap-DhCuwhHM.js";
|
|
18
18
|
import { a as isDataException, i as errorHandler, l as warnIfDatabaseClosed, o as isDatabaseUnreachable, r as declaredErrorAnswer, t as ApiError } from "./errors-DpTMfX77.js";
|
|
19
19
|
import { createHash, randomBytes, randomInt } from "node:crypto";
|
|
20
20
|
import { Hono } from "hono";
|
|
21
21
|
import { promisify } from "util";
|
|
22
|
-
import { createCipheriv, createDecipheriv, createHash as createHash$1, createHmac, createPublicKey, randomBytes as randomBytes$1, randomUUID as randomUUID$1, scrypt, timingSafeEqual } from "crypto";
|
|
22
|
+
import { createCipheriv, createDecipheriv, createHash as createHash$1, createHmac, createPublicKey, randomBytes as randomBytes$1, randomInt as randomInt$1, randomUUID as randomUUID$1, scrypt, timingSafeEqual } from "crypto";
|
|
23
23
|
import { getConnInfo } from "@hono/node-server/conninfo";
|
|
24
24
|
import { createMiddleware } from "hono/factory";
|
|
25
25
|
import { z } from "zod";
|
|
@@ -4709,7 +4709,7 @@ var OTP_ATTEMPTS_PER_WINDOW = 5;
|
|
|
4709
4709
|
* and one of them is the classic modulo bias.
|
|
4710
4710
|
*/
|
|
4711
4711
|
function generateOtpCode() {
|
|
4712
|
-
return String(randomInt$
|
|
4712
|
+
return String(randomInt$2(10 ** OTP_DIGITS)).padStart(OTP_DIGITS, "0");
|
|
4713
4713
|
}
|
|
4714
4714
|
/**
|
|
4715
4715
|
* What gets hashed and stored.
|
|
@@ -4994,6 +4994,216 @@ function mountMagicLinkRoutes(deps) {
|
|
|
4994
4994
|
return c.json(redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth));
|
|
4995
4995
|
});
|
|
4996
4996
|
}
|
|
4997
|
+
/**
|
|
4998
|
+
* The slack allowed between two polls before the second counts as early. The
|
|
4999
|
+
* gap is measured between the requests' arrivals, and a device that sleeps
|
|
5000
|
+
* exactly its interval can arrive a little sooner than that when the earlier
|
|
5001
|
+
* request was the slower one on the wire.
|
|
5002
|
+
*/
|
|
5003
|
+
var POLL_JITTER_SECONDS = 1;
|
|
5004
|
+
/**
|
|
5005
|
+
* The user code's alphabet: consonants only, so no code spells a word, and
|
|
5006
|
+
* none of the letters a person confuses with a digit (RFC 8628 §6.1 suggests
|
|
5007
|
+
* exactly these twenty). Eight of them is 20⁸ ≈ 2.6 × 10¹⁰ codes.
|
|
5008
|
+
*/
|
|
5009
|
+
var USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
|
|
5010
|
+
var USER_CODE_LENGTH = 8;
|
|
5011
|
+
/** A user code as it is shown: `BCDF-GHJK`. */
|
|
5012
|
+
function formatUserCode(code) {
|
|
5013
|
+
return `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
5014
|
+
}
|
|
5015
|
+
/**
|
|
5016
|
+
* A user code as typed or pasted — any case, with or without the dash or
|
|
5017
|
+
* spaces — in the form it is stored in, or null when it cannot be one.
|
|
5018
|
+
*/
|
|
5019
|
+
function normalizeUserCode(input) {
|
|
5020
|
+
const code = input.toUpperCase().replace(/[\s-]/g, "");
|
|
5021
|
+
if (code.length !== USER_CODE_LENGTH) return null;
|
|
5022
|
+
for (const char of code) if (!USER_CODE_ALPHABET.includes(char)) return null;
|
|
5023
|
+
return code;
|
|
5024
|
+
}
|
|
5025
|
+
function generateUserCode() {
|
|
5026
|
+
let code = "";
|
|
5027
|
+
for (let i = 0; i < USER_CODE_LENGTH; i++) code += USER_CODE_ALPHABET[randomInt$1(20)];
|
|
5028
|
+
return code;
|
|
5029
|
+
}
|
|
5030
|
+
/** What a device calls itself, made safe to store and show: one line, printable, at most 100 characters. */
|
|
5031
|
+
function cleanClientName(input) {
|
|
5032
|
+
return (input ?? "").replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 100) || "Unknown device";
|
|
5033
|
+
}
|
|
5034
|
+
/**
|
|
5035
|
+
* Polls per address per window. A device polling every five seconds for its
|
|
5036
|
+
* whole ten minutes makes 120; this leaves room for a few at once behind one
|
|
5037
|
+
* address (an office, a CI runner) without letting one address hammer it.
|
|
5038
|
+
*/
|
|
5039
|
+
var DEVICE_POLL_LIMIT = {
|
|
5040
|
+
name: "auth:device-poll",
|
|
5041
|
+
windowMs: 900 * 1e3,
|
|
5042
|
+
limit: 600
|
|
5043
|
+
};
|
|
5044
|
+
function mountDeviceLoginRoutes(deps) {
|
|
5045
|
+
const { router, config, deviceLogin, limiters, ops, parseBody, requireLiveSession, buildAuthResponse, createSessionAndTokens, applyTransformHook } = deps;
|
|
5046
|
+
const { authRepo } = config;
|
|
5047
|
+
const { store, verificationUrl } = deviceLogin;
|
|
5048
|
+
const pollLimiter = limiters.named(DEVICE_POLL_LIMIT);
|
|
5049
|
+
const startSchema = z.object({ clientName: z.string().max(500).optional() });
|
|
5050
|
+
const tokenSchema = z.object({ deviceCode: z.string().min(1).max(200) });
|
|
5051
|
+
const decideSchema = z.object({ userCode: z.string().min(1).max(50) });
|
|
5052
|
+
const userCodeOf = (input) => {
|
|
5053
|
+
const code = normalizeUserCode(input);
|
|
5054
|
+
if (!code) throw ApiError.badRequest("That is not a sign-in code. It is eight letters, like BCDF-GHJK.", "INVALID_USER_CODE");
|
|
5055
|
+
return code;
|
|
5056
|
+
};
|
|
5057
|
+
/** The device sign-in a code names, for the approval page. */
|
|
5058
|
+
const describe = (record) => ({
|
|
5059
|
+
userCode: formatUserCode(record.userCode),
|
|
5060
|
+
clientName: record.clientName,
|
|
5061
|
+
requestIp: record.requestIp,
|
|
5062
|
+
requestUserAgent: record.requestUserAgent,
|
|
5063
|
+
status: record.expired && record.status === "pending" ? "expired" : record.status,
|
|
5064
|
+
createdAt: record.createdAt.toISOString(),
|
|
5065
|
+
expiresAt: record.expiresAt.toISOString()
|
|
5066
|
+
});
|
|
5067
|
+
/** The pending sign-in a code names, or the refusal that says why it cannot be decided. */
|
|
5068
|
+
async function requirePending(code) {
|
|
5069
|
+
const record = await store.findByUserCode(code);
|
|
5070
|
+
if (!record) throw ApiError.notFound("No sign-in is waiting for that code. Check it against the one your device shows.", "DEVICE_LOGIN_NOT_FOUND");
|
|
5071
|
+
if (record.status !== "pending") throw ApiError.conflict(`This sign-in has already been ${record.status === "denied" ? "denied" : "approved"}.`, "DEVICE_LOGIN_DECIDED");
|
|
5072
|
+
if (record.expired) throw new ApiError(410, "DEVICE_LOGIN_EXPIRED", "This sign-in has expired. Start it again on your device.", void 0, true);
|
|
5073
|
+
return record;
|
|
5074
|
+
}
|
|
5075
|
+
function signedInCaller(c) {
|
|
5076
|
+
const user = c.get("user");
|
|
5077
|
+
if (!user?.uid) throw ApiError.unauthorized("Not authenticated");
|
|
5078
|
+
if (user.isAnonymous === true) throw ApiError.forbidden("Sign in with an account to approve a device.", "ANONYMOUS_NOT_ALLOWED");
|
|
5079
|
+
return {
|
|
5080
|
+
uid: user.uid,
|
|
5081
|
+
aal: user.aal === "aal2" ? "aal2" : "aal1"
|
|
5082
|
+
};
|
|
5083
|
+
}
|
|
5084
|
+
/**
|
|
5085
|
+
* POST /auth/device — start a device sign-in.
|
|
5086
|
+
*/
|
|
5087
|
+
router.post("/device", limiters.strict, async (c) => {
|
|
5088
|
+
const { clientName } = parseBody(startSchema, await c.req.json().catch(() => ({})));
|
|
5089
|
+
const deviceCode = randomBytes$1(32).toString("base64url");
|
|
5090
|
+
const login = {
|
|
5091
|
+
clientName: cleanClientName(clientName),
|
|
5092
|
+
requestIp: requestClientAddress(c),
|
|
5093
|
+
requestUserAgent: (c.req.header("user-agent") || "unknown").slice(0, 300),
|
|
5094
|
+
expiresAt: new Date(Date.now() + 600 * 1e3),
|
|
5095
|
+
intervalSeconds: 5
|
|
5096
|
+
};
|
|
5097
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
5098
|
+
const userCode = generateUserCode();
|
|
5099
|
+
if (!await store.create(deviceCode, {
|
|
5100
|
+
...login,
|
|
5101
|
+
userCode
|
|
5102
|
+
})) continue;
|
|
5103
|
+
const shown = formatUserCode(userCode);
|
|
5104
|
+
const complete = new URL(verificationUrl);
|
|
5105
|
+
complete.searchParams.set("code", shown);
|
|
5106
|
+
return c.json({
|
|
5107
|
+
deviceCode,
|
|
5108
|
+
userCode: shown,
|
|
5109
|
+
verificationUri: verificationUrl,
|
|
5110
|
+
verificationUriComplete: complete.toString(),
|
|
5111
|
+
expiresIn: 600,
|
|
5112
|
+
interval: 5
|
|
5113
|
+
});
|
|
5114
|
+
}
|
|
5115
|
+
throw ApiError.internal("Could not start a device sign-in. Try again.");
|
|
5116
|
+
});
|
|
5117
|
+
/**
|
|
5118
|
+
* POST /auth/device/token — poll. `400` with RFC 8628's error codes until
|
|
5119
|
+
* the sign-in is decided; then the session, once.
|
|
5120
|
+
*
|
|
5121
|
+
* Always answered in the body, whatever `cookieAuth` says: the caller is a
|
|
5122
|
+
* device without a browser, and a cookie is a credential it cannot keep.
|
|
5123
|
+
*/
|
|
5124
|
+
router.post("/device/token", pollLimiter, async (c) => {
|
|
5125
|
+
const { deviceCode } = parseBody(tokenSchema, await c.req.json());
|
|
5126
|
+
const refuse = (code, message, details) => new ApiError(400, code, message, details, true);
|
|
5127
|
+
const poll = await store.poll(deviceCode);
|
|
5128
|
+
if (!poll) throw refuse("invalid_grant", "No device sign-in has that device code.");
|
|
5129
|
+
if (poll.status === "consumed") throw refuse("invalid_grant", "This device sign-in has already been used.");
|
|
5130
|
+
if (poll.expired) throw refuse("expired_token", "The device sign-in expired before it was approved.");
|
|
5131
|
+
if (poll.secondsSincePreviousPoll !== null && poll.secondsSincePreviousPoll < poll.intervalSeconds - POLL_JITTER_SECONDS) {
|
|
5132
|
+
await store.slowDown(deviceCode, 5);
|
|
5133
|
+
const interval = poll.intervalSeconds + 5;
|
|
5134
|
+
throw refuse("slow_down", `Polling too fast. Wait ${interval} seconds between polls.`, { interval });
|
|
5135
|
+
}
|
|
5136
|
+
if (poll.status === "pending") throw refuse("authorization_pending", "Waiting for the sign-in to be approved in the browser.", { interval: poll.intervalSeconds });
|
|
5137
|
+
if (poll.status === "denied") throw refuse("access_denied", "The sign-in was denied in the browser.");
|
|
5138
|
+
const approved = await store.consume(deviceCode);
|
|
5139
|
+
if (!approved) throw refuse("invalid_grant", "This device sign-in has already been used.");
|
|
5140
|
+
const user = await authRepo.getUserById(approved.uid);
|
|
5141
|
+
if (!user) throw refuse("invalid_grant", "The account that approved this sign-in no longer exists.");
|
|
5142
|
+
const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(user.id, c.req.header("user-agent") || "unknown", requestClientAddress(c), {
|
|
5143
|
+
method: "device",
|
|
5144
|
+
skipMfaGate: true,
|
|
5145
|
+
aal: approved.aal
|
|
5146
|
+
});
|
|
5147
|
+
logger.info("[Security Audit] Device sign-in completed", {
|
|
5148
|
+
eventType: "auth.device.signed_in",
|
|
5149
|
+
uid: user.id
|
|
5150
|
+
});
|
|
5151
|
+
if (ops.onAuthenticated) ops.onAuthenticated(user, "device").catch((err) => {
|
|
5152
|
+
logger.error("[AuthHooks] onAuthenticated error", { error: err instanceof Error ? err.message : err });
|
|
5153
|
+
});
|
|
5154
|
+
const response = buildAuthResponse(user, roleIds, accessToken, refreshToken, "device");
|
|
5155
|
+
return c.json(await applyTransformHook(response, "device", c.req.raw, user.id));
|
|
5156
|
+
});
|
|
5157
|
+
/**
|
|
5158
|
+
* GET /auth/device/:userCode — what is asking to sign in, for the page
|
|
5159
|
+
* that approves it. Signed-in only: where a request came from is not for
|
|
5160
|
+
* anyone holding a guessed code.
|
|
5161
|
+
*/
|
|
5162
|
+
router.get("/device/:userCode", limiters.strict, requireLiveSession, async (c) => {
|
|
5163
|
+
signedInCaller(c);
|
|
5164
|
+
const record = await store.findByUserCode(userCodeOf(c.req.param("userCode")));
|
|
5165
|
+
if (!record) throw ApiError.notFound("No sign-in is waiting for that code. Check it against the one your device shows.", "DEVICE_LOGIN_NOT_FOUND");
|
|
5166
|
+
return c.json(describe(record));
|
|
5167
|
+
});
|
|
5168
|
+
/** POST /auth/device/approve — give the device a session for this account. */
|
|
5169
|
+
router.post("/device/approve", limiters.strict, requireLiveSession, async (c) => {
|
|
5170
|
+
const caller = signedInCaller(c);
|
|
5171
|
+
const code = userCodeOf(parseBody(decideSchema, await c.req.json()).userCode);
|
|
5172
|
+
await requirePending(code);
|
|
5173
|
+
if (caller.aal !== "aal2" && typeof authRepo.hasVerifiedMfaFactors === "function" && await authRepo.hasVerifiedMfaFactors(caller.uid)) throw ApiError.forbidden("This account has two-factor authentication on. Sign in again with your second factor, then approve the device.", "AAL2_REQUIRED");
|
|
5174
|
+
if (!await store.decide(code, {
|
|
5175
|
+
approve: true,
|
|
5176
|
+
uid: caller.uid,
|
|
5177
|
+
aal: caller.aal
|
|
5178
|
+
})) {
|
|
5179
|
+
await requirePending(code);
|
|
5180
|
+
throw ApiError.conflict("This sign-in has already been decided.", "DEVICE_LOGIN_DECIDED");
|
|
5181
|
+
}
|
|
5182
|
+
logger.info("[Security Audit] Device sign-in approved", {
|
|
5183
|
+
eventType: "auth.device.approved",
|
|
5184
|
+
uid: caller.uid
|
|
5185
|
+
});
|
|
5186
|
+
return c.json({ success: true });
|
|
5187
|
+
});
|
|
5188
|
+
/** POST /auth/device/deny — refuse it; the device is told on its next poll. */
|
|
5189
|
+
router.post("/device/deny", limiters.strict, requireLiveSession, async (c) => {
|
|
5190
|
+
const caller = signedInCaller(c);
|
|
5191
|
+
const code = userCodeOf(parseBody(decideSchema, await c.req.json()).userCode);
|
|
5192
|
+
await requirePending(code);
|
|
5193
|
+
if (!await store.decide(code, {
|
|
5194
|
+
approve: false,
|
|
5195
|
+
uid: caller.uid
|
|
5196
|
+
})) {
|
|
5197
|
+
await requirePending(code);
|
|
5198
|
+
throw ApiError.conflict("This sign-in has already been decided.", "DEVICE_LOGIN_DECIDED");
|
|
5199
|
+
}
|
|
5200
|
+
logger.info("[Security Audit] Device sign-in denied", {
|
|
5201
|
+
eventType: "auth.device.denied",
|
|
5202
|
+
uid: caller.uid
|
|
5203
|
+
});
|
|
5204
|
+
return c.json({ success: true });
|
|
5205
|
+
});
|
|
5206
|
+
}
|
|
4997
5207
|
//#endregion
|
|
4998
5208
|
//#region src/auth/oauth-signin-policy.ts
|
|
4999
5209
|
/**
|
|
@@ -6014,6 +6224,18 @@ function createAuthRoutes(config) {
|
|
|
6014
6224
|
applyTransformHook,
|
|
6015
6225
|
captchaMiddleware: captcha.emailOtp
|
|
6016
6226
|
});
|
|
6227
|
+
if (config.deviceLogin) mountDeviceLoginRoutes({
|
|
6228
|
+
router,
|
|
6229
|
+
config,
|
|
6230
|
+
deviceLogin: config.deviceLogin,
|
|
6231
|
+
limiters,
|
|
6232
|
+
ops,
|
|
6233
|
+
parseBody,
|
|
6234
|
+
requireLiveSession,
|
|
6235
|
+
buildAuthResponse,
|
|
6236
|
+
createSessionAndTokens,
|
|
6237
|
+
applyTransformHook
|
|
6238
|
+
});
|
|
6017
6239
|
return router;
|
|
6018
6240
|
}
|
|
6019
6241
|
//#endregion
|
|
@@ -6026,7 +6248,7 @@ function createAuthRoutes(config) {
|
|
|
6026
6248
|
* `anonymousLogin` go through the shared predicates for exactly that reason.
|
|
6027
6249
|
*/
|
|
6028
6250
|
function buildBuiltinAuthCapabilities(inputs) {
|
|
6029
|
-
const { needsSetup, allowRegistration, disableSelfRegistration, allowAnonymous, enableMagicLink, enableEmailOtp, emailConfigured, enabledProviders, providerClientIds } = inputs;
|
|
6251
|
+
const { needsSetup, allowRegistration, disableSelfRegistration, allowAnonymous, enableMagicLink, enableEmailOtp, enableDeviceLogin, emailConfigured, enabledProviders, providerClientIds } = inputs;
|
|
6030
6252
|
return {
|
|
6031
6253
|
hasBuiltInAuthRoutes: true,
|
|
6032
6254
|
emailPasswordLogin: true,
|
|
@@ -6042,6 +6264,7 @@ function buildBuiltinAuthCapabilities(inputs) {
|
|
|
6042
6264
|
emailVerification: emailConfigured,
|
|
6043
6265
|
magicLink: !!enableMagicLink && emailConfigured,
|
|
6044
6266
|
emailOtp: !!enableEmailOtp && emailConfigured,
|
|
6267
|
+
deviceLogin: !!enableDeviceLogin,
|
|
6045
6268
|
anonymousLogin: isAnonymousAuthOpen({
|
|
6046
6269
|
allowAnonymous,
|
|
6047
6270
|
disableSelfRegistration
|
|
@@ -6735,7 +6958,7 @@ function createAdminUsersRoute(config) {
|
|
|
6735
6958
|
* when the user passes a plain `RebaseAuthConfig` object.
|
|
6736
6959
|
*/
|
|
6737
6960
|
function createBuiltinAuthAdapter(config) {
|
|
6738
|
-
const { authRepository, emailService, emailConfig, allowRegistration = false, disableSelfRegistration = false, allowAnonymous = false, allowUserLookup = false, captcha, defaultRole, oauthProviders = [], allowedRedirectUris, serviceKey, authHooks, collectionAuthConfig, enableMagicLink = false, enableEmailOtp = false, cookieAuth, requireEmailVerification = false, refreshTokenReuseIntervalSeconds, refreshTokenReuse, magicLinkCreatesUsers = false } = config;
|
|
6961
|
+
const { authRepository, emailService, emailConfig, allowRegistration = false, disableSelfRegistration = false, allowAnonymous = false, allowUserLookup = false, captcha, defaultRole, oauthProviders = [], allowedRedirectUris, serviceKey, authHooks, collectionAuthConfig, enableMagicLink = false, enableEmailOtp = false, deviceLogin, cookieAuth, requireEmailVerification = false, refreshTokenReuseIntervalSeconds, refreshTokenReuse, magicLinkCreatesUsers = false } = config;
|
|
6739
6962
|
const jwt = config.jwt ?? processJwtService;
|
|
6740
6963
|
const resolvedOps = resolveAuthHooks(authHooks);
|
|
6741
6964
|
/**
|
|
@@ -6893,6 +7116,7 @@ function createBuiltinAuthAdapter(config) {
|
|
|
6893
7116
|
authHooks,
|
|
6894
7117
|
enableMagicLink,
|
|
6895
7118
|
enableEmailOtp,
|
|
7119
|
+
deviceLogin,
|
|
6896
7120
|
cookieAuth,
|
|
6897
7121
|
captcha,
|
|
6898
7122
|
requireEmailVerification,
|
|
@@ -6975,6 +7199,7 @@ function createBuiltinAuthAdapter(config) {
|
|
|
6975
7199
|
allowAnonymous,
|
|
6976
7200
|
enableMagicLink,
|
|
6977
7201
|
enableEmailOtp,
|
|
7202
|
+
enableDeviceLogin: !!deviceLogin,
|
|
6978
7203
|
emailConfigured: !!emailService?.isConfigured(),
|
|
6979
7204
|
enabledProviders: oauthProviders.map((p) => p.id),
|
|
6980
7205
|
providerClientIds: Object.fromEntries(oauthProviders.flatMap((p) => p.publicClientId ? [[p.id, p.publicClientId]] : []))
|
|
@@ -9033,4 +9258,4 @@ var auth_exports = /* @__PURE__ */ __exportAll({
|
|
|
9033
9258
|
//#endregion
|
|
9034
9259
|
export { getEmailChangeNoticeTemplate as $, createDataRateLimitCheck as A, registerDevEmailSink as B, createJwksRoutes as C, AUTH_CONFIG_LIMIT as D, isBootstrapWindowOpen as E, activeDevEmailSink as F, validatePasswordStrength as G, createEmailService as H, clearActiveDevEmailSink as I, createAdapterAuthMiddleware as J, verifyPassword as K, createDevEmailSink as L, createRateLimiter as M, setSharedRateLimitStore as N, DEFAULT_FUNCTIONS_ANONYMOUS_LIMIT as O, MemoryRateLimitStore as P, resolveEmailLinkBase as Q, devEmailSinkFor as R, createApiKeyStore as S, configureUserPicking as T, resolveAuthHooks as U, SMTPEmailService as V, hashPassword as W, generateSecurePassword as X, completeUserCreation as Y, assertEmailLinkBases as Z, oauthCodeFlowSchema as _, createBitbucketProvider as a, getUserInvitationTemplate as at, createApiKeyRoutes as b, createTwitterProvider as c, RawHtml as ct, createMicrosoftProvider as d, raw as dt, getEmailChangeTemplate as et, tryVerifyOidcIdToken as f, createSqlRateLimitStore as ft, createGoogleProvider as g, createLinkedinProvider as h, createSlackProvider as i, getPasswordResetTemplate as it, createDataRateLimiter as j, createAuthLimiters as k, createFacebookProvider as l, escapeHtml as lt, createGitHubProvider as m, securityRuleToConditions as mt, createCustomAuthAdapter as n, getEmailVerificationTemplate as nt, createGitLabProvider as o, getWelcomeEmailTemplate as ot, verifyOidcIdToken as p, resolveRateLimitStoreKind as pt, adapterRefusal as q, createSpotifyProvider as r, getMagicLinkTemplate as rt, createDiscordProvider as s, resolveEmailBranding as st, auth_exports as t, getEmailOtpTemplate as tt, createAppleProvider as u, html as ut, pkceTokenParams as v, createBuiltinAuthAdapter as w, createPersonalKeyRoutes as x, providerVerifiedEmail as y, extractLinks as z };
|
|
9035
9260
|
|
|
9036
|
-
//# sourceMappingURL=auth-
|
|
9261
|
+
//# sourceMappingURL=auth-Bzb_b1KY.js.map
|