Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Add session limits and sign out everywhere

Claudeaf3c1fd9d151
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb478e8..403719e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,12 @@ release says when it does.
- Administrators can require two-step sign-in of everyone (Settings,
Organization, Sign-in security), and reset it for someone who lost their
phone (People).
+- Session limits: administrators can sign people out after a time without
+ use (15 minutes to 8 hours) and at the latest a set time after sign-in
+ (8 hours to 3 days). Anyone can sign out on every device at once.
+- A session that was ended (signed out everywhere, or reset by an
+ administrator) stops working at once, not when the short-lived session
+ cookie runs out.
- Ten wrong passwords for one email address within 15 minutes stop sign-in
for that address for 15 minutes.
- The site audit trail now records sign-ins, failed sign-ins, lockouts,
@@ -24,8 +30,8 @@ release says when it does.
to the new Sign-in security panel, and is there whether or not Part 11
mode is on.
-This release changes the database (`20261117090000_sign_in_security.sql`),
-which the production build applies.
+This release changes the database (`20261117090000_sign_in_security.sql`,
+`20261117100000_session_controls.sql`), which the production build applies.
## [0.2.1] - 2026-11-16
diff --git a/db/migrations/20261117100000_session_controls.sql b/db/migrations/20261117100000_session_controls.sql
new file mode 100644
index 0000000..0075493
--- /dev/null
+++ b/db/migrations/20261117100000_session_controls.sql
@@ -0,0 +1,19 @@
+-- Session controls: how long a signed-in session may sit unused, and how
+-- long it may last at most, both set by an administrator.
+--
+-- * session.last_active_at: when the session was last used, in seconds,
+-- written at most once a minute. Null until the first use after this
+-- migration, which counts from when the session was created.
+-- * app_settings.session_idle_minutes: minutes without use before a session
+-- ends. Null means sessions do not end for being idle.
+-- * app_settings.session_max_hours: hours after sign-in when a session ends
+-- whatever happens. Null means Better Auth's 7 days.
+
+alter table public.session
+ add column if not exists last_active_at bigint;
+
+alter table public.app_settings
+ add column if not exists session_idle_minutes integer
+ check (session_idle_minutes is null or session_idle_minutes between 5 and 1440),
+ add column if not exists session_max_hours integer
+ check (session_max_hours is null or session_max_hours between 1 and 168);
diff --git a/docs/part11/known-gaps.md b/docs/part11/known-gaps.md
index ac02d1e..7343dbf 100644
--- a/docs/part11/known-gaps.md
+++ b/docs/part11/known-gaps.md
@@ -2,14 +2,13 @@
What Part 11 mode does not do yet, and what to do instead. These are also listed in the [risk assessment](risk-assessment.md).
-| Gap | Part 11 | What to do for now |
-| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
-| **No idle timeout.** A signed-in session lasts up to 7 days. Each signature needs the password again, but someone at an unlocked computer could see records. | 11.200(a)(1)(ii), 11.10(d) | Screen lock by policy and device management (SOP-2). |
-| **No password aging or reuse rules.** Passwords need 15 or more characters and are checked against breach lists, but they never expire. | 11.300(b) | Set a change interval in SOP-2 if your organization requires one. |
-| **No biometrics or passkeys.** Signing uses email and password. | 11.200(b) | Not needed: email and password meet 11.200(a). |
-| **No signature meaning on templates.** A draft made from a template needs a meaning chosen for each signer before it can be sent. | none | The send is refused until each meaning is chosen, so nothing goes out without one. |
-| **Full database access can rewrite the audit chain** consistently. | 11.10(e) | Limit database access, and file audit exports outside the database (SOP-5). |
-| **No built-in backup of the PDFs** in Vercel Blob. | 11.10(c) | Copy the Blob store on a schedule, and test a restore (SOP-5). |
-| **Signers outside your organization** need an account on your install, and an administrator must confirm who they are. | 11.100 | Fine for staff. For outside parties, decide whether this is workable or keep those records out of Part 11 mode. |
+| Gap | Part 11 | What to do for now |
+| --------------------------------------------------------------------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------- |
+| **No password aging or reuse rules.** Passwords need 15 or more characters and are checked against breach lists, but they never expire. | 11.300(b) | Set a change interval in SOP-2 if your organization requires one. |
+| **No biometrics or passkeys.** Signing uses email and password. | 11.200(b) | Not needed: email and password meet 11.200(a). |
+| **No signature meaning on templates.** A draft made from a template needs a meaning chosen for each signer before it can be sent. | none | The send is refused until each meaning is chosen, so nothing goes out without one. |
+| **Full database access can rewrite the audit chain** consistently. | 11.10(e) | Limit database access, and file audit exports outside the database (SOP-5). |
+| **No built-in backup of the PDFs** in Vercel Blob. | 11.10(c) | Copy the Blob store on a schedule, and test a restore (SOP-5). |
+| **Signers outside your organization** need an account on your install, and an administrator must confirm who they are. | 11.100 | Fine for staff. For outside parties, decide whether this is workable or keep those records out of Part 11 mode. |
Suggestions and fixes are welcome on the project's GitHub.
diff --git a/docs/part11/risk-assessment.md b/docs/part11/risk-assessment.md
index 5b29348..ca95d85 100644
--- a/docs/part11/risk-assessment.md
+++ b/docs/part11/risk-assessment.md
@@ -7,20 +7,20 @@ A starting risk assessment for SignuDoc in Part 11 mode. Score each risk for you
**Detectability** (D): 1 = would certainly be found, 5 = would probably not be found.
A risk priority (S × L × D) of 27 or more needs a further control or a documented acceptance.
-| # | Risk | Controls in SignuDoc | Controls you add | S | L | D | RPN |
-| --- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | --- | --- | --- | --- |
-| R1 | Someone signs as another person. | Own account and password at open and at signing. An admin confirms identity. Lock after 5 wrong passwords, with admin alert. | Identity check procedure, no shared passwords, training. Investigate every lock. | 5 | 1 | 3 | 15 |
-| R2 | A signer's identity confirmation is wrong. | Admin must record how they checked. The confirmation is in the install audit trail. | Two-person check for identity confirmation. Periodic review of confirmed accounts. | 5 | 2 | 3 | 30 |
-| R3 | A record is changed after signing. | Sealed PDF. The verify page checks a copy against the stored hash. | Keep the signed PDF with the record. Check copies on the verify page when in doubt. | 5 | 1 | 1 | 5 |
-| R4 | An audit trail entry is changed or deleted in the database. | Hash chain over every entry, checked on screen and in every CSV export. | Restrict database access to named people. Export and file audit trails at each review. | 5 | 1 | 2 | 10 |
-| R5 | A database administrator rewrites the whole chain consistently. | None: someone with full database access can recompute hashes. | Keep exported CSVs outside the database (they carry the hashes at that time). Limit and log Neon console access. | 5 | 1 | 4 | 20 |
-| R6 | A record is deleted early. | Part 11 records are skipped by the retention timer and by data requests. A retention period can't be set in Part 11 mode. | Back up the database and storage. Control who can close accounts or delete by hand. | 5 | 1 | 3 | 15 |
-| R7 | Records are lost when a service fails or an account lapses. | None in the software. | Neon backups or point-in-time restore, a Blob copy, and supplier review ([Suppliers](suppliers.md)). Keep billing current. | 5 | 2 | 2 | 20 |
-| R8 | Part 11 mode is turned off by mistake. | Admin only, recorded in the install audit trail. Records already sent keep their rules. | Audit review procedure checks for `part11_mode_changed`. | 3 | 2 | 2 | 12 |
-| R9 | The signature meaning is wrong for the record. | The sender chooses it, and the signer sees and confirms it before signing. | Procedure says which meaning each record type needs. | 3 | 2 | 3 | 18 |
-| R10 | A session left open is used by someone else. | Each signature needs the password again. App sessions last up to 7 days. | Lock screens when away, by policy. See [Known gaps](known-gaps.md). | 3 | 2 | 3 | 18 |
-| R11 | A new SignuDoc version breaks a control. | Automated tests on every change, including a Part 11 browser test. | Change control: review, re-run the OQ for changed areas, approve before use. | 5 | 2 | 2 | 20 |
-| R12 | Clock error makes times wrong. | Times come from the server (Vercel) and are written in UTC. | Note the time source in the IQ. | 3 | 1 | 3 | 9 |
-| R13 | Emails (invitations, lock alerts) don't arrive. | Delivery is tracked, and the Email panel shows a failing address. | Check the Email panel in the IQ. Admins check People for locks during audit review. | 2 | 2 | 2 | 8 |
+| # | Risk | Controls in SignuDoc | Controls you add | S | L | D | RPN |
+| --- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | --- | --- | --- | --- |
+| R1 | Someone signs as another person. | Own account and password at open and at signing. An admin confirms identity. Lock after 5 wrong passwords, with admin alert. | Identity check procedure, no shared passwords, training. Investigate every lock. | 5 | 1 | 3 | 15 |
+| R2 | A signer's identity confirmation is wrong. | Admin must record how they checked. The confirmation is in the install audit trail. | Two-person check for identity confirmation. Periodic review of confirmed accounts. | 5 | 2 | 3 | 30 |
+| R3 | A record is changed after signing. | Sealed PDF. The verify page checks a copy against the stored hash. | Keep the signed PDF with the record. Check copies on the verify page when in doubt. | 5 | 1 | 1 | 5 |
+| R4 | An audit trail entry is changed or deleted in the database. | Hash chain over every entry, checked on screen and in every CSV export. | Restrict database access to named people. Export and file audit trails at each review. | 5 | 1 | 2 | 10 |
+| R5 | A database administrator rewrites the whole chain consistently. | None: someone with full database access can recompute hashes. | Keep exported CSVs outside the database (they carry the hashes at that time). Limit and log Neon console access. | 5 | 1 | 4 | 20 |
+| R6 | A record is deleted early. | Part 11 records are skipped by the retention timer and by data requests. A retention period can't be set in Part 11 mode. | Back up the database and storage. Control who can close accounts or delete by hand. | 5 | 1 | 3 | 15 |
+| R7 | Records are lost when a service fails or an account lapses. | None in the software. | Neon backups or point-in-time restore, a Blob copy, and supplier review ([Suppliers](suppliers.md)). Keep billing current. | 5 | 2 | 2 | 20 |
+| R8 | Part 11 mode is turned off by mistake. | Admin only, recorded in the install audit trail. Records already sent keep their rules. | Audit review procedure checks for `part11_mode_changed`. | 3 | 2 | 2 | 12 |
+| R9 | The signature meaning is wrong for the record. | The sender chooses it, and the signer sees and confirms it before signing. | Procedure says which meaning each record type needs. | 3 | 2 | 3 | 18 |
+| R10 | A session left open is used by someone else. | Each signature needs the password again. An administrator can end sessions after a time without use and cap their length (Settings, Organization, Sign-in security). | Set an idle timeout. Lock screens when away, by policy. | 3 | 2 | 3 | 18 |
+| R11 | A new SignuDoc version breaks a control. | Automated tests on every change, including a Part 11 browser test. | Change control: review, re-run the OQ for changed areas, approve before use. | 5 | 2 | 2 | 20 |
+| R12 | Clock error makes times wrong. | Times come from the server (Vercel) and are written in UTC. | Note the time source in the IQ. | 3 | 1 | 3 | 9 |
+| R13 | Emails (invitations, lock alerts) don't arrive. | Delivery is tracked, and the Email panel shows a failing address. | Check the Email panel in the IQ. Admins check People for locks during audit review. | 2 | 2 | 2 | 8 |
Reviewed by `[name, role]`, approved by `[name, role]`, on `[date]`.
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 329aa05..3295d19 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -160,7 +160,8 @@ These cover the people with an account (senders and administrators). Signers who
- **Two-step sign-in.** Anyone can turn it on under Settings, Two-step sign-in: after the password, the site asks for a 6-digit code from an authenticator app such as 1Password, Google Authenticator or Microsoft Authenticator. Setting it up gives ten single-use backup codes for when the phone is not at hand. The key and the backup codes are stored encrypted with `BETTER_AUTH_SECRET`, so keep that secret the same: a new one makes every authenticator stop working.
- **Requiring it.** An administrator can require two-step sign-in of everyone under Settings, Organization, Sign-in security. They have to use it themselves first. From then on anyone who has not set it up sees only the setup page until they have, the API refuses their requests too, and nobody can turn theirs off.
-- **Lost phone.** If someone loses their phone and their backup codes, an administrator can reset their two-step sign-in under People. That turns it off and signs them out everywhere; they sign in with their password and set it up again (at once, if it is required). A session lasts until it ends or, at most, five minutes after it was reset, because sessions are briefly cached in a signed cookie.
+- **Lost phone.** If someone loses their phone and their backup codes, an administrator can reset their two-step sign-in under People. That turns it off and signs them out everywhere at once; they sign in with their password and set it up again (at once, if it is required).
+- **Sessions.** A session lasts 7 days by default. Under Settings, Organization, Sign-in security an administrator can sign people out after 15 minutes to 8 hours without use, and at the latest 8 hours to 3 days after they signed in. A change applies to sessions that are already open, from their next click. Anyone can sign out on every device at once under Settings, Signed-in devices.
- **Wrong passwords.** Ten wrong passwords for one email address within 15 minutes stop sign-in for that address until the 15 minutes are up. This happens whether or not the address has an account, so it says nothing about which ones do. Ten wrong codes at the second step lock that step for 15 minutes in the same way.
- **The site audit trail** (Settings, Organization, Sign-in security) records each sign-in and failed sign-in with the address it came from, lockouts, sign-outs, password changes and resets, two-step sign-in being turned on, off or reset, new backup codes, and changes to settings, roles, the logo, the email domain, identity confirmations and signing locks. The rows form one hash chain, so a changed or removed row shows, and the trail downloads as CSV.
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index 45e64e7..eb3ff61 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -1374,6 +1374,19 @@ test("two-step sign-in: an administrator sets it up and requires it of everyone"
).toBe(true);
});
+ await test.step("session limits are saved and recorded", async () => {
+ await page
+ .getByLabel("Sign out after no use for")
+ .selectOption({ label: "8 hours" });
+ await page.getByRole("button", { name: "Save session limits" }).click();
+ await expect(page.getByText("Session limits saved.")).toBeVisible();
+ // Still signed in: the page's own session is well within the limit.
+ await page.reload();
+ await expect(page.getByLabel("Sign out after no use for")).toHaveValue(
+ "480",
+ );
+ });
+
await test.step("the requirement can be lifted again", async () => {
await page
.getByRole("button", { name: "Stop requiring two-step sign-in" })
diff --git a/src/app/api/admin/security/route.ts b/src/app/api/admin/security/route.ts
index 805130b..3c90c8b 100644
--- a/src/app/api/admin/security/route.ts
+++ b/src/app/api/admin/security/route.ts
@@ -13,13 +13,20 @@ import {
} from "@/lib/security/request";
import { getSettings, readStoredSettings } from "@/lib/settings";
import {
+ parseSessionLimit,
+ SESSION_IDLE_CHOICES,
+ SESSION_MAX_HOURS_CHOICES,
+} from "@/lib/session-controls";
+import {
+ setSessionLimits,
setTwoFactorRequirement,
SignInSecurityError,
} from "@/lib/sign-in-security";
const noStore = { "cache-control": "private, no-store" };
-// Turns the two-step sign-in requirement on or off. Administrators only.
+// Sign-in security settings: whether two-step sign-in is required, or the
+// two session limits (both at once). Administrators only.
export async function PUT(request: Request) {
const sessionResult = await requireAdminSession(request);
@@ -43,11 +50,35 @@ export async function PUT(request: Request) {
const body = (await request.json().catch(() => null)) as {
requireTwoFactor?: unknown;
+ sessionIdleMinutes?: unknown;
+ sessionMaxHours?: unknown;
} | null;
+ const changesRequirement = typeof body?.requireTwoFactor === "boolean";
+ const changesSessions =
+ body !== null &&
+ ("sessionIdleMinutes" in body || "sessionMaxHours" in body);
+ const sessionIdleMinutes = parseSessionLimit(
+ body?.sessionIdleMinutes,
+ SESSION_IDLE_CHOICES,
+ );
+ const sessionMaxHours = parseSessionLimit(
+ body?.sessionMaxHours,
+ SESSION_MAX_HOURS_CHOICES,
+ );
- if (typeof body?.requireTwoFactor !== "boolean") {
+ if (
+ !changesRequirement &&
+ !(
+ changesSessions &&
+ sessionIdleMinutes !== undefined &&
+ sessionMaxHours !== undefined
+ )
+ ) {
return NextResponse.json(
- { error: "Say whether two-step sign-in should be required." },
+ {
+ error:
+ "Say whether two-step sign-in should be required, or choose both session limits.",
+ },
{ headers: noStore, status: 400 },
);
}
@@ -59,21 +90,30 @@ export async function PUT(request: Request) {
);
}
+ const actor = {
+ email: session.user.email,
+ ipAddress: getClientIpAddress(request.headers),
+ userAgent: getRequestUserAgent(request.headers),
+ userId: session.user.id,
+ };
+
try {
- await setTwoFactorRequirement(
- {
- email: session.user.email,
- ipAddress: getClientIpAddress(request.headers),
- userAgent: getRequestUserAgent(request.headers),
- userId: session.user.id,
- },
- body.requireTwoFactor,
- );
+ if (changesRequirement) {
+ await setTwoFactorRequirement(actor, body?.requireTwoFactor === true);
+ } else {
+ await setSessionLimits(actor, {
+ sessionIdleMinutes: sessionIdleMinutes ?? null,
+ sessionMaxHours: sessionMaxHours ?? null,
+ });
+ }
+
+ const stored = await readStoredSettings();
return NextResponse.json(
{
- requireTwoFactor:
- (await readStoredSettings())?.requireTwoFactor ?? false,
+ requireTwoFactor: stored?.requireTwoFactor ?? false,
+ sessionIdleMinutes: stored?.sessionIdleMinutes ?? null,
+ sessionMaxHours: stored?.sessionMaxHours ?? null,
},
{ headers: noStore },
);
diff --git a/src/components/settings/organization-settings.tsx b/src/components/settings/organization-settings.tsx
index b5ce19e..61f3fcd 100644
--- a/src/components/settings/organization-settings.tsx
+++ b/src/components/settings/organization-settings.tsx
@@ -402,7 +402,11 @@ export function OrganizationSettings({
{!values.hosted ? <PeoplePanel part11Mode={values.part11Mode} /> : null}
{!values.hosted ? (
- <SecurityPanel initialRequireTwoFactor={values.requireTwoFactor} />
+ <SecurityPanel
+ initialRequireTwoFactor={values.requireTwoFactor}
+ initialSessionIdleMinutes={values.sessionIdleMinutes}
+ initialSessionMaxHours={values.sessionMaxHours}
+ />
) : null}
{!values.hosted ? (
diff --git a/src/components/settings/security-panel.tsx b/src/components/settings/security-panel.tsx
index 23c7f9e..826bc9e 100644
--- a/src/components/settings/security-panel.tsx
+++ b/src/components/settings/security-panel.tsx
@@ -3,6 +3,10 @@
import { useEffect, useState } from "react";
import type { SystemAuditEvent } from "@/lib/services/system-audit";
+import {
+ SESSION_IDLE_CHOICES,
+ SESSION_MAX_HOURS_CHOICES,
+} from "@/lib/session-choices";
// Sign-in security and the install's own audit trail. Administrators only.
@@ -30,6 +34,7 @@ const EVENT_LABELS: Record<SystemAuditEvent["event"], string> = {
sign_in_failed: "Sign-in failed",
sign_in_locked: "Sign-in stopped after wrong passwords",
sign_in_succeeded: "Signed in",
+ sessions_revoked: "Signed out everywhere",
signed_out: "Signed out",
signing_locked: "Signing locked",
signing_unlocked: "Signing unlocked",
@@ -92,14 +97,40 @@ function describeEvent(event: SystemAuditEvent): string {
}
}
+function describeMinutes(minutes: number): string {
+ return minutes < 60
+ ? `${String(minutes)} minutes`
+ : minutes === 60
+ ? "1 hour"
+ : `${String(minutes / 60)} hours`;
+}
+
+function describeHours(hours: number): string {
+ return hours % 24 === 0
+ ? hours === 24
+ ? "1 day"
+ : `${String(hours / 24)} days`
+ : `${String(hours)} hours`;
+}
+
export function SecurityPanel({
initialRequireTwoFactor,
+ initialSessionIdleMinutes,
+ initialSessionMaxHours,
}: {
initialRequireTwoFactor: boolean;
+ initialSessionIdleMinutes: number | null;
+ initialSessionMaxHours: number | null;
}) {
const [requireTwoFactor, setRequireTwoFactor] = useState(
initialRequireTwoFactor,
);
+ const [savedLimits, setSavedLimits] = useState({
+ sessionIdleMinutes: initialSessionIdleMinutes,
+ sessionMaxHours: initialSessionMaxHours,
+ });
+ const [limits, setLimits] = useState(savedLimits);
+ const [limitsMessage, setLimitsMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [audit, setAudit] = useState<AuditResponse>(null);
@@ -160,6 +191,48 @@ export function SecurityPanel({
}
}
+ async function saveLimits() {
+ setIsSaving(true);
+ setError(null);
+ setLimitsMessage(null);
+
+ try {
+ const response = await fetch("/api/admin/security", {
+ body: JSON.stringify(limits),
+ headers: { "content-type": "application/json" },
+ method: "PUT",
+ });
+ const payload = (await response.json().catch(() => null)) as {
+ error?: string;
+ sessionIdleMinutes?: number | null;
+ sessionMaxHours?: number | null;
+ } | null;
+
+ if (!response.ok || payload?.sessionIdleMinutes === undefined) {
+ setError(payload?.error ?? GENERIC_ERROR_MESSAGE);
+ return;
+ }
+
+ const saved = {
+ sessionIdleMinutes: payload.sessionIdleMinutes,
+ sessionMaxHours: payload.sessionMaxHours ?? null,
+ };
+
+ setSavedLimits(saved);
+ setLimits(saved);
+ setLimitsMessage("Session limits saved.");
+ setAuditRevision((value) => value + 1);
+ } catch {
+ setError(GENERIC_ERROR_MESSAGE);
+ } finally {
+ setIsSaving(false);
+ }
+ }
+
+ const limitsChanged =
+ limits.sessionIdleMinutes !== savedLimits.sessionIdleMinutes ||
+ limits.sessionMaxHours !== savedLimits.sessionMaxHours;
+
return (
<div className="space-y-5 border-t border-(--border) pt-8" id="security">
<div className="space-y-2">
@@ -204,6 +277,88 @@ export function SecurityPanel({
</button>
</div>
+ <div className="space-y-3">
+ <h4 className="text-[0.9375rem] font-bold text-(--fg)">Sessions</h4>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ How long someone stays signed in. A change applies to everyone who is
+ signed in now, from their next click. Anyone can also sign out
+ everywhere from their own Settings.
+ </p>
+ <div className="grid max-w-xl gap-4 sm:grid-cols-2">
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Sign out after no use for
+ </span>
+ <select
+ className="field-input"
+ disabled={isSaving}
+ onChange={(event) => {
+ setLimitsMessage(null);
+ setLimits((current) => ({
+ ...current,
+ sessionIdleMinutes:
+ event.target.value === ""
+ ? null
+ : Number(event.target.value),
+ }));
+ }}
+ value={limits.sessionIdleMinutes ?? ""}
+ >
+ <option value="">Never</option>
+ {SESSION_IDLE_CHOICES.map((minutes) => (
+ <option key={minutes} value={minutes}>
+ {describeMinutes(minutes)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="grid gap-1.5">
+ <span className="text-[0.8125rem] font-semibold text-(--secondary)">
+ Sign out at the latest after
+ </span>
+ <select
+ className="field-input"
+ disabled={isSaving}
+ onChange={(event) => {
+ setLimitsMessage(null);
+ setLimits((current) => ({
+ ...current,
+ sessionMaxHours:
+ event.target.value === ""
+ ? null
+ : Number(event.target.value),
+ }));
+ }}
+ value={limits.sessionMaxHours ?? ""}
+ >
+ <option value="">7 days (the default)</option>
+ {SESSION_MAX_HOURS_CHOICES.filter((hours) => hours !== 168).map(
+ (hours) => (
+ <option key={hours} value={hours}>
+ {describeHours(hours)}
+ </option>
+ ),
+ )}
+ </select>
+ </label>
+ </div>
+ <div className="flex flex-wrap items-center gap-3">
+ <button
+ className="btn-quiet"
+ disabled={isSaving || !limitsChanged}
+ onClick={() => void saveLimits()}
+ type="button"
+ >
+ {isSaving ? "Saving..." : "Save session limits"}
+ </button>
+ {limitsMessage ? (
+ <span className="text-sm text-(--secondary)" role="status">
+ {limitsMessage}
+ </span>
+ ) : null}
+ </div>
+ </div>
+
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<h4 className="text-[0.9375rem] font-bold text-(--fg)">
diff --git a/src/components/settings/sessions-panel.tsx b/src/components/settings/sessions-panel.tsx
new file mode 100644
index 0000000..1316a60
--- /dev/null
+++ b/src/components/settings/sessions-panel.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { useState } from "react";
+
+import { ShellButton } from "@/components/shared/form-shell";
+
+// Ends every session this account has, on every device, this one included.
+export function SessionsPanel() {
+ const [isBusy, setIsBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ async function signOutEverywhere() {
+ setIsBusy(true);
+ setError(null);
+
+ try {
+ const response = await fetch("/api/auth/revoke-sessions", {
+ body: "{}",
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+
+ if (!response.ok) {
+ setError("Something went wrong. Please try again.");
+ return;
+ }
+
+ window.location.assign("/login");
+ } catch {
+ setError("Something went wrong. Please try again.");
+ } finally {
+ setIsBusy(false);
+ }
+ }
+
+ return (
+ <div className="panel p-6 sm:p-8">
+ <div className="space-y-5">
+ <h2 className="text-xl font-extrabold tracking-[-0.02em] text-(--fg)">
+ Signed-in devices
+ </h2>
+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">
+ If you signed in on a computer that is not yours, or lost a device,
+ sign out everywhere. Every browser signed in to your account,
+ including this one, has to sign in again.
+ </p>
+ {error ? (
+ <p className="notice notice-danger" role="alert">
+ {error}
+ </p>
+ ) : null}
+ <ShellButton
+ className="w-fit"
+ loading={isBusy}
+ onClick={() => void signOutEverywhere()}
+ variant="secondary"
+ >
+ {isBusy ? "Signing out..." : "Sign out everywhere"}
+ </ShellButton>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/settings/settings-shell.tsx b/src/components/settings/settings-shell.tsx
index a103cc3..26b158f 100644
--- a/src/components/settings/settings-shell.tsx
+++ b/src/components/settings/settings-shell.tsx
@@ -5,6 +5,7 @@ import { useState, type ChangeEvent, type FormEvent } from "react";
import { useBranding } from "@/components/layout/branding-provider";
import { FieldShell, ShellButton } from "@/components/shared/form-shell";
import { PageHeader } from "@/components/shared/page-header";
+import { SessionsPanel } from "@/components/settings/sessions-panel";
import { TwoFactorPanel } from "@/components/settings/two-factor-panel";
import {
Dialog,
@@ -664,6 +665,8 @@ export function SettingsShell({
required={twoFactor.required}
/>
+ <SessionsPanel />
+
<div className="panel p-6 sm:p-8">
<div className="space-y-5">
<SectionHeading title="Danger zone" />
diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.ts
index 8158cb1..87fefd3 100644
--- a/src/lib/auth/server.ts
+++ b/src/lib/auth/server.ts
@@ -22,7 +22,13 @@ import {
requireConfigValue,
ServiceConfigurationError,
} from "../services/service-config.ts";
-import { evaluateSignupRequest, getBranding } from "../settings.ts";
+import {
+ evaluateSignupRequest,
+ getBranding,
+ getSettings,
+ isMissingSchemaError,
+} from "../settings.ts";
+import { enforceSessionLimits } from "../session-controls.ts";
import {
getEnv,
resolveDeploymentOrigins,
@@ -495,9 +501,33 @@ export function getAuth(): AppAuth {
}
export async function getAuthSessionFromHeaders(requestHeaders: Headers) {
- return getAuth().api.getSession({
+ const session = await getAuth().api.getSession({
headers: requestHeaders,
});
+
+ if (!session) {
+ return null;
+ }
+
+ // The session cookie can vouch for a session for a few minutes on its
+ // own. Its row decides: one that was ended (signed out everywhere, reset
+ // by an administrator) or that is past the install's limits does not
+ // count. See session-controls.ts.
+ try {
+ const allowed = await enforceSessionLimits(
+ session.session.token,
+ await getSettings(),
+ );
+
+ return allowed ? session : null;
+ } catch (error) {
+ // A database from before the session controls: nothing to enforce yet.
+ if (isMissingSchemaError(error)) {
+ return session;
+ }
+
+ throw error;
+ }
}
const getCachedAuthSession = cache(async () => {
diff --git a/src/lib/auth/sign-in-events.ts b/src/lib/auth/sign-in-events.ts
index b50f8a4..31bff11 100644
--- a/src/lib/auth/sign-in-events.ts
+++ b/src/lib/auth/sign-in-events.ts
@@ -16,6 +16,7 @@ import {
import {
recordSystemAuditEvent,
type RecordSystemAuditEventInput,
+ type SystemAuditEventType,
} from "../services/system-audit.ts";
import {
clearFailedSignIns,
@@ -45,11 +46,19 @@ const SECOND_STEP_PATHS = new Set([
// Paths whose actor is only known before the endpoint runs: each replaces
// or ends the session it was called with.
const SESSION_FIRST_PATHS = new Set([
+ "/revoke-sessions",
"/sign-out",
"/two-factor/disable",
"/two-factor/generate-backup-codes",
]);
+const SESSION_FIRST_EVENTS: Record<string, SystemAuditEventType> = {
+ "/revoke-sessions": "sessions_revoked",
+ "/sign-out": "signed_out",
+ "/two-factor/disable": "two_factor_disabled",
+ "/two-factor/generate-backup-codes": "two_factor_backup_codes_regenerated",
+};
+
type Actor = { email: string; userId: string };
type HookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
@@ -258,12 +267,7 @@ export function signInEvents() {
await record(ctx, {
actorEmail: actor.email,
actorUserId: actor.userId,
- event:
- path === "/sign-out"
- ? "signed_out"
- : path === "/two-factor/disable"
- ? "two_factor_disabled"
- : "two_factor_backup_codes_regenerated",
+ event: SESSION_FIRST_EVENTS[path] ?? "signed_out",
targetUserId: actor.userId,
});
}),
diff --git a/src/lib/email-status.test.ts b/src/lib/email-status.test.ts
index cb91b64..aa5d1a2 100644
--- a/src/lib/email-status.test.ts
+++ b/src/lib/email-status.test.ts
@@ -19,6 +19,8 @@ const stored: AppSettings = {
organizationName: "Acme Corp",
part11Mode: false,
requireTwoFactor: false,
+ sessionIdleMinutes: null,
+ sessionMaxHours: null,
privacyUrl: null,
retentionDays: null,
senderAddress: "[email protected]",
diff --git a/src/lib/organization-settings.test.ts b/src/lib/organization-settings.test.ts
index 2d09d67..e9b5c77 100644
--- a/src/lib/organization-settings.test.ts
+++ b/src/lib/organization-settings.test.ts
@@ -16,6 +16,8 @@ const stored: AppSettings = {
organizationName: "Acme Corp",
part11Mode: false,
requireTwoFactor: false,
+ sessionIdleMinutes: null,
+ sessionMaxHours: null,
privacyUrl: null,
retentionDays: null,
senderAddress: "[email protected]",
diff --git a/src/lib/organization-settings.ts b/src/lib/organization-settings.ts
index cef3b6d..f8d105f 100644
--- a/src/lib/organization-settings.ts
+++ b/src/lib/organization-settings.ts
@@ -48,6 +48,10 @@ export type OrganizationSettingsView = {
privacyUrl: string;
/** Everyone must use two-step sign-in. Changed in the security panel. */
requireTwoFactor: boolean;
+ /** Minutes without use before a session ends, or null for no limit. */
+ sessionIdleMinutes: number | null;
+ /** Hours after sign-in when a session ends, or null for 7 days. */
+ sessionMaxHours: number | null;
/** Days, as typed. Empty keeps finished envelopes until deleted by hand. */
retentionDays: string;
senderAddress: string;
@@ -73,6 +77,8 @@ export function toOrganizationSettingsView(
part11Mode: settings.part11Mode,
privacyUrl: settings.privacyUrl ?? "",
requireTwoFactor: settings.requireTwoFactor,
+ sessionIdleMinutes: settings.sessionIdleMinutes,
+ sessionMaxHours: settings.sessionMaxHours,
retentionDays:
settings.retentionDays === null ? "" : String(settings.retentionDays),
senderAddress: settings.senderAddress ?? "",
diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.ts
index 4ce4a49..e88d32f 100644
--- a/src/lib/services/system-audit.ts
+++ b/src/lib/services/system-audit.ts
@@ -28,6 +28,7 @@ export const systemAuditEventTypes = [
"sign_in_failed",
"sign_in_locked",
"signed_out",
+ "sessions_revoked",
"password_changed",
"password_reset",
"two_factor_enabled",
diff --git a/src/lib/session-choices.ts b/src/lib/session-choices.ts
new file mode 100644
index 0000000..dfc5b26
--- /dev/null
+++ b/src/lib/session-choices.ts
@@ -0,0 +1,9 @@
+// The session limits an administrator can choose (session-controls.ts).
+// Kept apart from that module so the settings page can list them without
+// loading database code.
+
+/** Minutes without use before a session ends. */
+export const SESSION_IDLE_CHOICES = [15, 30, 60, 240, 480] as const;
+
+/** Hours after sign-in when a session ends. 168 is Better Auth's 7 days. */
+export const SESSION_MAX_HOURS_CHOICES = [8, 12, 24, 72, 168] as const;
diff --git a/src/lib/session-controls.test.ts b/src/lib/session-controls.test.ts
new file mode 100644
index 0000000..a275702
--- /dev/null
+++ b/src/lib/session-controls.test.ts
@@ -0,0 +1,79 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import { checkSession, parseSessionLimit } from "./session-controls.ts";
+import { SESSION_IDLE_CHOICES } from "./session-choices.ts";
+
+const CREATED = new Date("2026-11-17T09:00:00Z");
+const createdSeconds = Math.floor(CREATED.getTime() / 1000);
+const noLimits = { sessionIdleMinutes: null, sessionMaxHours: null };
+
+test("a session that is gone does not count", () => {
+ assert.deepEqual(checkSession(null, noLimits, createdSeconds), {
+ ok: false,
+ reason: "gone",
+ });
+});
+
+test("without limits a session lasts, and its use is written once a minute", () => {
+ const row = { createdAt: CREATED, lastActiveAt: createdSeconds + 3600 };
+
+ assert.deepEqual(checkSession(row, noLimits, createdSeconds + 3630), {
+ ok: true,
+ touch: false,
+ });
+ assert.deepEqual(checkSession(row, noLimits, createdSeconds + 3660), {
+ ok: true,
+ touch: true,
+ });
+});
+
+test("an idle session ends, counted from its last use or else its start", () => {
+ const limits = { sessionIdleMinutes: 30, sessionMaxHours: null };
+
+ assert.equal(
+ checkSession(
+ { createdAt: CREATED, lastActiveAt: null },
+ limits,
+ createdSeconds + 29 * 60,
+ ).ok,
+ true,
+ );
+ assert.deepEqual(
+ checkSession(
+ { createdAt: CREATED, lastActiveAt: null },
+ limits,
+ createdSeconds + 30 * 60,
+ ),
+ { ok: false, reason: "idle" },
+ );
+ assert.equal(
+ checkSession(
+ { createdAt: CREATED, lastActiveAt: createdSeconds + 3600 },
+ limits,
+ createdSeconds + 3600 + 29 * 60,
+ ).ok,
+ true,
+ );
+});
+
+test("a session ends at its maximum length however busy it is", () => {
+ const limits = { sessionIdleMinutes: 15, sessionMaxHours: 8 };
+
+ assert.deepEqual(
+ checkSession(
+ { createdAt: CREATED, lastActiveAt: createdSeconds + 8 * 3600 - 10 },
+ limits,
+ createdSeconds + 8 * 3600,
+ ),
+ { ok: false, reason: "too_old" },
+ );
+});
+
+test("only listed limits, or null for none, are accepted", () => {
+ assert.equal(parseSessionLimit(30, SESSION_IDLE_CHOICES), 30);
+ assert.equal(parseSessionLimit(null, SESSION_IDLE_CHOICES), null);
+ assert.equal(parseSessionLimit(31, SESSION_IDLE_CHOICES), undefined);
+ assert.equal(parseSessionLimit("30", SESSION_IDLE_CHOICES), undefined);
+ assert.equal(parseSessionLimit(undefined, SESSION_IDLE_CHOICES), undefined);
+});
diff --git a/src/lib/session-controls.ts b/src/lib/session-controls.ts
new file mode 100644
index 0000000..afb870f
--- /dev/null
+++ b/src/lib/session-controls.ts
@@ -0,0 +1,121 @@
+import { type DbExecutor, getDb, queryOne } from "./db/connection.ts";
+
+// Session controls, set by an administrator: a session ends after a time
+// without use (idle timeout) and at most a set time after sign-in.
+//
+// Better Auth keeps the session in a signed cookie for a few minutes so most
+// requests do not ask the database. That cache cannot know about these
+// limits, or that an administrator reset someone's sign-in, so the app's own
+// session check (auth/server.ts) also reads the session's row each time, and
+// treats a row that is gone, or past a limit, as signed out.
+
+export {
+ SESSION_IDLE_CHOICES,
+ SESSION_MAX_HOURS_CHOICES,
+} from "./session-choices.ts";
+
+/** Use is written down at most this often, to keep writes rare. */
+const ACTIVITY_WRITE_INTERVAL_SECONDS = 60;
+
+export type SessionLimits = {
+ sessionIdleMinutes: number | null;
+ sessionMaxHours: number | null;
+};
+
+export type SessionRow = {
+ createdAt: Date;
+ lastActiveAt: number | null;
+};
+
+export type SessionCheck =
+ | { ok: true; touch: boolean }
+ | { ok: false; reason: "gone" | "idle" | "too_old" };
+
+/** Whether a session may still be used now. Pure, for testing. */
+export function checkSession(
+ row: SessionRow | null,
+ limits: SessionLimits,
+ nowSeconds: number,
+): SessionCheck {
+ if (!row) {
+ return { ok: false, reason: "gone" };
+ }
+
+ const createdAt = Math.floor(row.createdAt.getTime() / 1000);
+ const lastActiveAt = row.lastActiveAt ?? createdAt;
+
+ if (
+ limits.sessionMaxHours !== null &&
+ nowSeconds - createdAt >= limits.sessionMaxHours * 3600
+ ) {
+ return { ok: false, reason: "too_old" };
+ }
+
+ if (
+ limits.sessionIdleMinutes !== null &&
+ nowSeconds - lastActiveAt >= limits.sessionIdleMinutes * 60
+ ) {
+ return { ok: false, reason: "idle" };
+ }
+
+ return {
+ ok: true,
+ touch: nowSeconds - lastActiveAt >= ACTIVITY_WRITE_INTERVAL_SECONDS,
+ };
+}
+
+/**
+ * Checks a session against the install's limits, records its use, and ends
+ * it when a limit is passed. True when it may be used.
+ */
+export async function enforceSessionLimits(
+ token: string,
+ limits: SessionLimits,
+ options: { database?: DbExecutor; nowSeconds?: number } = {},
+): Promise<boolean> {
+ const database = options.database ?? getDb();
+ const nowSeconds = options.nowSeconds ?? Math.floor(Date.now() / 1000);
+ const row = await queryOne<SessionRow>(
+ database,
+ `
+ SELECT "createdAt" AS "createdAt", last_active_at AS "lastActiveAt"
+ FROM session
+ WHERE token = $1
+ `,
+ [token],
+ );
+ const check = checkSession(row, limits, nowSeconds);
+
+ if (!check.ok) {
+ if (check.reason !== "gone") {
+ await database.query(`DELETE FROM session WHERE token = $1`, [token]);
+ }
+
+ return false;
+ }
+
+ if (check.touch) {
+ await database.query(
+ `UPDATE session SET last_active_at = $2 WHERE token = $1`,
+ [token, nowSeconds],
+ );
+ }
+
+ return true;
+}
+
+/** Reads a choice from a request body: a listed number, or null for "off". */
+export function parseSessionLimit(
+ value: unknown,
+ choices: readonly number[],
+): number | null | undefined {
+ if (value === null) {
+ return null;
+ }
+
+ if (typeof value === "number" && choices.includes(value)) {
+ return value;
+ }
+
+ return undefined;
+}
diff --git a/src/lib/settings.test.ts b/src/lib/settings.test.ts
index 69f0235..0cc3247 100644
--- a/src/lib/settings.test.ts
+++ b/src/lib/settings.test.ts
@@ -16,6 +16,8 @@ const stored: AppSettings = {
organizationName: "Acme Corp",
part11Mode: false,
requireTwoFactor: false,
+ sessionIdleMinutes: null,
+ sessionMaxHours: null,
privacyUrl: "https://acme.com/privacy",
retentionDays: null,
senderAddress: "[email protected]",
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index e4004af..5a03a25 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -45,6 +45,13 @@ export type AppSettings = {
* they can use the app. See sign-in-security.ts.
*/
requireTwoFactor: boolean;
+ /**
+ * Minutes a signed-in session may go unused before it ends, or null for
+ * no limit. See session-controls.ts.
+ */
+ sessionIdleMinutes: number | null;
+ /** Hours after sign-in when a session ends, or null for 7 days. */
+ sessionMaxHours: number | null;
/**
* Days a finished envelope is kept before the nightly job deletes it, or
* null to keep finished envelopes until someone deletes them.
@@ -98,6 +105,8 @@ type AppSettingsRow = {
require_two_factor: boolean;
retention_days: number | null;
sender_address: string | null;
+ session_idle_minutes: number | null;
+ session_max_hours: number | null;
setup_completed_at: number | null;
signup_mode: SignupMode;
support_address: string | null;
@@ -127,6 +136,7 @@ const LATER_SETTINGS_COLUMNS = [
["brand_color", "logo_hash"], // 20261114120000_branding
["part11_mode"], // 20261115090000_part11_mode
["require_two_factor"], // 20261117090000_sign_in_security
+ ["session_idle_minutes", "session_max_hours"], // 20261117100000_session_controls
] as const;
type LaterSettingsColumn = (typeof LATER_SETTINGS_COLUMNS)[number][number];
@@ -159,6 +169,8 @@ const UNSET_SETTINGS: AppSettings = {
requireTwoFactor: false,
retentionDays: null,
senderAddress: null,
+ sessionIdleMinutes: null,
+ sessionMaxHours: null,
setupCompletedAt: null,
signupMode: "open",
supportAddress: null,
@@ -226,6 +238,8 @@ function mapSettingsRow(row: StoredSettingsRow): AppSettings {
requireTwoFactor: row.require_two_factor ?? false,
retentionDays: row.retention_days ?? null,
senderAddress: row.sender_address,
+ sessionIdleMinutes: row.session_idle_minutes ?? null,
+ sessionMaxHours: row.session_max_hours ?? null,
setupCompletedAt: row.setup_completed_at,
signupMode: row.signup_mode,
supportAddress: row.support_address,
@@ -389,10 +403,12 @@ async function saveSettingsLocked(
brand_color,
part11_mode,
require_two_factor,
+ session_idle_minutes,
+ session_max_hours,
created_at,
updated_at
)
- values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $14, $10, $10)
+ values (true, $1, $2, $3, $4, $5, $6, $7, $8, $9, $11, $12, $13, $14, $15, $16, $10, $10)
on conflict (id) do update set
allowed_email_domains = excluded.allowed_email_domains,
email_ready_at = excluded.email_ready_at,
@@ -407,6 +423,8 @@ async function saveSettingsLocked(
brand_color = excluded.brand_color,
part11_mode = excluded.part11_mode,
require_two_factor = excluded.require_two_factor,
+ session_idle_minutes = excluded.session_idle_minutes,
+ session_max_hours = excluded.session_max_hours,
updated_at = excluded.updated_at
returning ${SETTINGS_COLUMNS}
`,
@@ -425,6 +443,8 @@ async function saveSettingsLocked(
next.brandColor,
next.part11Mode,
next.requireTwoFactor,
+ next.sessionIdleMinutes,
+ next.sessionMaxHours,
],
);
diff --git a/src/lib/sign-in-security.dbtest.ts b/src/lib/sign-in-security.dbtest.ts
index d6eccbf..85b1ce8 100644
--- a/src/lib/sign-in-security.dbtest.ts
+++ b/src/lib/sign-in-security.dbtest.ts
@@ -14,6 +14,7 @@ import {
verifySystemAuditChain,
} from "./services/system-audit.ts";
import { invalidateSettingsCache, saveSettings } from "./settings.ts";
+import { enforceSessionLimits } from "./session-controls.ts";
import {
MAX_FAILED_SIGN_INS,
resetTwoFactor,
@@ -482,3 +483,73 @@ test("signing out is recorded", async () => {
assert.equal(result.status, 200);
assert.equal((await events("signed_out"))[0]?.actorUserId, userId);
});
+
+test("signing out everywhere ends every session and is recorded", async () => {
+ const userId = await createVerifiedUser("[email protected]");
+ const first = await signIn("[email protected]");
+
+ await signIn("[email protected]");
+
+ const result = await call("/revoke-sessions", {}, first.cookies);
+
+ assert.equal(result.status, 200, JSON.stringify(result.payload));
+ assert.equal((await events("sessions_revoked"))[0]?.actorUserId, userId);
+
+ const left = await database.query<{ total: number }>(
+ `select count(*)::int as total from session where "userId" = $1`,
+ [userId],
+ );
+
+ assert.equal(left.rows[0]?.total, 0);
+});
+
+test("session limits end idle and old sessions, and record use", async () => {
+ const userId = await createVerifiedUser("[email protected]");
+
+ await signIn("[email protected]");
+
+ const row = await database.query<{ createdAt: Date; token: string }>(
+ `select token, "createdAt" as "createdAt" from session where "userId" = $1`,
+ [userId],
+ );
+ const token = row.rows[0]?.token ?? "";
+ const created = Math.floor((row.rows[0]?.createdAt.getTime() ?? 0) / 1000);
+ const limits = { sessionIdleMinutes: 30, sessionMaxHours: 8 };
+
+ assert.equal(
+ await enforceSessionLimits(token, limits, {
+ database,
+ nowSeconds: created + 20 * 60,
+ }),
+ true,
+ );
+
+ const touched = await database.query<{ lastActiveAt: string }>(
+ `select last_active_at as "lastActiveAt" from session where token = $1`,
+ [token],
+ );
+
+ assert.equal(Number(touched.rows[0]?.lastActiveAt), created + 20 * 60);
+ // Counted from that use, not from sign-in.
+ assert.equal(
+ await enforceSessionLimits(token, limits, {
+ database,
+ nowSeconds: created + 45 * 60,
+ }),
+ true,
+ );
+ assert.equal(
+ await enforceSessionLimits(token, limits, {
+ database,
+ nowSeconds: created + 45 * 60 + 30 * 60,
+ }),
+ false,
+ );
+
+ const gone = await database.query(`select 1 from session where token = $1`, [
+ token,
+ ]);
+
+ assert.equal(gone.rowCount, 0);
+ assert.equal(await enforceSessionLimits(token, limits, { database }), false);
+});
diff --git a/src/lib/sign-in-security.ts b/src/lib/sign-in-security.ts
index bc1d1d5..712b379 100644
--- a/src/lib/sign-in-security.ts
+++ b/src/lib/sign-in-security.ts
@@ -262,3 +262,52 @@ export async function resetTwoFactor(
);
}, database);
}
+
+/**
+ * Sets how long sessions may go unused and how long they may last. Applies
+ * to sessions that are already open too, from their next request.
+ */
+export async function setSessionLimits(
+ actor: Actor,
+ limits: {
+ sessionIdleMinutes: number | null;
+ sessionMaxHours: number | null;
+ },
+ database: DbPool = getDb(),
+): Promise<void> {
+ const { readStoredSettings, saveSettings } = await import("./settings.ts");
+
+ await withTransaction(async (tx) => {
+ await lockActor(actor, tx);
+ await tx.query(`SELECT id FROM app_settings WHERE id FOR UPDATE`);
+
+ const current = await readStoredSettings(tx);
+ const changes: Record<string, { from: number | null; to: number | null }> =
+ {};
+
+ for (const field of ["sessionIdleMinutes", "sessionMaxHours"] as const) {
+ const from = current?.[field] ?? null;
+
+ if (from !== limits[field]) {
+ changes[field] = { from, to: limits[field] };
+ }
+ }
+
+ if (Object.keys(changes).length === 0) {
+ return;
+ }
+
+ await saveSettings(limits, tx);
+ await recordSystemAuditEvent(
+ {
+ actorEmail: actor.email,
+ actorUserId: actor.userId,
+ event: "settings_changed",
+ ipAddress: actor.ipAddress ?? null,
+ metadata: { changes },
+ userAgent: actor.userAgent ?? null,
+ },
+ tx,
+ );
+ }, database);
+}