@appgrowstack/app-auth 0.0.0-stage → 0.6.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.
@@ -0,0 +1,33 @@
1
+ import type { AppleWebConfig } from "./config.js";
2
+ import type { AppleWebPlatform, AppleWebReturnError } from "./contract.js";
3
+ import type { D1Like } from "./d1.js";
4
+ import { type TokenKeyring } from "./tokens.js";
5
+ export declare const APPLE_AUTHORIZE_URL = "https://appleid.apple.com/auth/authorize";
6
+ export declare const APPLE_WEB_STATE_TTL_MS: number;
7
+ export declare const APPLE_WEB_CODE_TTL_MS: number;
8
+ export interface AppleWebState {
9
+ installId: string;
10
+ platform: AppleWebPlatform;
11
+ nonce: string;
12
+ codeChallenge: string;
13
+ }
14
+ export declare function isCodeChallenge(value: unknown): value is string;
15
+ export declare function codeChallengeFor(verifier: unknown): Promise<string | null>;
16
+ export declare function signAppleWebState(keyring: TokenKeyring, app: string, state: AppleWebState, now: number): Promise<string>;
17
+ export declare function verifyAppleWebState(keyring: TokenKeyring, app: string, token: string, now: number): Promise<AppleWebState | null>;
18
+ export declare function newNonce(): string;
19
+ export declare function appleAuthorizeUrl(web: AppleWebConfig, state: string, nonce: string): string;
20
+ export declare function appleWebReturnUrl(web: AppleWebConfig, query: {
21
+ code: string;
22
+ } | {
23
+ error: AppleWebReturnError;
24
+ }): string;
25
+ export declare function appleWebErrorFrom(value: unknown): AppleWebReturnError;
26
+ export declare function createAppleWebCode(db: D1Like, subject: string, installId: string, codeChallenge: string, now: number): Promise<string>;
27
+ export interface AppleWebCode {
28
+ codeHash: string;
29
+ subject: string;
30
+ installId: string;
31
+ }
32
+ export declare function findAppleWebCode(db: D1Like, code: string, codeChallenge: string, now: number): Promise<AppleWebCode | null>;
33
+ export declare function consumeAppleWebCode(db: D1Like, codeHash: string): Promise<boolean>;
@@ -0,0 +1,92 @@
1
+ import { SignJWT, jwtVerify } from "jose";
2
+ import { base64url, hashSecret, newRefreshSecret } from "./tokens.js";
3
+ export const APPLE_AUTHORIZE_URL = "https://appleid.apple.com/auth/authorize";
4
+ export const APPLE_WEB_STATE_TTL_MS = 5 * 60 * 1000;
5
+ export const APPLE_WEB_CODE_TTL_MS = 60 * 1000;
6
+ const CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
7
+ const CODE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
8
+ export function isCodeChallenge(value) {
9
+ return typeof value === "string" && CODE_CHALLENGE.test(value);
10
+ }
11
+ export async function codeChallengeFor(verifier) {
12
+ if (typeof verifier !== "string" || !CODE_VERIFIER.test(verifier))
13
+ return null;
14
+ return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
15
+ }
16
+ const stateAudience = (app) => `${app}:apple_web_state`;
17
+ export async function signAppleWebState(keyring, app, state, now) {
18
+ const iat = Math.floor(now / 1000);
19
+ return new SignJWT({ iid: state.installId, plt: state.platform, nonce: state.nonce, cch: state.codeChallenge })
20
+ .setProtectedHeader({ alg: "HS256", typ: "JWT", kid: keyring.signing.kid })
21
+ .setIssuer(app)
22
+ .setAudience(stateAudience(app))
23
+ .setIssuedAt(iat)
24
+ .setExpirationTime(Math.floor((now + APPLE_WEB_STATE_TTL_MS) / 1000))
25
+ .sign(keyring.signing.key);
26
+ }
27
+ export async function verifyAppleWebState(keyring, app, token, now) {
28
+ try {
29
+ const { payload } = await jwtVerify(token, (header) => {
30
+ const key = header.kid ? keyring.byKid.get(header.kid) : undefined;
31
+ if (!key)
32
+ throw new Error("unknown kid");
33
+ return key;
34
+ }, { issuer: app, audience: stateAudience(app), algorithms: ["HS256"], requiredClaims: ["exp"], currentDate: new Date(now) });
35
+ const { iid, plt, nonce, cch } = payload;
36
+ if (typeof iid !== "string" || plt !== "android" || typeof nonce !== "string" || !isCodeChallenge(cch))
37
+ return null;
38
+ return { installId: iid, platform: plt, nonce, codeChallenge: cch };
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ export function newNonce() {
45
+ const bytes = new Uint8Array(16);
46
+ crypto.getRandomValues(bytes);
47
+ return base64url(bytes);
48
+ }
49
+ export function appleAuthorizeUrl(web, state, nonce) {
50
+ const url = new URL(APPLE_AUTHORIZE_URL);
51
+ url.searchParams.set("client_id", web.servicesId);
52
+ url.searchParams.set("redirect_uri", web.redirectUri);
53
+ url.searchParams.set("response_type", "code id_token");
54
+ url.searchParams.set("response_mode", "form_post");
55
+ url.searchParams.set("state", state);
56
+ url.searchParams.set("nonce", nonce);
57
+ return url.toString();
58
+ }
59
+ export function appleWebReturnUrl(web, query) {
60
+ const url = new URL(web.returnUrl);
61
+ if ("code" in query)
62
+ url.searchParams.set("code", query.code);
63
+ else
64
+ url.searchParams.set("error", query.error);
65
+ return url.toString();
66
+ }
67
+ export function appleWebErrorFrom(value) {
68
+ return value === "user_cancelled_authorize" ? "user_cancelled_authorize" : "apple_error";
69
+ }
70
+ const codeHashOf = (code, codeChallenge) => hashSecret(`${code}.${codeChallenge}`);
71
+ export async function createAppleWebCode(db, subject, installId, codeChallenge, now) {
72
+ const code = newRefreshSecret();
73
+ await db.batch([
74
+ db.prepare("DELETE FROM auth_apple_web_codes WHERE expires_at <= ?").bind(now),
75
+ db
76
+ .prepare("INSERT INTO auth_apple_web_codes (code_hash, subject, install_id, created_at, expires_at) VALUES (?, ?, ?, ?, ?)")
77
+ .bind(await codeHashOf(code, codeChallenge), subject, installId, now, now + APPLE_WEB_CODE_TTL_MS),
78
+ ]);
79
+ return code;
80
+ }
81
+ export async function findAppleWebCode(db, code, codeChallenge, now) {
82
+ const codeHash = await codeHashOf(code, codeChallenge);
83
+ const row = await db
84
+ .prepare("SELECT subject, install_id AS installId FROM auth_apple_web_codes WHERE code_hash = ? AND expires_at > ?")
85
+ .bind(codeHash, now)
86
+ .first();
87
+ return row ? { codeHash, ...row } : null;
88
+ }
89
+ export async function consumeAppleWebCode(db, codeHash) {
90
+ const result = await db.prepare("DELETE FROM auth_apple_web_codes WHERE code_hash = ?").bind(codeHash).run();
91
+ return result.meta.changes === 1;
92
+ }
@@ -0,0 +1,29 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ import { type AppAuthConfig } from "./config.js";
3
+ import type { AuthKind } from "./contract.js";
4
+ export interface AuthVariables {
5
+ userId: string;
6
+ auth_kind: AuthKind;
7
+ }
8
+ export type AuthEnv<E> = {
9
+ Bindings: E;
10
+ Variables: AuthVariables;
11
+ };
12
+ export declare function authenticate<E extends object>(config: AppAuthConfig<E>): MiddlewareHandler<AuthEnv<E>>;
13
+ export type ResolvedBearer = {
14
+ kind: AuthKind;
15
+ userId: string;
16
+ deviceId?: string;
17
+ } | {
18
+ kind: "invalid";
19
+ } | {
20
+ kind: "deleted";
21
+ };
22
+ export declare function ownsAccount(current: ResolvedBearer): current is {
23
+ kind: "session" | "legacy_access_token";
24
+ userId: string;
25
+ deviceId?: string;
26
+ };
27
+ export declare function resolveBearer<E>(config: AppAuthConfig<E>, env: E, token: string, options?: {
28
+ allowLegacy: boolean;
29
+ }): Promise<ResolvedBearer>;
@@ -0,0 +1,64 @@
1
+ import { decodeProtectedHeader } from "jose";
2
+ import { fromEnv } from "./config.js";
3
+ import { bearerToken, fail } from "./http.js";
4
+ import { verifyFirebaseToken } from "./providers.js";
5
+ import { sessionIsLive, userState } from "./store.js";
6
+ import { parseTokenSecrets, verifyAccessToken, verifyLegacyAccessToken } from "./tokens.js";
7
+ export function authenticate(config) {
8
+ return async (c, next) => {
9
+ const token = bearerToken(c);
10
+ if (!token)
11
+ return fail(c, 401, "missing_token", "Authorization: Bearer <token> is required");
12
+ const resolved = await resolveBearer(config, c.env, token);
13
+ if (resolved.kind === "invalid")
14
+ return fail(c, 401, "invalid_token", "access token is not valid");
15
+ if (resolved.kind === "deleted")
16
+ return fail(c, 410, "account_deleted", "account was deleted");
17
+ c.set("userId", resolved.userId);
18
+ c.set("auth_kind", resolved.kind);
19
+ await next();
20
+ };
21
+ }
22
+ export function ownsAccount(current) {
23
+ return current.kind === "session" || current.kind === "legacy_access_token";
24
+ }
25
+ export async function resolveBearer(config, env, token, options = { allowLegacy: true }) {
26
+ const now = config.now?.() ?? Date.now();
27
+ const db = config.db(env);
28
+ let alg;
29
+ let kid;
30
+ try {
31
+ ;
32
+ ({ alg, kid } = decodeProtectedHeader(token));
33
+ }
34
+ catch {
35
+ return { kind: "invalid" };
36
+ }
37
+ if (alg === "HS256" && kid === undefined) {
38
+ const legacy = fromEnv(config.legacyAccessToken, env);
39
+ const userId = legacy ? await verifyLegacyAccessToken(legacy, token, now) : null;
40
+ if (!userId)
41
+ return { kind: "invalid" };
42
+ const state = await userState(db, userId);
43
+ if (state === "deleted")
44
+ return { kind: "deleted" };
45
+ return state === "missing" ? { kind: "invalid" } : { kind: "legacy_access_token", userId };
46
+ }
47
+ if (alg === "HS256") {
48
+ const claims = await verifyAccessToken(parseTokenSecrets(config.tokenSecrets(env)), config.app, token, now);
49
+ if (!claims)
50
+ return { kind: "invalid" };
51
+ if (await sessionIsLive(db, claims.userId, claims.deviceId))
52
+ return { kind: "session", userId: claims.userId, deviceId: claims.deviceId };
53
+ return (await userState(db, claims.userId)) === "deleted" ? { kind: "deleted" } : { kind: "invalid" };
54
+ }
55
+ const firebase = fromEnv(config.legacyFirebase, env);
56
+ if (!options.allowLegacy || !firebase?.acceptLegacyBearer || alg !== "RS256")
57
+ return { kind: "invalid" };
58
+ const identity = await verifyFirebaseToken(firebase, token, now);
59
+ if (!identity)
60
+ return { kind: "invalid" };
61
+ if ((await userState(db, identity.uid)) === "deleted")
62
+ return { kind: "deleted" };
63
+ return { kind: "legacy_firebase", userId: identity.uid };
64
+ }
@@ -0,0 +1,88 @@
1
+ import type { JWTVerifyGetKey } from "jose";
2
+ import type { LinkableProvider } from "./contract.js";
3
+ import type { D1Like } from "./d1.js";
4
+ export type FromEnv<E, T> = T | ((env: E) => T);
5
+ export type KeySource = string | JWTVerifyGetKey;
6
+ export interface AppleConfig {
7
+ audience: string | string[];
8
+ keys?: KeySource;
9
+ revoke?: AppleRevokeConfig;
10
+ web?: AppleWebConfig;
11
+ }
12
+ export interface AppleWebConfig {
13
+ servicesId: string;
14
+ redirectUri: string;
15
+ returnUrl: string;
16
+ }
17
+ export interface DeviceAuthConfig {
18
+ verificationUri: string;
19
+ }
20
+ export interface AppleRevokeConfig {
21
+ teamId: string;
22
+ keyId: string;
23
+ clientId: string;
24
+ privateKey: string | undefined;
25
+ }
26
+ export interface GoogleConfig {
27
+ clientIds: string[];
28
+ keys?: KeySource;
29
+ }
30
+ export interface LegacyFirebaseConfig {
31
+ projectId: string;
32
+ acceptLegacyBearer: boolean;
33
+ keys?: KeySource;
34
+ webApiKey?: string;
35
+ }
36
+ export interface LegacyAccessTokenConfig {
37
+ secret: string | undefined;
38
+ issuer: string;
39
+ audience: string;
40
+ }
41
+ export interface RateLimiterLike {
42
+ limit(options: {
43
+ key: string;
44
+ }): Promise<{
45
+ success: boolean;
46
+ }>;
47
+ }
48
+ export interface RateLimitConfig {
49
+ anonymous?: RateLimiterLike | {
50
+ byIp?: RateLimiterLike;
51
+ byInstall?: RateLimiterLike;
52
+ };
53
+ refresh?: RateLimiterLike | {
54
+ byIp?: RateLimiterLike;
55
+ byDevice?: RateLimiterLike;
56
+ };
57
+ firebase?: RateLimiterLike;
58
+ deviceStart?: RateLimiterLike;
59
+ deviceVerify?: RateLimiterLike | {
60
+ byIp?: RateLimiterLike;
61
+ byUser?: RateLimiterLike;
62
+ };
63
+ }
64
+ export interface AuthHooks<E> {
65
+ onUserCreated?: (userId: string, env: E) => void | Promise<void>;
66
+ onIdentityLinked?: (userId: string, provider: LinkableProvider, env: E) => void | Promise<void>;
67
+ }
68
+ export interface AppAuthConfig<E> {
69
+ app: string;
70
+ db: (env: E) => D1Like;
71
+ tokenSecrets: (env: E) => string | undefined;
72
+ apple?: FromEnv<E, AppleConfig | undefined>;
73
+ google?: FromEnv<E, GoogleConfig | undefined>;
74
+ legacyFirebase?: FromEnv<E, LegacyFirebaseConfig | undefined>;
75
+ legacyAccessToken?: FromEnv<E, LegacyAccessTokenConfig | undefined>;
76
+ device?: FromEnv<E, DeviceAuthConfig | undefined>;
77
+ anonymous?: FromEnv<E, boolean | undefined>;
78
+ requireNonce?: FromEnv<E, boolean | undefined>;
79
+ hooks?: AuthHooks<E>;
80
+ rateLimit?: FromEnv<E, RateLimitConfig | undefined>;
81
+ accessTokenTtlMs?: number;
82
+ refreshTokenIdleTtlMs?: number;
83
+ now?: () => number;
84
+ fetch?: typeof fetch;
85
+ }
86
+ export declare const DEFAULT_ACCESS_TOKEN_TTL_MS: number;
87
+ export declare const DEFAULT_REFRESH_TOKEN_IDLE_TTL_MS: number;
88
+ export declare function fromEnv<E, T>(value: FromEnv<E, T> | undefined, env: E): T | undefined;
package/dist/config.js ADDED
@@ -0,0 +1,5 @@
1
+ export const DEFAULT_ACCESS_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
2
+ export const DEFAULT_REFRESH_TOKEN_IDLE_TTL_MS = 180 * 24 * 60 * 60 * 1000;
3
+ export function fromEnv(value, env) {
4
+ return typeof value === "function" ? value(env) : value;
5
+ }
@@ -0,0 +1,93 @@
1
+ export type ProviderId = "apple" | "google" | "anonymous";
2
+ export type LinkableProvider = Exclude<ProviderId, "anonymous">;
3
+ export type IdentityProvider = LinkableProvider | "firebase";
4
+ export type EpochMs = number;
5
+ export interface SessionUser {
6
+ id: string;
7
+ linkedProviders: ProviderId[];
8
+ createdAt: EpochMs;
9
+ }
10
+ export interface Session {
11
+ user: SessionUser;
12
+ accessToken: string;
13
+ accessTokenExpiresAt: EpochMs;
14
+ refreshToken: string;
15
+ }
16
+ export interface AnonymousRequest {
17
+ installId: string;
18
+ }
19
+ export interface RefreshRequest {
20
+ refreshToken: string;
21
+ }
22
+ export type SignInMode = "link_or_sign_in" | "sign_in_existing";
23
+ export interface AppleRequest {
24
+ identityToken: string;
25
+ installId: string;
26
+ nonce?: string;
27
+ mode?: SignInMode;
28
+ }
29
+ export interface GoogleRequest {
30
+ idToken: string;
31
+ installId: string;
32
+ nonce?: string;
33
+ mode?: SignInMode;
34
+ }
35
+ export interface AppleWebStartQuery {
36
+ installId: string;
37
+ platform: AppleWebPlatform;
38
+ codeChallenge: string;
39
+ }
40
+ export type AppleWebPlatform = "android";
41
+ export type AppleWebReturnQuery = {
42
+ code: string;
43
+ } | {
44
+ error: AppleWebReturnError;
45
+ };
46
+ export type AppleWebReturnError = "invalid_state" | "invalid_apple_token" | "user_cancelled_authorize" | "apple_error";
47
+ export interface AppleWebExchangeRequest {
48
+ code: string;
49
+ installId: string;
50
+ codeVerifier: string;
51
+ mode?: SignInMode;
52
+ }
53
+ export type UnlinkResponse = SessionUser;
54
+ export type FirebaseExchangeRequest = {
55
+ idToken: string;
56
+ installId: string;
57
+ } | {
58
+ refreshToken: string;
59
+ installId: string;
60
+ };
61
+ export interface DeviceStartRequest {
62
+ installId: string;
63
+ deviceName: string;
64
+ }
65
+ export interface DeviceStartResponse {
66
+ deviceCode: string;
67
+ userCode: string;
68
+ verificationUri: string;
69
+ verificationUriComplete: string;
70
+ expiresIn: number;
71
+ interval: number;
72
+ }
73
+ export interface DeviceLookupResponse {
74
+ deviceName: string;
75
+ createdAt: EpochMs;
76
+ }
77
+ export interface DeviceDecisionRequest {
78
+ userCode: string;
79
+ }
80
+ export interface DeviceTokenRequest {
81
+ deviceCode: string;
82
+ installId: string;
83
+ }
84
+ export type FirebaseRefreshRejection = "TOKEN_EXPIRED" | "USER_DISABLED" | "USER_NOT_FOUND" | "INVALID_REFRESH_TOKEN";
85
+ export type ErrorReason = "invalid_json" | "body_too_large" | "bad_request" | "missing_token" | "invalid_token" | "invalid_refresh_token" | "invalid_apple_token" | "invalid_google_token" | "invalid_nonce" | "invalid_firebase_token" | "legacy_credential_rejected" | "firebase_unavailable" | "rate_limited" | "credential_already_in_use" | "identity_not_linked" | "last_identity" | "account_not_found" | "invalid_code" | "provider_not_enabled" | "account_deleted" | "invalid_user_code" | "authorization_pending" | "slow_down" | "expired_token" | "access_denied";
86
+ export interface ErrorBody {
87
+ error: {
88
+ reason: ErrorReason;
89
+ message: string;
90
+ details?: Record<string, unknown>;
91
+ };
92
+ }
93
+ export type AuthKind = "session" | "legacy_firebase" | "legacy_access_token";
File without changes
package/dist/d1.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export interface D1RunResult {
2
+ meta: {
3
+ changes: number;
4
+ };
5
+ }
6
+ export interface D1StatementLike {
7
+ bind(...values: unknown[]): D1StatementLike;
8
+ first<T = Record<string, unknown>>(): Promise<T | null>;
9
+ all<T = Record<string, unknown>>(): Promise<{
10
+ results: T[];
11
+ }>;
12
+ run(): Promise<D1RunResult>;
13
+ }
14
+ export interface D1Like {
15
+ prepare(sql: string): D1StatementLike;
16
+ batch(statements: D1StatementLike[]): Promise<D1RunResult[]>;
17
+ }
package/dist/d1.js ADDED
File without changes
@@ -0,0 +1,14 @@
1
+ import { type AppleRevocation } from "./apple-revoke.js";
2
+ import { type AppAuthConfig, type AppleRevokeConfig } from "./config.js";
3
+ import type { D1Like } from "./d1.js";
4
+ export interface DeleteUserOptions {
5
+ appleAuthorizationCode?: string;
6
+ appleRevoke?: AppleRevokeConfig | undefined;
7
+ fetch?: typeof fetch;
8
+ now?: number;
9
+ }
10
+ export interface DeleteUserResult {
11
+ apple: AppleRevocation;
12
+ }
13
+ export declare function deleteUser(db: D1Like, userId: string, options?: DeleteUserOptions): Promise<DeleteUserResult>;
14
+ export declare function appleRevokeConfig<E>(config: AppAuthConfig<E>, env: E): AppleRevokeConfig | undefined;
@@ -0,0 +1,17 @@
1
+ import { revokeAppleAuthorization } from "./apple-revoke.js";
2
+ import { fromEnv } from "./config.js";
3
+ import { deleteAuthRows } from "./store.js";
4
+ export async function deleteUser(db, userId, options = {}) {
5
+ const now = options.now ?? Date.now();
6
+ const apple = options.appleAuthorizationCode
7
+ ? await revokeAppleAuthorization(options.appleRevoke, options.appleAuthorizationCode, {
8
+ now,
9
+ ...(options.fetch ? { fetch: options.fetch } : {}),
10
+ })
11
+ : { status: "not_requested" };
12
+ await deleteAuthRows(db, userId, now);
13
+ return { apple };
14
+ }
15
+ export function appleRevokeConfig(config, env) {
16
+ return fromEnv(config.apple, env)?.revoke;
17
+ }
@@ -0,0 +1,9 @@
1
+ import { Hono } from "hono";
2
+ import { type AuthEnv } from "./authenticate.js";
3
+ import { type AppAuthConfig } from "./config.js";
4
+ import type { Session } from "./contract.js";
5
+ export interface DeviceRouteDeps<E> {
6
+ now: () => number;
7
+ newSession: (env: E, userId: string, installId: string, at: number) => Promise<Session>;
8
+ }
9
+ export declare function deviceRoutes<E extends object>(config: AppAuthConfig<E>, deps: DeviceRouteDeps<E>): Hono<AuthEnv<E>>;
@@ -0,0 +1,144 @@
1
+ import { Hono } from "hono";
2
+ import { ownsAccount, resolveBearer } from "./authenticate.js";
3
+ import { fromEnv } from "./config.js";
4
+ import { createDeviceCode, decideDeviceCode, DEVICE_CODE_TTL_MS, DEVICE_POLL_INTERVAL_MS, displayUserCode, normalizeUserCode, pendingDevice, pollDeviceCode, } from "./device.js";
5
+ import { bearerToken, fail, nonEmptyString, rateLimited, readObject } from "./http.js";
6
+ const MAX_INSTALL_ID = 128;
7
+ const MAX_DEVICE_NAME = 64;
8
+ const MAX_DEVICE_CODE = 256;
9
+ async function verifyAllowed(limiter, ip, userId) {
10
+ if (!limiter)
11
+ return true;
12
+ const { byIp, byUser } = "limit" in limiter ? { byIp: limiter, byUser: limiter } : limiter;
13
+ const checks = [];
14
+ if (byIp && ip)
15
+ checks.push(byIp.limit({ key: `ip:${ip}` }));
16
+ if (byUser)
17
+ checks.push(byUser.limit({ key: `user:${userId}` }));
18
+ return (await Promise.all(checks)).every((result) => result.success);
19
+ }
20
+ export function deviceRoutes(config, deps) {
21
+ const app = new Hono();
22
+ const notEnabled = (c) => fail(c, 404, "provider_not_enabled", "device authorization is not enabled");
23
+ const invalidUserCode = (c) => fail(c, 404, "invalid_user_code", "user code is not valid");
24
+ app.post("/v1/auth/device/start", async (c) => {
25
+ const device = fromEnv(config.device, c.env);
26
+ if (!device)
27
+ return notEnabled(c);
28
+ const body = await readObject(c);
29
+ if (body instanceof Response)
30
+ return body;
31
+ const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
32
+ const deviceName = nonEmptyString(body.deviceName, MAX_DEVICE_NAME);
33
+ if (!installId || !deviceName)
34
+ return fail(c, 400, "bad_request", `installId and deviceName (${MAX_DEVICE_NAME} characters or less) are required`);
35
+ const limiter = fromEnv(config.rateLimit, c.env)?.deviceStart;
36
+ const ip = c.req.header("cf-connecting-ip");
37
+ if (limiter && ip && !(await limiter.limit({ key: `ip:${ip}` })).success)
38
+ return rateLimited(c, "device authorizations");
39
+ const started = await createDeviceCode(config.db(c.env), installId, deviceName, deps.now());
40
+ const userCode = displayUserCode(started.userCode);
41
+ const response = {
42
+ deviceCode: started.deviceCode,
43
+ userCode,
44
+ verificationUri: device.verificationUri,
45
+ verificationUriComplete: verificationUriComplete(device, userCode),
46
+ expiresIn: DEVICE_CODE_TTL_MS / 1000,
47
+ interval: DEVICE_POLL_INTERVAL_MS / 1000,
48
+ };
49
+ c.header("cache-control", "no-store");
50
+ return c.json(response);
51
+ });
52
+ async function approver(c) {
53
+ if (!fromEnv(config.device, c.env))
54
+ return notEnabled(c);
55
+ const token = bearerToken(c);
56
+ if (!token)
57
+ return fail(c, 401, "missing_token", "Authorization: Bearer <token> is required");
58
+ const current = await resolveBearer(config, c.env, token, { allowLegacy: false });
59
+ if (current.kind === "deleted")
60
+ return fail(c, 410, "account_deleted", "account was deleted");
61
+ if (!ownsAccount(current))
62
+ return fail(c, 401, "invalid_token", "access token is not valid");
63
+ if (!(await verifyAllowed(fromEnv(config.rateLimit, c.env)?.deviceVerify, c.req.header("cf-connecting-ip"), current.userId))) {
64
+ return rateLimited(c, "device code checks");
65
+ }
66
+ return { userId: current.userId };
67
+ }
68
+ async function decisionCode(c) {
69
+ const body = await readObject(c);
70
+ if (body instanceof Response)
71
+ return body;
72
+ if (body.userCode === undefined)
73
+ return fail(c, 400, "bad_request", "userCode is required");
74
+ return normalizeUserCode(body.userCode) ?? invalidUserCode(c);
75
+ }
76
+ app.get("/v1/auth/device/lookup", async (c) => {
77
+ const who = await approver(c);
78
+ if (who instanceof Response)
79
+ return who;
80
+ const raw = c.req.query("userCode");
81
+ if (raw === undefined)
82
+ return fail(c, 400, "bad_request", "userCode is required");
83
+ const userCode = normalizeUserCode(raw);
84
+ const found = userCode ? await pendingDevice(config.db(c.env), userCode, deps.now()) : null;
85
+ if (!found)
86
+ return invalidUserCode(c);
87
+ const response = found;
88
+ c.header("cache-control", "no-store");
89
+ return c.json(response);
90
+ });
91
+ app.post("/v1/auth/device/approve", async (c) => {
92
+ const who = await approver(c);
93
+ if (who instanceof Response)
94
+ return who;
95
+ const userCode = await decisionCode(c);
96
+ if (userCode instanceof Response)
97
+ return userCode;
98
+ if (!(await decideDeviceCode(config.db(c.env), userCode, { approve: who.userId }, deps.now())))
99
+ return invalidUserCode(c);
100
+ return c.body(null, 204);
101
+ });
102
+ app.post("/v1/auth/device/deny", async (c) => {
103
+ const who = await approver(c);
104
+ if (who instanceof Response)
105
+ return who;
106
+ const userCode = await decisionCode(c);
107
+ if (userCode instanceof Response)
108
+ return userCode;
109
+ await decideDeviceCode(config.db(c.env), userCode, "deny", deps.now());
110
+ return c.body(null, 204);
111
+ });
112
+ app.post("/v1/auth/device/token", async (c) => {
113
+ if (!fromEnv(config.device, c.env))
114
+ return notEnabled(c);
115
+ const body = await readObject(c);
116
+ if (body instanceof Response)
117
+ return body;
118
+ const deviceCode = nonEmptyString(body.deviceCode, MAX_DEVICE_CODE);
119
+ const installId = nonEmptyString(body.installId, MAX_INSTALL_ID);
120
+ if (!deviceCode || !installId)
121
+ return fail(c, 400, "bad_request", "deviceCode and installId are required");
122
+ const at = deps.now();
123
+ const poll = await pollDeviceCode(config.db(c.env), deviceCode, installId, at);
124
+ c.header("cache-control", "no-store");
125
+ switch (poll.kind) {
126
+ case "approved":
127
+ return c.json(await deps.newSession(c.env, poll.userId, installId, at));
128
+ case "authorization_pending":
129
+ return fail(c, 400, "authorization_pending", "waiting for the user to approve on the phone");
130
+ case "slow_down":
131
+ return fail(c, 400, "slow_down", "polling too fast; add 5 seconds to the interval");
132
+ case "access_denied":
133
+ return fail(c, 400, "access_denied", "the user denied this device");
134
+ case "expired_token":
135
+ return fail(c, 400, "expired_token", "device code is expired or not valid; start again");
136
+ }
137
+ });
138
+ return app;
139
+ }
140
+ function verificationUriComplete(device, userCode) {
141
+ const url = new URL(device.verificationUri);
142
+ url.searchParams.set("code", userCode);
143
+ return url.toString();
144
+ }
@@ -0,0 +1,31 @@
1
+ import type { D1Like } from "./d1.js";
2
+ export declare const DEVICE_CODE_TTL_MS: number;
3
+ export declare const DEVICE_POLL_INTERVAL_MS: number;
4
+ export declare function displayUserCode(code: string): string;
5
+ export declare function normalizeUserCode(value: unknown): string | null;
6
+ export interface StartedDeviceCode {
7
+ deviceCode: string;
8
+ userCode: string;
9
+ expiresAt: number;
10
+ }
11
+ export declare function createDeviceCode(db: D1Like, installId: string, deviceName: string, now: number): Promise<StartedDeviceCode>;
12
+ export declare function pendingDevice(db: D1Like, userCode: string, now: number): Promise<{
13
+ deviceName: string;
14
+ createdAt: number;
15
+ } | null>;
16
+ export declare function decideDeviceCode(db: D1Like, userCode: string, decision: {
17
+ approve: string;
18
+ } | "deny", now: number): Promise<boolean>;
19
+ export type DevicePoll = {
20
+ kind: "approved";
21
+ userId: string;
22
+ } | {
23
+ kind: "authorization_pending";
24
+ } | {
25
+ kind: "slow_down";
26
+ } | {
27
+ kind: "expired_token";
28
+ } | {
29
+ kind: "access_denied";
30
+ };
31
+ export declare function pollDeviceCode(db: D1Like, deviceCode: string, installId: string, now: number): Promise<DevicePoll>;