diff --git a/src/auth.ts b/src/auth.ts index 6ddb9e9..a8d315a 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -20,39 +20,73 @@ export const isIdentityAllowed = (identity?: string | null) => { return allowedIdentities.has(identityNormalized); }; -export const verifyToken = async (idToken: string) => { - const JWKS = jose.createRemoteJWKSet( - new URL("https://www.googleapis.com/oauth2/v3/certs"), - ); +/** + * Hard cap on how long a session may live after sign-in, regardless of + * activity. + */ +export const SESSION_ABSOLUTE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; +/** + * How long a session may go unused. It is the cookie's `maxAge` (see + * index.ts), which rolls while the session is in use, and it is also checked + * here against `lastActiveAt`: the cookie's own expiry only binds a browser + * that honours it, not a copy of the cookie. + */ +export const SESSION_IDLE_MAX_AGE_MS = 24 * 60 * 60 * 1000; + +/** + * cookie-session only re-sends the cookie when the session object changes, so + * to roll the idle timeout we touch `lastActiveAt` — but at most this often, to + * avoid a Set-Cookie on every request. + */ +export const SESSION_TOUCH_INTERVAL_MS = 5 * 60 * 1000; + +type SessionClaims = jose.JWTPayload & { email?: string }; + +/** + * Returns the ID token claims of a session, or null when the session is + * missing, malformed, idle for too long, or past its absolute lifetime. + * + * The ID token was verified (signature, issuer, audience) by openid-client in + * the OIDC callback, and the session cookie itself is signed with + * COOKIE_SECRET, so the token is not re-verified here. In particular its `exp` + * is NOT treated as the session expiry: Google issues ID tokens for about an + * hour, and using that as the session lifetime signed everyone out hourly. + */ +export function getActiveSession( + session: CookieSessionInterfaces.CookieSessionObject | null | undefined, +): SessionClaims | null { + const idToken = session?.id_token; + if (typeof idToken !== "string" || !idToken) return null; + + let claims: SessionClaims; try { - const { payload } = await jose.jwtVerify(idToken, JWKS, { - issuer: "https://accounts.google.com", - audience: process.env.GOOGLE_CLIENT_ID, - }); - - return payload; - } catch (e) { - console.error(e); + claims = jose.decodeJwt(idToken); + } catch { return null; } -}; -/** The verified ID token of the session's user; throws UnauthorizedError otherwise. */ -export const verifySession = async (req: Request) => { - const idToken = req.session?.id_token; - if (!idToken) throw new UnauthorizedError(); + // Sessions created before `authenticatedAt` existed fall back to the + // token's issue time, which is when the user actually signed in. + const authenticatedAt: unknown = + session?.authenticatedAt ?? (claims.iat && claims.iat * 1000); + if (typeof authenticatedAt !== "number") return null; + if (Date.now() - authenticatedAt > SESSION_ABSOLUTE_MAX_AGE_MS) return null; - const payload = await verifyToken(idToken); - if (!payload) throw new UnauthorizedError(); - if (!payload.exp) throw new UnauthorizedError(); + // A session that has never been touched was last active when it was made. + const lastActiveAt: unknown = session?.lastActiveAt ?? authenticatedAt; + if (typeof lastActiveAt !== "number") return null; + if (Date.now() - lastActiveAt > SESSION_IDLE_MAX_AGE_MS) return null; - if (new Date(payload.exp * 1000) < new Date()) { - throw new UnauthorizedError(); - } + return claims; +} + +/** The ID token claims of the session's user; throws UnauthorizedError otherwise. */ +export const verifySession = async (req: Request) => { + const payload = getActiveSession(req.session); + if (!payload) throw new UnauthorizedError(); - const email = (payload as { email?: string }).email; - if (!isIdentityAllowed(email)) { + if (!isIdentityAllowed(payload.email)) { throw new UnauthorizedError("Account is not in the allowlist", "account_not_allowed"); } @@ -61,6 +95,16 @@ export const verifySession = async (req: Request) => { export const authenticated = async (req: Request, res: Response, next: NextFunction) => { await verifySession(req); + + // Roll the idle timeout while the session is in use. + const lastActiveAt = req.session!.lastActiveAt; + if ( + typeof lastActiveAt !== "number" || + Date.now() - lastActiveAt > SESSION_TOUCH_INTERVAL_MS + ) { + req.session!.lastActiveAt = Date.now(); + } + next(); }; diff --git a/src/index.ts b/src/index.ts index 5d677e9..75fa37f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,7 +11,7 @@ import * as Webrtc from "./webrtc"; import * as Releases from "./releases"; import { HttpError } from "./errors"; -import { authenticated, bearerToken } from "./auth"; +import { authenticated, bearerToken, SESSION_IDLE_MAX_AGE_MS } from "./auth"; import { prisma } from "./db"; import { baseUrl, bucketName, s3Client } from "./s3"; import { createReleaseSyncRunner, scheduleReleaseSync } from "./release-sync"; @@ -78,7 +78,7 @@ export const cookieSessionMiddleware = cookieSession({ keys: [process.env.COOKIE_SECRET], secure: process.env.NODE_ENV === "production", sameSite: "strict", - maxAge: 24 * 60 * 60 * 1000, // 24 hours + maxAge: SESSION_IDLE_MAX_AGE_MS, // 24 hours, also enforced in getActiveSession }); app.use(cookieSessionMiddleware); diff --git a/src/oidc.ts b/src/oidc.ts index 7908e76..cabf10d 100644 --- a/src/oidc.ts +++ b/src/oidc.ts @@ -99,6 +99,8 @@ export const Callback = async (req: express.Request, res: express.Response) => { } req.session!.id_token = tokenSet.id_token; + req.session!.authenticatedAt = Date.now(); + req.session!.lastActiveAt = Date.now(); await prisma.user.upsert({ where: { googleId: tokenClaims.sub }, diff --git a/src/webrtc-signaling.ts b/src/webrtc-signaling.ts index 49ef4d2..76f88a7 100644 --- a/src/webrtc-signaling.ts +++ b/src/webrtc-signaling.ts @@ -1,13 +1,13 @@ // src/webrtc.ts import { MessageEvent, WebSocket, WebSocketServer } from "ws"; -import * as jose from "jose"; import { prisma } from "./db"; import { IncomingMessage } from "http"; import { Socket } from "node:net"; import { Device } from "@prisma/client"; import { Server, ServerResponse } from "node:http"; import { cookieSessionMiddleware } from "."; +import { getActiveSession } from "./auth"; import { effectiveSku, normalizeSku } from "./skus"; export interface DeviceConnection { @@ -260,15 +260,16 @@ async function handleClientSocketRequest( // Authenticate the client connection async function authenticateClientRequest(req: Request & { session: any }) { const session = req.session; - const token = session?.id_token; + const claims = getActiveSession(session); - if (!token) { - console.log("[Client] No authentication token."); + if (!claims) { + console.log("[Client] No active session."); return { deviceId: null }; } + const token: string = session.id_token; try { - const { sub } = jose.decodeJwt(token); + const { sub } = claims; const url = new URL(req.url || "", "http://localhost"); const deviceId = url.searchParams.get("id"); diff --git a/test/auth.test.ts b/test/auth.test.ts index d324c3c..4d47f6f 100644 --- a/test/auth.test.ts +++ b/test/auth.test.ts @@ -1,7 +1,16 @@ import type { Request, Response } from "express"; import { describe, expect, it, vi } from "vitest"; -import { bearerToken } from "../src/auth"; +import * as jose from "jose"; + +import { + authenticated, + bearerToken, + getActiveSession, + SESSION_ABSOLUTE_MAX_AGE_MS, + SESSION_IDLE_MAX_AGE_MS, + SESSION_TOUCH_INTERVAL_MS, +} from "../src/auth"; import { UnauthorizedError } from "../src/errors"; describe("bearerToken", () => { @@ -33,3 +42,172 @@ describe("bearerToken", () => { expect(next).not.toHaveBeenCalled(); }); }); + +const HOUR = 60 * 60 * 1000; +const DAY = 24 * HOUR; + +// Builds an ID token like the one openid-client stores in the session after +// sign-in. The signature is irrelevant here: sessions are trusted because the +// cookie is signed with COOKIE_SECRET, not because the token is re-verified. +async function idToken(opts: { issuedAgoMs: number; ttlMs?: number; email?: string }) { + const now = Date.now(); + const iat = Math.floor((now - opts.issuedAgoMs) / 1000); + const exp = Math.floor((now - opts.issuedAgoMs + (opts.ttlMs ?? HOUR)) / 1000); + return new jose.SignJWT({ email: opts.email ?? "user@example.com", sub: "123" }) + .setProtectedHeader({ alg: "HS256" }) + .setIssuer("https://accounts.google.com") + .setIssuedAt(iat) + .setExpirationTime(exp) + .sign(new TextEncoder().encode("test-key")); +} + +function runMiddleware(session: Record | null) { + const req = { session } as unknown as Request; + const res = {} as Response; + const next = vi.fn(); + return { req, run: () => authenticated(req, res, next), next }; +} + +describe("getActiveSession", () => { + it("returns null without a session or token", () => { + expect(getActiveSession(null)).toBeNull(); + expect(getActiveSession(undefined)).toBeNull(); + expect(getActiveSession({} as any)).toBeNull(); + expect(getActiveSession({ id_token: "not-a-jwt" } as any)).toBeNull(); + }); + + it("stays active after the ID token's own expiry has passed", async () => { + // Google ID tokens live ~1h; that is not the session lifetime. + const token = await idToken({ issuedAgoMs: 5 * HOUR }); + const active = getActiveSession({ + id_token: token, + authenticatedAt: Date.now() - 5 * HOUR, + } as any); + expect(active?.email).toBe("user@example.com"); + }); + + it("expires once the absolute lifetime is exceeded, even when in constant use", async () => { + const token = await idToken({ issuedAgoMs: 1 * HOUR }); + const authenticatedAt = Date.now() - SESSION_ABSOLUTE_MAX_AGE_MS - DAY; + expect( + getActiveSession({ id_token: token, authenticatedAt, lastActiveAt: Date.now() } as any), + ).toBeNull(); + }); + + it("expires after the idle timeout, whatever the cookie's own expiry says", async () => { + const token = await idToken({ issuedAgoMs: 3 * DAY }); + const authenticatedAt = Date.now() - 3 * DAY; + + // In use an hour ago: still active three days after sign-in. + expect( + getActiveSession({ + id_token: token, + authenticatedAt, + lastActiveAt: Date.now() - HOUR, + } as any), + ).not.toBeNull(); + + // A copied cookie replayed after a day of silence is refused. + expect( + getActiveSession({ + id_token: token, + authenticatedAt, + lastActiveAt: Date.now() - SESSION_IDLE_MAX_AGE_MS - 1, + } as any), + ).toBeNull(); + }); + + it("treats a session that was never touched as last active at sign-in", async () => { + const token = await idToken({ issuedAgoMs: 2 * DAY }); + expect( + getActiveSession({ id_token: token, authenticatedAt: Date.now() - 2 * HOUR } as any), + ).not.toBeNull(); + expect( + getActiveSession({ id_token: token, authenticatedAt: Date.now() - 2 * DAY } as any), + ).toBeNull(); + }); + + it("falls back to the token's iat for sessions created before authenticatedAt", async () => { + // Such a session has no timestamps at all, so both limits run from iat. + const recent = await idToken({ issuedAgoMs: 2 * HOUR }); + expect(getActiveSession({ id_token: recent } as any)).not.toBeNull(); + + const idle = await idToken({ issuedAgoMs: 2 * DAY }); + expect(getActiveSession({ id_token: idle } as any)).toBeNull(); + + const kept = await idToken({ issuedAgoMs: 2 * DAY }); + expect(getActiveSession({ id_token: kept, lastActiveAt: Date.now() } as any)).not.toBeNull(); + + const ancient = await idToken({ issuedAgoMs: 40 * DAY }); + expect(getActiveSession({ id_token: ancient, lastActiveAt: Date.now() } as any)).toBeNull(); + }); +}); + +describe("authenticated middleware", () => { + it("rejects requests without a session", async () => { + const { run, next } = runMiddleware(null); + await expect(run()).rejects.toBeInstanceOf(UnauthorizedError); + expect(next).not.toHaveBeenCalled(); + }); + + it("accepts a session whose ID token expired hours ago", async () => { + const token = await idToken({ issuedAgoMs: 6 * HOUR }); + const { run, next } = runMiddleware({ + id_token: token, + authenticatedAt: Date.now() - 6 * HOUR, + }); + await run(); + expect(next).toHaveBeenCalledOnce(); + }); + + it("rejects an idle session without reviving it", async () => { + const token = await idToken({ issuedAgoMs: 2 * DAY }); + const stale = Date.now() - SESSION_IDLE_MAX_AGE_MS - 1; + const session: Record = { + id_token: token, + authenticatedAt: Date.now() - 2 * DAY, + lastActiveAt: stale, + }; + const { run, next } = runMiddleware(session); + await expect(run()).rejects.toBeInstanceOf(UnauthorizedError); + expect(next).not.toHaveBeenCalled(); + expect(session.lastActiveAt).toBe(stale); + }); + + it("rejects a session past the absolute lifetime", async () => { + const token = await idToken({ issuedAgoMs: 0 }); + const { run, next } = runMiddleware({ + id_token: token, + authenticatedAt: Date.now() - SESSION_ABSOLUTE_MAX_AGE_MS - 1, + }); + await expect(run()).rejects.toBeInstanceOf(UnauthorizedError); + expect(next).not.toHaveBeenCalled(); + }); + + it("touches lastActiveAt so the cookie's idle timeout rolls, but not on every request", async () => { + const token = await idToken({ issuedAgoMs: 0 }); + const session: Record = { + id_token: token, + authenticatedAt: Date.now(), + }; + + const first = runMiddleware(session); + await first.run(); + const touched = session.lastActiveAt as number; + expect(typeof touched).toBe("number"); + + // Within the touch interval the session is left untouched, so + // cookie-session doesn't re-send the cookie on every request. + const second = runMiddleware(session); + await second.run(); + expect(session.lastActiveAt).toBe(touched); + + // Once the interval has elapsed, the next request touches it again. + const stale = Date.now() - SESSION_TOUCH_INTERVAL_MS - 1; + session.lastActiveAt = stale; + const before = Date.now(); + const third = runMiddleware(session); + await third.run(); + expect(session.lastActiveAt as number).toBeGreaterThanOrEqual(before); + }); +});