fix(auth): revoke stale sessions and tokens

Revoked or rotated credentials must stop working despite stale KV
replicas. Track the live token and revocations in D1 and preserve
immutable identity bindings rather than trusting a recycled login.
This commit is contained in:
翅膀 committed 2026-10-23 23:22:52 +08:00
1 parent 5ff2338b48
commit 2bdce90776
5 files changed
+285 -22

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ async function userOctokit(
event: H3Event,
userId: string,
): Promise<Awaited<ReturnType<typeof getUserOctokit>>> {
return getUserOctokit(userId, cfEnv(event).KV);
return getUserOctokit(userId, cfEnv(event));
}
function fail(event: H3Event, status: number, error: string): Record<string, unknown> {
+2 -1
View File
@@ -99,7 +99,8 @@ export async function bearerUserId(event: H3Event): Promise<string> {
const auth = getHeader(event, "authorization");
if (!auth?.startsWith("Bearer "))
throw createError({ statusCode: 401, statusMessage: "Missing authorization" });
const userId = await findUserIdByToken(env.KV, auth.slice(7));
// Resolves only the user's *current* token: a rotated or revoked one fails.
const userId = await findUserIdByToken(env.KV, auth.slice(7), env.DB);
if (!userId) throw createError({ statusCode: 401, statusMessage: "Invalid or expired token" });
return userId;
}
+60 -7
View File
@@ -1,4 +1,5 @@
import type { Env } from "../types";
import { idempotencyStore } from "../lib/idempotency";
const SESSION_COOKIE = "wh_admin_session";
const SESSION_TTL = 24 * 3600;
@@ -6,6 +7,33 @@ const SESSION_TTL = 24 * 3600;
export interface AdminSession {
userId: string;
login: string;
/**
* False when the login was first seen with another GitHub account (a name
* released by a rename and taken over since): identity checks then match
* this session by its user id only, never by the login.
*/
loginTrusted?: boolean;
}
/** The login identity checks may use for this session ("" — by user id only). */
export function authLogin(session: AdminSession): string {
return session.loginTrusted === false ? "" : session.login;
}
/**
* Whether `login` belongs to `userId` as far as this deployment knows: the
* first account seen with a login owns it here (`login-owner:{login}`). A
* GitHub login can be renamed away and registered by someone else; that
* newcomer then never inherits what was granted to the login (an admin
* entry, a member entry not yet bound to an id).
*/
export async function claimLogin(kv: KVNamespace, userId: string, login: string): Promise<boolean> {
const key = `login-owner:${login.toLowerCase()}`;
const owner = await kv.get(key);
if (owner) return owner === userId;
await kv.put(key, userId);
// Read back: of two first sign-ins racing, only the one stored wins.
return (await kv.get(key)) === userId;
}
export function isDebugMode(env: Env): boolean {
@@ -20,14 +48,24 @@ export function isDebugMode(env: Env): boolean {
return false;
}
/**
* Whether one configured identity names this user. An all-digit entry is a
* GitHub user id, anything else a login (case-insensitive) — one string is
* never matched both ways, so a user whose login is digits can never pass for
* the user with that id.
*/
export function identityEntryMatches(entry: string, userId: string, login: string): boolean {
const e = entry.trim();
if (!e) return false;
if (/^\d+$/.test(e)) return e === userId;
return e.toLowerCase() === login.toLowerCase();
}
export function isAdminUser(env: Env, userId: string, login: string): boolean {
if (isDebugMode(env)) return true;
const ids = (env.ADMIN_USER_IDS ?? "")
return (env.ADMIN_USER_IDS ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (ids.length === 0) return false;
return ids.includes(userId) || ids.some((id) => id.toLowerCase() === login.toLowerCase());
.some((entry) => identityEntryMatches(entry, userId, login));
}
function generateSessionId(): string {
@@ -42,9 +80,10 @@ export async function createAdminSession(
kv: KVNamespace,
userId: string,
login: string,
loginTrusted = true,
): Promise<string> {
const sessionId = generateSessionId();
const session: AdminSession = { userId, login };
const session: AdminSession = loginTrusted ? { userId, login } : { userId, login, loginTrusted };
await kv.put(`session:${sessionId}`, JSON.stringify(session), {
expirationTtl: SESSION_TTL,
});
@@ -70,21 +109,35 @@ function parseCookies(header: string | undefined): Record<string, string> {
return out;
}
/**
* Sessions are revoked in the idempotency store (D1) as well as deleted from
* KV: a KV delete takes a while to reach every location, and a stolen cookie
* must stop working at once.
*/
function revokedSessionKey(sessionId: string): string {
return `session-revoked:${sessionId}`;
}
export async function getAdminSession(
kv: KVNamespace,
cookieHeader: string | undefined,
db?: D1Database,
): Promise<AdminSession | null> {
const sessionId = parseCookies(cookieHeader)[SESSION_COOKIE];
if (!sessionId) return null;
const raw = await kv.get<AdminSession>(`session:${sessionId}`, "json");
if (!raw) return null;
if (db && (await idempotencyStore(db, kv).has(revokedSessionKey(sessionId)))) return null;
return raw;
}
export async function destroyAdminSession(
kv: KVNamespace,
cookieHeader: string | undefined,
db?: D1Database,
): Promise<void> {
const sessionId = parseCookies(cookieHeader)[SESSION_COOKIE];
if (sessionId) await kv.delete(`session:${sessionId}`);
if (!sessionId) return;
if (db) await idempotencyStore(db, kv).claim(revokedSessionKey(sessionId), SESSION_TTL);
await kv.delete(`session:${sessionId}`);
}