Skip to content
Myr

Keep a person signed in on the platform for thirty days after any grant, so the next client's sign-in asks only to continue as them: an HttpOnly, Secure, SameSite=Lax session sealed with the cookie key names the handle and a digest of its password hash, so a reset ends it everywhere; the continue page keeps a third party's consent, offers another account, and holds the email rule; sign-out on the web ends it too, and the platform's sign-out goes only to the web's home

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parent 9142e90 · 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

12 files+951 added−47 removed

modified:apps/platform/src/auth/pages.ts+58 added
30 unmodified lines
31 resetVerify: "/oauth/reset/verify",32 signUpVerify: "/oauth/signup/verify",33} as const;3435// The platform's own session: continue as the person it names, switch away from them, or end it.36export const SESSION_PATHS = {37 continue: "/authorize/continue",38 signOut: "/oauth/signout",39 switch: "/oauth/switch",40} as const;4142export const GOOGLE_PATHS = {43 callback: "/oauth/google/callback",44 handle: "/oauth/google/handle",45 link: "/oauth/google/link",
67 unmodified lines
113.button svg{flex:none;width:18px;height:18px}114button.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}115button.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}123pre{margin:8px 0 12px;padding:8px 12px;overflow-x:auto;background-color:var(--surface);border:1px solid var(--rule)}
153 unmodified lines
277 after: `New here? <a href="${withRequest("/signup", form)}">Create an account</a>`,278 }279 );280281// A name's first letter as a reader sees it, an accent or an emoji whole.282const graphemes = new Intl.Segmenter("en", { granularity: "grapheme" });283284export interface SignedInAs {285 readonly displayName?: string | undefined;286 readonly handle: string;287}288289/**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 */293export const continuePage = (294 asker: Asker,295 form: PendingForm,296 who: SignedInAs,297 message?: string298) => {299 const handle = `@${escapeHtml(who.handle)}`;300301 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>`;305306 const [first] = Array.from(307 graphemes.segment(who.displayName ?? who.handle),308 ({ segment }) => segment309 );310311 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};328329export interface ProfileValues {330 readonly displayName?: string;331 readonly handle?: string;332}
160 unmodified lines
added: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.5import { Handle } from "@repo/protocol/ids";6import { Duration, Effect, Option, Schema } from "effect";7import type { Redacted } from "effect";8import type { HttpServerRequest } from "effect/http";9import { HttpServerResponse } from "effect/http";1011import { Accounts } from "./accounts.ts";12import type { Account } from "./accounts.ts";13import { sealing } from "./state.ts";1415export const SESSION_COOKIE = "__Host-platform-session";1617export const SESSION_LIFETIME = Duration.days(30);1819// `Lax`, not `Strict`: a client sends the person here by a top-level link, and the cookie must come with it.20export const sessionCookie = {21 httpOnly: true,22 path: "/",23 sameSite: "lax",24 secure: true,25} as const;2627const PlatformSession = Schema.Struct({ handle: Handle, stamp: Schema.String });2829const sessions = sealing("platform-session", PlatformSession, SESSION_LIFETIME);3031const encodeStamp = Schema.encodeEffect(Schema.Uint8ArrayFromBase64Url);3233// A digest of the password hash, never the hash: the cookie's payload is signed, not hidden.34const 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 );4243/**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 */49export const sessionAccount = (50 key: Redacted.Redacted,51 request: HttpServerRequest.HttpServerRequest52) =>53 Effect.gen(function* () {54 const sealed = request.cookies[SESSION_COOKIE];5556 if (sealed === undefined || sealed === "") {57 return Option.none<Account>();58 }5960 const opened = yield* sessions.open(key, sealed).pipe(Effect.option);6162 if (Option.isNone(opened)) {63 return Option.none<Account>();64 }6566 const accounts = yield* Accounts;6768 const account = yield* accounts.find(opened.value.handle);6970 if (Option.isNone(account)) {71 return Option.none<Account>();72 }7374 const stamp = yield* stampOf(account.value);7576 return stamp === opened.value.stamp ? account : Option.none<Account>();77 });7879export const hasSessionCookie = (80 request: HttpServerRequest.HttpServerRequest81) => request.cookies[SESSION_COOKIE] !== undefined;8283export 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 });9192 return yield* response.pipe(93 HttpServerResponse.setCookie(SESSION_COOKIE, sealed, {94 ...sessionCookie,95 maxAge: SESSION_LIFETIME,96 }),97 Effect.orDie98 );99 });100101export 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 lines
38import {39 ACCOUNT_PATHS,40 addEmailPage,41 codePage,42 continuePage,43 problemPage,44 resetPage,45 SESSION_PATHS,46 signInPage,47 signUpPage,48} from "./pages.ts";49import type { Asker, CodeForm, PendingForm, SignUpValues } from "./pages.ts";
3 unmodified lines
53 PasswordPolicy,54 verifyPassword,55} from "./password.ts";56import {57 hasSessionCookie,58 sessionAccount,59 withoutSession,60 withSession,61} from "./platform-session.ts";62import {63 AuthRequest,64 openState,65 sealing,66 sealState,
50 unmodified lines
117 "/authorize",118 "/signup",119 CLI_CLIENT_PATH,120 ...Object.values(ACCOUNT_PATHS),121 ...Object.values(SESSION_PATHS),122] as const;123124// 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.125const RESERVED_HANDLES: ReadonlySet<string> = new Set([
31 unmodified lines
157 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 lines
382 : Effect.fail(startAgain);383384// 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.390export 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);395396 const { redirectTo } = yield* provider(() =>397 api.completeAuthorization({398 metadata: {},
14 unmodified lines
413 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 });426427const offeredSignIn = (
36 unmodified lines
464465 return yield* withCsrfCookie(csrf)(page);466 });467468const continuePageFor = (request: AuthRequest, account: Account) =>469 Effect.gen(function* () {470 const { cookieKey } = yield* SignInKeys;471472 const csrf = yield* freshCsrf;473474 const sealed = yield* sealState(cookieKey, { csrf, request });475476 const asker = yield* askerOf(request);477478 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 });490491// A session that no longer fits is dropped as the page that replaces it is shown.492const signInOrDropped = (493 request: HttpServerRequest.HttpServerRequest,494 pending: AuthRequest,495 message?: string496) =>497 Effect.gen(function* () {498 const page = yield* signInPageFor(pending, 200, message);499500 return hasSessionCookie(request) ? yield* withoutSession(page) : page;501 });502503// Someone signed in here already is asked only to continue; anyone else, to sign in.504const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>505 Effect.gen(function* () {506 const api = yield* oauthApi;507 const { cookieKey } = yield* SignInKeys;508509 const web = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);510511 const parsed = yield* provider(() => api.parseAuthRequest(web));512455 return yield* signInPageFor(parsed, 200);513 const account = yield* sessionAccount(cookieKey, request);514515 return yield* Option.match(account, {516 onNone: () => signInOrDropped(request, parsed),517 onSome: (signedIn) => continuePageFor(parsed, signedIn),518 });519 });520521// Mailing522
229 unmodified lines
752 });753754// A signed-in account with no email adds one before its grant.755export 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 });761762const signIn = (request: HttpServerRequest.HttpServerRequest) =>763 byPassword(request, (account, pending) =>764 signedInWithEmail(account, pending.request)765 );766767const PostedContinue = Schema.Struct({768 csrf: Schema.String,769 request: Schema.String,770});771772// No password is asked, so the session is read again at the click: it must still fit, and the email rule still holds.773const continueAs = (request: HttpServerRequest.HttpServerRequest) =>774 Effect.gen(function* () {775 const { cookieKey } = yield* SignInKeys;776777 const form = yield* HttpServerRequest.schemaBodyUrlParams(778 PostedContinue779 ).pipe(Effect.mapError(() => startAgain));780781 const pending = yield* openState(cookieKey, form.request);782783 yield* sameCsrf(request, form.csrf, pending.csrf);784785 const account = yield* sessionAccount(cookieKey, request);786787 return yield* Option.match(account, {788 onNone: () => signInOrDropped(request, pending.request, Says.signedOut),789 onSome: (signedIn) => signedInWithEmail(signedIn, pending.request),790 });791 });792793// Leaves the session and signs in afresh for the same client.794const switchAccount = Effect.gen(function* () {795 const { cookieKey } = yield* SignInKeys;796797 const { request: sealed } = yield* HttpServerRequest.schemaSearchParams(798 Schema.Struct({ request: Schema.String })799 ).pipe(Effect.mapError(() => startAgain));800801 const pending = yield* openState(cookieKey, sealed);802803 return yield* signInPageFor(pending.request, 200).pipe(804 Effect.flatMap(withoutSession)805 );806});807808// Always to the web's home, never to an address the request names.809const signOut = Effect.gen(function* () {810 const { webUrl } = yield* SignInHome;811812 return yield* withoutSession(813 HttpServerResponse.redirect(814 Option.getOrElse(webUrl, () => "/"),815 { headers: { "cache-control": "no-store" }, status: 302 }816 )817 );818});819820const addEmailCode = (request: AuthRequest, email: Email): CodeForm => ({821 action: ACCOUNT_PATHS.addEmailVerify,822 intro: codeSentTo(email),823 newPassword: false,
666 unmodified lines
1490 );14911492 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 lines
modified:apps/platform/src/auth/state.ts+6 added-2 removed
modified:apps/platform/test/google.fixtures.ts+7 added-1 removed
345 unmodified lines
346 const cookies = [...jar].flatMap(([name, kept]) =>347 from === "same-site" || !kept.strict ? [`${name}=${kept.value}`] : []348 );349350 // A cookie the request names itself is kept beside the jar's.351 const named = headers.get("cookie");352353 if (cookies.length > 0) {351 headers.set("cookie", cookies.join("; "));354 headers.set(355 "cookie",356 [...(named === null ? [] : [named]), ...cookies].join("; ")357 );358 }359360 const response = yield* Effect.promise(() =>361 handler(new Request(request, { headers, redirect: "manual" }))
107 unmodified lines
modified:apps/platform/test/google.test.ts+5 added
807 unmodified lines
808 );809810 yield* chooseHandle(world, first, "Carol");811812 // Signed out, or the platform's session would only ask to continue.813 yield* visit(world, "/oauth/signout");814815 const again = yield* backFromGoogle(816 world,817 yield* continueWithGoogle(world),818 { sub: "1042" }
404 unmodified lines
1223 Option.some(Handle.make("alice")),1224 Option.some(googleEmailOf("5150")),1225 ]);12261227 yield* visit(world, "/oauth/signout");12281229 const later = yield* backFromGoogle(1230 world,1231 yield* continueWithGoogle(world),1232 { sub: "5150" }
95 unmodified lines
modified:apps/platform/test/oauth.test.ts+517 added-2 removed
2 unmodified lines
3import { Handle } from "@repo/protocol/ids";4import { Person } from "@repo/protocol/principal";5import { untouchable } from "@repo/testkit/untouchable";6import { Effect, Option, Redacted, Schema } from "effect";7import { HttpServerRequest, HttpServerResponse } from "effect/http";8import { TestClock } from "effect/testing";910import { OAuthSessions } from "../src/adapters/sessions-oauth.ts";10import { Email } from "../src/auth/accounts.ts";11import { Accounts, Email } from "../src/auth/accounts.ts";12import type { Account } from "../src/auth/accounts.ts";13import { AccountsMemory } from "../src/auth/accounts/memory.ts";14import { SignInAttempts } from "../src/auth/attempts.ts";15import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";16import { cliClientMetadata } from "../src/auth/cli-client.ts";17import { codeMatches, codeTag, deadTag, freshCode } from "../src/auth/codes.ts";18import type { CodePurpose } from "../src/auth/codes.ts";16import { ACCOUNT_PATHS } from "../src/auth/pages.ts";19import { ACCOUNT_PATHS, SESSION_PATHS } from "../src/auth/pages.ts";20import {21 hashPassword,22 hashPasswordWith,23 PasswordHash,24 verifyPassword,25} from "../src/auth/password.ts";26import { sessionAccount, withSession } from "../src/auth/platform-session.ts";27import { tokenReader } from "../src/auth/provider.ts";28import { openState, sealState, SignInFailed } from "../src/auth/state.ts";29import type { PendingSignIn } from "../src/auth/state.ts";30import worker from "../src/worker.ts";
1490 unmodified lines
1521 ).toBeFalsy();1522 })1523 );1524});15251526const SESSION = "__Host-platform-session";15271528const webHome = fakeEnv().PUBLIC_WEB_URL;15291530const sessionLine = (response: Response) =>1531 Option.fromNullishOr(1532 response.headers1533 .getSetCookie()1534 .find((line) => line.startsWith(`${SESSION}=`))1535 );15361537const 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);15481549// A line that ends the session: an empty value, kept for no time at all.1550const endsSession = (response: Response) =>1551 Option.exists(1552 sessionLine(response),1553 (line) =>1554 line.startsWith(`${SESSION}=;`) &&1555 line.toLowerCase().includes("max-age=0")1556 );15571558const withCookies = (1559 request: Request,1560 cookies: Readonly<Record<string, string>>1561) => {1562 const headers = new Headers(request.headers);15631564 headers.set(1565 "cookie",1566 Object.entries(cookies)1567 .map(([name, value]) => `${name}=${value}`)1568 .join("; ")1569 );15701571 return new Request(request, { headers });1572};15731574const openSignedIn = (world: World, session: string, url = authorizeUrl()) =>1575 world1576 .fetch(withCookies(new Request(url), { [SESSION]: session }))1577 .pipe(Effect.flatMap(read));15781579const continueFrom = (1580 world: World,1581 page: Page,1582 session: string,1583 csrf?: string1584) =>1585 Effect.gen(function* () {1586 const form = yield* formIn(page);15871588 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 });15991600const signedInSession = (world: World) =>1601 Effect.gen(function* () {1602 yield* signUp(world, "alice", alicePassword);16031604 return yield* signIn(world, "alice", alicePassword).pipe(1605 Effect.flatMap(sessionIn)1606 );1607 });16081609// A session sealed as the platform would, for an account a test names.1610const sessionFor = (account: Account) =>1611 withSession(1612 cookieKey,1613 account1614 )(HttpServerResponse.empty()).pipe(1615 Effect.map(HttpServerResponse.toWeb),1616 Effect.flatMap(sessionIn)1617 );16181619const asksToContinue = (page: Page) => ({1620 continues: page.html.includes("Continue as @alice"),1621 password: page.html.includes('name="password"'),1622 status: page.response.status,1623});16241625describe("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();16311632 yield* signUp(world, "alice", alicePassword);16331634 const signedIn = yield* signIn(world, "alice", alicePassword);16351636 const attributes = Option.map(sessionLine(signedIn), (line) =>1637 line1638 .split(";")1639 .slice(1)1640 .map((part) => part.trim().toLowerCase())1641 .toSorted()1642 );16431644 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 );16561657 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();16621663 const session = yield* signedInSession(world);16641665 const page = yield* openSignedIn(1666 world,1667 session,1668 authorizeUrl("state-2")1669 );16701671 const code = yield* continueFrom(world, page, session).pipe(1672 Effect.flatMap(codeIn)1673 );16741675 const response = yield* world.fetch(tokenRequest(code));16761677 const { access_token } = yield* Effect.promise(() =>1678 response.json()1679 ).pipe(1680 Effect.flatMap(Schema.decodeUnknownEffect(TokenResponse)),1681 Effect.orDie1682 );16831684 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 );16961697 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();17021703 const session = yield* signedInSession(world);17041705 const url = authorizeUrl();17061707 url.searchParams.set("client_id", "https://other.test/oauth/cli");17081709 const page = yield* openSignedIn(world, session, url);17101711 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 );17261727 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();17321733 const session = yield* signedInSession(world);17341735 const page = yield* openSignedIn(world, tampered(session));17361737 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 );17481749 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();17541755 const session = yield* signedInSession(world);17561757 const started = yield* startReset(world, emailOf("alice"));17581759 const code = yield* Effect.fromOption(1760 yield* codeMailedTo(world, emailOf("alice"))1761 ).pipe(Effect.orDie);17621763 const reset = yield* enterCode(1764 world,1765 started,1766 ACCOUNT_PATHS.resetVerify,1767 code,1768 { password: "a brand new password" }1769 );17701771 const old = yield* openSignedIn(world, session);17721773 const fresh = yield* openSignedIn(world, yield* sessionIn(reset));17741775 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 );17861787 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();17921793 const session = yield* sessionFor({1794 email: Email.make("ghost@mail.example"),1795 handle: Handle.make("ghost"),1796 hash: yield* hashPassword(pepper, password),1797 });17981799 const page = yield* openSignedIn(world, session);18001801 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 );18121813 it.live("refuses a continue with another form's CSRF token, or none", () =>1814 Effect.gen(function* () {1815 const world = yield* signInWorld();18161817 const session = yield* signedInSession(world);18181819 const page = yield* openSignedIn(world, session);18201821 const wrong = yield* continueFrom(world, page, session, "another-token");18221823 const form = yield* formIn(page);18241825 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 );18351836 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 );18441845 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();18501851 const session = yield* signedInSession(world);18521853 const page = yield* openSignedIn(world, session);18541855 const clicked = yield* continueFrom(1856 world,1857 page,1858 tampered(session)1859 ).pipe(Effect.flatMap(read));18601861 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 );18761877 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();18821883 const session = yield* signedInSession(world);18841885 const page = yield* openSignedIn(1886 world,1887 session,1888 authorizeUrl("state-9")1889 );18901891 const form = yield* formIn(page);18921893 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));19061907 const again = yield* formIn(switched);19081909 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 );19211922 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 );19381939 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();19441945 const session = yield* signedInSession(world);19461947 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 );19611962 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 );19741975 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();19801981 yield* legacyAccount(world);19821983 const account = yield* Effect.fromOption(1984 yield* world.accounts.find(Handle.make("alice"))1985 ).pipe(Effect.orDie);19861987 const session = yield* sessionFor(account);19881989 const page = yield* openSignedIn(world, session);19901991 const clicked = yield* continueFrom(world, page, session).pipe(1992 Effect.flatMap(read)1993 );19941995 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});20032004describe("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;20082009 const account = {2010 email: Email.make("alice@mail.example"),2011 handle: Handle.make("alice"),2012 hash: yield* hashPasswordWith(1000)(pepper, password),2013 };20142015 yield* accounts.create(account);20162017 const session = yield* sessionFor(account);20182019 const request = HttpServerRequest.fromWeb(2020 new Request(origin, { headers: { cookie: `${SESSION}=${session}` } })2021 );20222023 const opened = () =>2024 Effect.map(sessionAccount(cookieKey, request), Option.isSome);20252026 yield* TestClock.adjust("29 days");20272028 const before = yield* opened();20292030 yield* TestClock.adjust("1 day");20312032 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 lines
9import {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";21import type { Asker, PendingForm } from "../src/auth/pages.ts";
84 unmodified lines
106 "/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 lines
758 signUpPage(local, form, { google: false }, "/authorize", {})759 ).not.toContain("Continue with Google");760 });761});762763describe("the page that asks only to continue", () => {764 const alice = { displayName: "Alice Example", handle: "alice" };765766 it("names who is signed in and offers one button, asking for no password", () => {767 const html = continuePage(ourWeb, form, alice);768769 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 });787788 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);791792 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 });800801 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 );812813 expect(html).not.toMatch(/<script|<img|<b>|<i>|<u>/u);814 expect(html).toContain("&lt;i&gt;Alice&lt;/i&gt;");815 expect(html).toContain("@&lt;u&gt;alice&lt;/u&gt;");816 });817});
modified:apps/web/src/routes/auth/signout.ts+9 added-2 removed
modified:apps/web/src/server/session.ts+18 added-2 removed
27 unmodified lines
28 client: "/auth/client",29 signIn: "/auth/signin",30} as const;3132// The platform ends its own session here and sends the browser to the web's home.33export const PLATFORM_SIGN_OUT = "/oauth/signout";3435export interface Handled {36 readonly request: Request;37}38
358 unmodified lines
397 )398 )399 );400398export 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 */406export 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 );416417const whoAnswer = (418 who: { readonly handle?: Handle },419 cookies: readonly string[] = []
55 unmodified lines
modified:apps/web/test/session.test.ts+30 added-31 removed
650 unmodified lines
651 })652 );653});654655const 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 });663664 return [665 response.status,666 response.headers.get("location"),667 expiriesOf(response),668 ];669 });670671describe("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 ];676665 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 });683672 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 lines
modified:AGENTS.md+1 added-1 removed
16 unmodified lines
17| 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