@appgrowstack/app-auth 0.0.0-stage → 0.7.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.
@@ -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>;
package/dist/device.js ADDED
@@ -0,0 +1,88 @@
1
+ import { hashSecret, newRefreshSecret } from "./tokens.js";
2
+ export const DEVICE_CODE_TTL_MS = 600 * 1000;
3
+ export const DEVICE_POLL_INTERVAL_MS = 5 * 1000;
4
+ const POLL_JITTER_MS = 1000;
5
+ const USER_CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
6
+ const USER_CODE_LENGTH = 8;
7
+ const USER_CODE = new RegExp(`^[${USER_CODE_ALPHABET}]{${USER_CODE_LENGTH}}$`);
8
+ function newUserCode() {
9
+ const limit = 256 - (256 % USER_CODE_ALPHABET.length);
10
+ let code = "";
11
+ while (code.length < USER_CODE_LENGTH) {
12
+ const bytes = new Uint8Array(USER_CODE_LENGTH * 2);
13
+ crypto.getRandomValues(bytes);
14
+ for (const b of bytes) {
15
+ if (b < limit && code.length < USER_CODE_LENGTH)
16
+ code += USER_CODE_ALPHABET[b % USER_CODE_ALPHABET.length];
17
+ }
18
+ }
19
+ return code;
20
+ }
21
+ export function displayUserCode(code) {
22
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
23
+ }
24
+ export function normalizeUserCode(value) {
25
+ if (typeof value !== "string" || value.length > 32)
26
+ return null;
27
+ const code = value.replace(/[\s-]/g, "").toUpperCase();
28
+ return USER_CODE.test(code) ? code : null;
29
+ }
30
+ const USER_CODE_ATTEMPTS = 5;
31
+ export async function createDeviceCode(db, installId, deviceName, now) {
32
+ await db.prepare("DELETE FROM auth_device_codes WHERE expires_at <= ?").bind(now).run();
33
+ const expiresAt = now + DEVICE_CODE_TTL_MS;
34
+ for (let attempt = 0; attempt < USER_CODE_ATTEMPTS; attempt++) {
35
+ const deviceCode = newRefreshSecret();
36
+ const userCode = newUserCode();
37
+ const inserted = await db
38
+ .prepare(`INSERT INTO auth_device_codes (device_code_hash, user_code, install_id, device_name, status, created_at, expires_at)
39
+ VALUES (?, ?, ?, ?, 'pending', ?, ?) ON CONFLICT DO NOTHING`)
40
+ .bind(await hashSecret(deviceCode), userCode, installId, deviceName, now, expiresAt)
41
+ .run();
42
+ if (inserted.meta.changes === 1)
43
+ return { deviceCode, userCode, expiresAt };
44
+ }
45
+ throw new Error("could not allocate a unique user code");
46
+ }
47
+ export async function pendingDevice(db, userCode, now) {
48
+ return db
49
+ .prepare("SELECT device_name AS deviceName, created_at AS createdAt FROM auth_device_codes WHERE user_code = ? AND status = 'pending' AND expires_at > ?")
50
+ .bind(userCode, now)
51
+ .first();
52
+ }
53
+ export async function decideDeviceCode(db, userCode, decision, now) {
54
+ const statement = decision === "deny"
55
+ ? db.prepare("UPDATE auth_device_codes SET status = 'denied' WHERE user_code = ? AND status = 'pending' AND expires_at > ?").bind(userCode, now)
56
+ : db
57
+ .prepare("UPDATE auth_device_codes SET status = 'approved', user_id = ? WHERE user_code = ? AND status = 'pending' AND expires_at > ?")
58
+ .bind(decision.approve, userCode, now);
59
+ return (await statement.run()).meta.changes === 1;
60
+ }
61
+ export async function pollDeviceCode(db, deviceCode, installId, now) {
62
+ const hash = await hashSecret(deviceCode);
63
+ const row = await db
64
+ .prepare(`SELECT install_id AS installId, status, user_id AS userId, expires_at AS expiresAt, last_polled_at AS lastPolledAt
65
+ FROM auth_device_codes WHERE device_code_hash = ?`)
66
+ .bind(hash)
67
+ .first();
68
+ if (!row || row.installId !== installId)
69
+ return { kind: "expired_token" };
70
+ const remove = () => db.prepare("DELETE FROM auth_device_codes WHERE device_code_hash = ?").bind(hash).run();
71
+ if (row.expiresAt <= now) {
72
+ await remove();
73
+ return { kind: "expired_token" };
74
+ }
75
+ await db.prepare("UPDATE auth_device_codes SET last_polled_at = ? WHERE device_code_hash = ?").bind(now, hash).run();
76
+ if (row.lastPolledAt !== null && now - row.lastPolledAt < DEVICE_POLL_INTERVAL_MS - POLL_JITTER_MS)
77
+ return { kind: "slow_down" };
78
+ if (row.status === "pending")
79
+ return { kind: "authorization_pending" };
80
+ if (row.status === "denied") {
81
+ await remove();
82
+ return { kind: "access_denied" };
83
+ }
84
+ const consumed = await db.prepare("DELETE FROM auth_device_codes WHERE device_code_hash = ? AND status = 'approved'").bind(hash).run();
85
+ if (consumed.meta.changes !== 1 || !row.userId)
86
+ return { kind: "expired_token" };
87
+ return { kind: "approved", userId: row.userId };
88
+ }
@@ -0,0 +1,14 @@
1
+ import type { FirebaseRefreshRejection } from "./contract.js";
2
+ export declare const SECURETOKEN_URL = "https://securetoken.googleapis.com/v1/token";
3
+ export type FirebaseRefreshResult = {
4
+ kind: "ok";
5
+ idToken: string;
6
+ } | {
7
+ kind: "rejected";
8
+ cause: FirebaseRefreshRejection;
9
+ } | {
10
+ kind: "unavailable";
11
+ httpStatus?: number;
12
+ message?: string;
13
+ };
14
+ export declare function exchangeFirebaseRefreshToken(send: typeof fetch, webApiKey: string, refreshToken: string): Promise<FirebaseRefreshResult>;
@@ -0,0 +1,33 @@
1
+ export const SECURETOKEN_URL = "https://securetoken.googleapis.com/v1/token";
2
+ const TIMEOUT_MS = 10_000;
3
+ const REJECTIONS = ["TOKEN_EXPIRED", "USER_DISABLED", "USER_NOT_FOUND", "INVALID_REFRESH_TOKEN"];
4
+ export async function exchangeFirebaseRefreshToken(send, webApiKey, refreshToken) {
5
+ let response;
6
+ try {
7
+ response = await send(`${SECURETOKEN_URL}?key=${encodeURIComponent(webApiKey)}`, {
8
+ method: "POST",
9
+ headers: { "content-type": "application/x-www-form-urlencoded" },
10
+ body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken }).toString(),
11
+ signal: AbortSignal.timeout(TIMEOUT_MS),
12
+ });
13
+ }
14
+ catch {
15
+ return { kind: "unavailable" };
16
+ }
17
+ const body = await response.json().catch(() => null);
18
+ if (response.ok) {
19
+ const idToken = typeof body === "object" && body !== null ? body.id_token : undefined;
20
+ return typeof idToken === "string" && idToken.length > 0 ? { kind: "ok", idToken } : { kind: "unavailable", httpStatus: response.status };
21
+ }
22
+ const message = errorMessage(body);
23
+ const head = message?.split(/[\s:]/, 1)[0];
24
+ const cause = REJECTIONS.find((r) => r === head);
25
+ if (response.status === 400 && cause)
26
+ return { kind: "rejected", cause };
27
+ return { kind: "unavailable", httpStatus: response.status, ...(message ? { message } : {}) };
28
+ }
29
+ function errorMessage(body) {
30
+ const error = typeof body === "object" && body !== null ? body.error : undefined;
31
+ const message = typeof error === "object" && error !== null ? error.message : undefined;
32
+ return typeof message === "string" ? message : undefined;
33
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Context } from "hono";
2
+ import type { ErrorReason } from "./contract.js";
3
+ export type FailStatus = 400 | 401 | 404 | 409 | 410 | 413 | 429 | 503;
4
+ export declare function fail(c: Context, status: FailStatus, reason: ErrorReason, message: string, details?: Record<string, unknown>): Response & import("hono").TypedResponse<{
5
+ error: {
6
+ reason: ErrorReason;
7
+ message: string;
8
+ details?: {
9
+ [x: string]: import("hono/utils/types").JSONValue;
10
+ };
11
+ };
12
+ }, 400 | 401 | 404 | 409 | 410 | 413 | 429 | 503, "json">;
13
+ export declare const MAX_BODY_BYTES: number;
14
+ export declare function readObject(c: Context): Promise<Record<string, unknown> | Response>;
15
+ export declare function bearerToken(c: Context): string | null;
16
+ export declare function nonEmptyString(value: unknown, maxLength: number): string | null;
17
+ export declare function rateLimited(c: Context, what: string): Response & import("hono").TypedResponse<{
18
+ error: {
19
+ reason: ErrorReason;
20
+ message: string;
21
+ details?: {
22
+ [x: string]: import("hono/utils/types").JSONValue;
23
+ };
24
+ };
25
+ }, 400 | 401 | 404 | 409 | 410 | 413 | 429 | 503, "json">;
package/dist/http.js ADDED
@@ -0,0 +1,32 @@
1
+ export function fail(c, status, reason, message, details) {
2
+ const body = { error: { reason, message, ...(details ? { details } : {}) } };
3
+ return c.json(body, status);
4
+ }
5
+ export const MAX_BODY_BYTES = 64 * 1024;
6
+ export async function readObject(c) {
7
+ const declared = Number(c.req.header("content-length") ?? "0");
8
+ if (declared > MAX_BODY_BYTES)
9
+ return fail(c, 413, "body_too_large", `body must be ${MAX_BODY_BYTES} bytes or less`);
10
+ const bytes = await c.req.arrayBuffer().catch(() => null);
11
+ if (bytes && bytes.byteLength > MAX_BODY_BYTES)
12
+ return fail(c, 413, "body_too_large", `body must be ${MAX_BODY_BYTES} bytes or less`);
13
+ try {
14
+ const body = bytes ? JSON.parse(new TextDecoder().decode(bytes)) : null;
15
+ if (body !== null && typeof body === "object" && !Array.isArray(body))
16
+ return body;
17
+ }
18
+ catch {
19
+ }
20
+ return fail(c, 400, "invalid_json", "body is not a JSON object");
21
+ }
22
+ export function bearerToken(c) {
23
+ const match = /^Bearer\s+(.+)$/i.exec(c.req.header("authorization") ?? "");
24
+ return match?.[1]?.trim() || null;
25
+ }
26
+ export function nonEmptyString(value, maxLength) {
27
+ return typeof value === "string" && value.length > 0 && value.length <= maxLength ? value : null;
28
+ }
29
+ export function rateLimited(c, what) {
30
+ c.header("retry-after", "60");
31
+ return fail(c, 429, "rate_limited", `too many ${what}; retry later`);
32
+ }
@@ -0,0 +1,11 @@
1
+ export { authRoutes, issueSession } from "./routes.js";
2
+ export { authenticate, resolveBearer, type AuthEnv, type AuthVariables, type ResolvedBearer } from "./authenticate.js";
3
+ export { deleteUser, appleRevokeConfig, type DeleteUserOptions, type DeleteUserResult } from "./delete-user.js";
4
+ export { revokeAppleAuthorization, appleClientSecret, APPLE_REVOKE_URL, APPLE_TOKEN_URL, type AppleRevocation } from "./apple-revoke.js";
5
+ export { SECURETOKEN_URL } from "./firebase-refresh.js";
6
+ export { DEVICE_CODE_TTL_MS, DEVICE_POLL_INTERVAL_MS } from "./device.js";
7
+ export { APPLE_AUTHORIZE_URL, APPLE_WEB_CODE_TTL_MS, APPLE_WEB_STATE_TTL_MS } from "./apple-web.js";
8
+ export * from "./config.js";
9
+ export * from "./contract.js";
10
+ export type { D1Like, D1StatementLike, D1RunResult } from "./d1.js";
11
+ export { parseTokenSecrets, type TokenKeyring } from "./tokens.js";
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export { authRoutes, issueSession } from "./routes.js";
2
+ export { authenticate, resolveBearer } from "./authenticate.js";
3
+ export { deleteUser, appleRevokeConfig } from "./delete-user.js";
4
+ export { revokeAppleAuthorization, appleClientSecret, APPLE_REVOKE_URL, APPLE_TOKEN_URL } from "./apple-revoke.js";
5
+ export { SECURETOKEN_URL } from "./firebase-refresh.js";
6
+ export { DEVICE_CODE_TTL_MS, DEVICE_POLL_INTERVAL_MS } from "./device.js";
7
+ export { APPLE_AUTHORIZE_URL, APPLE_WEB_CODE_TTL_MS, APPLE_WEB_STATE_TTL_MS } from "./apple-web.js";
8
+ export * from "./config.js";
9
+ export * from "./contract.js";
10
+ export { parseTokenSecrets } from "./tokens.js";
@@ -0,0 +1,24 @@
1
+ import type { AppleConfig, GoogleConfig, LegacyFirebaseConfig } from "./config.js";
2
+ export declare const APPLE_ISSUER = "https://appleid.apple.com";
3
+ export declare const APPLE_KEYS_URL = "https://appleid.apple.com/auth/keys";
4
+ export declare const GOOGLE_ISSUERS: string[];
5
+ export declare const GOOGLE_KEYS_URL = "https://www.googleapis.com/oauth2/v3/certs";
6
+ export declare const FIREBASE_KEYS_URL = "https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com";
7
+ export interface AppleTokenExpectation {
8
+ audience?: string;
9
+ nonce?: string;
10
+ }
11
+ export interface VerifiedIdToken {
12
+ sub: string;
13
+ nonce: unknown;
14
+ }
15
+ export declare function verifyAppleIdToken(config: AppleConfig, token: string, now: number, audience?: string): Promise<VerifiedIdToken | null>;
16
+ export declare function verifyAppleToken(config: AppleConfig, token: string, now: number, expect?: AppleTokenExpectation): Promise<string | null>;
17
+ export declare function verifyGoogleToken(config: GoogleConfig, token: string, now: number): Promise<VerifiedIdToken | null>;
18
+ export declare function hashedNonce(rawNonce: string): Promise<string>;
19
+ export interface FirebaseIdentity {
20
+ uid: string;
21
+ appleSubjects: string[];
22
+ googleSubjects: string[];
23
+ }
24
+ export declare function verifyFirebaseToken(config: LegacyFirebaseConfig, token: string, now: number): Promise<FirebaseIdentity | null>;
@@ -0,0 +1,74 @@
1
+ import { createRemoteJWKSet, jwtVerify } from "jose";
2
+ export const APPLE_ISSUER = "https://appleid.apple.com";
3
+ export const APPLE_KEYS_URL = "https://appleid.apple.com/auth/keys";
4
+ export const GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
5
+ export const GOOGLE_KEYS_URL = "https://www.googleapis.com/oauth2/v3/certs";
6
+ export const FIREBASE_KEYS_URL = "https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com";
7
+ const remoteKeySets = new Map();
8
+ function keyGetter(source, fallbackUrl) {
9
+ if (typeof source === "function")
10
+ return source;
11
+ const url = source ?? fallbackUrl;
12
+ let keys = remoteKeySets.get(url);
13
+ if (!keys) {
14
+ keys = createRemoteJWKSet(new URL(url));
15
+ remoteKeySets.set(url, keys);
16
+ }
17
+ return keys;
18
+ }
19
+ async function verifiedPayload(token, keys, options) {
20
+ try {
21
+ const { payload } = await jwtVerify(token, keys, {
22
+ issuer: options.issuer,
23
+ audience: options.audience,
24
+ algorithms: ["RS256"],
25
+ requiredClaims: ["exp"],
26
+ currentDate: new Date(options.now),
27
+ });
28
+ return typeof payload.sub === "string" && payload.sub.length > 0 ? payload : null;
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ export async function verifyAppleIdToken(config, token, now, audience) {
35
+ const payload = await verifiedPayload(token, keyGetter(config.keys, APPLE_KEYS_URL), { issuer: APPLE_ISSUER, audience: audience ?? config.audience, now });
36
+ return payload?.sub ? { sub: payload.sub, nonce: payload.nonce } : null;
37
+ }
38
+ export async function verifyAppleToken(config, token, now, expect = {}) {
39
+ const verified = await verifyAppleIdToken(config, token, now, expect.audience);
40
+ if (!verified)
41
+ return null;
42
+ if (expect.nonce !== undefined && verified.nonce !== expect.nonce)
43
+ return null;
44
+ return verified.sub;
45
+ }
46
+ export async function verifyGoogleToken(config, token, now) {
47
+ if (config.clientIds.length === 0)
48
+ return null;
49
+ const payload = await verifiedPayload(token, keyGetter(config.keys, GOOGLE_KEYS_URL), { issuer: GOOGLE_ISSUERS, audience: config.clientIds, now });
50
+ return payload?.sub ? { sub: payload.sub, nonce: payload.nonce } : null;
51
+ }
52
+ export async function hashedNonce(rawNonce) {
53
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(rawNonce)));
54
+ return Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
55
+ }
56
+ export async function verifyFirebaseToken(config, token, now) {
57
+ const payload = await verifiedPayload(token, keyGetter(config.keys, FIREBASE_KEYS_URL), {
58
+ issuer: `https://securetoken.google.com/${config.projectId}`,
59
+ audience: config.projectId,
60
+ now,
61
+ });
62
+ if (!payload?.sub)
63
+ return null;
64
+ const identities = readIdentities(payload.firebase);
65
+ return { uid: payload.sub, appleSubjects: identities["apple.com"], googleSubjects: identities["google.com"] };
66
+ }
67
+ function readIdentities(claim) {
68
+ const identities = typeof claim === "object" && claim !== null ? claim.identities : undefined;
69
+ const pick = (key) => {
70
+ const value = typeof identities === "object" && identities !== null ? identities[key] : undefined;
71
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string" && v.length > 0) : [];
72
+ };
73
+ return { "apple.com": pick("apple.com"), "google.com": pick("google.com") };
74
+ }
@@ -0,0 +1,6 @@
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 declare function issueSession<E>(config: AppAuthConfig<E>, env: E, userId: string, installId: string, at: number, previousUserId?: string | null): Promise<Session>;
6
+ export declare function authRoutes<E extends object>(config: AppAuthConfig<E>): Hono<AuthEnv<E>>;