Merge auth/platform-session into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 9142e90, 632d6d2 · Browse files · 12 files·+951 added−47 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+951 added−47 removed
- tests:+621 added−34 removed
- other:+330 added−13 removed
Provenance
- Commit
f559a7b- Tree
43d9a1f- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
9142e90- Parent 2
632d6d2
12 files changed+951 added−47 removed
modified:apps/platform/src/auth/pages.ts+58 added
30 unmodified lines31 resetVerify: "/oauth/reset/verify",32 signUpVerify: "/oauth/signup/verify",33 } as const;34 35+// The platform's own session: continue as the person it names, switch away from them, or end it.36+export const SESSION_PATHS = {37+ continue: "/authorize/continue",38+ signOut: "/oauth/signout",39+ switch: "/oauth/switch",40+} as const;41+42 export const GOOGLE_PATHS = {43 callback: "/oauth/google/callback",44 handle: "/oauth/google/handle",45 link: "/oauth/google/link",67 unmodified lines113 .button svg{flex:none;width:18px;height:18px}114 button.link{display:block;width:auto;min-height:0;margin:16px auto 0;padding:2px 4px;color:var(--muted);background-color:transparent;border:0;font-size:.875rem;line-height:1.3rem;font-weight:400;text-decoration:none;text-underline-offset:.2em}115 button.link:hover{color:var(--ink);opacity:1;text-decoration:underline}116 .submit{margin-top:24px}117+.who{display:flex;align-items:center;gap:12px;padding:12px;border:1px solid var(--rule);border-radius:2px;overflow-wrap:anywhere}118+.who .mark{flex:none;display:flex;align-items:center;justify-content:center;width:36px;height:36px;border-radius:50%;background-color:var(--surface);font-weight:600;text-transform:uppercase}119+.who .name{display:block;font-weight:600}120 .or{display:flex;align-items:center;gap:12px;margin:20px 0}121 .or .line{flex:1;height:1px;background-color:var(--rule)}122 .aside{margin:24px 0 0;text-align:center}123 pre{margin:8px 0 12px;padding:8px 12px;overflow-x:auto;background-color:var(--surface);border:1px solid var(--rule)}153 unmodified lines277 after: `New here? <a href="${withRequest("/signup", form)}">Create an account</a>`,278 }279 );280 281+// A name's first letter as a reader sees it, an accent or an emoji whole.282+const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });283+284+export interface SignedInAs {285+ readonly displayName?: string | undefined;286+ readonly handle: string;287+}288+289+/**290+ * Someone already signed in here: one click gives this client its grant, and a291+ * client that is not ours still says who asks and what it may do first.292+ */293+export const continuePage = (294+ asker: Asker,295+ form: PendingForm,296+ who: SignedInAs,297+ message?: string298+) => {299+ const handle = `@${escapeHtml(who.handle)}`;300+301+ const named =302+ who.displayName === undefined303+ ? `<span class="name">${handle}</span>`304+ : `<span class="name">${escapeHtml(who.displayName)}</span><span class="small muted">${handle}</span>`;305+306+ const [first] = Array.from(307+ graphemes.segment(who.displayName ?? who.handle),308+ ({ segment }) => segment309+ );310+311+ return page(312+ "Sign in",313+ `<h1>Sign in to ${escapeHtml(Brand.name)}</h1>314+${askerParagraphs(asker, "who and what")}315+${messageParagraph(message)}316+<section class="who" aria-label="Signed in as"><span class="mark" aria-hidden="true">${escapeHtml(first ?? "")}</span><div>${named}</div></section>317+<form method="post" action="${SESSION_PATHS.continue}">318+${hiddenFields(form)}319+<div class="submit"><button type="submit">Continue as ${handle}</button></div>320+</form>`,321+ "form",322+ {323+ ...homeOf(asker),324+ after: `Not you? <a href="${withRequest(SESSION_PATHS.switch, form)}">Use another account</a>`,325+ }326+ );327+};328+329 export interface ProfileValues {330 readonly displayName?: string;331 readonly handle?: string;332 }160 unmodified linesadded:apps/platform/src/auth/platform-session.ts+110 added
1+// The platform's own sign-in, kept between grants: a person who signed in once2+// for any client is asked only to continue for the next, never for their3+// password again. It names an account and the password it was signed in4+// under, so a reset or a change of password ends every session at once.5+import { Handle } from "@repo/protocol/ids";6+import { Duration, Effect, Option, Schema } from "effect";7+import type { Redacted } from "effect";8+import type { HttpServerRequest } from "effect/http";9+import { HttpServerResponse } from "effect/http";10+11+import { Accounts } from "./accounts.ts";12+import type { Account } from "./accounts.ts";13+import { sealing } from "./state.ts";14+15+export const SESSION_COOKIE = "__Host-platform-session";16+17+export const SESSION_LIFETIME = Duration.days(30);18+19+// `Lax`, not `Strict`: a client sends the person here by a top-level link, and the cookie must come with it.20+export const sessionCookie = {21+ httpOnly: true,22+ path: "/",23+ sameSite: "lax",24+ secure: true,25+} as const;26+27+const PlatformSession = Schema.Struct({ handle: Handle, stamp: Schema.String });28+29+const sessions = sealing("platform-session", PlatformSession, SESSION_LIFETIME);30+31+const encodeStamp = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);32+33+// A digest of the password hash, never the hash: the cookie's payload is signed, not hidden.34+const stampOf = (account: Account) =>35+ Effect.promise(() =>36+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(account.hash))37+ ).pipe(38+ Effect.flatMap((digest) => encodeStamp(new Uint8Array(digest))),39+ Effect.map((stamp) => stamp.slice(0, 22)),40+ Effect.orDie41+ );42+43+/**44+ * The account a request's session names, while the account stands and its45+ * password is the one it was signed in under. A session that does not open,46+ * has expired or no longer fits reads as none, the same as no cookie, so a47+ * forged one learns nothing.48+ */49+export const sessionAccount = (50+ key: Redacted.Redacted,51+ request: HttpServerRequest.HttpServerRequest52+) =>53+ Effect.gen(function* () {54+ const sealed = request.cookies[SESSION_COOKIE];55+56+ if (sealed === undefined || sealed === "") {57+ return Option.none<Account>();58+ }59+60+ const opened = yield* sessions.open(key, sealed).pipe(Effect.option);61+62+ if (Option.isNone(opened)) {63+ return Option.none<Account>();64+ }65+66+ const accounts = yield* Accounts;67+68+ const account = yield* accounts.find(opened.value.handle);69+70+ if (Option.isNone(account)) {71+ return Option.none<Account>();72+ }73+74+ const stamp = yield* stampOf(account.value);75+76+ return stamp === opened.value.stamp ? account : Option.none<Account>();77+ });78+79+export const hasSessionCookie = (80+ request: HttpServerRequest.HttpServerRequest81+) => request.cookies[SESSION_COOKIE] !== undefined;82+83+export const withSession =84+ (key: Redacted.Redacted, account: Account) =>85+ (response: HttpServerResponse.HttpServerResponse) =>86+ Effect.gen(function* () {87+ const sealed = yield* sessions.seal(key, {88+ handle: account.handle,89+ stamp: yield* stampOf(account),90+ });91+92+ return yield* response.pipe(93+ HttpServerResponse.setCookie(SESSION_COOKIE, sealed, {94+ ...sessionCookie,95+ maxAge: SESSION_LIFETIME,96+ }),97+ Effect.orDie98+ );99+ });100+101+export const withoutSession = (102+ response: HttpServerResponse.HttpServerResponse103+) =>104+ response.pipe(105+ HttpServerResponse.setCookie(SESSION_COOKIE, "", {106+ ...sessionCookie,107+ maxAge: 0,108+ }),109+ Effect.orDie110+ );modified:apps/platform/src/auth/sign-in.ts+128 added-6 removed
37 unmodified lines38 import {39 ACCOUNT_PATHS,40 addEmailPage,41 codePage,42+ continuePage,43 problemPage,44 resetPage,45+ SESSION_PATHS,46 signInPage,47 signUpPage,48 } from "./pages.ts";49 import type { Asker, CodeForm, PendingForm, SignUpValues } from "./pages.ts";3 unmodified lines53 PasswordPolicy,54 verifyPassword,55 } from "./password.ts";56 import {57+ hasSessionCookie,58+ sessionAccount,59+ withoutSession,60+ withSession,61+} from "./platform-session.ts";62+import {63 AuthRequest,64 openState,65 sealing,66 sealState,50 unmodified lines117 "/authorize",118 "/signup",119 CLI_CLIENT_PATH,120 ...Object.values(ACCOUNT_PATHS),121+ ...Object.values(SESSION_PATHS),122 ] as const;123 124 // A handle is an owner, the first segment of a project's address, so it may not be a word the web serves pages at.125 const RESERVED_HANDLES: ReadonlySet<string> = new Set([31 unmodified lines157 handleTakenSince:158 "Someone took that handle while you confirmed your email. Choose another.",159 mailFailed: "We could not send the mail just now. Try again in a minute.",160 passwordLength: "A password is 12 to 256 characters.",161+ signedOut: "You were signed out here. Sign in again.",162 tooManyCodes:163 "Too many codes tried for that address. Wait a minute, then try again.",164 tooManyMails:165 "Too many mails to that address, or from here. Wait a minute, then try again.",216 unmodified lines382 : Effect.fail(startAgain);383 384 // The grant's user is the handle's key, so a grant is one account's in any case.385 // Every account it is given for has a proven email, or the person just proved376-// who they are to Google, whose address is then the account's.386+// who they are to Google, whose address is then the account's. Each grant387+// keeps the person signed in here, under the password the account has now388+// (read again, since a reset has just changed it), so the next asks only to389+// continue.390 export const completed = (handle: Handle, request: AuthRequest) =>391 Effect.gen(function* () {392 const api = yield* oauthApi;393+ const { cookieKey } = yield* SignInKeys;394+ const account = yield* (yield* Accounts).find(handle);395 396 const { redirectTo } = yield* provider(() =>397 api.completeAuthorization({398 metadata: {},14 unmodified lines413 HttpServerResponse.setCookie(CSRF_COOKIE, "", {414 ...csrfCookie,415 maxAge: 0,416 }),402- Effect.orDie417+ Effect.orDie,418+ Effect.flatMap((response) =>419+ Option.match(account, {420+ onNone: () => Effect.succeed(response),421+ onSome: (found) => withSession(cookieKey, found)(response),422+ })423+ )424 );425 });426 427 const offeredSignIn = (36 unmodified lines464 465 return yield* withCsrfCookie(csrf)(page);466 });467 468+const continuePageFor = (request: AuthRequest, account: Account) =>469+ Effect.gen(function* () {470+ const { cookieKey } = yield* SignInKeys;471+472+ const csrf = yield* freshCsrf;473+474+ const sealed = yield* sealState(cookieKey, { csrf, request });475+476+ const asker = yield* askerOf(request);477+478+ return yield* withCsrfCookie(csrf)(479+ htmlPage(480+ continuePage(481+ asker,482+ { csrf, request: sealed },483+ { displayName: account.displayName, handle: account.handle }484+ ),485+ 200,486+ request.redirectUri487+ )488+ );489+ });490+491+// A session that no longer fits is dropped as the page that replaces it is shown.492+const signInOrDropped = (493+ request: HttpServerRequest.HttpServerRequest,494+ pending: AuthRequest,495+ message?: string496+) =>497+ Effect.gen(function* () {498+ const page = yield* signInPageFor(pending, 200, message);499+500+ return hasSessionCookie(request) ? yield* withoutSession(page) : page;501+ });502+503+// Someone signed in here already is asked only to continue; anyone else, to sign in.504 const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>505 Effect.gen(function* () {506 const api = yield* oauthApi;507+ const { cookieKey } = yield* SignInKeys;508 509 const web = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);510 511 const parsed = yield* provider(() => api.parseAuthRequest(web));512 455- return yield* signInPageFor(parsed, 200);513+ const account = yield* sessionAccount(cookieKey, request);514+515+ return yield* Option.match(account, {516+ onNone: () => signInOrDropped(request, parsed),517+ onSome: (signedIn) => continuePageFor(parsed, signedIn),518+ });519 });520 521 // Mailing522 229 unmodified lines752 });753 754 // A signed-in account with no email adds one before its grant.755 export const signedInWithEmail = (account: Account, request: AuthRequest) =>756+ Effect.gen(function* () {693- account.email === undefined694- ? addEmailPageFor(account.handle, request, 200)695- : completed(account.handle, request);757+ return account.email === undefined758+ ? yield* addEmailPageFor(account.handle, request, 200)759+ : yield* completed(account.handle, request);760+ });761 762 const signIn = (request: HttpServerRequest.HttpServerRequest) =>763 byPassword(request, (account, pending) =>764 signedInWithEmail(account, pending.request)765 );766 767+const PostedContinue = Schema.Struct({768+ csrf: Schema.String,769+ request: Schema.String,770+});771+772+// No password is asked, so the session is read again at the click: it must still fit, and the email rule still holds.773+const continueAs = (request: HttpServerRequest.HttpServerRequest) =>774+ Effect.gen(function* () {775+ const { cookieKey } = yield* SignInKeys;776+777+ const form = yield* HttpServerRequest.schemaBodyUrlParams(778+ PostedContinue779+ ).pipe(Effect.mapError(() => startAgain));780+781+ const pending = yield* openState(cookieKey, form.request);782+783+ yield* sameCsrf(request, form.csrf, pending.csrf);784+785+ const account = yield* sessionAccount(cookieKey, request);786+787+ return yield* Option.match(account, {788+ onNone: () => signInOrDropped(request, pending.request, Says.signedOut),789+ onSome: (signedIn) => signedInWithEmail(signedIn, pending.request),790+ });791+ });792+793+// Leaves the session and signs in afresh for the same client.794+const switchAccount = Effect.gen(function* () {795+ const { cookieKey } = yield* SignInKeys;796+797+ const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(798+ Schema.Struct({ request: Schema.String })799+ ).pipe(Effect.mapError(() => startAgain));800+801+ const pending = yield* openState(cookieKey, sealed);802+803+ return yield* signInPageFor(pending.request, 200).pipe(804+ Effect.flatMap(withoutSession)805+ );806+});807+808+// Always to the web's home, never to an address the request names.809+const signOut = Effect.gen(function* () {810+ const { webUrl } = yield* SignInHome;811+812+ return yield* withoutSession(813+ HttpServerResponse.redirect(814+ Option.getOrElse(webUrl, () => "/"),815+ { headers: { "cache-control": "no-store" }, status: 302 }816+ )817+ );818+});819+820 const addEmailCode = (request: AuthRequest, email: Email): CodeForm => ({821 action: ACCOUNT_PATHS.addEmailVerify,822 intro: codeSentTo(email),823 newPassword: false,666 unmodified lines1490 );1491 1492 yield* add("GET", "/authorize", showSignIn);1493 yield* add("POST", "/authorize", signIn);1494+ yield* add("POST", SESSION_PATHS.continue, continueAs);1495+ yield* add("GET", SESSION_PATHS.switch, () => switchAccount);1496+ yield* add("GET", SESSION_PATHS.signOut, () => signOut);1497+ yield* add("POST", SESSION_PATHS.signOut, () => signOut);1498 yield* add("GET", "/signup", () => showSignUp);1499 yield* add("POST", "/signup", signUp);1500 yield* add("POST", ACCOUNT_PATHS.signUpVerify, signUpVerified);1501 yield* add("POST", ACCOUNT_PATHS.addEmail, addEmail);11 unmodified linesmodified:apps/platform/src/auth/state.ts+6 added-2 removed
53 unmodified lines545556575858596061626364656611 unmodified lines7879808178828384858652 unmodified lines53 unmodified lines ) );
// The signature covers `purpose` too: a schema ignores extra keys, so a value sealed for another purpose must not open.export const sealing = <A, I>(purpose: string, schema: Schema.Codec<A, I>) => {export const sealing = <A, I>( purpose: string, schema: Schema.Codec<A, I>, lifetime: Duration.Duration = SIGN_IN_LIFETIME) => { const signed = (payload: string) => utf8(`${purpose}.${payload}`);
const Payload = Schema.StringFromBase64Url.pipe( Schema.decodeTo(11 unmodified lines Effect.gen(function* () { const now = yield* Clock.currentTimeMillis;
const payload = yield* encodePayload({ expiresAt: now + Duration.toMillis(SIGN_IN_LIFETIME), expiresAt: now + Duration.toMillis(lifetime), value, }).pipe(Effect.orDie);
const hmac = yield* hmacKey(key);52 unmodified linesmodified:apps/platform/test/google.fixtures.ts+7 added-1 removed
345 unmodified lines346 const cookies = [...jar].flatMap(([name, kept]) =>347 from === "same-site" || !kept.strict ? [`${name}=${kept.value}`] : []348 );349 350+ // A cookie the request names itself is kept beside the jar's.351+ const named = headers.get("cookie");352+353 if (cookies.length > 0) {351- headers.set("cookie", cookies.join("; "));354+ headers.set(355+ "cookie",356+ [...(named === null ? [] : [named]), ...cookies].join("; ")357+ );358 }359 360 const response = yield* Effect.promise(() =>361 handler(new Request(request, { headers, redirect: "manual" }))107 unmodified linesmodified:apps/platform/test/google.test.ts+5 added
807 unmodified lines808 );809 810 yield* chooseHandle(world, first, "Carol");811 812+ // Signed out, or the platform's session would only ask to continue.813+ yield* visit(world, "/oauth/signout");814+815 const again = yield* backFromGoogle(816 world,817 yield* continueWithGoogle(world),818 { sub: "1042" }404 unmodified lines1223 Option.some(Handle.make("alice")),1224 Option.some(googleEmailOf("5150")),1225 ]);1226 1227+ yield* visit(world, "/oauth/signout");1228+1229 const later = yield* backFromGoogle(1230 world,1231 yield* continueWithGoogle(world),1232 { sub: "5150" }95 unmodified linesmodified:apps/platform/test/oauth.test.ts+517 added-2 removed
2 unmodified lines3 import { Handle } from "@repo/protocol/ids";4 import { Person } from "@repo/protocol/principal";5 import { untouchable } from "@repo/testkit/untouchable";6 import { Effect, Option, Redacted, Schema } from "effect";7+import { HttpServerRequest, HttpServerResponse } from "effect/http";8 import { TestClock } from "effect/testing";9 10 import { OAuthSessions } from "../src/adapters/sessions-oauth.ts";10-import { Email } from "../src/auth/accounts.ts";11+import { Accounts, Email } from "../src/auth/accounts.ts";12+import type { Account } from "../src/auth/accounts.ts";13+import { AccountsMemory } from "../src/auth/accounts/memory.ts";14 import { SignInAttempts } from "../src/auth/attempts.ts";15 import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";16 import { cliClientMetadata } from "../src/auth/cli-client.ts";17 import { codeMatches, codeTag, deadTag, freshCode } from "../src/auth/codes.ts";18 import type { CodePurpose } from "../src/auth/codes.ts";16-import { ACCOUNT_PATHS } from "../src/auth/pages.ts";19+import { ACCOUNT_PATHS, SESSION_PATHS } from "../src/auth/pages.ts";20 import {21 hashPassword,22 hashPasswordWith,23 PasswordHash,24 verifyPassword,25 } from "../src/auth/password.ts";26+import { sessionAccount, withSession } from "../src/auth/platform-session.ts";27 import { tokenReader } from "../src/auth/provider.ts";28 import { openState, sealState, SignInFailed } from "../src/auth/state.ts";29 import type { PendingSignIn } from "../src/auth/state.ts";30 import worker from "../src/worker.ts";1490 unmodified lines1521 ).toBeFalsy();1522 })1523 );1524 });1525+1526+const SESSION = "__Host-platform-session";1527+1528+const webHome = fakeEnv().PUBLIC_WEB_URL;1529+1530+const sessionLine = (response: Response) =>1531+ Option.fromNullishOr(1532+ response.headers1533+ .getSetCookie()1534+ .find((line) => line.startsWith(`${SESSION}=`))1535+ );1536+1537+const sessionIn = (response: Response) =>1538+ Effect.fromOption(1539+ sessionLine(response).pipe(1540+ Option.flatMap((line) =>1541+ Option.fromNullishOr(1542+ /^[^=]+=(?<value>[^;]*)/u.exec(line)?.groups?.value1543+ )1544+ ),1545+ Option.filter((value) => value !== "")1546+ )1547+ ).pipe(Effect.orDie);1548+1549+// A line that ends the session: an empty value, kept for no time at all.1550+const endsSession = (response: Response) =>1551+ Option.exists(1552+ sessionLine(response),1553+ (line) =>1554+ line.startsWith(`${SESSION}=;`) &&1555+ line.toLowerCase().includes("max-age=0")1556+ );1557+1558+const withCookies = (1559+ request: Request,1560+ cookies: Readonly<Record<string, string>>1561+) => {1562+ const headers = new Headers(request.headers);1563+1564+ headers.set(1565+ "cookie",1566+ Object.entries(cookies)1567+ .map(([name, value]) => `${name}=${value}`)1568+ .join("; ")1569+ );1570+1571+ return new Request(request, { headers });1572+};1573+1574+const openSignedIn = (world: World, session: string, url = authorizeUrl()) =>1575+ world1576+ .fetch(withCookies(new Request(url), { [SESSION]: session }))1577+ .pipe(Effect.flatMap(read));1578+1579+const continueFrom = (1580+ world: World,1581+ page: Page,1582+ session: string,1583+ csrf?: string1584+) =>1585+ Effect.gen(function* () {1586+ const form = yield* formIn(page);1587+1588+ return yield* world.fetch(1589+ withCookies(1590+ post(1591+ SESSION_PATHS.continue,1592+ { csrf: csrf ?? form.csrf, request: form.request },1593+ form.cookie1594+ ),1595+ { "__Host-sign-in": form.cookie, [SESSION]: session }1596+ )1597+ );1598+ });1599+1600+const signedInSession = (world: World) =>1601+ Effect.gen(function* () {1602+ yield* signUp(world, "alice", alicePassword);1603+1604+ return yield* signIn(world, "alice", alicePassword).pipe(1605+ Effect.flatMap(sessionIn)1606+ );1607+ });1608+1609+// A session sealed as the platform would, for an account a test names.1610+const sessionFor = (account: Account) =>1611+ withSession(1612+ cookieKey,1613+ account1614+ )(HttpServerResponse.empty()).pipe(1615+ Effect.map(HttpServerResponse.toWeb),1616+ Effect.flatMap(sessionIn)1617+ );1618+1619+const asksToContinue = (page: Page) => ({1620+ continues: page.html.includes("Continue as @alice"),1621+ password: page.html.includes('name="password"'),1622+ status: page.response.status,1623+});1624+1625+describe("the platform's own session", () => {1626+ it.live(1627+ "keeps the person signed in here for thirty days after a grant, out of reach of scripts and other sites' posts",1628+ () =>1629+ Effect.gen(function* () {1630+ const world = yield* signInWorld();1631+1632+ yield* signUp(world, "alice", alicePassword);1633+1634+ const signedIn = yield* signIn(world, "alice", alicePassword);1635+1636+ const attributes = Option.map(sessionLine(signedIn), (line) =>1637+ line1638+ .split(";")1639+ .slice(1)1640+ .map((part) => part.trim().toLowerCase())1641+ .toSorted()1642+ );1643+1644+ expect(Option.isSome(codeOf(signedIn))).toBeTruthy();1645+ expect(attributes).toStrictEqual(1646+ Option.some([1647+ "httponly",1648+ "max-age=2592000",1649+ "path=/",1650+ "samesite=lax",1651+ "secure",1652+ ])1653+ );1654+ })1655+ );1656+1657+ it.live(1658+ "asks only to continue on the next sign-in, and gives the code to the same person",1659+ () =>1660+ Effect.gen(function* () {1661+ const world = yield* signInWorld();1662+1663+ const session = yield* signedInSession(world);1664+1665+ const page = yield* openSignedIn(1666+ world,1667+ session,1668+ authorizeUrl("state-2")1669+ );1670+1671+ const code = yield* continueFrom(world, page, session).pipe(1672+ Effect.flatMap(codeIn)1673+ );1674+1675+ const response = yield* world.fetch(tokenRequest(code));1676+1677+ const { access_token } = yield* Effect.promise(() =>1678+ response.json()1679+ ).pipe(1680+ Effect.flatMap(Schema.decodeUnknownEffect(TokenResponse)),1681+ Effect.orDie1682+ );1683+1684+ expect(asksToContinue(page)).toStrictEqual({1685+ continues: true,1686+ password: false,1687+ status: 200,1688+ });1689+ expect(1690+ yield* OAuthSessions(tokenReader(world.store)).verify(access_token)1691+ ).toStrictEqual(1692+ Option.some(Person.make({ handle: Handle.make("alice") }))1693+ );1694+ })1695+ );1696+1697+ it.live(1698+ "shows a client that is not ours who asks and what it may do, then the button",1699+ () =>1700+ Effect.gen(function* () {1701+ const world = yield* signInWorld();1702+1703+ const session = yield* signedInSession(world);1704+1705+ const url = authorizeUrl();1706+1707+ url.searchParams.set("client_id", "https://other.test/oauth/cli");1708+1709+ const page = yield* openSignedIn(world, session, url);1710+1711+ expect({1712+ ...asksToContinue(page),1713+ asks: page.html.includes("wants to act as you."),1714+ host: page.html.includes("Access goes to <strong>127.0.0.1"),1715+ lists: page.html.includes("<summary>What it can do</summary>"),1716+ }).toStrictEqual({1717+ asks: true,1718+ continues: true,1719+ host: true,1720+ lists: true,1721+ password: false,1722+ status: 200,1723+ });1724+ })1725+ );1726+1727+ it.live(1728+ "reads a changed session as none, the same page as no session, and drops it",1729+ () =>1730+ Effect.gen(function* () {1731+ const world = yield* signInWorld();1732+1733+ const session = yield* signedInSession(world);1734+1735+ const page = yield* openSignedIn(world, tampered(session));1736+1737+ expect({1738+ ...asksToContinue(page),1739+ dropped: endsSession(page.response),1740+ }).toStrictEqual({1741+ continues: false,1742+ dropped: true,1743+ password: true,1744+ status: 200,1745+ });1746+ })1747+ );1748+1749+ it.live(1750+ "ends with a reset of the password, wherever it was kept, and a new one starts",1751+ () =>1752+ Effect.gen(function* () {1753+ const world = yield* signInWorld();1754+1755+ const session = yield* signedInSession(world);1756+1757+ const started = yield* startReset(world, emailOf("alice"));1758+1759+ const code = yield* Effect.fromOption(1760+ yield* codeMailedTo(world, emailOf("alice"))1761+ ).pipe(Effect.orDie);1762+1763+ const reset = yield* enterCode(1764+ world,1765+ started,1766+ ACCOUNT_PATHS.resetVerify,1767+ code,1768+ { password: "a brand new password" }1769+ );1770+1771+ const old = yield* openSignedIn(world, session);1772+1773+ const fresh = yield* openSignedIn(world, yield* sessionIn(reset));1774+1775+ expect([1776+ asksToContinue(old),1777+ endsSession(old.response),1778+ asksToContinue(fresh).continues,1779+ ]).toStrictEqual([1780+ { continues: false, password: true, status: 200 },1781+ true,1782+ true,1783+ ]);1784+ })1785+ );1786+1787+ it.live(1788+ "names nobody for an account that is not there, though its session is genuine",1789+ () =>1790+ Effect.gen(function* () {1791+ const world = yield* signInWorld();1792+1793+ const session = yield* sessionFor({1794+ email: Email.make("ghost@mail.example"),1795+ handle: Handle.make("ghost"),1796+ hash: yield* hashPassword(pepper, password),1797+ });1798+1799+ const page = yield* openSignedIn(world, session);1800+1801+ expect({1802+ ...asksToContinue(page),1803+ dropped: endsSession(page.response),1804+ }).toStrictEqual({1805+ continues: false,1806+ dropped: true,1807+ password: true,1808+ status: 200,1809+ });1810+ })1811+ );1812+1813+ it.live("refuses a continue with another form's CSRF token, or none", () =>1814+ Effect.gen(function* () {1815+ const world = yield* signInWorld();1816+1817+ const session = yield* signedInSession(world);1818+1819+ const page = yield* openSignedIn(world, session);1820+1821+ const wrong = yield* continueFrom(world, page, session, "another-token");1822+1823+ const form = yield* formIn(page);1824+1825+ const without = yield* world.fetch(1826+ withCookies(1827+ post(1828+ SESSION_PATHS.continue,1829+ { csrf: form.csrf, request: form.request },1830+ form.cookie1831+ ),1832+ { [SESSION]: session }1833+ )1834+ );1835+1836+ expect([1837+ wrong.status,1838+ Option.isNone(codeOf(wrong)),1839+ without.status,1840+ Option.isNone(codeOf(without)),1841+ ]).toStrictEqual([400, true, 400, true]);1842+ })1843+ );1844+1845+ it.live(1846+ "asks to sign in again when the session ended between the page and the click",1847+ () =>1848+ Effect.gen(function* () {1849+ const world = yield* signInWorld();1850+1851+ const session = yield* signedInSession(world);1852+1853+ const page = yield* openSignedIn(world, session);1854+1855+ const clicked = yield* continueFrom(1856+ world,1857+ page,1858+ tampered(session)1859+ ).pipe(Effect.flatMap(read));1860+1861+ expect({1862+ ...asksToContinue(clicked),1863+ code: Option.isSome(codeOf(clicked.response)),1864+ dropped: endsSession(clicked.response),1865+ says: clicked.html.includes("You were signed out here."),1866+ }).toStrictEqual({1867+ code: false,1868+ continues: false,1869+ dropped: true,1870+ password: true,1871+ says: true,1872+ status: 200,1873+ });1874+ })1875+ );1876+1877+ it.live(1878+ "lets the person use another account: the session is dropped and the same request asks to sign in",1879+ () =>1880+ Effect.gen(function* () {1881+ const world = yield* signInWorld();1882+1883+ const session = yield* signedInSession(world);1884+1885+ const page = yield* openSignedIn(1886+ world,1887+ session,1888+ authorizeUrl("state-9")1889+ );1890+1891+ const form = yield* formIn(page);1892+1893+ const switched = yield* world1894+ .fetch(1895+ withCookies(1896+ new Request(1897+ new URL(1898+ `${SESSION_PATHS.switch}?request=${encodeURIComponent(form.request)}`,1899+ origin1900+ )1901+ ),1902+ { [SESSION]: session }1903+ )1904+ )1905+ .pipe(Effect.flatMap(read));1906+1907+ const again = yield* formIn(switched);1908+1909+ const signedIn = yield* world.fetch(1910+ post(1911+ "/authorize",1912+ {1913+ csrf: again.csrf,1914+ login: "alice",1915+ password: alicePassword,1916+ request: again.request,1917+ },1918+ again.cookie1919+ )1920+ );1921+1922+ expect({1923+ ...asksToContinue(switched),1924+ dropped: endsSession(switched.response),1925+ state: Option.map(1926+ Option.fromNullishOr(signedIn.headers.get("location")),1927+ (location) => new URL(location).searchParams.get("state")1928+ ),1929+ }).toStrictEqual({1930+ continues: false,1931+ dropped: true,1932+ password: true,1933+ state: Option.some("state-9"),1934+ status: 200,1935+ });1936+ })1937+ );1938+1939+ it.live(1940+ "signs out to the web's home alone, whatever address the request names",1941+ () =>1942+ Effect.gen(function* () {1943+ const world = yield* signInWorld();1944+1945+ const session = yield* signedInSession(world);1946+1947+ const answers = yield* Effect.forEach(["GET", "POST"], (method) =>1948+ world.fetch(1949+ withCookies(1950+ new Request(1951+ new URL(1952+ `${SESSION_PATHS.signOut}?return=https://elsewhere.example/&redirect_uri=https://elsewhere.example/`,1953+ origin1954+ ),1955+ { method, redirect: "manual" }1956+ ),1957+ { [SESSION]: session }1958+ )1959+ )1960+ );1961+1962+ expect(1963+ answers.map((response) => [1964+ response.status,1965+ response.headers.get("location"),1966+ endsSession(response),1967+ ])1968+ ).toStrictEqual([1969+ [302, webHome, true],1970+ [302, webHome, true],1971+ ]);1972+ })1973+ );1974+1975+ it.live(1976+ "asks an account with no email for one before it continues, and gives no code",1977+ () =>1978+ Effect.gen(function* () {1979+ const world = yield* signInWorld();1980+1981+ yield* legacyAccount(world);1982+1983+ const account = yield* Effect.fromOption(1984+ yield* world.accounts.find(Handle.make("alice"))1985+ ).pipe(Effect.orDie);1986+1987+ const session = yield* sessionFor(account);1988+1989+ const page = yield* openSignedIn(world, session);1990+1991+ const clicked = yield* continueFrom(world, page, session).pipe(1992+ Effect.flatMap(read)1993+ );1994+1995+ expect([1996+ asksToContinue(page).continues,1997+ clicked.html.includes("Add your email"),1998+ Option.isNone(codeOf(clicked.response)),1999+ ]).toStrictEqual([true, true, true]);2000+ })2001+ );2002+});2003+2004+describe("a session's lifetime", () => {2005+ it.effect("names its account for thirty days, and nobody after", () =>2006+ Effect.gen(function* () {2007+ const accounts = yield* Accounts;2008+2009+ const account = {2010+ email: Email.make("alice@mail.example"),2011+ handle: Handle.make("alice"),2012+ hash: yield* hashPasswordWith(1000)(pepper, password),2013+ };2014+2015+ yield* accounts.create(account);2016+2017+ const session = yield* sessionFor(account);2018+2019+ const request = HttpServerRequest.fromWeb(2020+ new Request(origin, { headers: { cookie: `${SESSION}=${session}` } })2021+ );2022+2023+ const opened = () =>2024+ Effect.map(sessionAccount(cookieKey, request), Option.isSome);2025+2026+ yield* TestClock.adjust("29 days");2027+2028+ const before = yield* opened();2029+2030+ yield* TestClock.adjust("1 day");2031+2032+ expect([before, yield* opened()]).toStrictEqual([true, false]);2033+ }).pipe(Effect.provide(AccountsMemory.layer))2034+ );2035+});modified:apps/platform/test/pages.test.ts+62 added
8 unmodified lines9 import {10 ACCOUNT_PATHS,11 addEmailPage,12 codePage,13+ continuePage,14 problemPage,15 profilePage,16 resetPage,17+ SESSION_PATHS,18 signInPage,19 signUpPage,20 } from "../src/auth/pages.ts";21 import type { Asker, PendingForm } from "../src/auth/pages.ts";84 unmodified lines106 "/authorize?x=1",107 "alice@mail.example",108 "Another account already uses that email. Add a different one."109 ),110+ "continuing as someone signed in": continuePage(claude, form, {111+ displayName: "Alice Example",112+ handle: "alice",113+ }),114 "entering a code": codePage(115 claude,116 form,117 {640 unmodified lines758 signUpPage(local, form, { google: false }, "/authorize", {})759 ).not.toContain("Continue with Google");760 });761 });762+763+describe("the page that asks only to continue", () => {764+ const alice = { displayName: "Alice Example", handle: "alice" };765+766+ it("names who is signed in and offers one button, asking for no password", () => {767+ const html = continuePage(ourWeb, form, alice);768+769+ expect({770+ button: html.includes(">Continue as @alice</button>"),771+ consent: html.includes('class="consent"'),772+ named: html.includes("Alice Example"),773+ password: html.includes('name="password"'),774+ posts: html.includes(`action="${SESSION_PATHS.continue}"`),775+ switches: html.includes(776+ `href="${SESSION_PATHS.switch}?request=sealed-request">Use another account</a>`777+ ),778+ }).toStrictEqual({779+ button: true,780+ consent: false,781+ named: true,782+ password: false,783+ posts: true,784+ switches: true,785+ });786+ });787+788+ it("gives the CLI its one line, and a client that is not ours its consent first", () => {789+ const cli = continuePage(ourCli, form, alice);790+ const other = continuePage(claude, form, alice);791+792+ expect([793+ cli.includes("This finishes signing in the CLI"),794+ cli.includes("What it can do"),795+ other.includes("wants to act as you"),796+ other.includes("<summary>What it can do</summary>"),797+ other.indexOf("wants to act as you") < other.indexOf("Continue as"),798+ ]).toStrictEqual([true, false, true, true, true]);799+ });800+801+ it("escapes the handle, the name and every value a client supplies", () => {802+ const html = continuePage(803+ {804+ clientDomain: `"><img src=x>`,805+ clientName: `<script>alert("x")</script>`,806+ redirectHost: "evil.example<b>",807+ redirectIsLoopback: false,808+ },809+ { csrf: `"><script>`, request: `a"b` },810+ { displayName: `<i>Alice</i>`, handle: `<u>alice</u>` }811+ );812+813+ expect(html).not.toMatch(/<script|<img|<b>|<i>|<u>/u);814+ expect(html).toContain("<i>Alice</i>");815+ expect(html).toContain("@<u>alice</u>");816+ });817+});modified:apps/web/src/routes/auth/signout.ts+9 added-2 removed
1234567891011121314891516171819import { createFileRoute } from "@tanstack/react-router";import { env } from "cloudflare:workers";import { Option } from "effect";
import { signOutHandler } from "../../server/session.ts";
// A development build serves the dev world, which has no platform to sign out of, as in `signin.ts`.const signOut = signOutHandler( import.meta.env.DEV ? Option.none() : Option.some(env.PUBLIC_PLATFORM_URL));
export const Route = createFileRoute("/auth/signout")({ server: { handlers: { GET: signOutHandler, POST: signOutHandler, GET: signOut, POST: signOut, }, },});modified:apps/web/src/server/session.ts+18 added-2 removed
27 unmodified lines28 client: "/auth/client",29 signIn: "/auth/signin",30 } as const;31 32+// The platform ends its own session here and sends the browser to the web's home.33+export const PLATFORM_SIGN_OUT = "/oauth/signout";34+35 export interface Handled {36 readonly request: Request;37 }38 358 unmodified lines397 )398 )399 );400 398-export const signOutHandler = (_handled: Handled): Response =>399- redirect("/", clearedCookies());401+/**402+ * Ends the web's session, then the platform's, which comes home again: signed403+ * out of one is signed out of both, so the next sign-in asks who you are. With404+ * no platform (the dev world) it goes home at once.405+ */406+export const signOutHandler =407+ (platformUrl: Option.Option<string>) =>408+ (_handled: Handled): Response =>409+ redirect(410+ Option.match(platformUrl, {411+ onNone: () => "/",412+ onSome: (platform) => new URL(PLATFORM_SIGN_OUT, platform).href,413+ }),414+ clearedCookies()415+ );416 417 const whoAnswer = (418 who: { readonly handle?: Handle },419 cookies: readonly string[] = []55 unmodified linesmodified:apps/web/test/session.test.ts+30 added-31 removed
650 unmodified lines651 })652 );653 });654 655+const signedOut = (platform: Option.Option<string>) =>656+ ["POST", "GET"].map((method) => {657+ const response = signOutHandler(platform)({658+ request: new Request(`${WEB_URL}/auth/signout`, {659+ headers: { cookie: `${SESSION_COOKIE}=tok123` },660+ method,661+ }),662+ });663+664+ return [665+ response.status,666+ response.headers.get("location"),667+ expiriesOf(response),668+ ];669+ });670+671 describe("sign-out", () => {656- it("goes home and expires the session and handle cookies, by POST or by a plain link", () => {657- const answers = ["POST", "GET"].map((method) => {658- const response = signOutHandler({659- request: new Request(`${WEB_URL}/auth/signout`, {660- headers: { cookie: `${SESSION_COOKIE}=tok123` },661- method,662- }),663- });672+ const expired = [673+ [SESSION_COOKIE, true],674+ [HANDLE_COOKIE, true],675+ ];676 665- return [666- response.status,667- response.headers.get("location"),668- expiriesOf(response),669- ];670- });677+ it("expires the session and handle cookies, then ends the platform's session too, by POST or by a plain link", () => {678+ expect(signedOut(Option.some(PLATFORM_URL))).toStrictEqual([679+ [302, `${PLATFORM_URL}/oauth/signout`, expired],680+ [302, `${PLATFORM_URL}/oauth/signout`, expired],681+ ]);682+ });683 672- expect(answers).toStrictEqual([673- [674- 302,675- "/",676- [677- [SESSION_COOKIE, true],678- [HANDLE_COOKIE, true],679- ],680- ],681- [682- 302,683- "/",684- [685- [SESSION_COOKIE, true],686- [HANDLE_COOKIE, true],687- ],688- ],684+ it("goes home at once where there is no platform to sign out of", () => {685+ expect(signedOut(Option.none())).toStrictEqual([686+ [302, "/", expired],687+ [302, "/", expired],688 ]);689 });690 });691 336 unmodified linesmodified:AGENTS.md+1 added-1 removed
16 unmodified lines17 | 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a `retryable` and a `next` command fixed per tag, an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` and `packages/protocol/test/render.test.ts` (every tag, the code reads' and drafting's `UnknownPath`, `UnknownRevision`, `UnknownProposal`, `ProposalClosed` and `DraftInProgress` included; a limit's refusal names its kind and its wait, and a ref outside `refs/heads/` reads as one the platform writes); `packages/agent-kit/test/full-llms.test.ts` (every tag in the union has a row in `/llms-full.txt`); `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`; `packages/gate/test/shape.test.ts` (one push hears every stage-1 refusal at once); `apps/platform/test/mcp.test.ts` (each refusing MCP contract comes back as its exact refusal, `draftAsk`, `showProposal` and a code read's `UnknownPath` included); `apps/platform/test/workflows/draft.test.ts` (past the draft limit, `CapReached`); `apps/cli/test/policy.test.ts`; `apps/cli/test/local/check.test.ts` (the local check gives the gateway's stage-1 refusals for the same commit); `packages/protocol/test/exit-code.test.ts` (each tag's CLI exit code is pinned, 75 exactly when it is retryable); `packages/telemetry/test/defects.test.ts` (a refusal is never reported as an error, and a defect is reported once, at Error, with its cause and stack, however many boundaries it crosses), with `apps/platform/test/telemetry.test.ts` (the routers, a Project DO call and a Workflow instance each report a defect once, and neither the DO's caller nor a Workflow step that met it reports it again) and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's defect is the platform's to report), and `apps/sandbox/test/check-logs.test.ts` (a check's phases reach the logs by their size alone, never their text, so an answer's failing test makes no Issue); `packages/config/test/legacy-projects.test.ts` (the same alias rule for a project's address: the forty projects made before owners keep their keys as aliases of their full names, the two examples and the import plan's, each key and each name once) |18 | 4 | **One schema, many surfaces.** Change `packages/protocol`; every surface derives from it. Projections live only in `apps/*/src/surfaces.ts`. The CLI's command list is `commandDocs` in `@repo/agent-kit`, which the platform's skill, the CLI's MCP prompt and the web's `llms.txt` all read. | `apps/cli/test/commands-doc.test.ts` (the command list against the real CLI's commands, flags and positionals, `policy`, `ask draft` and `proposal` included); `packages/protocol/test/mcp.test.ts` (every MCP tool's schemas, with no JSON Schema leak, the policy and drafting contracts included; the five capped code reads are tools, `showCommit` and `listPaths` are not); `packages/agent-kit/test/install-channels.test.ts` and `apps/web/test/agents.test.tsx` (every snippet, command and link on the Install page is `@repo/agent-kit`'s, and the old `/agents` answers a 301 to `/install`); `packages/agent-kit/test/docs.test.ts` and `apps/web/test/docs.test.tsx` (the `/docs` pages name only the CLI's commands with flags each takes and link only to pages that exist, the reference lists every command, refusal, event, MCP tool, limit, endpoint and imported project from its source, and the web draws each page and its Markdown from that one text); `apps/web/test/llms.test.ts` (`/` and `/<project>` asked for Markdown answer with the `llms.txt` texts, and their HTML names that Markdown as an alternate); `packages/agent-kit/test/full-llms.test.ts` (one `ProjectEvent` line per tag); `apps/platform/test/home.test.ts` (the platform's `/` in Markdown is the web's `llms.txt`, one text from `@repo/agent-kit`); `packages/protocol/test/project-name.test.ts` (`ProjectName` is the one parser of a project's name for every surface: lowercase, a legacy key read as its full name, encoded only in the full form, and a key that reads back to its name); per-package `allowedUnstableApis` with `unstableApiUsage` at error |19 | 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` (`scripts/brand.ts`, tested by `packages/brand/test/leaks.test.ts`); `apps/web/test/shell.test.tsx` (the footer's wordmark is `Brand.domain`, read from `@repo/brand`, never typed) |20 | 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. No module-level mutable state in a package's `src/`. | Scoped `allowedUnstableApis`; `packages/artifacts/test/repo-host-contract.ts` (one RepoHost contract every adapter passes); `apps/platform/test/bindings.test.ts` and `apps/platform/test/worker-init.test.ts` (the Worker starts on its real adapters, composed in `apps/platform/src/ports.ts`); `apps/platform/test/router-build.test.ts` (both handlers are built when the Worker module loads, with no binding touched, and a layer that awaits a promise while it is built is refused there); `apps/web/test/production-bundle.test.ts` (no dev-world module in the web's production build, and no chunk every page preloads holds the Markdown renderer, under a gzip ceiling); `packages/config/test/cartridge.test.ts` (the visibility cartridge is plugged in by one marked line and reached by nothing else, so removing it is a deletion); `packages/drafting/test/memory.test.ts` (the `Drafter` port's `/memory` adapter, `packages/drafting/src/drafter/memory.ts`) and `packages/drafting/test/binding.test.ts` (its Workers AI adapter over the `AI` binding); `apps/platform/test/mailer.test.ts` (sign-in's `Mailer` port, its `/memory` adapter and its Email Service adapter over the `EMAIL` binding); `packages/project/test/code-store.test.ts` (the `CodeStore` port's `/memory` adapter, `packages/project/src/code-store/memory.ts`, and its R2 adapter over `CODE_CACHE`, whose failures are misses, never the read's); `packages/project/test/metrics.test.ts` (the `Metrics` port's `/memory` adapter, `packages/project/src/metrics/memory.ts`, and its Analytics Engine adapter over `METRICS`, which drops a point the dataset refuses and fails nothing; `apps/platform/test/worker-init.test.ts` writes through the Worker's own ports); `apps/platform/test/code-reads.test.ts` and `apps/web/test/dev-backend.test.ts` (the platform and the web's dev world answer the code reads and raw files alike, both through `@repo/project/code`); `packages/project/test/standing-posture.test.ts` (one helper, `withStandingPosture`, gives a listing each project's own posture, for the platform and the web's dev world alike, through the `StandingPostures` port whose default keeps nothing; its D1 adapter is the platform's); `packages/project/test/description.test.ts` and `packages/project/test/description-d1.test.ts` (the `ProjectDescriptions` port's `/memory` adapter, `packages/project/src/description/memory.ts`, and its D1 adapter, whose unreadable rows and missing table are misses); `apps/web/test/seeded.test.tsx` (a loader's read seeds a registry of its own page and leaves the registry every request shares as it was); `apps/web/test/shell.test.tsx` (no plain anchor between the web's pages: every link is the router's); `packages/telemetry/test/spans.test.ts` (the spans port: Effect's `Tracer`, bridged onto a Worker's `tracing` by `packages/telemetry/src/spans/binding.ts`, with its `/memory` adapter, `packages/telemetry/src/spans/memory.ts`, on which every span opens under the invocation's root, a sibling of the runtime's own, and an ended span is traced no more, as in workerd; only a Worker's composition imports `tracing` from `cloudflare:workers`). No fence: import direction and module-level state |21-| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `packages/config/test/observability.test.ts` (a Checker's container logs are off in every stage, and every container sets its own; the platform's traces are kept in the account and sent to no destination, since the runtime's own spans record each Project DO statement's bound values and each fetch's full URL); `packages/config/test/alerts.test.ts` (an alert's query counts rows of its own stage's Workers and datasets, never a layer's or another stage's); `packages/telemetry/test/spans.test.ts` (a span carries only the listed ids onto a trace, never a repo, a path or a query, and Issues reads ids alone), `packages/telemetry/test/logger.test.ts` and `packages/telemetry/test/defects.test.ts` (no line, report or span carries a Worker secret or a write-only value, and where a Worker keeps a defect by its name, no line it logs carries the defect's text), with `apps/platform/test/telemetry.test.ts` (every secret the platform's env decodes, each session token included, and a route's or a Project DO's defect kept by its name and frames alone, since its text may name a layer's repo, on a report and on any line whose cause holds it, a warning's included), `apps/platform/test/sandbox-adapters.test.ts` (a sandbox job's defect logged by its name and frames alone), and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's lines carry none of its tokens, and a Checker's span keeps a defect by its name alone, since its text may quote a sealed path); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `packages/protocol/test/fork-address.test.ts` (a fork's address is a closed parse that never joins text into a ref path), with `packages/project/test/code.test.ts` and `apps/platform/test/code-reads.test.ts` (a fork is read only at the address of a claim fork the project lists, and a layer's repo, an unlisted fork or a repo's name is `UnknownRevision`); `packages/protocol/test/recent-landing.test.ts` and `packages/project/test/recent-landings-d1.test.ts` (a kept refusal is its tag and area alone); `packages/project/test/metrics.test.ts` (a metric names a project, a refusal's tag and area, a stage and a lane, with numbers: never a path, a command, a log or a held-back check); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing's latest landings name each by its project, and a refused answer by its tag and its area alone, never a check's name, suite, lane, path or log) and `apps/web/test/explore.test.tsx` (each project's card shows the posture its listing gives); `apps/web/test/ledger.test.tsx` (the Visibility tab's ledger adds no path, check name or file name, and the tab's views import nothing from the visibility cartridge) and `apps/web/test/env.test.tsx` (its Environment shows no value and no control to set or read one, and the old `/env` and `/ledger` answer a 301 to the tab); `apps/web/test/home.test.tsx`, `apps/web/test/today.test.tsx` and `apps/web/test/edge-cache.test.ts` (`/inbox` is read with the reader's own session and kept by no cache, and the old `/home` and `/today` answer a 301 to it); `apps/web/test/theme.test.ts` and `apps/web/test/settings.test.tsx` (the theme preference lives in `localStorage` and never in a cookie, so it makes no page personal); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |21+| 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree`, one rule for the gate's stage 1 and the landing guard (`packages/gate/test/shape.test.ts`, `packages/visibility/test/guards.test.ts`); `apps/platform/test/visibility/layer-gateway.test.ts` (only a layer's readers clone it, every read is logged, a fork push cannot carry its paths); `apps/sandbox/test/held-back.test.ts` (egress off and the snapshot taken before any sealed file is written; one bit per area, no output); `packages/config/test/observability.test.ts` (a Checker's container logs are off in every stage, and every container sets its own; the platform's traces are kept in the account and sent to no destination, since the runtime's own spans record each Project DO statement's bound values and each fetch's full URL); `packages/config/test/alerts.test.ts` (an alert's query counts rows of its own stage's Workers and datasets, never a layer's or another stage's); `packages/telemetry/test/spans.test.ts` (a span carries only the listed ids onto a trace, never a repo, a path or a query, and Issues reads ids alone), `packages/telemetry/test/logger.test.ts` and `packages/telemetry/test/defects.test.ts` (no line, report or span carries a Worker secret or a write-only value, and where a Worker keeps a defect by its name, no line it logs carries the defect's text), with `apps/platform/test/telemetry.test.ts` (every secret the platform's env decodes, each session token included, and a route's or a Project DO's defect kept by its name and frames alone, since its text may name a layer's repo, on a report and on any line whose cause holds it, a warning's included), `apps/platform/test/sandbox-adapters.test.ts` (a sandbox job's defect logged by its name and frames alone), and `apps/sandbox/test/telemetry.test.ts` (a sandbox job's lines carry none of its tokens, and a Checker's span keeps a defect by its name alone, since its text may quote a sealed path); `apps/platform/test/visibility/held-back.test.ts` (the `Held-back:` trailer, the landing guards, no stored value in a note or a kept log); `apps/platform/test/bindings.test.ts`; `apps/sandbox/test/checker.test.ts` (no snapshot once the held-back slot is reached); `apps/web/test/env.test-d.ts` (the web's Env has no private-namespace, Artifacts or `CODE_CACHE` binding) and `apps/platform/test/env.test-d.ts` (only the platform's has both); `packages/project/test/code-raw.test.ts` and `apps/platform/test/raw.test.ts` (raw bytes under `nosniff` and the sandboxing CSP, refusals included); `apps/platform/test/code-reads.test.ts` (no code read's payload names a repo); `packages/project/test/code-history.test.ts` (the code store is keyed under the project's canonical repo alone and holds no landing); `apps/platform/test/w9-contracts.test.ts` (`projectPolicy` answers without the policy's layers or asks, and `packages/config/test/cartridge.test.ts` keeps the cartridge removable); `packages/drafting/test/prompt.test.ts` (a draft's prompt never carries a layer's name, repo, reason or paths); `apps/web/test/markdown.test.tsx` (a README's script, handlers, unsafe URLs, iframes, styles and forms never reach the page); `apps/platform/test/gateway.test.ts` and `packages/gate/test/parse.test.ts` (a fork takes branches only: its notes, tags and the platform's refs are refused); `packages/protocol/test/fork-address.test.ts` (a fork's address is a closed parse that never joins text into a ref path), with `packages/project/test/code.test.ts` and `apps/platform/test/code-reads.test.ts` (a fork is read only at the address of a claim fork the project lists, and a layer's repo, an unlisted fork or a repo's name is `UnknownRevision`); `packages/protocol/test/recent-landing.test.ts` and `packages/project/test/recent-landings-d1.test.ts` (a kept refusal is its tag and area alone); `packages/project/test/metrics.test.ts` (a metric names a project, a refusal's tag and area, a stage and a lane, with numbers: never a path, a command, a log or a held-back check); `apps/platform/test/visibility/posture-listing.test.ts` and `apps/platform/test/home.test.ts` (the project list and the platform's `/` show the posture the project's ledger shows); `apps/web/test/landing.test.tsx` (the landing's latest landings name each by its project, and a refused answer by its tag and its area alone, never a check's name, suite, lane, path or log) and `apps/web/test/explore.test.tsx` (each project's card shows the posture its listing gives); `apps/web/test/ledger.test.tsx` (the Visibility tab's ledger adds no path, check name or file name, and the tab's views import nothing from the visibility cartridge) and `apps/web/test/env.test.tsx` (its Environment shows no value and no control to set or read one, and the old `/env` and `/ledger` answer a 301 to the tab); `apps/web/test/home.test.tsx`, `apps/web/test/today.test.tsx` and `apps/web/test/edge-cache.test.ts` (`/inbox` is read with the reader's own session and kept by no cache, and the old `/home` and `/today` answer a 301 to it); `apps/web/test/theme.test.ts` and `apps/web/test/settings.test.tsx` (the theme preference lives in `localStorage` and never in a cookie, so it makes no page personal); `apps/platform/test/pages.test.ts` (the sign-in page, as an MCP client's consent, escapes every value a client supplies, and every sign-in form shown again escapes what the person typed); `apps/platform/test/oauth.test.ts` (no account is written, and no grant given, until its email is proved by a mailed code, and a password reset reads the same for an address no account has; the platform's own session is an HttpOnly, Secure, SameSite=Lax cookie that a changed seal, a missing account or a password reset turns into the plain sign-in page, and its sign-out goes only to the web's home); `apps/platform/test/gateway-owner.test.ts` (the gateway reads a full name, a source path, a legacy key or a fork's address to the repo its project's key names, and an owner alone or a name under a page's word to none) |22 | 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins; `packages/rules/test/replay.test.ts`; `packages/project/test/project-store.contract.ts`; `packages/project/test/claim.model.test.ts` and `packages/project/test/landing.model.test.ts`; `apps/platform/test/workflows/answer.test.ts`; `apps/platform/test/workflows/on-push.test.ts`; `apps/platform/test/core-loop.test.ts`; `apps/platform/test/workflows/draft.test.ts` (a replayed draft round asks the model nothing more, and each round is its own instance); `packages/project/test/code.test.ts` (code reads cached by object id, only once finished, while `main` resolves every time, and a commit's diff kept by its SHA without its landing); `packages/project/test/drafting.model.test.ts` (a settle of a stale round changes nothing); `packages/project/test/import.test.ts` (a retried import adopts the repo it made, and a retried import keeps its source); `packages/project/test/code-history.test.ts` (a why and a path's history are kept by commit, path hash and algorithm version, and the store, a step from a kept ancestor and a whole walk agree); `packages/config/test/smoke-loop.test.ts` (smoke's throwaway project is in the ledger before init makes it, and a taken name stops before anything is made); `apps/web/test/events.test.ts` (the web's fold of a project's events gives the same map when an event is heard twice or out of order, and a replay that already holds a landing stamps nothing); `packages/project/test/standing-posture.test.ts` (a kept posture is read again only for the project whose event the projection applied, or once its instant has come); `packages/project/test/recent-landings-d1.test.ts` (the same rows heard again change nothing, and at most `RECENT_LANDINGS_CAP` rows are kept); `packages/project/test/description.test.ts` (a landed project is read once while its last landing stands); `apps/platform/test/well-known.test.ts` (the agent skills index is kept by its listing's projects and last landings, so while no listed project lands it wakes no project, and a landing reads again only its own skill); `packages/project/test/metrics.test.ts` (each landing, refusal, checked lane, wait before checks and draft round is written at most once, from the outbox of the commit that keeps it, however often its push, report or settle is heard, and when a call's settle and the alarm's both hold its row), with `packages/project/test/project-store.contract.ts` (of two acks of one outbox row, only the first takes it). No fence: one push deduped by (repo, sha) across the gateway's record and OnPush's |23 | 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Effect marks its unstable modules (`effect/http`, `effect/sql`, `effect/observability` and the rest) in place, with no `effect/unstable/*` path: one is off limits outside the paths its package's allow-list names. Off limits too: v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `unstableApiUsage` at error, with per-path `allowedUnstableApis` in `tsconfig.base.json`; `no-restricted-imports` |24 | 10 | **Escapes need a reason.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries its reason after `--`, and is added only where no idiomatic code does the job. | `check` fails on an unused directive. No fence: the reason |25 | 11 | **`bun run verify` is the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `packages/config/test/verify.test.ts` (verify's steps); `infra/deploy.ts` refuses without a known stage, runs `verify` first and `scripts/smoke.ts` after, which fails on any exception or error-level line the stage's Workers logged since the first upload, or on a token that can't read them (`packages/config/test/deploy.test.ts`, `packages/config/test/smoke.test.ts`), and refuses every deploy while `infra/.recording` is there (`packages/config/test/recording.test.ts`) |114 unmodified lines