Public: anyone can read this; the crew can change it.

Signing in issues a fresh session id and the old one stops working #13609

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13579-signing-in-issues-a-fresh-session-id-and → main 3 commits fork 4 threads · 4 unresolved

  • Merged. scout/13579-signing-in-issues-a-fresh-session-id-and was merged into main as 9decd10.

Review

Sign in to review this change.
15 files changed +488 −40
src/auth/session_rotate.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * Signing in rotates the session id (#13579). Every door that signs a
3 * browser in (password, passkey, a recovery or access link, a parent forge's
4 * OAuth) asks here instead of `createSession`: the id the browser presented
5 * is ended, and a fresh one is made. An id someone planted or saw before
6 * the sign-in is worth nothing after it.
7 *
8 * Only the presented id ends: the person's other browsers stay signed in.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import { createSession, destroySession } from "../core/sessions.ts";
13
14 /** End the `presented` session id, when there is one, and make a fresh one for `userId`. */
15 export function rotateSession(
16 db: Database,
17 presented: string | undefined,
18 userId: string,
19 ): { token: string; expiresAt: Date } {
20 if (presented !== undefined && presented !== "") destroySession(db, presented);

Fine as written. Once every browser sign-in door uses it, add a test that fails if a new one calls createSession directly, such as a grep-style test over src/web and src/http. Otherwise doors will keep being missed.

21 return createSession(db, userId);
22 }
src/http/api/tokens.ts +2 −2
@@ -8,7 +8,7 @@
88 import { signOutHere } from "../../actions/signins.ts";
99 import { createToken, deleteToken } from "../../actions/users.ts";
1010 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
11 import { createSession } from "../../core/sessions.ts";
11 import { rotateSession } from "../../auth/session_rotate.ts";
1212 import { listTokensWithClients } from "../../core/oauth.ts";
1313 import { ADMIN_TOKEN_WORDS } from "../../core/tokens.ts";
1414 import { type User, verifyPasswordThrottled } from "../../core/users.ts";
@@ -38,7 +38,7 @@ export function tokenRoutes(router: Router<Handler>): void {
3838 return verified.error.reason === "throttled"
3939 ? tooManyAttempts(verified.error.retryAfter)
4040 : unauthorized();
41 const session = createSession(ctx.app.db, verified.value.id);
41 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), verified.value.id);
4242 return json(publicUser(verified.value), 201, {
4343 "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
4444 });
src/http/rp.ts +8 −4
@@ -30,7 +30,7 @@ import { retryAfterOf } from "./respond.ts";
3030 import { readCapped } from "../origins/providers/http.ts";
3131 import { clientAddress } from "./peer.ts";
3232 import { signinAllowed } from "../web/pages/site.ts";
33 import { createSession } from "../core/sessions.ts";
33 import { rotateSession } from "../auth/session_rotate.ts";
3434 import { SIGNIN_EXPIRED, SIGNIN_NOT_THIS_BROWSER } from "../kernel/signin_words.ts";
3535 import { verifyJwt } from "../kernel/jwt.ts";
3636 import { html } from "../web/html.ts";
@@ -128,7 +128,10 @@ export const cookieHeader = (value: string, maxAge: number, url: URL, forgeUrl?:
128128
129129 export const parentStart = (ctx: Ctx): Promise<Response> => begin(ctx);
130130
131 /** POST /settings/parent/link: the same round trip, begun by a signed-in person to link, not to sign in. */
131 /**
132 * POST /settings/parent/link: the same round trip, begun by a signed-in person to link, not to sign
133 * in.
134 */
132135 export async function parentLinkStart(ctx: Ctx): Promise<Response> {
133136 if (!ctx.auth.user) return signInFirst(ctx);
134137 const form = await readForm(ctx, "admin");
@@ -226,7 +229,8 @@ export async function parentCallback(ctx: Ctx): Promise<Response> {
226229 if (typeof sub !== "string" || !SUB.test(sub))
227230 return refuse("The parent forge's answer did not verify.", 502);
228231 if (login.linkUser !== undefined) {
229 // A link is for the account that began it, still signed in in this browser: never a sign-in, never a new account.
232 // A link is for the account that began it, still signed in in this browser: never a sign-in,
233 // never a new account.
230234 if (ctx.auth.user?.id !== login.linkUser) return refuse("Sign in again, then link from your settings.", 403);
231235 const linked = linkParent(ctx.app.db, login.linkUser, login.issuer, sub);
232236 const back = flashTo(ctx, "/settings", {
@@ -249,7 +253,7 @@ export async function parentCallback(ctx: Ctx): Promise<Response> {
249253 done.headers.set("cache-control", "no-store");
250254 return done;
251255 }
252 const session = createSession(ctx.app.db, user.id);
256 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), user.id);
253257 const done = redirect("/", sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url));
254258 done.headers.append("set-cookie", clear);
255259 done.headers.set("cache-control", "no-store");
src/web/pages/claim.ts +3 −3
@@ -25,7 +25,7 @@
2525 import { PASSWORD_TOO_LONG, withinPasswordCap } from "../../core/hash-gate.ts";
2626 import { givenEmail, MIN_SIGNUP_PASSWORD, noEmail } from "../../actions/users.ts";
2727 import type { Credential } from "../../auth/webauthn.ts";
28 import { crossOrigin, type Ctx } from "../../http/context.ts";
28 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
2929 import { STRANGER_MAX } from "../../http/limits.ts";
3030 import { clientAddress } from "../../http/peer.ts";
3131 import { boundedBody, json, str } from "../../http/respond.ts";
@@ -42,7 +42,7 @@ import {
4242 timePhase,
4343 timePhaseAsync,
4444 } from "../../core/route_timing.ts";
45 import { createSession } from "../../core/sessions.ts";
45 import { rotateSession } from "../../auth/session_rotate.ts";
4646 import { createUser, discardFreshUser, getUserByName, type User } from "../../core/users.ts";
4747 import {
4848 burnClaim,
@@ -544,7 +544,7 @@ function claimed(ctx: Ctx, spawned: Spawned, user: User): Response {
544544 user: user.username,
545545 spawnerKeeps: spawned.keepAccess,
546546 });
547 const session = createSession(ctx.app.db, user.id);
547 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), user.id);
548548 // Home: where the crew's work shows (its first-login screen is #600).
549549 return redirect(
550550 "/",
src/web/pages/everyday.ts +6 −5
@@ -20,7 +20,7 @@ import { spawnedOrg } from "../../spawn/claim.ts";
2020 import { mailConfigured, requireVerified } from "../../actions/verify.ts";
2121 import { noEmail } from "../../actions/users.ts";
2222 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
23 import { createSession } from "../../core/sessions.ts";
23 import { rotateSession } from "../../auth/session_rotate.ts";
2424 import { createUser, discardFreshUser, getUserByName, type User } from "../../core/users.ts";
2525 import { addPasskey } from "../../core/passkeys.ts";
2626 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
@@ -46,7 +46,8 @@ function suggestedName(ctx: Ctx, admin: User): string {
4646 return getUserByName(ctx.app.db, name) === undefined ? name : "";
4747 }
4848
49 // GET /settings/everyday — the step on its own page: why, a username, one passkey button, and "Keep using admin".
49 // GET /settings/everyday — the step on its own page: why, a username, one passkey button, and "Keep
50 // using admin".
5051 export function everydayPage(ctx: Ctx): Response {
5152 const user = ctx.auth.user;
5253 if (!user) return signInFirst(ctx);
@@ -197,8 +198,8 @@ export async function everydayCreate(ctx: Ctx): Promise<Response> {
197198 if (!key.ok) return say(PASSKEY_WORDS[key.error]);
198199 // The same names a sign-up may not take (a crew member's, a page's,
199200 // another admin's), held where accounts are made; the admin's own handle
200 // may appear in their everyday name ("ada-me"). A proven admin vouches for their own second account, as a claim
201 // vouches for the first: held back, it could not tell the crew.
201 // may appear in their everyday name ("ada-me"). A proven admin vouches for their own second
202 // account, as a claim vouches for the first: held back, it could not tell the crew.
202203 const made = await createUser(ctx.app.db, {
203204 username,
204205 email,
@@ -231,7 +232,7 @@ export async function everydayCreate(ctx: Ctx): Promise<Response> {
231232 tone: "danger",
232233 message: `${made.value.username} was made but could not join ${spawned.org.username}: add it to a team that writes there, then sign in as it.`,
233234 });
234 const session = createSession(ctx.app.db, made.value.id);
235 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), made.value.id);
235236 return redirect("/", {
236237 cookie: sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
237238 url: ctx.url,
src/web/pages/first-admin.ts +3 −3
@@ -9,14 +9,14 @@
99 * `POST /api/v1/first-admin` for a token instead.
1010 */
1111
12 import { crossOrigin, type Ctx } from "../../http/context.ts";
12 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
1313 import { STRANGER_MAX } from "../../http/limits.ts";
1414 import { clientAddress } from "../../http/peer.ts";
1515 import { boundedBody, json, str } from "../../http/respond.ts";
1616 import { FIRST_ADMIN_WORDS, firstAdminProblem, redeemFirstAdmin } from "../../actions/first_admin.ts";
1717 import { addPasskey } from "../../core/passkeys.ts";
1818 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
19 import { createSession } from "../../core/sessions.ts";
19 import { rotateSession } from "../../auth/session_rotate.ts";
2020 import { pageHead, CAME_FROM_ELSEWHERE } from "../chrome.ts";
2121 import { field, readForm } from "../form.ts";
2222 import { html, type Html } from "../html.ts";
@@ -166,6 +166,6 @@ export async function firstAdminSubmit(ctx: Ctx): Promise<Response> {
166166 (user) => (addPasskey(ctx.app.db, user.id, "Passkey", key.value).ok ? true : undefined),
167167 );
168168 if (!made.ok) return again(errorsOf(made.error), statusOf(made.error));
169 const session = createSession(ctx.app.db, made.value.user.id);
169 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), made.value.user.id);
170170 return redirect("/", sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url));
171171 }
src/web/pages/passkeys.ts +5 −5
@@ -21,13 +21,13 @@ import { linkEdgeLogin } from "../../core/edge_links.ts";
2121 import { activeEdgeToken, edgeIdentity } from "../../http/edge.ts";
2222 import { RateLimiter } from "../../core/ratelimit.ts";
2323 import { requestOf } from "../../core/requests.ts";
24 import { createSession } from "../../core/sessions.ts";
24 import { rotateSession } from "../../auth/session_rotate.ts";
2525 import { LAST_WAY_IN, removeOwnPasskey } from "../../actions/passkeys.ts";
2626 import { recoveryAccount, requestRecovery, spendRecoveryLink } from "../../actions/verify.ts";
2727 import { getUserById, isActive, MIN_PASSWORD } from "../../core/users.ts";
2828 import { accessLinkPerson, redeemAccessLink } from "../../actions/account_access.ts";
2929 import { CHANGE_PASSWORD_WORDS } from "../../actions/users.ts";
30 import { crossOrigin, type Ctx } from "../../http/context.ts";
30 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
3131 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
3232 import { clientAddress, clientBucket } from "../../http/peer.ts";
3333 import { STRANGER_MAX } from "../../http/limits.ts";
@@ -216,7 +216,7 @@ export async function signinPasskey(ctx: Ctx): Promise<Response> {
216216 // A proven key on an account whose request has no yes yet starts no session (#10928).
217217 if (waiting)
218218 return json({ ok: true, waiting: true, next: requestOf(ctx.app.db, user.id)?.state === "declined" ? "/signup/requested?answer=declined" : "/signup/requested" }, 202);
219 const session = createSession(ctx.app.db, user.id);
219 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), user.id);
220220 return json(
221221 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" },
222222 200,
@@ -350,7 +350,7 @@ export async function recoverFinish(ctx: Ctx): Promise<Response> {
350350 const name = str(data.name).replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, PASSKEY_NAME_MAX) || "Passkey";
351351 const added = addPasskey(ctx.app.db, spent.value.id, name, made);
352352 if (!added.ok) return refuse(409, "That passkey could not be added.");
353 const session = createSession(ctx.app.db, spent.value.id);
353 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), spent.value.id);

