Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Fix review findings: session limits on auth actions, sign-in audit, backup streams, pinned actions
Claude0320da661c98
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.ymlindex 7a07b95..236c9db 100644--- a/.github/workflows/codeql.yml+++ b/.github/workflows/codeql.yml@@ -3,6 +3,7 @@## Only in the SignuDoc repository itself: a copy made by the Vercel Deploy# button skips it (its owner can turn on CodeQL in their own settings).+# Actions are pinned to a commit, with the version beside it.name: CodeQL@@ -22,6 +23,7 @@ jobs:if: github.repository == 'NYLLON-SOFTWARE/SignuDoc'runs-on: ubuntu-latestpermissions:+ actions: readcontents: readsecurity-events: writestrategy:@@ -29,11 +31,11 @@ jobs:matrix:language: [javascript-typescript, actions]steps:- - uses: actions/checkout@v6- - uses: github/codeql-action/init@v4+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3with:languages: ${{ matrix.language }}queries: security-extended- - uses: github/codeql-action/analyze@v4+ - uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3with:category: /language:${{ matrix.language }}diff --git a/.github/workflows/dependency-audit.yml b/.github/workflows/dependency-audit.ymlindex a007cbf..48805b5 100644--- a/.github/workflows/dependency-audit.yml+++ b/.github/workflows/dependency-audit.yml@@ -35,7 +35,7 @@ jobs:contents: readpull-requests: writesteps:- - uses: actions/dependency-review-action@v4+ - uses: actions/dependency-review-action@2031cfc080254a8a887f58cffee85186f0e49e48 # v4.9.0with:fail-on-severity: highcomment-summary-in-pr: on-failure@@ -46,8 +46,8 @@ jobs:if: github.repository == 'NYLLON-SOFTWARE/SignuDoc' && github.event_name != 'pull_request'runs-on: ubuntu-lateststeps:- - uses: actions/checkout@v6- - uses: actions/setup-node@v6+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0with:node-version-file: .nvmrccache: npmdiff --git a/.github/workflows/release-artifacts.yml b/.github/workflows/release-artifacts.ymlindex 9022c25..6f7f1cb 100644--- a/.github/workflows/release-artifacts.yml+++ b/.github/workflows/release-artifacts.yml@@ -36,11 +36,11 @@ jobs:env:TAG: ${{ github.event.release.tag_name || inputs.tag }}steps:- - uses: actions/checkout@v6+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0with:ref: ${{ env.TAG }}persist-credentials: false- - uses: actions/setup-node@v6+ - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0with:node-version-file: .nvmrccache: npm@@ -53,10 +53,10 @@ jobs:npm sbom --omit=dev --sbom-format=cyclonedx --sbom-type=application > "dist/signudoc-${version}.cdx.json"git archive --format=tar.gz --prefix="signudoc-${version}/" -o "dist/signudoc-${version}.tar.gz" HEAD(cd dist && sha256sum * > SHA256SUMS)- - uses: actions/attest-build-provenance@v2+ - uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0with:subject-path: dist/*- - uses: actions/attest-sbom@v2+ - uses: actions/attest-sbom@bd218ad0dbcb3e146bd073d1d9c6d78e08aa8a0b # v2.4.0with:subject-path: dist/signudoc-${{ env.VERSION }}.tar.gzsbom-path: dist/signudoc-${{ env.VERSION }}.cdx.jsondiff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.ymlindex c452307..8ffff28 100644--- a/.github/workflows/scorecard.yml+++ b/.github/workflows/scorecard.yml@@ -26,14 +26,14 @@ jobs:id-token: writesecurity-events: writesteps:- - uses: actions/checkout@v6+ - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0with:persist-credentials: false- - uses: ossf/[email protected]+ - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0with:results_file: results.sarifresults_format: sarifpublish_results: true- - uses: github/codeql-action/upload-sarif@v4+ - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3with:sarif_file: results.sarifdiff --git a/docs/backup-and-restore.md b/docs/backup-and-restore.mdindex ffc54b8..8f31fca 100644--- a/docs/backup-and-restore.md+++ b/docs/backup-and-restore.md@@ -50,7 +50,7 @@ You need a computer with Node.js 24 and a copy of this repository at the same venpm run restore-backup # restore the newest one```- `--backup database/<name>` restores an older one instead. The script applies the migrations, loads the database in one transaction (so a failed restore leaves nothing half done), then copies the files back to their own paths. It refuses a database that already has accounts in it, and a backup made by a newer SignuDoc than the copy you are running.+ `--backup database/<name>` restores an older one instead. The script applies the migrations, loads the database in one transaction (so a failed restore leaves nothing half done), then copies the files back to their own paths. It refuses a database that already has accounts in it, and a backup made by a newer SignuDoc than the copy you are running. If copying the files stops part way (a network error, or you stopped it), run `npm run restore-backup -- --files-only` to finish: it skips the database and every file that is already there.4. Connect the new database and Blob store to the install's Vercel project (or a new one) in place of the old ones, keep `BETTER_AUTH_SECRET` the same as before, and deploy. Two-step sign-in keys are encrypted with that secret, and session cookies are signed with it; if it changes, everyone signs in again and sets up two-step sign-in again.5. Sign in, open a finished document, and check its audit trail and download.diff --git a/scripts/restore-backup.ts b/scripts/restore-backup.tsindex 86c868f..8db1458 100644--- a/scripts/restore-backup.ts+++ b/scripts/restore-backup.ts@@ -9,6 +9,8 @@// npm run restore-backup restore the newest one, and the files// npm run restore-backup -- --backup <path> restore that one// npm run restore-backup -- --skip-files the database only+// npm run restore-backup -- --files-only the files only, for example to+// finish a copy that stopped//// It applies the migrations first, then loads the backup in one transaction,// so a restore that fails leaves the database as it was.@@ -64,48 +66,61 @@ async function main() {return;}- const connectionString = requireVariable("DATABASE_URL");- const appStore = process.argv.includes("--skip-files")- ? null- : createVercelBlobStore(requireVariable("BLOB_READ_WRITE_TOKEN"));- const backupPath =- readArgument("--backup") ?? (await findLatestDatabaseBackup(backupStore));+ const filesOnly = process.argv.includes("--files-only");+ const skipFiles = process.argv.includes("--skip-files");- if (!backupPath) {- console.error("The backup store has no database backups yet.");+ if (filesOnly && skipFiles) {+ console.error("Choose --files-only or --skip-files, not both.");process.exit(1);}- console.log("Applying migrations…");- await runMigrations({ connectionString });+ const appStore = skipFiles+ ? null+ : createVercelBlobStore(requireVariable("BLOB_READ_WRITE_TOKEN"));++ if (!filesOnly) {+ const connectionString = requireVariable("DATABASE_URL");+ const backupPath =+ readArgument("--backup") ?? (await findLatestDatabaseBackup(backupStore));- const database = new pg.Pool({ connectionString, max: 2 });+ if (!backupPath) {+ console.error("The backup store has no database backups yet.");+ process.exit(1);+ }- try {- console.log(`Restoring ${backupPath}…`);+ console.log("Applying migrations…");+ await runMigrations({ connectionString });- const { rows } = await restoreDatabase({- backupPath,- database,- store: backupStore,- });+ const database = new pg.Pool({ connectionString, max: 2 });++ try {+ console.log(`Restoring ${backupPath}…`);- for (const [table, count] of Object.entries(rows)) {- console.log(` ${table}: ${String(count)} rows`);+ const { rows } = await restoreDatabase({+ backupPath,+ database,+ store: backupStore,+ });++ for (const [table, count] of Object.entries(rows)) {+ console.log(` ${table}: ${String(count)} rows`);+ }+ } finally {+ await database.end();}- } finally {- await database.end();}if (appStore) {console.log("Copying files…");- const { copied, failures } = await restoreFiles({+ const { copied, failures, skipped } = await restoreFiles({source: backupStore,target: appStore,});- console.log(` ${String(copied)} files copied.`);+ console.log(+ ` ${String(copied)} files copied, ${String(skipped)} already there.`,+ );if (failures.length > 0) {console.error(` ${String(failures.length)} could not be copied:`);@@ -114,6 +129,9 @@ async function main() {console.error(` ${pathname}`);}+ console.error(+ " Run it again with --files-only to retry them; files already copied are skipped.",+ );process.exitCode = 1;}}diff --git a/src/app/api/admin/security/route.ts b/src/app/api/admin/security/route.tsindex 3c90c8b..b71bf05 100644--- a/src/app/api/admin/security/route.ts+++ b/src/app/api/admin/security/route.ts@@ -48,11 +48,15 @@ export async function PUT(request: Request) {return rateLimitResponse;}- const body = (await request.json().catch(() => null)) as {- requireTwoFactor?: unknown;- sessionIdleMinutes?: unknown;- sessionMaxHours?: unknown;- } | null;+ const parsed: unknown = await request.json().catch(() => null);+ const body =+ typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)+ ? (parsed as {+ requireTwoFactor?: unknown;+ sessionIdleMinutes?: unknown;+ sessionMaxHours?: unknown;+ })+ : null;const changesRequirement = typeof body?.requireTwoFactor === "boolean";const changesSessions =body !== null &&diff --git a/src/lib/auth/sign-in-events.ts b/src/lib/auth/sign-in-events.tsindex a9d2216..554fb59 100644--- a/src/lib/auth/sign-in-events.ts+++ b/src/lib/auth/sign-in-events.ts@@ -8,7 +8,8 @@ import {import { getDb, queryOne } from "../db/connection.ts";import { logSecurityEvent } from "../security/logging.ts";-import { getSettings } from "../settings.ts";+import { enforceSessionLimits } from "../session-controls.ts";+import { getSettings, isMissingSchemaError } from "../settings.ts";import {getClientIpAddress,getRequestUserAgent,@@ -59,6 +60,25 @@ const SESSION_FIRST_EVENTS: Record<string, SystemAuditEventType> = {"/two-factor/generate-backup-codes": "two_factor_backup_codes_regenerated",};+// Paths that do not act on the caller's session, so a stale one does not+// stand in their way: signing in again, or reading the session (the app's+// own session check in auth/server.ts applies the limits to that).+function skipsSessionLimits(path: string): boolean {+ return (+ path === "/get-session" ||+ path === "/sign-out" ||+ path === "/ok" ||+ path === "/error" ||+ path === "/request-password-reset" ||+ path === "/verify-email" ||+ path.startsWith("/reset-password") ||+ path.startsWith("/sign-in/") ||+ path.startsWith("/sign-up/") ||+ path.startsWith("/callback/") ||+ path.startsWith("/oauth2/callback/")+ );+}+type Actor = { email: string; userId: string };type HookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];@@ -158,11 +178,95 @@ async function record(export function signInEvents() {const sessionActors = new WeakMap<Request, Actor>();+ // Whether a second-step check came with a signed-in session (someone+ // confirming the authenticator they are setting up) or not (the second+ // step of a sign-in). A leftover challenge cookie does not decide it.+ const secondStepWithSession = new WeakMap<Request, boolean>();return {id: "signudoc-sign-in-events",hooks: {before: [+ {+ // The install's session limits (session-controls.ts) apply to the+ // auth server's own account actions too: changing a password or+ // email, managing two-step sign-in, listing sessions. Without+ // this, the signed cookie cache would let an ended or expired+ // session use them for a few more minutes.+ matcher: (ctx) => !skipsSessionLimits(ctx.path ?? ""),+ handler: createAuthMiddleware(async (ctx) => {+ const session = await getSessionFromCtx(ctx).catch(() => null);++ if (!session) {+ return;+ }++ let allowed = true;++ try {+ allowed = await enforceSessionLimits(+ session.session.token,+ await getSettings(),+ );+ } catch (error) {+ if (!isMissingSchemaError(error)) {+ throw error;+ }+ }++ if (!allowed) {+ throw new APIError("UNAUTHORIZED", {+ code: "SESSION_ENDED",+ message: "Your session has ended. Sign in again.",+ });+ }+ }),+ },+ {+ // Single sign-on goes through the provider's sign-in page and back+ // to /callback/sso, where it is recorded. Better Auth would also+ // take an ID token posted straight to /sign-in/social; the app+ // never does that, so it is refused rather than left unaudited.+ matcher: (ctx) => ctx.path === "/sign-in/social",+ handler: createAuthMiddleware(async (ctx) => {+ if (+ typeof ctx.body === "object" &&+ ctx.body !== null &&+ "idToken" in ctx.body &&+ ctx.body.idToken+ ) {+ throw new APIError("BAD_REQUEST", {+ code: "ID_TOKEN_SIGN_IN_NOT_ALLOWED",+ message: "Sign in through your organization's sign-in page.",+ });+ }+ }),+ },+ {+ // A device that skips the second step would make "two-step+ // sign-in required" untrue, so devices are never trusted.+ matcher: (ctx) => SECOND_STEP_PATHS.has(ctx.path ?? ""),+ handler: createAuthMiddleware(async (ctx) => {+ if (+ typeof ctx.body === "object" &&+ ctx.body !== null &&+ "trustDevice" in ctx.body &&+ ctx.body.trustDevice+ ) {+ throw new APIError("BAD_REQUEST", {+ code: "TRUST_DEVICE_NOT_ALLOWED",+ message:+ "This install asks for the second step at every sign-in.",+ });+ }++ if (ctx.request) {+ const session = await getSessionFromCtx(ctx).catch(() => null);++ secondStepWithSession.set(ctx.request, session !== null);+ }+ }),+ },{matcher: (ctx) => ctx.path === "/sign-in/email",handler: createAuthMiddleware(async (ctx) => {@@ -239,7 +343,14 @@ export function signInEvents() {}if (SECOND_STEP_PATHS.has(path)) {- await afterSecondStep(ctx, returned, failed);+ await afterSecondStep(+ ctx,+ returned,+ failed,+ ctx.request+ ? secondStepWithSession.get(ctx.request)+ : undefined,+ );return;}@@ -420,6 +531,7 @@ async function afterSecondStep(ctx: HookContext,returned: unknown,failed: boolean,+ withSession: boolean | undefined,) {const challengeCookie = await ctx.getSignedCookie(@@ -433,7 +545,9 @@ async function afterSecondStep(: "authenticator";// A signed-in person confirming the authenticator they are setting up.- if (!challengeCookie) {+ // Better Auth treats any check made with a session that way, whatever+ // challenge cookie is left over from an earlier sign-in.+ if (withSession ?? !challengeCookie) {const user = readUser(returned);if (diff --git a/src/lib/auth/sso.dbtest.ts b/src/lib/auth/sso.dbtest.tsindex 3d6588c..6636a64 100644--- a/src/lib/auth/sso.dbtest.ts+++ b/src/lib/auth/sso.dbtest.ts@@ -313,12 +313,15 @@ beforeEach(async () => {});after(async () => {- await database.query(`truncate public."user" cascade`);- await database.query("delete from public.system_audit_events");- await database.query("delete from public.app_settings");- replaceDbPoolForTests(replaced ?? database);- await database.end();- provider.close();+ try {+ await database.query(`truncate public."user" cascade`);+ await database.query("delete from public.system_audit_events");+ await database.query("delete from public.app_settings");+ replaceDbPoolForTests(replaced ?? database);+ await database.end();+ } finally {+ provider?.close();+ }});test("a first sign-in through the identity provider makes a verified account and is audited", async () => {@@ -541,3 +544,29 @@ test("requiring two-step sign-in does not hold up someone who only uses single strue,);});++test("an ID token posted straight to the sign-in route is refused, not signed in unaudited", async () => {+ const auth = await makeAuth();+ const token = await signIdToken(+ {+ email: "[email protected]",+ email_verified: true,+ name: "Pat Person",+ sub: "okta-pat",+ },+ null,+ );+ const result = await post(auth, "/sign-in/social", {+ idToken: { token },+ provider: "sso",+ });++ assert.equal(result.status, 400);+ assert.equal(result.payload?.code, "ID_TOKEN_SIGN_IN_NOT_ALLOWED");++ const accounts = await database.query(+ `select 1 from "user" where email = '[email protected]'`,+ );++ assert.equal(accounts.rowCount, 0);+});diff --git a/src/lib/backup.dbtest.ts b/src/lib/backup.dbtest.tsindex ae4559e..50050d1 100644--- a/src/lib/backup.dbtest.ts+++ b/src/lib/backup.dbtest.ts@@ -316,3 +316,95 @@ test("copying stops at the deadline and the next run carries on", async () => {assert.equal(resumed.filesCopied, 3);});++test("text outside ASCII comes back whole, even where it spans two chunks", async () => {+ // Long enough that the decompressed backup reaches the reader in several+ // chunks, with two-byte and four-byte characters across their edges.+ const name = "Zoë Ångström 名前 🖋️ ".repeat(6000);+ const id = randomUUID();++ await database.query(+ `insert into "user" (id, name, email, "emailVerified", role) values ($1, $2, '[email protected]', true, 'admin')`,+ [id, name],+ );++ const target = memoryStore();+ const summary = await runBackup({+ database,+ keepDays: 30,+ source: memoryStore(),+ target,+ });++ await clearTables();+ await restoreDatabase({+ backupPath: summary.databaseBackup,+ database,+ store: target,+ });++ const restored = await database.query<{ name: string }>(+ `select name from "user" where id = $1`,+ [id],+ );++ assert.equal(restored.rows[0]?.name, name);+});++test("a database that cannot be read fails the backup instead of hanging it", async () => {+ const broken = {+ connect: () => Promise.reject(new Error("connection refused")),+ } as unknown as pg.Pool;++ await assert.rejects(+ runBackup({+ database: broken,+ keepDays: 30,+ source: memoryStore(),+ target: memoryStore(),+ }),+ /connection refused/,+ );+});++test("a manifest that cannot be read stops the run rather than starting over", async () => {+ const target = memoryStore();++ await target.put("manifest.json", "{ not json", {+ contentType: "application/json",+ });++ await assert.rejects(+ runBackup({+ database,+ keepDays: 30,+ source: memoryStore(),+ target,+ }),+ SyntaxError,+ );+ assert.equal(+ target.objects.get("manifest.json")?.body.toString(),+ "{ not json",+ );+});++test("copying files back skips the ones a stopped run already copied", async () => {+ const backup = memoryStore();+ const app = memoryStore();++ await backup.put("files/a.pdf", Buffer.from("aaa"), {+ contentType: "application/pdf",+ });+ await backup.put("files/b.pdf", Buffer.from("bbb"), {+ contentType: "application/pdf",+ });+ await app.put("a.pdf", Buffer.from("aaa"), {+ contentType: "application/pdf",+ });++ const result = await restoreFiles({ source: backup, target: app });++ assert.deepEqual(result, { copied: 1, failures: [], skipped: 1 });+ assert.equal(app.objects.get("b.pdf")?.body.toString(), "bbb");+});diff --git a/src/lib/backup.ts b/src/lib/backup.tsindex 85eb652..210df6d 100644--- a/src/lib/backup.ts+++ b/src/lib/backup.ts@@ -1,4 +1,5 @@import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";import { createGunzip, createGzip } from "node:zlib";import { del, get, list, put } from "@vercel/blob";@@ -313,21 +314,20 @@ type Manifest = {version: 1;};+// Only a manifest that is not there yet starts empty. One that cannot be+// read stops the run: starting over would restart the clock on every+// deleted file, and keep them past BACKUP_KEEP_DAYS.async function readManifest(store: BackupStore): Promise<Manifest> {- const found = await store.get(MANIFEST_PATH).catch(() => null);+ const found = await store.get(MANIFEST_PATH);if (!found) {return { missingSince: {}, version: 1 };}- try {- const text = await new Response(found.stream).text();- const parsed = JSON.parse(text) as Partial<Manifest>;+ const text = await new Response(found.stream).text();+ const parsed = JSON.parse(text) as Partial<Manifest>;- return { missingSince: parsed.missingSince ?? {}, version: 1 };- } catch {- return { missingSince: {}, version: 1 };- }+ return { missingSince: parsed.missingSince ?? {}, version: 1 };}export type BackupSummary = {@@ -360,11 +360,14 @@ export async function runBackup({// 1. The database.const databaseBackup = databaseBackupPath(now);- await target.put(- databaseBackup,- Readable.from(exportDatabaseLines(database, now)).pipe(createGzip()),- { contentType: "application/gzip" },- );+ // pipeline() passes a failed export on to the upload, so it ends with+ // that error rather than waiting for data that will not come.+ const compressed = createGzip();++ await Promise.all([+ pipeline(Readable.from(exportDatabaseLines(database, now)), compressed),+ target.put(databaseBackup, compressed, { contentType: "application/gzip" }),+ ]);const cutoff = now.getTime() - keepDays * DAY_MS;const databaseCopies = (await listAll(target, DATABASE_PREFIX)).sort((a, b) =>@@ -479,14 +482,22 @@ export async function* readDatabaseBackup(}| { kind: "row"; row: unknown; table: string }> {- const lines = Readable.fromWeb(- stream as import("node:stream/web").ReadableStream,- ).pipe(createGunzip());+ const lines = createGunzip();++ // A read error ends the loop below with that error.+ pipeline(+ Readable.fromWeb(stream as import("node:stream/web").ReadableStream),+ lines,+ ).catch(() => {});+ // Decoded as one stream, so a character split between two chunks stays+ // whole.+ lines.setEncoding("utf8");+let buffered = "";let first = true;for await (const chunk of lines) {- buffered += (chunk as Buffer).toString("utf8");+ buffered += chunk as string;let newline = buffered.indexOf("\n");@@ -654,12 +665,23 @@ export async function restoreFiles({}: {source: BackupStore;target: BackupStore;-}): Promise<{ copied: number; failures: string[] }> {+}): Promise<{ copied: number; failures: string[]; skipped: number }> {const copies = await listAll(source, FILES_PREFIX);+ // A file already there at the same size was copied by an earlier run that+ // stopped part way, so running it again carries on from there.+ const present = new Map(+ (await listAll(target)).map((blob) => [blob.pathname, blob.size]),+ );const failures: string[] = [];let copied = 0;+ let skipped = 0;for (const copy of copies) {+ if (present.get(copy.pathname.slice(FILES_PREFIX.length)) === copy.size) {+ skipped += 1;+ continue;+ }+try {const found = await source.get(copy.pathname);@@ -677,5 +699,5 @@ export async function restoreFiles({}}- return { copied, failures };+ return { copied, failures, skipped };}diff --git a/src/lib/sign-in-security.dbtest.ts b/src/lib/sign-in-security.dbtest.tsindex 85b1ce8..0791171 100644--- a/src/lib/sign-in-security.dbtest.ts+++ b/src/lib/sign-in-security.dbtest.ts@@ -553,3 +553,107 @@ test("session limits end idle and old sessions, and record use", async () => {assert.equal(gone.rowCount, 0);assert.equal(await enforceSessionLimits(token, limits, { database }), false);});++test("an ended session cannot use the auth server's account actions, even with its cookie cache", async () => {+ const userId = await createVerifiedUser("[email protected]");+ const session = await signIn("[email protected]");++ // Signed out everywhere from another device: the row is gone, but the+ // signed cookie cache still vouches for the session for a few minutes.+ await database.query(`delete from session where "userId" = $1`, [userId]);++ const changed = await call(+ "/change-password",+ { currentPassword: PASSWORD, newPassword: `${PASSWORD} again` },+ session.cookies,+ );++ assert.equal(changed.status, 401, JSON.stringify(changed.payload));+ assert.equal(changed.payload?.code, "SESSION_ENDED");+ assert.equal((await events("password_changed")).length, 0);++ // Past the install's idle limit, the same.+ const later = await signIn("[email protected]");++ await saveSettings({ sessionIdleMinutes: 15 }, database);+ invalidateSettingsCache();+ await database.query(+ `update session set last_active_at = extract(epoch from now())::int - 3600 where "userId" = $1`,+ [userId],+ );++ const enabled = await call(+ "/two-factor/enable",+ { password: PASSWORD },+ later.cookies,+ );++ assert.equal(enabled.status, 401, JSON.stringify(enabled.payload));++ // Signing in again is never in the way.+ assert.equal((await signIn("[email protected]")).status, 200);+});++test("a device is never trusted to skip the second step", async () => {+ await createVerifiedUser("[email protected]");++ const { totpURI } = await enableTwoFactor("[email protected]");+ const first = await signIn("[email protected]");+ const trusted = await call(+ "/two-factor/verify-totp",+ { code: totp(totpURI), trustDevice: true },+ first.cookies,+ );++ assert.equal(trusted.status, 400);+ assert.equal(trusted.payload?.code, "TRUST_DEVICE_NOT_ALLOWED");+ assert.equal(+ [...first.cookies.keys()].some((name) => name.includes("trust_device")),+ false,+ );+});++test("confirming an authenticator with a leftover challenge cookie is recorded as set-up, not a sign-in", async () => {+ const userId = await createVerifiedUser("[email protected]");++ // A challenge cookie left over from a sign-in that was never finished,+ // before an administrator reset this person's two-step sign-in.+ await enableTwoFactor("[email protected]");++ const abandoned = await signIn("[email protected]");++ assert.equal(abandoned.payload?.twoFactorRedirect, true);+ await database.query(+ `update "user" set "twoFactorEnabled" = false where id = $1`,+ [userId],+ );+ await database.query(`delete from "twoFactor" where "userId" = $1`, [userId]);+ await database.query("delete from public.system_audit_events");++ const session = await signIn("[email protected]");++ for (const [name, value] of abandoned.cookies) {+ if (name.includes("two_factor")) {+ session.cookies.set(name, value);+ }+ }++ const enabled = await call(+ "/two-factor/enable",+ { password: PASSWORD },+ session.cookies,+ );++ assert.equal(enabled.status, 200, JSON.stringify(enabled.payload));++ const before = (await events("sign_in_succeeded")).length;+ const verified = await call(+ "/two-factor/verify-totp",+ { code: totp(String(enabled.payload?.totpURI)) },+ session.cookies,+ );++ assert.equal(verified.status, 200, JSON.stringify(verified.payload));+ assert.equal((await events("two_factor_enabled"))[0]?.actorUserId, userId);+ assert.equal((await events("sign_in_succeeded")).length, before);+});diff --git a/src/proxy.ts b/src/proxy.tsindex 4a98652..b08f169 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -1,9 +1,7 @@import type { NextRequest } from "next/server";-import { getCookieCache } from "better-auth/cookies";import { NextResponse } from "next/server";import { supportsDirectUploads } from "@/lib/services/storage/driver";-import { resolveAuthSecret, resolveAuthUrl } from "@/lib/utils/env";const DEFAULT_PERMISSIONS_POLICY = ["accelerometer=()",@@ -154,73 +152,15 @@ function applySecurityHeaders(response: NextResponse, pathname: string) {return response;}-// True only for a session the auth server would accept without looking it-// up: its signed, short-lived copy in the cookie cache. The session token-// cookie on its own proves nothing. It outlives a session that was signed-// out elsewhere, expired, or belongs to a database that has been replaced,-// and sending such a visitor to the dashboard would bounce them straight-// back here, forever. Someone signed in whose cached copy has run out is-// sent on by the page itself, which asks the auth server.-async function hasVerifiedSession(request: NextRequest) {- // Resolved the same way the auth server does, so this keeps working when- // the secret is derived rather than set.- const secret = resolveAuthSecret();-- if (!secret) {- return false;- }-- try {- const session = await getCookieCache(request, {- isSecure: resolveAuthUrl()?.startsWith("https://") ?? false,- secret,- });-- return session !== null;- } catch {- return false;- }-}+// The sign-in and sign-up pages send someone already signed in on to their+// documents themselves (redirectIfSignedIn), after asking the auth server.+// This proxy does not: the cookie cache can still vouch for a session for a+// few minutes after it was ended or passed the install's session limits,+// and trusting it here would bounce that visitor between /login and+// /dashboard until it ran out.-async function maybeRedirectAuthenticatedAuthRoute(request: NextRequest) {+export function proxy(request: NextRequest) {const pathname = request.nextUrl.pathname;-- if (pathname !== "/login" && pathname !== "/signup") {- return null;- }-- if (pathname === "/login") {- const hasResetState =- request.nextUrl.searchParams.has("token") ||- request.nextUrl.searchParams.has("error");-- if (hasResetState) {- return null;- }- }-- const hasSession = await hasVerifiedSession(request);-- if (!hasSession) {- return null;- }-- const dashboardUrl = request.nextUrl.clone();-- dashboardUrl.pathname = "/dashboard";- dashboardUrl.search = "";-- return NextResponse.redirect(dashboardUrl);-}--export async function proxy(request: NextRequest) {- const pathname = request.nextUrl.pathname;- const authRedirect = await maybeRedirectAuthenticatedAuthRoute(request);-- if (authRedirect) {- return applySecurityHeaders(authRedirect, pathname);- }-return applySecurityHeaders(NextResponse.next(), pathname);}