From 8bc9332a5f084820be76aff0e8671cc1dea08480 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Wed, 25 Nov 2026 23:07:25 +0000
Subject: [PATCH 01/11] feat(control): session policies for how long sign-ins
last
Instance admins set how long a browser stays signed in (from its sign-in,
and unused), how long a CLI stays signed in, the longest an access token
lasts and whether members make them. Every request checks its token
against them, and saving one ends at once what it doesn't let last.
`fctl admin sign-in policies` shows and changes them, with what a change
ends before it saves.
---
crates/fctl-client/src/api.rs | 10 +
crates/fctl-control/src/api/admin.rs | 17 +
crates/fctl-control/src/api/sign_in.rs | 41 ++
crates/fctl-control/src/api/tokens.rs | 65 ++-
crates/fctl-control/src/auth.rs | 99 +++-
crates/fctl-control/src/lib.rs | 3 +
crates/fctl-control/src/sign_in.rs | 228 +++++++-
crates/fctl-domain/src/lib.rs | 1 +
crates/fctl-domain/src/session_policy.rs | 566 +++++++++++++++++++
crates/fctl-domain/src/verify.rs | 67 +++
crates/fctl-proto/src/api.rs | 114 ++++
crates/fctl-proto/src/ts_export.rs | 2 +
crates/fctl/src/cmd/admin.rs | 6 +-
crates/fctl/src/cmd/sign_in.rs | 214 ++++++-
web/src/gen/InstanceSettings.ts | 36 +-
web/src/gen/Me.ts | 9 +-
web/src/gen/SessionPolicy.ts | 8 +
web/src/gen/SessionPolicyPreview.ts | 30 +
web/src/gen/SignInOverview.ts | 8 +-
web/src/gen/UpdateInstanceSettingsRequest.ts | 20 +-
web/src/gen/index.ts | 2 +
21 files changed, 1497 insertions(+), 49 deletions(-)
create mode 100644 crates/fctl-domain/src/session_policy.rs
create mode 100644 web/src/gen/SessionPolicy.ts
create mode 100644 web/src/gen/SessionPolicyPreview.ts
diff --git a/crates/fctl-client/src/api.rs b/crates/fctl-client/src/api.rs
index 660bdabc..fcb804b1 100644
--- a/crates/fctl-client/src/api.rs
+++ b/crates/fctl-client/src/api.rs
@@ -2300,6 +2300,16 @@ impl Api {
.await
}
+ /// What saving `policy` in place of the instance's session policy
+ /// would end at once, before anything changes (admins). Saving it is
+ /// [`Self::update_instance_settings`] with its fields.
+ pub async fn session_policy_preview(
+ &self,
+ policy: &SessionPolicy,
+ ) -> Result {
+ self.post("/admin/sign-in/sessions/preview", policy).await
+ }
+
/// Invites an address to the instance, and to workspaces you are an
/// admin of.
pub async fn invite(&self, req: &CreateInviteRequest) -> Result {
diff --git a/crates/fctl-control/src/api/admin.rs b/crates/fctl-control/src/api/admin.rs
index d3bb637b..593775f8 100644
--- a/crates/fctl-control/src/api/admin.rs
+++ b/crates/fctl-control/src/api/admin.rs
@@ -1162,6 +1162,18 @@ pub async fn update_settings(ctx: &mut Ctx, req: &mut Request) -> AppResult AppResult AppResult {
let people = crate::sign_in::people(&ctx.db).await?;
let how = signed_in_with(ctx);
let count = |f: fn(&rules::Person) -> bool| people.iter().filter(|p| f(p)).count() as u32;
+ let sessions = settings.session_policy();
http::ok(&SignInOverview {
providers: crate::sign_in::statuses(&ctx.cfg, &people),
coverage: settings
@@ -781,9 +782,49 @@ pub async fn overview(ctx: &Ctx) -> AppResult {
method: how.method_str().map(str::to_owned),
method_domain: how.domain,
email: ctx.cfg.email.is_some(),
+ sessions,
})
}
+/// `POST /api/v1/admin/sign-in/sessions/preview`: what saving the
+/// request's session policy would end at once, before anything changes.
+pub async fn sessions_preview(ctx: &Ctx, req: &mut Request) -> AppResult {
+ let actor = ctx.admin()?.clone();
+ let policy: SessionPolicy = http::body(req).await?;
+ fctl_domain::session_policy::check(&policy).map_err(AppError)?;
+ let mut p = SessionPolicyPreview::default();
+ for (kind, member, n) in crate::sign_in::ended_by_policy(&ctx.db, &policy, ctx.now).await? {
+ match kind {
+ TokenKind::Web => p.browsers += n,
+ TokenKind::Cli => p.clis += n,
+ TokenKind::Pat => {
+ p.access_tokens += n;
+ if member {
+ p.member_tokens += n;
+ }
+ }
+ }
+ }
+ // The sign-in this request comes with, used just now: one of those, if
+ // it's too old. An admin token isn't one.
+ p.you = ctx.auth.as_ref().is_some_and(|a| {
+ !a.admin_token
+ && fctl_domain::session_policy::ended(
+ &policy,
+ &fctl_domain::session_policy::Token {
+ kind: a.kind,
+ created_at: a.signed_in_at,
+ last_used_at: Some(ctx.now),
+ expires_at: None,
+ member: actor.role() == fctl_proto::session::InstanceRole::Member,
+ },
+ ctx.now,
+ )
+ .is_some()
+ });
+ http::ok(&p)
+}
+
/// How the caller's sign-in was made.
fn signed_in_with(ctx: &Ctx) -> SignedIn {
ctx.auth
diff --git a/crates/fctl-control/src/api/tokens.rs b/crates/fctl-control/src/api/tokens.rs
index eb0fa255..139e012b 100644
--- a/crates/fctl-control/src/api/tokens.rs
+++ b/crates/fctl-control/src/api/tokens.rs
@@ -10,10 +10,11 @@ use crate::error::{AppError, AppResult, not_found, validation};
use crate::http;
use crate::model::PROJECT_VISIBLE;
use fctl_domain::limits::{Limits, MAX_PLACES, Places};
+use fctl_domain::session_policy;
use fctl_domain::validate;
use fctl_domain::verify::Sensitive;
-use fctl_proto::TokenId;
use fctl_proto::api::*;
+use fctl_proto::{ApiError, TokenId};
use serde::Deserialize;
use std::collections::HashMap;
use worker::{Request, Response};
@@ -134,8 +135,27 @@ impl TokenRow {
Limits::parse(self.scope.as_deref())
}
- fn info(self, current: &str, named: &Named) -> TokenInfo {
+ /// It as the instance's session policy reads it (`member`: its person
+ /// is a member of the instance, not an admin).
+ fn token(&self, member: bool) -> session_policy::Token {
+ session_policy::Token {
+ kind: TokenKind::parse(&self.kind).unwrap_or(TokenKind::Pat),
+ created_at: self.created_at,
+ last_used_at: self.last_used_at,
+ expires_at: self.expires_at,
+ member,
+ }
+ }
+
+ /// Whether `policy` still lets it sign its person in at `now`.
+ fn live(&self, policy: &SessionPolicy, member: bool, now: i64) -> bool {
+ session_policy::ended(policy, &self.token(member), now).is_none()
+ }
+
+ /// What people see of it, as `policy` lets it last.
+ fn info(self, current: &str, named: &Named, policy: &SessionPolicy) -> TokenInfo {
let scope = self.limits().map(|l| named.scope(&l));
+ let expires_at = session_policy::ends_at(policy, &self.token(false));
TokenInfo {
current: self.id == current,
id: TokenId(self.id),
@@ -143,7 +163,7 @@ impl TokenRow {
name: self.name,
created_at: self.created_at,
last_used_at: self.last_used_at,
- expires_at: self.expires_at,
+ expires_at,
user_agent: self.user_agent,
scope,
method: self.auth_method,
@@ -170,10 +190,20 @@ pub async fn list(ctx: &Ctx) -> AppResult {
)?
.all()
.await?;
+ // Those the instance's session policy ended are gone.
+ let policy = ctx.settings().session_policy();
+ let member = user.role() == fctl_proto::session::InstanceRole::Member;
+ let rows: Vec = rows
+ .into_iter()
+ .filter(|r| r.live(&policy, member, ctx.now))
+ .collect();
let limits: Vec = rows.iter().filter_map(TokenRow::limits).collect();
let named = Named::of(ctx, &user.id, &limits.iter().collect::>()).await?;
http::ok(&TokenList {
- tokens: rows.into_iter().map(|r| r.info(¤t, &named)).collect(),
+ tokens: rows
+ .into_iter()
+ .map(|r| r.info(¤t, &named, &policy))
+ .collect(),
})
}
@@ -195,7 +225,11 @@ pub async fn current(ctx: &Ctx) -> AppResult
)}
- setOpen(false)} />
+ {!adminsOnly && setOpen(false)} max={max} />}
);
}
/** Makes an access token: what it does, where, what its agents may do on GitHub, how long it works. */
-export function NewTokenDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
- const [form, setForm] = useState(NEW_TOKEN);
+export function NewTokenDialog({ open, onClose, max }: { open: boolean; onClose: () => void; max: number }) {
+ const [typed, setForm] = useState(NEW_TOKEN);
+ // Within the longest the instance lets a token last.
+ const form = { ...typed, expires: fitExpiry(typed.expires, max) };
const [created, setCreated] = useState(null);
const set = (f: Partial) => setForm((was) => ({ ...was, ...f }));
const create = useMutation({
@@ -123,7 +138,7 @@ export function NewTokenDialog({ open, onClose }: { open: boolean; onClose: () =
{created ? (
) : (
-
+
)}
);
@@ -133,10 +148,13 @@ function TokenFormView({
form,
set,
create,
+ max,
}: {
form: TokenForm;
set: (f: Partial) => void;
create: { mutate: () => void; isPending: boolean; error: Error | null };
+ /** The longest the instance lets a token last, in days; 0: as long as its maker chooses. */
+ max: number;
}) {
const workspaces = useWorkspaces().data?.workspaces ?? [];
const projects = useProjects().data?.projects ?? [];
@@ -148,7 +166,7 @@ function TokenFormView({
[workspaces, projects],
);
const scope = formScope(form, names);
- const expiry = EXPIRIES.find((e) => e.value === form.expires)?.days;
+ const expiry = expiryDays(form.expires);
const field = (create.error as { field?: string } | null)?.field;
const err = (f: string) => (field === f ? create.error?.message : undefined);
const id = useId();
@@ -240,13 +258,17 @@ function TokenFormView({
)}
)}
-
+ 0 ? `This instance lets a token last ${expiryWords(max)} at most.` : undefined}
+ error={err("expires_in_days")}
+ >
{(fid) => (
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index d881e558..f65c636b 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -626,6 +626,9 @@ export const api = {
/** What saving `rules` as the instance's sign-in rules would do, before anything changes (admins). */
signInPreview: (rules: G.SignInRule[]) =>
request("POST", "/admin/sign-in/preview", { rules } satisfies G.SignInPreviewRequest),
+ /** What saving `policy` as the instance's session policy would end at once, before anything changes (admins). */
+ sessionPolicyPreview: (policy: G.SessionPolicy) =>
+ request("POST", "/admin/sign-in/sessions/preview", policy),
updateInstanceSettings: (b: G.UpdateInstanceSettingsRequest) =>
request("PATCH", "/admin/settings", b),
};
diff --git a/web/src/lib/session-policy.test.ts b/web/src/lib/session-policy.test.ts
new file mode 100644
index 00000000..d790cd1b
--- /dev/null
+++ b/web/src/lib/session-policy.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from "vitest";
+import {
+ browserIdleChoices,
+ browserMaxChoices,
+ consequences,
+ DEFAULT_POLICY,
+ describe as describePolicy,
+ devicesNote,
+ minutes,
+ tokenMaxChoices,
+} from "./session-policy";
+
+describe("session policies", () => {
+ it("read as the CLI says them", () => {
+ expect(describePolicy(DEFAULT_POLICY)).toEqual([
+ "Browsers stay signed in while they're used, until 30 days unused.",
+ "CLIs stay signed in while they're used, until 180 days unused.",
+ "Everyone makes access tokens, each lasting as long as its maker chooses.",
+ ]);
+ expect(
+ describePolicy({
+ browser_max_hours: 12,
+ browser_idle_minutes: 60,
+ cli_max_days: 30,
+ access_token_max_days: 365,
+ member_access_tokens: false,
+ }),
+ ).toEqual([
+ "Browsers sign in again after 12 hours, and after an hour unused.",
+ "CLIs sign in again after 30 days, and after 180 days unused.",
+ "Only admins make access tokens, each lasting a year at most.",
+ ]);
+ expect([1, 15, 60, 90, 1440, 10080, 43200].map(minutes)).toEqual([
+ "a minute",
+ "15 minutes",
+ "an hour",
+ "90 minutes",
+ "a day",
+ "a week",
+ "30 days",
+ ]);
+ });
+
+ it("say what a change ends, as the CLI does", () => {
+ expect(consequences({ browsers: 14, clis: 1, access_tokens: 5, member_tokens: 3, you: true })).toEqual([
+ "Saving signs out 14 browsers and 1 CLI at once, yours among them: their people sign in again.",
+ "It ends 5 access tokens, 3 of them members': scripts and CI that use them need new ones.",
+ ]);
+ expect(consequences({ browsers: 0, clis: 0, access_tokens: 0, member_tokens: 0, you: false })).toEqual([
+ "Nobody is signed out now: sign-ins end as it says from here on.",
+ ]);
+ expect(consequences({ browsers: 0, clis: 0, access_tokens: 0, member_tokens: 0, you: true })).toEqual([
+ "Saving signs you out at once: you sign in again.",
+ ]);
+ });
+
+ it("offer each limit's choices, the saved one among them", () => {
+ expect(browserMaxChoices().map((o) => o.label)).toEqual([
+ "8 hours",
+ "12 hours",
+ "A day",
+ "A week",
+ "30 days",
+ "While it's used",
+ ]);
+ // Set with the CLI to something the page doesn't offer.
+ expect(browserMaxChoices(36).map((o) => o.label)).toContain("36 hours");
+ expect(browserIdleChoices().find((o) => o.value === "43200")?.description).toBe("The default");
+ expect(tokenMaxChoices(60).map((o) => o.value)).toEqual(["7", "30", "60", "90", "365", "0"]);
+ });
+
+ it("tell people in Settings how long their devices stay signed in", () => {
+ expect(devicesNote(DEFAULT_POLICY)).toBeUndefined();
+ expect(
+ devicesNote({ ...DEFAULT_POLICY, browser_max_hours: 12, browser_idle_minutes: 60, cli_max_days: 30 }),
+ ).toBe(
+ "This instance signs out browsers 12 hours after they sign in, browsers unused for an hour and CLIs 30 days after they sign in.",
+ );
+ });
+});
diff --git a/web/src/lib/session-policy.ts b/web/src/lib/session-policy.ts
new file mode 100644
index 00000000..9590424f
--- /dev/null
+++ b/web/src/lib/session-policy.ts
@@ -0,0 +1,137 @@
+// How long sign-ins last and who makes access tokens: the instance's session policies (G.SessionPolicy), the
+// choices Admin → Sign-in offers for them, and the sentences it and Settings say about them. The rules mirror
+// crates/fctl-domain/src/session_policy.rs, and the sentences the CLI's (`fctl admin sign-in policies`).
+
+import type { SelectOption } from "@/components/ui/select";
+import type * as G from "@/gen";
+
+/** A policy as control planes from before them behave. */
+export const DEFAULT_POLICY: G.SessionPolicy = {
+ browser_max_hours: 0,
+ browser_idle_minutes: 30 * 24 * 60,
+ cli_max_days: 0,
+ access_token_max_days: 0,
+ member_access_tokens: true,
+};
+
+/** "a minute", "15 minutes", "an hour", "12 hours", "a day", "a week", "30 days", as the CLI says them. */
+export function minutes(m: number): string {
+ if (m === 1) return "a minute";
+ if (m === 60) return "an hour";
+ if (m === 1440) return "a day";
+ if (m === 10080) return "a week";
+ if (m === 525600) return "a year";
+ if (m % 1440 === 0) return `${m / 1440} days`;
+ if (m % 60 === 0) return `${m / 60} hours`;
+ return `${m} minutes`;
+}
+
+export const hours = (h: number) => (h === 8760 ? "a year" : minutes(h * 60));
+export const days = (d: number) => (d === 365 ? "a year" : minutes(d * 1440));
+
+const capital = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+
+/** The choices for one limit: `values` and the one saved, each in words; 0 is `none`, no limit. */
+function choices(
+ values: number[],
+ current: number | undefined,
+ words: (n: number) => string,
+ none?: string,
+ fallback?: number,
+): SelectOption[] {
+ const all = [...values];
+ if (current !== undefined && !all.includes(current)) all.push(current);
+ return all
+ .sort((a, b) => (a || Number.POSITIVE_INFINITY) - (b || Number.POSITIVE_INFINITY))
+ .map((n) => ({
+ value: String(n),
+ label: n === 0 ? (none ?? "") : capital(words(n)),
+ description: n === fallback ? "The default" : undefined,
+ }));
+}
+
+/** How long a browser stays signed in, however much it's used. */
+export const browserMaxChoices = (current?: number) =>
+ choices([0, 8, 12, 24, 168, 720], current, hours, "While it's used", 0);
+
+/** How long a browser may go unused. */
+export const browserIdleChoices = (current?: number) =>
+ choices([15, 60, 480, 1440, 10080, 43200], current, minutes, undefined, 43200);
+
+/** How long a CLI stays signed in. */
+export const cliMaxChoices = (current?: number) =>
+ choices([0, 1, 7, 30, 90], current, days, "While it's used", 0);
+
+/** The longest an access token lasts. */
+export const tokenMaxChoices = (current?: number) =>
+ choices([0, 7, 30, 90, 365], current, days, "As its maker chooses", 0);
+
+/** What a policy says, a sentence for browsers, CLIs and access tokens each, as the CLI says it. */
+export function describe(p: G.SessionPolicy): string[] {
+ const idle = minutes(p.browser_idle_minutes);
+ const browsers =
+ p.browser_max_hours > 0
+ ? `Browsers sign in again after ${hours(p.browser_max_hours)}, and after ${idle} unused.`
+ : `Browsers stay signed in while they're used, until ${idle} unused.`;
+ const clis =
+ p.cli_max_days > 0
+ ? `CLIs sign in again after ${days(p.cli_max_days)}, and after 180 days unused.`
+ : "CLIs stay signed in while they're used, until 180 days unused.";
+ const who = p.member_access_tokens ? "Everyone makes access tokens" : "Only admins make access tokens";
+ const tokens =
+ p.access_token_max_days > 0
+ ? `${who}, each lasting ${days(p.access_token_max_days)} at most.`
+ : `${who}, each lasting as long as its maker chooses.`;
+ return [browsers, clis, tokens];
+}
+
+/** "a", "a and b". */
+const and = (items: string[]) =>
+ items.length <= 1 ? (items[0] ?? "") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
+
+const count = (n: number, one: string, many: string) => (n === 1 ? `1 ${one}` : `${n} ${many}`);
+
+/** What saving a policy ends at once, as the CLI says it before it asks. */
+export function consequences(p: G.SessionPolicyPreview): string[] {
+ const out: string[] = [];
+ if (p.browsers > 0) out.push(count(p.browsers, "browser", "browsers"));
+ if (p.clis > 0) out.push(count(p.clis, "CLI", "CLIs"));
+ const lines: string[] = [];
+ if (out.length > 0)
+ lines.push(
+ `Saving signs out ${and(out)} at once${p.you ? ", yours among them" : ""}: their people sign in again.`,
+ );
+ else if (p.you) lines.push("Saving signs you out at once: you sign in again.");
+ if (p.access_tokens > 0) {
+ const members =
+ p.member_tokens === 0
+ ? ""
+ : p.member_tokens === p.access_tokens
+ ? ", all of them members'"
+ : `, ${p.member_tokens} of them members'`;
+ lines.push(
+ `It ends ${count(p.access_tokens, "access token", "access tokens")}${members}: scripts and CI that use ${p.access_tokens === 1 ? "it" : "them"} need new ones.`,
+ );
+ }
+ if (lines.length === 0) lines.push("Nobody is signed out now: sign-ins end as it says from here on.");
+ return lines;
+}
+
+/** Whether two policies say the same. */
+export const samePolicy = (a: G.SessionPolicy, b: G.SessionPolicy) =>
+ a.browser_max_hours === b.browser_max_hours &&
+ a.browser_idle_minutes === b.browser_idle_minutes &&
+ a.cli_max_days === b.cli_max_days &&
+ a.access_token_max_days === b.access_token_max_days &&
+ a.member_access_tokens === b.member_access_tokens;
+
+/** What Settings → Devices says of how long its sign-ins last, where the instance limits them more than by default. */
+export function devicesNote(p: G.SessionPolicy | undefined): string | undefined {
+ if (!p) return undefined;
+ const parts: string[] = [];
+ if (p.browser_max_hours > 0) parts.push(`browsers ${hours(p.browser_max_hours)} after they sign in`);
+ if (p.browser_idle_minutes < DEFAULT_POLICY.browser_idle_minutes)
+ parts.push(`browsers unused for ${minutes(p.browser_idle_minutes)}`);
+ if (p.cli_max_days > 0) parts.push(`CLIs ${days(p.cli_max_days)} after they sign in`);
+ return parts.length ? `This instance signs out ${and(parts)}.` : undefined;
+}
diff --git a/web/src/lib/sign-in.test.ts b/web/src/lib/sign-in.test.ts
index f175472c..2d65ff5f 100644
--- a/web/src/lib/sign-in.test.ts
+++ b/web/src/lib/sign-in.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import type * as G from "@/gen";
+import { DEFAULT_POLICY } from "./session-policy";
import {
consequences,
domainOf,
@@ -170,6 +171,7 @@ describe("changing the rules", () => {
passkeys: 9,
no_way_in: 3,
email: true,
+ sessions: DEFAULT_POLICY,
};
expect(today(overview)).toBe(
"52 people have an account: 38 with a password, 12 with Google and 9 with a passkey. 3 people haven't signed in yet.",
diff --git a/web/src/lib/tokens.test.ts b/web/src/lib/tokens.test.ts
index dcdb9690..33c7f924 100644
--- a/web/src/lib/tokens.test.ts
+++ b/web/src/lib/tokens.test.ts
@@ -1,6 +1,16 @@
import { describe, expect, it } from "vitest";
import type * as G from "@/gen";
-import { describeScope, example, formScope, NEW_TOKEN, ready, tokenRequest, words } from "./tokens";
+import {
+ describeScope,
+ example,
+ expiries,
+ fitExpiry,
+ formScope,
+ NEW_TOKEN,
+ ready,
+ tokenRequest,
+ words,
+} from "./tokens";
const place = (id: string, name?: string, slug?: string): G.TokenPlace => ({ id, name, slug });
@@ -76,6 +86,19 @@ describe("access tokens", () => {
expect(formScope({ ...NEW_TOKEN, access: "full", github: "comment" }, names)).toBeUndefined();
});
+ it("lasts no longer than the instance lets a token last", () => {
+ expect(expiries(0).map((e) => e.value)).toEqual(["7", "30", "90", "365", "never"]);
+ expect(expiries(90).map((e) => e.value)).toEqual(["7", "30", "90"]);
+ expect(expiries(60).map((e) => e.label)).toEqual(["7 days", "30 days", "60 days"]);
+ // The form's 90 days, or never, become the longest it lets.
+ expect(fitExpiry("90", 60)).toBe("60");
+ expect(fitExpiry("never", 30)).toBe("30");
+ expect(fitExpiry("7", 30)).toBe("7");
+ expect(fitExpiry("never", 0)).toBe("never");
+ expect(tokenRequest({ ...NEW_TOKEN, name: "CI", expires: "60" }).expires_in_days).toBe(60);
+ expect(tokenRequest({ ...NEW_TOKEN, name: "CI", expires: "never" }).expires_in_days).toBeUndefined();
+ });
+
it("needs a name, and a project when it names some", () => {
expect(ready(NEW_TOKEN)).toBe(false);
expect(ready({ ...NEW_TOKEN, name: "x" })).toBe(true);
diff --git a/web/src/lib/tokens.ts b/web/src/lib/tokens.ts
index 1fad0453..95ce3633 100644
--- a/web/src/lib/tokens.ts
+++ b/web/src/lib/tokens.ts
@@ -52,9 +52,32 @@ export interface TokenForm {
export const NEW_TOKEN: TokenForm = { name: "", access: "run", github: "push", expires: "90" };
+/** The days a form's expiry stands for; undefined for never. */
+export const expiryDays = (expires: string): number | undefined =>
+ expires === "never" ? undefined : Number(expires) || undefined;
+
+/**
+ * How long a new token may work, where the instance lets one last `max` days at most (0: as long as its maker
+ * chooses): the expiries within it, and the longest itself.
+ */
+export function expiries(max: number): { value: string; label: string; days?: number }[] {
+ if (max <= 0) return [...EXPIRIES];
+ const within = EXPIRIES.filter((e) => e.days !== undefined && e.days <= max);
+ if (!within.some((e) => e.days === max))
+ within.push({ value: String(max), label: max === 1 ? "1 day" : `${max} days`, days: max });
+ return within;
+}
+
+/** `expires` within what the instance lets a token last (`max` days; 0: any): the longest it lets, past it. */
+export function fitExpiry(expires: string, max: number): string {
+ if (max <= 0) return expires;
+ const days = expiryDays(expires);
+ return days === undefined || days > max ? String(max) : expires;
+}
+
/** The request that makes the token `f` describes. */
export function tokenRequest(f: TokenForm): G.CreateTokenRequest {
- const days = EXPIRIES.find((e) => e.value === f.expires)?.days;
+ const days = expiryDays(f.expires);
const req: G.CreateTokenRequest = { name: f.name.trim(), access: f.access };
if (days) req.expires_in_days = days;
if (f.places?.workspaces.length) req.workspaces = f.places.workspaces;
diff --git a/web/src/routes/admin.test.tsx b/web/src/routes/admin.test.tsx
index e976e162..1d47f2db 100644
--- a/web/src/routes/admin.test.tsx
+++ b/web/src/routes/admin.test.tsx
@@ -4,6 +4,7 @@ import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import type * as G from "@/gen";
import { keys } from "@/lib/queries";
+import { DEFAULT_POLICY } from "@/lib/session-policy";
import { Admin } from "./admin";
// No request is answered unless a test answers it: the page shows what the cache holds.
@@ -306,6 +307,7 @@ const instanceSettings = (s: Partial = {}): G.InstanceSettin
claude_refusals: 2,
sign_in: [],
self_sign_up: true,
+ ...DEFAULT_POLICY,
...s,
});
diff --git a/web/src/routes/admin.tsx b/web/src/routes/admin.tsx
index 544d5756..5a66794b 100644
--- a/web/src/routes/admin.tsx
+++ b/web/src/routes/admin.tsx
@@ -38,6 +38,7 @@ import { PageTabs, TabCount } from "@/components/page-tabs";
import { DriverLine } from "@/components/runner-driver";
import { SnapshotStoreLine } from "@/components/runner-snapshots";
import { SignInAdmin } from "@/components/sign-in/admin";
+import { SessionPolicies } from "@/components/sign-in/sessions";
import {
Avatar,
AvatarStack,
@@ -84,6 +85,7 @@ import {
import { buildsImages, runsImages } from "@/lib/images";
import { installCommand } from "@/lib/install";
import { keys, queryClient, useInstance, useMe, useRunners, useWorkspaces } from "@/lib/queries";
+import { DEFAULT_POLICY } from "@/lib/session-policy";
import { maxWorkspacesWords } from "@/lib/workspaces";
type Tab =
@@ -1847,10 +1849,12 @@ function useInstanceSettings() {
/** Admin → Sign-in: how people sign in, the providers and the domains that require one, then two-factor sign-in. */
function SignInTab() {
const { settings, save } = useInstanceSettings();
+ const overview = useQuery({ queryKey: keys.signIn, queryFn: api.signIn });
return (
<>
save.mutate(b)} saving={save.isPending} />
save.mutate(b)} saving={save.isPending} />
+
>
);
}
@@ -2473,6 +2477,7 @@ function SignInSettings({
claude_limit_pauses: true,
claude_instance_view: false,
claude_refusals: 2,
+ ...DEFAULT_POLICY,
};
const active = users.data?.users.filter((u) => u.status === "active") ?? [];
const using = active.filter(secured);
diff --git a/web/src/routes/settings.tsx b/web/src/routes/settings.tsx
index 5251a91b..5523017a 100644
--- a/web/src/routes/settings.tsx
+++ b/web/src/routes/settings.tsx
@@ -84,6 +84,7 @@ import { sampleTime, useHourCycle } from "@/lib/hour-cycle";
import { disablePush, enablePush, forgetPush, permission, pushSupport } from "@/lib/push";
import { fetchMe, keys, queryClient, useInstance, useMe, useWorkspaces } from "@/lib/queries";
import { forgetLeft } from "@/lib/reopen";
+import { devicesNote } from "@/lib/session-policy";
import {
askedTab,
claudeGist,
@@ -1860,6 +1861,8 @@ function signedInWith(method?: string): string | undefined {
function Devices() {
const list = useQuery({ queryKey: keys.tokens, queryFn: api.tokens });
+ const { data: me } = useMe();
+ const limits = devicesNote(me?.sessions);
const revoke = useMutation({
mutationFn: (id: string) => api.deleteToken(id),
onSuccess: () => list.refetch(),
@@ -1868,7 +1871,7 @@ function Devices() {
return (
From f06cd8bf2338346478c40dc839d56197f23282e1 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Wed, 25 Nov 2026 23:14:07 +0000
Subject: [PATCH 03/11] docs: how long people stay signed in, and ADR 0102
---
...-instances-limit-how-long-sign-ins-last.md | 64 +++++++++++++++++++
docs/adr/README.md | 1 +
docs/api.md | 18 ++++++
docs/architecture.md | 19 +++++-
docs/cli.md | 13 ++++
docs/llms.txt | 2 +-
docs/organizations.md | 10 +++
docs/security.md | 13 +++-
docs/self-hosting.md | 42 +++++++++++-
9 files changed, 175 insertions(+), 7 deletions(-)
create mode 100644 docs/adr/0102-instances-limit-how-long-sign-ins-last.md
diff --git a/docs/adr/0102-instances-limit-how-long-sign-ins-last.md b/docs/adr/0102-instances-limit-how-long-sign-ins-last.md
new file mode 100644
index 00000000..2f3e13fc
--- /dev/null
+++ b/docs/adr/0102-instances-limit-how-long-sign-ins-last.md
@@ -0,0 +1,64 @@
+# 0102: Instances limit how long sign-ins last
+
+2026-11-25 · accepted
+
+## Context
+
+A browser signed in to fctl stayed signed in while it was used, until 30
+days unused; a CLI until 180 days unused; an access token as long as its
+maker chose, for ever included. Once an organization requires its
+provider of its domains ([ADR 0099](0099-domains-require-signing-in-with-their-provider.md)),
+closing someone's account at the provider stops their next sign-in, but
+not the sign-ins they have: someone who left kept fctl for as long as
+their laptop's browser or CLI stayed in use. Google offers OpenID
+Connect apps no back-channel logout, and its Cross-Account Protection
+events, which could tell fctl of some closed accounts, take a service
+account of each organization's to receive. Security
+teams also ask for limits of their own: a browser that signs in again
+every working day, a CLI every month, no access token older than 90
+days, and no tokens made by people outside a few admins (#618).
+
+## Decision
+
+- **Instance admins set session policies**, beside the rules: how long a
+ browser stays signed in from its sign-in however much it's used, how
+ long one may sit unused (30 days, the default, at most), how long a
+ CLI stays signed in from `fctl login`, the oldest an access token may
+ be, and whether members make access tokens. Each limit is off by
+ default but the browser's unused one, which keeps its 30 days: nothing
+ changes until an admin says so.
+- **A policy holds every sign-in, those made before it too.** Every
+ request checks its token against it, as it checks the rules, and saving
+ one deletes at once what it ends, so that nothing it ended comes back
+ when it's relaxed. Admin → Sign-in and `fctl admin sign-in policies`
+ say what saving ends before it saves, and letting anything last longer
+ is a sensitive action.
+- **Signing in again goes through the provider.** That is how a closed
+ account ends: the shorter the policy, the sooner. Access tokens don't
+ sign in again, so their limit and who makes them are part of the
+ policy.
+- **Unused means no request.** The control plane sees requests, not
+ people: a tab left open on a page that updates itself counts as use,
+ and the pages say so.
+- **Admin tokens and service accounts' secrets aren't held to it.** They
+ are machines' credentials, made by admins for a directory sync or a bot
+ with an end of their own, and ending them with people's would stop the
+ sync that offboards people.
+- **The primary instance owner is held to it like everyone else.** A
+ policy ends sign-ins and nothing more: whoever it signs out signs in
+ again, the owner with their password while the provider is down.
+
+## Consequences
+
+- An organization that requires Google and signs browsers out after 12
+ hours has someone it closed out of Google out of fctl within 12 hours,
+ and out of their CLI within its limit; their access tokens last until
+ their own limit unless an admin disables the account.
+- A policy that shortens sign-ins signs people out the moment it's saved,
+ the admin who saves it among them if theirs is older: the preview says
+ so.
+- Members' access tokens that go when members may no longer make them
+ don't come back when they may again: their people make new ones.
+- Signals from a provider that someone signed out or left (Okta's
+ Universal Logout, OpenID back-channel logout, Google's Cross-Account
+ Protection), which would end sign-ins at once, remain later work.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 6334f9f8..dc2e2f2f 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -107,3 +107,4 @@ supersede an earlier one. Copy the newest record to start a new one.
| [0099](0099-domains-require-signing-in-with-their-provider.md) | Domains require signing in with their provider |
| [0100](0100-autopilots-keep-trying-after-their-sessions-fail.md) | Autopilots keep trying after their sessions fail (experimental) |
| [0101](0101-runners-keep-snapshots-in-a-bucket-of-their-own.md) | Runners keep snapshots in a bucket of their own |
+| [0102](0102-instances-limit-how-long-sign-ins-last.md) | Instances limit how long sign-ins last |
diff --git a/docs/api.md b/docs/api.md
index afcd5795..ceb0fb3a 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -652,6 +652,24 @@ out everywhere, as a password reset does. Each token in `GET
`passkey` or `google`), and `GET /api/v1/auth/me` the rule that covers you
(`sign_in`).
+How long sign-ins last ([How long people stay signed
+in](self-hosting.md#how-long-people-stay-signed-in)) is five fields of the
+same settings: `browser_max_hours` (0: while it's used),
+`browser_idle_minutes` (5 to 43200, 30 days by default), `cli_max_days`
+(0: while it's used), `access_token_max_days` (0: as its maker chooses)
+and `member_access_tokens`. `GET /api/v1/admin/sign-in` has them as
+`sessions`, and `POST /api/v1/admin/sign-in/sessions/preview` with them
+says what saving them would end at once, changing nothing: `{"browsers",
+"clis", "access_tokens", "member_tokens", "you"}`. Saving them with `PATCH
+/api/v1/admin/settings` ends those, and asks the caller to confirm it's
+them (`verification_required`) where it lets anything last longer. A CLI's
+or an access token's request past what they let it last answers `401`
+(`unauthorized`), saying why; `POST /api/v1/auth/tokens` refuses an access
+token that would last longer (`validation`, `expires_in_days`), and
+a member's where only admins make them (`403`, `forbidden`). `GET /api/v1/auth/me` has
+them as `sessions`, and each token's `expires_at` in `GET
+/api/v1/auth/tokens` says when it ends under them.
+
## Runner pools
What a pool (an enrollment token's runners) needs now, for whatever scales
diff --git a/docs/architecture.md b/docs/architecture.md
index 430f4553..e6af4055 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -436,8 +436,23 @@ by its id, `google` ([ADR 0099](adr/0099-domains-require-signing-in-with-their-p
token, removes one. Saving rules that let anyone sign in another way
(a domain let go, passkeys let in, another provider) is a sensitive
action (`Sensitive::RelaxSignIn`). Closing someone's account at the
- provider stops their next sign-in, not the sessions they have:
- disabling their account here does that.
+ provider stops their next sign-in, not the sign-ins they have:
+ disabling their account here does that, and session policies keep them
+ short.
+- **Session policies** (`InstanceSettings::browser_max_hours`,
+ `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`,
+ `member_access_tokens`; Admin → Sign-in → Staying signed in, `fctl admin
+ sign-in policies`): how long a browser's and a CLI's sign-ins last from
+ when they were made, how long a browser lasts unused (30 days unless
+ less), the oldest an access token may be, and whether members make them
+ ([ADR 0102](adr/0102-instances-limit-how-long-sign-ins-last.md)). Every
+ request checks its token against them as `auth::authenticate` reads it
+ (`fctl_domain::session_policy::ended`), those made before them too; a
+ token's sliding end never passes them, and its use is recorded at least
+ every quarter of the time a browser may sit unused. Saving one deletes
+ what it ends at once, in one statement (`sign_in::revoke_ended`, whose
+ count `POST /admin/sign-in/sessions/preview` shows first). Admin tokens
+ and service accounts' secrets aren't held to them.
- **Accounts only from the directory.** With `InstanceSettings::self_sign_up`
off, a provider's sign-in makes an account only for an address with an
allowlist entry of its own (an invitation's, or one an admin allowed):
diff --git a/docs/cli.md b/docs/cli.md
index 5a966d59..55234ee0 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1709,6 +1709,9 @@ fctl admin sign-in # the providers, the domains that req
fctl admin sign-in require acme.com acme.dev # their people sign in with Google alone: says whom it concerns, then asks
fctl admin sign-in require acme.com --passkeys --yes # passkeys alone sign them in too; without asking
fctl admin sign-in unrequire acme.dev # its people sign in as they like again
+fctl admin sign-in policies # how long sign-ins last, and who makes access tokens
+fctl admin sign-in policies --browser-max 12h --browser-idle 1h # browsers sign in again after 12 hours, and out after an hour unused
+fctl admin sign-in policies --cli-max 30d --token-max 90d --member-tokens off --yes # says what it ends at once; without asking
fctl admin unlink grace@example.com # her Google account was recreated: signs her out, and her next Google sign-in links the new one
fctl admin reset-two-factor grace@example.com # they lost their phone and recovery codes
fctl admin reset-link grace@example.com # a link that sets their password (emailed to them where the instance sends email)
@@ -1727,6 +1730,16 @@ your address there). A CLI whose sign-in a domain's rule doesn't meet
says so, and signs in again with `fctl login`
([Requiring Google for your domains](self-hosting.md#requiring-google-for-your-domains)).
+`fctl admin sign-in policies` takes durations as `12h`, `30d` or `none`
+(no limit): whole hours for browsers' `--browser-max`, whole days for
+`--cli-max` and `--token-max`, and 5 minutes to 30 days for
+`--browser-idle`. Like `require`, it prints what saving ends at once
+before it asks ("Saving signs out 14 browsers and 3 CLIs at once…"), and
+`--json` prints the policy once it's saved
+([How long people stay signed in](self-hosting.md#how-long-people-stay-signed-in)).
+A CLI signed in longer than the policy lets one says so, and signs in
+again with `fctl login`.
+
### Provisioning people with an admin token
Where a self-hosted instance's deployment turns them on
diff --git a/docs/llms.txt b/docs/llms.txt
index 55b3c084..9c7adb8a 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -73,7 +73,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · GitHub webhooks
- **Session**: `owner` (who started it, while they may still start sessions in the project, and the project's maintainers and owners: stop, resume, archive, share), `editor` (message and interrupt), `viewer` (read). Sessions can be shared with people in the same workspace, as viewers, editors or owners.
- **Access token**: `read` (like a viewer), `run` (like an editor, and it stops and resumes the sessions it started), `full` (whatever its person may in its projects). A limited token never reaches the account, workspaces' people and settings, Claude connections, other tokens or administration.
- **Admin token** (`fctl_adm_…`, id `adt_…`; self-hosted instances whose deployment sets `FCTL_ADMIN_TOKENS=1`, never app.fctl.sh): an instance admin's, for programs that provision people. It acts as that admin on the admin API's people endpoints alone: creates accounts (`POST /api/v1/admin/users`), reads one with their workspaces and projects (`GET /api/v1/admin/users/{id or address}`), changes names, primary address, commit email and status (`PATCH`), sets their picture and the Claude token their sessions run on (`PUT …/avatar`, `PUT …/claude`), adds them to any workspace and project or takes them out (`PUT`/`DELETE …/workspaces/{workspace}`, `…/projects/{project}`), and deletes them. A new account has no password (set one with `password`, or the link `fctl admin reset-link` makes, except where Google is required for its domain): where the instance has Google sign-in and Google hosts the address (Workspace or Gmail), the person's first Google sign-in links Google to it. It changes no roles and never the primary instance owner's account; only the primary owner's tokens change admins'. CLI: `fctl admin tokens create NAME`, then `FCTL_TOKEN=fctl_adm_… fctl admin users create|show|set|add|remove`.
-- **Sign-in rules** (instance admins: Admin → Sign-in, `fctl admin sign-in require acme.com acme.dev`, `PATCH /api/v1/admin/settings` with `sign_in`): the people with an address at those domains sign in with Google alone, as that address (a Google Workspace account's): passwords, passkeys alone (unless `--passkeys`) and personal Google accounts stop working, and saving it deletes their browser sessions, CLI sign-ins, access tokens and admin tokens made another way, before the rule too; their next Google sign-in links Google and takes their password. Closing their Google account stops their next sign-in, not their sessions: disable their account too. The primary instance owner keeps every way in, for when Google is down; a rule that would sign out the admin who saves it waits until they sign in with Google. `fctl admin sign-in` shows whom each covers; `POST /api/v1/admin/sign-in/preview` says what a change would do; `fctl admin set --self-sign-up off` makes signing in make no accounts (only invitations, allowed addresses and admin tokens). Someone whose Workspace account was recreated at the same address: `fctl admin unlink ada@acme.com` signs them out everywhere, then their next Google sign-in links the new one; an address handed to someone else calls for `fctl admin disable` instead. A CLI refused by a rule signs in again with `fctl login`.
+- **Sign-in rules** (instance admins: Admin → Sign-in, `fctl admin sign-in require acme.com acme.dev`, `PATCH /api/v1/admin/settings` with `sign_in`): the people with an address at those domains sign in with Google alone, as that address (a Google Workspace account's): passwords, passkeys alone (unless `--passkeys`) and personal Google accounts stop working, and saving it deletes their browser sessions, CLI sign-ins, access tokens and admin tokens made another way, before the rule too; their next Google sign-in links Google and takes their password. Closing their Google account stops their next sign-in, not their sessions: disable their account too. The primary instance owner keeps every way in, for when Google is down; a rule that would sign out the admin who saves it waits until they sign in with Google. `fctl admin sign-in` shows whom each covers; `POST /api/v1/admin/sign-in/preview` says what a change would do; `fctl admin set --self-sign-up off` makes signing in make no accounts (only invitations, allowed addresses and admin tokens). Someone whose Workspace account was recreated at the same address: `fctl admin unlink ada@acme.com` signs them out everywhere, then their next Google sign-in links the new one; an address handed to someone else calls for `fctl admin disable` instead. A CLI refused by a rule signs in again with `fctl login`. **Session policies** (`fctl admin sign-in policies`, Admin → Sign-in → Staying signed in, `PATCH /api/v1/admin/settings` with `browser_max_hours`, `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`, `member_access_tokens`): `--browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d --member-tokens off` makes browsers and CLIs sign in again (through Google where their domain requires it) and caps access tokens, those made before too; it prints what saving ends at once and asks unless `--yes` (`POST /api/v1/admin/sign-in/sessions/preview`). A CLI or token past it answers 401 saying why: `fctl login`, or a new token within the limit.
- **Service account**: as the person a request names, what an access token that runs sessions does, in its workspace's projects (start sessions, message, interrupt, stop and resume theirs, run schedules, keep memory), within that person's roles; as nobody, it reads them. Never the account, people, settings, secrets, tokens or live connections (`/ws`): read events with `fctl logs` or `GET /api/v1/sessions/{id}/events`.
## Session lifecycle
diff --git a/docs/organizations.md b/docs/organizations.md
index 78c725d6..11238db2 100644
--- a/docs/organizations.md
+++ b/docs/organizations.md
@@ -119,6 +119,16 @@ two-factor requirement. [Requiring Google for your
domains](self-hosting.md#requiring-google-for-your-domains) has the
details.
+How long sign-ins last is yours to say too, so that someone whose Google
+account you closed is out of fctl soon after, as their sign-ins end: a
+browser's after 12 hours, say, a CLI's after 30 days, and access tokens'
+after 90, which only admins make
+([How long people stay signed in](self-hosting.md#how-long-people-stay-signed-in)):
+
+```sh
+fctl admin sign-in policies --browser-max 12h --cli-max 30d --token-max 90d --member-tokens off
+```
+
## People from your directory
On an instance of yours, your identity provider, your HR system or a
diff --git a/docs/security.md b/docs/security.md
index 49f59d01..f1f8d213 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -140,8 +140,17 @@ owner and purpose), so a value copied between rows does not decrypt.
while the provider is down; an admin can't save a rule their own
sign-in doesn't meet, and letting a domain go, or passkeys in, is a
sensitive action. Closing someone's account at the provider stops their
- next sign-in, not the sessions they have: disable their account here
- too.
+ next sign-in, not the sign-ins they have: disable their account here
+ too, or keep sign-ins short.
+- **How long sign-ins last.** A browser's sign-in ends after 30 days
+ unused, a CLI's after 180, and an access token when its maker chose.
+ Instance admins can say less (Admin → Sign-in → Staying signed in,
+ `fctl admin sign-in policies`): browsers signed in at most so many
+ hours, however much they're used, and signed out after as little as 5
+ minutes unused; CLIs at most so many days; access tokens no older than
+ so many days, and made by admins alone. Every request checks its token
+ against them, those made before too, and saving one ends the sign-ins
+ it doesn't let last. Letting them last longer is a sensitive action.
- **Sensitive actions take a passkey or a code**, where the primary
instance owner turns that on (off by default): inviting and promoting
admins, handing over the primary owner's and workspaces' primary admin
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index a730e8ab..065018e3 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1170,9 +1170,10 @@ Where your people's addresses are your Google Workspace's, they can sign
in with it alone: under its two-step verification and device checks,
unable to sign in again once you close their Google account, and with no
password of fctl's to forget or leave behind. Closing a Google account
-doesn't end the sessions its person has already: disable their account
+doesn't end the sign-ins its person has already: disable their account
here too as they leave (or with your [admin
-token](#provision-people-with-admin-tokens)'s sync). Under **Admin → Sign-in → Domains that sign in
+token](#provision-people-with-admin-tokens)'s sync), or keep sign-ins
+short ([How long people stay signed in](#how-long-people-stay-signed-in)). Under **Admin → Sign-in → Domains that sign in
with a provider**, choose **Require a provider** and give your domains
(`acme.com, acme.dev`), or:
@@ -1243,6 +1244,43 @@ and the sign-in page tells people without one to ask an admin.
fctl signs people in through Google alone today. SAML, Okta, Microsoft
Entra ID and other OpenID Connect providers aren't supported yet.
+### How long people stay signed in
+
+By default a browser stays signed in while it's used, until 30 days
+unused; a CLI until 180 days unused; and an access token as long as its
+maker chose, for ever included. Under **Admin → Sign-in → Staying signed
+in**, or with `fctl admin sign-in policies`, an instance admin sets:
+
+- **Browsers sign in again after** a set time, however much they're used
+ (`--browser-max 12h`), and **sign out unused for** less than 30 days
+ (`--browser-idle 1h`, at least 5 minutes). A tab left open on a page
+ that updates itself counts as use.
+- **CLIs sign in again after** a set number of days (`--cli-max 30d`), with
+ `fctl login`.
+- **Access tokens last at most** a set number of days (`--token-max 90d`):
+ new ones can't be made to last longer, and older ones end once they're
+ that old.
+- **Members make access tokens**, or only admins (`--member-tokens off`):
+ members' tokens stop working, and they use the CLI, signed in as
+ themselves.
+
+```sh
+fctl admin sign-in policies --browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d
+```
+
+Before it saves, it shows what it ends at once ("Saving signs out 14
+browsers and 3 CLIs at once: their people sign in again. It ends 5 access
+tokens: scripts and CI that use them need new ones."), and the CLI asks
+unless `--yes`. Every request checks its sign-in against the policy,
+those made before it too, and **Settings** tells people how long theirs
+last. Where your domains require Google, signing in again goes through
+Google, which checks they still may: someone whose Google account you
+closed is out of fctl once their browser's and CLI's sign-ins end. Their
+access tokens don't go through Google, so limit those, or keep members
+from making them, too. Letting sign-ins or tokens last longer again asks
+you to confirm it's you, where the instance asks for that. Admin tokens
+and service accounts' secrets last as long as their makers chose.
+
## Email (optional)
Without email, admins copy invite and password-reset links from the app. To
From 5aea4f9fc07851e11b52596007289b38aefa8c41 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Wed, 25 Nov 2026 23:16:07 +0000
Subject: [PATCH 04/11] test(control): name the rows of the session policy test
---
crates/fctl-control/src/sign_in.rs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/crates/fctl-control/src/sign_in.rs b/crates/fctl-control/src/sign_in.rs
index e86522e8..825dc4ca 100644
--- a/crates/fctl-control/src/sign_in.rs
+++ b/crates/fctl-control/src/sign_in.rs
@@ -616,7 +616,8 @@ mod d1_tests {
.run()
.await?;
// id, kind, user, created, last used, expires.
- let tokens: [(&str, TokenKind, &str, i64, Option, Option); 9] = [
+ type Row<'a> = (&'a str, TokenKind, &'a str, i64, Option, Option);
+ let tokens: [Row; 9] = [
// A browser signed in 13 hours ago, used a minute ago.
(
"tok_web_old",
From 443462b963af52aeb55baf3e73091590b845137c Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Wed, 25 Nov 2026 23:25:19 +0000
Subject: [PATCH 05/11] feat(control): take sign-ins and requests only from an
instance's networks
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Instance admins name the IP ranges people sign in and send requests
from (InstanceSettings.networks): browsers, CLIs, access tokens, admin
tokens and service accounts elsewhere are refused, while runners,
webhooks and published links connect from anywhere. The primary
instance owner signs in from anywhere in a browser or the CLI, and an
admin can't save ranges their own address is outside of. Admin → Sign-in
has them beside the admin's address, `fctl admin sign-in policies
--networks` sets them, and the sign-in page says when a browser is
outside them.
---
crates/fctl-control/src/api/admin.rs | 15 ++
crates/fctl-control/src/api/auth.rs | 17 +-
crates/fctl-control/src/api/sign_in.rs | 13 ++
crates/fctl-control/src/auth.rs | 21 ++
crates/fctl-control/src/service_accounts.rs | 3 +
crates/fctl-control/src/sign_in.rs | 24 +-
crates/fctl-domain/src/lib.rs | 1 +
crates/fctl-domain/src/networks.rs | 220 +++++++++++++++++++
crates/fctl-domain/src/verify.rs | 42 +++-
crates/fctl-proto/src/api.rs | 28 +++
crates/fctl/src/cmd/admin.rs | 11 +-
crates/fctl/src/cmd/sign_in.rs | 141 ++++++++++--
web/src/components/sign-in/networks.test.tsx | 108 +++++++++
web/src/components/sign-in/networks.tsx | 123 +++++++++++
web/src/gen/InstanceSettings.ts | 12 +-
web/src/gen/SignInInfo.ts | 9 +-
web/src/gen/SignInOverview.ts | 11 +-
web/src/gen/UpdateInstanceSettingsRequest.ts | 8 +-
web/src/lib/google-sign-in.test.ts | 1 +
web/src/lib/google-sign-in.ts | 3 +
web/src/routes/admin.test.tsx | 1 +
web/src/routes/admin.tsx | 3 +
web/src/routes/auth.test.tsx | 9 +
web/src/routes/auth.tsx | 6 +
24 files changed, 802 insertions(+), 28 deletions(-)
create mode 100644 crates/fctl-domain/src/networks.rs
create mode 100644 web/src/components/sign-in/networks.test.tsx
create mode 100644 web/src/components/sign-in/networks.tsx
diff --git a/crates/fctl-control/src/api/admin.rs b/crates/fctl-control/src/api/admin.rs
index 593775f8..f5f0dea3 100644
--- a/crates/fctl-control/src/api/admin.rs
+++ b/crates/fctl-control/src/api/admin.rs
@@ -1162,6 +1162,21 @@ pub async fn update_settings(ctx: &mut Ctx, req: &mut Request) -> AppResult AppResult {
admin_tokens: ctx.cfg.admin_tokens,
service_account_consent: settings.service_account_consent,
},
- sign_in: Some(crate::sign_in::info(&ctx.cfg, &settings)),
+ sign_in: Some(crate::sign_in::info(&ctx.cfg, &settings, ctx.ip.as_deref())),
})
}
@@ -326,6 +326,11 @@ pub async fn login(ctx: &mut Ctx, req: &mut Request) -> AppResult {
if let Err(required) = user.admits(&instance, &SignedIn::password()) {
return Err(AppError(crate::sign_in::password_refused(&required)));
}
+ // Before a code is asked for: from outside the instance's networks it
+ // would sign nobody in.
+ if crate::sign_in::outside(&instance, ctx.ip.as_deref(), &user, true) {
+ return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
+ }
let settings = user.two_factor_settings(&instance);
if two_factor::asks(
&settings,
@@ -749,6 +754,11 @@ pub async fn reset_password(ctx: &mut Ctx, req: &mut Request) -> AppResult AppResult AppResult AppResult {
method_domain: how.domain,
email: ctx.cfg.email.is_some(),
sessions,
+ networks: settings.networks.clone(),
+ address: ctx.ip.clone(),
})
}
diff --git a/crates/fctl-control/src/auth.rs b/crates/fctl-control/src/auth.rs
index 3b880421..20093eb7 100644
--- a/crates/fctl-control/src/auth.rs
+++ b/crates/fctl-control/src/auth.rs
@@ -156,6 +156,11 @@ pub async fn start_web_session(
) -> AppResult<()> {
let verified_at = confirmed.then_some(ctx.now);
let settings = crate::instance::settings(&ctx.db).await?;
+ // Every way into a browser comes here: none from outside the
+ // instance's networks, but the primary instance owner's.
+ if crate::sign_in::outside(&settings, ctx.ip.as_deref(), user, true) {
+ return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
+ }
let (token_id, _) = issue_token(
ctx,
&user.id,
@@ -416,6 +421,19 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
"Your account is disabled. Ask an admin for access.",
)));
}
+ // From outside the instance's networks: a browser is as signed out,
+ // and keeps its sign-in for when it's back inside one.
+ if crate::sign_in::outside(
+ &settings,
+ ctx.ip.as_deref(),
+ &found.user,
+ kind != TokenKind::Pat,
+ ) {
+ if via_cookie {
+ return Ok(());
+ }
+ return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
+ }
// A domain of theirs signs in with a provider only: a sign-in made
// another way, or before fctl kept how, no longer lets them in. A
// browser's is signed out, and the sign-in page shows the way in.
@@ -518,6 +536,9 @@ async fn admin_token(ctx: &mut Ctx, secret: &str) -> AppResult<()> {
)));
}
let settings = crate::instance::parse(found.instance_settings.as_deref());
+ if crate::sign_in::outside(&settings, ctx.ip.as_deref(), &found.user, false) {
+ return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
+ }
// Held to the rules as its admin's own sign-ins are: one their domain's
// rule doesn't meet stops.
let how = SignedIn::read(found.auth_method.as_deref(), found.auth_domain.as_deref());
diff --git a/crates/fctl-control/src/service_accounts.rs b/crates/fctl-control/src/service_accounts.rs
index e4e34f82..2a6c54b6 100644
--- a/crates/fctl-control/src/service_accounts.rs
+++ b/crates/fctl-control/src/service_accounts.rs
@@ -274,6 +274,9 @@ pub async fn authenticate(ctx: &mut Ctx, secret: &str) -> AppResult<()> {
)));
};
let settings = crate::instance::settings(&ctx.db).await?;
+ if !fctl_domain::networks::admits(&settings.networks, ctx.ip.as_deref()) {
+ return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
+ }
// Its keeper left or lost the role, or, as it acts with their
// authority, has to set up two-factor sign-in first, as their own
// tokens wait too.
diff --git a/crates/fctl-control/src/sign_in.rs b/crates/fctl-control/src/sign_in.rs
index 825dc4ca..8d301699 100644
--- a/crates/fctl-control/src/sign_in.rs
+++ b/crates/fctl-control/src/sign_in.rs
@@ -70,8 +70,9 @@ pub fn statuses(cfg: &Config, people: &[Person]) -> Vec {
.collect()
}
-/// What the sign-in page needs ([`fctl_proto::api::InstanceInfo::sign_in`]).
-pub fn info(cfg: &Config, settings: &InstanceSettings) -> SignInInfo {
+/// What the sign-in page needs ([`fctl_proto::api::InstanceInfo::sign_in`]),
+/// for a request from `ip`.
+pub fn info(cfg: &Config, settings: &InstanceSettings, ip: Option<&str>) -> SignInInfo {
SignInInfo {
providers: PROVIDERS
.iter()
@@ -84,9 +85,28 @@ pub fn info(cfg: &Config, settings: &InstanceSettings) -> SignInInfo {
.collect(),
rules: settings.sign_in.clone(),
self_sign_up: settings.self_sign_up,
+ outside: !fctl_domain::networks::admits(&settings.networks, ip),
}
}
+/// Whether the instance's networks refuse `user`'s request from `ip`
+/// (`fctl_domain::networks`). `signing_in`: it's a browser's or a CLI's
+/// sign-in, or a request with one, which the primary instance owner makes
+/// from anywhere; their access tokens and admin tokens are held to them.
+pub fn outside(
+ settings: &InstanceSettings,
+ ip: Option<&str>,
+ user: &UserRow,
+ signing_in: bool,
+) -> bool {
+ !fctl_domain::networks::admits(&settings.networks, ip) && !(signing_in && user.is_owner())
+}
+
+/// The refusal of a request from outside the instance's networks.
+pub fn outside_refused(ip: Option<&str>) -> ApiError {
+ ApiError::forbidden(fctl_domain::networks::refusal(ip))
+}
+
/// What a rule requires, as refusals begin: "acme.com signs in with
/// Google".
pub fn says(required: &Required) -> String {
diff --git a/crates/fctl-domain/src/lib.rs b/crates/fctl-domain/src/lib.rs
index 5f6736fe..39729d62 100644
--- a/crates/fctl-domain/src/lib.rs
+++ b/crates/fctl-domain/src/lib.rs
@@ -41,6 +41,7 @@ pub mod merge_checks;
pub mod metadata;
pub mod models;
pub mod naming;
+pub mod networks;
pub mod notify;
pub mod order;
pub mod perm;
diff --git a/crates/fctl-domain/src/networks.rs b/crates/fctl-domain/src/networks.rs
new file mode 100644
index 00000000..7e7b638d
--- /dev/null
+++ b/crates/fctl-domain/src/networks.rs
@@ -0,0 +1,220 @@
+//! The networks an instance takes sign-ins and requests from
+//! (`InstanceSettings::networks`, #618): IP ranges such as an office's or
+//! a VPN's, in CIDR notation. None, the default, takes them from
+//! anywhere.
+//!
+//! People's browsers, CLIs and access tokens, admin tokens and service
+//! accounts' secrets are held to them; runners' connections, webhooks
+//! (GitHub's, Linear's), published links and the identity tokens' keys
+//! aren't, as they never sign anyone in. The primary instance owner signs
+//! in from anywhere, in a browser or with the CLI: the instance's way in
+//! when its network changes. Their access tokens and admin tokens are held
+//! to them as everyone's are.
+
+use fctl_proto::ApiError;
+use std::net::IpAddr;
+
+/// The most ranges an instance names.
+pub const MAX_NETWORKS: usize = 100;
+
+/// A range of addresses: an address and how many of its leading bits a
+/// member shares with it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Network {
+ addr: IpAddr,
+ prefix: u8,
+}
+
+impl Network {
+ /// A range as an admin types it: `10.0.0.0/8`, `2001:db8::/32`, or an
+ /// address alone, which is a range of one. Its host bits must be zero,
+ /// so that what's saved says what it takes.
+ pub fn parse(input: &str) -> Result {
+ let s = input.trim();
+ let bad = || format!("{s} isn't a network: give one like 203.0.113.0/24 or 2001:db8::/32");
+ let (addr, prefix) = match s.split_once('/') {
+ Some((a, p)) => (a, Some(p)),
+ None => (s, None),
+ };
+ let addr: IpAddr = addr.trim().parse().map_err(|_| bad())?;
+ let max = if addr.is_ipv4() { 32 } else { 128 };
+ let prefix = match prefix {
+ Some(p) => p.trim().parse::().map_err(|_| bad())?,
+ None => max,
+ };
+ if prefix > max {
+ return Err(bad());
+ }
+ let net = Self { addr, prefix };
+ if net.masked(addr) != addr {
+ return Err(format!(
+ "{s} has bits past its prefix: did you mean {}?",
+ Self {
+ addr: net.masked(addr),
+ prefix
+ }
+ ));
+ }
+ Ok(net)
+ }
+
+ /// `ip` with the bits past this range's prefix cleared.
+ fn masked(&self, ip: IpAddr) -> IpAddr {
+ match ip {
+ IpAddr::V4(v4) => {
+ let bits = u32::from(v4);
+ let mask = u32::MAX
+ .checked_shl(32 - u32::from(self.prefix))
+ .unwrap_or(0);
+ IpAddr::V4((bits & mask).into())
+ }
+ IpAddr::V6(v6) => {
+ let bits = u128::from(v6);
+ let mask = u128::MAX
+ .checked_shl(128 - u32::from(self.prefix))
+ .unwrap_or(0);
+ IpAddr::V6((bits & mask).into())
+ }
+ }
+ }
+
+ /// Whether `ip` is in it. An IPv4 address mapped into IPv6
+ /// (`::ffff:203.0.113.7`) counts as the IPv4 one.
+ pub fn contains(&self, ip: IpAddr) -> bool {
+ let ip = match ip {
+ IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(ip, IpAddr::V4),
+ v4 => v4,
+ };
+ ip.is_ipv4() == self.addr.is_ipv4() && self.masked(ip) == self.addr
+ }
+}
+
+impl std::fmt::Display for Network {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}/{}", self.addr, self.prefix)
+ }
+}
+
+/// `networks` as the instance keeps them, from what an admin saves: each
+/// checked and written as `address/prefix`, once each, [`MAX_NETWORKS`]
+/// at most.
+pub fn check(networks: &[String]) -> Result, ApiError> {
+ let mut out: Vec = Vec::new();
+ for typed in networks.iter().filter(|n| !n.trim().is_empty()) {
+ let net = Network::parse(typed).map_err(|m| ApiError::validation("networks", m))?;
+ let s = net.to_string();
+ if !out.contains(&s) {
+ out.push(s);
+ }
+ }
+ if out.len() > MAX_NETWORKS {
+ return Err(ApiError::validation(
+ "networks",
+ format!("Name {MAX_NETWORKS} networks at most: a wider one takes in several"),
+ ));
+ }
+ Ok(out)
+}
+
+/// Whether `networks` (as kept) take a request from `ip`: they name none,
+/// or one holds it. An address that isn't one, or none at all, is in none
+/// of them.
+pub fn admits(networks: &[String], ip: Option<&str>) -> bool {
+ if networks.is_empty() {
+ return true;
+ }
+ let Some(ip) = ip.and_then(|i| i.trim().parse::().ok()) else {
+ return false;
+ };
+ networks
+ .iter()
+ .filter_map(|n| Network::parse(n).ok())
+ .any(|n| n.contains(ip))
+}
+
+/// Whether saving `next` in place of `current` takes requests from
+/// anywhere `current` didn't: from anywhere at all, or from a network it
+/// didn't name. Such a change takes confirming it's you.
+pub fn widens(current: &[String], next: &[String]) -> bool {
+ if current.is_empty() {
+ return false;
+ }
+ let read = |n: &String| Network::parse(n).map_or_else(|_| n.clone(), |n| n.to_string());
+ let was: Vec = current.iter().map(read).collect();
+ let next: Vec = next
+ .iter()
+ .filter(|n| !n.trim().is_empty())
+ .map(read)
+ .collect();
+ next.is_empty() || next.iter().any(|n| !was.contains(n))
+}
+
+/// What a request from outside `networks` answers.
+pub fn refusal(ip: Option<&str>) -> String {
+ format!(
+ "This instance takes sign-ins and requests only from its organization's networks, and {} isn't in one: connect to one (a VPN, say), then try again.",
+ ip.map_or_else(|| "this request's address".to_owned(), |i| i.to_owned())
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn nets(list: &[&str]) -> Vec {
+ list.iter().map(|s| (*s).to_owned()).collect()
+ }
+
+ #[test]
+ fn ranges_read_as_admins_type_them() {
+ assert_eq!(
+ check(&nets(&[
+ " 10.0.0.0/8",
+ "203.0.113.7",
+ "2001:DB8::/32",
+ "10.0.0.0/8",
+ ""
+ ]))
+ .ok(),
+ Some(nets(&["10.0.0.0/8", "203.0.113.7/32", "2001:db8::/32"]))
+ );
+ for bad in [
+ "10.0.0/8",
+ "10.0.0.0/33",
+ "acme.com",
+ "2001:db8::/129",
+ "10.0.0.1/8",
+ ] {
+ assert!(check(&nets(&[bad])).is_err(), "{bad}");
+ }
+ // What a mistyped one meant.
+ assert!(
+ check(&nets(&["10.1.2.3/8"]))
+ .err()
+ .is_some_and(|e| e.message.contains("did you mean 10.0.0.0/8"))
+ );
+ let many: Vec = (0..=MAX_NETWORKS)
+ .map(|i| format!("10.0.{i}.0/24"))
+ .collect();
+ assert!(check(&many).is_err());
+ assert_eq!(check(&[]).ok(), Some(vec![]));
+ }
+
+ #[test]
+ fn requests_from_inside_a_range_are_taken() {
+ let ranges = nets(&["10.0.0.0/8", "203.0.113.7/32", "2001:db8::/32"]);
+ for inside in ["10.1.2.3", "203.0.113.7", "2001:db8::1", "::ffff:10.9.9.9"] {
+ assert!(admits(&ranges, Some(inside)), "{inside}");
+ }
+ for outside in ["11.0.0.1", "203.0.113.8", "2001:db9::1", "not an address"] {
+ assert!(!admits(&ranges, Some(outside)), "{outside}");
+ }
+ // Without an address, only an instance that names none takes it.
+ assert!(!admits(&ranges, None));
+ assert!(admits(&[], None));
+ assert!(admits(&[], Some("198.51.100.1")));
+ // Everything, as wide as ranges go.
+ assert!(admits(&nets(&["0.0.0.0/0"]), Some("198.51.100.1")));
+ assert!(!admits(&nets(&["0.0.0.0/0"]), Some("2001:db8::1")));
+ }
+}
diff --git a/crates/fctl-domain/src/verify.rs b/crates/fctl-domain/src/verify.rs
index 04e3f897..717f00ea 100644
--- a/crates/fctl-domain/src/verify.rs
+++ b/crates/fctl-domain/src/verify.rs
@@ -125,8 +125,9 @@ pub enum Sensitive {
/// domain requires the provider, whoever next signs in with its address
/// there links to their account.
UnlinkSignIn,
- /// Letting sign-ins and access tokens last longer, or members make
- /// access tokens again (`fctl_domain::session_policy::relaxes`).
+ /// Letting sign-ins and access tokens last longer, members make access
+ /// tokens again (`fctl_domain::session_policy::relaxes`), or people sign
+ /// in from more networks (`fctl_domain::networks::widens`).
RelaxSessions,
}
@@ -171,7 +172,9 @@ impl Sensitive {
}
RelaxSignIn => "let people sign in another way than their domain's provider",
UnlinkSignIn => "unlink someone's sign-in account",
- RelaxSessions => "let sign-ins or access tokens last longer",
+ RelaxSessions => {
+ "let sign-ins or access tokens last longer, or come from more networks"
+ }
}
}
}
@@ -262,7 +265,11 @@ pub fn instance_settings_change(
} else if crate::session_policy::relaxes(
¤t.session_policy(),
&session_policy(current, update),
- ) {
+ ) || update
+ .networks
+ .as_ref()
+ .is_some_and(|next| crate::networks::widens(¤t.networks, next))
+ {
Some(Sensitive::RelaxSessions)
} else {
None
@@ -637,6 +644,33 @@ mod tests {
None
);
assert_eq!(change(UpdateInstanceSettingsRequest::default()), None);
+ // Networks: anywhere again, or one more; not fewer.
+ let inside = InstanceSettings {
+ networks: vec!["10.0.0.0/8".to_owned()],
+ ..Default::default()
+ };
+ let networks = |next: &[&str]| {
+ instance_settings_change(
+ &inside,
+ &UpdateInstanceSettingsRequest {
+ networks: Some(next.iter().map(|n| (*n).to_owned()).collect()),
+ ..Default::default()
+ },
+ )
+ };
+ assert_eq!(networks(&[]), relaxes);
+ assert_eq!(networks(&["10.0.0.0/8", "192.0.2.0/24"]), relaxes);
+ assert_eq!(networks(&["10.0.0.0/8"]), None);
+ assert_eq!(
+ instance_settings_change(
+ &InstanceSettings::default(),
+ &UpdateInstanceSettingsRequest {
+ networks: Some(vec!["10.0.0.0/8".to_owned()]),
+ ..Default::default()
+ }
+ ),
+ None
+ );
}
#[test]
diff --git a/crates/fctl-proto/src/api.rs b/crates/fctl-proto/src/api.rs
index 7cbf5d24..d3bbc425 100644
--- a/crates/fctl-proto/src/api.rs
+++ b/crates/fctl-proto/src/api.rs
@@ -56,6 +56,13 @@ pub struct SignInInfo {
/// ([`InstanceSettings::self_sign_up`]). Off, the page tells people
/// without an account to ask an admin.
pub self_sign_up: bool,
+ /// This request comes from outside the networks the instance takes
+ /// sign-ins from ([`InstanceSettings::networks`]): the page says so,
+ /// as only the primary instance owner signs in from here. Absent from
+ /// control planes before it.
+ #[serde(default)]
+ #[cfg_attr(feature = "ts", ts(as = "Option", optional))]
+ pub outside: bool,
}
/// A provider people sign in with: Google, or (later) another OpenID
@@ -1797,6 +1804,14 @@ pub struct InstanceSettings {
/// primary instance owner make them, and members' stop working: they
/// use the CLI, signed in as themselves. On by default.
pub member_access_tokens: bool,
+ /// The networks people sign in and send requests from, as CIDR ranges
+ /// (`203.0.113.0/24`, `2001:db8::/32`): an office's, a VPN's. Browsers,
+ /// CLIs, access tokens, admin tokens and service accounts outside them
+ /// are refused; runners, webhooks and published links aren't held to
+ /// them, and the primary instance owner signs in from anywhere, in a
+ /// browser or the CLI. None (the default): anywhere. At most
+ /// `fctl_domain::networks::MAX_NETWORKS`.
+ pub networks: Vec,
}
/// How long sign-ins last and who makes access tokens: the instance's
@@ -1922,7 +1937,15 @@ pub struct SignInOverview {
/// How long sign-ins last and who makes access tokens. Its defaults
/// from control planes before it.
#[serde(default)]
+ #[cfg_attr(feature = "ts", ts(as = "Option", optional))]
pub sessions: SessionPolicy,
+ /// [`InstanceSettings::networks`]. None from control planes before it.
+ #[serde(default)]
+ #[cfg_attr(feature = "ts", ts(as = "Option>", optional))]
+ pub networks: Vec,
+ /// The address this request comes from, as the instance sees it: what a
+ /// network has to hold for the admin to stay in.
+ pub address: Option,
}
/// A provider as instance admins see it ([`SignInOverview::providers`]).
@@ -2094,6 +2117,7 @@ impl Default for InstanceSettings {
cli_max_days: 0,
access_token_max_days: 0,
member_access_tokens: true,
+ networks: Vec::new(),
}
}
}
@@ -2138,6 +2162,10 @@ pub struct UpdateInstanceSettingsRequest {
/// 0 to [`MAX_ACCESS_TOKEN_DAYS`].
pub access_token_max_days: Option,
pub member_access_tokens: Option,
+ /// Replaces the networks: `[]` for anywhere. Refused (`409`) where the
+ /// caller's own address would be outside them, unless they're the
+ /// primary instance owner.
+ pub networks: Option>,
}
// ───────────────────────────── workspaces ─────────────────────────────
diff --git a/crates/fctl/src/cmd/admin.rs b/crates/fctl/src/cmd/admin.rs
index 980e2503..f571e71c 100644
--- a/crates/fctl/src/cmd/admin.rs
+++ b/crates/fctl/src/cmd/admin.rs
@@ -145,7 +145,7 @@ pub enum AdminCmd {
/// change those domains.
#[command(
name = "sign-in",
- after_help = "Examples:\n fctl admin sign-in\n fctl admin sign-in require acme.com acme.dev # people at acme.com and acme.dev sign in with Google only\n fctl admin sign-in require acme.com --passkeys # passkeys alone sign them in too\n fctl admin sign-in unrequire acme.dev\n fctl admin sign-in policies --browser-max 12h --browser-idle 1h # browsers sign in again twice a day\n fctl admin sign-in policies --token-max 90d --member-tokens off\n fctl admin set --self-sign-up off # accounts only from invitations and admin tokens"
+ after_help = "Examples:\n fctl admin sign-in\n fctl admin sign-in require acme.com acme.dev # people at acme.com and acme.dev sign in with Google only\n fctl admin sign-in require acme.com --passkeys # passkeys alone sign them in too\n fctl admin sign-in unrequire acme.dev\n fctl admin sign-in policies --browser-max 12h --browser-idle 1h # browsers sign in again twice a day\n fctl admin sign-in policies --token-max 90d --member-tokens off\n fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32 # sign-ins only from your office and VPN\n fctl admin set --self-sign-up off # accounts only from invitations and admin tokens"
)]
SignIn {
#[command(subcommand)]
@@ -764,6 +764,15 @@ fn print_settings(s: &InstanceSettings) {
for line in fctl_domain::session_policy::describe(&s.session_policy()) {
println!(" {}", style::dim(&line));
}
+ if !s.networks.is_empty() {
+ println!(
+ " {}",
+ style::dim(&format!(
+ "People sign in only from {}, the primary instance owner aside.",
+ fctl_domain::sign_in::domains_words(&s.networks)
+ ))
+ );
+ }
println!(
"Published screenshots {}",
if s.publish_screenshots {
diff --git a/crates/fctl/src/cmd/sign_in.rs b/crates/fctl/src/cmd/sign_in.rs
index 16fb3d6f..a401f0d0 100644
--- a/crates/fctl/src/cmd/sign_in.rs
+++ b/crates/fctl/src/cmd/sign_in.rs
@@ -79,6 +79,13 @@ pub enum SignInCmd {
/// themselves.
#[arg(long, value_name = "ON|OFF", value_parser = clap::builder::BoolishValueParser::new(), hide_possible_values = true)]
member_tokens: Option,
+ /// The networks people sign in and send requests from, as CIDR
+ /// ranges separated by commas (203.0.113.0/24,2001:db8::/32), or
+ /// `any`. Runners and webhooks connect from anywhere, and the
+ /// primary instance owner signs in from anywhere. Your own address
+ /// has to be in them.
+ #[arg(long, value_name = "RANGES|any")]
+ networks: Option,
/// Save it without asking.
#[arg(long)]
yes: bool,
@@ -121,11 +128,15 @@ pub async fn run(api: &Api, cmd: Option, json: bool) -> Result<()> {
cli_max,
token_max,
member_tokens,
+ networks,
yes,
} => {
let overview = api.sign_in_overview().await?;
- let was = overview.sessions.clone();
- let mut next = was.clone();
+ let was = Policies {
+ sessions: overview.sessions.clone(),
+ networks: overview.networks.clone(),
+ };
+ let mut next = was.sessions.clone();
if let Some(d) = browser_max {
next.browser_max_hours = whole(&d, 60, "hours", "12h or 1d")?;
}
@@ -147,6 +158,14 @@ pub async fn run(api: &Api, cmd: Option, json: bool) -> Result<()> {
if let Some(on) = member_tokens {
next.member_access_tokens = on;
}
+ let next = Policies {
+ sessions: next,
+ networks: match networks.as_deref().map(str::trim) {
+ Some("any" | "anywhere" | "none" | "") => Vec::new(),
+ Some(list) => network_list(list)?,
+ None => was.networks.clone(),
+ },
+ };
if next == was {
if json {
return style::print_json(&was);
@@ -154,7 +173,7 @@ pub async fn run(api: &Api, cmd: Option, json: bool) -> Result<()> {
print_policy(&was);
return Ok(());
}
- change_policy(api, next, yes, json).await?;
+ change_policy(api, &overview, &was, next, yes, json).await?;
}
}
Ok(())
@@ -170,12 +189,47 @@ fn whole(input: &str, per: u32, unit: &str, example: &str) -> Result {
}
}
+/// How long sign-ins last, who makes access tokens and where people sign
+/// in from: what `fctl admin sign-in policies` shows and changes.
+#[derive(Clone, Debug, PartialEq, serde::Serialize)]
+struct Policies {
+ #[serde(flatten)]
+ sessions: SessionPolicy,
+ networks: Vec,
+}
+
+/// Ranges as typed: by commas or spaces, each checked as the instance
+/// checks them.
+fn network_list(list: &str) -> Result> {
+ let typed: Vec = list
+ .split([',', ' '])
+ .filter(|n| !n.trim().is_empty())
+ .map(str::to_owned)
+ .collect();
+ fctl_domain::networks::check(&typed).map_err(|e| anyhow::anyhow!(e.message))
+}
+
/// Shows what saving `next` ends at once, asks unless `yes`, saves it and
-/// shows the policy now.
-async fn change_policy(api: &Api, next: SessionPolicy, yes: bool, json: bool) -> Result<()> {
- let preview = api.session_policy_preview(&next).await?;
- for line in policy_consequences(&preview) {
- eprintln!("{line}");
+/// shows the policies now.
+async fn change_policy(
+ api: &Api,
+ overview: &SignInOverview,
+ was: &Policies,
+ next: Policies,
+ yes: bool,
+ json: bool,
+) -> Result<()> {
+ if next.sessions != was.sessions {
+ let preview = api.session_policy_preview(&next.sessions).await?;
+ for line in policy_consequences(&preview) {
+ eprintln!("{line}");
+ }
+ }
+ if next.networks != was.networks {
+ eprintln!(
+ "{}",
+ networks_consequence(&next.networks, overview.address.as_deref())
+ );
}
if !yes {
if !std::io::stdin().is_terminal() {
@@ -189,17 +243,22 @@ async fn change_policy(api: &Api, next: SessionPolicy, yes: bool, json: bool) ->
bail!("Not saved");
}
}
+ let p = &next.sessions;
let saved = api
.update_instance_settings(&UpdateInstanceSettingsRequest {
- browser_max_hours: Some(next.browser_max_hours),
- browser_idle_minutes: Some(next.browser_idle_minutes),
- cli_max_days: Some(next.cli_max_days),
- access_token_max_days: Some(next.access_token_max_days),
- member_access_tokens: Some(next.member_access_tokens),
+ browser_max_hours: Some(p.browser_max_hours),
+ browser_idle_minutes: Some(p.browser_idle_minutes),
+ cli_max_days: Some(p.cli_max_days),
+ access_token_max_days: Some(p.access_token_max_days),
+ member_access_tokens: Some(p.member_access_tokens),
+ networks: (next.networks != was.networks).then(|| next.networks.clone()),
..UpdateInstanceSettingsRequest::default()
})
.await?;
- let now = saved.session_policy();
+ let now = Policies {
+ sessions: saved.session_policy(),
+ networks: saved.networks,
+ };
if json {
return style::print_json(&now);
}
@@ -208,6 +267,26 @@ async fn change_policy(api: &Api, next: SessionPolicy, yes: bool, json: bool) ->
Ok(())
}
+/// What saving `networks` does, for a request from `address`.
+fn networks_consequence(networks: &[String], address: Option<&str>) -> String {
+ if networks.is_empty() {
+ return "People sign in and send requests from anywhere again.".to_owned();
+ }
+ let you = match address {
+ Some(a) if fctl_domain::networks::admits(networks, Some(a)) => {
+ format!("your address, {a}, is in them")
+ }
+ Some(a) => format!(
+ "your address, {a}, isn't in them: only the primary instance owner saves them from outside"
+ ),
+ None => "fctl can't tell your address".to_owned(),
+ };
+ format!(
+ "People sign in and send requests only from {}, the primary instance owner's browser and CLI aside; {you}. Runners and webhooks connect from anywhere.",
+ domains_words(networks)
+ )
+}
+
/// What saving a session policy ends, in the sentences the web app shows
/// too.
pub fn policy_consequences(p: &SessionPolicyPreview) -> Vec {
@@ -253,10 +332,23 @@ pub fn policy_consequences(p: &SessionPolicyPreview) -> Vec {
lines
}
-fn print_policy(p: &SessionPolicy) {
- for line in describe_policy(p) {
+fn print_policy(p: &Policies) {
+ for line in describe_policy(&p.sessions) {
println!("{line}");
}
+ println!("{}", networks_line(&p.networks));
+}
+
+/// Where people sign in from, in a sentence.
+fn networks_line(networks: &[String]) -> String {
+ if networks.is_empty() {
+ "People sign in from anywhere.".to_owned()
+ } else {
+ format!(
+ "People sign in only from {}, the primary instance owner aside.",
+ domains_words(networks)
+ )
+ }
}
/// Shows what saving `next` would do, asks unless `yes`, saves it and
@@ -509,6 +601,7 @@ fn print_overview(o: &SignInOverview) {
for line in describe_policy(&o.sessions) {
println!(" {}", style::dim(&line));
}
+ println!(" {}", style::dim(&networks_line(&o.networks)));
if let Some(owner) = &o.owner
&& !o.rules.is_empty()
{
@@ -614,6 +707,22 @@ mod tests {
);
}
+ #[test]
+ fn networks_say_whether_you_stay_in() {
+ let nets = network_list("203.0.113.0/24, 10.0.0.0/8").unwrap_or_default();
+ assert_eq!(nets, ["203.0.113.0/24", "10.0.0.0/8"]);
+ assert!(network_list("acme.com").is_err());
+ assert!(
+ networks_consequence(&nets, Some("203.0.113.9"))
+ .contains("your address, 203.0.113.9, is in them")
+ );
+ assert!(networks_consequence(&nets, Some("198.51.100.1")).contains("isn't in them"));
+ assert_eq!(
+ networks_consequence(&[], None),
+ "People sign in and send requests from anywhere again."
+ );
+ }
+
#[test]
fn policy_durations_read_in_whole_units() {
assert_eq!(whole("12h", 60, "hours", "12h").ok(), Some(12));
diff --git a/web/src/components/sign-in/networks.test.tsx b/web/src/components/sign-in/networks.test.tsx
new file mode 100644
index 00000000..6b69060d
--- /dev/null
+++ b/web/src/components/sign-in/networks.test.tsx
@@ -0,0 +1,108 @@
+import { QueryClientProvider } from "@tanstack/react-query";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type * as G from "@/gen";
+import { queryClient } from "@/lib/queries";
+import { DEFAULT_POLICY } from "@/lib/session-policy";
+import { Networks, networksLead, parseNetworks } from "./networks";
+
+const updateInstanceSettings = vi.fn();
+vi.mock("@/lib/api", async (original) => ({
+ ...(await original()),
+ api: { updateInstanceSettings: (b: G.UpdateInstanceSettingsRequest) => updateInstanceSettings(b) },
+}));
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const roots: (() => void)[] = [];
+beforeEach(() => {
+ updateInstanceSettings.mockReset();
+ queryClient.clear();
+});
+afterEach(() => {
+ for (const unmount of roots.splice(0)) unmount();
+});
+
+const overview = (networks: string[]): G.SignInOverview => ({
+ providers: [],
+ rules: [],
+ coverage: [],
+ self_sign_up: true,
+ active: 3,
+ passwords: 3,
+ passkeys: 0,
+ no_way_in: 0,
+ email: false,
+ sessions: DEFAULT_POLICY,
+ networks,
+ address: "203.0.113.9",
+});
+
+function open(o: G.SignInOverview) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ act(() =>
+ root.render(
+
+
+ ,
+ ),
+ );
+ roots.push(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+ const button = (text: string) =>
+ [...container.querySelectorAll("button")].find((b) => b.textContent?.trim() === text);
+ return { container, button };
+}
+
+describe("Admin → Sign-in: networks", () => {
+ it("reads ranges as typed, and says where people sign in from", () => {
+ expect(parseNetworks("203.0.113.0/24\n 2001:db8::/32, 10.0.0.1")).toEqual([
+ "203.0.113.0/24",
+ "2001:db8::/32",
+ "10.0.0.1",
+ ]);
+ expect(networksLead([])).toBe("People sign in and send requests from anywhere.");
+ expect(networksLead(["203.0.113.0/24", "2001:db8::/32"])).toBe(
+ "People sign in and send requests only from 203.0.113.0/24 and 2001:db8::/32. The primary instance owner signs in from anywhere, in a browser or the CLI.",
+ );
+ });
+
+ it("adds the admin's own address, and saves the ranges", async () => {
+ updateInstanceSettings.mockResolvedValue({ networks: ["203.0.113.9/32"] });
+ const page = open(overview([]));
+ expect(page.container.textContent).toContain("Your address: 203.0.113.9");
+ expect(page.button("Save")).toBeUndefined();
+ await act(async () => page.button("Add it")?.click());
+ expect(page.container.querySelector("textarea")?.value).toBe("203.0.113.9");
+ await act(async () => page.button("Save")?.click());
+ expect(updateInstanceSettings).toHaveBeenCalledWith({ networks: ["203.0.113.9"] });
+ });
+
+ it("shows why the instance refused them", async () => {
+ updateInstanceSettings.mockRejectedValue(
+ Object.assign(new Error("Your own address, 203.0.113.9, isn't in these networks"), {
+ field: undefined,
+ }),
+ );
+ const page = open(overview(["10.0.0.0/8"]));
+ const area = page.container.querySelector("textarea");
+ expect(area?.value).toBe("10.0.0.0/8");
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set?.call(
+ area,
+ "192.0.2.0/24",
+ );
+ area?.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () => page.button("Save")?.click());
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 0));
+ });
+ expect(page.container.textContent).toContain("Your own address, 203.0.113.9, isn't in these networks");
+ });
+});
diff --git a/web/src/components/sign-in/networks.tsx b/web/src/components/sign-in/networks.tsx
new file mode 100644
index 00000000..db14cfcd
--- /dev/null
+++ b/web/src/components/sign-in/networks.tsx
@@ -0,0 +1,123 @@
+// Admin → Sign-in's networks (InstanceSettings.networks): the IP ranges people sign in and send requests from,
+// an office's or a VPN's. The admin's own address shows beside them, and the control plane refuses to save ranges
+// that would shut them out, unless they are the primary instance owner, who signs in from anywhere.
+
+import { useMutation } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
+import { Banner, Button, Field, Section, Skeleton, Textarea, toast } from "@/components/ui";
+import type * as G from "@/gen";
+import { api } from "@/lib/api";
+import { keys, queryClient } from "@/lib/queries";
+import { domainsWords } from "@/lib/sign-in";
+
+/** Ranges as typed: by lines, commas or spaces. */
+export const parseNetworks = (text: string): string[] =>
+ text
+ .split(/[\s,]+/)
+ .map((n) => n.trim())
+ .filter(Boolean);
+
+/** What the section says of the networks saved. */
+export function networksLead(networks: readonly string[]): string {
+ return networks.length === 0
+ ? "People sign in and send requests from anywhere."
+ : `People sign in and send requests only from ${domainsWords(networks)}. The primary instance owner signs in from anywhere, in a browser or the CLI.`;
+}
+
+export function Networks({ overview }: { overview?: G.SignInOverview }) {
+ const saved = overview?.networks;
+ const [text, setText] = useState("");
+ // What's saved, here or in another tab, replaces what's typed.
+ useEffect(() => setText((saved ?? []).join("\n")), [saved]);
+ const typed = parseNetworks(text);
+ const changed = !!saved && typed.join(",") !== saved.join(",");
+ const save = useMutation({
+ mutationFn: (networks: string[]) => api.updateInstanceSettings({ networks }),
+ onSuccess: (s) => {
+ queryClient.setQueryData(keys.instanceSettings, s);
+ void queryClient.invalidateQueries({ queryKey: keys.signIn });
+ void queryClient.invalidateQueries({ queryKey: keys.instance });
+ toast(
+ s.networks.length
+ ? "Saved: sign-ins come only from these networks"
+ : "Saved: people sign in from anywhere",
+ );
+ },
+ });
+ const address = overview?.address;
+ const field = (save.error as { field?: string } | null)?.field;
+ return (
+
+ {!overview ? (
+
+ ) : (
+
+ )}
+
+ );
+}
diff --git a/web/src/gen/InstanceSettings.ts b/web/src/gen/InstanceSettings.ts
index 520ba329..415941a9 100644
--- a/web/src/gen/InstanceSettings.ts
+++ b/web/src/gen/InstanceSettings.ts
@@ -176,4 +176,14 @@ access_token_max_days: number,
* primary instance owner make them, and members' stop working: they
* use the CLI, signed in as themselves. On by default.
*/
-member_access_tokens: boolean, };
+member_access_tokens: boolean,
+/**
+ * The networks people sign in and send requests from, as CIDR ranges
+ * (`203.0.113.0/24`, `2001:db8::/32`): an office's, a VPN's. Browsers,
+ * CLIs, access tokens, admin tokens and service accounts outside them
+ * are refused; runners, webhooks and published links aren't held to
+ * them, and the primary instance owner signs in from anywhere, in a
+ * browser or the CLI. None (the default): anywhere. At most
+ * `fctl_domain::networks::MAX_NETWORKS`.
+ */
+networks: Array, };
diff --git a/web/src/gen/SignInInfo.ts b/web/src/gen/SignInInfo.ts
index 9dc6b16d..10799e66 100644
--- a/web/src/gen/SignInInfo.ts
+++ b/web/src/gen/SignInInfo.ts
@@ -22,4 +22,11 @@ rules: Array,
* ([`InstanceSettings::self_sign_up`]). Off, the page tells people
* without an account to ask an admin.
*/
-self_sign_up: boolean, };
+self_sign_up: boolean,
+/**
+ * This request comes from outside the networks the instance takes
+ * sign-ins from ([`InstanceSettings::networks`]): the page says so,
+ * as only the primary instance owner signs in from here. Absent from
+ * control planes before it.
+ */
+outside?: boolean, };
diff --git a/web/src/gen/SignInOverview.ts b/web/src/gen/SignInOverview.ts
index 770f70a2..d015a1ad 100644
--- a/web/src/gen/SignInOverview.ts
+++ b/web/src/gen/SignInOverview.ts
@@ -64,4 +64,13 @@ email: boolean,
* How long sign-ins last and who makes access tokens. Its defaults
* from control planes before it.
*/
-sessions: SessionPolicy, };
+sessions?: SessionPolicy,
+/**
+ * [`InstanceSettings::networks`]. None from control planes before it.
+ */
+networks?: Array,
+/**
+ * The address this request comes from, as the instance sees it: what a
+ * network has to hold for the admin to stay in.
+ */
+address?: string, };
diff --git a/web/src/gen/UpdateInstanceSettingsRequest.ts b/web/src/gen/UpdateInstanceSettingsRequest.ts
index 461d17f8..1bd98ea6 100644
--- a/web/src/gen/UpdateInstanceSettingsRequest.ts
+++ b/web/src/gen/UpdateInstanceSettingsRequest.ts
@@ -48,4 +48,10 @@ cli_max_days?: number,
/**
* 0 to [`MAX_ACCESS_TOKEN_DAYS`].
*/
-access_token_max_days?: number, member_access_tokens?: boolean, };
+access_token_max_days?: number, member_access_tokens?: boolean,
+/**
+ * Replaces the networks: `[]` for anywhere. Refused (`409`) where the
+ * caller's own address would be outside them, unless they're the
+ * primary instance owner.
+ */
+networks?: Array, };
diff --git a/web/src/lib/google-sign-in.test.ts b/web/src/lib/google-sign-in.test.ts
index 94164b5a..e80d27ac 100644
--- a/web/src/lib/google-sign-in.test.ts
+++ b/web/src/lib/google-sign-in.test.ts
@@ -30,6 +30,7 @@ describe("what the sign-in page says when Google didn't sign someone in", () =>
it("tells a stranger where accounts come from only from the directory", () => {
expect(googleError("sign_up_closed", true)).toContain("Ask an admin of this instance for one.");
+ expect(googleError("network", true)).toContain("Connect to one (your VPN, say), then sign in.");
});
it("says the sign-in did not work for an error it doesn't know", () => {
diff --git a/web/src/lib/google-sign-in.ts b/web/src/lib/google-sign-in.ts
index 0b6dc499..b739e039 100644
--- a/web/src/lib/google-sign-in.ts
+++ b/web/src/lib/google-sign-in.ts
@@ -26,6 +26,9 @@ const GOOGLE_ERRORS: Record = {
sign_up_closed:
"Your organization makes the accounts here, and there's none for this address yet. Ask an admin of this instance for one.",
disabled: "Your account is disabled. Ask an admin for access.",
+ // From outside the instance's networks (InstanceSettings.networks).
+ network:
+ "This instance takes sign-ins only from its organization's networks, and this browser is outside them. Connect to one (your VPN, say), then sign in.",
};
/**
diff --git a/web/src/routes/admin.test.tsx b/web/src/routes/admin.test.tsx
index 1d47f2db..c3c71b07 100644
--- a/web/src/routes/admin.test.tsx
+++ b/web/src/routes/admin.test.tsx
@@ -308,6 +308,7 @@ const instanceSettings = (s: Partial = {}): G.InstanceSettin
sign_in: [],
self_sign_up: true,
...DEFAULT_POLICY,
+ networks: [],
...s,
});
diff --git a/web/src/routes/admin.tsx b/web/src/routes/admin.tsx
index 5a66794b..981cfd26 100644
--- a/web/src/routes/admin.tsx
+++ b/web/src/routes/admin.tsx
@@ -38,6 +38,7 @@ import { PageTabs, TabCount } from "@/components/page-tabs";
import { DriverLine } from "@/components/runner-driver";
import { SnapshotStoreLine } from "@/components/runner-snapshots";
import { SignInAdmin } from "@/components/sign-in/admin";
+import { Networks } from "@/components/sign-in/networks";
import { SessionPolicies } from "@/components/sign-in/sessions";
import {
Avatar,
@@ -1855,6 +1856,7 @@ function SignInTab() {
save.mutate(b)} saving={save.isPending} />
save.mutate(b)} saving={save.isPending} />
+
>
);
}
@@ -2478,6 +2480,7 @@ function SignInSettings({
claude_instance_view: false,
claude_refusals: 2,
...DEFAULT_POLICY,
+ networks: [],
};
const active = users.data?.users.filter((u) => u.status === "active") ?? [];
const using = active.filter(secured);
diff --git a/web/src/routes/auth.test.tsx b/web/src/routes/auth.test.tsx
index 03680d6f..2f4e75c7 100644
--- a/web/src/routes/auth.test.tsx
+++ b/web/src/routes/auth.test.tsx
@@ -91,6 +91,15 @@ function open(info: G.InstanceInfo) {
describe("the sign-in page where a domain signs in with a provider", () => {
const acme = instance([{ domains: ["acme.com", "acme.dev"], provider: "google", passkeys: false }]);
+ it("says when the browser is outside the networks the instance takes sign-ins from", () => {
+ const outside = instance([]);
+ if (outside.sign_in) outside.sign_in.outside = true;
+ expect(open(outside).container.textContent).toContain(
+ "Acme factory takes sign-ins only from its organization's networks, and this browser is outside them.",
+ );
+ expect(open(instance([])).container.textContent).not.toContain("organization's networks");
+ });
+
it("says which domains sign in with it, under its button", () => {
const page = open(acme);
expect(page.container.textContent).toContain("acme.com and acme.dev sign in with Google.");
diff --git a/web/src/routes/auth.tsx b/web/src/routes/auth.tsx
index a5b3978b..5da73ad7 100644
--- a/web/src/routes/auth.tsx
+++ b/web/src/routes/auth.tsx
@@ -282,6 +282,12 @@ export function LoginPage() {
{external}
)}
+ {instance?.sign_in?.outside && !external && (
+
+ {instance.name} takes sign-ins only from its organization's networks, and this browser is outside
+ them. Connect to one (your VPN, say), then sign in.
+
+ )}
{(buttons.length > 0 || passkey.supported) && (
<>
From 4fd36fedf871a2c99e2ba3e12f6b135a79e5e347 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Wed, 25 Nov 2026 23:26:08 +0000
Subject: [PATCH 06/11] docs: signing in only from an instance's networks
---
...-instances-limit-how-long-sign-ins-last.md | 8 ++++++
docs/api.md | 12 +++++++++
docs/architecture.md | 10 +++++++
docs/cli.md | 6 ++++-
docs/llms.txt | 2 +-
docs/organizations.md | 5 ++++
docs/security.md | 8 ++++++
docs/self-hosting.md | 26 +++++++++++++++++++
8 files changed, 75 insertions(+), 2 deletions(-)
diff --git a/docs/adr/0102-instances-limit-how-long-sign-ins-last.md b/docs/adr/0102-instances-limit-how-long-sign-ins-last.md
index 2f3e13fc..55282fdb 100644
--- a/docs/adr/0102-instances-limit-how-long-sign-ins-last.md
+++ b/docs/adr/0102-instances-limit-how-long-sign-ins-last.md
@@ -47,6 +47,14 @@ days, and no tokens made by people outside a few admins (#618).
- **The primary instance owner is held to it like everyone else.** A
policy ends sign-ins and nothing more: whoever it signs out signs in
again, the owner with their password while the provider is down.
+- **Networks keep sign-ins and requests to some IP ranges**, with the
+ same exemptions as the rest: runners, webhooks and published links
+ connect from anywhere. The primary instance owner signs in from
+ anywhere with a browser or the CLI, the instance's way in when its
+ network's addresses change, while their access tokens and admin tokens
+ are held to them; an admin can't save ranges they're outside of. A
+ browser outside them is as signed out and keeps its sign-in, so that
+ stepping off the VPN signs nobody out for good.
## Consequences
diff --git a/docs/api.md b/docs/api.md
index ceb0fb3a..51ac7601 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -670,6 +670,18 @@ a member's where only admins make them (`403`, `forbidden`). `GET /api/v1/auth/m
them as `sessions`, and each token's `expires_at` in `GET
/api/v1/auth/tokens` says when it ends under them.
+`networks` in the same settings, a list of CIDR ranges (`[]` for
+anywhere), keeps sign-ins and requests to them ([Signing in only from your
+networks](self-hosting.md#signing-in-only-from-your-networks)): a request
+from elsewhere with a CLI's sign-in, an access token, an admin token or a
+service account's secret answers `403` (`forbidden`), and a sign-in from
+elsewhere is refused the same way, but the primary instance owner's in a
+browser or the CLI. Saving ranges the caller's own address is outside of
+answers `409` (`conflict`), unless they're the primary instance owner. `GET
+/api/v1/admin/sign-in` has them as `networks`, with the caller's
+`address`, and `GET /api/v1/instance` says whether the request comes from
+outside them (`sign_in.outside`).
+
## Runner pools
What a pool (an enrollment token's runners) needs now, for whatever scales
diff --git a/docs/architecture.md b/docs/architecture.md
index e6af4055..61d96c84 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -453,6 +453,16 @@ by its id, `google` ([ADR 0099](adr/0099-domains-require-signing-in-with-their-p
what it ends at once, in one statement (`sign_in::revoke_ended`, whose
count `POST /admin/sign-in/sessions/preview` shows first). Admin tokens
and service accounts' secrets aren't held to them.
+- **Networks** (`InstanceSettings::networks`, `fctl_domain::networks`):
+ the CIDR ranges sign-ins and requests come from, by `CF-Connecting-IP`.
+ `auth::authenticate` refuses a CLI's, access token's or admin token's
+ request from elsewhere and treats a browser as signed out without
+ clearing its cookie; `service_accounts::authenticate` refuses theirs;
+ `auth::start_web_session`, the password and reset handlers, the Google
+ sign-in (`?error=network`) and the CLI's device code refuse a sign-in.
+ The primary instance owner's browser and CLI are exempt
+ (`sign_in::outside`); runners, webhooks and published links never reach
+ these checks.
- **Accounts only from the directory.** With `InstanceSettings::self_sign_up`
off, a provider's sign-in makes an account only for an address with an
allowlist entry of its own (an invitation's, or one an admin allowed):
diff --git a/docs/cli.md b/docs/cli.md
index 55234ee0..303b3c11 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -1712,6 +1712,7 @@ fctl admin sign-in unrequire acme.dev # its people sign in as they like aga
fctl admin sign-in policies # how long sign-ins last, and who makes access tokens
fctl admin sign-in policies --browser-max 12h --browser-idle 1h # browsers sign in again after 12 hours, and out after an hour unused
fctl admin sign-in policies --cli-max 30d --token-max 90d --member-tokens off --yes # says what it ends at once; without asking
+fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32 # sign-ins and requests only from these ranges (`any` for anywhere)
fctl admin unlink grace@example.com # her Google account was recreated: signs her out, and her next Google sign-in links the new one
fctl admin reset-two-factor grace@example.com # they lost their phone and recovery codes
fctl admin reset-link grace@example.com # a link that sets their password (emailed to them where the instance sends email)
@@ -1738,7 +1739,10 @@ before it asks ("Saving signs out 14 browsers and 3 CLIs at once…"), and
`--json` prints the policy once it's saved
([How long people stay signed in](self-hosting.md#how-long-people-stay-signed-in)).
A CLI signed in longer than the policy lets one says so, and signs in
-again with `fctl login`.
+again with `fctl login`. `--networks` takes CIDR ranges separated by
+commas, or `any`; it says whether your own address is in them before it
+asks ([Signing in only from your
+networks](self-hosting.md#signing-in-only-from-your-networks)).
### Provisioning people with an admin token
diff --git a/docs/llms.txt b/docs/llms.txt
index 9c7adb8a..6485c3a8 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -73,7 +73,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · GitHub webhooks
- **Session**: `owner` (who started it, while they may still start sessions in the project, and the project's maintainers and owners: stop, resume, archive, share), `editor` (message and interrupt), `viewer` (read). Sessions can be shared with people in the same workspace, as viewers, editors or owners.
- **Access token**: `read` (like a viewer), `run` (like an editor, and it stops and resumes the sessions it started), `full` (whatever its person may in its projects). A limited token never reaches the account, workspaces' people and settings, Claude connections, other tokens or administration.
- **Admin token** (`fctl_adm_…`, id `adt_…`; self-hosted instances whose deployment sets `FCTL_ADMIN_TOKENS=1`, never app.fctl.sh): an instance admin's, for programs that provision people. It acts as that admin on the admin API's people endpoints alone: creates accounts (`POST /api/v1/admin/users`), reads one with their workspaces and projects (`GET /api/v1/admin/users/{id or address}`), changes names, primary address, commit email and status (`PATCH`), sets their picture and the Claude token their sessions run on (`PUT …/avatar`, `PUT …/claude`), adds them to any workspace and project or takes them out (`PUT`/`DELETE …/workspaces/{workspace}`, `…/projects/{project}`), and deletes them. A new account has no password (set one with `password`, or the link `fctl admin reset-link` makes, except where Google is required for its domain): where the instance has Google sign-in and Google hosts the address (Workspace or Gmail), the person's first Google sign-in links Google to it. It changes no roles and never the primary instance owner's account; only the primary owner's tokens change admins'. CLI: `fctl admin tokens create NAME`, then `FCTL_TOKEN=fctl_adm_… fctl admin users create|show|set|add|remove`.
-- **Sign-in rules** (instance admins: Admin → Sign-in, `fctl admin sign-in require acme.com acme.dev`, `PATCH /api/v1/admin/settings` with `sign_in`): the people with an address at those domains sign in with Google alone, as that address (a Google Workspace account's): passwords, passkeys alone (unless `--passkeys`) and personal Google accounts stop working, and saving it deletes their browser sessions, CLI sign-ins, access tokens and admin tokens made another way, before the rule too; their next Google sign-in links Google and takes their password. Closing their Google account stops their next sign-in, not their sessions: disable their account too. The primary instance owner keeps every way in, for when Google is down; a rule that would sign out the admin who saves it waits until they sign in with Google. `fctl admin sign-in` shows whom each covers; `POST /api/v1/admin/sign-in/preview` says what a change would do; `fctl admin set --self-sign-up off` makes signing in make no accounts (only invitations, allowed addresses and admin tokens). Someone whose Workspace account was recreated at the same address: `fctl admin unlink ada@acme.com` signs them out everywhere, then their next Google sign-in links the new one; an address handed to someone else calls for `fctl admin disable` instead. A CLI refused by a rule signs in again with `fctl login`. **Session policies** (`fctl admin sign-in policies`, Admin → Sign-in → Staying signed in, `PATCH /api/v1/admin/settings` with `browser_max_hours`, `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`, `member_access_tokens`): `--browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d --member-tokens off` makes browsers and CLIs sign in again (through Google where their domain requires it) and caps access tokens, those made before too; it prints what saving ends at once and asks unless `--yes` (`POST /api/v1/admin/sign-in/sessions/preview`). A CLI or token past it answers 401 saying why: `fctl login`, or a new token within the limit.
+- **Sign-in rules** (instance admins: Admin → Sign-in, `fctl admin sign-in require acme.com acme.dev`, `PATCH /api/v1/admin/settings` with `sign_in`): the people with an address at those domains sign in with Google alone, as that address (a Google Workspace account's): passwords, passkeys alone (unless `--passkeys`) and personal Google accounts stop working, and saving it deletes their browser sessions, CLI sign-ins, access tokens and admin tokens made another way, before the rule too; their next Google sign-in links Google and takes their password. Closing their Google account stops their next sign-in, not their sessions: disable their account too. The primary instance owner keeps every way in, for when Google is down; a rule that would sign out the admin who saves it waits until they sign in with Google. `fctl admin sign-in` shows whom each covers; `POST /api/v1/admin/sign-in/preview` says what a change would do; `fctl admin set --self-sign-up off` makes signing in make no accounts (only invitations, allowed addresses and admin tokens). Someone whose Workspace account was recreated at the same address: `fctl admin unlink ada@acme.com` signs them out everywhere, then their next Google sign-in links the new one; an address handed to someone else calls for `fctl admin disable` instead. A CLI refused by a rule signs in again with `fctl login`. **Session policies** (`fctl admin sign-in policies`, Admin → Sign-in → Staying signed in, `PATCH /api/v1/admin/settings` with `browser_max_hours`, `browser_idle_minutes`, `cli_max_days`, `access_token_max_days`, `member_access_tokens`): `--browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d --member-tokens off` makes browsers and CLIs sign in again (through Google where their domain requires it) and caps access tokens, those made before too; it prints what saving ends at once and asks unless `--yes` (`POST /api/v1/admin/sign-in/sessions/preview`). A CLI or token past it answers 401 saying why: `fctl login`, or a new token within the limit. `--networks 203.0.113.0/24,2001:db8::/32` (`any` to undo; `networks` in the settings) takes sign-ins and requests only from those ranges: elsewhere, CLIs, access tokens, admin tokens and service accounts answer 403 and browsers can't sign in; runners and webhooks aren't held to them, and the primary instance owner signs in from anywhere.
- **Service account**: as the person a request names, what an access token that runs sessions does, in its workspace's projects (start sessions, message, interrupt, stop and resume theirs, run schedules, keep memory), within that person's roles; as nobody, it reads them. Never the account, people, settings, secrets, tokens or live connections (`/ws`): read events with `fctl logs` or `GET /api/v1/sessions/{id}/events`.
## Session lifecycle
diff --git a/docs/organizations.md b/docs/organizations.md
index 11238db2..6a29d166 100644
--- a/docs/organizations.md
+++ b/docs/organizations.md
@@ -129,6 +129,11 @@ after 90, which only admins make
fctl admin sign-in policies --browser-max 12h --cli-max 30d --token-max 90d --member-tokens off
```
+And where your people work from known networks, sign-ins and requests can
+come only from those: `fctl admin sign-in policies --networks
+203.0.113.0/24,2001:db8::/32` ([Signing in only from your
+networks](self-hosting.md#signing-in-only-from-your-networks)).
+
## People from your directory
On an instance of yours, your identity provider, your HR system or a
diff --git a/docs/security.md b/docs/security.md
index f1f8d213..5c947b28 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -151,6 +151,14 @@ owner and purpose), so a value copied between rows does not decrypt.
so many days, and made by admins alone. Every request checks its token
against them, those made before too, and saving one ends the sign-ins
it doesn't let last. Letting them last longer is a sensitive action.
+- **Networks.** Instance admins can take sign-ins and requests only from
+ some IP ranges (Admin → Sign-in → Networks): browsers, CLIs, access
+ tokens, admin tokens and service accounts elsewhere are refused, while
+ runners, webhooks and published links aren't held to them. The primary
+ instance owner signs in from anywhere with a browser or the CLI; an admin
+ can't save ranges their own address is outside of; and letting people in
+ from more places is a sensitive action. The address is the one
+ Cloudflare, or a self-hosted server's trusted proxies, saw.
- **Sensitive actions take a passkey or a code**, where the primary
instance owner turns that on (off by default): inviting and promoting
admins, handing over the primary owner's and workspaces' primary admin
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 065018e3..75b0aff2 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1281,6 +1281,32 @@ from making them, too. Letting sign-ins or tokens last longer again asks
you to confirm it's you, where the instance asks for that. Admin tokens
and service accounts' secrets last as long as their makers chose.
+### Signing in only from your networks
+
+Under **Admin → Sign-in → Networks**, or with `fctl admin sign-in policies
+--networks`, an instance admin names the IP ranges people sign in and send
+requests from (your office's, your VPN's), as CIDR:
+
+```sh
+fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32
+fctl admin sign-in policies --networks any # from anywhere again
+```
+
+Browsers, CLIs, access tokens, admin tokens and service accounts elsewhere
+are refused: a browser outside them shows the sign-in page, which says
+why, and keeps its sign-in for when it's back inside. Runners' connections,
+GitHub's and Linear's webhooks and published screenshots' links come from
+anywhere, so runners in your cloud need no range of their own, but a
+script that calls the API from CI does. The primary instance owner signs
+in from anywhere with a browser or the CLI, the way in when your network's
+addresses change; their access tokens and admin tokens are held to the
+ranges. An admin can't save ranges their own address is outside of
+(**Admin → Sign-in** shows it, with **Add it**), and letting people in from
+more places asks you to confirm it's you, where the instance asks for
+that. The control plane sees each request's address as `CF-Connecting-IP`
+says, which your own server sets from the proxies in front of it
+([`FCTL_TRUST_PROXY`](#https-and-reverse-proxies)).
+
## Email (optional)
Without email, admins copy invite and password-reset links from the app. To
From 10a645eb9d5e7eaa5726d9bd03e0313b4f82b10c Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Thu, 26 Nov 2026 00:01:03 +0000
Subject: [PATCH 07/11] fix(control): name the longest an access token may last
once
---
crates/fctl-domain/src/session_policy.rs | 28 +++++++++++++++++++-----
1 file changed, 23 insertions(+), 5 deletions(-)
diff --git a/crates/fctl-domain/src/session_policy.rs b/crates/fctl-domain/src/session_policy.rs
index b562c94b..a4a650d5 100644
--- a/crates/fctl-domain/src/session_policy.rs
+++ b/crates/fctl-domain/src/session_policy.rs
@@ -231,12 +231,15 @@ pub fn check(p: &SessionPolicy) -> Result<(), ApiError> {
pub fn check_token_days(p: &SessionPolicy, days_asked: Option) -> Result<(), ApiError> {
let max = p.access_token_max_days;
if max > 0 && days_asked.is_none_or(|d| d > max) {
+ let words = days(max);
+ let longest = if words == format!("{max} days") {
+ words
+ } else {
+ format!("{words} ({max} days)")
+ };
return Err(ApiError::validation(
"expires_in_days",
- format!(
- "This instance's access tokens last {} at most ({max} days): choose that or less",
- days(max)
- ),
+ format!("This instance's access tokens last {longest} at most: choose that or less"),
));
}
Ok(())
@@ -490,7 +493,22 @@ mod tests {
assert!(check_token_days(&p, Some(90)).is_ok());
assert!(check_token_days(&p, Some(7)).is_ok());
let refused = check_token_days(&p, Some(365)).err();
- assert!(refused.is_some_and(|e| e.message.contains("90 days")));
+ assert_eq!(
+ refused.map(|e| e.message),
+ Some(
+ "This instance's access tokens last 90 days at most: choose that or less"
+ .to_owned()
+ )
+ );
+ let year = SessionPolicy {
+ access_token_max_days: 365,
+ ..policy()
+ };
+ assert!(
+ check_token_days(&year, None)
+ .err()
+ .is_some_and(|e| e.message.contains("a year (365 days) at most"))
+ );
// For ever is longer than any.
assert!(check_token_days(&p, None).is_err());
assert!(check_token_days(&policy(), None).is_ok());
From c4fcb9f269e600eb591b873bb47d822780525ca6 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Thu, 26 Nov 2026 00:05:43 +0000
Subject: [PATCH 08/11] fix(web): say plainly what session policies end and
don't hold
The policy section ends with what it doesn't hold (admin tokens and
service accounts' secrets) instead of repeating its controls, a lone
member's token reads as one, its switch stays beside its label on a
phone, and Devices names browsers once.
---
crates/fctl/src/cmd/sign_in.rs | 10 ++++++
web/src/components/sign-in/networks.tsx | 2 +-
web/src/components/sign-in/sessions.test.tsx | 8 +++--
web/src/components/sign-in/sessions.tsx | 30 +++++++++++++----
web/src/lib/session-policy.test.ts | 32 ++++++------------
web/src/lib/session-policy.ts | 35 ++++++--------------
6 files changed, 61 insertions(+), 56 deletions(-)
diff --git a/crates/fctl/src/cmd/sign_in.rs b/crates/fctl/src/cmd/sign_in.rs
index a401f0d0..8853bb3c 100644
--- a/crates/fctl/src/cmd/sign_in.rs
+++ b/crates/fctl/src/cmd/sign_in.rs
@@ -317,6 +317,7 @@ pub fn policy_consequences(p: &SessionPolicyPreview) -> Vec {
if p.access_tokens > 0 {
let members = match p.member_tokens {
0 => String::new(),
+ 1 if p.access_tokens == 1 => ", a member's".to_owned(),
n if n == p.access_tokens => ", all of them members'".to_owned(),
n => format!(", {n} of them members'"),
};
@@ -701,6 +702,15 @@ mod tests {
"It ends 5 access tokens, 3 of them members': scripts and CI that use them need new ones.",
]
);
+ let one = SessionPolicyPreview {
+ access_tokens: 1,
+ member_tokens: 1,
+ ..SessionPolicyPreview::default()
+ };
+ assert_eq!(
+ policy_consequences(&one),
+ ["It ends 1 access token, a member's: scripts and CI that use it need new ones."]
+ );
assert_eq!(
policy_consequences(&SessionPolicyPreview::default()),
["Nobody is signed out now: sign-ins end as it says from here on."]
diff --git a/web/src/components/sign-in/networks.tsx b/web/src/components/sign-in/networks.tsx
index db14cfcd..f618b440 100644
--- a/web/src/components/sign-in/networks.tsx
+++ b/web/src/components/sign-in/networks.tsx
@@ -65,7 +65,7 @@ export function Networks({ overview }: { overview?: G.SignInOverview }) {
{networksLead(overview.networks ?? [])}
diff --git a/web/src/components/sign-in/sessions.test.tsx b/web/src/components/sign-in/sessions.test.tsx
index 542efaf3..0b063962 100644
--- a/web/src/components/sign-in/sessions.test.tsx
+++ b/web/src/components/sign-in/sessions.test.tsx
@@ -65,10 +65,10 @@ function open(policy: G.SessionPolicy) {
}
describe("Admin → Sign-in: staying signed in", () => {
- it("says what the policy is while nothing changes", () => {
+ it("says what it doesn't hold while nothing changes", () => {
const page = open(DEFAULT_POLICY);
expect(page.container.textContent).toContain(
- "Browsers stay signed in while they're used, until 30 days unused. CLIs stay signed in while they're used, until 180 days unused. Everyone makes access tokens, each lasting as long as its maker chooses.",
+ "Admin tokens and service accounts' secrets last as long as their makers chose",
);
expect(page.button("Save")).toBeUndefined();
expect(sessionPolicyPreview).not.toHaveBeenCalled();
@@ -114,7 +114,9 @@ describe("Admin → Sign-in: staying signed in", () => {
expect(page.container.textContent).toContain("It ends 3 access tokens, all of them members'");
await act(async () => page.button("Cancel")?.click());
expect(page.button("Save")).toBeUndefined();
- expect(page.container.textContent).toContain("Everyone makes access tokens");
+ expect(page.container.textContent).toContain(
+ "Everyone makes tokens for scripts, CI and bots in Settings.",
+ );
expect(updateInstanceSettings).not.toHaveBeenCalled();
});
});
diff --git a/web/src/components/sign-in/sessions.tsx b/web/src/components/sign-in/sessions.tsx
index eca7164b..6fc8139e 100644
--- a/web/src/components/sign-in/sessions.tsx
+++ b/web/src/components/sign-in/sessions.tsx
@@ -14,15 +14,31 @@ import {
browserMaxChoices,
cliMaxChoices,
consequences,
- describe,
samePolicy,
tokenMaxChoices,
} from "@/lib/session-policy";
-/** A limit's row: what it is and what its value means, its control beside them. */
-function Row({ label, hint, children }: { label: string; hint: ReactNode; children: ReactNode }) {
+/** A limit's row: what it is and what its value means, its control beside them (under them on a phone, but a switch). */
+function Row({
+ label,
+ hint,
+ inline,
+ children,
+}: {
+ label: string;
+ hint: ReactNode;
+ inline?: boolean;
+ children: ReactNode;
+}) {
return (
-
+ Admin tokens and service accounts' secrets last as long as their makers chose: they're for
+ machines, such as the directory sync that closes people's accounts.
)}
diff --git a/web/src/lib/session-policy.test.ts b/web/src/lib/session-policy.test.ts
index d790cd1b..ace74c0f 100644
--- a/web/src/lib/session-policy.test.ts
+++ b/web/src/lib/session-policy.test.ts
@@ -4,32 +4,13 @@ import {
browserMaxChoices,
consequences,
DEFAULT_POLICY,
- describe as describePolicy,
devicesNote,
minutes,
tokenMaxChoices,
} from "./session-policy";
describe("session policies", () => {
- it("read as the CLI says them", () => {
- expect(describePolicy(DEFAULT_POLICY)).toEqual([
- "Browsers stay signed in while they're used, until 30 days unused.",
- "CLIs stay signed in while they're used, until 180 days unused.",
- "Everyone makes access tokens, each lasting as long as its maker chooses.",
- ]);
- expect(
- describePolicy({
- browser_max_hours: 12,
- browser_idle_minutes: 60,
- cli_max_days: 30,
- access_token_max_days: 365,
- member_access_tokens: false,
- }),
- ).toEqual([
- "Browsers sign in again after 12 hours, and after an hour unused.",
- "CLIs sign in again after 30 days, and after 180 days unused.",
- "Only admins make access tokens, each lasting a year at most.",
- ]);
+ it("say durations as the CLI does", () => {
expect([1, 15, 60, 90, 1440, 10080, 43200].map(minutes)).toEqual([
"a minute",
"15 minutes",
@@ -49,6 +30,9 @@ describe("session policies", () => {
expect(consequences({ browsers: 0, clis: 0, access_tokens: 0, member_tokens: 0, you: false })).toEqual([
"Nobody is signed out now: sign-ins end as it says from here on.",
]);
+ expect(consequences({ browsers: 0, clis: 0, access_tokens: 1, member_tokens: 1, you: false })).toEqual([
+ "It ends 1 access token, a member's: scripts and CI that use it need new ones.",
+ ]);
expect(consequences({ browsers: 0, clis: 0, access_tokens: 0, member_tokens: 0, you: true })).toEqual([
"Saving signs you out at once: you sign in again.",
]);
@@ -74,7 +58,13 @@ describe("session policies", () => {
expect(
devicesNote({ ...DEFAULT_POLICY, browser_max_hours: 12, browser_idle_minutes: 60, cli_max_days: 30 }),
).toBe(
- "This instance signs out browsers 12 hours after they sign in, browsers unused for an hour and CLIs 30 days after they sign in.",
+ "This instance signs browsers out 12 hours after they sign in, or after an hour unused, and CLIs 30 days after they sign in.",
+ );
+ expect(devicesNote({ ...DEFAULT_POLICY, cli_max_days: 7 })).toBe(
+ "This instance signs CLIs out a week after they sign in.",
+ );
+ expect(devicesNote({ ...DEFAULT_POLICY, browser_max_hours: 24 })).toBe(
+ "This instance signs browsers out a day after they sign in.",
);
});
});
diff --git a/web/src/lib/session-policy.ts b/web/src/lib/session-policy.ts
index 9590424f..d276bb39 100644
--- a/web/src/lib/session-policy.ts
+++ b/web/src/lib/session-policy.ts
@@ -66,25 +66,6 @@ export const cliMaxChoices = (current?: number) =>
export const tokenMaxChoices = (current?: number) =>
choices([0, 7, 30, 90, 365], current, days, "As its maker chooses", 0);
-/** What a policy says, a sentence for browsers, CLIs and access tokens each, as the CLI says it. */
-export function describe(p: G.SessionPolicy): string[] {
- const idle = minutes(p.browser_idle_minutes);
- const browsers =
- p.browser_max_hours > 0
- ? `Browsers sign in again after ${hours(p.browser_max_hours)}, and after ${idle} unused.`
- : `Browsers stay signed in while they're used, until ${idle} unused.`;
- const clis =
- p.cli_max_days > 0
- ? `CLIs sign in again after ${days(p.cli_max_days)}, and after 180 days unused.`
- : "CLIs stay signed in while they're used, until 180 days unused.";
- const who = p.member_access_tokens ? "Everyone makes access tokens" : "Only admins make access tokens";
- const tokens =
- p.access_token_max_days > 0
- ? `${who}, each lasting ${days(p.access_token_max_days)} at most.`
- : `${who}, each lasting as long as its maker chooses.`;
- return [browsers, clis, tokens];
-}
-
/** "a", "a and b". */
const and = (items: string[]) =>
items.length <= 1 ? (items[0] ?? "") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
@@ -107,7 +88,9 @@ export function consequences(p: G.SessionPolicyPreview): string[] {
p.member_tokens === 0
? ""
: p.member_tokens === p.access_tokens
- ? ", all of them members'"
+ ? p.access_tokens === 1
+ ? ", a member's"
+ : ", all of them members'"
: `, ${p.member_tokens} of them members'`;
lines.push(
`It ends ${count(p.access_tokens, "access token", "access tokens")}${members}: scripts and CI that use ${p.access_tokens === 1 ? "it" : "them"} need new ones.`,
@@ -128,10 +111,12 @@ export const samePolicy = (a: G.SessionPolicy, b: G.SessionPolicy) =>
/** What Settings → Devices says of how long its sign-ins last, where the instance limits them more than by default. */
export function devicesNote(p: G.SessionPolicy | undefined): string | undefined {
if (!p) return undefined;
- const parts: string[] = [];
- if (p.browser_max_hours > 0) parts.push(`browsers ${hours(p.browser_max_hours)} after they sign in`);
+ const browser: string[] = [];
+ if (p.browser_max_hours > 0) browser.push(`${hours(p.browser_max_hours)} after they sign in`);
if (p.browser_idle_minutes < DEFAULT_POLICY.browser_idle_minutes)
- parts.push(`browsers unused for ${minutes(p.browser_idle_minutes)}`);
- if (p.cli_max_days > 0) parts.push(`CLIs ${days(p.cli_max_days)} after they sign in`);
- return parts.length ? `This instance signs out ${and(parts)}.` : undefined;
+ browser.push(`after ${minutes(p.browser_idle_minutes)} unused`);
+ const cli = p.cli_max_days > 0 ? `CLIs ${days(p.cli_max_days)} after they sign in` : undefined;
+ if (browser.length === 0) return cli && `This instance signs ${cli.replace(/^CLIs/, "CLIs out")}.`;
+ const browsers = `This instance signs browsers out ${browser.join(", or ")}`;
+ return cli ? `${browsers}, and ${cli}.` : `${browsers}.`;
}
From b9791d8626b7cb6a0869fb0d2ba5a67a898a43a0 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Thu, 26 Nov 2026 00:20:12 +0000
Subject: [PATCH 09/11] fix(control): keep access tokens' own ends, and refuse
outside the networks before writing
Access tokens store the end their makers chose, and every request
applies the policy's longest from when they were made, so relaxing the
policy gives that choice back. Open sockets count as use. Sign-up from
outside the networks is refused before the account and the invitation
are written, and a CLI's approved code waits for a poll from inside one
rather than being used up. The longest token life is named in days, and
Save waits for the preview of the draft as it is.
---
crates/fctl-control/src/api/auth.rs | 23 +++++++++++--
crates/fctl-control/src/auth.rs | 36 ++++++++++++++------
crates/fctl-domain/src/session_policy.rs | 19 ++++++++---
web/src/components/sign-in/sessions.test.tsx | 30 +++++++++++++++-
web/src/components/sign-in/sessions.tsx | 5 +--
5 files changed, 91 insertions(+), 22 deletions(-)
diff --git a/crates/fctl-control/src/api/auth.rs b/crates/fctl-control/src/api/auth.rs
index 487eff1c..7f43d013 100644
--- a/crates/fctl-control/src/api/auth.rs
+++ b/crates/fctl-control/src/api/auth.rs
@@ -237,6 +237,12 @@ pub async fn signup(ctx: &mut Ctx, req: &mut Request) -> AppResult {
"An account with this email already exists. Sign in instead.",
));
}
+ // From outside the instance's networks, before the account and the
+ // invitation's use are written: nobody new signs in from there.
+ let networks = crate::instance::settings(&ctx.db).await?.networks;
+ if !fctl_domain::networks::admits(&networks, ctx.ip.as_deref()) {
+ return Err(AppError(crate::sign_in::outside_refused(ctx.ip.as_deref())));
+ }
// Where its domain signs in with a provider, the invitation is taken
// with that provider's sign-in, which makes the account (`api::sign_in`).
let settings = crate::instance::settings(&ctx.db).await?;
@@ -952,6 +958,20 @@ pub async fn device_poll(ctx: &mut Ctx, req: &mut Request) -> AppResult AppResult s.session_policy(),
None => crate::instance::settings(&ctx.db).await?.session_policy(),
};
- let expires_at = session_policy::expires_at(&policy, kind, ctx.now, ctx.now, expires_at);
+ let expires_at = match kind {
+ TokenKind::Pat => expires_at,
+ TokenKind::Web | TokenKind::Cli => {
+ session_policy::expires_at(&policy, kind, ctx.now, ctx.now, expires_at)
+ }
+ };
let scope = limits
.filter(|_| kind == TokenKind::Pat)
.map(Limits::to_json);
@@ -246,18 +253,21 @@ struct TokenLookup {
impl TokenLookup {
/// Whether, and why, the token no longer signs its person in at `now`
/// under `settings`' session policy (`fctl_domain::session_policy`).
+ /// `in_use`: a socket opened with it is open, which counts as use,
+ /// though nothing records it in `last_used_at`.
fn ended(
&self,
kind: TokenKind,
settings: &InstanceSettings,
now: i64,
+ in_use: bool,
) -> Option {
session_policy::ended(
&settings.session_policy(),
&session_policy::Token {
kind,
created_at: self.token_created_at,
- last_used_at: self.last_used_at,
+ last_used_at: if in_use { Some(now) } else { self.last_used_at },
expires_at: self.expires_at,
member: self.user.role() == fctl_proto::session::InstanceRole::Member,
},
@@ -332,7 +342,9 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult
Ok(found.and_then(|f| {
let settings = crate::instance::parse(f.instance_settings.as_deref());
let kind = TokenKind::parse(&f.kind).unwrap_or(TokenKind::Pat);
- if f.ended(kind, &settings, now).is_some() || !f.user.is_active() {
+ // An open socket is in use: only its sign-in's age, its end and
+ // who makes access tokens close it.
+ if f.ended(kind, &settings, now, true).is_some() || !f.user.is_active() {
return None;
}
let how = SignedIn::read(f.auth_method.as_deref(), f.auth_domain.as_deref());
@@ -405,7 +417,7 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
let settings = crate::instance::parse(found.instance_settings.as_deref());
// Expired, or past what the instance's session policy lets it last: a
// browser's is signed out, and signs in again.
- if let Some(why) = found.ended(kind, &settings, ctx.now) {
+ if let Some(why) = found.ended(kind, &settings, ctx.now, false) {
if via_cookie {
clear_session_cookie(ctx);
return Ok(());
@@ -455,11 +467,13 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
};
let stale = found.last_used_at.is_none_or(|t| ctx.now - t > touch_after);
if stale {
- let chosen = (kind == TokenKind::Pat)
- .then_some(found.expires_at)
- .flatten();
- let new_expiry =
- session_policy::expires_at(&policy, kind, found.token_created_at, ctx.now, chosen);
+ // An access token's end stays its maker's ([`issue_token`]).
+ let new_expiry = match kind {
+ TokenKind::Pat => found.expires_at,
+ TokenKind::Web | TokenKind::Cli => {
+ session_policy::expires_at(&policy, kind, found.token_created_at, ctx.now, None)
+ }
+ };
let db = crate::db::handle(&ctx.db);
let id = found.token_id.clone();
let now = ctx.now;
diff --git a/crates/fctl-domain/src/session_policy.rs b/crates/fctl-domain/src/session_policy.rs
index a4a650d5..59840c79 100644
--- a/crates/fctl-domain/src/session_policy.rs
+++ b/crates/fctl-domain/src/session_policy.rs
@@ -231,11 +231,11 @@ pub fn check(p: &SessionPolicy) -> Result<(), ApiError> {
pub fn check_token_days(p: &SessionPolicy, days_asked: Option) -> Result<(), ApiError> {
let max = p.access_token_max_days;
if max > 0 && days_asked.is_none_or(|d| d > max) {
- let words = days(max);
- let longest = if words == format!("{max} days") {
- words
+ // In days, as people choose a token's: "1 day", "90 days".
+ let longest = if max == 1 {
+ "1 day".to_owned()
} else {
- format!("{words} ({max} days)")
+ format!("{max} days")
};
return Err(ApiError::validation(
"expires_in_days",
@@ -507,7 +507,16 @@ mod tests {
assert!(
check_token_days(&year, None)
.err()
- .is_some_and(|e| e.message.contains("a year (365 days) at most"))
+ .is_some_and(|e| e.message.contains("last 365 days at most"))
+ );
+ let day = SessionPolicy {
+ access_token_max_days: 1,
+ ..policy()
+ };
+ assert!(
+ check_token_days(&day, Some(7))
+ .err()
+ .is_some_and(|e| e.message.contains("last 1 day at most"))
);
// For ever is longer than any.
assert!(check_token_days(&p, None).is_err());
diff --git a/web/src/components/sign-in/sessions.test.tsx b/web/src/components/sign-in/sessions.test.tsx
index 0b063962..c4ee5cdc 100644
--- a/web/src/components/sign-in/sessions.test.tsx
+++ b/web/src/components/sign-in/sessions.test.tsx
@@ -54,11 +54,16 @@ function open(policy: G.SessionPolicy) {
const choose = async (label: string, text: string) => {
const list = container.querySelector(`[aria-label="${label}"]`);
await act(async () => list?.click());
- const option = [...document.body.querySelectorAll('[role="option"]')].find((o) =>
+ // The list just opened: one opened before may linger as it closes.
+ const option = [...document.body.querySelectorAll('[role="option"]')].findLast((o) =>
o.textContent?.startsWith(text),
);
expect(option, text).toBeTruthy();
await act(async () => option?.click());
+ // The list flashes the pick, then closes, before it opens again.
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 600));
+ });
await settle();
};
return { container, button, choose };
@@ -96,6 +101,29 @@ describe("Admin → Sign-in: staying signed in", () => {
expect(updateInstanceSettings).toHaveBeenCalledWith({ ...DEFAULT_POLICY, browser_max_hours: 12 });
});
+ it("waits for what the draft as it is ends before it saves", async () => {
+ let answer: (p: G.SessionPolicyPreview) => void = () => {};
+ sessionPolicyPreview.mockResolvedValueOnce({
+ browsers: 1,
+ clis: 0,
+ access_tokens: 0,
+ member_tokens: 0,
+ you: false,
+ } satisfies G.SessionPolicyPreview);
+ const page = open(DEFAULT_POLICY);
+ await page.choose("Browsers sign in again after", "A week");
+ expect(page.button("Save")?.disabled).toBe(false);
+ // Another change: the first draft's counts show, faded, and Save waits.
+ sessionPolicyPreview.mockReturnValueOnce(new Promise((r) => (answer = r)));
+ await page.choose("Browsers sign in again after", "12 hours");
+ expect(page.container.textContent).toContain("Saving signs out 1 browser at once");
+ expect(page.button("Save")?.disabled).toBe(true);
+ await act(async () => answer({ browsers: 9, clis: 0, access_tokens: 0, member_tokens: 0, you: false }));
+ await settle();
+ expect(page.container.textContent).toContain("Saving signs out 9 browsers at once");
+ expect(page.button("Save")?.disabled).toBe(false);
+ });
+
it("puts the saved policy back on cancel", async () => {
sessionPolicyPreview.mockResolvedValue({
browsers: 0,
diff --git a/web/src/components/sign-in/sessions.tsx b/web/src/components/sign-in/sessions.tsx
index 6fc8139e..83bfafaa 100644
--- a/web/src/components/sign-in/sessions.tsx
+++ b/web/src/components/sign-in/sessions.tsx
@@ -157,7 +157,8 @@ export function SessionPolicies({ policy }: { policy?: G.SessionPolicy }) {
{changed ? (
{
@@ -213,7 +214,7 @@ function Change({
-
From 912547a5a67616b6b054e71dba78f092fa739854 Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Thu, 26 Nov 2026 00:24:21 +0000
Subject: [PATCH 10/11] fix(control): keep a browser watching over a socket
signed in
An open socket's checks read its sign-in as in use without the end its
last recorded use gave it, and record that use as a request does, so
that its end slides and the hourly job doesn't delete it.
---
crates/fctl-control/src/auth.rs | 107 +++++++++++++++++------
crates/fctl-domain/src/session_policy.rs | 50 +++++++++++
2 files changed, 131 insertions(+), 26 deletions(-)
diff --git a/crates/fctl-control/src/auth.rs b/crates/fctl-control/src/auth.rs
index a02a2413..a59bb66d 100644
--- a/crates/fctl-control/src/auth.rs
+++ b/crates/fctl-control/src/auth.rs
@@ -254,7 +254,7 @@ impl TokenLookup {
/// Whether, and why, the token no longer signs its person in at `now`
/// under `settings`' session policy (`fctl_domain::session_policy`).
/// `in_use`: a socket opened with it is open, which counts as use,
- /// though nothing records it in `last_used_at`.
+ /// though nothing records it ([`session_policy::Token::in_use`]).
fn ended(
&self,
kind: TokenKind,
@@ -262,17 +262,15 @@ impl TokenLookup {
now: i64,
in_use: bool,
) -> Option {
- session_policy::ended(
- &settings.session_policy(),
- &session_policy::Token {
- kind,
- created_at: self.token_created_at,
- last_used_at: if in_use { Some(now) } else { self.last_used_at },
- expires_at: self.expires_at,
- member: self.user.role() == fctl_proto::session::InstanceRole::Member,
- },
- now,
- )
+ let token = session_policy::Token {
+ kind,
+ created_at: self.token_created_at,
+ last_used_at: self.last_used_at,
+ expires_at: self.expires_at,
+ member: self.user.role() == fctl_proto::session::InstanceRole::Member,
+ };
+ let token = if in_use { token.in_use(now) } else { token };
+ session_policy::ended(&settings.session_policy(), &token, now)
}
}
@@ -339,11 +337,21 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult
let found: Option = q(db, &token_lookup_sql("id"), &[s(token_id)])?
.first()
.await?;
+ // An open socket is in use: it records that as a request does
+ // ([`authenticate`]), so that its sign-in's end slides, and the hourly
+ // job, which deletes ended sign-ins, leaves it.
+ if let Some(f) = &found {
+ let settings = crate::instance::parse(f.instance_settings.as_deref());
+ let kind = TokenKind::parse(&f.kind).unwrap_or(TokenKind::Pat);
+ if f.ended(kind, &settings, now, true).is_none() {
+ touch(db, f, kind, &settings.session_policy(), now).await?;
+ }
+ }
Ok(found.and_then(|f| {
let settings = crate::instance::parse(f.instance_settings.as_deref());
let kind = TokenKind::parse(&f.kind).unwrap_or(TokenKind::Pat);
- // An open socket is in use: only its sign-in's age, its end and
- // who makes access tokens close it.
+ // Only its sign-in's age, its end as its maker chose and who makes
+ // access tokens close it.
if f.ended(kind, &settings, now, true).is_some() || !f.user.is_active() {
return None;
}
@@ -364,6 +372,61 @@ pub async fn by_token_id(db: &D1Database, token_id: &str, now: i64) -> AppResult
}))
}
+/// When a token's use is recorded again after its last record: often
+/// enough, for a browser, that one in use isn't taken for unused.
+fn touch_after(kind: TokenKind, policy: &fctl_proto::api::SessionPolicy) -> i64 {
+ match kind {
+ TokenKind::Web => session_policy::touch_after_ms(policy),
+ TokenKind::Cli | TokenKind::Pat => session_policy::TOUCH_MS,
+ }
+}
+
+/// The end a token of `kind` slides to as it's used at `now`: a browser's
+/// or a CLI's as the session policy says; an access token's stays its
+/// maker's ([`issue_token`]).
+fn slid(
+ found: &TokenLookup,
+ kind: TokenKind,
+ policy: &fctl_proto::api::SessionPolicy,
+ now: i64,
+) -> Option {
+ match kind {
+ TokenKind::Pat => found.expires_at,
+ TokenKind::Web | TokenKind::Cli => {
+ session_policy::expires_at(policy, kind, found.token_created_at, now, None)
+ }
+ }
+}
+
+/// Records a socket's use of its token, at most as often as
+/// [`touch_after`] says.
+async fn touch(
+ db: &D1Database,
+ found: &TokenLookup,
+ kind: TokenKind,
+ policy: &fctl_proto::api::SessionPolicy,
+ now: i64,
+) -> AppResult<()> {
+ if found
+ .last_used_at
+ .is_some_and(|t| now - t <= touch_after(kind, policy))
+ {
+ return Ok(());
+ }
+ q(
+ db,
+ "UPDATE tokens SET last_used_at = ?, expires_at = ? WHERE id = ?",
+ &[
+ n(now),
+ on(slid(found, kind, policy, now)),
+ s(&found.token_id),
+ ],
+ )?
+ .run()
+ .await?;
+ Ok(())
+}
+
/// Resolves the caller from the bearer token or the session cookie. Invalid
/// or expired credentials are treated as signed out (and the cookie cleared).
pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
@@ -461,19 +524,11 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
// browsers sign out after a short while unused; slide web and CLI
// expiry, never past what the session policy lets them last.
let policy = settings.session_policy();
- let touch_after = match kind {
- TokenKind::Web => session_policy::touch_after_ms(&policy),
- TokenKind::Cli | TokenKind::Pat => session_policy::TOUCH_MS,
- };
- let stale = found.last_used_at.is_none_or(|t| ctx.now - t > touch_after);
+ let stale = found
+ .last_used_at
+ .is_none_or(|t| ctx.now - t > touch_after(kind, &policy));
if stale {
- // An access token's end stays its maker's ([`issue_token`]).
- let new_expiry = match kind {
- TokenKind::Pat => found.expires_at,
- TokenKind::Web | TokenKind::Cli => {
- session_policy::expires_at(&policy, kind, found.token_created_at, ctx.now, None)
- }
- };
+ let new_expiry = slid(&found, kind, &policy, ctx.now);
let db = crate::db::handle(&ctx.db);
let id = found.token_id.clone();
let now = ctx.now;
diff --git a/crates/fctl-domain/src/session_policy.rs b/crates/fctl-domain/src/session_policy.rs
index 59840c79..46cef2de 100644
--- a/crates/fctl-domain/src/session_policy.rs
+++ b/crates/fctl-domain/src/session_policy.rs
@@ -104,6 +104,25 @@ pub struct Token {
pub member: bool,
}
+impl Token {
+ /// It as a socket opened with it reads it while it stays open: used at
+ /// `now`, as an open socket is in use though nothing records it. A
+ /// browser's or a CLI's stored end is its last recorded use plus the
+ /// time it may go unused, capped by the policy's longest, so it goes
+ /// too: [`ended`] applies that longest from its sign-in. An access
+ /// token keeps the end its maker chose.
+ pub fn in_use(self, now: i64) -> Self {
+ Self {
+ last_used_at: Some(now),
+ expires_at: match self.kind {
+ TokenKind::Pat => self.expires_at,
+ TokenKind::Web | TokenKind::Cli => None,
+ },
+ ..self
+ }
+ }
+}
+
/// Why a token no longer signs its person in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Ended {
@@ -427,6 +446,37 @@ mod tests {
);
}
+ #[test]
+ fn an_open_socket_is_in_use() {
+ let p = SessionPolicy {
+ browser_max_hours: 12,
+ browser_idle_minutes: 15,
+ ..policy()
+ };
+ // A browser last recorded in use an hour ago, its stored end the
+ // 15 minutes after: a request ends it, its open socket doesn't.
+ let watching = Token {
+ expires_at: Some(15 * MINUTE_MS),
+ ..token(TokenKind::Web, 0, Some(0))
+ };
+ assert_eq!(ended(&p, &watching, HOUR_MS), Some(Ended::Expired));
+ assert_eq!(ended(&p, &watching.in_use(HOUR_MS), HOUR_MS), None);
+ // Past the policy's longest from its sign-in, it ends either way.
+ assert_eq!(
+ ended(&p, &watching.in_use(12 * HOUR_MS), 12 * HOUR_MS),
+ Some(Ended::TooOld)
+ );
+ // An access token keeps its maker's end.
+ let pat = Token {
+ expires_at: Some(HOUR_MS),
+ ..token(TokenKind::Pat, 0, None)
+ };
+ assert_eq!(
+ ended(&p, &pat.in_use(HOUR_MS), HOUR_MS),
+ Some(Ended::Expired)
+ );
+ }
+
#[test]
fn members_tokens_stop_where_members_make_none() {
let p = SessionPolicy {
From 537a336d814a70e9710b999697c0cd88f51744fb Mon Sep 17 00:00:00 2001
From: "fctl-sh[bot]"
Date: Thu, 26 Nov 2026 00:27:19 +0000
Subject: [PATCH 11/11] fix(control): keep a browser's cookie for as long as
its sign-in may last
Its cookie lasts until the policy's longest from its sign-in, and 30
days at most, rather than its time unused, which only requests renew: a
tab that holds a socket open keeps its cookie, and the server still ends
a sign-in unused too long.
---
crates/fctl-control/src/auth.rs | 12 +++++-----
crates/fctl-domain/src/session_policy.rs | 29 ++++++++++++++++++++++++
2 files changed, 35 insertions(+), 6 deletions(-)
diff --git a/crates/fctl-control/src/auth.rs b/crates/fctl-control/src/auth.rs
index a59bb66d..9c5d5075 100644
--- a/crates/fctl-control/src/auth.rs
+++ b/crates/fctl-control/src/auth.rs
@@ -135,17 +135,17 @@ pub async fn issue_token(
ctx.cookies.push(http::set_cookie(
Cookie::Session,
&secret,
- cookie_max_age(expires_at, ctx.now),
+ cookie_max_age(&policy, ctx.now, ctx.now),
ctx.cfg.secure_cookies(),
));
}
Ok((id.0, secret))
}
-/// The seconds a browser keeps the session cookie of a sign-in that ends
-/// at `expires_at`.
-fn cookie_max_age(expires_at: Option, now: i64) -> u64 {
- let ms = expires_at.map_or(30 * DAY_MS, |e| e - now).max(0);
+/// The seconds a browser keeps the session cookie of a sign-in made at
+/// `created_at`, as it's used at `now` (`session_policy::cookie_until`).
+fn cookie_max_age(policy: &fctl_proto::api::SessionPolicy, created_at: i64, now: i64) -> u64 {
+ let ms = (session_policy::cookie_until(policy, created_at, now) - now).max(0);
(ms / 1000) as u64
}
@@ -546,7 +546,7 @@ pub async fn authenticate(ctx: &mut Ctx, req: &Request) -> AppResult<()> {
ctx.cookies.push(http::set_cookie(
Cookie::Session,
&secret,
- cookie_max_age(new_expiry, ctx.now),
+ cookie_max_age(&policy, found.token_created_at, ctx.now),
ctx.cfg.secure_cookies(),
));
}
diff --git a/crates/fctl-domain/src/session_policy.rs b/crates/fctl-domain/src/session_policy.rs
index 46cef2de..5ce94952 100644
--- a/crates/fctl-domain/src/session_policy.rs
+++ b/crates/fctl-domain/src/session_policy.rs
@@ -82,6 +82,17 @@ pub fn expires_at(
[chosen, idle, max].into_iter().flatten().min()
}
+/// Until when a browser keeps the cookie of a sign-in made at
+/// `created_at`, as it's used at `now`: its policy's longest, and 30 days
+/// from now at most, as before policies. Not its time unused: only
+/// requests renew a cookie, and a tab that holds a socket open stays in
+/// use without them ([`Token::in_use`]); the server ends a sign-in unused
+/// too long whatever its cookie says.
+pub fn cookie_until(p: &SessionPolicy, created_at: i64, now: i64) -> i64 {
+ let longest = now.saturating_add(i64::from(DEFAULT_BROWSER_IDLE_MINUTES) * MINUTE_MS);
+ max_age_ms(p, TokenKind::Web).map_or(longest, |m| created_at.saturating_add(m).min(longest))
+}
+
/// How often a browser's use is recorded: often enough, where browsers
/// sign out after a short while unused, that one in use isn't taken for
/// unused between two records.
@@ -446,6 +457,24 @@ mod tests {
);
}
+ #[test]
+ fn a_cookie_lasts_as_long_as_its_sign_in_may() {
+ // Not just the time a browser may sit unused: a socket keeps it in
+ // use without requests that renew its cookie.
+ let idle = SessionPolicy {
+ browser_idle_minutes: 15,
+ ..policy()
+ };
+ assert_eq!(cookie_until(&idle, 0, HOUR_MS), HOUR_MS + 30 * DAY_MS);
+ // Its longest, from its sign-in.
+ let short = SessionPolicy {
+ browser_max_hours: 12,
+ ..idle
+ };
+ assert_eq!(cookie_until(&short, 0, HOUR_MS), 12 * HOUR_MS);
+ assert_eq!(cookie_until(&policy(), 0, 0), 30 * DAY_MS);
+ }
+
#[test]
fn an_open_socket_is_in_use() {
let p = SessionPolicy {