The recovery-link door has no test. Add one that checks the old id is refused and the other browsers stay.

354354 return json({ ok: true, next: "/settings/passkeys" }, 200, {
355355 "set-cookie": sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
356356 });
@@ -400,7 +400,7 @@ export async function accessSubmit(ctx: Ctx): Promise<Response> {
400400 const user = accessLinkPerson(ctx.app, token);
401401 return accessForm(ctx, token, user?.username ?? "", CHANGE_PASSWORD_WORDS[done.error], 422);
402402 }
403 const session = createSession(ctx.app.db, done.value.id);
403 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), done.value.id);

The access-link door has no test. Add one that checks the old id is refused and the other browsers stay.

404404 return redirect("/settings/passkeys", {
405405 cookie: sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
406406 flash: { message: "Password set; you are signed in. You can add a passkey here too." },
src/web/pages/signup-passkey.ts +3 −3
@@ -8,10 +8,10 @@
88
99 import { newChallenge, verifyRegistration } from "../../auth/webauthn.ts";
1010 import { givenEmail, signUpWithPasskey, signupClosed, HUMAN_CHECK_MESSAGE, SIGNUP_CLOSED_MESSAGE } from "../../actions/users.ts";
11 import { createSession } from "../../core/sessions.ts";
11 import { rotateSession } from "../../auth/session_rotate.ts";
1212 import { getUserByName } from "../../core/users.ts";
1313 import { isSafeName } from "../../git/guard.ts";
14 import { crossOrigin, type Ctx } from "../../http/context.ts";
14 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
1515 import { STRANGER_MAX } from "../../http/limits.ts";
1616 import { clientAddress, clientBucket } from "../../http/peer.ts";
1717 import { boundedBody, json, str } from "../../http/respond.ts";
@@ -109,7 +109,7 @@ export async function signupPasskey(ctx: Ctx): Promise<Response> {
109109 return refuse(created.error === "human_check" ? 422 : created.error === "signup_closed" ? 403 : 409, WORDS[created.error] ?? "Sign-up did not work. Try again.");
110110 // A request that waits starts no session: it lands on the page that says so.
111111 if (created.value.waitingAt !== null) return json({ ok: true, waiting: true, next: "/signup/requested" }, 202);
112 const session = createSession(ctx.app.db, created.value.id);
112 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), created.value.id);
113113 return json(
114114 { ok: true, next: safeNext(ctx.url.searchParams.get("next")) ?? "/" },
115115 201,
src/web/pages/site.ts +3 −3
@@ -27,7 +27,7 @@ import { HUMAN_CHECK_MESSAGE, INVITE_SPENT_MESSAGE, PASSKEY_REQUIRED_MESSAGE, SI
2727 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
2828 import { listPins } from "../../core/pins.ts";
2929 import { getReposByIds } from "../../core/repos.ts";
30 import { createSession } from "../../core/sessions.ts";
30 import { rotateSession } from "../../auth/session_rotate.ts";
3131 import { getUserByName, hasAnyUser, verifyPasswordThrottled, type User } from "../../core/users.ts";
3232 import { isThemeName } from "../../design/themes.ts";
3333 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
@@ -613,7 +613,7 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> {
613613 422,
614614 );
615615 }
616 const session = createSession(ctx.app.db, verified.value.id);
616 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), verified.value.id);
617617 return redirect(
618618 safeNext(ctx.url.searchParams.get("next")) ?? "/",
619619 sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
@@ -773,7 +773,7 @@ export async function signupSubmit(ctx: Ctx): Promise<Response> {
773773 }
774774 // A request that waits has no session to start: it lands on the page that says so.
775775 if (created.value.waitingAt !== null) return redirect("/signup/requested");
776 const session = createSession(ctx.app.db, created.value.id);
776 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), created.value.id);

