commit
updates
diff --git a/.env.example b/.env.example
index 0cbe5c2..522d697 100644
--- a/.env.example
+++ b/.env.example
@@ -1,8 +1,8 @@
# --- dough-git configuration -------------------------------------------------
# Copy to `.env` and fill in. Read at startup (see src/config.ts).
# Repo visibility is a filesystem marker plus a collaborator table, git auth is
-# per-user tokens minted in the browser, and browser sessions are stateless
-# signed cookies over a small SQLite user directory.
+# per-user tokens minted in the browser, and browser sessions are stored in the
+# same SQLite database and re-checked against the SSO every ten minutes.
# Where your bare repositories live. Each repo is a `<name>.git` directory here.
MINIGIT_REPOS_ROOT=/srv/git
@@ -90,24 +90,31 @@ MINIGIT_TRASH_DAYS=30
# This means the server makes outbound HTTPS requests to discord.com,
# github.com and codeberg.org — and, by host allow-list, nowhere else.
-# --- PocketID (OIDC) ---------------------------------------------------------
-# Only needed to *view private repos in a browser*. Register this callback URL
-# in PocketID: <MINIGIT_BASE_URL>/auth/callback
-# OIDC_ISSUER must EXACTLY match the `iss` PocketID puts on the callback (the
-# app logs the discovered issuer at boot so you can compare).
-OIDC_ISSUER=https://id.example.com
+# --- Single sign-on (Doughmination SSO / auth-server) ---------------------------
+# Only needed to sign in to the web UI (private repos, tokens, settings).
+#
+# In the SSO admin (/admin/clients) add a *confidential* application with:
+# Redirect URI: <MINIGIT_BASE_URL>/auth/callback
+# Post-logout redirect URI: <MINIGIT_BASE_URL>/
+# then copy its client id and the secret it shows you once.
+#
+# To limit who can sign in, tick groups under "Who can use it" on that
+# application. Everyone on the SSO is let in otherwise. Signed-in sessions are
+# re-checked every ten minutes, so disabling an account or taking it out of
+# those groups signs it out of here too. (Git tokens minted at /tokens are not
+# tied to the SSO; revoke those here.)
+OIDC_ISSUER=https://auth.doughmination.gay
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
-# Token-endpoint auth method. Leave blank for the default. Set to "post" if your
-# PocketID client uses client_secret_post, or "none" for a public (PKCE-only)
-# client with no secret.
-OIDC_TOKEN_AUTH=
+# Moving from PocketID gives everyone a new `sub`. While this is "true", the
+# first sign-in from the SSO takes over the PocketID-era account with the same
+# namespace (SSO username → slug), keeping its repos, tokens and collaborator
+# grants. Each old account can only be taken over once. Set it to "false" once
+# everyone has signed in again, so a new SSO username can never claim a
+# leftover namespace.
+OIDC_ADOPT_LEGACY_USERS=true
-# Signs session cookies. Generate with: openssl rand -hex 32
+# Signs the short-lived cookie that carries a sign-in attempt through the SSO
+# redirect. Generate with: openssl rand -hex 32
SESSION_SECRET=
-
-# There is no allow-list. Anyone who can sign in to PocketID can sign in here:
-# PocketID is the guest list, and a second one only ever drifts out of step with
-# it. Signing in earns a namespace of that person's own — not access to anybody
-# else's. Restrict who may log in by restricting the PocketID client instead.
diff --git a/compose.yml b/compose.yml
index 30d0abb..df49e44 100644
--- a/compose.yml
+++ b/compose.yml
@@ -4,7 +4,7 @@ services:
container_name: dough-git
restart: unless-stopped
- # Secrets + PocketID config live in .env (see .env.example).
+ # Secrets + SSO config live in .env (see .env.example).
env_file:
- .env
diff --git a/src/auth.ts b/src/auth.ts
index b978983..f4ecc72 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -7,6 +7,13 @@ import * as oidc from "openid-client";
import { config, oidcEnabled } from "./config.ts";
import { verifyDbToken } from "./tokens.ts";
import { rememberUser, findUserBySub } from "./users.ts";
+import {
+ createSession,
+ deleteSessionRow,
+ findSession,
+ revalidate,
+ type RefreshOutcome,
+} from "./sessions.ts";
import { ownerSlug } from "./git.ts";
function b64url(input: Buffer | string): string {
@@ -61,34 +68,11 @@ export function sessionSlug(user: SessionUser): string {
return user.slug || ownerSlug(user.username ?? user.name ?? "user");
}
-const SESSION_TTL = 60 * 60 * 24 * 30;
const OAUTH_TTL = 60 * 10;
export const SESSION_COOKIE = "mg_session";
export const OAUTH_COOKIE = "mg_oauth";
-export function makeSessionCookie(user: SessionUser): string {
- return signValue(user, SESSION_TTL);
-}
-
-export function readSession(token: string | undefined): SessionUser | null {
- return verifyValue<SessionUser & { exp: number }>(token);
-}
-
-export function currentUser(session: SessionUser): SessionUser | null {
- const row = findUserBySub(session.sub);
- if (!row) return null;
-
- return {
- sub: row.sub,
- email: session.email,
- name: row.name,
- username: row.username,
- slug: row.slug,
- picture: row.picture,
- };
-}
-
export function parseBasicAuth(
header: string | undefined,
): [string, string] | null {
@@ -142,33 +126,24 @@ export function gitActor(auth: GitAuth): string | null {
return auth.kind === "user" ? auth.owner : null;
}
-let discovered: oidc.Configuration | null = null;
+// --- OIDC (Doughmination SSO) ---------------------------------------------------
-async function oidcConfig(): Promise<oidc.Configuration> {
- if (!discovered) {
- const { issuer, clientId, clientSecret, tokenAuth } = config.oidc;
-
- let clientAuth: oidc.ClientAuth | undefined;
- switch (tokenAuth) {
- case "post":
- clientAuth = oidc.ClientSecretPost(clientSecret);
- break;
- case "basic":
- clientAuth = oidc.ClientSecretBasic(clientSecret);
- break;
- case "none":
- clientAuth = oidc.None();
- break;
- default:
- clientAuth = undefined;
- }
+let discovered: Promise<oidc.Configuration> | null = null;
- discovered = await oidc.discovery(
- new URL(issuer),
- clientId,
- clientAuth ? undefined : clientSecret,
- clientAuth,
- );
+function oidcConfig(): Promise<oidc.Configuration> {
+ if (!discovered) {
+ const { issuer, clientId, clientSecret } = config.oidc;
+ const insecure = issuer.startsWith("http://");
+ discovered = oidc
+ .discovery(new URL(issuer), clientId, clientSecret, undefined, {
+ // Plain http is only ever a local auth-server during development.
+ execute: insecure ? [oidc.allowInsecureRequests] : [],
+ })
+ .catch((err) => {
+ // Don't cache a failed discovery; try again on the next request.
+ discovered = null;
+ throw err;
+ });
}
return discovered;
}
@@ -178,6 +153,10 @@ export async function oidcIssuer(): Promise<string> {
return cfg.serverMetadata().issuer;
}
+export function accountUrl(): string | null {
+ return config.oidc.issuer ? `${config.oidc.issuer}/account` : null;
+}
+
export interface AuthStart {
redirectUrl: string;
txCookie: string;
@@ -188,32 +167,55 @@ export async function startLogin(): Promise<AuthStart> {
const verifier = oidc.randomPKCECodeVerifier();
const challenge = await oidc.calculatePKCECodeChallenge(verifier);
const state = oidc.randomState();
+ const nonce = oidc.randomNonce();
const url = oidc.buildAuthorizationUrl(cfg, {
redirect_uri: `${config.baseUrl}/auth/callback`,
- scope: "openid profile email",
+ // offline_access gets a refresh token, which is how a session keeps
+ // checking that the SSO still vouches for the account.
+ scope: "openid profile email offline_access",
code_challenge: challenge,
code_challenge_method: "S256",
state,
+ nonce,
});
return {
redirectUrl: url.href,
- txCookie: signValue({ verifier, state }, OAUTH_TTL),
+ txCookie: signValue({ verifier, state, nonce }, OAUTH_TTL),
};
}
+type Claims = Record<string, unknown>;
+
+function str(value: unknown): string | null {
+ return typeof value === "string" ? value : null;
+}
+
+function rememberFromClaims(claims: Claims) {
+ return rememberUser({
+ sub: String(claims.sub),
+ username: str(claims.preferred_username),
+ name: str(claims.name),
+ picture: str(claims.picture),
+ issuer: config.oidc.issuer,
+ adoptLegacy: config.oidc.adoptLegacyUsers,
+ });
+}
+
+/** Completes the code flow. Returns the new session cookie value, or null. */
export async function finishLogin(
currentUrl: string,
txToken: string | undefined,
-): Promise<SessionUser | null> {
- const tx = verifyValue<{ verifier: string; state: string }>(txToken);
+): Promise<string | null> {
+ const tx = verifyValue<{ verifier: string; state: string; nonce: string }>(txToken);
if (!tx) return null;
const cfg = await oidcConfig();
const tokens = await oidc.authorizationCodeGrant(cfg, new URL(currentUrl), {
pkceCodeVerifier: tx.verifier,
expectedState: tx.state,
+ expectedNonce: tx.nonce,
});
const claims = tokens.claims();
@@ -222,19 +224,93 @@ export async function finishLogin(
return null;
}
- const claimed = {
+ rememberFromClaims(claims);
+ return createSession({
sub: String(claims.sub),
- email: typeof claims.email === "string" ? claims.email : null,
- name: typeof claims.name === "string" ? claims.name : null,
- username:
- typeof claims.preferred_username === "string"
- ? claims.preferred_username
- : null,
- picture: typeof claims.picture === "string" ? claims.picture : null,
+ email: str(claims.email),
+ refreshToken: tokens.refresh_token ?? null,
+ idToken: tokens.id_token ?? null,
+ });
+}
+
+async function refreshWithSso(refreshToken: string): Promise<RefreshOutcome> {
+ try {
+ const cfg = await oidcConfig();
+ const tokens = await oidc.refreshTokenGrant(cfg, refreshToken);
+ const claims = tokens.claims();
+ // Names, avatars and usernames edited in the SSO show up here without a
+ // fresh sign-in. The namespace (slug) never changes.
+ if (claims?.sub) rememberFromClaims(claims);
+ return {
+ kind: "ok",
+ sub: claims?.sub ? String(claims.sub) : null,
+ email: claims ? str(claims.email) : null,
+ refreshToken: tokens.refresh_token ?? null,
+ idToken: tokens.id_token ?? null,
+ };
+ } catch (err) {
+ if (err instanceof oidc.ResponseBodyError && err.error === "invalid_grant") {
+ return { kind: "revoked" };
+ }
+ console.warn("[auth] could not reach the SSO to re-check a session:", err instanceof Error ? err.message : err);
+ return { kind: "unavailable" };
+ }
+}
+
+/** Resolves the session cookie to a user, re-checking with the SSO when due. */
+export async function sessionUser(token: string | undefined): Promise<SessionUser | null> {
+ const found = findSession(token);
+ if (!found) return null;
+
+ const session = await revalidate(found, refreshWithSso);
+ if (!session) return null;
+
+ const row = findUserBySub(session.sub);
+ if (!row) {
+ deleteSessionRow(session.id_hash);
+ return null;
+ }
+
+ return {
+ sub: row.sub,
+ email: session.email,
+ name: row.name,
+ username: row.username,
+ slug: row.slug,
+ picture: row.picture,
};
+}
+
+/**
+ * Ends the session here, revokes its refresh token, and returns where to send
+ * the browser: the SSO's logout (so the SSO session ends too), or home.
+ */
+export async function logout(token: string | undefined): Promise<string> {
+ const session = findSession(token);
+ const home = `${config.baseUrl}/`;
+ if (!session) return home;
+ deleteSessionRow(session.id_hash);
- const row = rememberUser(claimed);
- return { ...claimed, slug: row.slug };
+ if (!oidcEnabled) return home;
+ try {
+ const cfg = await oidcConfig();
+ if (session.refresh_token) {
+ await oidc.tokenRevocation(cfg, session.refresh_token).catch((err) => {
+ console.warn("[auth] refresh token revocation failed:", err instanceof Error ? err.message : err);
+ });
+ }
+ if (!cfg.serverMetadata().end_session_endpoint) return home;
+ const params: Record<string, string> = {
+ post_logout_redirect_uri: home,
+ client_id: config.oidc.clientId,
+ };
+ // With the id_token as proof, the SSO signs out without asking again.
+ if (session.id_token) params.id_token_hint = session.id_token;
+ return oidc.buildEndSessionUrl(cfg, params).href;
+ } catch (err) {
+ console.warn("[auth] SSO logout unavailable:", err instanceof Error ? err.message : err);
+ return home;
+ }
}
export { oidcEnabled };
diff --git a/src/config.ts b/src/config.ts
index 08f891a..3c1ac47 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -38,10 +38,10 @@ export const config = {
trashDays: Math.max(0, Number(optional("MINIGIT_TRASH_DAYS", "30")) || 0),
oidc: {
- issuer: optional("OIDC_ISSUER", ""),
+ issuer: optional("OIDC_ISSUER", "").replace(/\/+$/, ""),
clientId: optional("OIDC_CLIENT_ID", ""),
clientSecret: optional("OIDC_CLIENT_SECRET", ""),
- tokenAuth: optional("OIDC_TOKEN_AUTH", ""),
+ adoptLegacyUsers: optional("OIDC_ADOPT_LEGACY_USERS", "true") !== "false",
},
sessionSecret: optional("SESSION_SECRET", "dev-insecure-secret-change-me"),
diff --git a/src/server.ts b/src/server.ts
index bc7edb7..00f85f4 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -12,16 +12,16 @@ import { config, oidcEnabled } from "./config.ts";
import {
SESSION_COOKIE,
OAUTH_COOKIE,
- readSession,
- currentUser,
- makeSessionCookie,
+ sessionUser,
startLogin,
finishLogin,
+ logout,
oidcIssuer,
authenticateGit,
gitActor,
type SessionUser,
} from "./auth.ts";
+import { SESSION_TTL, purgeExpiredSessions } from "./sessions.ts";
import { listTokens, createToken, revokeToken } from "./tokens.ts";
import { findUserBySlug } from "./users.ts";
import {
@@ -107,11 +107,23 @@ const SITE_ORIGIN = new URL(config.baseUrl).origin;
const GIT_RPC = /\/(?:git-upload-pack|git-receive-pack)$/;
app.use("*", async (c, next) => {
- const session = readSession(getCookie(c, SESSION_COOKIE));
- c.set("user", session && "sub" in session ? currentUser(session) : null);
+ // Static files and git transport never look at the browser session, and
+ // skipping them keeps SSO re-checks off those hot paths.
+ if (c.req.path.startsWith("/static/") || GIT_RPC.test(c.req.path) || c.req.path.endsWith("/info/refs")) {
+ c.set("user", null);
+ return next();
+ }
+ const token = getCookie(c, SESSION_COOKIE);
+ const user = await sessionUser(token);
+ if (token && !user) deleteCookie(c, SESSION_COOKIE, { path: "/" });
+ c.set("user", user);
await next();
});
+// Logging out POSTs to /auth/logout, which redirects on to the SSO's logout,
+// and browsers check form-action against that redirect too.
+const SSO_ORIGIN = config.oidc.issuer ? new URL(config.oidc.issuer).origin : "";
+
const CSP = [
"default-src 'self'",
"script-src 'self'",
@@ -119,7 +131,7 @@ const CSP = [
"img-src 'self' data: https:",
`font-src 'self' ${FONT_ORIGIN}`,
"connect-src 'self'",
- "form-action 'self'",
+ `form-action 'self'${SSO_ORIGIN ? ` ${SSO_ORIGIN}` : ""}`,
"frame-ancestors 'none'",
"base-uri 'none'",
"object-src 'none'",
@@ -203,7 +215,7 @@ app.get("/auth/login", async (c) => {
return c.html(
view.messagePage({
title: "login unavailable",
- message: "PocketID (OIDC) is not configured on this instance.",
+ message: "Single sign-on (OIDC) is not configured on this instance.",
user: null,
}),
501,
@@ -240,9 +252,9 @@ app.get("/auth/callback", async (c) => {
const currentUrl = `${config.baseUrl}/auth/callback${new URL(c.req.url).search}`;
- let user = null;
+ let session: string | null = null;
try {
- user = await finishLogin(currentUrl, tx);
+ session = await finishLogin(currentUrl, tx);
} catch (err) {
const e = err as {
error?: string;
@@ -256,31 +268,39 @@ app.get("/auth/callback", async (c) => {
err instanceof Error ? e.message : err,
);
}
- if (!user) {
+ if (!session) {
return c.html(
view.messagePage({
title: "login failed",
- message: "Could not complete sign-in, or your account is not allowed.",
+ message:
+ idpError === "access_denied"
+ ? "Your SSO account isn't allowed to use this instance. Ask an SSO admin to add you to its allowed groups."
+ : "Could not complete sign-in. Please try again.",
user: null,
}),
403,
);
}
- setCookie(c, SESSION_COOKIE, makeSessionCookie(user), {
+ setCookie(c, SESSION_COOKIE, session, {
httpOnly: true,
secure: config.baseUrl.startsWith("https"),
sameSite: "Lax",
path: "/",
- maxAge: 60 * 60 * 24 * 30,
+ maxAge: SESSION_TTL,
});
return c.redirect("/");
});
-app.get("/auth/logout", (c) => {
+// POST so a stray link or image can't sign anyone out; the same-origin check
+// above covers the form.
+app.post("/auth/logout", async (c) => {
+ const target = await logout(getCookie(c, SESSION_COOKIE));
deleteCookie(c, SESSION_COOKIE, { path: "/" });
- return c.redirect("/");
+ return c.redirect(target);
});
+app.get("/auth/logout", (c) => c.redirect("/"));
+
app.get("/settings", (c) => {
const user = c.get("user");
if (!user) return c.redirect("/auth/login");
@@ -799,7 +819,7 @@ app.post("/:owner/:name/collaborators", async (c) => {
title: "no such user",
message:
`Nobody on this instance goes by "${slug}". They have to sign in ` +
- `with PocketID once before they can be added.`,
+ `to this instance once before they can be added.`,
user: c.get("user"),
}),
400,
@@ -1003,6 +1023,15 @@ app.post("/:owner/:name/mirrors/check", async (c) => {
const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
+function sweepSessions(): void {
+ try {
+ const purged = purgeExpiredSessions();
+ if (purged) console.log(`[auth] purged ${purged} expired sessions`);
+ } catch (err) {
+ console.warn("[auth] session sweep failed:", err);
+ }
+}
+
async function sweepTrash(): Promise<void> {
try {
const purged = await purgeAllExpired();
@@ -1030,7 +1059,7 @@ serve(
console.log(
` trash: ${config.trashDays > 0 ? `${config.trashDays}d, swept every 6h` : "kept forever"}`,
);
- console.log(` logins: any PocketID account`);
+ console.log(` logins: accounts on ${config.oidc.issuer || "(no issuer)"} (limit with the client's allowed groups)`);
if (oidcEnabled) {
try {
const iss = await oidcIssuer();
@@ -1045,6 +1074,10 @@ serve(
}
void sweepTrash();
- setInterval(() => void sweepTrash(), SWEEP_INTERVAL_MS).unref();
+ sweepSessions();
+ setInterval(() => {
+ void sweepTrash();
+ sweepSessions();
+ }, SWEEP_INTERVAL_MS).unref();
},
);
diff --git a/src/sessions.ts b/src/sessions.ts
new file mode 100644
index 0000000..864de5c
--- /dev/null
+++ b/src/sessions.ts
@@ -0,0 +1,186 @@
+/* src/sessions.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+import { createHash, randomBytes } from "node:crypto";
+import { db, now } from "./db.ts";
+
+// Browser sessions live here rather than in a signed cookie so they can be
+// ended from the server side: on logout, and when the SSO stops vouching for
+// the account (disabled, removed from the app's allowed groups, signed out
+// everywhere).
+db.exec(`
+ CREATE TABLE IF NOT EXISTS sessions (
+ id_hash TEXT PRIMARY KEY,
+ sub TEXT NOT NULL,
+ email TEXT,
+ refresh_token TEXT,
+ id_token TEXT,
+ created_at INTEGER NOT NULL,
+ verified_at INTEGER NOT NULL,
+ checked_at INTEGER NOT NULL,
+ expires_at INTEGER NOT NULL
+ );
+`);
+
+db.exec("CREATE INDEX IF NOT EXISTS sessions_sub ON sessions (sub)");
+
+/** Hard cap on a session, however often it is refreshed. */
+export const SESSION_TTL = 60 * 60 * 24 * 30;
+/** How stale the SSO's last word on a session may get before asking again. */
+export const RECHECK_AFTER = 60 * 10;
+/** How long to keep people signed in while the SSO can't be reached. */
+export const OUTAGE_GRACE = 60 * 60;
+/** Minimum gap between retries while the SSO is unreachable. */
+const RETRY_AFTER = 60;
+/** Sessions without a refresh token can't be re-checked, so they end sooner. */
+export const UNCHECKED_TTL = 60 * 60 * 24;
+
+export interface SessionRow {
+ id_hash: string;
+ sub: string;
+ email: string | null;
+ refresh_token: string | null;
+ id_token: string | null;
+ created_at: number;
+ verified_at: number;
+ checked_at: number;
+ expires_at: number;
+}
+
+function hashId(token: string): string {
+ return createHash("sha256").update(token).digest("hex");
+}
+
+export interface NewSession {
+ sub: string;
+ email: string | null;
+ refreshToken: string | null;
+ idToken: string | null;
+}
+
+/** Returns the cookie value. Only its hash is stored. */
+export function createSession(input: NewSession): string {
+ const token = randomBytes(32).toString("base64url");
+ const ts = now();
+ db.prepare(
+ `INSERT INTO sessions (id_hash, sub, email, refresh_token, id_token, created_at, verified_at, checked_at, expires_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ hashId(token),
+ input.sub,
+ input.email,
+ input.refreshToken,
+ input.idToken,
+ ts,
+ ts,
+ ts,
+ ts + (input.refreshToken ? SESSION_TTL : UNCHECKED_TTL),
+ );
+ return token;
+}
+
+export function findSession(token: string | undefined): SessionRow | null {
+ if (!token) return null;
+ const row = (db
+ .prepare("SELECT * FROM sessions WHERE id_hash = ?")
+ .get(hashId(token)) as unknown as SessionRow) ?? null;
+ if (!row) return null;
+ if (row.expires_at <= now()) {
+ deleteSessionRow(row.id_hash);
+ return null;
+ }
+ return row;
+}
+
+export function deleteSessionRow(idHash: string): void {
+ db.prepare("DELETE FROM sessions WHERE id_hash = ?").run(idHash);
+}
+
+export function purgeExpiredSessions(): number {
+ const result = db.prepare("DELETE FROM sessions WHERE expires_at <= ?").run(now());
+ return Number(result.changes);
+}
+
+export type RefreshOutcome =
+ | {
+ kind: "ok";
+ sub: string | null;
+ email: string | null;
+ refreshToken: string | null;
+ idToken: string | null;
+ }
+ /** The SSO refused: the session must end. */
+ | { kind: "revoked" }
+ /** The SSO couldn't be asked (network, outage). */
+ | { kind: "unavailable" };
+
+export type Refresher = (refreshToken: string) => Promise<RefreshOutcome>;
+
+const inflight = new Map<string, Promise<SessionRow | null>>();
+
+/**
+ * Makes sure the SSO still vouches for a session, asking at most every
+ * RECHECK_AFTER seconds. Refresh tokens rotate on every use and replaying one
+ * shuts the whole grant down, so concurrent requests on one session share a
+ * single refresh instead of racing each other with the same token.
+ */
+export function revalidate(row: SessionRow, refresh: Refresher): Promise<SessionRow | null> {
+ const ts = now();
+ if (ts - row.verified_at < RECHECK_AFTER) return Promise.resolve(row);
+
+ if (!row.refresh_token) {
+ // Nothing to check with; expires_at (UNCHECKED_TTL) bounds these.
+ return Promise.resolve(row);
+ }
+
+ const pending = inflight.get(row.id_hash);
+ if (pending) return pending;
+
+ if (ts - row.checked_at < RETRY_AFTER) {
+ // A recent attempt failed to reach the SSO; don't hammer it on every request.
+ return Promise.resolve(ts - row.verified_at > RECHECK_AFTER + OUTAGE_GRACE ? end(row) : row);
+ }
+
+ const task = (async (): Promise<SessionRow | null> => {
+ let outcome: RefreshOutcome;
+ try {
+ outcome = await refresh(row.refresh_token!);
+ } catch {
+ outcome = { kind: "unavailable" };
+ }
+ const at = now();
+
+ if (outcome.kind === "revoked" || (outcome.kind === "ok" && outcome.sub && outcome.sub !== row.sub)) {
+ return end(row);
+ }
+
+ if (outcome.kind === "unavailable") {
+ if (at - row.verified_at > RECHECK_AFTER + OUTAGE_GRACE) return end(row);
+ db.prepare("UPDATE sessions SET checked_at = ? WHERE id_hash = ?").run(at, row.id_hash);
+ return { ...row, checked_at: at };
+ }
+
+ const updated: SessionRow = {
+ ...row,
+ email: outcome.email ?? row.email,
+ refresh_token: outcome.refreshToken ?? row.refresh_token,
+ id_token: outcome.idToken ?? row.id_token,
+ verified_at: at,
+ checked_at: at,
+ };
+ db.prepare(
+ `UPDATE sessions SET email = ?, refresh_token = ?, id_token = ?, verified_at = ?, checked_at = ?
+ WHERE id_hash = ?`,
+ ).run(updated.email, updated.refresh_token, updated.id_token, at, at, row.id_hash);
+ return updated;
+ })().finally(() => inflight.delete(row.id_hash));
+
+ inflight.set(row.id_hash, task);
+ return task;
+}
+
+function end(row: SessionRow): null {
+ deleteSessionRow(row.id_hash);
+ return null;
+}
diff --git a/src/styles/app.css.ts b/src/styles/app.css.ts
index 6d271d2..9a3ecc6 100644
--- a/src/styles/app.css.ts
+++ b/src/styles/app.css.ts
@@ -69,6 +69,26 @@ export const classes = {
color: vars.accent,
}),
+ navForm: style({
+ display: "inline",
+ margin: 0,
+ }),
+
+ // A form button that looks exactly like the nav links beside it.
+ navButton: style({
+ padding: 0,
+ border: 0,
+ background: "none",
+ font: "inherit",
+ selectors: {
+ "&:hover, &:active": {
+ color: vars.accent,
+ background: "none",
+ textDecoration: "underline",
+ },
+ },
+ }),
+
user: style({
display: "flex",
alignItems: "center",
diff --git a/src/users.ts b/src/users.ts
index 3220b36..8495a2a 100644
--- a/src/users.ts
+++ b/src/users.ts
@@ -2,7 +2,7 @@
* LICENCED DASL-1.0 (c) Clove Twilight
*/
-import { db, now } from "./db.ts";
+import { db, now, hasColumn } from "./db.ts";
import { ownerSlug } from "./git.ts";
db.exec(`
@@ -17,12 +17,19 @@ db.exec(`
);
`);
+// Which identity provider the `sub` belongs to. NULL marks accounts created
+// before this column existed, i.e. by the previous provider (PocketID).
+if (!hasColumn("users", "issuer")) {
+ db.exec("ALTER TABLE users ADD COLUMN issuer TEXT");
+}
+
export interface UserRow {
sub: string;
slug: string;
username: string | null;
name: string | null;
picture: string | null;
+ issuer: string | null;
created_at: number;
last_login: number;
}
@@ -63,18 +70,83 @@ export interface RememberInput {
username: string | null;
name: string | null;
picture: string | null;
+ /** The OIDC issuer that vouched for `sub`. */
+ issuer?: string | null;
+ /**
+ * Let a first sign-in take over the pre-migration account whose namespace
+ * matches this username. See adoptLegacyUser.
+ */
+ adoptLegacy?: boolean;
+}
+
+function hasTable(name: string): boolean {
+ return Boolean(
+ db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name),
+ );
+}
+
+/**
+ * Moving identity providers changes every `sub`, but namespaces, tokens and
+ * collaborator grants all hang off the slug. So when someone signs in from the
+ * new provider for the first time, an account left over from the old one
+ * (issuer IS NULL) with the same namespace is re-pointed at their new `sub`
+ * rather than a fresh "name-2" namespace being made.
+ *
+ * Usernames on the new provider are issued by its admins, which is what makes
+ * matching on them acceptable. Each old account can only be adopted once.
+ */
+function adoptLegacyUser(input: RememberInput): UserRow | null {
+ if (!input.username || !input.issuer) return null;
+ const slug = ownerSlug(input.username);
+ const legacy = (db
+ .prepare("SELECT * FROM users WHERE slug = ? AND issuer IS NULL")
+ .get(slug) as unknown as UserRow) ?? null;
+ if (!legacy) return null;
+
+ db.exec("BEGIN");
+ try {
+ db.prepare("UPDATE users SET sub = ?, issuer = ? WHERE sub = ?").run(
+ input.sub,
+ input.issuer,
+ legacy.sub,
+ );
+ if (hasTable("tokens")) {
+ db.prepare("UPDATE tokens SET created_by = ? WHERE created_by = ?").run(
+ input.sub,
+ legacy.sub,
+ );
+ }
+ db.exec("COMMIT");
+ } catch (err) {
+ db.exec("ROLLBACK");
+ throw err;
+ }
+
+ console.warn(
+ `[auth] adopted pre-migration account "${slug}" for ${input.issuer} subject ${input.sub}`,
+ );
+ return { ...legacy, sub: input.sub, issuer: input.issuer };
}
export function rememberUser(input: RememberInput): UserRow {
- const existing = findUserBySub(input.sub);
+ const existing =
+ findUserBySub(input.sub) ?? (input.adoptLegacy ? adoptLegacyUser(input) : null);
const ts = now();
+ const issuer = input.issuer ?? null;
+ const profile = {
+ sub: input.sub,
+ username: input.username,
+ name: input.name,
+ picture: input.picture,
+ };
if (existing) {
db.prepare(
- `UPDATE users SET username = ?, name = ?, picture = ?, last_login = ?
+ `UPDATE users SET username = ?, name = ?, picture = ?, last_login = ?,
+ issuer = COALESCE(?, issuer)
WHERE sub = ?`,
- ).run(input.username, input.name, input.picture, ts, input.sub);
- return { ...existing, ...input, last_login: ts };
+ ).run(input.username, input.name, input.picture, ts, issuer, input.sub);
+ return { ...existing, ...profile, issuer: issuer ?? existing.issuer, last_login: ts };
}
const slug = uniqueSlug(
@@ -82,10 +154,10 @@ export function rememberUser(input: RememberInput): UserRow {
input.sub,
);
db.prepare(
- `INSERT INTO users (sub, slug, username, name, picture, created_at, last_login)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- ).run(input.sub, slug, input.username, input.name, input.picture, ts, ts);
- return { ...input, slug, created_at: ts, last_login: ts };
+ `INSERT INTO users (sub, slug, username, name, picture, issuer, created_at, last_login)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).run(input.sub, slug, input.username, input.name, input.picture, issuer, ts, ts);
+ return { ...profile, slug, issuer, created_at: ts, last_login: ts };
}
export function slugForSub(sub: string | null): string | null {
diff --git a/src/views.ts b/src/views.ts
index 2609379..835cdbc 100644
--- a/src/views.ts
+++ b/src/views.ts
@@ -6,7 +6,7 @@ import { config } from "./config.ts";
import { classes as c } from "./styles/index.ts";
import { icon } from "./icons.ts";
import { escapeHtml, renderMarkdown, plainSummary } from "./markdown.ts";
-import { sessionSlug } from "./auth.ts";
+import { accountUrl, sessionSlug } from "./auth.ts";
import { maskWebhook, mirrorHost, mirrorSlug, MIRROR_KINDS, type MirrorKind } from "./urls.ts";
import type { SessionUser } from "./auth.ts";
import type { CollaboratorRow } from "./access.ts";
@@ -113,7 +113,9 @@ function layout(opts: {
: "";
const settings = opts.user
? `<a class="${c.navLink}" href="/settings">${icon("gear")}settings</a>
- <a class="${c.navLink}" href="/auth/logout">${icon("logout")}logout</a>`
+ <form method="post" action="/auth/logout" class="${c.navForm}">
+ <button type="submit" class="${c.navLink} ${c.navButton}">${icon("logout")}logout</button>
+ </form>`
: `<a class="${c.navLink}" href="/auth/login">${icon("login")}login</a>`;
const description = metaText(opts.description || config.description);
@@ -977,8 +979,10 @@ ${clear}
</form>
<h2 class="${c.sectionTitle}">${icon("user")}account</h2>
- <p class="${c.repoDesc}">Your name and avatar come from PocketID and refresh on each sign-in,
- so there is nothing to edit here. Your owner namespace is
+ <p class="${c.repoDesc}">Your name and avatar come from your SSO account and refresh
+ automatically, so there is nothing to edit here${
+ accountUrl() ? ` — change them on <a href="${esc(accountUrl()!)}">your SSO account page</a>` : ""
+ }. Your owner namespace is
<code>${esc(opts.user ? ownerOf(opts.user) : "")}</code> and never changes.</p>`;
return layout({
diff --git a/test/sessions.test.mjs b/test/sessions.test.mjs
new file mode 100644
index 0000000..e924bf6
--- /dev/null
+++ b/test/sessions.test.mjs
@@ -0,0 +1,175 @@
+/* test/sessions.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const root = mkdtempSync(join(tmpdir(), "dough-sessions-"));
+process.env.MINIGIT_REPOS_ROOT = root;
+process.env.MINIGIT_DB_PATH = join(root, "test.db");
+
+const { db, now } = await import("../src/db.ts");
+const { rememberUser, findUserBySlug } = await import("../src/users.ts");
+const { createToken } = await import("../src/tokens.ts");
+const { authenticateGit } = await import("../src/auth.ts");
+const {
+ createSession,
+ findSession,
+ revalidate,
+ RECHECK_AFTER,
+ OUTAGE_GRACE,
+} = await import("../src/sessions.ts");
+
+let failures = 0;
+function check(label, cond) {
+ console.log(`${cond ? "PASS" : "FAIL"} ${label}`);
+ if (!cond) failures++;
+}
+
+const SSO = "https://auth.example";
+const basic = (user, pass) => `Basic ${Buffer.from(`${user}:${pass}`).toString("base64")}`;
+
+console.log("\n-- moving accounts over from the old provider --");
+
+const legacy = rememberUser({ sub: "pocketid-clove", username: "clove", name: "Clove", picture: null });
+const legacyToken = createToken("laptop", legacy.slug, legacy.sub);
+check("a pre-migration account has no issuer", legacy.issuer === null);
+
+const moved = rememberUser({
+ sub: "sso-clove",
+ username: "clove",
+ name: "Clove T",
+ picture: null,
+ issuer: SSO,
+ adoptLegacy: true,
+});
+check("first SSO sign-in keeps the old namespace", moved.slug === "clove");
+check("and re-points it at the new subject", findUserBySlug("clove")?.sub === "sso-clove");
+check("and records the issuer", findUserBySlug("clove")?.issuer === SSO);
+check("and picks up the new profile", findUserBySlug("clove")?.name === "Clove T");
+check(
+ "tokens minted before the move still authenticate",
+ authenticateGit(basic("clove", legacyToken)).kind === "user",
+);
+const createdBy = db.prepare("SELECT created_by FROM tokens WHERE owner = 'clove'").get();
+check("token authorship follows the new subject", createdBy?.created_by === "sso-clove");
+
+const again = rememberUser({ sub: "sso-clove", username: "clove", name: "Clove T", picture: null, issuer: SSO, adoptLegacy: true });
+check("signing in again changes nothing", again.slug === "clove");
+
+const squatter = rememberUser({ sub: "sso-other", username: "clove", name: "Other", picture: null, issuer: SSO, adoptLegacy: true });
+check("an adopted account can't be taken over a second time", squatter.slug === "clove-2");
+
+rememberUser({ sub: "pocketid-ari", username: "ari", name: "Ari", picture: null });
+const noAdopt = rememberUser({ sub: "sso-ari", username: "ari", name: "Ari", picture: null, issuer: SSO, adoptLegacy: false });
+check("with adoption off, a new namespace is made", noAdopt.slug === "ari-2");
+check("and the old account is left alone", findUserBySlug("ari")?.sub === "pocketid-ari");
+
+console.log("\n-- sessions --");
+
+check("an unknown cookie is no session", findSession("nope") === null);
+check("no cookie is no session", findSession(undefined) === null);
+
+function makeSession(refreshToken = "rt-1") {
+ const token = createSession({ sub: "sso-clove", email: "[email protected]", refreshToken, idToken: "id-1" });
+ return { token, row: findSession(token) };
+}
+
+function age(row, seconds) {
+ db.prepare("UPDATE sessions SET verified_at = ?, checked_at = ? WHERE id_hash = ?").run(
+ now() - seconds,
+ now() - seconds,
+ row.id_hash,
+ );
+ return { ...row, verified_at: now() - seconds, checked_at: now() - seconds };
+}
+
+{
+ const { token, row } = makeSession();
+ check("a new session is found by its cookie", row?.sub === "sso-clove");
+ check("the cookie value itself isn't stored", !JSON.stringify(row).includes(token));
+
+ let calls = 0;
+ const result = await revalidate(row, async () => {
+ calls++;
+ return { kind: "revoked" };
+ });
+ check("a freshly verified session isn't re-checked", calls === 0 && result !== null);
+}
+
+{
+ const { token, row } = makeSession();
+ const stale = age(row, RECHECK_AFTER + 5);
+ let calls = 0;
+ const refresher = async (rt) => {
+ calls++;
+ await new Promise((r) => setTimeout(r, 20));
+ return { kind: "ok", sub: "sso-clove", email: "[email protected]", refreshToken: `${rt}-next`, idToken: "id-2" };
+ };
+ const [a, b, c] = await Promise.all([revalidate(stale, refresher), revalidate(stale, refresher), revalidate(stale, refresher)]);
+ check("concurrent requests share one refresh (rotation-safe)", calls === 1);
+ check("all of them stay signed in", a && b && c);
+ const after = findSession(token);
+ check("the rotated refresh token is stored", after?.refresh_token === "rt-1-next");
+ check("the new id_token is stored", after?.id_token === "id-2");
+ check("email follows the SSO", after?.email === "[email protected]");
+ check("the session is marked verified", now() - after.verified_at < 5);
+}
+
+{
+ const { token, row } = makeSession();
+ const result = await revalidate(age(row, RECHECK_AFTER + 5), async () => ({ kind: "revoked" }));
+ check("a revoked grant ends the session", result === null && findSession(token) === null);
+}
+
+{
+ const { token, row } = makeSession();
+ const result = await revalidate(age(row, RECHECK_AFTER + 5), async () => ({
+ kind: "ok", sub: "someone-else", email: null, refreshToken: "x", idToken: "y",
+ }));
+ check("a refresh for a different subject ends the session", result === null && findSession(token) === null);
+}
+
+{
+ const { token, row } = makeSession();
+ const result = await revalidate(age(row, RECHECK_AFTER + 5), async () => ({ kind: "unavailable" }));
+ check("an SSO outage within the grace period keeps the session", result !== null && findSession(token) !== null);
+
+ let calls = 0;
+ await revalidate(findSession(token), async () => {
+ calls++;
+ return { kind: "unavailable" };
+ });
+ check("and doesn't retry on every request", calls === 0);
+}
+
+{
+ const { token, row } = makeSession();
+ const result = await revalidate(age(row, RECHECK_AFTER + OUTAGE_GRACE + 5), async () => ({ kind: "unavailable" }));
+ check("an outage past the grace period ends the session", result === null && findSession(token) === null);
+}
+
+{
+ const { token, row } = makeSession();
+ const result = await revalidate(age(row, RECHECK_AFTER + 5), async () => {
+ throw new Error("boom");
+ });
+ check("a refresher that throws counts as an outage", result !== null && findSession(token) !== null);
+}
+
+{
+ const { token, row } = makeSession();
+ db.prepare("UPDATE sessions SET expires_at = ? WHERE id_hash = ?").run(now() - 1, row.id_hash);
+ check("an expired session is gone", findSession(token) === null);
+}
+
+db.close();
+rmSync(root, { recursive: true, force: true });
+
+if (failures) {
+ console.error(`\n${failures} check(s) failed`);
+ process.exit(1);
+}
+console.log("\nall session checks passed");