From c8e03fd00f0369f23259d7e2b2d42a67c0a90be0 Mon Sep 17 00:00:00 2001 From: John Coffey Date: Tue, 17 Nov 2026 23:43:01 -0700 Subject: [PATCH 1/2] Sessions that work across replicas: SESSION_BACKEND=cookie A second SessionBackend that seals the whole session into its cookie (s1.., AES-256-GCM under a key derived from APP_SECRET), so any replica can serve a session it never issued and the webmail keeps no state of its own. The default stays the in-memory store with SESSION_FILE. - Cookie mode needs APP_SECRET set explicitly and OAuth sign-in; it refuses to start otherwise. A sealed password couldn't be revoked. - Token renewal and sliding expiry re-issue the cookie, for the account in front and for the other signed-in accounts in the _more cookie. - APP_SECRET_PREVIOUS opens cookies sealed before a rotation and re-seals them under the current key. - The session list can't reach other sessions in this mode: the API says enumerable: false, the Security page shows only this device and hides "Sign out all other sessions". Changing the password still signs out everywhere, through the server. - The _more cookie accepts the new shape and stays under 3,800 bytes. One new string, translated in all ten catalogs. --- .env.example | 20 ++- server/src/accounts.ts | 22 ++- server/src/app.ts | 61 +++++-- server/src/config.ts | 26 +++ server/src/crypto.ts | Bin 1867 -> 2400 bytes server/src/sessions-cookie.test.ts | 96 +++++++++++ server/src/sessions.ts | 172 +++++++++++++++++++- web/src/locales/de.ts | 1 + web/src/locales/es.ts | 1 + web/src/locales/fr.ts | 1 + web/src/locales/ja.ts | 1 + web/src/locales/nl.ts | 1 + web/src/locales/pt-BR.ts | 1 + web/src/locales/ru.ts | 1 + web/src/locales/tr.ts | 1 + web/src/locales/uk.ts | 1 + web/src/locales/zh-Hans.ts | 1 + web/src/views/settings/SecuritySettings.tsx | 7 +- 18 files changed, 391 insertions(+), 23 deletions(-) create mode 100644 server/src/sessions-cookie.test.ts diff --git a/.env.example b/.env.example index 203d514..5052dbb 100644 --- a/.env.example +++ b/.env.example @@ -44,14 +44,30 @@ SESSION_REMEMBER_TTL=2592000 # instance does -- see IMMUTABLE below. SESSION_FILE=./data/sessions.json +# Where sessions live. "memory" (default) is the above: this process, mirrored +# to SESSION_FILE. "cookie" seals each session into its own cookie instead, so +# any replica can serve it and a restart signs nobody out -- what running more +# than one webmail replica (Kubernetes, say) needs. It requires APP_SECRET set +# to the same value on every replica, and OAuth sign-in (OAUTH_CLIENT_SECRET). +# The cost: the Security page can't list or sign out your other sessions; +# changing the password still signs out everywhere. Use PUSH_MODE=relay with +# several replicas: subscribe mode fans out only to tabs on the replica the +# mail server calls back. +# SESSION_BACKEND=memory + +# When rotating APP_SECRET in cookie mode: the old value(s), comma-separated. +# Cookies sealed with them still open and are re-sealed with the new secret +# on their next request. Drop them once SESSION_REMEMBER_TTL has passed. +# APP_SECRET_PREVIOUS= + # Assert that this instance is running as an immutable container: read-only # root filesystem, no durable state of its own. It is checked rather than # taken on trust -- the server refuses to start if SESSION_FILE is set, or if # the filesystem it is installed on turns out to be writable. Off by default. # Running one looks like: # docker run --read-only --tmpfs /tmp -e IMMUTABLE=1 -e SESSION_FILE= ... -# The cost today is that a restart signs everyone out, since there is nowhere -# left to keep the sessions. Removing that cost is what the OAuth work is for. +# In memory mode a restart signs everyone out, since there is nowhere left to +# keep the sessions; SESSION_BACKEND=cookie removes that cost. # IMMUTABLE=1 # Upstream timeouts / limits diff --git a/server/src/accounts.ts b/server/src/accounts.ts index 820a8ae..b9e75f7 100644 --- a/server/src/accounts.ts +++ b/server/src/accounts.ts @@ -17,9 +17,17 @@ import type { UpstreamSession } from "./upstream.js"; export const MAX_ACCOUNTS = 5; -/** A session cookie's shape: `id.secret`, both base64url. Anything else is dropped. */ -const COOKIE_SHAPE = /^[A-Za-z0-9_-]{8,128}\.[A-Za-z0-9_-]{8,256}$/; +/** + * A session cookie's shape: `id.secret`, both base64url, or a cookie-mode + * session `s1..` (sessions.ts). Anything else is dropped. + */ +const COOKIE_SHAPE = /^(?:[A-Za-z0-9_-]{8,128}\.[A-Za-z0-9_-]{8,256}|s1\.[A-Za-z0-9_-]{8}\.[A-Za-z0-9_-]{40,1500})$/; const SEP = "~"; +/** + * Browsers drop a cookie over about 4 KB. Cookie-mode sessions are several + * hundred bytes each, so the list stops before it would pass this. + */ +const MAX_OTHERS_BYTES = 3800; export function parseOthers(value: string | undefined): string[] { if (!value) return []; @@ -35,7 +43,15 @@ export function parseOthers(value: string | undefined): string[] { } export function serializeOthers(cookies: string[]): string { - return cookies.filter((c) => COOKIE_SHAPE.test(c)).slice(0, MAX_ACCOUNTS - 1).join(SEP); + const out: string[] = []; + let bytes = 0; + for (const c of cookies.filter((c) => COOKIE_SHAPE.test(c)).slice(0, MAX_ACCOUNTS - 1)) { + const add = c.length + (out.length ? SEP.length : 0); + if (bytes + add > MAX_OTHERS_BYTES) break; + out.push(c); + bytes += add; + } + return out.join(SEP); } /** diff --git a/server/src/app.ts b/server/src/app.ts index 0a6fb96..458f9b4 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -12,7 +12,7 @@ import { config } from "./config.js"; import { sourceDocument } from "./source.js"; import { fetchPermissions } from "./permissionSchema.js"; import { administrationAllowed, gateAdministration, grantsAdministration } from "./adminGate.js"; -import { SessionStore, accountKey, type SessionBackend, type LiveSession } from "./sessions.js"; +import { CookieSessionStore, SessionStore, accountKey, type SessionBackend, type LiveSession } from "./sessions.js"; import { RateLimiter } from "./ratelimit.js"; import { rateLimitKey, resolveClientIp } from "./clientip.js"; import { safeEqual } from "./crypto.js"; @@ -51,7 +51,10 @@ import { ADD_REFUSED, MAX_ACCOUNTS, mayAddAccounts, parseOthers, serializeOthers type Env = { Variables: { session: LiveSession } }; -export const sessions: SessionBackend = new SessionStore(config.sessionFile); +export const sessions: SessionBackend = + config.sessionBackend === "cookie" + ? new CookieSessionStore(config.appSecret, config.appSecretPrevious) + : new SessionStore(config.sessionFile); const loginLimiter = new RateLimiter(config.loginRateLimit, 15 * 60_000); /* * The backstop that is never refunded. @@ -236,11 +239,16 @@ const limitSmallBody = bodyLimit({ maxSize: MAX_SMALL_BODY, onError: (c) => c.js const smallBodies: MiddlewareHandler = (c, next) => (LARGE_BODY_ROUTE.test(c.req.path) ? next() : limitSmallBody(c, next)); const requireSession: MiddlewareHandler = async (c, next) => { - const cookie = getCookie(c, config.cookieName); + let cookie = getCookie(c, config.cookieName); let session = sessions.resolve(cookie); if (session?.tokens && needsRefresh(session.tokens)) { try { - session = await refreshSession(cookie!, session); + const refreshed = await refreshSession(cookie!, session); + session = refreshed?.session ?? null; + if (refreshed && refreshed.cookie !== cookie) { + cookie = refreshed.cookie; + setSessionCookie(c, cookie, refreshed.session.remember); + } } catch (err) { // Couldn't ask the server. The token may still have a few minutes; if // not, the call itself will say so. @@ -254,6 +262,9 @@ const requireSession: MiddlewareHandler = async (c, next) => { if (!session) { return c.json({ error: "unauthenticated" }, 401); } + // inbuxa K-W1: the cookie backend slides expiry by re-issuing the cookie. + const reissued = sessions.touch(cookie); + if (reissued) setSessionCookie(c, reissued, session.remember); c.set("session", session); await next(); }; @@ -262,14 +273,14 @@ const requireSession: MiddlewareHandler = async (c, next) => { * One refresh per session at a time: a page opening does several requests at * once, and each would otherwise renew the same token. */ -const refreshing = new Map>(); +const refreshing = new Map>(); /** * Renew an OAuth session's access token and keep the new one. Null when the * server refused the refresh token (a password change revokes it), which * ends the session. */ -function refreshSession(cookie: string, session: LiveSession): Promise { +function refreshSession(cookie: string, session: LiveSession): Promise<{ session: LiveSession; cookie: string } | null> { let inFlight = refreshing.get(session.id); if (!inFlight) { inFlight = (async () => { @@ -279,8 +290,9 @@ function refreshSession(cookie: string, session: LiveSession): Promise refreshing.delete(session.id)); refreshing.set(session.id, inFlight); } @@ -355,6 +367,17 @@ function setOthersCookie(c: Context, cookies: string[]) { }); } +/** + * inbuxa K-W1: put re-issued cookies of accounts not in front back into the + * list. Only the cookie backend re-issues; the memory backend's cookies never + * change, so this is then a no-op. + */ +function replaceOthers(c: Context, replaced: Map) { + if (!replaced.size) return; + const current = parseOthers(getCookie(c, OTHERS_COOKIE)); + setOthersCookie(c, current.map((cookie) => replaced.get(cookie) ?? cookie)); +} + /** The other accounts still signed in, in their order; ended ones are left out. */ function liveOthers(c: Context): { cookie: string; session: LiveSession }[] { const out: { cookie: string; session: LiveSession }[] = []; @@ -832,13 +855,18 @@ export function createApp(basePath = config.basePath): Hono { * several tabs may ask at once. */ api.get("/auth/accounts/unread", requireSession, async (c) => { + const replaced = new Map(); const answers = await Promise.all( liveOthers(c).map(async ({ cookie, session }) => { const cached = unreadCache.get(session.id); if (cached && Date.now() - cached.at < UNREAD_CACHE_MS) return { id: session.id, unread: cached.unread }; try { let live: LiveSession | null = session; - if (live.tokens && needsRefresh(live.tokens)) live = await refreshSession(cookie, live); + if (live.tokens && needsRefresh(live.tokens)) { + const refreshed = await refreshSession(cookie, live); + live = refreshed?.session ?? null; + if (refreshed && refreshed.cookie !== cookie) replaced.set(cookie, refreshed.cookie); + } if (!live) return { id: session.id, unread: null }; const unread = await inboxUnread(live); unreadCache.set(session.id, { unread, at: Date.now() }); @@ -848,6 +876,7 @@ export function createApp(basePath = config.basePath): Hono { } }), ); + replaceOthers(c, replaced); return c.json({ accounts: answers }); }); @@ -867,7 +896,11 @@ export function createApp(basePath = config.basePath): Hono { } const using = Array.isArray(body.using) ? body.using.filter((u): u is string => typeof u === "string") : []; let session: LiveSession | null = other.session; - if (session.tokens && needsRefresh(session.tokens)) session = await refreshSession(other.cookie, session); + if (session.tokens && needsRefresh(session.tokens)) { + const refreshed = await refreshSession(other.cookie, session); + session = refreshed?.session ?? null; + if (refreshed && refreshed.cookie !== other.cookie) replaceOthers(c, new Map([[other.cookie, refreshed.cookie]])); + } if (!session) return c.json({ error: "unauthenticated" }, 401); try { const upstream = await getUpstreamSession(session.id, session.authorization, upstreamFor(session.username)); @@ -903,11 +936,17 @@ export function createApp(basePath = config.basePath): Hono { api.get("/auth/sessions", requireSession, (c) => { const session = c.get("session"); - return c.json({ current: session.id, sessions: sessions.listForUser(session.account) }); + if (!sessions.enumerable) { + // inbuxa K-W1: the cookie backend only knows the session presenting itself. + const { authorization: _a, tokens: _t, account: _c, ...summary } = session; + return c.json({ current: session.id, enumerable: false, sessions: [{ ...summary, userAgent: c.req.header("user-agent")?.slice(0, 200) ?? "" }] }); + } + return c.json({ current: session.id, enumerable: true, sessions: sessions.listForUser(session.account) }); }); api.post("/auth/sessions/revoke-others", requireSession, (c) => { const session = c.get("session"); + if (!sessions.enumerable) return c.json({ error: "not_supported" }, 409); const n = sessions.destroyAllForUser(session.account, session.id); return c.json({ revoked: n }); }); diff --git a/server/src/config.ts b/server/src/config.ts index 21413e5..b53d9b6 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -47,6 +47,24 @@ function int(name: string, fallback: number): number { const isProd = process.env.NODE_ENV === "production"; let appSecret = process.env.APP_SECRET ?? ""; +/* + * inbuxa K-W1: where sessions live. "memory" (the default) keeps them in this + * process, mirrored to SESSION_FILE when set. "cookie" seals the whole session + * into the cookie, so any replica can serve it and nothing is kept here -- + * what running more than one webmail replica needs. Cookie mode signs in with + * OAuth only and can't list or end other sessions (see sessions.ts). + */ +const sessionBackend = (process.env.SESSION_BACKEND ?? "memory").trim().toLowerCase(); +if (sessionBackend !== "memory" && sessionBackend !== "cookie") { + throw new Error(`SESSION_BACKEND must be "memory" or "cookie", not "${sessionBackend}"`); +} +if (sessionBackend === "cookie" && (!appSecret || appSecret === "change-me")) { + // An ephemeral secret would differ on every replica, so each would refuse + // the others' cookies. Unlike memory mode there is no safe fallback. + throw new Error("SESSION_BACKEND=cookie needs APP_SECRET set, and the same on every replica"); +} +/** Secrets that sealed cookies before APP_SECRET was rotated; they still open, never seal. */ +const appSecretPrevious = (process.env.APP_SECRET_PREVIOUS ?? "").split(",").map((s) => s.trim()).filter(Boolean); if (!appSecret || appSecret === "change-me") { if (isProd) { throw new Error("APP_SECRET must be set to a strong random value in production"); @@ -271,6 +289,12 @@ const stalwartServers = readStalwartServers(); * registered exactly. */ const oauthClientSecret = process.env.OAUTH_CLIENT_SECRET ?? ""; +if (sessionBackend === "cookie" && !oauthClientSecret) { + // A sealed password in a cookie can't be revoked: changing it would leave + // the old cookie working wherever it was copied. OAuth tokens are revoked + // by the server when the password changes. + throw new Error("SESSION_BACKEND=cookie signs in with OAuth only: set OAUTH_CLIENT_SECRET"); +} const publicUrl = process.env.PUBLIC_URL ? httpUrl(process.env.PUBLIC_URL, "PUBLIC_URL") : ""; if (oauthClientSecret && !publicUrl) { throw new Error("OAUTH_CLIENT_SECRET is set but PUBLIC_URL is not: the sign-in redirect needs ihasmail's public address"); @@ -352,6 +376,8 @@ export const config = { oauthClientId: env("OAUTH_CLIENT_ID", "ihasmail-inbuxa"), publicUrl, appSecret, + appSecretPrevious, + sessionBackend: sessionBackend as "memory" | "cookie", trustProxy: bool("TRUST_PROXY", true), /** * Peers whose X-Forwarded-* headers are believed. Empty falls back to diff --git a/server/src/crypto.ts b/server/src/crypto.ts index 69541f44209ba4b44ae53861980116fa78270446..93484c776de933a2e9e3fc8ba4ca424904d9cfb7 100644 GIT binary patch delta 492 zcmYL`%SyvQ7==L)AqyAog+o?JNz+zEN{S0_3+bjV0x*$SrOu=>;7J8br2;q5@<4!KbJ7Q}$(VsGNNlwghIk;w7Z#W* zIj=>mD6C1W$W%O*OFMb2Y}Oy&s}(^{@A9k-*=`}pzx`SGPj>qfti5L!;h zp=D7`nU*3pRh0Ot&Nrl$XC242VFYcI1^W@!nDOLqKd35+a95@&DQvKIVCxau)K%T= z-i|QYUxrnTe_#N&G-==UgXVF_@?6GV*B-e0-rG&jO~vg+&kb;S;rjz?VoNBMXolJS o9G`dWAbyzeDQV-m6Q=3 { + const a = new CookieSessionStore("shared-secret"); + const b = new CookieSessionStore("shared-secret"); + const { cookie, session } = a.create(params); + const live = b.resolve(cookie); + assert.ok(live); + assert.equal(live!.id, session.id); + assert.equal(live!.authorization, `Bearer ${tokens.access}`); + assert.equal(live!.account, params.account); + assert.equal(new CookieSessionStore("another-secret").resolve(cookie), null); +}); + +test("cookie sessions refuse tampered, foreign and expired cookies", () => { + const store = new CookieSessionStore("s"); + const { cookie } = store.create(params); + const [v, kid, sealed] = cookie.split("."); + assert.equal(store.resolve(`${v}.${kid}.${sealed!.slice(0, -2)}AA`), null); + assert.equal(store.resolve(`s2.${kid}.${sealed}`), null); + assert.equal(store.resolve(`${cookie}.x`), null); + assert.equal(store.resolve(undefined), null); + const expired = new CookieSessionStore("s"); + const old = expired.create({ ...params, remember: false }); + const real = Date.now; + try { + Date.now = () => real() + 13 * 3600_000; + assert.equal(expired.resolve(old.cookie), null); + } finally { + Date.now = real; + } +}); + +test("a cookie session stays small enough for five accounts", () => { + const { cookie } = new CookieSessionStore("s").create(params); + // The user agent and IP aren't carried: nothing lists them in this mode. + assert.ok(cookie.length < 900, `cookie is ${cookie.length} bytes`); + const others = Array.from({ length: 4 }, () => new CookieSessionStore("s").create(params).cookie); + const value = serializeOthers(others); + assert.ok(value.length < 3800); + assert.deepEqual(parseOthers(value), others); +}); + +test("renewed tokens and sliding expiry re-issue the cookie", () => { + const store = new CookieSessionStore("s"); + const { cookie } = store.create(params); + assert.equal(store.touch(cookie), null, "fresh cookie stays"); + const renewed = { ...tokens, access: "b".repeat(110) }; + const next = store.updateTokens(cookie, renewed); + assert.ok(next && next !== cookie); + assert.equal(store.resolve(next!)!.authorization, `Bearer ${renewed.access}`); + const real = Date.now; + try { + Date.now = () => real() + 120_000; + const slid = store.touch(next!); + assert.ok(slid); + assert.ok(store.resolve(slid!)!.expiresAt > store.resolve(next!)!.expiresAt); + } finally { + Date.now = real; + } +}); + +test("rotating APP_SECRET: old cookies open and are re-sealed under the new key", () => { + const before = new CookieSessionStore("old"); + const { cookie } = before.create(params); + const after = new CookieSessionStore("new", ["old"]); + assert.ok(after.resolve(cookie)); + const resealed = after.touch(cookie); + assert.ok(resealed && resealed.split(".")[1] !== cookie.split(".")[1]); + assert.ok(new CookieSessionStore("new").resolve(resealed!)); + assert.equal(new CookieSessionStore("new").resolve(cookie), null); +}); + +test("cookie sessions hold OAuth tokens only and can't enumerate", () => { + const store = new CookieSessionStore("s"); + assert.throws(() => store.create({ username: "u", password: "p", remember: false, userAgent: "", ip: "" })); + assert.equal(store.enumerable, false); + assert.equal(store.reseal("x", "p"), false); + assert.deepEqual(store.listForUser("u"), []); + assert.equal(store.destroyAllForUser("u"), 0); + assert.equal(new SessionStore("").enumerable, true); +}); + +test("the memory store keeps its cookie across a token renewal", () => { + const store = new SessionStore(""); + const { cookie } = store.create(params); + assert.equal(store.updateTokens(cookie, { ...tokens, access: "c" }), cookie); + assert.equal(store.touch(cookie), null); +}); diff --git a/server/src/sessions.ts b/server/src/sessions.ts index fd14474..23b751a 100644 --- a/server/src/sessions.ts +++ b/server/src/sessions.ts @@ -2,7 +2,7 @@ import { mkdir, readFile, writeFile, rename } from "node:fs/promises"; import { dirname } from "node:path"; import { randomBytes } from "node:crypto"; import { config } from "./config.js"; -import { deriveKey, open, randomToken, safeEqual, seal, sha256 } from "./crypto.js"; +import { cookieKey, deriveKey, open, randomToken, safeEqual, seal, sha256 } from "./crypto.js"; import type { TokenSet } from "./oauth.js"; export interface StoredSession { @@ -107,13 +107,28 @@ export interface CreateSessionParams { * Stalwart's own token registry, which can already answer both questions. */ export interface SessionBackend { + /** + * Whether `listForUser` and `destroyAllForUser` can reach sessions other + * than the one presenting itself. False for the cookie backend. + */ + readonly enumerable: boolean; init(): Promise; close(): Promise; create(params: CreateSessionParams): { cookie: string; session: LiveSession }; resolve(cookie: string | undefined): LiveSession | null; reseal(cookie: string | undefined, password: string): boolean; - /** Store renewed OAuth tokens in place of the ones the session holds. */ - updateTokens(cookie: string | undefined, tokens: TokenSet): boolean; + /** + * Store renewed OAuth tokens in place of the ones the session holds. Returns + * the cookie to use from now on (the same one, for a backend that keeps the + * record itself), or null when the cookie doesn't resolve. + */ + updateTokens(cookie: string | undefined, tokens: TokenSet): string | null; + /** + * A new cookie to send, when the backend wants this one re-issued (the + * cookie backend's sliding expiry, or a cookie sealed under a retired key). + * Null when the cookie stays as it is. + */ + touch(cookie: string | undefined): string | null; destroy(id: string): void; /** `account` is an `accountKey`, as carried on `LiveSession.account`. */ destroyAllForUser(account: string, exceptId?: string): number; @@ -132,6 +147,7 @@ function sealable(username: string, params: { password?: string; tokens?: TokenS } export class SessionStore implements SessionBackend { + readonly enumerable = true; private sessions = new Map(); private dirty = false; private saveTimer: NodeJS.Timeout | null = null; @@ -274,8 +290,13 @@ export class SessionStore implements SessionBackend { return this.rewrite(cookie, (username) => ({ u: username, p: password })); } - updateTokens(cookie: string | undefined, tokens: TokenSet): boolean { - return this.rewrite(cookie, (username) => ({ u: username, t: tokens })); + updateTokens(cookie: string | undefined, tokens: TokenSet): string | null { + return this.rewrite(cookie, (username) => ({ u: username, t: tokens })) ? cookie! : null; + } + + /** Expiry slides in `resolve`, and the cookie itself never changes. */ + touch(_cookie: string | undefined): string | null { + return null; } private rewrite(cookie: string | undefined, next: (username: string) => Sealed): boolean { @@ -338,3 +359,144 @@ export class SessionStore implements SessionBackend { }; } } + +/* + * inbuxa K-W1: sessions carried whole in the cookie, so that any replica can + * serve a session it never issued and the webmail keeps no state of its own. + * + * The cookie is `s1..`: the record below sealed with AES-256-GCM + * under a key derived from APP_SECRET (`cookieKey`), `kid` naming that key. + * APP_SECRET_PREVIOUS keys still open cookies, and a cookie opened with one is + * re-sealed under the current key on its next request (`touch`). + * + * What it can't do, by construction: list a user's other sessions or end + * them, so `enumerable` is false and the UI hides both. Ending this session is + * deleting the cookie; the server revokes the tokens behind every session when + * the password changes. Password sessions aren't offered at all (config.ts + * refuses cookie mode without OAuth): a sealed password couldn't be revoked. + */ +const COOKIE_V1 = "s1"; + +/** The sealed record. Short keys: it travels on every request. */ +interface CookieRecord { + i: string; // session id + u: string; // username + a: string; // accountKey + t: TokenSet; + c: number; // createdAt + l: number; // lastSeenAt + e: number; // expiresAt + r: boolean; // remember +} + +export class CookieSessionStore implements SessionBackend { + readonly enumerable = false; + private readonly keys: { kid: string; key: Buffer }[]; + + constructor(appSecret: string, previous: string[] = []) { + this.keys = [appSecret, ...previous].map(cookieKey); + } + + async init(): Promise {} + async close(): Promise {} + + create(params: CreateSessionParams): { cookie: string; session: LiveSession } { + if (!params.tokens) throw new Error("cookie sessions hold OAuth tokens only"); + const now = Date.now(); + const record: CookieRecord = { + i: randomToken(18), + u: params.username, + a: params.account ?? params.username.trim().toLowerCase(), + t: params.tokens, + c: now, + l: now, + e: now + this.ttl(params.remember), + r: params.remember, + }; + return { cookie: this.seal(record), session: this.toLive(record) }; + } + + resolve(cookie: string | undefined): LiveSession | null { + const opened = this.open(cookie); + return opened ? this.toLive(opened.record) : null; + } + + touch(cookie: string | undefined): string | null { + const opened = this.open(cookie); + if (!opened) return null; + const now = Date.now(); + const stale = now - opened.record.l > 60_000; + if (!stale && opened.current) return null; + if (stale) { + opened.record.l = now; + opened.record.e = now + this.ttl(opened.record.r); + } + return this.seal(opened.record); + } + + /** Cookie sessions hold no password to re-seal. */ + reseal(_cookie: string | undefined, _password: string): boolean { + return false; + } + + updateTokens(cookie: string | undefined, tokens: TokenSet): string | null { + const opened = this.open(cookie); + if (!opened) return null; + opened.record.t = tokens; + return this.seal(opened.record); + } + + /** Nothing is kept here: the caller deletes the cookie. */ + destroy(_id: string): void {} + + destroyAllForUser(_account: string, _exceptId?: string): number { + return 0; + } + + listForUser(_account: string): SessionSummary[] { + return []; + } + + private ttl(remember: boolean): number { + return (remember ? config.sessionRememberTtl : config.sessionTtl) * 1000; + } + + private seal(record: CookieRecord): string { + const { kid, key } = this.keys[0]!; + return `${COOKIE_V1}${COOKIE_SEP}${kid}${COOKIE_SEP}${seal(JSON.stringify(record), key)}`; + } + + private open(cookie: string | undefined): { record: CookieRecord; current: boolean } | null { + if (!cookie) return null; + const [version, kid, sealed, extra] = cookie.split(COOKIE_SEP); + if (version !== COOKIE_V1 || !kid || !sealed || extra !== undefined) return null; + const at = this.keys.findIndex((k) => k.kid === kid); + if (at < 0) return null; + const json = open(sealed, this.keys[at]!.key); + if (!json) return null; + let record: CookieRecord; + try { + record = JSON.parse(json) as CookieRecord; + } catch { + return null; + } + if (typeof record.e !== "number" || record.e <= Date.now() || !record.t?.access) return null; + return { record, current: at === 0 }; + } + + private toLive(r: CookieRecord): LiveSession { + return { + id: r.i, + username: r.u, + account: r.a, + authorization: `Bearer ${r.t.access}`, + tokens: r.t, + remember: r.r, + createdAt: r.c, + lastSeenAt: r.l, + expiresAt: r.e, + userAgent: "", + ip: "", + }; + } +} diff --git a/web/src/locales/de.ts b/web/src/locales/de.ts index e0f45a5..50b2cd3 100644 --- a/web/src/locales/de.ts +++ b/web/src/locales/de.ts @@ -1096,6 +1096,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "Sie sind als {user} angemeldet. Ihr Passwort wird nie im Browser gespeichert; der Server hält es pro Sitzung verschlüsselt vor, um mit dem Mailserver zu kommunizieren.", "App passwords are managed by your mail administrator.": "App-Passwörter werden von Ihrer Mail-Administration verwaltet.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Wenn Sie Ihr Passwort ändern, werden Ihre anderen Webmail-Sitzungen abgemeldet. App-Passwörter funktionieren weiterhin.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Diese Webmail kann Ihre anderen Sitzungen nicht auflisten. Wenn Sie Ihr Passwort ändern, werden Sie überall abgemeldet.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "F\u00fcr dieses Konto ist die Zwei-Faktor-Authentifizierung aktiviert. {app} kann Sie noch nicht per Code anmelden; die Anmeldung auf einem anderen Ger\u00e4t ben\u00f6tigt daher ein App-Passwort \u2014 oder Sie deaktivieren die Zwei-Faktor-Authentifizierung hier.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Ein eigenes Passwort für ein E-Mail-Programm oder Gerät, das Sie einzeln widerrufen können. App-Passwörter umgehen Zwei-Faktor-Codes und funktionieren daher auch in Programmen, die keinen abfragen können.", "Copy it into {name} now — it isn't shown again.": "Übertragen Sie es jetzt nach {name} — es wird nicht erneut angezeigt.", diff --git a/web/src/locales/es.ts b/web/src/locales/es.ts index 6de4160..18053c3 100644 --- a/web/src/locales/es.ts +++ b/web/src/locales/es.ts @@ -1158,6 +1158,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "Ha iniciado sesión como {user}. Su contraseña nunca se guarda en el navegador; el servidor la conserva cifrada por sesión para comunicarse con el servidor de correo.", "App passwords are managed by your mail administrator.": "Las contraseñas de aplicación las gestiona su administrador de correo.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Cambiar la contraseña cierra sus demás sesiones de webmail. Las contraseñas de aplicación siguen funcionando.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Este webmail no puede mostrar tus otras sesiones. Si cambias la contraseña, se cerrará tu sesión en todas partes.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "Esta cuenta tiene activada la autenticaci\u00f3n en dos pasos. {app} todav\u00eda no puede iniciar su sesi\u00f3n con un c\u00f3digo, as\u00ed que iniciar sesi\u00f3n en otro dispositivo requiere una contrase\u00f1a de aplicaci\u00f3n; o puede desactivar aqu\u00ed la autenticaci\u00f3n en dos pasos.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Una contraseña aparte para una aplicación de correo o un dispositivo, que puede revocar por separado. Las contraseñas de aplicación se saltan los códigos de dos pasos, así que siguen funcionando en aplicaciones que no pueden pedir uno.", "Copy it into {name} now — it isn't shown again.": "Cópiela ahora en {name}: no se volverá a mostrar.", diff --git a/web/src/locales/fr.ts b/web/src/locales/fr.ts index 7cf5675..ab0b22e 100644 --- a/web/src/locales/fr.ts +++ b/web/src/locales/fr.ts @@ -1163,6 +1163,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "Vous êtes connecté en tant que {user}. Votre mot de passe n’est jamais stocké dans le navigateur ; le serveur le conserve chiffré, par session, pour communiquer avec le serveur de messagerie.", "App passwords are managed by your mail administrator.": "Les mots de passe d'application sont gérés par votre administrateur de messagerie.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Changer votre mot de passe déconnecte vos autres sessions webmail. Les mots de passe d'application continuent de fonctionner.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Ce webmail ne peut pas afficher vos autres sessions. Changer votre mot de passe vous déconnecte partout.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "L'authentification \u00e0 deux facteurs est activ\u00e9e sur ce compte. {app} ne sait pas encore vous connecter avec un code : la connexion sur un autre appareil n\u00e9cessite donc un mot de passe d'application \u2014 ou vous pouvez d\u00e9sactiver l'authentification \u00e0 deux facteurs ici.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Un mot de passe distinct pour une application ou un appareil, révocable indépendamment. Les mots de passe d'application contournent les codes à deux facteurs et fonctionnent donc dans les applications qui ne peuvent pas en demander.", "Copy it into {name} now — it isn't shown again.": "Copiez-le dans {name} maintenant — il ne sera plus affiché.", diff --git a/web/src/locales/ja.ts b/web/src/locales/ja.ts index 58f16ce..25481b6 100644 --- a/web/src/locales/ja.ts +++ b/web/src/locales/ja.ts @@ -1111,6 +1111,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "{user} としてサインインしています。パスワードがブラウザーに保存されることはありません。メールサーバーとの通信用に、サーバーがセッションごとに暗号化して保持します。", "App passwords are managed by your mail administrator.": "アプリパスワードはメール管理者が管理しています。", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "パスワードを変更すると、他のウェブメールのセッションはサインアウトされます。アプリパスワードはそのまま使えます。", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "このWebメールでは他のセッションを一覧表示できません。パスワードを変更すると、すべての場所からサインアウトされます。", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "\u3053\u306e\u30a2\u30ab\u30a6\u30f3\u30c8\u3067\u306f 2 \u6bb5\u968e\u8a8d\u8a3c\u304c\u6709\u52b9\u3067\u3059\u3002{app} \u306f\u307e\u3060\u78ba\u8a8d\u30b3\u30fc\u30c9\u3067\u306e\u30b5\u30a4\u30f3\u30a4\u30f3\u306b\u5bfe\u5fdc\u3057\u3066\u3044\u306a\u3044\u305f\u3081\u3001\u4ed6\u306e\u30c7\u30d0\u30a4\u30b9\u304b\u3089\u30b5\u30a4\u30f3\u30a4\u30f3\u3059\u308b\u306b\u306f\u30a2\u30d7\u30ea\u30d1\u30b9\u30ef\u30fc\u30c9\u304c\u5fc5\u8981\u3067\u3059\u3002\u3053\u3053\u3067 2 \u6bb5\u968e\u8a8d\u8a3c\u3092\u30aa\u30d5\u306b\u3059\u308b\u3053\u3068\u3082\u3067\u304d\u307e\u3059\u3002", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "メールアプリやデバイスごとに用意する別のパスワードで、単独で無効化できます。アプリパスワードは 2 段階認証の確認コードを省くため、コードを入力できないアプリでも使えます。", "Copy it into {name} now — it isn't shown again.": "いま {name} にコピーしてください。二度と表示されません。", diff --git a/web/src/locales/nl.ts b/web/src/locales/nl.ts index a9780e2..fc710c8 100644 --- a/web/src/locales/nl.ts +++ b/web/src/locales/nl.ts @@ -1158,6 +1158,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "U bent ingelogd als {user}. Uw wachtwoord wordt nooit in de browser opgeslagen; de server bewaart het versleuteld per sessie om met de mailserver te communiceren.", "App passwords are managed by your mail administrator.": "App-wachtwoorden worden beheerd door uw mailbeheerder.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Als u uw wachtwoord wijzigt, worden uw andere webmailsessies afgemeld. App-wachtwoorden blijven werken.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Deze webmail kan je andere sessies niet tonen. Als je je wachtwoord wijzigt, word je overal afgemeld.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "Voor dit account staat tweefactorauthenticatie aan. {app} kan u nog niet met een code inloggen, dus inloggen op een ander apparaat vereist een app-wachtwoord \u2014 of u schakelt tweefactorauthenticatie hier uit.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Een apart wachtwoord voor een e-mail app of apparaat, dat u afzonderlijk kunt intrekken. App-wachtwoorden omzeilen tweestapsverificatie, zodat ze blijven werken in apps die hier niet om kunnen vragen.", "Copy it into {name} now — it isn't shown again.": "Neem het nu over in {name} — het wordt niet opnieuw getoond.", diff --git a/web/src/locales/pt-BR.ts b/web/src/locales/pt-BR.ts index 4c7adf6..02be997 100644 --- a/web/src/locales/pt-BR.ts +++ b/web/src/locales/pt-BR.ts @@ -1161,6 +1161,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "Você entrou como {user}. Sua senha nunca é guardada no navegador; o servidor a mantém criptografada por sessão para se comunicar com o servidor de e-mail.", "App passwords are managed by your mail administrator.": "As senhas de aplicativo são gerenciadas pelo seu administrador de e-mail.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Mudar sua senha encerra suas outras sessões de webmail. As senhas de aplicativo continuam funcionando.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Este webmail não consegue listar suas outras sessões. Alterar a senha encerra sua sessão em todos os lugares.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "Esta conta est\u00e1 com a autentica\u00e7\u00e3o em duas etapas ativada. O {app} ainda n\u00e3o consegue conectar voc\u00ea com um c\u00f3digo, ent\u00e3o entrar em outro dispositivo exige uma senha de aplicativo \u2014 ou voc\u00ea pode desativar a autentica\u00e7\u00e3o em duas etapas aqui.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Uma senha separada para um aplicativo de e-mail ou dispositivo, que você pode revogar sozinha. As senhas de aplicativo dispensam os códigos de duas etapas, então continuam funcionando em aplicativos que não conseguem pedir um.", "Copy it into {name} now — it isn't shown again.": "Copie-a para {name} agora — ela não será mostrada de novo.", diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts index b8c2617..666e1bc 100644 --- a/web/src/locales/ru.ts +++ b/web/src/locales/ru.ts @@ -1160,6 +1160,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "Вы вошли как {user}. Пароль никогда не хранится в браузере; сервер хранит его в зашифрованном виде для каждого сеанса, чтобы обращаться к почтовому серверу.", "App passwords are managed by your mail administrator.": "Паролями приложений управляет ваш почтовый администратор.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Смена пароля завершает остальные сеансы веб-почты. Пароли приложений продолжают работать.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Эта веб-почта не может показать ваши другие сеансы. При смене пароля вы выйдете из системы везде.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "\u0414\u043b\u044f \u044d\u0442\u043e\u0439 \u0443\u0447\u0451\u0442\u043d\u043e\u0439 \u0437\u0430\u043f\u0438\u0441\u0438 \u0432\u043a\u043b\u044e\u0447\u0435\u043d\u0430 \u0434\u0432\u0443\u0445\u0444\u0430\u043a\u0442\u043e\u0440\u043d\u0430\u044f \u0430\u0443\u0442\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u044f. {app} \u043f\u043e\u043a\u0430 \u043d\u0435 \u0443\u043c\u0435\u0435\u0442 \u0432\u0445\u043e\u0434\u0438\u0442\u044c \u043f\u043e \u043a\u043e\u0434\u0443, \u043f\u043e\u044d\u0442\u043e\u043c\u0443 \u0434\u043b\u044f \u0432\u0445\u043e\u0434\u0430 \u043d\u0430 \u0434\u0440\u0443\u0433\u043e\u043c \u0443\u0441\u0442\u0440\u043e\u0439\u0441\u0442\u0432\u0435 \u043d\u0443\u0436\u0435\u043d \u043f\u0430\u0440\u043e\u043b\u044c \u043f\u0440\u0438\u043b\u043e\u0436\u0435\u043d\u0438\u044f \u2014 \u043b\u0438\u0431\u043e \u0434\u0432\u0443\u0445\u0444\u0430\u043a\u0442\u043e\u0440\u043d\u0443\u044e \u0430\u0443\u0442\u0435\u043d\u0442\u0438\u0444\u0438\u043a\u0430\u0446\u0438\u044e \u043c\u043e\u0436\u043d\u043e \u043e\u0442\u043a\u043b\u044e\u0447\u0438\u0442\u044c \u0437\u0434\u0435\u0441\u044c.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Отдельный пароль для почтовой программы или устройства, который можно отозвать по отдельности. Пароли приложений обходят двухфакторные коды и поэтому работают там, где запросить код невозможно.", "Copy it into {name} now — it isn't shown again.": "Скопируйте его в {name} сейчас — больше он не показывается.", diff --git a/web/src/locales/tr.ts b/web/src/locales/tr.ts index a423a5a..71afa6a 100644 --- a/web/src/locales/tr.ts +++ b/web/src/locales/tr.ts @@ -237,6 +237,7 @@ export const catalog: Catalog = { "Change this event?": "Bu etkinlik değiştirilsin mi?", "Change your own password in {settings}.": "Kendi şifrenizi {settings} bölümünden değiştirin.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Şifrenizi değiştirmek diğer webmail oturumlarınızı kapatır. Varsa uygulama şifreleriniz çalışmaya devam eder.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Bu web postası diğer oturumlarınızı listeleyemez. Parolanızı değiştirmek her yerde oturumunuzu kapatır.", "Check for new shares": "Yeni paylaşımları kontrol et", "Checking what is still in this tenant…": "Bu kiracıda hâlâ nelerin bulunduğu kontrol ediliyor…", "Choose a calendar": "Bir takvim seçin", diff --git a/web/src/locales/uk.ts b/web/src/locales/uk.ts index dc176c9..5376c45 100644 --- a/web/src/locales/uk.ts +++ b/web/src/locales/uk.ts @@ -1154,6 +1154,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "Ви ввійшли як {user}. Пароль ніколи не зберігається в браузері; сервер зберігає його зашифрованим для кожного сеансу, щоб звертатися до поштового сервера.", "App passwords are managed by your mail administrator.": "Паролями програм керує ваш поштовий адміністратор.", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "Зміна пароля завершує інші сеанси вебпошти. Паролі програм продовжують працювати.", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "Ця веб-пошта не може показати ваші інші сеанси. Зміна пароля завершить ваші сеанси всюди.", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "\u0414\u043b\u044f \u0446\u044c\u043e\u0433\u043e \u043e\u0431\u043b\u0456\u043a\u043e\u0432\u043e\u0433\u043e \u0437\u0430\u043f\u0438\u0441\u0443 \u0443\u0432\u0456\u043c\u043a\u043d\u0435\u043d\u043e \u0434\u0432\u043e\u0444\u0430\u043a\u0442\u043e\u0440\u043d\u0443 \u0430\u0432\u0442\u0435\u043d\u0442\u0438\u0444\u0456\u043a\u0430\u0446\u0456\u044e. {app} \u043f\u043e\u043a\u0438 \u043d\u0435 \u0432\u043c\u0456\u0454 \u0432\u0445\u043e\u0434\u0438\u0442\u0438 \u0437\u0430 \u043a\u043e\u0434\u043e\u043c, \u0442\u043e\u043c\u0443 \u0434\u043b\u044f \u0432\u0445\u043e\u0434\u0443 \u043d\u0430 \u0456\u043d\u0448\u043e\u043c\u0443 \u043f\u0440\u0438\u0441\u0442\u0440\u043e\u0457 \u043f\u043e\u0442\u0440\u0456\u0431\u0435\u043d \u043f\u0430\u0440\u043e\u043b\u044c \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u0438 \u2014 \u0430\u0431\u043e \u0434\u0432\u043e\u0444\u0430\u043a\u0442\u043e\u0440\u043d\u0443 \u0430\u0432\u0442\u0435\u043d\u0442\u0438\u0444\u0456\u043a\u0430\u0446\u0456\u044e \u043c\u043e\u0436\u043d\u0430 \u0432\u0438\u043c\u043a\u043d\u0443\u0442\u0438 \u0442\u0443\u0442.", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "Окремий пароль для поштової програми чи пристрою, який можна відкликати окремо. Паролі програм обходять двофакторні коди й тому працюють там, де запитати код неможливо.", "Copy it into {name} now — it isn't shown again.": "Скопіюйте його до {name} зараз — більше він не показується.", diff --git a/web/src/locales/zh-Hans.ts b/web/src/locales/zh-Hans.ts index d35fe25..359d837 100644 --- a/web/src/locales/zh-Hans.ts +++ b/web/src/locales/zh-Hans.ts @@ -1110,6 +1110,7 @@ export const catalog: Catalog = { "You're signed in as {user}. Your password is never stored in the browser; the server keeps it encrypted per-session for talking to the mail server.": "您已以 {user} 身份登录。您的密码从不保存在浏览器中;服务器会按会话加密保存它,用于与邮件服务器通信。", "App passwords are managed by your mail administrator.": "应用专用密码由您的邮件管理员管理。", "Changing your password signs out your other webmail sessions. Any app passwords keep working.": "更改密码会让您的其他网页邮箱会话退出登录。已有的应用专用密码仍可继续使用。", + "This webmail can't list your other sessions. Changing your password signs you out everywhere.": "此网页邮箱无法列出您的其他会话。更改密码会让您在所有地方退出登录。", "This account has two-factor authentication on. {app} can't sign you in with a code yet, so signing in on another device needs an app password \u2014 or you can turn two-factor authentication off here.": "\u6b64\u8d26\u6237\u5df2\u5f00\u542f\u4e24\u6b65\u9a8c\u8bc1\u3002{app} \u76ee\u524d\u8fd8\u4e0d\u80fd\u901a\u8fc7\u9a8c\u8bc1\u7801\u767b\u5f55\uff0c\u56e0\u6b64\u5728\u5176\u4ed6\u8bbe\u5907\u4e0a\u767b\u5f55\u9700\u8981\u4f7f\u7528\u5e94\u7528\u4e13\u7528\u5bc6\u7801\u2014\u2014\u60a8\u4e5f\u53ef\u4ee5\u5728\u8fd9\u91cc\u5173\u95ed\u4e24\u6b65\u9a8c\u8bc1\u3002", "A separate password for a mail app or device, which you can revoke on its own. App passwords skip two-factor codes, so they keep working in apps that can't ask for one.": "为某个邮件应用或设备单独设置的密码,可以单独吊销。应用专用密码会跳过两步验证码,因此在无法输入验证码的应用中仍然可用。", "Copy it into {name} now — it isn't shown again.": "请立即把它复制到 {name}——它不会再次显示。", diff --git a/web/src/views/settings/SecuritySettings.tsx b/web/src/views/settings/SecuritySettings.tsx index 940a71e..c4d1a0a 100644 --- a/web/src/views/settings/SecuritySettings.tsx +++ b/web/src/views/settings/SecuritySettings.tsx @@ -43,7 +43,9 @@ export function SecuritySettings() { const logout = useSession((s) => s.logout); const appName = useAppName(); - const load = () => apiFetch<{ current: string; sessions: SessionRow[] }>("/api/auth/sessions").then((r) => { setRows(r.sessions); setCurrent(r.current); }).catch(() => setRows([])); + /* inbuxa K-W1: false when sessions live in their cookies and can't be listed or ended from here. */ + const [enumerable, setEnumerable] = useState(true); + const load = () => apiFetch<{ current: string; enumerable?: boolean; sessions: SessionRow[] }>("/api/auth/sessions").then((r) => { setRows(r.sessions); setCurrent(r.current); setEnumerable(r.enumerable !== false); }).catch(() => setRows([])); const loadSecurity = useCallback(async () => { try { @@ -120,8 +122,9 @@ export function SecuritySettings() { )} + {!enumerable &&

{t("This webmail can't list your other sessions. Changing your password signs you out everywhere.")}

}
- + {enumerable && }
-- 2.54.0 From c0768358f2dc502e550f2c6b8473e98d6b3431cb Mon Sep 17 00:00:00 2001 From: John Coffey Date: Wed, 18 Nov 2026 01:33:35 -0700 Subject: [PATCH 2/2] Sign-out revokes the session's tokens at the mail server With cookie sessions there is nothing on this side to delete, so signing out (one account or all) now revokes the refresh and access token through the server's RFC 7009 endpoint, read from its OAuth metadata. A copy of the cookie then gets 401. A server without revocation still signs out, and in cookie mode a warning says the copy works until the tokens expire. Closes #104 --- .env.example | 6 +- server/src/app.ts | 27 +++++---- server/src/mock/oauth.ts | 21 ++++++- server/src/oauth.ts | 46 ++++++++++++++- server/src/signout-revoke.test.ts | 94 +++++++++++++++++++++++++++++++ 5 files changed, 179 insertions(+), 15 deletions(-) create mode 100644 server/src/signout-revoke.test.ts diff --git a/.env.example b/.env.example index 5052dbb..a130e9c 100644 --- a/.env.example +++ b/.env.example @@ -50,7 +50,11 @@ SESSION_FILE=./data/sessions.json # than one webmail replica (Kubernetes, say) needs. It requires APP_SECRET set # to the same value on every replica, and OAuth sign-in (OAUTH_CLIENT_SECRET). # The cost: the Security page can't list or sign out your other sessions; -# changing the password still signs out everywhere. Use PUSH_MODE=relay with +# changing the password still signs out everywhere. Signing out revokes the +# session's tokens at the mail server, so a copy of the cookie stops working; +# that needs a server with token revocation (inbuxa-server 27.1 or later). +# Against an older one, a copied cookie works until its tokens expire, and a +# warning is logged at each sign-out. Use PUSH_MODE=relay with # several replicas: subscribe mode fans out only to tabs on the replica the # mail server calls back. # SESSION_BACKEND=memory diff --git a/server/src/app.ts b/server/src/app.ts index 458f9b4..7f7db6d 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -43,7 +43,7 @@ import { revokeAppPassword, } from "./account.js"; import { imageProxyHandler } from "./imageproxy.js"; -import { SignInError, finish as finishSignIn, needsRefresh, oauthEnabled, passwordConfirms, refreshTokens, singleServer, start as startSignIn, type TokenSet } from "./oauth.js"; +import { SignInError, finish as finishSignIn, needsRefresh, oauthEnabled, passwordConfirms, refreshTokens, revokeTokens, singleServer, start as startSignIn, type TokenSet } from "./oauth.js"; import { icsProxyHandler } from "./icsproxy.js"; import { staticHandler } from "./static.js"; import { mailNode, webmailNode } from "./nodes.js"; @@ -791,13 +791,24 @@ export function createApp(basePath = config.basePath): Hono { } }); + // inbuxa K-W2: a signed-out session's tokens are revoked at the server, so + // a copy of its cookie stops working (with cookie sessions there is nothing + // here to delete) + const endSession = async (session: LiveSession) => { + sessions.destroy(session.id); + forgetUpstreamSession(session.id); + if (session.tokens) { + const revoked = await revokeTokens(upstreamFor(session.username), session.tokens); + if (!revoked && !sessions.enumerable) { + console.warn("[ihasmail] signed out, but the mail server didn't revoke the session's tokens; a copy of the cookie works until they expire"); + } + } + }; + api.post("/auth/logout", async (c) => { const cookie = getCookie(c, config.cookieName); const session = sessions.resolve(cookie); - if (session) { - sessions.destroy(session.id); - forgetUpstreamSession(session.id); - } + if (session) await endSession(session); // inbuxa MA-B: only this account ends; the next one comes to the front const [next, ...rest] = liveOthers(c); if (next) { @@ -813,11 +824,7 @@ export function createApp(basePath = config.basePath): Hono { /* inbuxa MA-B: every account signed in here ends. */ api.post("/auth/logout-all", async (c) => { const front = sessions.resolve(getCookie(c, config.cookieName)); - for (const session of [front, ...liveOthers(c).map((o) => o.session)]) { - if (!session) continue; - sessions.destroy(session.id); - forgetUpstreamSession(session.id); - } + await Promise.all([front, ...liveOthers(c).map((o) => o.session)].filter((s): s is LiveSession => Boolean(s)).map(endSession)); deleteCookie(c, config.cookieName, { path: cookiePath }); deleteCookie(c, OTHERS_COOKIE, { path: cookiePath }); return c.json({ ok: true }); diff --git a/server/src/mock/oauth.ts b/server/src/mock/oauth.ts index c1b9957..f54daf8 100644 --- a/server/src/mock/oauth.ts +++ b/server/src/mock/oauth.ts @@ -28,13 +28,18 @@ const base = () => `http://127.0.0.1:${PORT}`; * C-23). Off by default, since the mock also serves password sign-in. */ export let basicRefused = false; +/** Whether the metadata offers RFC 7009 revocation, as inbuxa-server 27.1 does. */ +export let revocationOffered = true; /** For tests: how long new access tokens last, and a way to end every token. */ export const oauthMock = { setAccessTokenTtl(seconds: number) { accessTokenTtl = seconds; }, expireAccessTokens() { for (const t of accessTokens.values()) t.expiresAt = 0; }, refuseBasic(on: boolean) { basicRefused = on; }, - reset() { codes.clear(); accessTokens.clear(); refreshTokens.clear(); accessTokenTtl = 3600; basicRefused = false; }, + offerRevocation(on: boolean) { revocationOffered = on; }, + /** Tokens revoked so far, by RFC 7009. */ + revoked: [] as string[], + reset() { codes.clear(); accessTokens.clear(); refreshTokens.clear(); accessTokenTtl = 3600; basicRefused = false; revocationOffered = true; oauthMock.revoked.length = 0; }, }; /** A bearer token the mock issued, still valid under the current password. */ @@ -84,6 +89,7 @@ export async function handleOAuth(req: IncomingMessage, res: ServerResponse, url issuer: base(), authorization_endpoint: `${base()}/login`, token_endpoint: `${base()}/auth/token`, + ...(revocationOffered ? { revocation_endpoint: `${base()}/auth/revoke` } : {}), grant_types_supported: ["authorization_code", "refresh_token"], response_types_supported: ["code"], scopes_supported: ["openid", "offline_access"], @@ -137,6 +143,19 @@ export async function handleOAuth(req: IncomingMessage, res: ServerResponse, url json(res, 200, { type: "authenticated", client_code: code, iss: base() }); return true; } + if (url.pathname === "/auth/revoke" && req.method === "POST" && revocationOffered) { + // RFC 7009: this client's secret, then the token goes, whatever it was + const form = await readForm(req); + if (form.get("client_id") !== OAUTH_CLIENT_ID || form.get("client_secret") !== OAUTH_CLIENT_SECRET) { + json(res, 401, { error: "invalid_client" }); + return true; + } + const token = form.get("token") ?? ""; + if (accessTokens.delete(token) || refreshTokens.delete(token)) oauthMock.revoked.push(token); + res.writeHead(200); + res.end(); + return true; + } if (url.pathname === "/auth/token" && req.method === "POST") { const form = await readForm(req); if (form.get("client_id") !== OAUTH_CLIENT_ID || form.get("client_secret") !== OAUTH_CLIENT_SECRET) { diff --git a/server/src/oauth.ts b/server/src/oauth.ts index 06e4dc2..7e70426 100644 --- a/server/src/oauth.ts +++ b/server/src/oauth.ts @@ -18,10 +18,11 @@ * Access tokens last an hour; `refreshTokens()` renews them before they run * out. A password change on the server revokes both tokens, which ends every * session holding them -- the safe result, and the one the web app is told - * about. + * about. Signing out revokes them too (`revokeTokens()`), where the server + * offers RFC 7009 revocation, so a copy of the session cookie dies with it. * * Nothing here is taken from another client's implementation; the shapes are - * RFC 6749, RFC 7636 and RFC 8414. + * RFC 6749, RFC 7636, RFC 7009 and RFC 8414. */ import { createHash } from "node:crypto"; import { config } from "./config.js"; @@ -38,6 +39,8 @@ export interface TokenSet { interface Metadata { authorizationEndpoint: string; tokenEndpoint: string; + /** RFC 7009; null on a server without it (inbuxa-server before 27.1). */ + revocationEndpoint: string | null; scopes: string[]; } @@ -77,7 +80,7 @@ async function metadataFor(base: string): Promise { signal: AbortSignal.timeout(config.upstreamTimeout), }); if (!res.ok) throw new UpstreamError(`OAuth metadata request failed (${res.status})`, 502); - const doc = (await res.json()) as { authorization_endpoint?: string; token_endpoint?: string; scopes_supported?: string[] }; + const doc = (await res.json()) as { authorization_endpoint?: string; token_endpoint?: string; revocation_endpoint?: string; scopes_supported?: string[] }; if (!doc.authorization_endpoint || !doc.token_endpoint) { throw new UpstreamError("The mail server's OAuth metadata has no authorization or token endpoint", 502); } @@ -86,6 +89,7 @@ async function metadataFor(base: string): Promise { authorizationEndpoint: new URL(doc.authorization_endpoint, base).toString(), // Where this process goes, so the configured route, like every other call. tokenEndpoint: absoluteUpstream(doc.token_endpoint, base), + revocationEndpoint: doc.revocation_endpoint ? absoluteUpstream(doc.revocation_endpoint, base) : null, scopes: doc.scopes_supported ?? [], }; metadataCache.set(base, { metadata, fetchedAt: Date.now() }); @@ -237,6 +241,42 @@ async function tokenRequest(endpoint: string, fields: Record): P }; } +/** + * K-W2: revoke a signed-out session's tokens at the server, refresh token + * first so no new access token can be minted while the access token goes. + * With cookie sessions there is nothing here to delete, so this is what + * makes a copy of the cookie stop working. + * + * Returns whether both were revoked: false on a server without RFC 7009, or + * one that couldn't be reached. Signing out never waits on more than that, + * and never fails because of it. + */ +export async function revokeTokens(base: string, tokens: TokenSet): Promise { + let endpoint: string | null; + try { + endpoint = (await metadataFor(base)).revocationEndpoint; + } catch { + return false; + } + if (!endpoint) return false; + const revoke = async (token: string, hint: string) => { + try { + const res = await fetch(endpoint!, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" }, + body: new URLSearchParams({ token, token_type_hint: hint, client_id: config.oauthClientId, client_secret: config.oauthClientSecret }), + signal: AbortSignal.timeout(config.upstreamTimeout), + }); + return res.ok; + } catch { + return false; + } + }; + const refreshed = tokens.refresh ? await revoke(tokens.refresh, "refresh_token") : true; + const accessed = await revoke(tokens.access, "access_token"); + return refreshed && accessed; +} + export function needsRefresh(tokens: TokenSet, now = Date.now()): boolean { return tokens.expiresAt - now < REFRESH_MARGIN_MS; } diff --git a/server/src/signout-revoke.test.ts b/server/src/signout-revoke.test.ts new file mode 100644 index 0000000..abae6b3 --- /dev/null +++ b/server/src/signout-revoke.test.ts @@ -0,0 +1,94 @@ +import { test, after, beforeEach } from "node:test"; +import assert from "node:assert/strict"; + +/** + * inbuxa K-W2: signing out revokes the session's tokens at the server. With + * cookie sessions there is nothing on this side to delete, so the revocation + * is what makes a copy of the cookie stop working. + */ + +const PORT = 18821; +process.env.MOCK_PORT = String(PORT); +process.env.MOCK_USER = "demo@example.com"; +process.env.MOCK_PASS = "demo-password"; +process.env.MAIL_SERVER_URL = `http://127.0.0.1:${PORT}`; +process.env.APP_SECRET = "test-secret-for-signout-revoke"; +process.env.OAUTH_CLIENT_SECRET = "mock-oauth-secret"; +process.env.PUBLIC_URL = "https://webmail.example.test"; +process.env.SESSION_BACKEND = "cookie"; + +const mock = await import("./mock/index.js"); +const { oauthMock } = await import("./mock/oauth.js"); +const { createApp, sessions } = await import("./app.js"); +const { resetOAuthState } = await import("./oauth.js"); + +const app = createApp(); + +async function call(path: string, cookie?: string, init: RequestInit = {}) { + return app.request(path, { + ...init, + headers: { "content-type": "application/json", "x-requested-with": "ihasmail", ...(cookie ? { cookie } : {}) }, + }); +} + +function cookieFrom(res: Response, name: string): string | undefined { + for (const header of res.headers.getSetCookie()) { + const pair = header.split(";")[0]!; + if (pair.startsWith(`${name}=`)) return pair.slice(name.length + 1) || undefined; + } + return undefined; +} + +/** Sign in on the mock's page; returns the session cookie as a Cookie header. */ +async function signIn(): Promise { + const start = await call("/api/auth/oauth/start?username=demo%40example.com&remember=1"); + assert.equal(start.status, 302); + const state = cookieFrom(start, "ihm_session_signin"); + const approved = await fetch(new URL(start.headers.get("location")!), { redirect: "manual" }); + const back = new URL(approved.headers.get("location")!); + const res = await call(`/api/auth/callback${back.search}`, state ? `ihm_session_signin=${state}` : undefined); + assert.equal(res.status, 302); + const session = cookieFrom(res, "ihm_session"); + assert.ok(session, "a session cookie was set"); + assert.ok(session!.startsWith("s1."), "a sealed cookie session"); + return `ihm_session=${session}`; +} + +beforeEach(() => { + oauthMock.reset(); + resetOAuthState(); +}); + +after(() => { + (mock as { server?: { close(): void } }).server?.close(); +}); + +test("after sign-out, a copy of the old cookie gets 401", async () => { + assert.equal(sessions.enumerable, false, "cookie sessions"); + const copy = await signIn(); + assert.equal((await call("/api/auth/session", copy)).status, 200); + + const out = await call("/api/auth/logout", copy, { method: "POST" }); + assert.equal(out.status, 200); + assert.equal(oauthMock.revoked.length, 2, "the refresh and the access token were revoked"); + + assert.equal((await call("/api/auth/session", copy)).status, 401, "the copied cookie is dead"); +}); + +test("signing out of every account revokes each one's tokens", async () => { + const copy = await signIn(); + const out = await call("/api/auth/logout-all", copy, { method: "POST" }); + assert.equal(out.status, 200); + assert.equal(oauthMock.revoked.length, 2); + assert.equal((await call("/api/auth/session", copy)).status, 401); +}); + +test("a server without revocation still signs out", async () => { + oauthMock.offerRevocation(false); + const copy = await signIn(); + const out = await call("/api/auth/logout", copy, { method: "POST" }); + assert.equal(out.status, 200, "sign-out doesn't fail"); + assert.equal(oauthMock.revoked.length, 0); + // What revocation is for: without it, the copy works until its tokens expire + assert.equal((await call("/api/auth/session", copy)).status, 200); +}); -- 2.54.0