Signup rotation has no test. Add one that would fail without the change.

777777 return redirect(
778778 safeNext(ctx.url.searchParams.get("next")) ?? "/",
779779 sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
src/web/pages/start_claim.ts +3 −3
@@ -9,9 +9,9 @@
99 import { claimStart, CLAIM_WORDS, viewClaim } from "../../actions/claim.ts";
1010 import { noEmail, plausibleEmail, signupClosed } from "../../actions/users.ts";
1111 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
12 import { createSession } from "../../core/sessions.ts";
12 import { rotateSession } from "../../auth/session_rotate.ts";
1313 import { createUser } from "../../core/users.ts";
14 import type { Ctx } from "../../http/context.ts";
14 import { cookieValue, type Ctx } from "../../http/context.ts";
1515 import { notFoundPage, pageHead } from "../chrome.ts";
1616 import { field, readForm } from "../form.ts";
1717 import { html } from "../html.ts";
@@ -108,6 +108,6 @@ export async function startClaimAccountSubmit(ctx: Ctx): Promise<Response> {
108108 }
109109 const done = await claimStart(ctx.app, made.value, token);
110110 if (!done.ok) return refused(ctx, done.error);
111 const session = createSession(ctx.app.db, made.value.id);
111 const session = rotateSession(ctx.app.db, cookieValue(ctx.request, "forge_session"), made.value.id);
112112 return redirect(`/${done.value.org}`, sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url));
113113 }
test/everyday.test.ts +6 −3
@@ -181,9 +181,12 @@ describe("the everyday account", () => {
181181 expect(await page(cookie, "/settings")).toContain(
182182 "This is the everyday account of",
183183 );
184 // The admin is not asked again, and its page names the pair.
185 expect(await page(root, "/")).not.toContain("Make an everyday account");
186 expect(await page(root, "/settings")).toContain("Your everyday account is");
184 // The admin's id in this browser ended with the sign-in (#13579).
185 expect(await page(root, "/settings")).not.toContain("Your everyday account is");
186 // Signed in as admin again, it is not asked again, and its page names the pair.
187 const back = await signIn("ada");
188 expect(await page(back, "/")).not.toContain("Make an everyday account");
189 expect(await page(back, "/settings")).toContain("Your everyday account is");
187190 });
188191
189192 test("Keep using admin is recorded; the account page still offers the way, without asking again", async () => {
test/first-login-words.test.ts +7 −2
@@ -7,6 +7,8 @@
77 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
88 import { claimedForge, type ClaimedForge } from "./helpers/claimed-forge.ts";
99 import { jargonIn } from "./helpers/jargon.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { getUserByName } from "../src/core/users.ts";
1012 import { quietLogs } from "./helpers/globals.ts";
1113 import { passkeyFields } from "./helpers/passkey.ts";
1214
@@ -35,9 +37,12 @@ describe("the first-login page of a spawned forge, in plain words", () => {
3537
3638 test("the everyday account's first page has no jargon", async () => {
3739 const who = { username: "maria-me", email: "[email protected]" };
38 const res = await forge.post(owner, "/settings/everyday", {
40 // Made in another browser of the owner's: signing in there ends that
41 // browser's admin id only (#13579), and `owner` stays signed in.
42 const here = `forge_session=${createSession(forge.child.db, getUserByName(forge.child.db, "maria")!.id).token}`;
43 const res = await forge.post(here, "/settings/everyday", {
3944 ...who,
40 ...(await passkeyFields(forge.base, "/settings/everyday/options", who, { headers: { cookie: owner } })),
45 ...(await passkeyFields(forge.base, "/settings/everyday/options", who, { headers: { cookie: here } })),
4146 });
4247 expect(res.status).toBe(303);
4348 const daily = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
test/first-login.test.ts +5 −2
@@ -242,9 +242,12 @@ describe("the first login to a spawned forge", () => {
242242
243243 test("the everyday account, made first, joins the client's org and sees the card part-way, every step one it can do", async () => {
244244 const who = { username: "maria-me", email: "[email protected]" };
245 const res = await post(owner, "/settings/everyday", {
245 // Made in another browser of the owner's: signing in there ends that
246 // browser's admin id only (#13579), and `owner` stays signed in.
247 const here = `forge_session=${createSession(child.db, getUserByName(child.db, "maria")!.id).token}`;
248 const res = await post(here, "/settings/everyday", {
246249 ...who,
247 ...(await passkeyFields(servers.url, "/settings/everyday/options", who, { headers: { cookie: owner } })),
250 ...(await passkeyFields(servers.url, "/settings/everyday/options", who, { headers: { cookie: here } })),
248251 });
249252 expect(res.status).toBe(303);
250253 daily = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
test/session-rotation.test.ts added +408
@@ -0,0 +1,408 @@
1 /**
2 * Signing in rotates the session id (#13579): on every sign-in door the
3 * cookie handed back differs from the one the browser sent, the id it sent
4 * is refused afterwards, and the person's other browsers stay signed in.
5 * Each test fails against a door that keeps the presented id alive.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { b64u } from "../src/auth/webauthn.ts";
13 import { rotateSession } from "../src/auth/session_rotate.ts";
14 import { linkParent } from "../src/core/federation.ts";
15 import { createSession, sessionUser } from "../src/core/sessions.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { device as keyDevice, passkeyFields } from "./helpers/passkey.ts";
20 import { resetAccess } from "../src/actions/account_access.ts";
21 import { mintFirstAdmin } from "../src/core/first_admin.ts";
22 import { createOrg } from "../src/core/orgs.ts";
23 import { recordStart } from "../src/core/starts.ts";
24 import { issueRecovery, markVerified } from "../src/core/verify.ts";
25 import { mintClaim } from "../src/spawn/claim.ts";
26
27 const keyFor = (url: string) => keyDevice(new URL(url).origin);
28
29 quietLogs();
30
31 const PASSWORD = "a-long-family-passphrase";
32 const dirs: string[] = [];
33 const servers: Servers[] = [];
34
35 async function forge(opts: Record<string, unknown> = {}): Promise<{ app: App; url: string }> {
36 const dir = await mkdtemp(join(tmpdir(), "session-rotation-"));
37 dirs.push(dir);
38 const app = createApp({ dataDir: dir, port: 0, ...opts });
39 const s = await serve(app);
40 servers.push(s);
41 return { app, url: s.url };
42 }
43
44 afterAll(async () => {
45 for (const s of servers) s.stop();
46 for (const dir of dirs) await rm(dir, { recursive: true, force: true });
47 });
48
49 /** The fresh `forge_session` a response sets, and its whole line. */
50 function issued(res: Response): { value: string; line: string } {
51 const line = res.headers.getSetCookie().find((c) => c.startsWith("forge_session=") && !c.startsWith("forge_session=;"));
52 if (line === undefined) throw new Error(`no session cookie set (status ${res.status})`);
53 return { value: line.split(";")[0]!.slice("forge_session=".length), line };
54 }
55
56 /** A browser that had a session (`fixed`), and the same person's other browser (`other`). */
57 function planted(app: App, userId: string): { fixed: string; other: string } {
58 return { fixed: createSession(app.db, userId).token, other: createSession(app.db, userId).token };
59 }
60
61 function expectRotated(app: App, res: Response, fixed: string, other: string): void {
62 const { value, line } = issued(res);
63 expect(value).not.toBe(fixed);
64 expect(line).toContain("HttpOnly");
65 expect(line).toContain("SameSite=Lax");
66 expect(sessionUser(app.db, value).ok).toBe(true);
67 expect(sessionUser(app.db, fixed).ok).toBe(false);
68 expect(sessionUser(app.db, other).ok).toBe(true);
69 }
70
71 describe("rotateSession", () => {
72 test("ends only the presented id and makes a fresh one", async () => {
73 const { app } = await forge();
74 const made = await createUser(app.db, { origin: "seed", username: "rae", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
75 if (!made.ok) throw new Error(made.error);
76 const { fixed, other } = planted(app, made.value.id);
77 const fresh = rotateSession(app.db, fixed, made.value.id);
78 expect(fresh.token).not.toBe(fixed);
79 expect(sessionUser(app.db, fixed).ok).toBe(false);
80 expect(sessionUser(app.db, other).ok).toBe(true);
81 expect(sessionUser(app.db, fresh.token).ok).toBe(true);
82 expect(sessionUser(app.db, rotateSession(app.db, undefined, made.value.id).token).ok).toBe(true);
83 });
84 });
85
86 describe("password sign-in", () => {
87 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
88 const { app, url } = await forge();
89 const made = await createUser(app.db, { origin: "seed", username: "pat", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
90 if (!made.ok) throw new Error(made.error);
91 const { fixed, other } = planted(app, made.value.id);
92 const res = await fetch(`${url}/signin`, {
93 method: "POST",
94 redirect: "manual",
95 headers: { cookie: `forge_session=${fixed}`, origin: url },
96 body: new URLSearchParams({ username: "pat", password: PASSWORD }),
97 });
98 expect(res.status).toBe(303);
99 expectRotated(app, res, fixed, other);
100 const old = await fetch(`${url}/settings`, { redirect: "manual", headers: { cookie: `forge_session=${fixed}` } });
101 expect(old.status).not.toBe(200);
102 });
103
104 test("on https the cookie is Secure", async () => {
105 const { app, url } = await forge({ url: "https://forge.example" });
106 const made = await createUser(app.db, { origin: "seed", username: "sal", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
107 if (!made.ok) throw new Error(made.error);
108 const res = await fetch(`${url}/signin`, {
109 method: "POST",
110 redirect: "manual",
111 headers: { origin: "https://forge.example" },
112 body: new URLSearchParams({ username: "sal", password: PASSWORD }),
113 });
114 expect(issued(res).line).toContain("Secure");
115 });
116 });
117
118 // A software authenticator: P-256, attestation "none".
119 const te = new TextEncoder();
120 const sha = async (d: Uint8Array<ArrayBuffer>) => new Uint8Array(await crypto.subtle.digest("SHA-256", d));
121 const cat = (...p: Uint8Array[]): Uint8Array<ArrayBuffer> => {
122 const o: Uint8Array<ArrayBuffer> = new Uint8Array(p.reduce((n, a) => n + a.length, 0));
123 let i = 0;
124 for (const a of p) { o.set(a, i); i += a.length; }
125 return o;
126 };
127 const head = (major: number, n: number): Uint8Array =>
128 n < 24 ? Uint8Array.of((major << 5) | n) : n < 256 ? Uint8Array.of((major << 5) | 24, n) : Uint8Array.of((major << 5) | 25, n >> 8, n & 255);
129 type V = number | string | Uint8Array | [V, V][];
130 function enc(v: V): Uint8Array {
131 if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v);
132 if (typeof v === "string") { const b = te.encode(v); return cat(head(3, b.length), b); }
133 if (v instanceof Uint8Array) return cat(head(2, v.length), v);
134 return cat(head(5, v.length), ...v.flatMap(([k, x]) => [enc(k), enc(x)]));
135 }
136 function rawToDer(raw: Uint8Array): Uint8Array<ArrayBuffer> {
137 const int = (b: Uint8Array) => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; b = b.subarray(i); if (b[0]! & 0x80) b = cat(Uint8Array.of(0), b); return cat(Uint8Array.of(2, b.length), b); };
138 const body = cat(int(raw.subarray(0, 32)), int(raw.subarray(32)));
139 return cat(Uint8Array.of(0x30, body.length), body);
140 }
141 async function device(origin: string, rp: string) {
142 const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign"])) as CryptoKeyPair;
143 const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
144 const unb = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
145 const cose: [number, V][] = [[1, 2], [3, -7], [-1, 1], [-2, unb(jwk.x!)], [-3, unb(jwk.y!)]];
146 const id = crypto.getRandomValues(new Uint8Array(32));
147 let count = 0;
148 const cd = (type: string, challenge: string) => te.encode(JSON.stringify({ type, challenge, origin }));
149 const counter = (n: number) => Uint8Array.of(n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255);
150 return {
151 async create(challenge: string) {
152 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x45), counter(0), new Uint8Array(16), Uint8Array.of(0, id.length), id, enc(cose as V));
153 return { clientDataJSON: b64u(cd("webauthn.create", challenge)), attestationObject: b64u(enc([["fmt", "none"], ["attStmt", []], ["authData", authData]])) };
154 },
155 async get(challenge: string) {
156 const clientData = cd("webauthn.get", challenge);
157 const authData = cat(await sha(te.encode(rp)), Uint8Array.of(0x05), counter(++count));
158 const sig = rawToDer(new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pair.privateKey, cat(authData, await sha(clientData)))));
159 return { id: b64u(id), clientDataJSON: b64u(clientData), authenticatorData: b64u(authData), signature: b64u(sig) };
160 },
161 };
162 }
163
164 describe("passkey sign-in", () => {
165 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
166 const { app, url } = await forge();
167 const made = await createUser(app.db, { origin: "seed", username: "kim", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
168 if (!made.ok) throw new Error(made.error);
169 const post = (path: string, body: unknown, cookie?: string) =>
170 fetch(`${url}${path}`, {
171 method: "POST",
172 redirect: "manual",
173 headers: { "content-type": "application/json", origin: url, ...(cookie === undefined ? {} : { cookie }) },
174 body: JSON.stringify(body),
175 });
176 const enrolling = `forge_session=${createSession(app.db, made.value.id).token}`;
177 const d = await device(new URL(url).origin, new URL(url).hostname);
178 const opts = (await (await post("/settings/passkeys/options", {}, enrolling)).json()) as { challenge: string };
179 expect((await post("/settings/passkeys", { name: "Key", challenge: opts.challenge, ...(await d.create(opts.challenge)) }, enrolling)).status).toBe(200);
180
181 const { fixed, other } = planted(app, made.value.id);
182 const o = (await (await post("/signin/passkey/options", {})).json()) as { challenge: string };
183 const res = await post("/signin/passkey", { challenge: o.challenge, ...(await d.get(o.challenge)) }, `forge_session=${fixed}`);
184 expect(res.status).toBe(200);
185 expectRotated(app, res, fixed, other);
186 });
187 });
188
189 describe("parent forge (OAuth) sign-in", () => {
190 let parent: { app: App; url: string };
191 let child: { app: App; url: string };
192 let consenting = "";
193 let childUser = "";
194
195 beforeAll(async () => {
196 parent = await forge();
197 child = await forge({ parentUrl: parent.url, parentLoopback: true });
198 const up = await createUser(parent.app.db, { origin: "seed", username: "lee", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
199 if (!up.ok) throw new Error(up.error);
200 consenting = `forge_session=${createSession(parent.app.db, up.value.id).token}`;
201 const down = await createUser(child.app.db, { origin: "seed", username: "lee", email: "[email protected]", password: PASSWORD, adminIfFirst: true });
202 if (!down.ok) throw new Error(down.error);
203 childUser = down.value.id;
204 expect(linkParent(child.app.db, childUser, parent.url, up.value.id).ok).toBe(true);
205 });
206
207 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
208 const { fixed, other } = planted(child.app, childUser);
209 const start = await fetch(`${child.url}/signin/parent`, { redirect: "manual", headers: { cookie: `forge_session=${fixed}` } });
210 const to = new URL(start.headers.get("location")!);
211 const consent = await fetch(`${parent.url}/oauth/authorize`, {
212 method: "POST",
213 redirect: "manual",
214 headers: { cookie: consenting, origin: parent.url },
215 body: new URLSearchParams({ ...Object.fromEntries(to.searchParams), decision: "allow" }),
216 });
217 const back = new URL(consent.headers.get("location")!);
218 const rp = start.headers.getSetCookie().map((c) => c.split(";")[0]!).find((c) => c.startsWith("forge_rp="))!;
219 const done = await fetch(`${child.url}${back.pathname}${back.search}`, {
220 redirect: "manual",
221 headers: { cookie: `${rp}; forge_session=${fixed}` },
222 });
223 expect(done.status).toBe(303);
224 expect(done.headers.get("location")).toBe("/");
225 expectRotated(child.app, done, fixed, other);
226 });
227 });
228
229 /** A POST from the forge's own origin, carrying `cookie` when given. */
230 function poster(url: string) {
231 return (path: string, body: URLSearchParams | Record<string, unknown>, cookie?: string) =>
232 fetch(`${url}${path}`, {
233 method: "POST",
234 redirect: "manual",
235 headers: {
236 origin: url,
237 ...(body instanceof URLSearchParams ? {} : { "content-type": "application/json" }),
238 ...(cookie === undefined ? {} : { cookie: `forge_session=${cookie}` }),
239 },
240 body: body instanceof URLSearchParams ? body : JSON.stringify(body),
241 });
242 }
243
244 async function seed(app: App, username: string, adminIfFirst = false) {
245 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: PASSWORD, adminIfFirst });
246 if (!made.ok) throw new Error(made.error);
247 return made.value;
248 }
249
250 describe("password sign-in through the API", () => {
251 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
252 const { app, url } = await forge();
253 const pat = await seed(app, "api-pat", true);
254 const { fixed, other } = planted(app, pat.id);
255 const res = await poster(url)("/api/v1/sessions", { username: "api-pat", password: PASSWORD }, fixed);
256 expect(res.status).toBe(201);
257 expectRotated(app, res, fixed, other);
258 });
259 });
260
261 describe("sign-up by form", () => {
262 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
263 const { app, url } = await forge();
264 const was = await seed(app, "was-here", true);
265 const { fixed, other } = planted(app, was.id);
266 const res = await poster(url)("/signup", new URLSearchParams({ username: "finch", email: "", password: PASSWORD }), fixed);
267 expect(res.status).toBe(303);
268 expectRotated(app, res, fixed, other);
269 });
270 });
271
272 describe("sign-up by passkey", () => {
273 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
274 const { app, url } = await forge();
275 const was = await seed(app, "was-here", true);
276 const { fixed, other } = planted(app, was.id);
277 const post = poster(url);
278 const d = await keyFor(url);
279 const o = (await (await post("/signup/passkey/options", { username: "wren", email: "" })).json()) as { challenge: string };
280 const res = await post("/signup/passkey", { username: "wren", email: "", challenge: o.challenge, ...(await d.create(o.challenge)) }, fixed);
281 expect(res.status).toBe(201);
282 expectRotated(app, res, fixed, other);
283 });
284 });
285
286 describe("recovery link", () => {
287 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
288 const { app, url } = await forge();
289 const rob = await seed(app, "rob", true);
290 markVerified(app.db, rob.id, new Date().toISOString());
291 const token = issueRecovery(app.db, rob.id, Date.now())!;
292 const { fixed, other } = planted(app, rob.id);
293 const post = poster(url);
294 const d = await keyFor(url);
295 const o = (await (await post("/recover/options", { token })).json()) as { challenge: string };
296 const res = await post("/recover/passkey", { token, name: "r", challenge: o.challenge, ...(await d.create(o.challenge)) }, fixed);
297 expect(res.status).toBe(200);
298 expectRotated(app, res, fixed, other);
299 });
300 });
301
302 describe("access link", () => {
303 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
304 const { app, url } = await forge();
305 const olive = await seed(app, "olive", true);
306 const bob = await seed(app, "bob");
307 const link = await resetAccess(app, olive, "bob");
308 if (!link.ok || link.value.token === undefined) throw new Error("no access link");
309 const { fixed, other } = planted(app, bob.id);
310 const res = await poster(url)(`/signin/access/${link.value.token}`, new URLSearchParams({ password: "a-good-new-passphrase" }), fixed);
311 expect(res.status).toBe(303);
312 expectRotated(app, res, fixed, other);
313 });
314 });
315
316 describe("first admin", () => {
317 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
318 const { app, url } = await forge();
319 const was = await seed(app, "was-here");
320 const { fixed, other } = planted(app, was.id);
321 const who = { token: mintFirstAdmin(app.db)!.code, username: "ada", email: "[email protected]" };
322 const fields = await passkeyFields(url, "/first-admin/options", who, { headers: { origin: url }, device: await keyFor(url) });
323 const res = await poster(url)("/first-admin", new URLSearchParams({ ...who, ...fields }), fixed);
324 expect(res.status).toBe(303);
325 expectRotated(app, res, fixed, other);
326 });
327 });
328
329 /** A spawned forge as spawn leaves it: an org with a placeholder founder and parent.json. */
330 async function spawned() {
331 const dir = await mkdtemp(join(tmpdir(), "session-rotation-kin-"));
332 dirs.push(dir);
333 const app = createApp({ dataDir: dir, port: 0 });
334 const s = await serve(app);
335 servers.push(s);
336 const founder = await seed(app, "founder");
337 const org = createOrg(app.db, "kin", founder.id);
338 if (!org.ok) throw new Error(org.error);
339 await Bun.write(join(dir, "parent.json"), JSON.stringify({ org: "kin" }));
340 return { app, url: s.url, orgId: org.value.id };
341 }
342
343 describe("claim link", () => {
344 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
345 const { app, url, orgId } = await spawned();
346 const was = await seed(app, "was-here");
347 const { fixed, other } = planted(app, was.id);
348 const form = new URLSearchParams({ token: mintClaim(app.db, orgId), username: "kin-owner", email: "[email protected]", password: "a-long-claim-passphrase" });
349 const res = await poster(url)("/claim", form, fixed);
350 expect(res.status).toBe(303);
351 expectRotated(app, res, fixed, other);
352 });
353 });
354
355 describe("everyday account", () => {
356 test("issues a fresh id; the admin's id in this browser is refused; their other browsers stay", async () => {
357 const { app, url, orgId } = await spawned();
358 const claim = await poster(url)("/claim", new URLSearchParams({ token: mintClaim(app.db, orgId), username: "kin-owner", email: "[email protected]", password: "a-long-claim-passphrase" }));
359 expect(claim.status).toBe(303);
360 const ownerId = sessionUser(app.db, issued(claim).value);
361 if (!ownerId.ok) throw new Error("owner not signed in");
362 const { fixed, other } = planted(app, ownerId.value.id);
363 const daily = { username: "kin-me", email: "[email protected]" };
364 const key = await passkeyFields(url, "/settings/everyday/options", daily, { headers: { origin: url, cookie: `forge_session=${fixed}` }, device: await keyFor(url) });
365 const res = await poster(url)("/settings/everyday", new URLSearchParams({ ...daily, ...key }), fixed);
366 expect(res.status).toBe(303);
367 expectRotated(app, res, fixed, other);
368 });
369 });
370
371 describe("an agent's start taken with a new account", () => {
372 test("issues a fresh id; the one sent in is refused; other browsers stay", async () => {
373 const { app, url } = await spawned();
374 const agent = await seed(app, "agent-start");
375 const token = "claim_session-rotation-start";
376 recordStart(app.db, agent.id, token, "session-rotation");
377 const was = await seed(app, "was-here");
378 const { fixed, other } = planted(app, was.id);
379 const res = await poster(url)(`/claim/start/${token}/account`, new URLSearchParams({ username: "taker", email: "[email protected]", password: "a-long-start-passphrase" }), fixed);
380 expect(res.status).toBe(303);
381 expectRotated(app, res, fixed, other);
382 });
383 });
384
385 /**
386 * Every place that makes a session, and why it may skip `rotateSession`. A
387 * door that signs a browser in and calls `createSession` itself keeps the id
388 * the browser sent alive; it fails here by file and line until it rotates.
389 */
390 const MAKES_SESSIONS: Record<string, string> = {
391 "src/core/sessions.ts": "defines it",
392 "src/auth/session_rotate.ts": "the rotation itself",
393 "src/tui/screens/api.ts": "a session for one in-process request from the terminal; no browser holds it",
394 "src/keeper/wire.ts": "a session for the keeper's own probe under load; no browser holds it",
395 "src/spawn/preview-seed.ts": "sessions for the preview's own in-process looks; no browser holds them",
396 };
397
398 describe("sign-in doors", () => {
399 test("no file but those named calls createSession; every browser door rotates", async () => {
400 const stray: string[] = [];
401 for await (const file of new Bun.Glob("src/**/*.ts").scan(".")) {
402 if (file in MAKES_SESSIONS) continue;
403 const text = await Bun.file(file).text();
404 for (const m of text.matchAll(/\bcreateSession\(/g)) stray.push(`${file}:${text.slice(0, m.index).split("\n").length}`);
405 }
406 expect(stray).toEqual([]);
407 });
408 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs