Land checks async with a receipt; check on Node 26 and older git; 20s test timeout; fix the prod log tail; name thrown failures in evidence; key setup snapshots by image; pin burrow's lockfile to the root's
Landed as f7b8ef2
This landing
State
Landed as f7b8ef2
By oscar
Credit
- Signed-off-by: oscar
Diff stats
111 files+4456 added−418 removed
- tests:+2781 added−137 removed
- other:+1675 added−281 removed
Provenance
- Commit
f7b8ef2- Tree
1baf41e- Author
oscar <oscar@users.myr.technology>- Committer
Myr <platform@myr.technology>- Parent
5157dd9- Request-Id
land-1a01e31
111 files changed+4456 added−418 removed
This commit is too large to show whole: its files are listed by path, without their changes.
modified:apps/cli/src/local/check.ts+4 added-2 removed
741 unmodified lines742 ]743 );744 745 for (const evidence of run.evidence) {746+ const said = evidence.signature ?? evidence.threw;747+746- if (evidence.signature !== undefined) {747- yield* output.note(`${evidence.lane} failed: ${evidence.signature}`);748+ if (said !== undefined) {749+ yield* output.note(`${evidence.lane} failed: ${said}`);750 }751 }752 753 const declared = Array.isReadonlyArrayNonEmpty(policy.ratchets);58 unmodified linesmodified:apps/cli/src/local/login.ts+165 added-64 removed
29 unmodified lines30 31 import { currentEnv } from "../credential-helper.ts";32 import { Credentials, gitHelperConfig } from "../credentials.ts";33 import type { Profile } from "../credentials.ts";34+import {35+ CLI_CODE_PATH,36+ cliClientIdOf,37+ revoke,38+ tradeCode,39+} from "../oauth-token.ts";40+import type { Issued } from "../oauth-token.ts";41 import { Output } from "../output.ts";42 43 const SLUG = Brand.slug.toUpperCase();44 45 const LOOPBACK = "127.0.0.1";46 47 const SIGN_IN_WAIT = "5 minutes";48 42-const clientIdOf = (origin: string) => `${origin}/oauth/cli`;43-49 export const Loopback = Context.Reference<{50 readonly listen: (address: {51 readonly hostname: string;52 readonly port: number;200 unmodified lines253 })254 );255 });256 252-const tokenFromStdin = Effect.gen(function* () {257+const firstLine = Effect.gen(function* () {258 const { stdin } = yield* Stdio.Stdio;259 260 const [line = ""] = yield* stdin.pipe(261 Stream.decodeText(),2 unmodified lines264 Stream.runCollect,265 Effect.orElseSucceed((): readonly string[] => [])266 );267 263- const token = line.trim();268+ return line.trim();269+});270 271+const tokenFromStdin = Effect.gen(function* () {272+ const token = yield* firstLine;273+274 if (token === "") {275 return yield* new LoginUsage({276 reason: `--token-stdin read no token: pipe it in, one line, e.g. ${Brand.cli} login --token-stdin < token.txt`,277 });85 unmodified lines363 returned: Deferred.await(returned),364 };365 });366 358-const TokenResponse = Schema.Struct({359- access_token: Schema.RedactedFromValue(Schema.NonEmptyString),360- token_type: Schema.String,361-});367+const refusedTrade = (url: string) =>368+ new LoginRefused({369+ reason: `${url}/token would not trade the sign-in for a token: run ${Brand.cli} login again`,370+ });371 363-const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);364-372 const exchange = (input: {373 readonly code: string;374 readonly redirectUri: string;375 readonly url: string;376 readonly verifier: string;377+}) => tradeCode(input).pipe(Effect.mapError(() => refusedTrade(input.url)));378+379+const authorizeAt = (input: {380+ readonly challenge: string;381+ readonly redirectUri: string;382+ readonly state: string;383+ readonly url: string;384 }) => {371- const refused = new LoginRefused({372- reason: `${input.url}/token would not trade the sign-in for a token: run ${Brand.cli} login again`,373- });385+ const authorize = new URL("/authorize", input.url);386 375- return Effect.gen(function* () {376- const client = yield* HttpClient.HttpClient;387+ authorize.search = new URLSearchParams({388+ client_id: cliClientIdOf(input.url),389+ code_challenge: input.challenge,390+ code_challenge_method: "S256",391+ redirect_uri: input.redirectUri,392+ response_type: "code",393+ state: input.state,394+ }).toString();395 378- const response = yield* client.execute(379- HttpClientRequest.post(`${input.url}/token`).pipe(380- HttpClientRequest.acceptJson,381- HttpClientRequest.bodyUrlParams({382- client_id: clientIdOf(input.url),383- code: input.code,384- code_verifier: input.verifier,385- grant_type: "authorization_code",386- redirect_uri: input.redirectUri,387- })388- )389- );390-391- if (response.status !== 200) {392- return yield* refused;393- }394-395- const body = yield* decodeTokenResponse(yield* response.json);396-397- if (body.token_type.toLowerCase() !== "bearer") {398- return yield* refused;399- }400-401- return body.access_token;402- }).pipe(403- Effect.provide(FetchHttpClient.layer),404- Effect.mapError(() => refused)405- );396+ return authorize;397 };398 399 const tokenFromBrowser = (url: string, opens: boolean) =>400 Effect.scoped(2 unmodified lines403 const verifier = yield* randomText(32);404 const state = yield* randomText(32);405 const { redirectUri, returned } = yield* loopback;406 416- const authorize = new URL("/authorize", url);417-418- authorize.search = new URLSearchParams({419- client_id: clientIdOf(url),420- code_challenge: yield* challengeOf(verifier),421- code_challenge_method: "S256",422- redirect_uri: redirectUri,423- response_type: "code",407+ const authorize = authorizeAt({408+ challenge: yield* challengeOf(verifier),409+ redirectUri,410 state,425- }).toString();411+ url,412+ });413 414 const query = yield* Effect.gen(function* () {415 yield* output.note(416 opens417 ? `Opening a browser to sign in to ${url}. If it does not open, visit:\n ${authorize.href}`431- : `To sign in to ${url}, open this in a browser:\n ${authorize.href}`418+ : `To sign in to ${url}, open this in a browser:\n ${authorize.href}\nIf the browser is on another machine, run ${Brand.cli} login --paste instead.`419 );420 421 if (opens) {422 yield* (yield* Browser).open(authorize.href);29 unmodified lines452 return yield* exchange({ code, redirectUri, url, verifier });453 })454 );455 456+/**457+ * For a browser that cannot reach this machine (over SSH, in a container): the458+ * sign-in ends on the platform's page, which shows a code to paste here. The459+ * code trades for a token only with the verifier this process holds, so a460+ * code read off that page is worth nothing to anyone else.461+ */462+const tokenFromPaste = (url: string, opens: boolean) =>463+ Effect.gen(function* () {464+ const output = yield* Output;465+ const verifier = yield* randomText(32);466+ const redirectUri = `${url}${CLI_CODE_PATH}`;467+468+ const authorize = authorizeAt({469+ challenge: yield* challengeOf(verifier),470+ redirectUri,471+ state: yield* randomText(32),472+ url,473+ });474+475+ yield* output.note(476+ `To sign in to ${url}, open this in a browser on any machine:\n ${authorize.href}\nThen paste the code it shows here, and press Enter:`477+ );478+479+ if (opens) {480+ yield* (yield* Browser).open(authorize.href);481+ }482+483+ const code = yield* firstLine.pipe(484+ Effect.timeoutOrElse({485+ duration: SIGN_IN_WAIT,486+ orElse: () =>487+ Effect.fail(488+ new LoginUsage({489+ reason: `no code was pasted within ${SIGN_IN_WAIT}: run ${Brand.cli} login --paste again`,490+ })491+ ),492+ })493+ );494+495+ if (code === "") {496+ return yield* new LoginUsage({497+ reason: `--paste read no code: paste the code the sign-in page shows, then press Enter`,498+ });499+ }500+501+ return yield* exchange({ code, redirectUri, url, verifier });502+ });503+504+// A token given by hand, a pasted code's, or the loopback's: one way per sign-in.505+const issuedFor = (506+ url: string,507+ way: {508+ readonly opens: boolean;509+ readonly paste: boolean;510+ readonly tokenStdin: boolean;511+ }512+) =>513+ Effect.gen(function* () {514+ if (way.paste && way.tokenStdin) {515+ return yield* new LoginUsage({516+ reason: `--paste and --token-stdin both read stdin: choose one`,517+ });518+ }519+520+ if (way.tokenStdin) {521+ const given: Issued = {522+ expiresAt: Option.none(),523+ refreshToken: Option.none(),524+ token: yield* tokenFromStdin,525+ };526+527+ return given;528+ }529+530+ return way.paste531+ ? yield* tokenFromPaste(url, way.opens)532+ : yield* tokenFromBrowser(url, way.opens);533+ });534+535 const verify = (url: string, token: Redacted.Redacted) =>536 Effect.scoped(537 Effect.gen(function* () {538 const client = yield* (yield* PlatformClient).connect({ token, url });57 unmodified lines596 Flag.withDescription(597 "Leave git's config alone; print the lines to set instead"598 )599 ),600+ paste: Flag.Boolean("paste").pipe(601+ Flag.withDefault(false),602+ Flag.withDescription(603+ "Sign in from a browser on another machine: it shows a code to paste here"604+ )605+ ),606 tokenStdin: Flag.Boolean("token-stdin").pipe(607 Flag.withDefault(false),608 Flag.withDescription(609 "Read a token you were given from stdin, one line, instead of signing in"13 unmodified lines623 const env = yield* currentEnv;624 const name = profileName(given.profile, env);625 const url = yield* platformOf(given.url, given.profile, env);626 555- const token = given.tokenStdin556- ? yield* tokenFromStdin557- : yield* tokenFromBrowser(558- url,559- !given.noBrowser && (yield* mayOpenBrowser(env))560- );627+ const issued = yield* issuedFor(url, {628+ opens: !given.noBrowser && (yield* mayOpenBrowser(env)),629+ paste: given.paste,630+ tokenStdin: given.tokenStdin,631+ });632 562- const handle = yield* verify(url, token);633+ const handle = yield* verify(url, issued.token);634 564- yield* credentials.put(name, { handle, token, url });635+ yield* credentials.put(name, {636+ ...Option.match(issued.expiresAt, {637+ onNone: () => ({}),638+ onSome: (expiresAt) => ({ expiresAt }),639+ }),640+ handle,641+ ...Option.match(issued.refreshToken, {642+ onNone: () => ({}),643+ onSome: (refreshToken) => ({ refreshToken }),644+ }),645+ token: issued.token,646+ url,647+ });648 649 const commands = gitHelperConfig(url);650 651 if (!given.noGitConfig) {72 unmodified lines724 const output = yield* Output;725 const credentials = yield* Credentials;726 const env = yield* currentEnv;727 const name = profileName(given.profile, env);645- const removed = yield* credentials.remove(name);728+ const kept = yield* credentials.remove(name);729+ const removed = Option.isSome(kept);730 731+ // A browser sign-in's grant ends at the platform too, so a copy of its token lives no longer than this file's did.732+ const revoked = yield* Option.match(733+ Option.flatMap(kept, (profile) =>734+ Option.map(Option.fromUndefinedOr(profile.refreshToken), (token) => ({735+ token,736+ url: profile.url,737+ }))738+ ),739+ {740+ onNone: () => Effect.succeed(false),741+ onSome: ({ token, url }) =>742+ revoke(url, token, "refresh_token").pipe(743+ Effect.orElseSucceed(() => false)744+ ),745+ }746+ );747+748 // git keeps asking the helper for a platform another profile is still on.749 const unused: string[] = [];750 751 for (const url of yield* helperUrls(env)) {14 unmodified lines766 }767 768 yield* output.success({769 command: "logout",669- data: { gitConfig: commands, profile: name, removed },770+ data: { gitConfig: commands, profile: name, removed, revoked },771 json: given.json,772 view: viewOf(672- `${removed ? `Logged out: profile ${name} removed.` : `No profile ${name} to remove.`}${773+ `${removed ? `Logged out: profile ${name} removed${revoked ? ", and its sign-in ended on the platform" : ""}.` : `No profile ${name} to remove.`}${774 commands.length === 0775 ? ""776 : ` git no longer asks ${Brand.cli} for ${unused.join(", ")}; its global config lost:`777 }`,9 unmodified linesmodified:apps/cli/src/credentials.ts+116 added-14 removed
1 import { Brand } from "@repo/brand";2 import { Handle } from "@repo/protocol/ids";3 import {4 Array,5+ Clock,6 Config,7 Context,8+ Duration,9 Effect,10 FileSystem,11 Layer,12 Option,13 Order,14 Path,15+ Redacted,16 Schema,17 } from "effect";18 19+import { renew } from "./oauth-token.ts";20+21+// A browser sign-in keeps the token's lapse, in epoch milliseconds, and the22+// refresh token that renews it; a token given by hand keeps neither, and lasts23+// as long as the platform lets it.24 export const Profile = Schema.Struct({25+ expiresAt: Schema.optionalKey(Schema.Int),26 handle: Schema.optionalKey(Handle),27+ refreshToken: Schema.optionalKey(28+ Schema.RedactedFromValue(Schema.NonEmptyString)29+ ),30 token: Schema.RedactedFromValue(Schema.NonEmptyString),31 url: Schema.NonEmptyString,32 });33 16 unmodified lines50 readonly put: (51 name: string,52 profile: Profile53 ) => Effect.Effect<void, CredentialsUnwritable>;54+ // The profile it removed, if there was one.55 readonly remove: (56 name: string44- ) => Effect.Effect<boolean, CredentialsUnwritable>;57+ ) => Effect.Effect<Option.Option<Profile>, CredentialsUnwritable>;58 }59 >()("cli/Credentials") {}60 61 const Store = Schema.fromJsonString(22 unmodified lines84 const FILE_MODE = 0o600;85 86 const DIR_MODE = 0o700;87 88+/** Renewed this long before it lapses, so no call carries a token that dies on the way. */89+export const RENEW_MARGIN = Duration.minutes(1);90+91+const sameToken = (one: Redacted.Redacted, other: Redacted.Redacted) =>92+ Redacted.value(one) === Redacted.value(other);93+94 /** Replaced whole on every write so no reader sees half of one. */95 export const CredentialsFile = Layer.effect(Credentials)(96 Effect.gen(function* () {97 const fs = yield* FileSystem.FileSystem;60 unmodified lines158 })159 )160 );161 162+ /**163+ * A stored profile whose token is about to lapse, renewed and written back.164+ * When the platform refuses the renewal, another process (git's helper, a165+ * second command) may have renewed it first, so the file is read again; if166+ * it holds no newer token, the old one is handed back, and the call it167+ * carries is refused as signed out.168+ */169+ const fresh = (name: string, profile: Profile) =>170+ Effect.gen(function* () {171+ const now = yield* Clock.currentTimeMillis;172+173+ if (174+ profile.refreshToken === undefined ||175+ profile.expiresAt === undefined ||176+ profile.expiresAt - Duration.toMillis(RENEW_MARGIN) > now177+ ) {178+ return profile;179+ }180+181+ const { refreshToken } = profile;182+183+ const issued = yield* renew(profile.url, refreshToken).pipe(184+ Effect.option185+ );186+187+ if (Option.isNone(issued)) {188+ const latest = Option.fromNullishOr((yield* readable)[name]);189+190+ return Option.match(191+ Option.filter(192+ latest,193+ (kept) =>194+ kept.url === profile.url &&195+ !sameToken(kept.token, profile.token)196+ ),197+ { onNone: () => profile, onSome: (kept) => kept }198+ );199+ }200+201+ const renewed: Profile = {202+ ...profile,203+ ...Option.match(issued.value.expiresAt, {204+ onNone: () => ({}),205+ onSome: (expiresAt) => ({ expiresAt }),206+ }),207+ refreshToken: Option.getOrElse(208+ issued.value.refreshToken,209+ () => refreshToken210+ ),211+ token: issued.value.token,212+ };213+214+ // The renewal stands even if the file cannot take it: this call carries it.215+ yield* Effect.flatMap(load, (profiles) =>216+ save({ ...profiles, [name]: renewed })217+ ).pipe(Effect.ignore);218+219+ return renewed;220+ });221+222 const current = Option.match(fromEnv, {223 onNone: () =>145- Effect.map(readable, (profiles) =>146- Option.fromNullishOr(profiles[named])224+ Effect.flatMap(readable, (profiles) =>225+ Option.match(Option.fromNullishOr(profiles[named]), {226+ onNone: () => Effect.succeedNone,227+ onSome: (profile) => Effect.asSome(fresh(named, profile)),228+ })229 ),230 onSome: (profile) => Effect.succeedSome(profile),231 });232 233 return {234 current,235 forHost: (host) =>154- Effect.map(readable, (profiles) => {236+ Effect.flatMap(readable, (profiles) => {237 const stored = Array.sort(Object.keys(profiles), Order.String)238 .toSorted(239 (one, other) => Number(other === named) - Number(one === named)240 )241 .flatMap((name) =>160- Option.toArray(Option.fromNullishOr(profiles[name]))242+ Option.toArray(243+ Option.map(244+ Option.fromNullishOr(profiles[name]),245+ (profile) => [Option.some(name), profile] as const246+ )247+ )248 );249 163- return Array.findFirst(164- [...Option.toArray(fromEnv), ...stored],165- (profile) =>250+ const found = Array.findFirst(251+ [252+ ...Option.toArray(253+ Option.map(254+ fromEnv,255+ (profile) => [Option.none<string>(), profile] as const256+ )257+ ),258+ ...stored,259+ ],260+ ([, profile]) =>261 Option.contains(hostOf(profile.url), host.toLowerCase())262 );263+264+ return Option.match(found, {265+ onNone: () => Effect.succeedNone,266+ onSome: ([name, profile]) =>267+ Option.match(name, {268+ onNone: () => Effect.succeedSome(profile),269+ onSome: (at) => Effect.asSome(fresh(at, profile)),270+ }),271+ });272 }),273 put: (name, profile) =>274 Effect.flatMap(load, (profiles) =>275 save({ ...profiles, [name]: profile })276 ),277 remove: (name) =>278 Effect.flatMap(load, (profiles) => {175- if (!Object.hasOwn(profiles, name)) {176- return Effect.succeed(false);177- }279+ const { [name]: removed, ...rest } = profiles;280 179- const { [name]: _removed, ...rest } = profiles;180-181- return Effect.as(save(rest), true);281+ return removed === undefined282+ ? Effect.succeedNone283+ : Effect.as(save(rest), Option.some(removed));284 }),285 };286 })287 );23 unmodified linesadded:apps/cli/src/oauth-token.ts+113 added
1+// The platform's token endpoint, as the CLI's own OAuth client calls it: to2+// trade a sign-in's code, to renew a token with its refresh token, and to3+// revoke a grant at logout. Every token stays `Redacted`; it is written out4+// only in the form that carries it to the endpoint.5+import { Clock, Effect, Option, Redacted, Schema } from "effect";6+import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";7+8+export const CLI_CLIENT_PATH = "/oauth/cli";9+10+// Where the platform shows a code to paste: its page for a browser on another machine.11+export const CLI_CODE_PATH = "/oauth/cli/code";12+13+export const cliClientIdOf = (origin: string) => `${origin}${CLI_CLIENT_PATH}`;14+15+const Secret = Schema.RedactedFromValue(Schema.NonEmptyString);16+17+const TokenAnswer = Schema.Struct({18+ access_token: Secret,19+ expires_in: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),20+ refresh_token: Schema.optionalKey(Secret),21+ token_type: Schema.String,22+});23+24+const decodeTokenAnswer = Schema.decodeUnknownEffect(TokenAnswer);25+26+export class TokenRefused extends Schema.TaggedError<TokenRefused>()(27+ "TokenRefused",28+ {}29+) {}30+31+/** What the endpoint issued: a token, and when it lapses and how to renew it, where it says. */32+export interface Issued {33+ readonly expiresAt: Option.Option<number>;34+ readonly refreshToken: Option.Option<Redacted.Redacted>;35+ readonly token: Redacted.Redacted;36+}37+38+const post = (url: string, fields: Readonly<Record<string, string>>) =>39+ Effect.gen(function* () {40+ const client = yield* HttpClient.HttpClient;41+42+ return yield* client.execute(43+ HttpClientRequest.post(`${url}/token`).pipe(44+ HttpClientRequest.acceptJson,45+ HttpClientRequest.bodyUrlParams(fields)46+ )47+ );48+ }).pipe(Effect.provide(FetchHttpClient.layer));49+50+const issue = (url: string, fields: Readonly<Record<string, string>>) =>51+ Effect.gen(function* () {52+ const response = yield* post(url, fields);53+54+ if (response.status !== 200) {55+ return yield* new TokenRefused();56+ }57+58+ const answer = yield* decodeTokenAnswer(yield* response.json);59+60+ if (answer.token_type.toLowerCase() !== "bearer") {61+ return yield* new TokenRefused();62+ }63+64+ const now = yield* Clock.currentTimeMillis;65+66+ const issued: Issued = {67+ expiresAt: Option.map(68+ Option.fromUndefinedOr(answer.expires_in),69+ (seconds) => now + seconds * 100070+ ),71+ refreshToken: Option.fromUndefinedOr(answer.refresh_token),72+ token: answer.access_token,73+ };74+75+ return issued;76+ }).pipe(Effect.mapError(() => new TokenRefused()));77+78+export const tradeCode = (input: {79+ readonly code: string;80+ readonly redirectUri: string;81+ readonly url: string;82+ readonly verifier: string;83+}) =>84+ issue(input.url, {85+ client_id: cliClientIdOf(input.url),86+ code: input.code,87+ code_verifier: input.verifier,88+ grant_type: "authorization_code",89+ redirect_uri: input.redirectUri,90+ });91+92+export const renew = (url: string, refreshToken: Redacted.Redacted) =>93+ issue(url, {94+ client_id: cliClientIdOf(url),95+ grant_type: "refresh_token",96+ refresh_token: Redacted.value(refreshToken),97+ });98+99+/**100+ * Revoking a refresh token ends its whole grant, the access tokens it gave101+ * included (RFC 7009). Best effort: a platform out of reach changes nothing102+ * here, and the token lapses on its own.103+ */104+export const revoke = (105+ url: string,106+ token: Redacted.Redacted,107+ hint: "access_token" | "refresh_token"108+) =>109+ post(url, {110+ client_id: cliClientIdOf(url),111+ token: Redacted.value(token),112+ token_type_hint: hint,113+ }).pipe(Effect.map((response) => response.status === 200));modified:apps/cli/src/remote.ts+32 added-16 removed
55 unmodified lines56 )57 )58 );59 60-const over = (origin: string, token: Option.Option<Redacted.Redacted>) =>60+// The token is read for each request, not once: `mcp` serves for hours, and61+// the stored token is renewed under it as it nears its lapse.62+const over = (63+ origin: string,64+ token: Effect.Effect<Option.Option<Redacted.Redacted>>65+) =>66 Layer.effect(Client)(RpcClient.make(Contracts)).pipe(67 Layer.provide(SignedIn),68 Layer.provide(69 Layer.effect(RpcClient.Protocol)(4 unmodified lines74 HttpClientRequest.prependUrl(75 `${origin.replace(/\/+$/u, "")}/rpc`76 )77 ),78+ HttpClient.mapRequestEffect((request) =>73- HttpClient.mapRequest((request) =>74- Option.match(token, {75- onNone: () => request,76- onSome: (bearer) =>77- HttpClientRequest.bearerToken(78- request,79- Redacted.value(bearer)80- ),81- })79+ Effect.map(token, (bearer) =>80+ Option.match(bearer, {81+ onNone: () => request,82+ onSome: (value) =>83+ HttpClientRequest.bearerToken(84+ request,85+ Redacted.value(value)86+ ),87+ })88+ )89 ),90 // Any status but 2xx fails as itself, so a 401 is told apart.91 HttpClient.filterStatusOk92 )6 unmodified lines99 100 export const RemoteClient: Layer.Layer<Client, never, Credentials> =101 Layer.unwrap(102 Effect.gen(function* () {96- const profile = yield* Effect.flatMap(97- Effect.service(Credentials),98- (credentials) => credentials.current99- );103+ const credentials = yield* Credentials;104 105+ const profile = yield* credentials.current;106+107 if (Option.isSome(profile)) {102- return over(profile.value.url, Option.some(profile.value.token));108+ const { url } = profile.value;109+110+ return over(111+ url,112+ Effect.map(credentials.current, (now) =>113+ Option.map(114+ Option.filter(now, (kept) => kept.url === url),115+ ({ token }) => token116+ )117+ )118+ );119 }120 121 const url = yield* Config.option(122 Config.NonEmptyString(URL_VARIABLE)1 unmodified line124 125 // With nothing naming a platform, the platform itself, as anyone.126 return over(127 Option.getOrElse(url, () => Brand.platformUrl),112- Option.none()128+ Effect.succeedNone129 );130 })131 );modified:apps/cli/src/render.ts+11 added
4 unmodified lines5 Claim,6 Credits,7 Finish,8 FrontPage,9+ Land,10 LedgerOf,11 ListAsks,12 ListDiscussions,13 ListProjects,615 unmodified lines629 const submitted = viewOf(SubmitAnswer.successSchema, receipt);630 631 const finished = viewOf(Finish.successSchema, receipt);632 633+// The checks run after `land` returns; the same request sent again reads where they stand.634+const landing = viewOf(Land.successSchema, ({ head, outcome, requestId }) =>635+ prose(636+ Outcome.guards.Checking(outcome)637+ ? `checking ${short(head)} (${outcome.stage}); follow with the same \`${Brand.cli} land\`, --requestId ${requestId} and all, which checks nothing twice`638+ : `${short(head)}: ${outcomeText(outcome)}`639+ )640+);641+642 const isReceipt = Schema.is(LandReceipt);643 644 /** `finish` and `land` refuse stages 0–1 inside a success's receipt; the command prints them as refusals and exits 1. */645 export const refusalsIn = (7 unmodified lines653 export const views = {654 credits,655 finish: finished,656 frontPage: front,657+ land: landing,658 ledger,659 listAsks: asks,660 listDiscussions: discussions,661 listProjects: projects,17 unmodified linesmodified:apps/cli/test/local/login.test.ts+177 added-1 removed
13 unmodified lines14 import {15 Clock,16 ConfigProvider,17 Context,18+ Deferred,19 Effect,20 Exit,21 Fiber,22 FileSystem,164 unmodified lines187 interface Run {188 readonly env: Record<string, string>;189 readonly seams: Layer.Layer<never>;190 readonly stdin?: string;191+ // Read in place of `stdin`, for a test that types into it later.192+ readonly typed?: Stream.Stream<Uint8Array>;193 readonly terminal?: boolean;194 }195 196 const cli = (argv: readonly string[], run: Run) =>10 unmodified lines207 ConfigProvider.layer(ConfigProvider.fromEnv({ env: run.env })),208 run.seams209 ).pipe(Layer.provideMerge(NodeServices.layer)),210 Stdio.layerTest({211+ stdin:212+ run.typed ??208- stdin: Stream.make(new TextEncoder().encode(run.stdin ?? "")),213+ Stream.make(new TextEncoder().encode(run.stdin ?? "")),214 stdoutIsTerminal: Effect.succeed(run.terminal ?? false),215 }),216 noTerminal217 )541 unmodified lines759 30_000760 );761 });762 763+const renewalOf = (env: Record<string, string>, name: string) =>764+ Effect.provide(765+ Effect.flatMap(Effect.service(Credentials), ({ current }) => current),766+ credentialsIn({ ...env, [`${SLUG}_PROFILE`]: name })767+ ).pipe(768+ Effect.map(769+ Option.map(({ expiresAt, refreshToken }) => ({770+ expiresAt,771+ refreshToken:772+ refreshToken === undefined ? undefined : Redacted.value(refreshToken),773+ }))774+ )775+ );776+777+describe(`${Brand.cli} login's grant`, () => {778+ it.live(779+ "keeps the refresh token and when the token lapses, and logout ends the grant on the platform",780+ () =>781+ Effect.gen(function* () {782+ const env = yield* home;783+ const server = yield* oauthServer({ token: issued });784+ const platform = yield* seams(signedInAs("alice"));785+ const run = { env, seams: platform.layer };786+ const before = yield* Clock.currentTimeMillis;787+788+ const fiber = yield* Effect.forkChild(789+ cli(["login", "--url", server.origin, "--no-browser"], run)790+ );791+792+ yield* visit(yield* signInUrl(server.origin));793+794+ expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();795+796+ const renewal = yield* renewalOf(env, "default");797+798+ expect(799+ Option.map(renewal, ({ expiresAt, refreshToken }) => ({800+ lapses:801+ expiresAt !== undefined &&802+ expiresAt >= before + 3_600_000 &&803+ expiresAt <= before + 3_600_000 + 60_000,804+ refreshToken,805+ }))806+ ).toStrictEqual(807+ Option.some({ lapses: true, refreshToken: "refresh-1" })808+ );809+810+ expect(Exit.isSuccess(yield* cli(["logout"], run))).toBeTruthy();811+ expect({812+ live: yield* server.live,813+ revoked: (yield* server.revocations).map((form) => ({ ...form })),814+ }).toStrictEqual({815+ live: [],816+ revoked: [817+ {818+ client_id: `${server.origin}/oauth/cli`,819+ token: "refresh-1",820+ token_type_hint: "refresh_token",821+ },822+ ],823+ });824+ expect((yield* printed).stdout.join("\n")).toContain(825+ "its sign-in ended on the platform"826+ );827+ }).pipe(Effect.scoped, Effect.provide(testServices)),828+ 30_000829+ );830+831+ it.live(832+ "asks the platform to end no grant for a token given by hand",833+ () =>834+ Effect.gen(function* () {835+ const env = yield* home;836+ const server = yield* oauthServer({ token: issued });837+ const platform = yield* seams(signedInAs("alice"));838+ const run = { env, seams: platform.layer, stdin: `${given}\n` };839+840+ yield* cli(["login", "--url", server.origin, "--token-stdin"], run);841+842+ expect(Exit.isSuccess(yield* cli(["logout"], run))).toBeTruthy();843+ expect(yield* server.revocations).toStrictEqual([]);844+ }).pipe(Effect.scoped, Effect.provide(testServices)),845+ 30_000846+ );847+});848+849+// Where the platform's code page would show the code: the sign-in's last redirect, not followed.850+const shownCode = (at: string) =>851+ Effect.gen(function* () {852+ const client = yield* HttpClient.HttpClient;853+ const response = yield* client.get(at);854+855+ return new URL(response.headers.location ?? "").searchParams.get("code");856+ }).pipe(857+ Effect.provide(858+ FetchHttpClient.layer.pipe(859+ Layer.provide(860+ Layer.succeed(FetchHttpClient.RequestInit, { redirect: "manual" })861+ )862+ )863+ )864+ );865+866+describe(`${Brand.cli} login --paste`, () => {867+ it.live(868+ "ends the sign-in on the platform's code page, reads the pasted code, and keeps the token it trades for",869+ () =>870+ Effect.gen(function* () {871+ const env = yield* home;872+ const server = yield* oauthServer({ token: issued });873+ const platform = yield* seams(signedInAs("alice"));874+ const pasted = yield* Deferred.make<Uint8Array>();875+876+ const fiber = yield* Effect.forkChild(877+ cli(["login", "--url", server.origin, "--paste"], {878+ env,879+ seams: platform.layer,880+ typed: Stream.fromEffect(Deferred.await(pasted)),881+ })882+ );883+884+ const shown = yield* signInUrl(server.origin);885+ const code = yield* shownCode(shown);886+887+ yield* Deferred.succeed(888+ pasted,889+ new TextEncoder().encode(` ${code ?? ""} \n`)890+ );891+892+ expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();893+894+ const [query] = yield* server.authorizations;895+896+ expect({897+ kept: yield* stored(env, "default"),898+ listened: yield* platform.listened,899+ redirect: query?.get("redirect_uri"),900+ }).toStrictEqual({901+ kept: Option.some({902+ handle: "alice",903+ token: issued,904+ url: server.origin,905+ }),906+ listened: [],907+ redirect: `${server.origin}/oauth/cli/code`,908+ });909+ }).pipe(Effect.scoped, Effect.provide(testServices)),910+ 30_000911+ );912+913+ it.live(914+ "refuses --paste beside --token-stdin, which both read stdin",915+ () =>916+ Effect.gen(function* () {917+ const env = yield* home;918+ const platform = yield* seams(signedInAs("alice"));919+920+ const exit = yield* cli(["login", "--paste", "--token-stdin"], {921+ env,922+ seams: platform.layer,923+ stdin: `${given}\n`,924+ });925+926+ expect(Exit.isFailure(exit)).toBeTruthy();927+ expect((yield* printed).stderr.join("\n")).toContain("choose one");928+ expect(yield* platform.connected).toStrictEqual([]);929+ }).pipe(Effect.scoped, Effect.provide(testServices)),930+ 30_000931+ );932+});933+934 describe(`${Brand.cli} logout`, () => {935 it.live(936 "removes the profile and the git config that names the helper for its platform",937 () =>80 unmodified linesmodified:apps/cli/test/credentials.test.ts+145 added-2 removed
17 unmodified lines18 CredentialsUnwritable,19 gitHelperConfig,20 } from "../src/credentials.ts";21 import type { Profile } from "../src/credentials.ts";22+import { oauthServer, refreshTokenOf, renewedTokenOf } from "./oauth-server.ts";23 24 const SLUG = Brand.slug.toUpperCase();25 26 const token = "tok-default-0123456789abcdefghijklmnopqrstuvwxyz";126 unmodified lines153 const credentials = yield* credentialsIn(env);154 155 yield* credentials.put("default", defaultProfile);156 156- expect(yield* credentials.remove("default")).toBeTruthy();157- expect(yield* credentials.remove("default")).toBeFalsy();157+ expect(Option.isSome(yield* credentials.remove("default"))).toBeTruthy();158+ expect(yield* credentials.remove("default")).toStrictEqual(Option.none());159 expect(yield* credentials.current).toStrictEqual(Option.none());160 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))161 );162 39 unmodified lines202 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))203 );204 });205 206+const kept = (profile: Option.Option<Profile>) =>207+ Option.map(profile, ({ refreshToken, token: secret }) => ({208+ refreshToken:209+ refreshToken === undefined ? undefined : Redacted.value(refreshToken),210+ token: Redacted.value(secret),211+ }));212+213+describe("a stored browser sign-in, near its token's lapse", () => {214+ const signedIn = "tok-signed-in-0123456789abcdefghijklmnopqrstuvwxyz";215+216+ const given = "refresh-given";217+218+ // A profile as `login` keeps it, its token lapsing `in` milliseconds from now.219+ const browserProfile = (url: string, lapsesIn: number) =>220+ Effect.map(221+ Effect.clockWith((clock) => clock.currentTimeMillis),222+ (now): Profile => ({223+ expiresAt: now + lapsesIn,224+ handle: Handle.make("oscar"),225+ refreshToken: Redacted.make(given),226+ token: Redacted.make(signedIn),227+ url,228+ })229+ );230+231+ it.live(232+ "is renewed by its refresh token when read, and the renewal is written back",233+ () =>234+ Effect.gen(function* () {235+ const server = yield* oauthServer({ given, token: signedIn });236+ const { env } = yield* configHome;237+ const credentials = yield* credentialsIn(env);238+239+ yield* credentials.put(240+ "default",241+ yield* browserProfile(server.origin, 30_000)242+ );243+244+ const read = yield* credentials.current;245+ const again = yield* (yield* credentialsIn(env)).current;246+247+ const renewed = {248+ refreshToken: refreshTokenOf(1),249+ token: renewedTokenOf(signedIn, 0),250+ };251+252+ expect({253+ again: kept(again),254+ asked: (yield* server.renewals).map((form) => ({ ...form })),255+ read: kept(read),256+ }).toStrictEqual({257+ again: Option.some(renewed),258+ asked: [259+ {260+ client_id: `${server.origin}/oauth/cli`,261+ grant_type: "refresh_token",262+ refresh_token: given,263+ },264+ ],265+ read: Option.some(renewed),266+ });267+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))268+ );269+270+ it.live("is renewed when git's helper finds it by host, too", () =>271+ Effect.gen(function* () {272+ const server = yield* oauthServer({ given, token: signedIn });273+ const { env } = yield* configHome;274+ const credentials = yield* credentialsIn(env);275+276+ yield* credentials.put("alice", yield* browserProfile(server.origin, 0));277+278+ expect(279+ kept(yield* credentials.forHost(new URL(server.origin).host))280+ ).toStrictEqual(281+ Option.some({282+ refreshToken: refreshTokenOf(1),283+ token: renewedTokenOf(signedIn, 0),284+ })285+ );286+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))287+ );288+289+ it.live("is left alone while its token has more than a minute to live", () =>290+ Effect.gen(function* () {291+ const server = yield* oauthServer({ given, token: signedIn });292+ const { env } = yield* configHome;293+ const credentials = yield* credentialsIn(env);294+295+ yield* credentials.put(296+ "default",297+ yield* browserProfile(server.origin, 10 * 60_000)298+ );299+300+ expect(kept(yield* credentials.current)).toStrictEqual(301+ Option.some({ refreshToken: given, token: signedIn })302+ );303+ expect(yield* server.renewals).toStrictEqual([]);304+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))305+ );306+307+ it.live(308+ "keeps its token when the platform refuses the renewal, so the call it carries is refused as signed out",309+ () =>310+ Effect.gen(function* () {311+ const server = yield* oauthServer({312+ given,313+ refuseRenewals: true,314+ token: signedIn,315+ });316+317+ const { env } = yield* configHome;318+ const credentials = yield* credentialsIn(env);319+320+ yield* credentials.put(321+ "default",322+ yield* browserProfile(server.origin, 0)323+ );324+325+ expect(kept(yield* credentials.current)).toStrictEqual(326+ Option.some({ refreshToken: given, token: signedIn })327+ );328+ expect(yield* server.renewals).toHaveLength(1);329+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))330+ );331+332+ it.live(333+ "never renews a token given by hand, which has no refresh token",334+ () =>335+ Effect.gen(function* () {336+ const { env } = yield* configHome;337+ const credentials = yield* credentialsIn(env);338+339+ yield* credentials.put("default", defaultProfile);340+341+ expect(seen(yield* credentials.current)).toStrictEqual(342+ seen(Option.some(defaultProfile))343+ );344+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))345+ );346+});347+348 describe("git's credential helper config", () => {349 it("names this CLI's helper for the platform's url alone, after clearing any other, with the repo path", () => {350 const url = "https://platform-dev.example.workers.dev";351 21 unmodified linesadded:apps/cli/test/land-view.test.ts+60 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Brand } from "@repo/brand";3+import type { Land } from "@repo/protocol/contracts";4+import { Outcome } from "@repo/protocol/domain/outcome";5+import {6+ CommitSha,7+ LandedSha,8+ ProjectName,9+ RequestId,10+} from "@repo/protocol/ids";11+import { StaleBase } from "@repo/protocol/refusal";12+import { Option } from "effect";13+14+import { refusalsIn, views } from "../src/render.ts";15+16+const base = CommitSha.make("4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c");17+18+const head = CommitSha.make("9f1e3d5c7b9a1f3e5d7c9b1a3f5e7d9c1b3a5f7e");19+20+const main = LandedSha.make("2b4d6f8a0c2e4a6c8e0b2d4f6a8c0e2b4d6f8a0c");21+22+type Receipt = typeof Land.successSchema.Type;23+24+const receiptWith = (outcome: Outcome): Receipt => ({25+ base,26+ head,27+ outcome,28+ project: ProjectName.make("alice/datekit"),29+ requestId: RequestId.make("land-alice-01"),30+});31+32+const textOf = (receipt: Receipt) =>33+ Option.match(views.land(receipt), {34+ onNone: () => "",35+ onSome: ({ markdown, text }) => text ?? markdown,36+ });37+38+describe("a land's receipt", () => {39+ it("while its checks run, says so and how to follow it with the same request", () => {40+ expect(41+ textOf(receiptWith(Outcome.cases.Checking.make({ stage: "merge" })))42+ ).toBe(43+ `checking 9f1e3d5 (merge); follow with the same \`${Brand.cli} land\`, --requestId land-alice-01 and all, which checks nothing twice`44+ );45+ });46+47+ it("once it lands, names the landing", () => {48+ expect(textOf(receiptWith(Outcome.cases.Landed.make({ sha: main })))).toBe(49+ "9f1e3d5: landed as 2b4d6f8"50+ );51+ });52+53+ it("refused, is the command's refusal, as finish's is", () => {54+ const stale = new StaleBase({ base, conflicts: [], main });55+56+ expect(57+ refusalsIn(receiptWith(Outcome.cases.Refused.make({ refusals: [stale] })))58+ ).toStrictEqual([stale]);59+ });60+});modified:apps/cli/test/oauth-server.ts+110 added-27 removed
3 unmodified lines4 5 export interface OAuthServerOptions {6 readonly token: string;7 readonly state?: "same" | "other";8+ // Refuse every renewal, as a platform does once the grant has ended.9+ readonly refuseRenewals?: boolean;10+ // A refresh token it gave out before the test began.11+ readonly given?: string;12 }13 14 interface Grant {15 readonly challenge: string;16 readonly clientId: string;17 readonly redirectUri: string;18 }19 16-const TokenForm = Schema.Struct({17- client_id: Schema.String,18- code: Schema.String,19- code_verifier: Schema.String,20- grant_type: Schema.String,21- redirect_uri: Schema.String,22-});20+const TokenForm = Schema.Record(Schema.String, Schema.String);21 22 /** Base64url without padding, as RFC 7636 §4.2 spells the S256 challenge. */23 const base64url = (bytes: Uint8Array) =>24 btoa(String.fromCodePoint(...bytes))11 unmodified lines36 37 const refused = (error: string) =>38 HttpServerResponse.jsonUnsafe({ error }, { status: 400 });39 40+export const refreshTokenOf = (count: number) => `refresh-${count}`;41+42+export const renewedTokenOf = (token: string, count: number) =>43+ `${token}-renewed-${count}`;44+45+/**46+ * An authorization server as the platform's behaves for the CLI: PKCE codes,47+ * then refresh tokens that rotate on each renewal, the one just replaced still48+ * taken once, and revocation of a whole grant by any of its refresh tokens.49+ */50 export const oauthServer = (options: OAuthServerOptions) =>51 Effect.gen(function* () {52 const grants = yield* Ref.make<ReadonlyMap<string, Grant>>(new Map());53 const authorizations = yield* Ref.make<readonly URLSearchParams[]>([]);54+ const renewals = yield* Ref.make<readonly Record<string, string>[]>([]);55+ const revocations = yield* Ref.make<readonly Record<string, string>[]>([]);56 const issued = yield* Ref.make(0);57+ const refreshes = yield* Ref.make(0);58 59+ // The refresh tokens still taken: the current one and the one before it.60+ const live = yield* Ref.make<readonly string[]>(61+ options.given === undefined ? [] : [options.given]62+ );63+64+ // Seconds each token lives, as the platform's default says.65+ const lifetime = 3600;66+67+ const tokens = (accessToken: string) =>68+ Effect.gen(function* () {69+ const count = yield* Ref.updateAndGet(refreshes, (n) => n + 1);70+ const refreshToken = refreshTokenOf(count);71+72+ yield* Ref.update(live, (all) => [...all.slice(-1), refreshToken]);73+74+ return HttpServerResponse.jsonUnsafe({75+ access_token: accessToken,76+ expires_in: lifetime,77+ refresh_token: refreshToken,78+ token_type: "bearer",79+ });80+ });81+82 const authorize = (query: URLSearchParams) =>83 Effect.gen(function* () {84 yield* Ref.update(authorizations, (all) => [...all, query]);85 30 unmodified lines116 117 return HttpServerResponse.redirect(back.href, { status: 302 });118 });119 86- const token = Effect.gen(function* () {87- const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);88- const grant = (yield* Ref.get(grants)).get(form.code);120+ const traded = (form: Readonly<Record<string, string>>) =>121+ Effect.gen(function* () {122+ const code = form.code ?? "";123+ const grant = (yield* Ref.get(grants)).get(code);124 90- yield* Ref.update(grants, (all) => {91- const left = new Map(all);125+ yield* Ref.update(grants, (all) => {126+ const left = new Map(all);127 93- left.delete(form.code);128+ left.delete(code);129 95- return left;130+ return left;131+ });132+133+ if (134+ grant === undefined ||135+ grant.clientId !== form.client_id ||136+ grant.redirectUri !== form.redirect_uri ||137+ (yield* s256(form.code_verifier ?? "")) !== grant.challenge138+ ) {139+ return refused("invalid_grant");140+ }141+142+ return yield* tokens(options.token);143 });144 98- if (99- form.grant_type !== "authorization_code" ||100- grant === undefined ||101- grant.clientId !== form.client_id ||102- grant.redirectUri !== form.redirect_uri ||103- (yield* s256(form.code_verifier)) !== grant.challenge104- ) {105- return refused("invalid_grant");106- }145+ const renewed = (form: Readonly<Record<string, string>>) =>146+ Effect.gen(function* () {147+ yield* Ref.update(renewals, (all) => [...all, form]);148 108- return HttpServerResponse.jsonUnsafe({109- access_token: options.token,110- token_type: "bearer",149+ const presented = form.refresh_token ?? "";150+151+ if (152+ options.refuseRenewals === true ||153+ !(yield* Ref.get(live)).includes(presented)154+ ) {155+ return refused("invalid_grant");156+ }157+158+ return yield* tokens(159+ renewedTokenOf(options.token, yield* Ref.get(refreshes))160+ );161 });162+163+ const revoked = (form: Readonly<Record<string, string>>) =>164+ Effect.gen(function* () {165+ yield* Ref.update(revocations, (all) => [...all, form]);166+167+ if ((yield* Ref.get(live)).includes(form.token ?? "")) {168+ yield* Ref.set(live, []);169+ }170+171+ return HttpServerResponse.empty({ status: 200 });172+ });173+174+ const token = Effect.gen(function* () {175+ const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);176+177+ if (form.grant_type === "authorization_code") {178+ return yield* traded(form);179+ }180+181+ if (form.grant_type === "refresh_token") {182+ return yield* renewed(form);183+ }184+185+ return form.grant_type === undefined && form.token !== undefined186+ ? yield* revoked(form)187+ : refused("unsupported_grant_type");188 }).pipe(Effect.orElseSucceed(() => refused("invalid_request")));189 190 const app = Effect.gen(function* () {191 const request = yield* HttpServerRequest.HttpServerRequest;20 unmodified lines212 "port" in address213 ? `http://127.0.0.1:${address.port}`214 : yield* Effect.die("the test server listens on a socket, not a port");215 140- return { authorizations: Ref.get(authorizations), origin };216+ return {217+ authorizations: Ref.get(authorizations),218+ // The refresh tokens it still takes.219+ live: Ref.get(live),220+ origin,221+ renewals: Ref.get(renewals),222+ revocations: Ref.get(revocations),223+ };224 });modified:apps/cli/test/remote.test.ts+36 added-2 removed
1 unmodified line2 import { Brand } from "@repo/brand";3 import { Contracts } from "@repo/protocol/contracts";4 import { AskId, Handle, KindName } from "@repo/protocol/ids";5 import { unanswered } from "@repo/protocol/testing";6-import { ConfigProvider, Effect, Layer, Option, Redacted } from "effect";6+import { ConfigProvider, Effect, Layer, Option, Redacted, Ref } from "effect";7 import { FetchHttpClient } from "effect/http";8 9 import { Credentials } from "../src/credentials.ts";10 import type { Profile } from "../src/credentials.ts";34 unmodified lines45 Layer.succeed(Credentials)({46 current: Effect.succeed(profile),47 forHost: () => Effect.succeed(profile),48 put: () => Effect.void,49- remove: () => Effect.succeed(false),49+ remove: () => Effect.succeedNone,50 });51 52 const profileOn = (url: string, token: string): Profile => ({53 token: Redacted.make(token),31 unmodified lines85 expect(yield* platform.seen).toStrictEqual([`Bearer ${knownToken}`]);86 }).pipe(Effect.scoped)87 );88 89+ it.live(90+ "reads the stored token for each request, so a token renewed while it serves is the one sent",91+ () =>92+ Effect.gen(function* () {93+ const platform = yield* httpPlatform(handlers);94+ const reads = yield* Ref.make(0);95+96+ // The first read, as the client is built, finds the token that has since been renewed.97+ const renewing = Layer.succeed(Credentials)({98+ current: Effect.map(99+ Ref.getAndUpdate(reads, (n) => n + 1),100+ (n) =>101+ Option.some(102+ profileOn(103+ platform.origin,104+ n === 0 ? "lapsed-token" : knownToken105+ )106+ )107+ ),108+ forHost: () => Effect.succeedNone,109+ put: () => Effect.void,110+ remove: () => Effect.succeedNone,111+ });112+113+ const run = yield* runProgram(["status", "--json"], {114+ client: remote(renewing),115+ handlers,116+ });117+118+ expect(run.code).toBe(0);119+ expect(yield* platform.seen).toStrictEqual([`Bearer ${knownToken}`]);120+ }).pipe(Effect.scoped)121+ );122+123 it.live("status says whom the platform takes the caller for", () =>124 Effect.gen(function* () {125 const platform = yield* httpPlatform(handlers);126 125 unmodified linesmodified:apps/cli/test/repo-context.test.ts+1 added-1 removed
129 unmodified lines130 return Layer.succeed(Credentials)({131 current: Effect.succeedSome(profile),132 forHost: () => Effect.succeedSome(profile),133 put: () => Effect.void,134- remove: () => Effect.succeed(false),134+ remove: () => Effect.succeedNone,135 });136 };137 138 describe("the repo the CLI stands in", () => {62 unmodified linesmodified:apps/platform/src/adapters/answer-runs-workflow.ts+8 added-2 removed
1 unmodified line2 import type { ProjectName } from "@repo/protocol/ids";3 import { Effect, Layer, Schema } from "effect";4 5 import { AnswerParams } from "../answer-runs.ts";6+import { disposed } from "./rpc-result.ts";7 8 export interface AnswerInstance {9 readonly id: string;10 readonly restart: () => Promise<void>;18 unmodified lines29 ]);30 31 const runAgain = (instance: AnswerInstance) =>32 Effect.gen(function* () {32- const { status } = yield* Effect.tryPromise(() => instance.status());33+ const { status } = yield* Effect.tryPromise(() => instance.status()).pipe(34+ Effect.flatMap(disposed)35+ );36 37 if (ended.has(status)) {38 yield* Effect.tryPromise(() => instance.restart());39 }12 unmodified lines52 53 yield* Effect.tryPromise(() =>54 workflow.create({ id: requestId, params })55 ).pipe(56+ Effect.flatMap(disposed),57 // The id is taken: the run was started before.58 Effect.catch((error) =>59 Effect.tryPromise(() => workflow.get(requestId)).pipe(60 Effect.mapError(() => error),57- Effect.flatMap(runAgain)61+ Effect.flatMap((instance) =>62+ runAgain(instance).pipe(Effect.ensuring(disposed(instance)))63+ )64 )65 )66 );67 }).pipe(Effect.orDie),2 unmodified linesmodified:apps/platform/src/adapters/do-projects.ts+2 added
15 unmodified lines16 ExitEncoded,17 ProjectMethod,18 SuccessOf,19 } from "../project-calls.ts";20+import { disposed } from "./rpc-result.ts";21 22 export interface ProjectStub {23 readonly call: (request: typeof CallRequest.Encoded) => Promise<ExitEncoded>;24 }26 unmodified lines51 const request = yield* encodeCall(method, args);52 53 // A DO that cannot answer (reset, storage gone) is a defect.54 const reply = yield* Effect.tryPromise(() => stub.call(request)).pipe(55+ Effect.flatMap(disposed),56 Effect.orDie57 );58 59 return yield* decodeReply(method, reply);140 unmodified linesmodified:apps/platform/src/adapters/rate-limits.ts+2 added
3 unmodified lines4 import { Effect, Layer, Ref } from "effect";5 6 import { RateLimits } from "../rate-limits.ts";7 import type { Limited } from "../rate-limits.ts";8+import { disposed } from "./rpc-result.ts";9 10 export type Limits = Readonly<Record<Limited, number>>;11 12 // Mirrors each binding's `simple.limit` in wrangler.jsonc: a binding can't say its own limit.26 unmodified lines39 bindings[kind].limit({40 key: handle.toLowerCase(),41 })42 ).pipe(43+ Effect.flatMap(disposed),44 Effect.orDie,45 Effect.flatMap(({ success }) =>46 success ? Effect.void : Effect.fail(capped(WorkerCaps, kind))47 )31 unmodified linesadded:apps/platform/src/adapters/rpc-result.ts+21 added
1+import { Effect, Predicate } from "effect";2+3+/**4+ * Workers RPC puts a `Symbol.dispose` on every object a call returns. Where5+ * the far side's own result carried a disposer (an object it had from an RPC6+ * call of its own, passed on as it came, is one), its call stays open until7+ * that is called, and a result left to the garbage collector draws the8+ * runtime's "An RPC result was not disposed properly". Every result here is9+ * data, whole once it arrives, so each is disposed as soon as it lands; on a10+ * result with nothing to release, disposing does nothing.11+ */12+export const disposed = <A>(result: A): Effect.Effect<A> =>13+ Effect.try(() => {14+ const dispose = Predicate.hasProperty(result, Symbol.dispose)15+ ? result[Symbol.dispose]16+ : undefined;17+18+ if (Predicate.isFunction(dispose)) {19+ dispose.call(result);20+ }21+ }).pipe(Effect.ignore, Effect.as(result));modified:apps/platform/src/adapters/sandbox-credentials.ts+3 added-1 removed
16 unmodified lines17 Redacted,18 Schema,19 } from "effect";20 21+import { disposed } from "./rpc-result.ts";22+23 // Each token is revoked when its job ends, so this bounds only a revoke that failed.24 export const jobTokenTtl = Duration.minutes(5);25 26 export type SandboxMethod =121 unmodified lines148 Effect.tryPromise({149 catch: (cause) =>150 new Unreached({ detail: String(cause), failure: "rejected" }),151 try: () => call.send(encoded),150- })152+ }).pipe(Effect.flatMap(disposed))153 ),154 Effect.flatMap((outcome) =>155 Schema.decodeEffect(call.exit)(outcome).pipe(156 Effect.mapError(11 unmodified linesmodified:apps/platform/src/auth/attempts/binding.ts+2 added
1 import { Effect, Layer } from "effect";2 3+import { disposed } from "../../adapters/rpc-result.ts";4 import { SignInAttempts } from "../attempts.ts";5 6 export const SignInAttemptsBinding = (limiter: RateLimit) =>7 Layer.succeed(8 SignInAttempts,9 SignInAttempts.of({10 admit: (key) =>11 Effect.promise(() => limiter.limit({ key })).pipe(12+ Effect.flatMap(disposed),13 Effect.map(({ success }) => success)14 ),15 })16 );modified:apps/platform/src/auth/mailer/binding.ts+2 added-1 removed
1 unmodified line2 // the brand's, onboarded for sending on the account.3 import { Brand } from "@repo/brand";4 import { Effect, Layer } from "effect";5 6+import { disposed } from "../../adapters/rpc-result.ts";7 import { MailFailed, Mailer } from "../mailer.ts";8 9 export const MAIL_FROM = {10 email: `no-reply@${Brand.domain}`,13 unmodified lines24 subject: mail.subject,25 text: mail.text,26 to: mail.to,27 }),27- }).pipe(Effect.asVoid),28+ }).pipe(Effect.flatMap(disposed), Effect.asVoid),29 })30 );modified:apps/platform/src/auth/cli-client.ts+7 added-1 removed
1 import { Brand } from "@repo/brand";2 3 export const CLI_CLIENT_PATH = "/oauth/cli";4 5+// Where a sign-in for `login --paste` ends: a page that shows the code, for a browser on another machine than the CLI.6+export const CLI_CODE_PATH = "/oauth/cli/code";7+8 export const cliClientId = (origin: string) => `${origin}${CLI_CLIENT_PATH}`;9 7-// RFC 8252: the provider matches loopback redirects without the port.10+// RFC 8252: the provider matches loopback redirects without the port. The11+// code page is the platform's own: a code shown there is worth nothing12+// without the verifier the CLI that asked for it holds (PKCE).13 export const cliClientMetadata = (origin: string) => ({14 client_id: cliClientId(origin),15 client_name: `${Brand.name} CLI`,16 grant_types: ["authorization_code", "refresh_token"] as const,17 redirect_uris: [18 "http://127.0.0.1/callback",19 "http://[::1]/callback",20+ `${origin}${CLI_CODE_PATH}`,21 ] as const,22 response_types: ["code"] as const,23 token_endpoint_auth_method: "none" as const,24 });modified:apps/platform/src/auth/google.ts+29 added-18 removed
35 unmodified lines36 byPassword,37 chosenDisplayName,38 chosenHandle,39 completed,40- CSRF_COOKIE,40+ csrfCookieName,41+ csrfOf,42 csrfCookie,43 failedPage,44 freshCsrf,45 HeldHandles,365 unmodified lines411 noEmail:412 "Google did not share a verified email for that account. Sign up with an email and password instead.",413 } as const;414 414-// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.415-const GOOGLE_COOKIE = "__Host-google-sign-in";415+/**416+ * One cookie per leg to Google, holding its verifier and named by the head of417+ * its challenge, which the state Google hands back seals: a second Google418+ * sign-in in the same browser (the CLI's beside an agent's, each in its own419+ * tab) never replaces the first's verifier, so neither is told to start again.420+ * Each lapses with its leg, and a finished one is cleared.421+ */422+export const googleCookieName = (challenge: string) =>423+ `__Host-google-sign-in-${challenge.slice(0, 16)}`;424 425+// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.426 const googleCookie = {427 httpOnly: true,428 path: "/",429 sameSite: "lax",430 secure: true,431 } as const;432 433+// Only this leg's cookie: another in progress in this browser keeps its own.434+const legDone =424-const legDone = (response: HttpServerResponse.HttpServerResponse) =>425- response.pipe(426- HttpServerResponse.setCookie(GOOGLE_COOKIE, "", {427- ...googleCookie,428- maxAge: 0,429- }),430- Effect.orDie431- );435+ (challenge: string) => (response: HttpServerResponse.HttpServerResponse) =>436+ response.pipe(437+ HttpServerResponse.setCookie(googleCookieName(challenge), "", {438+ ...googleCookie,439+ maxAge: 0,440+ }),441+ Effect.orDie442+ );443 444 // Carries the challenge of the verifier in this browser's cookie, so only this browser finishes the leg.445 const GoogleLeg = Schema.Struct({446 challenge: Schema.String,71 unmodified lines518 },519 status: 302,520 }521 ).pipe(511- HttpServerResponse.setCookie(GOOGLE_COOKIE, verifier, {522+ HttpServerResponse.setCookie(googleCookieName(challenge), verifier, {523 ...googleCookie,524 maxAge: SIGN_IN_LIFETIME,525 }),526 Effect.orDie10 unmodified lines537 ).pipe(Effect.mapError(() => startAgain));538 539 const pending = yield* openState(cookieKey, sealed);540 530- if (request.cookies[CSRF_COOKIE] !== pending.csrf) {541+ if (csrfOf(request, pending.csrf) !== pending.csrf) {542 return yield* startAgain;543 }544 545 return yield* toGoogle(client, pending.request, Option.none());30 unmodified lines576 ),577 status,578 pending.request.redirectUri579 ).pipe(569- HttpServerResponse.setCookie(CSRF_COOKIE, csrf, {580+ HttpServerResponse.setCookie(csrfCookieName(csrf), csrf, {581 ...csrfCookie,582 maxAge: SIGN_IN_LIFETIME,583 }),584 Effect.orDie117 unmodified lines702 ).pipe(Effect.mapError(() => startAgain));703 704 const leg = yield* legs.open(cookieKey, query.state);705 695- const verifier = request.cookies[GOOGLE_COOKIE] ?? "";706+ const verifier = request.cookies[googleCookieName(leg.challenge)] ?? "";707 708 if ((yield* challengeOf(verifier)) !== leg.challenge) {709 return yield* startAgain;710 }19 unmodified lines730 return yield* signInPageFor(731 leg.request,732 401,733 confirmed.failure.reason723- ).pipe(Effect.flatMap(legDone));734+ ).pipe(Effect.flatMap(legDone(leg.challenge)));735 }736 737 const answered = yield* Option.match(Option.fromUndefinedOr(leg.link), {738 onNone: () => signedInAs(confirmed.success, leg.request),739 onSome: (handle) => linkedTo(confirmed.success, handle, leg.request),740 });741 731- return yield* legDone(answered);742+ return yield* legDone(leg.challenge)(answered);743 });744 745 const PostedProfile = Schema.Struct({746 csrf: Schema.String,23 unmodified lines770 const pending = yield* pendingHandles.open(cookieKey, form.request);771 772 if (773 pending.csrf !== form.csrf ||763- request.cookies[CSRF_COOKIE] !== form.csrf774+ csrfOf(request, form.csrf) !== form.csrf775 ) {776 return yield* startAgain;777 }778 95 unmodified linesmodified:apps/platform/src/auth/pages.ts+26 added-1 removed
120 unmodified lines121 .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)}124 code{font-family:"IBM Plex Mono",ui-monospace,"SF Mono",Menlo,Consolas,monospace;font-size:.8125rem;overflow-wrap:anywhere}125+code.paste{display:block;padding:12px;border:1px solid var(--rule);border-radius:2px;user-select:all}126 ul{margin:0;padding-left:1.25rem}127 li{margin:0 0 8px}128 `;129 67 unmodified lines197 return "";198 }199 200 if (asker.firstParty === "cli") {200- return `<p class="lead small muted">This finishes signing in the CLI on this computer. Continue only if you just ran <code>${escapeHtml(Brand.cli)} login</code>.</p>`;201+ return asker.redirectIsLoopback202+ ? `<p class="lead small muted">This finishes signing in the CLI on this computer. Continue only if you just ran <code>${escapeHtml(Brand.cli)} login</code>.</p>`203+ : `<p class="lead small muted">This signs in the CLI where you ran <code>${escapeHtml(Brand.cli)} login --paste</code>: the next page shows a code to paste there. Continue only if you just ran it.</p>`;204 }205 206 const name = `<strong>${escapeHtml(asker.clientName)}</strong>`;207 275 unmodified lines483 after: `Remembered it? <a href="${escapeHtml(signInHref)}">Sign in</a>`,484 }485 );486 487+/**488+ * The end of a `login --paste` sign-in: the code, to paste into the terminal489+ * that asked for it. Or, when the sign-in did not finish, what to do instead.490+ */491+export const cliCodePage = (code: string | undefined, home = "/") =>492+ code === undefined493+ ? page(494+ "Sign-in code",495+ `<h1>No code to paste</h1>496+<p role="alert">The sign-in did not finish, so there is no code. Run <code>${escapeHtml(Brand.cli)} login --paste</code> again.</p>`,497+ "form",498+ { home }499+ )500+ : page(501+ "Sign-in code",502+ `<h1>Paste this code</h1>503+<p class="lead small muted">Paste it where <code>${escapeHtml(Brand.cli)} login --paste</code> is waiting. It works once, within ten minutes, and only for the CLI that asked for it.</p>504+<p><code class="paste">${escapeHtml(code)}</code></p>`,505+ "form",506+ { home }507+ );508+509 export const problemPage = (message: string, home = "/") =>510 page(511 "Sign-in problem",512 `<h1>Signing in did not work</h1>5 unmodified linesadded:apps/platform/src/auth/resource.ts+77 added
1+import { Effect } from "effect";2+3+// The platform is one protected resource, its origin, as4+// /.well-known/oauth-protected-resource says, and its tokens serve every path5+// on it. MCP's authorization has a client name its server's own URL6+// (`<origin>/mcp`) as the resource, and some clients name that only when they7+// trade a code or refresh, having named the origin to authorize; RFC 8707 §28+// lets the authorization server read a resource coarser than it was named, so9+// any URL on this origin is read as the origin. A resource on another origin10+// is left as it was sent, for the provider to refuse with `invalid_target`.11+const asPlatform = (origin: string) => (resource: string) => {12+ const url = URL.parse(resource);13+14+ return url !== null &&15+ url.origin === origin &&16+ url.username === "" &&17+ url.password === "" &&18+ url.search === "" &&19+ url.hash === ""20+ ? origin21+ : resource;22+};23+24+const withResources = (params: URLSearchParams, origin: string) => {25+ const named = new URLSearchParams(params);26+27+ named.delete("resource");28+29+ for (const resource of params.getAll("resource").map(asPlatform(origin))) {30+ named.append("resource", resource);31+ }32+33+ return named;34+};35+36+// An authorize request's `resource`, read as the platform's where it names a URL on it.37+export const authorizeNamingPlatform = (request: Request, origin: string) => {38+ const url = new URL(request.url);39+40+ if (!url.searchParams.has("resource")) {41+ return request;42+ }43+44+ url.search = withResources(url.searchParams, origin).toString();45+46+ return new Request(url, request);47+};48+49+const isForm = (request: Request) =>50+ request.method === "POST" &&51+ (request.headers.get("content-type") ?? "").startsWith(52+ "application/x-www-form-urlencoded"53+ );54+55+// A token request's `resource`, in its form body, read the same way.56+export const tokenNamingPlatform = (request: Request, origin: string) =>57+ isForm(request)58+ ? Effect.promise(() => request.clone().text()).pipe(59+ Effect.map((body) => {60+ const params = new URLSearchParams(body);61+62+ if (!params.has("resource")) {63+ return request;64+ }65+66+ const headers = new Headers(request.headers);67+68+ headers.delete("content-length");69+70+ return new Request(request.url, {71+ body: withResources(params, origin),72+ headers,73+ method: request.method,74+ });75+ })76+ )77+ : Effect.succeed(request);modified:apps/platform/src/auth/sign-in.ts+107 added-31 removed
27 unmodified lines28 handleKey,29 } from "./accounts.ts";30 import type { Account } from "./accounts.ts";31 import { SignInAttempts } from "./attempts.ts";32-import { CLI_CLIENT_PATH, cliClientMetadata } from "./cli-client.ts";32+import {33+ CLI_CLIENT_PATH,34+ CLI_CODE_PATH,35+ cliClientMetadata,36+} from "./cli-client.ts";37 import { codeMatches, codeTag, deadTag, freshCode } from "./codes.ts";38 import type { CodePurpose } from "./codes.ts";39 import { firstPartyOf } from "./first-party.ts";40 import { Mailer } from "./mailer.ts";41 import { OAuthStore } from "./oauth-store.ts";42 import {43 ACCOUNT_PATHS,44 addEmailPage,45+ cliCodePage,46 codePage,47 continuePage,48 problemPage,49 resetPage,13 unmodified lines63 sessionAccount,64 withoutSession,65 withSession,66 } from "./platform-session.ts";67+import { authorizeNamingPlatform, tokenNamingPlatform } from "./resource.ts";68 import {69 AuthRequest,70 openState,71 sealing,50 unmodified lines122 export const SIGN_IN_PATHS = [123 "/authorize",124 "/signup",125 CLI_CLIENT_PATH,126+ CLI_CODE_PATH,127 ...Object.values(ACCOUNT_PATHS),128 ...Object.values(SESSION_PATHS),129 ] as const;130 51 unmodified lines182 const STAND_IN_HASH = PasswordHash.make(183 `pbkdf2-sha256$${PasswordPolicy.iterations}$${"A".repeat(22)}$${"A".repeat(43)}`184 );185 179-export const CSRF_COOKIE = "__Host-sign-in";186+/**187+ * One cookie per sign-in in progress, named by the head of its own token: a188+ * second sign-in in the same browser (the CLI's and an agent's, each in its189+ * own tab) never replaces the first's, so neither is told it expired. Each190+ * lapses with its form, and a finished one is cleared.191+ */192+export const csrfCookieName = (csrf: string) =>193+ `__Host-sign-in-${csrf.slice(0, 16)}`;194 195+export const csrfOf = (196+ request: HttpServerRequest.HttpServerRequest,197+ csrf: string198+): string | undefined => request.cookies[csrfCookieName(csrf)];199+200 export const csrfCookie = {201 httpOnly: true,202 path: "/",203 sameSite: "strict",204 secure: true,205 } as const;206 188-const BASE_CSP =189- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'";190-207 // CSP's host grammar cannot name an IPv6 literal host, so only its scheme.208 const redirectSource = (redirectUri: string) =>209 Option.fromNullishOr(URL.parse(redirectUri)).pipe(210 Option.filter(({ origin }) => origin !== "null"),1 unmodified line212 hostname.startsWith("[") ? protocol : origin213 )214 );215 200-// Browsers hold a form post's redirect to `form-action` too, so the client's redirect URI is allowed.216+// Browsers hold a form post's redirect to `form-action` too, so the client's217+// redirect URI is allowed there. Built by directive, so a source meant for218+// `form-action` never lands in the directive written after it.219 const contentSecurityPolicy = (220 redirectUri?: string,221 formActions: readonly string[] = []222 ) =>223 [224+ ["default-src", "'none'"],225+ ["style-src", "'unsafe-inline'"],226+ [227+ "form-action",206- BASE_CSP,207- ...Option.toArray(208- Option.flatMap(Option.fromUndefinedOr(redirectUri), redirectSource)209- ),210- ...formActions,211- ].join(" ");228+ "'self'",229+ ...Option.toArray(230+ Option.flatMap(Option.fromUndefinedOr(redirectUri), redirectSource)231+ ),232+ ...formActions,233+ ],234+ ["frame-ancestors", "'none'"],235+ ]236+ .map((directive) => directive.join(" "))237+ .join("; ");238 239 export const htmlPage = (240 body: string,241 status: number,147 unmodified lines389 390 const withCsrfCookie =391 (csrf: string) => (response: HttpServerResponse.HttpServerResponse) =>392 response.pipe(367- HttpServerResponse.setCookie(CSRF_COOKIE, csrf, {393+ HttpServerResponse.setCookie(csrfCookieName(csrf), csrf, {394 ...csrfCookie,395 maxAge: SIGN_IN_LIFETIME,396 }),397 Effect.orDie4 unmodified lines402 request: HttpServerRequest.HttpServerRequest,403 posted: string,404 sealed: string405 ) =>380- sealed === posted && request.cookies[CSRF_COOKIE] === posted406+ sealed === posted && csrfOf(request, posted) === posted407 ? Effect.void408 : Effect.fail(startAgain);409 410+// The form a request posted, if it posted one: its CSRF token names the cookie to clear.411+const postedCsrf = Effect.gen(function* () {412+ const request = yield* HttpServerRequest.HttpServerRequest;413+414+ return request.method === "POST"415+ ? yield* HttpServerRequest.schemaBodyUrlParams(416+ Schema.Struct({ csrf: Schema.String })417+ ).pipe(418+ Effect.map(({ csrf }) => Option.some(csrf)),419+ Effect.orElseSucceed(() => Option.none<string>())420+ )421+ : Option.none<string>();422+});423+424 // The grant's user is the handle's key, so a grant is one account's in any case.425 // Every account it is given for has a proven email, or the person just proved426 // who they are to Google, whose address is then the account's. Each grant427 // keeps the person signed in here, under the password the account has now2 unmodified lines430 export const completed = (handle: Handle, request: AuthRequest) =>431 Effect.gen(function* () {432 const api = yield* oauthApi;433 const { cookieKey } = yield* SignInKeys;434+ const { origin } = yield* Authorization;435+ const { webUrl } = yield* SignInHome;436 const account = yield* (yield* Accounts).find(handle);437+ const csrf = yield* postedCsrf;438 439 const { redirectTo } = yield* provider(() =>440 api.completeAuthorization({441 metadata: {},442 props: { handle },443 request: forProvider(request),444+ // A grant to the web replaces none: each browser a person signs in on keeps its own.445+ revokeExistingGrants:446+ firstPartyOf(request.clientId, origin, webUrl) !== "web",447 scope: [...request.scope],448 userId: handleKey(handle),449 })450 );451 406- return yield* HttpServerResponse.redirect(redirectTo, {452+ const redirected = HttpServerResponse.redirect(redirectTo, {453 headers: {454 "cache-control": "no-store",455 "referrer-policy": "no-referrer",456 },457 status: 302,412- }).pipe(413- HttpServerResponse.setCookie(CSRF_COOKIE, "", {414- ...csrfCookie,415- maxAge: 0,416- }),417- 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- );458+ });459+460+ // Only this sign-in's cookie: another in progress in this browser keeps its own.461+ const cleared = yield* Option.match(csrf, {462+ onNone: () => Effect.succeed(redirected),463+ onSome: (finished) =>464+ redirected.pipe(465+ HttpServerResponse.setCookie(csrfCookieName(finished), "", {466+ ...csrfCookie,467+ maxAge: 0,468+ }),469+ Effect.orDie470+ ),471+ });472+473+ return yield* Option.match(account, {474+ onNone: () => Effect.succeed(cleared),475+ onSome: (found) => withSession(cookieKey, found)(cleared),476+ });477 });478 479 const offeredSignIn = (480 request: AuthRequest,74 unmodified lines555 // Someone signed in here already is asked only to continue; anyone else, to sign in.556 const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>557 Effect.gen(function* () {558 const api = yield* oauthApi;559+ const { origin } = yield* Authorization;560 const { cookieKey } = yield* SignInKeys;561 562 const web = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);563 511- const parsed = yield* provider(() => api.parseAuthRequest(web));564+ const parsed = yield* provider(() =>565+ api.parseAuthRequest(authorizeNamingPlatform(web, origin))566+ );567 568 const account = yield* sessionAccount(cookieKey, request);569 570 return yield* Option.match(account, {905 unmodified lines1476 headers: { "cache-control": "public, max-age=300" },1477 });1478 });1479 1480+// The code is shown, never kept: it is worth nothing without the CLI's verifier.1481+const cliCode = Effect.gen(function* () {1482+ const { webUrl } = yield* SignInHome;1483+1484+ const { code } = yield* HttpServerRequest.schemaSearchParams(1485+ Schema.Struct({ code: Schema.optionalKey(Schema.NonEmptyString) })1486+ ).pipe(Effect.orElseSucceed(() => ({ code: undefined })));1487+1488+ return htmlPage(1489+ cliCodePage(1490+ code,1491+ Option.getOrElse(webUrl, () => "/")1492+ ),1493+ code === undefined ? 400 : 2001494+ );1495+});1496+1497 const authorizationServer = (request: HttpServerRequest.HttpServerRequest) =>1498 Effect.gen(function* () {1427- const { context, server } = yield* Authorization;1499+ const { context, origin, server } = yield* Authorization;1500 1501 const store = yield* OAuthStore;1502 1431- const web = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);1503+ const web = yield* HttpServerRequest.toWeb(request).pipe(1504+ Effect.orDie,1505+ Effect.flatMap((sent) => tokenNamingPlatform(sent, origin))1506+ );1507 1508 const response = yield* Effect.promise(() =>1509 server.fetch(web, { OAUTH_KV: store }, context)1510 );67 unmodified lines1578 yield* add("GET", ACCOUNT_PATHS.reset, () => showReset);1579 yield* add("POST", ACCOUNT_PATHS.reset, reset);1580 yield* add("POST", ACCOUNT_PATHS.resetVerify, resetVerified);1581 yield* add("GET", CLI_CLIENT_PATH, () => cliClient);1582+ yield* add("GET", CLI_CODE_PATH, () => cliCode);1583 1584 for (const path of AUTHORIZATION_SERVER_PATHS) {1585 yield* add("*", path, authorizationServer);1586 }2 unmodified linesmodified:apps/platform/src/visibility/state.ts+3 added-1 removed
6 unmodified lines7 SaltSource,8 } from "@repo/project/visibility/state";9 import { Effect, Layer, Schema } from "effect";10 11+import { disposed } from "../adapters/rpc-result.ts";12 import { AdmissionParams, admissionId } from "../answer-runs.ts";13 import type { PlatformConfig } from "../platform.ts";14 import { layerRepos } from "./layer-repos.ts";15 33 unmodified lines49 Effect.catch((error) =>50 Effect.tryPromise(() => workflow.get(id)).pipe(51 Effect.mapError(() => error)52 )52- )53+ ),54+ Effect.flatMap(disposed)55 );56 }).pipe(Effect.orDie),57 })58 );13 unmodified linesmodified:apps/platform/src/workflows/answer/lanes.ts+3 added
122 unmodified lines123 Option.fromUndefinedOr(signature)124 )125 ),126 ...Option.toArray(127+ Option.flatMap(evidence, ({ threw }) => Option.fromUndefinedOr(threw))128+ ),129+ ...Option.toArray(130 Option.flatMap(evidence, ({ weakness }) =>131 Option.fromUndefinedOr(weakness)132 )133 ),444 unmodified linesmodified:apps/platform/src/home.ts+1 added
106 unmodified lines107 section(108 "Agents",109 list([110 `MCP: ${code(`${origin}/mcp`)}, streamable HTTP, protocol ${code(MCP_PROTOCOL)}, signed in`,111+ `MCP for anyone: ${code(`${origin}/mcp/public`)}, the tools that only read, with no sign-in`,112 `Agent skills: ${link(`${origin}/.well-known/agent-skills/index.json`)}`,113 `RPC: ${code(`POST ${origin}/rpc`)}`,114 `OAuth: ${link(`${origin}/.well-known/oauth-protected-resource`)} and ${link(`${origin}/.well-known/oauth-authorization-server`)}`,115 `The same facts as Markdown: ask for ${code("text/markdown")}, as in ${code(`curl -H 'accept: text/markdown' ${origin}/`)}`,59 unmodified linesmodified:apps/platform/src/project-do.ts+8 added-3 removed
128 unmodified lines129 override webSocketMessage(socket: WebSocket): Promise<void> {130 return this.#watched((room) => room.heard(socket));131 }132 133+ // A close needs neither the env nor the storage, so it never waits on the134+ // runtime: a socket that goes while the object wakes, or while its storage135+ // fails, is let go without failing the close.136+ // oxlint-disable-next-line eslint/class-methods-use-this -- workerd calls a hibernation handler on the instance, and a close needs nothing the instance holds.137 override webSocketClose(138 socket: WebSocket,139 code: number,136- reason: string137- ): Promise<void> {138- return this.#runtime.runPromise(closeEnd(socket, code, reason));140+ reason: string,141+ wasClean: boolean142+ ): void {143+ Effect.runSync(closeEnd(socket, { code, reason, wasClean }));144 }145 }modified:apps/platform/src/surfaces.ts+44 added-2 removed
7 unmodified lines8 import { FrontPage } from "@repo/project/front-page";9 import { Projects } from "@repo/project/projects";10 import { StandingPostures } from "@repo/project/standing-posture";11 import { authenticated, bearerToken } from "@repo/protocol/authenticate";12-import { Client, Contracts, surfaced } from "@repo/protocol/contracts";12+import {13+ Client,14+ Contracts,15+ surfaced,16+ surfacedToAnyone,17+} from "@repo/protocol/contracts";18 import { ProjectName } from "@repo/protocol/ids";19 import { toToolkit } from "@repo/protocol/mcp";20 import { briefResources, skillPrompt } from "@repo/protocol/mcp-extras";21 import { Authenticated } from "@repo/protocol/principal";58 unmodified lines80 /^\/(?:install\.sh|releases\/(?:manifest\.json|[^/]+\/[^/]+))$/u;81 82 const SKILLS_PATH = /^\/\.well-known\/agent-skills\/.+$/u;83 84+// MCP for anyone: it reads what anyone may, so it takes no credential and refuses none.85+export const PUBLIC_MCP_PATH = "/mcp/public";86+87 // No credential is asked for or checked on these, so none answers 401: git's gateway88 // answers an unknown credential itself, and the rest may carry a stale token or an89 // OAuth client's own credential.90 const isExempt = (path: string) =>3 unmodified lines94 GIT_PATH.test(path) ||95 DISCOVERY_PATH.test(path) ||96 SIGN_IN_PATH.test(path) ||97 RELEASE_PATH.test(path) ||90- SKILLS_PATH.test(path);98+ SKILLS_PATH.test(path) ||99+ path === PUBLIC_MCP_PATH;100 101 const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";102 103 const originOf = (request: HttpServerRequest.HttpServerRequest) =>112 unmodified lines216 );217 })218 );219 220+// A call from the MCP for anyone carries no credential, so it runs as anyone even when its client sent one.221+const forwardNoCredential = RpcMiddleware.layerClient(222+ Authenticated,223+ ({ next, request }) => next(request)224+);225+226 const projection = toToolkit(surfaced("mcp"), Effect.service(Client));227 228+const anyoneProjection = toToolkit(229+ surfacedToAnyone("mcp"),230+ Effect.service(Client)231+);232+233 // Made from the skill's parts, not its `SKILL.md`, whose hash is a promise the234 // router's build may not await.235 const contribute = skillPrompt(236 platformSkillParts({ commands: commandDocs(Contracts) })17 unmodified lines254 }).pipe(Layer.provide(signedInOnly))255 )256 );257 258+// Its own server, toolkit and client, so nothing it is built from is shared with the signed-in one's.259+const mcpForAnyone = Layer.mergeAll(260+ McpServer.toolkit(anyoneProjection.toolkit).pipe(261+ Layer.provideMerge(anyoneProjection.layer)262+ ),263+ briefResources,264+ contribute265+).pipe(266+ Layer.provide(Layer.effect(Client, RpcTest.makeClient(Contracts))),267+ Layer.provide([asCaller, forwardNoCredential]),268+ Layer.provide(269+ McpServer.layerHttp({270+ name: Brand.name,271+ path: PUBLIC_MCP_PATH,272+ protocols: [McpProtocol.v2026_07_28],273+ version: "0.0.0",274+ })275+ ),276+ Layer.fresh277+);278+279 const rpcIn = (serialization: Layer.Layer<RpcSerialization.RpcSerialization>) =>280 RpcServer.toHttpEffect(Contracts).pipe(Effect.provide(serialization));281 282 const rpc = HttpRouter.use((router) =>136 unmodified lines419 discovery,420 raw,421 git,422 mcp,423+ mcpForAnyone,424 rpc,425 releaseRoutes,426 agentSkillRoutes,427 identifyCaller3 unmodified linesmodified:apps/platform/src/watch.ts+19 added-4 removed
178 unmodified lines179 heard: (socket: WebSocket) => catchUp([socket]),180 };181 };182 183+// Codes a close only reports, which `close()` refuses to send.184 const reportOnly: ReadonlySet<number> = new Set([1005, 1006, 1015]);185 185-export const closeEnd = (socket: WebSocket, code: number, reason: string) =>186- Effect.try(() => {187- socket.close(reportOnly.has(code) ? 1000 : code, reason);188- }).pipe(Effect.ignore);186+// A clean close is answered with the peer's code. A socket that went without a187+// close frame (1006) has no peer left to answer: it is let go untouched.188+export const closeEnd = (189+ socket: WebSocket,190+ close: {191+ readonly code: number;192+ readonly reason: string;193+ readonly wasClean: boolean;194+ }195+): Effect.Effect<void> =>196+ close.wasClean197+ ? Effect.try(() => {198+ socket.close(199+ reportOnly.has(close.code) ? 1000 : close.code,200+ close.reason201+ );202+ }).pipe(Effect.ignore)203+ : Effect.void;204 205 interface Upgraded {206 readonly webSocket: WebSocket | null;207 }150 unmodified linesmodified:apps/platform/src/well-known.ts+60 added-8 removed
149 unmodified lines150 onSome: (sha) => keptSkillAt(project, sha),151 })152 );153 154+const LISTED_SKILL_VERSION = 1;155+156+// A project's main moves by a landing alone, so its skill is the same while157+// its listing's last landing stands: an index read again after another158+// project lands finds this one's kept by that instant, and wakes only the159+// project whose main moved. A project not yet landed is read where it is.160+const listedSkill = ({161+ landedAt,162+ project,163+}: ProjectListing): Effect.Effect<164+ Option.Option<string>,165+ never,166+ Projects | RepoHost167+> =>168+ landedAt === undefined169+ ? landedSkill(project)170+ : Effect.gen(function* () {171+ const cache = yield* CodeCache;172+ const store = yield* CodeStore;173+ const key = `${keyOf(project)}/skill-landed/v${LISTED_SKILL_VERSION}/${DateTime.formatIso(landedAt)}`;174+175+ return yield* cache.through(176+ key,177+ Effect.gen(function* () {178+ const kept = Option.flatMap(yield* store.get(key), decodeKept);179+180+ if (Option.isSome(kept)) {181+ return Option.fromUndefinedOr(kept.value.content);182+ }183+184+ const read = yield* landedSkill(project);185+186+ yield* encodeKept(187+ Option.match(read, {188+ onNone: () => ({}),189+ onSome: (content) => ({ content }),190+ })191+ ).pipe(192+ Effect.flatMap((text) => store.put(key, text)),193+ Effect.catch((error) =>194+ Effect.logWarning(195+ `${project}'s listed skill was not kept`,196+ error197+ )198+ )199+ );200+201+ return read;202+ })203+ );204+ });205+206 const decodeKey = Schema.decodeUnknownOption(ProjectKey);207 208 const INDEX_VERSION = 1;209 4 unmodified lines214 const decodeKeptIndex = Schema.decodeOption(KeptIndex);215 216 const encodeKeptIndex = Schema.encodeEffect(KeptIndex);217 166-const indexOf = (projects: readonly ProjectName[]) =>218+const indexOf = (listed: readonly ProjectListing[]) =>219 Effect.gen(function* () {220 const found = yield* Effect.forEach(169- projects,170- (project) =>221+ listed,222+ (listing) =>223 Effect.map(172- landedSkill(project),224+ listedSkill(listing),225 Option.map((content) => ({226 content,227 description: Option.getOrElse(describedIn(content), () =>176- contributeDescription(project)228+ contributeDescription(listing.project)229 ),178- name: contributeSkillName(project),179- url: skillUrl(project),230+ name: contributeSkillName(listing.project),231+ url: skillUrl(listing.project),232 }))233 ),234 { concurrency: FAN_OUT }235 );45 unmodified lines281 if (Option.isSome(kept)) {282 return kept.value.content;283 }284 233- const built = yield* indexOf(listed.map(({ project }) => project));285+ const built = yield* indexOf(listed);286 287 yield* encodeKeptIndex({ content: built }).pipe(288 Effect.flatMap((text) => store.put(key, text)),289 Effect.catch((error) =>91 unmodified linesmodified:apps/platform/test/workflows/answer.fixtures.ts+55 added
536 unmodified lines537 requestId: receipt.requestId,538 } satisfies Admitted;539 });540 541+export const ownMessage = "Split words on runs of spaces";542+543+/** Alice's own change, pushed to her working fork and sent to `land`, which queues it. */544+export const landedOwn = Effect.gen(function* () {545+ yield* advanceTo("2026-10-07T12:00:00Z");546+547+ const api = yield* Projects.use((each) => each.create(project)).pipe(548+ Effect.orDie549+ );550+551+ yield* api.initProject(alice, {}).pipe(Effect.orDie);552+553+ const first = yield* Pusher.use((each) =>554+ each.push(repo, Option.none(), start)555+ );556+557+ yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);558+559+ const { fork } = yield* api.fork(alice).pipe(Effect.orDie);560+ const opened = LandedSha.make(first);561+562+ const head = yield* Pusher.use((each) =>563+ each.push(564+ fork,565+ Option.some(first),566+ changed(start, lexPath, "export const lex = (s) => s.split(/ +/);\n")567+ )568+ );569+570+ const merged = yield* LanderCalls.use((calls) =>571+ calls.preview({ base: first, fork, head, main: opened, repo })572+ );573+574+ const request = {575+ base: first,576+ head,577+ message: ownMessage,578+ requestId: RequestId.make("land-alice-01"),579+ };580+581+ const receipt = yield* api.land(alice, request).pipe(Effect.orDie);582+583+ return {584+ admitted: {585+ api,586+ head,587+ merged,588+ opened,589+ requestId: request.requestId,590+ } satisfies Admitted,591+ again: api.land(alice, request).pipe(Effect.orDie),592+ receipt,593+ };594+});595+596 export const mainMoved = (from: LandedSha, files: Files) =>597 Effect.map(598 Pusher.use((each) => each.push(repo, Option.some(from), files)),599 (sha) => LandedSha.make(sha)65 unmodified linesmodified:apps/platform/test/workflows/answer.test.ts+62 added-1 removed
36 unmodified lines37 Answer,38 OutcomeJson,39 runWorkflow,40 } from "../../src/workflows/answer.ts";41-import { failingPathsOf } from "../../src/workflows/answer/lanes.ts";41+import { failingPathsOf, laneLog } from "../../src/workflows/answer/lanes.ts";42 import { runAnswer } from "../../src/workflows/answer/program.ts";43 import { memoSteps } from "../../src/workflows/step.ts";44 import type { StepRunner, WorkflowSteps } from "../../src/workflows/step.ts";45 import { fakeEnv } from "../fake-env.ts";8 unmodified lines54 Checker,55 DoCalls,56 finishRequired,57 LanderCalls,58+ landedOwn,59 lexPath,60 logged,61 mainMoved,62 mainTip,63 openedFiles,64+ ownMessage,65 parseIso,66 parsePath,67 policy,68 project,815 unmodified lines884 })885 );886 });887 888+describe(laneLog, () => {889+ it("keeps what a failed test threw when nothing asserted, so a timeout names its test", () => {890+ expect(891+ laneLog(892+ {893+ command: "bun run test",894+ durationMs: 404_409,895+ lane: unit,896+ result: "failed",897+ },898+ Option.some({899+ lane: unit,900+ threw:901+ "test/week.test.ts > week > parses a week: Error: Test timed out in <duration>.",902+ })903+ )904+ ).toBe(905+ [906+ "unit: failed in 404409 ms",907+ "$ bun run test",908+ "test/week.test.ts > week > parses a week: Error: Test timed out in <duration>.",909+ ].join("\n")910+ );911+ });912+});913+914 describe(failingPathsOf, () => {915 it("names the repo files a failure points at, tests and absolute paths left out", () => {916 expect(917 failingPathsOf(155 unmodified lines1073 expect(engine.ran).toStrictEqual(["load"]);1074 })1075 );1076 });1077+1078+describe("a maintainer's own landing", () => {1079+ it.effect(1080+ "is queued by land, then merged, checked and landed by the same run an answer has, with the message it was given",1081+ () =>1082+ Effect.gen(function* () {1083+ const own = yield* landedOwn;1084+1085+ yield* scriptProjectLanes(own.admitted.merged, { result: "passed" });1086+1087+ const outcome = yield* run(own.admitted, yield* freshSteps());1088+ const tip = yield* mainTip;1089+ const host = yield* RepoHost;1090+ const commit = yield* host.readCommit(repo, tip).pipe(Effect.orDie);1091+1092+ expect(own.receipt.outcome).toStrictEqual(1093+ Outcome.cases.Checking.make({ stage: "merge" })1094+ );1095+ expect(yield* Started.use(({ ids }) => ids)).toContain(1096+ own.admitted.requestId1097+ );1098+ // The same request sent again reads the landing the run made.1099+ expect([outcome, (yield* own.again).outcome]).toStrictEqual([1100+ landedAt(tip),1101+ landedAt(tip),1102+ ]);1103+ expect(1104+ Option.map(commit, ({ message }) => message.split("\n", 1)[0])1105+ ).toStrictEqual(Option.some(ownMessage));1106+ expect(yield* parentsOf(tip)).toStrictEqual([own.admitted.opened]);1107+ }).pipe(Effect.provide(world))1108+ );1109+});modified:apps/platform/test/answer-runs.test.ts+73 added-1 removed
1 // The engine refuses an instance id past 100 characters, and starting an id that2 // exists changes nothing.3 import { describe, expect, it } from "@effect/vitest";4-import { CommitSha, LayerName, ProjectName } from "@repo/protocol/ids";4+import { AnswerRuns } from "@repo/project/answer-runs";5+import type { AnswerQueue } from "@repo/project/answer-runs";6+import {7+ CommitSha,8+ LayerName,9+ ProjectName,10+ RequestId,11+} from "@repo/protocol/ids";12+import { untouchable } from "@repo/testkit/untouchable";13+import { Effect } from "effect";14 15+import { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";16+import type { AnswerWorkflow } from "../src/adapters/answer-runs-workflow.ts";17 import { AdmissionParams, admissionId } from "../src/answer-runs.ts";18 19 const INSTANCE_ID = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u;20 32 unmodified lines53 named: heads.every((head, at) => (ids[at] ?? "").endsWith(`-${head}`)),54 }).toStrictEqual({ distinct: 2, fit: true, named: true });55 });56 });57+58+describe("an answer's run on the Workflow binding", () => {59+ it.effect(60+ "disposes what the binding gives back: a new run, and a taken run's instance and status",61+ () =>62+ Effect.gen(function* () {63+ const disposals: string[] = [];64+ const started = new Set<string>();65+66+ // The runtime gives each object an RPC call returns a disposer of its67+ // own, which holds the far side's call open until it is called.68+ const disposable = <X extends object>(value: X, name: string): X =>69+ Object.defineProperty(value, Symbol.dispose, {70+ enumerable: false,71+ value: () => {72+ disposals.push(name);73+ },74+ });75+76+ const workflow: AnswerWorkflow = {77+ create: ({ id }) => {78+ if (started.has(id)) {79+ return Promise.reject(new Error("the id is taken"));80+ }81+82+ started.add(id);83+84+ return Promise.resolve(disposable({ id }, "create"));85+ },86+ get: (id) =>87+ Promise.resolve(88+ disposable(89+ {90+ id,91+ restart: () => Promise.resolve(),92+ status: () =>93+ Promise.resolve(94+ disposable({ status: "complete" as const }, "status")95+ ),96+ },97+ "get"98+ )99+ ),100+ };101+102+ const runs = yield* AnswerRuns.pipe(103+ Effect.provide(104+ AnswerRunsWorkflow(workflow, ProjectName.make("alice/datekit"))105+ )106+ );107+108+ const requestId = RequestId.make("request-0001");109+ const queue = untouchable<AnswerQueue>("AnswerQueue");110+111+ yield* runs.start(requestId, queue);112+ yield* runs.start(requestId, queue);113+114+ expect(disposals).toStrictEqual(["create", "status", "get"]);115+ })116+ );117+});modified:apps/platform/test/auth.test.ts+17 added
104 unmodified lines105 });106 })107 );108 109+ // RFC 9728 §3.1 has a client try the MCP endpoint's own document first; with110+ // none there it reads the origin's, so it names the resource /token takes.111 it.effect(112+ "keeps no document for the MCP endpoint alone, so a client reads the origin's",113+ () =>114+ Effect.gen(function* () {115+ const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));116+117+ const responses = yield* Effect.forEach(118+ [`${metadataUrl}/mcp`, `${metadataUrl}/mcp/public`],119+ (url) => fetch(new Request(url))120+ );121+122+ expect(responses.map(({ status }) => status)).toStrictEqual([404, 404]);123+ })124+ );125+126+ it.effect(127 "never turns away /health or the sign-in paths, whatever credential they carry",128 () =>129 Effect.gen(function* () {130 const { fetch } = yield* served(Layer.mergeAll(noProjects, sessions));371 unmodified linesmodified:apps/platform/test/do-projects.test.ts+63 added-1 removed
18 unmodified lines19 RequestId,20 } from "@repo/protocol/ids";21 import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";22 import { advanceTo } from "@repo/testkit/clock";23-import { Effect, Fiber, Layer, Option, Redacted, Ref, Schema } from "effect";23+import {24+ Effect,25+ Fiber,26+ Layer,27+ Option,28+ Predicate,29+ Redacted,30+ Ref,31+ Schema,32+} from "effect";33 34 import { DoProjects } from "../src/adapters/do-projects.ts";35 import type { ProjectNamespace } from "../src/adapters/do-projects.ts";36 import {170 unmodified lines207 other: yield* outcomeOf(projects.get(other)),208 };209 });210 211+// The runtime gives each object an RPC call returns a disposer of its own,212+// which holds the far side's call open until it is called.213+const disposing = (214+ namespace: ProjectNamespace,215+ disposals: string[]216+): ProjectNamespace => ({217+ get: (id) => {218+ const stub = namespace.get(id);219+220+ return {221+ call: (request) =>222+ Effect.runPromise(223+ Effect.tap(224+ Effect.promise(() => stub.call(request)),225+ (reply) =>226+ Effect.sync(() => {227+ if (Predicate.isObjectKeyword(reply)) {228+ Object.defineProperty(reply, Symbol.dispose, {229+ enumerable: false,230+ value: () => {231+ disposals.push(request.method);232+ },233+ });234+ }235+ })236+ )237+ ),238+ };239+ },240+ idFromName: (name) => namespace.idFromName(name),241+});242+243 describe("Projects over the Project DO namespace", () => {244 it("takes the Worker's PROJECT binding", () => {245 expectTypeOf<Env["PROJECT"]>().toExtend<ProjectNamespace>();246 });88 unmodified lines335 ]);336 }).pipe(Effect.provide(world))337 );338 339+ it.effect(340+ "disposes each reply once it is read, so no call holds the DO's own open",341+ () =>342+ Effect.gen(function* () {343+ const { namespace } = yield* namespaceOf;344+ const disposals: string[] = [];345+ const recording = disposing(namespace, disposals);346+347+ yield* Effect.gen(function* () {348+ const made = yield* (yield* Projects).create(project);349+350+ yield* made.initProject(alice, {});351+ yield* made.status(bob);352+ }).pipe(353+ Effect.provide(DoProjects(recording).pipe(Layer.provide(unlisted)))354+ );355+356+ expect(disposals).toStrictEqual(["listAsks", "initProject", "status"]);357+ }).pipe(Effect.provide(world))358+ );359+360 // On Workers a request that awaits another request's I/O is cancelled as hung,361 // and one whose client left is cancelled where it stands: its read never ends.362 it.live(363 "never has a request wait on the listing another request is reading",85 unmodified linesmodified:apps/platform/test/generated.test.ts+15 added-5 removed
322 unmodified lines323 message: "Change the project",324 requestId: RequestId.make(requestId),325 };326 327- return { api, land: () => api.land(alice, request).pipe(Effect.orDie) };327+ const send = api.land(alice, request).pipe(Effect.orDie);328+329+ // `land` queues the change and its run lands it; the same request sent330+ // again reads the landing.331+ return { api, land: () => Effect.andThen(send, send) };332 });333 334 const landedSha = (outcome: Outcome) =>335 Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();127 unmodified lines463 }).pipe(Effect.provide(world))464 );465 466 it.effect(463- "fails the call when the follow-up reached main but its answer was lost, and the call run again records both landings",467+ "fails the landing's run when the follow-up reached main but its answer was lost, and the run the alarm starts again records both landings",468 () =>469 Effect.gen(function* () {470 yield* firstPushed;471 6 unmodified lines478 );479 480 yield* Mishaps.use((each) => each.next("lost"));481 478- const lost = yield* Effect.exit(changed.land());482+ // The run's write that met it recorded nothing, so the request still reads as checking.483+ const lost = yield* changed.land();484 const tip = yield* mainTip;485 const followed = yield* followUpAt(tip);486+487+ // Its start goes back to the outbox, which the alarm settles once its backoff is past.488+ yield* advanceTo("2026-10-07T13:00:00Z");489+ yield* changed.api.onAlarm().pipe(Effect.orDie);490+491 const again = yield* changed.land();492 493 expect({494 followed: followed.requestId,485- lost: Exit.isFailure(lost),495+ lost: lost.outcome._tag,496 main: yield* mainTip,497 }).toStrictEqual({498 followed: `gen-${followed.parent}`,489- lost: true,499+ lost: "Checking",500 main: tip,501 });502 expect(landedSha(again.outcome)).toStrictEqual(503 Option.some(followed.parent)10 unmodified linesmodified:apps/platform/test/google.test.ts+96 added-7 removed
18 unmodified lines19 import { Email } from "../src/auth/accounts.ts";20 import {21 GOOGLE_DISCOVERY,22 googleAuthorizeUrl,23+ googleCookieName,24 GoogleKeysPerIsolate,25 googlePerson,26 } from "../src/auth/google.ts";27 import type { GoogleKeys } from "../src/auth/google.ts";28 import { Identities, IdentityTaken } from "../src/auth/identities.ts";29 import { IdentitiesMemory } from "../src/auth/identities/memory.ts";30 import { hashPassword } from "../src/auth/password.ts";31 import { tokenReader } from "../src/auth/provider.ts";32+import { csrfCookieName } from "../src/auth/sign-in.ts";33 import { SignInFailed } from "../src/auth/state.ts";34 import { decodeEnv, InvalidEnv } from "../src/platform.ts";35 import worker from "../src/worker.ts";36 import { fakeEnv, passwordPepper } from "./fake-env.ts";15 unmodified lines52 } from "./google.fixtures.ts";53 import {54 authorizeUrl,55 codeOf,56+ cspOf,57 formOf,58 origin,59+ port,60 tokenRequest,61 } from "./oauth.fixtures.ts";62 63 const alicePassword = "correct horse battery";498 unmodified lines562 563 expect(page.response.status).toBe(200);564 expect(Option.isSome(formOf(page.response, page.html))).toBeTruthy();565 expect(page.html).not.toContain("Google");562- expect(563- page.response.headers.get("content-security-policy")564- ).not.toContain("accounts.google.com");566+ expect(cspOf(page.response)["form-action"]).toStrictEqual([567+ "'self'",568+ `http://127.0.0.1:${port}`,569+ ]);570 })571 );572 573 it.live(42 unmodified lines616 617 expect(Option.isSome(googleLinkIn(page))).toBeTruthy();618 expect(page.html).toContain("Continue with Google");619 expect(page.html).toContain('formaction="/oauth/google/link"');615- expect(page.response.headers.get("content-security-policy")).toContain(620+ expect(cspOf(page.response)["form-action"]).toContain(621 "https://accounts.google.com"622 );623+ expect(cspOf(page.response)["frame-ancestors"]).toStrictEqual([624+ "'none'",625+ ]);626 })627 );628 629 it.live(33 unmodified lines663 true,664 true,665 ]);666 expect(659- Option.isSome(world.browser.cookie("__Host-google-sign-in"))660- ).toBeTruthy();667+ world.browser668+ .cookie(googleCookieName(query.code_challenge ?? ""))669+ .pipe(Option.map((kept) => kept.length))670+ ).toStrictEqual(Option.some(43));671+ expect(googleCookieName(query.code_challenge ?? "")).toMatch(672+ /^__Host-google-sign-in-[\w-]{16}$/u673+ );674 })675 );676 677 it.live(92 unmodified lines770 });771 772 const isPickHandle = (page: Page) => page.html.includes("Set up your profile");773 774+const challengeIn = (response: Response) =>775+ Effect.fromOption(776+ locationOf(response).pipe(777+ Option.flatMap((location) =>778+ Option.fromNullishOr(location.searchParams.get("code_challenge"))779+ )780+ )781+ ).pipe(Effect.orDie);782+783+describe("two Google sign-ins in progress in one browser", () => {784+ it.live(785+ "lets each come back and finish, the first after the second started, each clearing only its own cookie",786+ () =>787+ Effect.gen(function* () {788+ const world = yield* googleWorld();789+790+ const first = yield* continueWithGoogle(world);791+792+ const second = yield* continueWithGoogle(world);793+794+ const [firstCookie, secondCookie] = yield* Effect.forEach(795+ [first, second],796+ (started) => Effect.map(challengeIn(started), googleCookieName)797+ );798+799+ const firstBack = yield* backFromGoogle(world, first, { sub: "1042" });800+801+ const kept = [firstCookie, secondCookie].map((name) =>802+ Option.isSome(world.browser.cookie(name ?? ""))803+ );804+805+ const secondBack = yield* backFromGoogle(world, second, {806+ sub: "2077",807+ });808+809+ expect({810+ firstBack: [firstBack.response.status, isPickHandle(firstBack)],811+ kept,812+ left: Option.isSome(world.browser.cookie(secondCookie ?? "")),813+ secondBack: [secondBack.response.status, isPickHandle(secondBack)],814+ }).toStrictEqual({815+ firstBack: [200, true],816+ kept: [false, true],817+ left: false,818+ secondBack: [200, true],819+ });820+ })821+ );822+823+ it.live(824+ "keeps each verifier HttpOnly, Secure and SameSite=Lax, under a __Host- name",825+ () =>826+ Effect.gen(function* () {827+ const world = yield* googleWorld();828+829+ const started = yield* continueWithGoogle(world);830+831+ const name = googleCookieName(yield* challengeIn(started));832+833+ const line =834+ started.headers835+ .getSetCookie()836+ .find((each) => each.startsWith(`${name}=`)) ?? "";837+838+ expect(839+ line840+ .split(";")841+ .slice(1)842+ .map((attribute) => attribute.trim().toLowerCase())843+ .filter((attribute) => !attribute.startsWith("max-age"))844+ .toSorted()845+ ).toStrictEqual(["httponly", "path=/", "samesite=lax", "secure"]);846+ })847+ );848+});849+850 describe("coming back from Google", () => {851 it.live(852 "asks a first-time Google account for a handle and a name, Google's filled in, then signs it in as that handle with Google's email",853 () =>87 unmodified lines941 {942 headers: {943 "cf-connecting-ip": "198.51.100.7",944 "content-type": "application/x-www-form-urlencoded",856- cookie: `__Host-sign-in=${form.csrf}`,945+ cookie: `${csrfCookieName(form.csrf)}=${form.csrf}`,946 },947 }948 );949 467 unmodified linesmodified:apps/platform/test/mcp.test.ts+105 added-3 removed
2 unmodified lines3 import { readManaged } from "@repo/agent-kit/generated-file";4 import { platformSkill } from "@repo/agent-kit/platform";5 import { Brand } from "@repo/brand";6 import { CheckAt } from "@repo/checks/check-runner";7-import { Contracts, EnvSchemaOf, Surfaces } from "@repo/protocol/contracts";7+import {8+ Contracts,9+ EnvSchemaOf,10+ Surfaces,11+ surfacedToAnyone,12+} from "@repo/protocol/contracts";13 import type { Contract, ContractOn } from "@repo/protocol/contracts";14 import { Ask, AskListing } from "@repo/protocol/domain/ask";15 import { CheckSpec } from "@repo/protocol/domain/check";16 import { ProjectListing } from "@repo/protocol/domain/front-page";142 unmodified lines159 ["resources/read", "uri"],160 ["tools/call", "name"],161 ]);162 158-const mcpRequest = (163+const mcpRequestAt = (164+ path: string,165 method: string,166 params: Readonly<Record<string, Schema.Json>>,167 token?: string168 ) => {14 unmodified lines183 if (token !== undefined) {184 headers.set("authorization", `Bearer ${token}`);185 }186 181- return new Request(`${origin}/mcp`, {187+ return new Request(`${origin}${path}`, {188 body: JSON.stringify({189 id: 1,190 jsonrpc: "2.0",191 method,3 unmodified lines195 method: "POST",196 });197 };198 199+const mcpRequest = (200+ method: string,201+ params: Readonly<Record<string, Schema.Json>>,202+ token?: string203+) => mcpRequestAt("/mcp", method, params, token);204+205+const ToolNames = Schema.Struct({206+ tools: Schema.Array(Schema.Struct({ name: Schema.String })),207+});208+209 const Reply = Schema.fromJsonString(210 Schema.Struct({211 error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),212 result: Schema.optionalKey(Schema.Unknown),487 unmodified lines700 expect(statuses).toStrictEqual([401, 401, 401]);701 })702 );703 704+ test.effect(705+ "serves anyone, with no credential, the MCP tools anyone may call, and none that writes",706+ () =>707+ Effect.gen(function* () {708+ const { fetch } = yield* Seeded;709+710+ const response = yield* fetch(711+ mcpRequestAt("/mcp/public", "tools/list", {})712+ );713+714+ const { tools } = yield* replyOf(response).pipe(715+ Effect.flatMap(({ result }) =>716+ Schema.decodeUnknownEffect(ToolNames)(result)717+ )718+ );719+720+ expect({721+ status: response.status,722+ tools: tools.map(({ name }) => name),723+ }).toStrictEqual({724+ status: 200,725+ tools: [...surfacedToAnyone("mcp").requests.keys()],726+ });727+ expect(tools.map(({ name }) => name)).not.toContain("claim");728+ })729+ );730+731+ test.effect(732+ "answers a read for anyone as anyone, even when its client sends a credential the platform does not know",733+ () =>734+ Effect.gen(function* () {735+ const { fetch } = yield* Seeded;736+737+ const asked = yield* Effect.forEach(738+ [undefined, "a-token-nobody-holds"],739+ (token) =>740+ Effect.gen(function* () {741+ const response = yield* fetch(742+ mcpRequestAt(743+ "/mcp/public",744+ "tools/call",745+ { arguments: { project }, name: "listAsks" },746+ token747+ )748+ );749+750+ const { result } = yield* replyOf(response);751+752+ const answered =753+ yield* Schema.decodeUnknownEffect(Answered)(result);754+755+ return [response.status, answered.isError];756+ })757+ );758+759+ expect(asked).toStrictEqual([760+ [200, false],761+ [200, false],762+ ]);763+ })764+ );765+766+ test.effect(767+ "keeps a write from anyone: claim is no tool of the MCP for anyone",768+ () =>769+ Effect.gen(function* () {770+ const { fetch } = yield* Seeded;771+772+ const response = yield* fetch(773+ mcpRequestAt("/mcp/public", "tools/call", {774+ arguments: { ask: fixWeek, project },775+ name: "claim",776+ })777+ );778+779+ const { error, result } = yield* replyOf(response);780+781+ expect(782+ error !== undefined ||783+ Schema.is(Schema.Struct({ isError: Schema.Literal(true) }))(784+ result785+ )786+ ).toBeTruthy();787+ })788+ );789+790 test.effect("reads a file at main as structured content", () =>791 Effect.gen(function* () {792 const world = yield* Seeded;793 const { landed } = yield* world.rpc("anonymous").listRefs({ project });306 unmodified linesmodified:apps/platform/test/oauth.fixtures.ts+67 added-18 removed
10 unmodified lines11 import { MailerMemory } from "../src/auth/mailer/memory.ts";12 import { OAuthStore } from "../src/auth/oauth-store.ts";13 import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";14 import { oauthProvider, signInSettings } from "../src/auth/provider.ts";15+import { csrfCookieName } from "../src/auth/sign-in.ts";16 import { decodeEnv } from "../src/platform.ts";17 import { fakeEnv } from "./fake-env.ts";18 19 export const origin = "https://platform.test";9 unmodified lines29 export const redirectUri = `http://127.0.0.1:${port}/callback`;30 31 export const namedPerson = "carol";32 32-const worldEnv = () => ({33- ...fakeEnv(),34- SESSION_TOKENS: JSON.stringify({35- "carol-token-0123456789abcdef01234567": namedPerson,36- }),37-});33+// Where a world that names a web serves the web's client metadata document.34+export const webOrigin = "https://web.test";35 36+export const webClient = `${webOrigin}/auth/client`;37+38+export const webCallback = `${webOrigin}/auth/callback`;39+40+const worldEnv = (web: boolean) => {41+ const env = {42+ ...fakeEnv(),43+ SESSION_TOKENS: JSON.stringify({44+ "carol-token-0123456789abcdef01234567": namedPerson,45+ }),46+ };47+48+ return web ? { ...env, PUBLIC_WEB_URL: webOrigin } : env;49+};50+51+const webMetadata = () =>52+ Response.json({53+ client_id: webClient,54+ client_name: "web",55+ grant_types: ["authorization_code", "refresh_token"],56+ redirect_uris: [webCallback],57+ response_types: ["code"],58+ token_endpoint_auth_method: "none",59+ });60+61 const context = untouchable<ExecutionContext>("ExecutionContext");62 63 const platformFetch = (request: Request) =>64 Promise.resolve(3 unmodified lines68 const decodeTokenRecord = Schema.decodeUnknownEffect(69 Schema.Record(Schema.String, Schema.Unknown)70 );71 50-export const signInWorld = (options: { readonly mailFails?: boolean } = {}) =>72+export const signInWorld = (73+ options: { readonly mailFails?: boolean; readonly web?: boolean } = {}74+) =>75 Effect.gen(function* () {52- const config = yield* decodeEnv(worldEnv()).pipe(Effect.orDie);76+ const config = yield* decodeEnv(worldEnv(options.web === true)).pipe(77+ Effect.orDie78+ );79 80 const accounts = yield* Effect.provide(81 Effect.service(Accounts),82 AccountsMemory.layer24 unmodified lines107 Effect.sync(() => {108 vi.stubGlobal("Cloudflare", {109 compatibilityFlags: { global_fetch_strictly_public: true },110 });85- vi.stubGlobal("fetch", (input: RequestInfo | URL) =>86- send(new Request(input))87- );111+ vi.stubGlobal("fetch", (input: RequestInfo | URL) => {112+ const request = new Request(input);113+114+ return options.web === true && request.url === webClient115+ ? Promise.resolve(webMetadata())116+ : send(request);117+ });118 }),119 () =>120 Effect.promise(dispose).pipe(121 Effect.andThen(Effect.sync(() => vi.unstubAllGlobals()))48 unmodified lines170 ): Option.Option<SignInForm> =>171 Option.all({172 cookie: Option.orElse(173 Option.fromNullishOr(144- /__Host-sign-in=(?<value>[^;]+)/u.exec(174+ /__Host-sign-in-[\w-]+=(?<value>[^;]+)/u.exec(175 response.headers.get("set-cookie") ?? ""176 )?.groups?.value177 ),178 () => Option.fromNullishOr(cookie)1 unmodified line180 csrf: field(html, "csrf"),181 request: field(html, "request"),182 });183 184+// Each directive's sources, by name: a source counts only under the directive it was written in.185+export const cspOf = (response: Response) =>186+ Object.fromEntries(187+ (response.headers.get("content-security-policy") ?? "")188+ .split(";")189+ .map((directive) => directive.trim().split(/\s+/u))190+ .filter(([name]) => name !== undefined && name !== "")191+ .map(([name = "", ...sources]) => [name, sources])192+ );193+194 export const codeOf = (response: Response) =>195 Option.fromNullishOr(response.headers.get("location")).pipe(196 Option.flatMap((location) => Option.fromNullishOr(URL.parse(location))),197 Option.filter((url) => url.origin === new URL(redirectUri).origin),198 Option.flatMap((url) => Option.fromNullishOr(url.searchParams.get("code")))199 );200 161-export const authorizeUrl = (state = "state-1", redirect = redirectUri) => {201+export const authorizeUrl = (202+ state = "state-1",203+ redirect = redirectUri,204+ client = cliClient205+) => {206 const url = new URL("/authorize", origin);207 208 for (const [name, value] of Object.entries({165- client_id: cliClient,209+ client_id: client,210 code_challenge: challenge,211 code_challenge_method: "S256",212 redirect_uri: redirect,213 response_type: "code",15 unmodified lines229 body: new URLSearchParams(fields),230 headers: {231 "cf-connecting-ip": address,232 "content-type": "application/x-www-form-urlencoded",189- cookie: `__Host-sign-in=${cookie}`,233+ cookie: `${csrfCookieName(cookie)}=${cookie}`,234 },235 method: "POST",236 redirect: "manual",237 });238 195-export const tokenRequest = (code: string, codeVerifier = verifier) =>239+export const tokenRequest = (240+ code: string,241+ codeVerifier = verifier,242+ client = cliClient,243+ redirect = redirectUri244+) =>245 new Request(new URL("/token", origin), {246 body: new URLSearchParams({198- client_id: cliClient,247+ client_id: client,248 code,249 code_verifier: codeVerifier,250 grant_type: "authorization_code",202- redirect_uri: redirectUri,251+ redirect_uri: redirect,252 }),253 headers: { "content-type": "application/x-www-form-urlencoded" },254 method: "POST",255 });modified:apps/platform/test/oauth.test.ts+467 added-12 removed
11 unmodified lines12 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";16+import { CLI_CODE_PATH, 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";19 import { ACCOUNT_PATHS, SESSION_PATHS } from "../src/auth/pages.ts";20 import {3 unmodified lines24 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 { csrfCookieName } from "../src/auth/sign-in.ts";29 import { openState, sealState, SignInFailed } from "../src/auth/state.ts";30 import type { PendingSignIn } from "../src/auth/state.ts";31 import worker from "../src/worker.ts";32 import {4 unmodified lines37 import {38 authorizeUrl,39 cliClient,40 codeOf,41+ cspOf,42 formOf,43 namedPerson,44 origin,45 port,46 post,47 signInWorld,48+ redirectUri,49 tokenRequest,50+ verifier,51+ webCallback,52+ webClient,53 } from "./oauth.fixtures.ts";54 import type { World } from "./oauth.fixtures.ts";55 56 const pepper = Redacted.make(passwordPepper);145 unmodified lines202 );203 });204 205 describe("the CLI's OAuth client", () => {200- it("is public, signs in with PKCE only, and comes back to a loopback port", () => {206+ it("is public, signs in with PKCE only, and comes back to a loopback port or the platform's own code page", () => {207 expect(cliClientMetadata("https://platform.test")).toStrictEqual({208 client_id: "https://platform.test/oauth/cli",209 client_name: `${Brand.name} CLI`,210 grant_types: ["authorization_code", "refresh_token"],205- redirect_uris: ["http://127.0.0.1/callback", "http://[::1]/callback"],211+ redirect_uris: [212+ "http://127.0.0.1/callback",213+ "http://[::1]/callback",214+ "https://platform.test/oauth/cli/code",215+ ],216 response_types: ["code"],217 token_endpoint_auth_method: "none",218 });219 });255 unmodified lines475 });476 477 const alicePassword = "correct horse battery";478 469-const CSP =470- "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'";479+// The page loads nothing, cannot be framed, and posts its forms only here and to where the code goes back.480+const lockedDown = (formAction: readonly string[]) => ({481+ "default-src": ["'none'"],482+ "form-action": ["'self'", ...formAction],483+ "frame-ancestors": ["'none'"],484+ "style-src": ["'unsafe-inline'"],485+});486 487 describe("the platform as its own OAuth authorization server", () => {488 it.live("publishes where to authorize and where to get a token", () =>489 Effect.gen(function* () {52 unmodified lines542 543 expect([544 page.response.status,545 page.response.headers.get("content-type"),531- page.response.headers.get("content-security-policy"),546+ cspOf(page.response),547 page.response.headers.get("x-frame-options"),548 ]).toStrictEqual([549 200,550 "text/html; charset=utf-8",536- `${CSP} http://127.0.0.1:${port}`,551+ lockedDown([`http://127.0.0.1:${port}`]),552 "DENY",553 ]);554 expect(page.html).toContain(555 "This finishes signing in the CLI on this computer."50 unmodified lines606 )607 )608 .pipe(Effect.flatMap(read));609 595- expect([596- page.response.status,597- page.response.headers.get("content-security-policy"),598- ]).toStrictEqual([200, `${CSP} http:`]);610+ expect([page.response.status, cspOf(page.response)]).toStrictEqual([611+ 200,612+ lockedDown(["http:"]),613+ ]);614 })615 );616 });617 989 unmodified lines1607 SESSION_PATHS.continue,1608 { csrf: csrf ?? form.csrf, request: form.request },1609 form.cookie1610 ),1596- { "__Host-sign-in": form.cookie, [SESSION]: session }1611+ { [csrfCookieName(form.cookie)]: form.cookie, [SESSION]: session }1612 )1613 );1614 });1615 21 unmodified lines1637 password: page.html.includes('name="password"'),1638 status: page.response.status,1639 });1640 1641+// A code given back to `redirect`, wherever that is.1642+const codeAt = (response: Response, redirect: string) =>1643+ Effect.fromOption(1644+ Option.fromNullishOr(response.headers.get("location")).pipe(1645+ Option.flatMap((location) => Option.fromNullishOr(URL.parse(location))),1646+ Option.filter((url) => `${url.origin}${url.pathname}` === redirect),1647+ Option.flatMap((url) =>1648+ Option.fromNullishOr(url.searchParams.get("code"))1649+ )1650+ )1651+ ).pipe(Effect.orDie);1652+1653+const tokenAt = (1654+ world: World,1655+ code: string,1656+ client = cliClient,1657+ redirect = redirectUri1658+) =>1659+ Effect.gen(function* () {1660+ const response = yield* world.fetch(1661+ tokenRequest(code, undefined, client, redirect)1662+ );1663+1664+ return yield* Effect.promise(() => response.json()).pipe(1665+ Effect.flatMap(Schema.decodeUnknownEffect(TokenResponse)),1666+ Effect.map(({ access_token }) => access_token),1667+ Effect.orDie1668+ );1669+ });1670+1671+// A password sign-in for `client`, from a page opened in a browser that holds `jar` as well.1672+const signInWithJar = (1673+ world: World,1674+ form: {1675+ readonly cookie: string;1676+ readonly csrf: string;1677+ readonly request: string;1678+ },1679+ jar: readonly string[]1680+) =>1681+ world.fetch(1682+ withCookies(1683+ post(1684+ "/authorize",1685+ {1686+ csrf: form.csrf,1687+ login: "alice",1688+ password: alicePassword,1689+ request: form.request,1690+ },1691+ form.cookie1692+ ),1693+ Object.fromEntries(jar.map((value) => [csrfCookieName(value), value]))1694+ )1695+ );1696+1697+// The sign-in cookies an answer clears, by name.1698+const cleared = (response: Response) =>1699+ response.headers1700+ .getSetCookie()1701+ .filter(1702+ (line) =>1703+ line.startsWith("__Host-sign-in-") &&1704+ line.toLowerCase().includes("max-age=0")1705+ )1706+ .map((line) => line.slice(0, line.indexOf("=")));1707+1708+describe("a CLI sign-in by pasted code", () => {1709+ const codePage = `${origin}${CLI_CODE_PATH}`;1710+1711+ it.live(1712+ "ends on the platform's code page, which shows the code to paste, and the code trades for a token with the CLI's verifier",1713+ () =>1714+ Effect.gen(function* () {1715+ const world = yield* signInWorld();1716+1717+ yield* signUp(world, "alice", alicePassword);1718+1719+ const page = yield* world1720+ .fetch(new Request(authorizeUrl("state-1", codePage)))1721+ .pipe(Effect.flatMap(read));1722+1723+ const form = yield* formIn(page);1724+1725+ const signedIn = yield* signInWithJar(world, form, [form.cookie]);1726+1727+ const code = yield* codeAt(signedIn, codePage);1728+1729+ const shown = yield* world1730+ .fetch(new Request(signedIn.headers.get("location") ?? ""))1731+ .pipe(Effect.flatMap(read));1732+1733+ const token = yield* tokenAt(world, code, cliClient, codePage);1734+1735+ expect({1736+ asks: page.html.includes(1737+ "login --paste</code>: the next page shows a code"1738+ ),1739+ cached: shown.response.headers.get("cache-control"),1740+ shows: shown.html.includes(1741+ `<code class="paste">${code.replaceAll("&", "&")}</code>`1742+ ),1743+ status: shown.response.status,1744+ verified: Option.isSome(1745+ yield* OAuthSessions(tokenReader(world.store)).verify(token)1746+ ),1747+ }).toStrictEqual({1748+ asks: true,1749+ cached: "no-store",1750+ shows: true,1751+ status: 200,1752+ verified: true,1753+ });1754+ })1755+ );1756+1757+ it.live("gives no token for a shown code without the CLI's verifier", () =>1758+ Effect.gen(function* () {1759+ const world = yield* signInWorld();1760+1761+ yield* signUp(world, "alice", alicePassword);1762+1763+ const form = yield* formIn(1764+ yield* world1765+ .fetch(new Request(authorizeUrl("state-1", codePage)))1766+ .pipe(Effect.flatMap(read))1767+ );1768+1769+ const code = yield* signInWithJar(world, form, [form.cookie]).pipe(1770+ Effect.flatMap((response) => codeAt(response, codePage))1771+ );1772+1773+ const response = yield* world.fetch(1774+ tokenRequest(1775+ code,1776+ "another-verifier-0123456789abcdefghijklmnopqrstu",1777+ cliClient,1778+ codePage1779+ )1780+ );1781+1782+ expect(response.status).toBe(400);1783+ })1784+ );1785+1786+ it.live("says there is no code when the sign-in did not finish", () =>1787+ Effect.gen(function* () {1788+ const world = yield* signInWorld();1789+1790+ const shown = yield* world1791+ .fetch(new Request(`${codePage}?error=access_denied&state=state-1`))1792+ .pipe(Effect.flatMap(read));1793+1794+ expect([1795+ shown.response.status,1796+ shown.html.includes("No code to paste"),1797+ ]).toStrictEqual([400, true]);1798+ })1799+ );1800+});1801+1802+describe("two sign-ins in progress in one browser", () => {1803+ it.live(1804+ "both finish, whichever page was opened last, and each clears only its own cookie",1805+ () =>1806+ Effect.gen(function* () {1807+ const world = yield* signInWorld();1808+1809+ yield* signUp(world, "alice", alicePassword);1810+1811+ const first = yield* formIn(yield* openSignIn(world, "state-1"));1812+ const second = yield* formIn(yield* openSignIn(world, "state-2"));1813+ const jar = [first.cookie, second.cookie];1814+1815+ const done = yield* signInWithJar(world, first, jar);1816+ const after = yield* signInWithJar(world, second, jar);1817+1818+ expect({1819+ after: Option.isSome(codeOf(after)),1820+ cleared: cleared(done),1821+ distinct:1822+ csrfCookieName(first.cookie) !== csrfCookieName(second.cookie),1823+ done: Option.isSome(codeOf(done)),1824+ }).toStrictEqual({1825+ after: true,1826+ cleared: [csrfCookieName(first.cookie)],1827+ distinct: true,1828+ done: true,1829+ });1830+ })1831+ );1832+});1833+1834+describe("grants to one person's clients", () => {1835+ it.live(1836+ "keeps each browser's grant to the web: signing in on a second ends none on the first",1837+ () =>1838+ Effect.gen(function* () {1839+ const world = yield* signInWorld({ web: true });1840+1841+ yield* signUp(world, "alice", alicePassword);1842+1843+ const tokens = yield* Effect.forEach(["state-1", "state-2"], (state) =>1844+ Effect.gen(function* () {1845+ const page = yield* world1846+ .fetch(new Request(authorizeUrl(state, webCallback, webClient)))1847+ .pipe(Effect.flatMap(read));1848+1849+ const form = yield* formIn(page);1850+1851+ const code = yield* signInWithJar(world, form, [form.cookie]).pipe(1852+ Effect.flatMap((response) => codeAt(response, webCallback))1853+ );1854+1855+ return yield* tokenAt(world, code, webClient, webCallback);1856+ })1857+ );1858+1859+ const sessions = OAuthSessions(tokenReader(world.store));1860+1861+ expect(1862+ yield* Effect.forEach(tokens, (token) =>1863+ Effect.map(sessions.verify(token), Option.isSome)1864+ )1865+ ).toStrictEqual([true, true]);1866+ })1867+ );1868+1869+ it.live(1870+ "still replaces another client's grant to the same redirect, so an app signed in again holds one",1871+ () =>1872+ Effect.gen(function* () {1873+ const world = yield* signInWorld();1874+1875+ yield* signUp(world, "alice", alicePassword);1876+1877+ const tokens = yield* Effect.forEach(["state-1", "state-2"], (state) =>1878+ Effect.gen(function* () {1879+ const form = yield* formIn(yield* openSignIn(world, state));1880+1881+ const code = yield* signInWithJar(world, form, [form.cookie]).pipe(1882+ Effect.flatMap(codeIn)1883+ );1884+1885+ return yield* tokenAt(world, code);1886+ })1887+ );1888+1889+ const sessions = OAuthSessions(tokenReader(world.store));1890+1891+ expect(1892+ yield* Effect.forEach(tokens, (token) =>1893+ Effect.map(sessions.verify(token), Option.isSome)1894+ )1895+ ).toStrictEqual([false, true]);1896+ })1897+ );1898+});1899+1900 describe("the platform's own session", () => {1901 it.live(1902 "keeps the person signed in here for thirty days after a grant, out of reach of scripts and other sites' posts",1903 () =>403 unmodified lines2307 expect([before, yield* opened()]).toStrictEqual([true, false]);2308 }).pipe(Effect.provide(AccountsMemory.layer))2309 );2310 });2311+2312+// MCP's authorization has a client name its server's own URL as the resource, and2313+// some name it only when they trade a code or refresh: the platform is one2314+// protected resource, its origin, so a resource anywhere on it names the platform.2315+const mcpEndpoint = `${origin}/mcp`;2316+2317+const TokenOutcome = Schema.Struct({2318+ access_token: Schema.optionalKey(Schema.String),2319+ error: Schema.optionalKey(Schema.String),2320+ refresh_token: Schema.optionalKey(Schema.String),2321+});2322+2323+const outcomeOf = (response: Response) =>2324+ Effect.promise(() => response.json()).pipe(2325+ Effect.flatMap(Schema.decodeUnknownEffect(TokenOutcome)),2326+ Effect.orDie,2327+ Effect.map((body) => ({ body, status: response.status }))2328+ );2329+2330+const toToken = (fields: URLSearchParams | Readonly<Record<string, string>>) =>2331+ new Request(new URL("/token", origin), {2332+ body: new URLSearchParams(fields),2333+ headers: { "content-type": "application/x-www-form-urlencoded" },2334+ method: "POST",2335+ });2336+2337+const tradeCode = (code: string, resource?: string) => {2338+ const fields = new URLSearchParams({2339+ client_id: cliClient,2340+ code,2341+ code_verifier: verifier,2342+ grant_type: "authorization_code",2343+ redirect_uri: redirectUri,2344+ });2345+2346+ if (resource !== undefined) {2347+ fields.set("resource", resource);2348+ }2349+2350+ return toToken(fields);2351+};2352+2353+const refresh = (refreshToken: string, resource: string) =>2354+ toToken({2355+ client_id: cliClient,2356+ grant_type: "refresh_token",2357+ refresh_token: refreshToken,2358+ resource,2359+ });2360+2361+const authorizeNaming = (resource?: string) => {2362+ const url = authorizeUrl();2363+2364+ if (resource !== undefined) {2365+ url.searchParams.set("resource", resource);2366+ }2367+2368+ return new Request(url);2369+};2370+2371+// Alice's password sign-in, from an authorize request that names `resource` if given.2372+const codeNaming = (world: World, resource?: string) =>2373+ Effect.gen(function* () {2374+ yield* signUp(world, "alice", alicePassword);2375+2376+ const form = yield* world.fetch(authorizeNaming(resource)).pipe(2377+ Effect.flatMap(read),2378+ Effect.flatMap((page) => formIn(page))2379+ );2380+2381+ return yield* world2382+ .fetch(2383+ post(2384+ "/authorize",2385+ {2386+ csrf: form.csrf,2387+ login: "alice",2388+ password: alicePassword,2389+ request: form.request,2390+ },2391+ form.cookie2392+ )2393+ )2394+ .pipe(Effect.flatMap(codeIn));2395+ });2396+2397+describe("a resource named on the platform", () => {2398+ it.live(2399+ "trades a code for a token when the authorize and token requests both name the MCP endpoint",2400+ () =>2401+ Effect.gen(function* () {2402+ const world = yield* signInWorld();2403+2404+ const code = yield* codeNaming(world, mcpEndpoint);2405+2406+ const { body, status } = yield* world2407+ .fetch(tradeCode(code, mcpEndpoint))2408+ .pipe(Effect.flatMap(outcomeOf));2409+2410+ expect([2411+ status,2412+ body.error,2413+ body.access_token === undefined,2414+ ]).toStrictEqual([200, undefined, false]);2415+ })2416+ );2417+2418+ it.live(2419+ "trades a code granted for the platform's origin at a token request that names the MCP endpoint",2420+ () =>2421+ Effect.gen(function* () {2422+ const world = yield* signInWorld();2423+2424+ const code = yield* codeNaming(world, origin);2425+2426+ const { body, status } = yield* world2427+ .fetch(tradeCode(code, mcpEndpoint))2428+ .pipe(Effect.flatMap(outcomeOf));2429+2430+ expect([status, body.error]).toStrictEqual([200, undefined]);2431+ })2432+ );2433+2434+ it.live(2435+ "refreshes a grant at a refresh that names the MCP endpoint, or the origin with or without its slash",2436+ () =>2437+ Effect.gen(function* () {2438+ const world = yield* signInWorld();2439+2440+ const code = yield* codeNaming(world);2441+2442+ const traded = yield* world2443+ .fetch(tradeCode(code))2444+ .pipe(Effect.flatMap(outcomeOf));2445+2446+ const none: readonly number[] = [];2447+2448+ const { statuses } = yield* Effect.reduce(2449+ [mcpEndpoint, `${origin}/`, origin],2450+ () => ({2451+ refreshToken: traded.body.refresh_token ?? "",2452+ statuses: none,2453+ }),2454+ (held, resource) =>2455+ world.fetch(refresh(held.refreshToken, resource)).pipe(2456+ Effect.flatMap(outcomeOf),2457+ Effect.map(({ body, status }) => ({2458+ refreshToken: body.refresh_token ?? "",2459+ statuses: [...held.statuses, status],2460+ }))2461+ )2462+ );2463+2464+ expect(statuses).toStrictEqual([200, 200, 200]);2465+ })2466+ );2467+2468+ it.live("still refuses a resource on another origin", () =>2469+ Effect.gen(function* () {2470+ const world = yield* signInWorld();2471+2472+ const code = yield* codeNaming(world);2473+2474+ const traded = yield* world2475+ .fetch(tradeCode(code, "https://elsewhere.test/mcp"))2476+ .pipe(Effect.flatMap(outcomeOf));2477+2478+ const asked = yield* world.fetch(2479+ authorizeNaming("https://elsewhere.test")2480+ );2481+2482+ expect([2483+ traded.status,2484+ traded.body.error,2485+ URL.parse(asked.headers.get("location") ?? "")?.searchParams.get(2486+ "error"2487+ ),2488+ ]).toStrictEqual([400, "invalid_target", "invalid_target"]);2489+ })2490+ );2491+});modified:apps/platform/test/project-do.test.ts+57 added-2 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { AnswerRuns } from "@repo/project/answer-runs";3 import type { AnswerQueue } from "@repo/project/answer-runs";4 import { ProjectGenerator } from "@repo/project/generated";5-import { RequestId } from "@repo/protocol/ids";5+import { keyOf, RequestId } from "@repo/protocol/ids";6 import { UnknownProject } from "@repo/protocol/refusal";7 import { advanceTo, at } from "@repo/testkit/clock";8 import { untouchable } from "@repo/testkit/untouchable";9-import { Context, DateTime, Deferred, Effect, Layer, Option } from "effect";9+import {10+ Context,11+ DateTime,12+ Deferred,13+ Effect,14+ Exit,15+ Layer,16+ Option,17+} from "effect";18 19 import { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";20 import type { AnswerWorkflow } from "../src/adapters/answer-runs-workflow.ts";21 import { DoBackground } from "../src/adapters/background.ts";323 unmodified lines345 ]);346 });347 348 it.effect(349+ "lets a watch socket go without its runtime: a close that comes while the object's storage cannot be opened neither throws nor rejects",350+ () =>351+ Effect.gen(function* () {352+ const builds: Promise<unknown>[] = [];353+354+ const closes: (readonly [number | undefined, string | undefined])[] =355+ [];356+357+ // The runtime is built over storage that fails, as one being reset does.358+ const state = untouchable<DurableObjectState>("DurableObjectState", {359+ blockConcurrencyWhile: <T>(build: () => Promise<T>) => {360+ const building = build();361+362+ builds.push(building);363+364+ return building;365+ },366+ id: untouchable<DurableObjectId>("DurableObjectId", {367+ name: keyOf(project),368+ }),369+ storage: untouchable<DurableObjectStorage>("storage"),370+ });371+372+ const socket = untouchable<WebSocket>("WebSocket", {373+ close: (code?: number, reason?: string) => {374+ closes.push([code, reason]);375+ },376+ });377+378+ const object = new Project(state, fakeEnv());379+380+ const built = yield* Effect.exit(381+ Effect.tryPromise(() => Promise.all(builds))382+ );383+384+ // A close that waited on this runtime would reject, unhandled, and fail the run.385+ object.webSocketClose(socket, 1006, "", false);386+ object.webSocketClose(socket, 1000, "bye", true);387+388+ expect({ built: Exit.isFailure(built), closes }).toStrictEqual({389+ built: true,390+ closes: [[1000, "bye"]],391+ });392+ })393+ );394+395+ it.effect(396 "runs on ports that carry the platform's generator, so a landing that changes the config is followed",397 () =>398 Effect.gen(function* () {399 const config = yield* decodeEnv(fakeEnv()).pipe(Effect.orDie);14 unmodified linesmodified:apps/platform/test/raw.test.ts+43 added-1 removed
51 unmodified lines52 53 return sha;54 }).pipe(Effect.orDie, Effect.provide(world));55 56+ // The ids of the first commit's tree and its README's blob, which no commit has.57+ const others = yield* Effect.gen(function* () {58+ const host = yield* RepoHost;59+ const repo = RepoName.make(keyOf(project));60+ const commit = Option.getOrThrow(yield* host.readCommit(repo, first));61+62+ const entries = Option.getOrThrow(63+ yield* host.readTree(repo, commit.tree)64+ );65+66+ return [67+ commit.tree,68+ ...entries.flatMap(({ name, sha }) =>69+ name === "README.md" ? [sha] : []70+ ),71+ ];72+ }).pipe(Effect.orDie, Effect.provide(world));73+74 const cached = yield* Option.match(reads, {75 onNone: () => Effect.succeed(world),76 onSome: (count) =>77 Effect.map(Layer.build(CodeCacheLive(100)), (cache) => {24 unmodified lines102 MemorySessions.layer({})103 )104 );105 88- return { fetch, first };106+ return { fetch, first, others };107 });108 109 const platform = platformWith(Option.none());110 97 unmodified lines208 expect(answers).toStrictEqual(answers.map(() => [404, ""]));209 })210 );211 212+ it.effect(213+ "is a 404 at a full SHA that names a tree or a blob, which is no commit",214+ () =>215+ Effect.gen(function* () {216+ const { fetch, others } = yield* platform;217+218+ const answers = yield* Effect.forEach(others, (sha) =>219+ Effect.map(220+ get(fetch, `/${project}/raw/${sha}/README.md`),221+ ({ headers, status, text }) => [222+ status,223+ text,224+ headers.get("x-content-type-options"),225+ ]226+ )227+ );228+229+ expect(answers).toStrictEqual([230+ [404, "", "nosniff"],231+ [404, "", "nosniff"],232+ ]);233+ })234+ );235+236 it.effect("read a tree once per isolate, by its id", () =>237 Effect.gen(function* () {238 const reads = yield* Ref.make(0);239 const { fetch, first } = yield* platformWith(Option.some(reads));30 unmodified linesmodified:apps/platform/test/sandbox-adapters.test.ts+66 added
42 unmodified lines43 FiberSet,44 Layer,45 Logger,46 Option,47+ Predicate,48 Redacted,49 Result,50 Schema,51 } from "effect";52 53 import { CheckRunnerSandbox } from "../src/adapters/check-runner-sandbox.ts";54 import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";55 import { LanderSandbox } from "../src/adapters/lander-sandbox.ts";56+import type { SandboxMethod } from "../src/adapters/sandbox-credentials.ts";57 58 const project = ProjectName.make("alice/datekit");59 60 const canonical = RepoName.make("alice__datekit");677 unmodified lines738 expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);739 })740 );741 });742+743+// The runtime gives each object an RPC call returns a disposer of its own,744+// which holds the far side's call open until it is called.745+const recorded =746+ <WI, X>(747+ disposals: string[],748+ method: SandboxMethod,749+ send: (wire: WI) => Promise<X>750+ ) =>751+ (wire: WI): Promise<X> =>752+ Effect.runPromise(753+ Effect.tap(754+ Effect.promise(() => send(wire)),755+ (reply) =>756+ Effect.sync(() => {757+ if (Predicate.isObjectKeyword(reply)) {758+ Object.defineProperty(reply, Symbol.dispose, {759+ enumerable: false,760+ value: () => {761+ disposals.push(method);762+ },763+ });764+ }765+ })766+ )767+ );768+769+describe("a sandbox job's result", () => {770+ it.effect(771+ "is disposed once it is read, so no job holds the sandbox's call open",772+ () =>773+ Effect.gen(function* () {774+ const disposals: string[] = [];775+776+ const ok = yield* world({777+ binding: (sandbox) => ({778+ bundleRules: recorded(779+ disposals,780+ "bundleRules",781+ sandbox.bundleRules782+ ),783+ check: recorded(disposals, "check", sandbox.check),784+ compose: recorded(disposals, "compose", sandbox.compose),785+ land: recorded(disposals, "land", sandbox.land),786+ merge: recorded(disposals, "merge", sandbox.merge),787+ }),788+ });789+790+ const exits = yield* Effect.forEach(everyJob(ok), (job) =>791+ Effect.exit(job)792+ );793+794+ expect(exits.every(Exit.isSuccess)).toBeTruthy();795+ expect(disposals.toSorted()).toStrictEqual([796+ "bundleRules",797+ "check",798+ "compose",799+ "land",800+ "land",801+ "merge",802+ ]);803+ })804+ );805+});modified:apps/platform/test/watch.test.ts+57 added
33 unmodified lines34 import type { ProjectNamespace } from "../src/adapters/do-projects.ts";35 import { decodeEnv } from "../src/platform.ts";36 import { workerPorts } from "../src/ports.ts";37 import {38+ closeEnd,39 ProjectSockets,40 WATCH_TAG,41 WatchFrame,42 watchHandler,519 unmodified lines562 }).pipe(Effect.provide(doWorld))563 );564 });565 566+// Records every `close()`, and refuses a code a close only reports, as workerd does.567+const closingSocket = () => {568+ const closes: (readonly [number | undefined, string | undefined])[] = [];569+570+ const socket = untouchable<WebSocket>("WebSocket", {571+ close: (code?: number, reason?: string) => {572+ closes.push([code, reason]);573+574+ if (code === 1005 || code === 1006 || code === 1015) {575+ throw new DOMException(576+ `Invalid WebSocket close code: ${code}.`,577+ "InvalidAccessError"578+ );579+ }580+ },581+ });582+583+ return { closes, socket };584+};585+586+describe("a Project DO's answer to a watch socket's close", () => {587+ it.effect(588+ "answers a clean close with the peer's code, and one that carried no code with 1000",589+ () =>590+ Effect.gen(function* () {591+ const { closes, socket } = closingSocket();592+593+ yield* closeEnd(socket, { code: 1000, reason: "bye", wasClean: true });594+ yield* closeEnd(socket, { code: 4000, reason: "", wasClean: true });595+ yield* closeEnd(socket, { code: 1005, reason: "", wasClean: true });596+597+ expect(closes).toStrictEqual([598+ [1000, "bye"],599+ [4000, ""],600+ [1000, ""],601+ ]);602+ })603+ );604+605+ it.effect(606+ "lets a socket that went without a close frame (1006) go without calling close: there is no peer left to answer",607+ () =>608+ Effect.gen(function* () {609+ const { closes, socket } = closingSocket();610+611+ yield* closeEnd(socket, {612+ code: 1006,613+ reason: "WebSocket disconnected without sending Close frame.",614+ wasClean: false,615+ });616+617+ expect(closes).toStrictEqual([]);618+ })619+ );620+});621+622 const socketPair = (gone: (socket: WebSocket) => void) => {623 const events = new EventTarget<WebSocketEventMap>();624 const held: string[] = [];625 let listening = false;222 unmodified linesmodified:apps/platform/test/well-known.test.ts+2 added-2 removed
302 unmodified lines303 );304 305 describe("the agent skills index, kept by each project's landed commit", () => {306 it.effect(307- "reads each skill once while no main moves, wakes no project while no listed project lands, and reads again only the skill whose main moved",307+ "reads each skill once while no main moves, wakes no project while no listed project lands, and after a landing wakes only the project that landed and reads again only its skill",308 () =>309 Effect.gen(function* () {310 const counts = yield* Ref.make({ files: 0, refs: 0 });311 const heads = yield* Ref.make(0);91 unmodified lines403 twice,404 }).toStrictEqual({405 afterMove: ["Answer any one of datekit's asks."],406 once: ["Answer one of datekit's asks."],407- readAfterMove: { files: 1, heads: 2, refs: 0 },407+ readAfterMove: { files: 1, heads: 1, refs: 0 },408 readOnce: { files: 2, heads: 2, refs: 0 },409 readTwice: { files: 0, heads: 0, refs: 0 },410 twice: ["Answer one of datekit's asks."],411 });13 unmodified linesmodified:apps/sandbox/images/check.Dockerfile+5 added-2 removed
1 # The Checker's image: where an answer's checks run, with no credentials2 # (`src/checker/run.ts` runs the phases). Debian trixie slim with3-# Node 24, Bun 1.4.2, git and corepack (pnpm and Yarn, fetched from the npm3+# Node 26, Bun 1.4.2, git and corepack (pnpm and Yarn, fetched from the npm4 # registry during setup), plus the Sandbox SDK's `sandbox-shim`, which `Files`5 # runs. Nothing is copied from the build context, and no token, remote or6 # secret is baked in: the clone goes through the Worker's clone gateway.7 #2 unmodified lines10 # runs (/etc/cloudflare/certs/cloudflare-containers-ca.crt), never here; the11 # Checker points git, Node, Bun, pip and cargo at it through their env vars.12 FROM docker.io/cloudflare/sandbox:1.0.0 AS shim13 FROM docker.io/oven/bun:1.4.2-slim AS bun14+# Node 26 for `node:ffi`, which a terminal UI's tests load under Node. It no15+# longer ships corepack, so corepack comes from npm, pinned.14-FROM docker.io/library/node:24-trixie-slim16+FROM docker.io/library/node:26-trixie-slim17 18 RUN apt-get update \19 && apt-get install -y --no-install-recommends ca-certificates git \20 && rm -rf /var/lib/apt/lists/* \21+ && npm install -g corepack@0.34.0 \22 && corepack enable23 24 COPY --from=shim /usr/local/bin/sandbox-shim /usr/local/bin/sandbox-shim25 COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun8 unmodified linesmodified:apps/sandbox/src/checker.ts+8 added-3 removed
14 unmodified lines15 import { blocked, check } from "./checker/run.ts";16 import { hasGateways, SdkChecker } from "./checker/sdk.ts";17 import { answerJob } from "./job.ts";18 import type { Job } from "./job.ts";19+import { disposed } from "./rpc-result.ts";20 import { jobTelemetry } from "./telemetry.ts";21 22 const DEFAULT_IMAGE = "checker:default";23 81 unmodified lines105 }),106 SdkChecker.layer(107 container,108 exports,109+ // A snapshot is the whole root filesystem, so it is kept by the110+ // image that took it: a new image sets up again rather than bring111+ // back an older image's toolchain.112 {109- find: (key) => index.snapshotOf(key),110- forget: (key) => index.forgetSnapshot(key),111- keep: (key, id) => index.keepSnapshot(key, id),113+ find: (key) => index.snapshotOf(`${image}:${key}`),114+ forget: (key) => index.forgetSnapshot(`${image}:${key}`),115+ keep: (key, id) => index.keepSnapshot(`${image}:${key}`, id),116 },117 {118 instance: checkInstance,119 // The hosts its env route may open, reserved ahead of the35 unmodified lines155 Effect.runPromise(156 Effect.tryPromise(() =>157 env.CHECKER.get(env.CHECKER.newUniqueId()).check(wire)158 ).pipe(159+ Effect.flatMap(disposed),160 Effect.flatMap(Schema.decodeEffect(CheckExit)),161 Effect.tapError((failure) =>162 Effect.logError("the Checker could not be reached").pipe(163 Effect.annotateLogs({ reason: String(failure) })8 unmodified linesmodified:apps/sandbox/src/lander.ts+9 added-4 removed
16 unmodified lines17 import type { Box } from "./box.ts";18 import { SdkBox } from "./box/sdk.ts";19 import { answerJob } from "./job.ts";20 import { bundleRules, compose, land, merge } from "./lander/run.ts";21+import { passedOn } from "./rpc-result.ts";22 23 export const landImage = "land";24 25 // A Lander job names no repo: a repo's name is no id (AGENTS.md principle 7).118 unmodified lines144 145 export const runMerge = (146 env: Landers,147 wire: typeof MergeWire.Encoded147-): Promise<typeof MergeExit.Encoded> => landerOf(env, wire).merge(wire);148+): Promise<typeof MergeExit.Encoded> =>149+ passedOn(() => landerOf(env, wire).merge(wire));150 151 export const runLand = (152 env: Landers,153 wire: typeof LandWire.Encoded152-): Promise<typeof LandExit.Encoded> => landerOf(env, wire).land(wire);154+): Promise<typeof LandExit.Encoded> =>155+ passedOn(() => landerOf(env, wire).land(wire));156 157 export const runCompose = (158 env: Landers,159 wire: typeof ComposeWire.Encoded157-): Promise<typeof ComposeExit.Encoded> => landerOf(env, wire).compose(wire);160+): Promise<typeof ComposeExit.Encoded> =>161+ passedOn(() => landerOf(env, wire).compose(wire));162 163 export const runBundleRules = (164 env: Landers,165 wire: typeof BundleWire.Encoded162-): Promise<typeof BundleExit.Encoded> => landerOf(env, wire).bundleRules(wire);166+): Promise<typeof BundleExit.Encoded> =>167+ passedOn(() => landerOf(env, wire).bundleRules(wire));added:apps/sandbox/src/rpc-result.ts+38 added
1+import { Effect, Predicate } from "effect";2+3+/**4+ * Workers RPC puts a `Symbol.dispose` on every object a call returns. Where5+ * the far side's own result carried a disposer, its call stays open until6+ * that is called, and a result left to the garbage collector draws the7+ * runtime's "An RPC result was not disposed properly". Every result here is8+ * data, whole once it arrives, so each is disposed as soon as it lands; on a9+ * result with nothing to release, disposing does nothing.10+ */11+export const disposed = <A>(result: A): Effect.Effect<A> =>12+ Effect.try(() => {13+ const dispose = Predicate.hasProperty(result, Symbol.dispose)14+ ? result[Symbol.dispose]15+ : undefined;16+17+ if (Predicate.isFunction(dispose)) {18+ dispose.call(result);19+ }20+ }).pipe(Effect.ignore, Effect.as(result));21+22+/**23+ * A Durable Object's reply, to be returned from the sandbox's own RPC method.24+ * Passed on as it came, it would carry the disposer the runtime gave it, so25+ * the platform's call would stay open until the platform disposed of it. The26+ * reply is copied instead (a structured clone keeps no symbol-keyed27+ * property), and disposed here.28+ */29+export const passedOn = <X>(call: () => Promise<X>): Promise<X> =>30+ Effect.runPromise(31+ Effect.promise(call).pipe(32+ Effect.flatMap((reply) =>33+ Effect.sync(() => structuredClone(reply)).pipe(34+ Effect.ensuring(disposed(reply))35+ )36+ )37+ )38+ );modified:apps/sandbox/test/checker.test.ts+42 added-1 removed
705 unmodified lines706 707 const checkerWorld = (options: {708 readonly withGateways: boolean;709 readonly running?: boolean;710+ /** Each container's image, in turn; the last one stays. */711+ readonly images?: readonly string[];712 }) => {713 const boxes: ReturnType<typeof fakeContainer>[] = [];714 const index = new Map<string, string>();715 const named: string[] = [];29 unmodified lines745 746 const checkers: Checkers = {747 CHECKER: {748 get: () => {747- const box = fakeContainer({ running: options.running ?? true });749+ const box = fakeContainer({750+ image: options.images?.[boxes.length] ?? options.images?.at(-1),751+ running: options.running ?? true,752+ });753 754 boxes.push(box);755 756 // The Worker's other exports are not the Checker's to touch: only123 unmodified lines880 })881 );882 883 it.effect(884+ "sets up again on a new image, never starting from a snapshot an older image took",885+ () =>886+ Effect.gen(function* () {887+ const world = checkerWorld({888+ images: [889+ "registry.cloudflare.com/sandbox/check:315",890+ "registry.cloudflare.com/sandbox/check:316",891+ "registry.cloudflare.com/sandbox/check:316",892+ ],893+ withGateways: true,894+ });895+896+ const wire = yield* encodedWire();897+898+ yield* Effect.forEach([wire, wire, wire], (each) =>899+ Effect.promise(() => runCheck(world.checkers, each))900+ );901+902+ expect(903+ world.boxes.map(({ calls }) =>904+ calls.flatMap((call) => (call.kind === "start" ? [call.from] : []))905+ )906+ ).toStrictEqual([[], [], ["snapshot-1"]]);907+ expect(908+ world.boxes.map(909+ ({ calls }) =>910+ calls.filter(911+ (call) => call.kind === "exec" && call.argv.includes(SETUP)912+ ).length913+ )914+ ).toStrictEqual([1, 1, 0]);915+ expect(world.index.size).toBe(2);916+ })917+ );918+919+ it.effect(920 "starts each container on two vCPUs and 8 GiB, from the image and from a snapshot alike",921 () =>922 Effect.gen(function* () {923 const { boxes } = yield* twoJobsIn({ running: false });35 unmodified linesmodified:apps/sandbox/test/fake-box.ts+5 added-2 removed
217 unmodified lines218 219 return buffer;220 };221 222-export const fakeContainer = ({ running = true } = {}) => {222+export const fakeContainer = ({223+ image = "registry.cloudflare.com/sandbox/check:315",224+ running = true,225+} = {}) => {226 const calls: ContainerCall[] = [];227 const gateways = new Map<Fetcher, string>();228 229 const gateway = (description: string) => {25 unmodified lines255 }),256 })257 );258 },256- images: { check: "registry.cloudflare.com/sandbox/check:315" },259+ images: { check: image },260 interceptAllOutboundHttp: (binding) => {261 calls.push({262 kind: "intercept",263 target: "http:*",45 unmodified linesmodified:apps/sandbox/test/lander.test.ts+51 added-1 removed
24 unmodified lines25 } from "effect";26 27 import { Box } from "../src/box.ts";28 import { Lander, landerJobs, runMerge } from "../src/lander.ts";29+import type { LanderJobs } from "../src/lander.ts";30 import { bundleRules, compose, land, merge } from "../src/lander/run.ts";31 import { landScript, mergeScript } from "../src/lander/script.ts";32 import {33 bob,259 unmodified lines293 territory: ".",294 vouched: true,295 });296 297+// Each case makes and merges real repos with git, which outlasts the default298+// 5s while every workspace's tests share the machine, as in the Checker.296-describe("the Lander's git", () => {299+describe("the Lander's git", { timeout: 30_000 }, () => {300 describe(merge, () => {301 it.live(302 "merges a clean answer onto main: the tree git's own merge makes, the answer's changes, nothing written to canonical, and the merged commit kept on the fork for the Checker",303 () =>791 unmodified lines1095 url: "https://artifacts.invalid/datekit.git",1096 },1097 };1098 1099+const notThisJob = () => Promise.reject(new Error("not this job"));1100+1101 describe("the Lander's Durable Objects", () => {1102+ it.effect(1103+ "passes on a copy of the Lander's reply, with no disposer for the platform to call, and disposes the reply itself",1104+ () =>1105+ Effect.gen(function* () {1106+ const disposals: string[] = [];1107+1108+ const reply = yield* Schema.encodeEffect(MergeExit)(1109+ Exit.fail(1110+ new StaleBase({1111+ base: idleMerge.job.base,1112+ conflicts: [],1113+ main: idleMerge.job.main,1114+ })1115+ )1116+ );1117+1118+ // The runtime gives each object an RPC call returns a disposer of its1119+ // own, which holds the far side's call open until it is called.1120+ const jobs: LanderJobs = {1121+ bundleRules: notThisJob,1122+ compose: notThisJob,1123+ land: notThisJob,1124+ merge: () =>1125+ Promise.resolve(1126+ Object.defineProperty(structuredClone(reply), Symbol.dispose, {1127+ enumerable: false,1128+ value: () => {1129+ disposals.push("merge");1130+ },1131+ })1132+ ),1133+ };1134+1135+ const wire = yield* Schema.encodeEffect(MergeWire)(idleMerge);1136+1137+ const passed = yield* Effect.promise(() =>1138+ runMerge({ LANDER: { getByName: () => jobs } }, wire)1139+ );1140+1141+ expect(passed).toStrictEqual(reply);1142+ expect(Predicate.hasProperty(passed, Symbol.dispose)).toBeFalsy();1143+ expect(disposals).toStrictEqual(["merge"]);1144+ })1145+ );1146+1147 it.live(1148 "runs each job in the Lander named by the job's canonical repo: the wire decoded, the job run, its Exit encoded",1149 () =>1150 Effect.gen(function* () {137 unmodified linesmodified:apps/sandbox/test/telemetry.test.ts+4 added-1 removed
113 unmodified lines114 const { spans } = yield* observed(checkJob, checkWire, () =>115 Effect.die(new TypeError(`no file at ${sealedPath}`))116 );117 118- expect(spans[1]?.exceptions).toStrictEqual([{ name: "TypeError" }]);118+ expect(119+ spans[1]?.exceptions.map(({ name, text }) => ({ name, text }))120+ ).toStrictEqual([{ name: "TypeError", text: "TypeError: <withheld>" }]);121+ expect(JSON.stringify(spans[1]?.exceptions)).not.toContain(sealedPath);122 })123 );124 125 it.effect("carries none of its tokens in a line it logs", () =>41 unmodified linesadded:apps/web/public/og.pngbinary
A binary file, added.
modified:apps/web/src/routes/[.]well-known/agent-skills/$.ts+4 added-1 removed
2 unmodified lines3 4 import { backend } from "#backend";5 6 import { forwarded } from "../../../features/agents/forward.ts";7+import { keptPage } from "../../../server/kept-pages.ts";8 9+const { GET, HEAD } = forwarded(backend, env);10+11 export const Route = createFileRoute("/.well-known/agent-skills/$")({9- server: { handlers: forwarded(backend, env) },12+ server: { handlers: { GET: keptPage(GET), HEAD } },13 });modified:apps/web/src/routes/$owner/$project/asks/{$ask}[.]md.ts+4 added-1 removed
8 unmodified lines9 askMarkdownResponse,10 noAskAt,11 } from "../../../../features/ask/markdown.ts";12 import { serverClient } from "../../../../server/client.ts";13+import { keptPage } from "../../../../server/kept-pages.ts";14 15 export interface AskParams {16 readonly ask: string;17 readonly project: string;36 unmodified lines54 55 export const Route = createFileRoute("/$owner/$project/asks/{$ask}.md")({56 server: {57 handlers: {57- GET: askMarkdownHandler((request) => serverClient(env, request)),58+ GET: keptPage(59+ askMarkdownHandler((request) => serverClient(env, request))60+ ),61 },62 },63 });modified:apps/web/src/routes/$owner/$project/llms[.]txt.ts+6 added-3 removed
1 import { createFileRoute } from "@tanstack/react-router";2 import { env } from "cloudflare:workers";3 4 import { serverClient } from "../../../server/client.ts";5+import { keptPage } from "../../../server/kept-pages.ts";6 import { projectLlmsHandler } from "../../../server/llms.ts";7 8 export const Route = createFileRoute("/$owner/$project/llms.txt")({9 server: {10 handlers: {11+ GET: keptPage(10- GET: projectLlmsHandler(11- (request) => serverClient(env, request),12- env.PUBLIC_PLATFORM_URL12+ projectLlmsHandler(13+ (request) => serverClient(env, request),14+ env.PUBLIC_PLATFORM_URL15+ )16 ),17 },18 },19 });modified:apps/web/src/routes/auth/signout.ts+1 added-1 removed
4 unmodified lines5 import { signOutHandler } from "../../server/session.ts";6 7 // A development build serves the dev world, which has no platform to sign out of, as in `signin.ts`.8 const signOut = signOutHandler(9- import.meta.env.DEV ? Option.none() : Option.some(env.PUBLIC_PLATFORM_URL)9+ import.meta.env.DEV ? Option.none() : Option.some(env)10 );11 12 export const Route = createFileRoute("/auth/signout")({13 server: {6 unmodified linesmodified:apps/web/src/routes/auth/whoami.ts+1 added-1 removed
5 unmodified lines6 7 export const Route = createFileRoute("/auth/whoami")({8 server: {9 handlers: {10- GET: whoamiHandler((request) => serverClient(env, request)),10+ GET: whoamiHandler(env, (request) => serverClient(env, request)),11 },12 },13 });modified:apps/web/src/routes/__root.tsx+9 added
105 unmodified lines106 "A git platform where a project says what it wants as asks, anyone may answer, and a change lands on main only by passing a typed gate, with credit for every person involved.";107 108 const ICON_PATH = "/icons/icon.svg";109 110+// The unfurl's card: the repeat button emoji beside the domain, on the dark paper. A crawler reads111+// og:image only as an absolute URL, and the card names prod's domain, so it points there on every stage.112+export const OG_IMAGE_URL = `https://${Brand.domain}/og.png`;113+114 // Fonts are fetched without credentials whatever their origin, so the preload says so too,115 // or the browser fetches the file twice.116 const fontPreload = (href: string) =>117 ({23 unmodified lines141 { content: Brand.name, property: "og:title" },142 { content: SITE_DESCRIPTION, property: "og:description" },143 { content: "website", property: "og:type" },144 { content: Brand.name, property: "og:site_name" },145+ { content: OG_IMAGE_URL, property: "og:image" },146+ { content: "1200", property: "og:image:width" },147+ { content: "630", property: "og:image:height" },148+ { content: Brand.domain, property: "og:image:alt" },149+ { content: "summary_large_image", name: "twitter:card" },150 ],151 });152 153 export const Route = createRootRoute({7 unmodified linesmodified:apps/web/src/routes/llms[.]txt.ts+6 added-3 removed
1 import { createFileRoute } from "@tanstack/react-router";2 import { env } from "cloudflare:workers";3 4 import { serverClient } from "../server/client.ts";5+import { keptPage } from "../server/kept-pages.ts";6 import { frontLlmsHandler } from "../server/llms.ts";7 8 export const Route = createFileRoute("/llms.txt")({9 server: {10 handlers: {11+ GET: keptPage(10- GET: frontLlmsHandler(11- (request) => serverClient(env, request),12- env.PUBLIC_PLATFORM_URL12+ frontLlmsHandler(13+ (request) => serverClient(env, request),14+ env.PUBLIC_PLATFORM_URL15+ )16 ),17 },18 },19 });modified:apps/web/src/server/edge-cache.ts+5 added-3 removed
1 // Workers Cache keys an answer by path and query alone, not by host, `Cookie` or `Authorization`.2 // An answer to a request with a credential, one that sets a cookie, or one with no `Cache-Control` is kept nowhere;3 // any other varies by `Cookie`, so a signed-in reader is never handed a page kept from a signed-out one.4-// A page the edge keeps is served stale for a day while it is read again, so a page seldom visited still answers5-// at the edge's speed; the browser keeps its own `Cache-Control`, and a page's events bring it up to date once drawn.4+// A page the edge keeps is served stale for a day to the readers who come while it is read again, though the one5+// reader who finds it expired waits for the Worker (`EXPIRED`), as does the first after a deploy; an agent's page is6+// kept by the Worker as well (`kept-pages.ts`), so that reader is answered at once too. The browser keeps its own7+// `Cache-Control`, and a page's events bring it up to date once drawn.8 import { Effect } from "effect";9 10 export const KEPT_NOWHERE = "private, no-store";11 8 unmodified lines20 .split(",")21 .map((directive) => directive.trim().toLowerCase())22 .filter((directive) => directive !== "");23 22-const speaksForSomeone = (request: Request) =>24+export const speaksForSomeone = (request: Request) =>25 request.headers.has("cookie") || request.headers.has("authorization");26 27 // A field-naming directive (`private="set-cookie"`) lets the cache store the answer with that field stripped.28 const unsafeFor = (cacheControl: string | null) =>107 unmodified linesadded:apps/web/src/server/kept-pages.ts+282 added
1+// An agent's document (`/llms.txt`, a project's, an ask's Markdown, the agent skills index) names no hashed asset,2+// so a copy of it is still whole after a deploy. Workers Cache keeps it per Worker version, and answers the first3+// reader after it expires, and every first reader after a deploy, only once the Worker has read the platform again.4+// So the Worker keeps its last answer to each in its colo's Cache API as well, hands it back at once while it is no5+// older than the edge's stale window, and reads it again in the background once it is past the route's `max-age`.6+// A request that says who is reading is neither handed a kept answer nor kept, as at the edge, and so is any answer7+// but a 200 that may be kept for a while.8+import { waitUntil } from "cloudflare:workers";9+import { Clock, Effect, Option, Schema } from "effect";10+11+import { EDGE_STALE_SECONDS, speaksForSomeone } from "./edge-cache.ts";12+13+/** One answer as it was kept, and the instant, in epoch milliseconds, it was read from the platform. */14+export interface KeptPage {15+ readonly body: string;16+ readonly cacheControl: string;17+ readonly contentType: string;18+ readonly keptAt: number;19+}20+21+export interface PageKeeper {22+ readonly get: (key: string) => Effect.Effect<Option.Option<KeptPage>>;23+ readonly put: (key: string, page: KeptPage) => Effect.Effect<void>;24+ /** Runs the work after the answer has gone, as the request's own. */25+ readonly inBackground: (work: Effect.Effect<void>) => Effect.Effect<void>;26+}27+28+const directivesOf = (cacheControl: string) =>29+ cacheControl30+ .split(",")31+ .map((directive) => directive.trim().toLowerCase())32+ .filter((directive) => directive !== "");33+34+// An answer kept by nobody, or one that forbids serving it stale, is never kept here either.35+const NOT_KEPT = new Set([36+ "private",37+ "no-store",38+ "no-cache",39+ "must-revalidate",40+ "proxy-revalidate",41+]);42+43+const MAX_AGE = "max-age=";44+45+const MaxAge = Schema.FiniteFromString.check(Schema.isGreaterThan(0));46+47+const decodeMaxAge = Schema.decodeUnknownOption(MaxAge);48+49+/** How long the route says its answer is fresh, in seconds; none when it may not be kept. */50+const maxAgeOf = (cacheControl: string): Option.Option<number> => {51+ const directives = directivesOf(cacheControl);52+53+ const forbids = directives.some(54+ (directive) =>55+ NOT_KEPT.has(directive) ||56+ directive.startsWith("private=") ||57+ directive.startsWith("no-cache=")58+ );59+60+ return forbids61+ ? Option.none()62+ : Option.firstSomeOf(63+ directives.map((directive) =>64+ directive.startsWith(MAX_AGE)65+ ? decodeMaxAge(directive.slice(MAX_AGE.length))66+ : Option.none()67+ )68+ );69+};70+71+// Kept by its path alone, so a query string never makes a second copy.72+export const keptKeyOf = (request: Request) => {73+ const { origin, pathname } = new URL(request.url);74+75+ return `${origin}${pathname}`;76+};77+78+const answerOf = ({ body, cacheControl, contentType }: KeptPage) =>79+ new Response(body, {80+ headers: { "cache-control": cacheControl, "content-type": contentType },81+ status: 200,82+ });83+84+const keepable = (response: Response) => {85+ const cacheControl = response.headers.get("cache-control");86+ const contentType = response.headers.get("content-type");87+88+ return response.status !== 200 ||89+ response.headers.has("set-cookie") ||90+ cacheControl === null ||91+ contentType === null ||92+ Option.isNone(maxAgeOf(cacheControl))93+ ? Option.none()94+ : Option.some({ cacheControl, contentType });95+};96+97+/**98+ * The route's answer, kept when it may be. It is read whole, since a page an99+ * agent reads is a few kilobytes of text.100+ */101+const readAndKeep = (102+ keeper: PageKeeper,103+ key: string,104+ render: Effect.Effect<Response>105+) =>106+ Effect.gen(function* () {107+ const response = yield* render;108+ const kept = keepable(response);109+110+ if (Option.isNone(kept)) {111+ return response;112+ }113+114+ const page: KeptPage = {115+ ...kept.value,116+ body: yield* Effect.promise(() => response.text()),117+ keptAt: yield* Clock.currentTimeMillis,118+ };119+120+ yield* keeper.inBackground(keeper.put(key, page));121+122+ return answerOf(page);123+ });124+125+const MILLIS = 1000;126+127+/**128+ * The kept answer while it is fresh, and while it is stale within the edge's129+ * window, with the route read again in the background; the route's own answer130+ * otherwise.131+ */132+export const servedKept =133+ (keeper: PageKeeper) =>134+ (135+ request: Request,136+ render: Effect.Effect<Response>137+ ): Effect.Effect<Response> =>138+ Effect.gen(function* () {139+ if (request.method !== "GET" || speaksForSomeone(request)) {140+ return yield* render;141+ }142+143+ const key = keptKeyOf(request);144+ const kept = yield* keeper.get(key);145+146+ if (Option.isNone(kept)) {147+ return yield* readAndKeep(keeper, key, render);148+ }149+150+ const page = kept.value;151+ const age = (yield* Clock.currentTimeMillis) - page.keptAt;152+ const fresh = Option.getOrElse(maxAgeOf(page.cacheControl), () => 0);153+154+ if (age <= fresh * MILLIS) {155+ return answerOf(page);156+ }157+158+ if (age <= (fresh + EDGE_STALE_SECONDS) * MILLIS) {159+ yield* keeper.inBackground(160+ Effect.asVoid(readAndKeep(keeper, key, render))161+ );162+163+ return answerOf(page);164+ }165+166+ return yield* readAndKeep(keeper, key, render);167+ });168+169+/** A route's handler with its answer kept by `keeper`. */170+export const keptBy =171+ (keeper: PageKeeper) =>172+ <Args extends { readonly request: Request }>(173+ handler: (args: Args) => Promise<Response> | Response174+ ) =>175+ (args: Args): Promise<Response> =>176+ Effect.runPromise(177+ servedKept(keeper)(178+ args.request,179+ Effect.promise(() => Promise.resolve(handler(args)))180+ )181+ );182+183+const KeptHeaders = Schema.Struct({184+ cacheControl: Schema.NonEmptyString,185+ contentType: Schema.NonEmptyString,186+ keptAt: Schema.FiniteFromString,187+});188+189+const decodeKeptHeaders = Schema.decodeUnknownOption(KeptHeaders);190+191+const KEPT_AT = "x-kept-at";192+193+const KEPT_CACHE_CONTROL = "x-kept-cache-control";194+195+const quietly = (work: Effect.Effect<void>) =>196+ Effect.catchCause(work, (cause) =>197+ Effect.logWarning("an agent's page was not kept", cause)198+ );199+200+/**201+ * A cache of the colo's Cache API, which keeps an entry for as long as its own202+ * `Cache-Control` says: the route's age and the edge's stale window. A failed203+ * read is a miss, and a failed write keeps nothing.204+ */205+export const cacheApiKeeper = (206+ open: () => Promise<Cache>,207+ background: (promise: Promise<unknown>) => void208+): PageKeeper => ({209+ get: (key) =>210+ Effect.tryPromise(open).pipe(211+ Effect.flatMap((cache) => Effect.tryPromise(() => cache.match(key))),212+ Effect.flatMap((found) =>213+ found === undefined214+ ? Effect.succeedNone215+ : Option.match(216+ decodeKeptHeaders({217+ cacheControl: found.headers.get(KEPT_CACHE_CONTROL),218+ contentType: found.headers.get("content-type"),219+ keptAt: found.headers.get(KEPT_AT),220+ }),221+ {222+ onNone: () =>223+ Effect.as(224+ Effect.tryPromise(225+ () => found.body?.cancel() ?? Promise.resolve()226+ ),227+ Option.none<KeptPage>()228+ ),229+ onSome: (headers) =>230+ Effect.map(231+ Effect.tryPromise(() => found.text()),232+ (body) => Option.some({ ...headers, body })233+ ),234+ }235+ )236+ ),237+ Effect.orElseSucceed(Option.none<KeptPage>)238+ ),239+ inBackground: (work) =>240+ Effect.sync(() => {241+ background(Effect.runPromise(quietly(work)));242+ }),243+ put: (key, page) =>244+ Effect.tryPromise(open).pipe(245+ Effect.flatMap((cache) =>246+ Effect.tryPromise(() =>247+ cache.put(248+ key,249+ new Response(page.body, {250+ headers: {251+ "cache-control": `public, max-age=${252+ Option.getOrElse(maxAgeOf(page.cacheControl), () => 0) +253+ EDGE_STALE_SECONDS254+ }`,255+ "content-type": page.contentType,256+ [KEPT_AT]: String(page.keptAt),257+ [KEPT_CACHE_CONTROL]: page.cacheControl,258+ },259+ })260+ )261+ )262+ ),263+ Effect.ignore264+ ),265+});266+267+/** Keeps nothing, so every request reads the route: `vite dev`'s, as Workers Cache is off there too. */268+export const keepsNothing: PageKeeper = {269+ get: () => Effect.succeedNone,270+ inBackground: () => Effect.void,271+ put: () => Effect.void,272+};273+274+// A cache of its own, so no entry in it is ever the edge's answer to a page.275+const AGENT_PAGES = "agent-pages";276+277+/** The deployed Worker's keeper, a cache of the colo's own; `vite dev` keeps nothing. */278+export const keptPage = keptBy(279+ import.meta.env.PROD280+ ? cacheApiKeeper(() => caches.open(AGENT_PAGES), waitUntil)281+ : keepsNothing282+);modified:apps/web/src/server/session.ts+284 added-59 removed
1 // The access token lives only in an HttpOnly cookie: no URL, log line or response body carries it, and the web2 // holds no secret (PKCE, and a Client ID Metadata Document it serves itself). The handle cookie beside it only3 // shapes what a page shows; every call carries the token, and the platform decides who the caller is.4+// The refresh token lives in an HttpOnly cookie of its own, read only where a session is renewed: a page's5+// navigation and `/auth/whoami`, one request each, so two renewals seldom race over one rotating refresh token.6 import { Brand } from "@repo/brand";7 import { Client } from "@repo/protocol/contracts";8 import { Handle as HandleSchema } from "@repo/protocol/ids";9 import type { Handle } from "@repo/protocol/ids";8-import { Data, Effect, Option, Redacted, Schema } from "effect";10+import { Clock, Data, Effect, Option, Redacted, Result, Schema } from "effect";11 import type { Layer } from "effect";12 13 // `__Host-` keeps it to this exact origin over HTTPS, so no sibling host on the same `workers.dev` subdomain can set or shadow it.14 export const SESSION_COOKIE = "__Host-session";15 16 export const HANDLE_COOKIE = "__Host-handle";17 18+export const RENEW_COOKIE = "__Host-renew";19+20+// As long as the platform's refresh token lasts by default; the platform ends it sooner if it must.21+const RENEW_SECONDS = 30 * 24 * 60 * 60;22+23+// A session is renewed this long before its token lapses, so a page drawn now still has its token when it calls.24+const RENEW_MARGIN_SECONDS = 5 * 60;25+26 const SIGN_IN_COOKIE = "__Host-sign-in";27 28 const SIGN_IN_SECONDS = 600;29 63 unmodified lines93 lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);94 95 export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);96 97+// A session the platform no longer takes: its refresh token stays, for the next navigation to renew it with.98 export const clearedCookies = () => [99 clearedCookie(),100 lockedCookie(HANDLE_COOKIE, "", 0),101 ];102 103+// A session ended: signed out, or its refresh token refused.104+const endedCookies = () => [105+ ...clearedCookies(),106+ lockedCookie(RENEW_COOKIE, "", 0),107+];108+109 const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);110 111 export const settingCookies = (112 headers: HeadersInit,195 unmodified lines308 309 const TokenAnswer = Schema.Struct({310 access_token: Schema.RedactedFromValue(Token),311 expires_in: Schema.Int.check(Schema.isGreaterThan(0)),312+ refresh_token: Schema.optionalKey(Schema.RedactedFromValue(Token)),313 token_type: Schema.String,314 });315 316+type TokenAnswer = typeof TokenAnswer.Type;317+318 const decodeTokenAnswer = Schema.decodeEffect(319 Schema.fromJsonString(TokenAnswer)320 );321 302-const exchange = (303- env: Env,304- input: {305- readonly code: string;306- readonly origin: string;307- readonly verifier: string;308- }309-) =>322+const tokenCall = (env: Env, fields: Readonly<Record<string, string>>) =>323 Effect.gen(function* () {324 const response = yield* Effect.tryPromise({325 catch: () => unreachablePlatform,326 try: () =>327 env.PLATFORM.fetch(328 new Request(new URL("/token", env.PUBLIC_PLATFORM_URL), {316- body: new URLSearchParams({317- client_id: clientIdOf(input.origin),318- code: input.code,319- code_verifier: input.verifier,320- grant_type: "authorization_code",321- redirect_uri: redirectUriOf(input.origin),322- }),329+ body: new URLSearchParams(fields),330 headers: {331 accept: "application/json",332 "content-type": "application/x-www-form-urlencoded",333 },21 unmodified lines355 356 return answer;357 });358 359+const exchange = (360+ env: Env,361+ input: {362+ readonly code: string;363+ readonly origin: string;364+ readonly verifier: string;365+ }366+) =>367+ tokenCall(env, {368+ client_id: clientIdOf(input.origin),369+ code: input.code,370+ code_verifier: input.verifier,371+ grant_type: "authorization_code",372+ redirect_uri: redirectUriOf(input.origin),373+ });374+375+// `<lapse>.<refresh token>`: the token's lapse in epoch seconds, then the token that renews it.376+const Renewal = Schema.Struct({ lapse: Schema.Int, refreshToken: Token });377+378+type Renewal = typeof Renewal.Type;379+380+const decodeRenewal = Schema.decodeUnknownOption(Renewal);381+382+const renewalFrom = (request: Request) =>383+ Option.flatMap(cookieValue(request, RENEW_COOKIE), (value) => {384+ const at = value.indexOf(".");385+386+ return at > 0387+ ? decodeRenewal({388+ lapse: Number(value.slice(0, at)),389+ refreshToken: value.slice(at + 1),390+ })391+ : Option.none();392+ });393+394+/** The cookies an answer from `/token` sets: the session, and the refresh token beside it with its lapse. */395+const sessionCookies = (answer: TokenAnswer) =>396+ Effect.map(Clock.currentTimeMillis, (now) => {397+ const lapse = Math.floor(now / 1000) + answer.expires_in;398+399+ return [400+ sessionCookie(401+ Redacted.value(answer.access_token),402+ answer.expires_in - SESSION_MARGIN_SECONDS403+ ),404+ ...Option.toArray(405+ Option.map(Option.fromUndefinedOr(answer.refresh_token), (refresh) =>406+ lockedCookie(407+ RENEW_COOKIE,408+ `${lapse}.${Redacted.value(refresh)}`,409+ RENEW_SECONDS410+ )411+ )412+ ),413+ ];414+ });415+416+export interface Renewed {417+ // The session's token from here on: the request it renewed for carries it.418+ readonly token: Option.Option<string>;419+ readonly cookies: readonly string[];420+}421+422+/**423+ * A session near its token's lapse, or past it, renewed by the refresh token424+ * beside it. Nothing to renew, or a platform out of reach, is none: the425+ * session stands as it is. A refresh token the platform refuses ends the426+ * session, so the browser is signed out rather than left half in.427+ */428+export const renewedSession = (env: Env, request: Request) =>429+ Effect.gen(function* () {430+ const renewal = renewalFrom(request);431+432+ if (Option.isNone(renewal)) {433+ return Option.none<Renewed>();434+ }435+436+ const now = Math.floor((yield* Clock.currentTimeMillis) / 1000);437+438+ if (439+ Option.isSome(credentialFrom(request)) &&440+ renewal.value.lapse - RENEW_MARGIN_SECONDS > now441+ ) {442+ return Option.none<Renewed>();443+ }444+445+ const answer = yield* tokenCall(env, {446+ client_id: clientIdOf(new URL(request.url).origin),447+ grant_type: "refresh_token",448+ refresh_token: renewal.value.refreshToken,449+ }).pipe(Effect.result);450+451+ if (Result.isSuccess(answer)) {452+ return Option.some<Renewed>({453+ cookies: yield* sessionCookies(answer.success),454+ token: Option.some(Redacted.value(answer.success.access_token)),455+ });456+ }457+458+ return answer.failure.status === 502459+ ? Option.none<Renewed>()460+ : Option.some<Renewed>({461+ cookies: endedCookies(),462+ token: Option.none(),463+ });464+ });465+466+/** The request as it goes on after a renewal: its session cookie holds the renewed token, or none. */467+export const withRenewedSession = (request: Request, renewed: Renewed) => {468+ const headers = new Headers(request.headers);469+470+ const others = (headers.get("cookie") ?? "")471+ .split(";")472+ .map((part) => part.trim())473+ .filter(474+ (part) =>475+ part !== "" &&476+ ![SESSION_COOKIE, HANDLE_COOKIE, RENEW_COOKIE].some((name) =>477+ part.startsWith(`${name}=`)478+ )479+ );480+481+ const session = Option.map(482+ renewed.token,483+ (token) => `${SESSION_COOKIE}=${encodeURIComponent(token)}`484+ );485+486+ headers.set("cookie", [...others, ...Option.toArray(session)].join("; "));487+488+ return new Request(request, { headers });489+};490+491+export const withCookies = (response: Response, cookies: readonly string[]) =>492+ new Response(response.body, {493+ headers: settingCookies(response.headers, cookies),494+ status: response.status,495+ statusText: response.statusText,496+ });497+498+/**499+ * A page's navigation renews its session before the page is drawn, so the500+ * page is drawn for the person still signed in. Only a navigation: a page's501+ * own calls never renew, so they never race it.502+ */503+export const renewingEntry =504+ (env: Env) =>505+ <Rest extends readonly unknown[]>(entry: {506+ readonly fetch: (507+ request: Request,508+ ...rest: Rest509+ ) => Promise<Response> | Response;510+ }) => ({511+ fetch: (request: Request, ...rest: Rest): Promise<Response> =>512+ Effect.runPromise(513+ Effect.gen(function* () {514+ const navigates =515+ request.method === "GET" &&516+ request.headers.get("sec-fetch-mode") === "navigate" &&517+ !new URL(request.url).pathname.startsWith("/auth/");518+519+ const renewed = navigates520+ ? yield* renewedSession(env, request)521+ : Option.none<Renewed>();522+523+ return yield* Option.match(renewed, {524+ onNone: () =>525+ Effect.promise(() =>526+ Promise.resolve(entry.fetch(request, ...rest))527+ ),528+ onSome: (fresh) =>529+ Effect.map(530+ Effect.promise(() =>531+ Promise.resolve(532+ entry.fetch(withRenewedSession(request, fresh), ...rest)533+ )534+ ),535+ (response) => withCookies(response, fresh.cookies)536+ ),537+ });538+ })539+ ),540+ });541+542 export const callbackHandler =543 (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>544 ({ request }: Handled): Promise<Response> =>545 Effect.runPromise(30 unmodified lines576 Effect.catchCause(() => Effect.succeedNone)577 );578 579 return redirect(returnPath(here.origin, pending.return), [390- sessionCookie(token, lives),580+ ...(yield* sessionCookies(answer)),581 ...Option.toArray(handle),582 clearedSignIn(),583 ]);584 }).pipe(4 unmodified lines589 );590 591 /**592 * 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.593+ * out of one is signed out of both, so the next sign-in asks who you are. The594+ * refresh token's grant is ended on the platform too, so the token in it is595+ * worth nothing should a copy of the cookie outlive this. With no platform596+ * (the dev world) it goes home at once.597 */598 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()599+ (platform: Option.Option<Env>) =>600+ ({ request }: Handled): Promise<Response> =>601+ Effect.runPromise(602+ Effect.gen(function* () {603+ if (Option.isNone(platform)) {604+ return redirect("/", endedCookies());605+ }606+607+ const env = platform.value;608+609+ yield* Option.match(renewalFrom(request), {610+ onNone: () => Effect.void,611+ onSome: ({ refreshToken }) =>612+ tokenCall(env, {613+ client_id: clientIdOf(new URL(request.url).origin),614+ token: refreshToken,615+ token_type_hint: "refresh_token",616+ }).pipe(Effect.ignore),617+ });618+619+ return redirect(620+ new URL(PLATFORM_SIGN_OUT, env.PUBLIC_PLATFORM_URL).href,621+ endedCookies()622+ );623+ })624 );625 626 const whoAnswer = (627 who: { readonly handle?: Handle },2 unmodified lines630 Response.json(who, {631 headers: settingCookies({ "cache-control": "no-store" }, cookies),632 });633 634+const whoFor = (635+ clientFor: (request: Request) => Layer.Layer<Client>,636+ request: Request637+) =>638+ Option.match(credentialFrom(request), {639+ onNone: () =>640+ Effect.succeed(641+ whoAnswer(642+ {},643+ Option.isSome(cookieValue(request, HANDLE_COOKIE))644+ ? [lockedCookie(HANDLE_COOKIE, "", 0)]645+ : []646+ )647+ ),648+ onSome: (token) =>649+ Effect.flatMap(keptHandle(request, token), (kept) =>650+ Option.match(kept, {651+ onNone: () =>652+ handleOf(clientFor, new URL(request.url).origin, token).pipe(653+ Effect.flatMap((handle) =>654+ Effect.map(655+ handleCookie(token, handle, HANDLE_LEARNED_SECONDS),656+ (cookie) => whoAnswer({ handle }, [cookie])657+ )658+ ),659+ Effect.catchTag("Unauthenticated", () =>660+ Effect.succeed(whoAnswer({}, clearedCookies()))661+ ),662+ Effect.orElseSucceed(() => whoAnswer({}))663+ ),664+ onSome: (handle) => Effect.succeed(whoAnswer({ handle })),665+ })666+ ),667+ });668+669+// The page asks this once as it starts, so it is where a session past its token's lapse is renewed for a page already drawn.670 export const whoamiHandler =426- (clientFor: (request: Request) => Layer.Layer<Client>) =>671+ (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>672 ({ request }: Handled): Promise<Response> =>673 Effect.runPromise(429- Option.match(credentialFrom(request), {430- onNone: () =>431- Effect.succeed(432- whoAnswer(433- {},434- Option.isSome(cookieValue(request, HANDLE_COOKIE))435- ? [lockedCookie(HANDLE_COOKIE, "", 0)]436- : []437- )438- ),439- onSome: (token) =>440- Effect.flatMap(keptHandle(request, token), (kept) =>441- Option.match(kept, {442- onNone: () =>443- handleOf(clientFor, new URL(request.url).origin, token).pipe(444- Effect.flatMap((handle) =>445- Effect.map(446- handleCookie(token, handle, HANDLE_LEARNED_SECONDS),447- (cookie) => whoAnswer({ handle }, [cookie])448- )449- ),450- Effect.catchTag("Unauthenticated", () =>451- Effect.succeed(whoAnswer({}, clearedCookies()))452- ),453- Effect.orElseSucceed(() => whoAnswer({}))454- ),455- onSome: (handle) => Effect.succeed(whoAnswer({ handle })),456- })457- ),458- })674+ Effect.flatMap(renewedSession(env, request), (renewed) =>675+ Option.match(renewed, {676+ onNone: () => whoFor(clientFor, request),677+ onSome: (fresh) =>678+ Effect.map(679+ whoFor(clientFor, withRenewedSession(request, fresh)),680+ (answer) => withCookies(answer, fresh.cookies)681+ ),682+ })683+ )684 );685 686 export const webClientMetadata = (origin: string) => ({687 client_id: clientIdOf(origin),688 client_name: `${Brand.name} web`,689 client_uri: origin,465- grant_types: ["authorization_code"],690+ grant_types: ["authorization_code", "refresh_token"],691 redirect_uris: [redirectUriOf(origin)],692 response_types: ["code"],693 token_endpoint_auth_method: "none",694 });5 unmodified linesmodified:apps/web/src/server.ts+3 added-1 removed
1 import handler from "@tanstack/react-start/server-entry";2+import { env } from "cloudflare:workers";3 4 import { addressedEntry } from "./server/addresses.ts";5 import { edgeEntry } from "./server/edge-cache.ts";6+import { renewingEntry } from "./server/session.ts";7 6-export default edgeEntry(addressedEntry(handler));8+export default edgeEntry(renewingEntry(env)(addressedEntry(handler)));modified:apps/web/test/client-session.test.ts+3 added-1 removed
12 unmodified lines13 "signs a browser in as the person whose dev token its session cookie holds, as /auth/dev sets it",14 () =>15 Effect.gen(function* () {16 const response = yield* Effect.promise(() =>17- whoamiHandler((request) => serverClientOver(backend)(env, request))({17+ whoamiHandler(env, (request) =>18+ serverClientOver(backend)(env, request)19+ )({20 request: new Request(`${WEB_URL}/auth/whoami`, {21 headers: { cookie: `${SESSION_COOKIE}=${DECIDER}` },22 }),23 })8 unmodified linesmodified:apps/web/test/edge-cache.test.ts+4 added-2 removed
263 unmodified lines264 expect(kept(response).cacheControl).toBe(KEPT_NOWHERE);265 })266 );267 268- it("is Start's server entry behind the address redirects, wrapped by edgeEntry, and nothing else", () => {268+ it("is Start's server entry behind the address redirects and a navigation's session renewal, wrapped by edgeEntry, and nothing else", () => {269 const sources: Readonly<Record<string, string>> = import.meta.glob(270 "../src/server.ts",271 { eager: true, import: "default", query: "?raw" }272 );3 unmodified lines276 .trim();277 278 expect(code.split(/\n+/u)).toStrictEqual([279 'import handler from "@tanstack/react-start/server-entry";',280+ 'import { env } from "cloudflare:workers";',281 'import { addressedEntry } from "./server/addresses.ts";',282 'import { edgeEntry } from "./server/edge-cache.ts";',282- "export default edgeEntry(addressedEntry(handler));",283+ 'import { renewingEntry } from "./server/session.ts";',284+ "export default edgeEntry(renewingEntry(env)(addressedEntry(handler)));",285 ]);286 });287 });288 234 unmodified linesmodified:apps/web/test/head.test.ts+9 added-1 removed
1 unmodified line2 import { describe, expect, it } from "@effect/vitest";3 import { Brand } from "@repo/brand";4 5 import { pageHead } from "../src/features/shared/head.ts";6-import { rootHead } from "../src/routes/__root.tsx";6+import { OG_IMAGE_URL, rootHead } from "../src/routes/__root.tsx";7 8 const keyOf = (meta: Readonly<Record<string, string>>) =>9 meta.name ?? meta.property ?? (meta.title === undefined ? "" : "title");10 42 unmodified lines53 expect(metas["og:description"]).toBe(metas.description);54 expect(metas["og:title"]).toBe(Brand.name);55 expect(metas["og:type"]).toBe("website");56 });57+58+ it("gives every page the card as a large image, at its absolute URL", () => {59+ const metas = metasOf(rootHead());60+61+ expect(metas["og:image"]).toBe(OG_IMAGE_URL);62+ expect(new URL(OG_IMAGE_URL).pathname).toBe("/og.png");63+ expect(metas["twitter:card"]).toBe("summary_large_image");64+ });65 });modified:apps/web/test/icons.test.ts+1 added
56 unmodified lines57 expect(pngSize("../public/apple-touch-icon.png")).toStrictEqual([180, 180]);58 expect(pngSize("../public/icons/icon-192.png")).toStrictEqual([192, 192]);59 expect(pngSize("../public/icons/icon-512.png")).toStrictEqual([512, 512]);60 expect(icoSizes("../public/favicon.ico")).toStrictEqual([16, 32, 48]);61+ expect(pngSize("../public/og.png")).toStrictEqual([1200, 630]);62 });63 });added:apps/web/test/kept-pages.test.ts+247 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Effect, Option, Ref } from "effect";3+import { TestClock } from "effect/testing";4+5+import { EDGE_STALE_SECONDS } from "../src/server/edge-cache.ts";6+import { keptKeyOf, servedKept } from "../src/server/kept-pages.ts";7+import type { KeptPage, PageKeeper } from "../src/server/kept-pages.ts";8+import { SESSION_COOKIE } from "../src/server/session.ts";9+10+const WEB_URL = "https://web-test.example.workers.dev";11+12+const AGENT_PAGE = { "cache-control": "public, max-age=60" } as const;13+14+const get = (path: string, headers: HeadersInit = {}) =>15+ new Request(`${WEB_URL}${path}`, { headers });16+17+/** A keeper in memory whose background work waits until the test runs it. */18+const memoryKeeper = Effect.gen(function* () {19+ const pages = yield* Ref.make<ReadonlyMap<string, KeptPage>>(new Map());20+ const pending = yield* Ref.make<readonly Effect.Effect<void>[]>([]);21+22+ const keeper: PageKeeper = {23+ get: (key) =>24+ Effect.map(Ref.get(pages), (all) => Option.fromUndefinedOr(all.get(key))),25+ inBackground: (work) => Ref.update(pending, (all) => [...all, work]),26+ put: (key, page) =>27+ Ref.update(pages, (all) => new Map([...all, [key, page]])),28+ };29+30+ // Work queued by work in the background runs too, as `waitUntil` would.31+ const runBackground: Effect.Effect<void> = Effect.flatMap(32+ Ref.getAndSet(pending, []),33+ (queued) =>34+ queued.length === 035+ ? Effect.void36+ : Effect.andThen(37+ Effect.forEach(queued, (work) => work, { discard: true }),38+ Effect.suspend(() => runBackground)39+ )40+ );41+42+ return { keeper, pages, pending, runBackground };43+});44+45+/** The route: each read answers the next version of the page, and is counted. */46+const countedRoute = (47+ headers: Readonly<Record<string, string>> = AGENT_PAGE,48+ status = 20049+) =>50+ Effect.map(Ref.make(0), (reads) => ({51+ reads,52+ render: Effect.map(53+ Ref.updateAndGet(reads, (n) => n + 1),54+ (n) =>55+ new Response(`version ${n}`, {56+ headers: { ...headers, "content-type": "text/markdown" },57+ status,58+ })59+ ),60+ }));61+62+const bodyOf = (response: Response) => Effect.promise(() => response.text());63+64+describe("an agent's page, kept by the Worker", () => {65+ it.effect(66+ "is read from the platform once while it is fresh, and kept by its path alone",67+ () =>68+ Effect.gen(function* () {69+ const { keeper, pages, runBackground } = yield* memoryKeeper;70+ const { reads, render } = yield* countedRoute();71+ const served = servedKept(keeper);72+73+ const first = yield* bodyOf(yield* served(get("/llms.txt"), render));74+ yield* runBackground;75+ yield* TestClock.adjust("59 seconds");76+77+ const second = yield* bodyOf(78+ yield* served(get("/llms.txt?again"), render)79+ );80+81+ expect({82+ first,83+ kept: [...(yield* Ref.get(pages)).keys()],84+ reads: yield* Ref.get(reads),85+ second,86+ }).toStrictEqual({87+ first: "version 1",88+ kept: [keptKeyOf(get("/llms.txt"))],89+ reads: 1,90+ second: "version 1",91+ });92+ })93+ );94+95+ it.effect(96+ "is answered at once from what was kept once it has expired, and read again only in the background",97+ () =>98+ Effect.gen(function* () {99+ const { keeper, pending, runBackground } = yield* memoryKeeper;100+ const { reads, render } = yield* countedRoute();101+ const served = servedKept(keeper);102+103+ yield* served(get("/oscabriel/datekit/llms.txt"), render);104+ yield* runBackground;105+ yield* TestClock.adjust("2 minutes");106+107+ const stale = yield* served(get("/oscabriel/datekit/llms.txt"), render);108+109+ // The answer has gone before the platform is asked again.110+ const readsWhenAnswered = yield* Ref.get(reads);111+ const waiting = (yield* Ref.get(pending)).length;112+113+ yield* runBackground;114+115+ const after = yield* served(get("/oscabriel/datekit/llms.txt"), render);116+117+ expect({118+ after: yield* bodyOf(after),119+ cacheControl: stale.headers.get("cache-control"),120+ contentType: stale.headers.get("content-type"),121+ reads: yield* Ref.get(reads),122+ readsWhenAnswered,123+ stale: yield* bodyOf(stale),124+ waiting,125+ }).toStrictEqual({126+ after: "version 2",127+ cacheControl: AGENT_PAGE["cache-control"],128+ contentType: "text/markdown",129+ reads: 2,130+ readsWhenAnswered: 1,131+ stale: "version 1",132+ waiting: 1,133+ });134+ })135+ );136+137+ it.effect(138+ "is read again before it is answered once it is older than the edge's stale window",139+ () =>140+ Effect.gen(function* () {141+ const { keeper, runBackground } = yield* memoryKeeper;142+ const { reads, render } = yield* countedRoute();143+ const served = servedKept(keeper);144+145+ yield* served(get("/llms.txt"), render);146+ yield* runBackground;147+ yield* TestClock.adjust(`${60 + EDGE_STALE_SECONDS + 1} seconds`);148+149+ const late = yield* bodyOf(yield* served(get("/llms.txt"), render));150+151+ expect({ late, reads: yield* Ref.get(reads) }).toStrictEqual({152+ late: "version 2",153+ reads: 2,154+ });155+ })156+ );157+158+ it.effect.each([159+ ["a session cookie", { cookie: `${SESSION_COOKIE}=dev-ada` }],160+ ["any cookie", { cookie: "theme=dark" }],161+ ["an Authorization", { authorization: "Bearer token" }],162+ ] as const)(163+ "is neither kept nor handed back for a request with %s",164+ ([, headers]) =>165+ Effect.gen(function* () {166+ const { keeper, pages, runBackground } = yield* memoryKeeper;167+ const { reads, render } = yield* countedRoute();168+ const served = servedKept(keeper);169+170+ yield* served(get("/llms.txt"), render);171+ yield* runBackground;172+173+ const asked = yield* bodyOf(174+ yield* served(get("/llms.txt", headers), render)175+ );176+177+ yield* runBackground;178+179+ const keptBeforeSecond = (yield* Ref.get(pages)).size;180+181+ yield* Ref.set(pages, new Map());182+ yield* served(get("/llms.txt", headers), render);183+ yield* runBackground;184+185+ expect({186+ asked,187+ keptAfter: (yield* Ref.get(pages)).size,188+ keptBeforeSecond,189+ reads: yield* Ref.get(reads),190+ }).toStrictEqual({191+ asked: "version 2",192+ keptAfter: 0,193+ keptBeforeSecond: 1,194+ reads: 3,195+ });196+ })197+ );198+199+ it.effect.each([200+ ["the platform did not answer", { "cache-control": "no-store" }, 503],201+ ["a page not found", AGENT_PAGE, 404],202+ ["an answer kept by nobody", { "cache-control": "private, no-store" }, 200],203+ ["an answer with no age", { "cache-control": "public" }, 200],204+ [205+ "an answer that forbids serving it stale",206+ { "cache-control": "public, max-age=60, must-revalidate" },207+ 200,208+ ],209+ [210+ "an answer that sets a cookie",211+ { ...AGENT_PAGE, "set-cookie": "a=b" },212+ 200,213+ ],214+ ] as const)("keeps nothing when %s", ([, headers, status]) =>215+ Effect.gen(function* () {216+ const { keeper, pages, runBackground } = yield* memoryKeeper;217+ const { reads, render } = yield* countedRoute(headers, status);218+ const served = servedKept(keeper);219+220+ const first = yield* served(get("/llms.txt"), render);221+ yield* runBackground;222+ yield* served(get("/llms.txt"), render);223+224+ expect({225+ kept: (yield* Ref.get(pages)).size,226+ reads: yield* Ref.get(reads),227+ status: first.status,228+ }).toStrictEqual({ kept: 0, reads: 2, status });229+ })230+ );231+});232+233+describe("the agents' routes", () => {234+ const routes: Readonly<Record<string, string>> = import.meta.glob(235+ "../src/routes/**/*.ts",236+ { eager: true, import: "default", query: "?raw" }237+ );238+239+ it.each([240+ "../src/routes/llms[.]txt.ts",241+ "../src/routes/$owner/$project/llms[.]txt.ts",242+ "../src/routes/$owner/$project/asks/{$ask}[.]md.ts",243+ "../src/routes/[.]well-known/agent-skills/$.ts",244+ ])("keep each answer to a GET by the Worker: %s", (path) => {245+ expect(routes[path]).toMatch(/GET: keptPage\(/u);246+ });247+});modified:apps/web/test/routes.test.ts+1 added
79 unmodified lines80 "install",81 "install.sh",82 "llms-full.txt",83 "llms.txt",84+ "og.png",85 "people",86 "privacy",87 "releases",88 "robots.txt",50 unmodified linesmodified:apps/web/test/session.test.ts+341 added-35 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { Handle } from "@repo/protocol/ids";3 import { untouchable } from "@repo/testkit/untouchable";4-import { Effect, Option, Schema } from "effect";4+import { Clock, Effect, Option, Schema } from "effect";5 import { createElement } from "react";6 import { renderToStaticMarkup } from "react-dom/server";7 8 import { devPeople } from "../src/dev/seed.ts";8 unmodified lines17 clientMetadataHandler,18 credentialFrom,19 HANDLE_COOKIE,20 pkce,21+ RENEW_COOKIE,22+ renewingEntry,23 SESSION_COOKIE,24 sessionCookie,25 signInHandler,26 signOutHandler,521 unmodified lines548 })549 );550 551 it.effect(550- "answers with no token or refresh token in its body or its URL",552+ "answers with no token or refresh token in its body or its URL, and the refresh token only in the renewal cookie",553 () =>554 Effect.gen(function* () {555 const { response } = yield* signInAndBack("/auth/signin", "c0de");556 557 const shown = `${yield* textOf(response)}\n${response.headers.get("location") ?? ""}`;558 559 expect(shown).not.toContain("tok-from-platform");560 expect(shown).not.toContain("refresh-secret");559- expect(response.headers.getSetCookie().join("\n")).not.toContain(560- "refresh-secret"561+ expect(562+ cookiesOf(response)563+ .filter(({ value }) => value.includes("refresh-secret"))564+ .map(({ name }) => name)565+ ).toStrictEqual([RENEW_COOKIE]);566+ })567+ );568+569+ it.live(570+ "keeps the refresh token beside the session, locked down, with the token's lapse, for as long as the platform keeps it",571+ () =>572+ Effect.gen(function* () {573+ const before = Math.floor((yield* Clock.currentTimeMillis) / 1000);574+ const { response } = yield* signInAndBack("/auth/signin", "c0de");575+576+ const renewal = cookiesOf(response).find(577+ ({ name }) => name === RENEW_COOKIE578 );579+580+ const [lapse = "", token] = decodeURIComponent(581+ renewal?.value ?? ""582+ ).split(".");583+584+ expect({585+ host: RENEW_COOKIE.startsWith("__Host-"),586+ lapses:587+ Number(lapse) >= before + TOKEN_ANSWER.expires_in &&588+ Number(lapse) <= before + TOKEN_ANSWER.expires_in + 60,589+ lives: maxAgeOf(renewal?.attributes ?? []),590+ lockedDown: lockedDown(renewal?.attributes),591+ token,592+ }).toStrictEqual({593+ host: true,594+ lapses: true,595+ lives: 30 * 24 * 60 * 60,596+ lockedDown: true,597+ token: TOKEN_ANSWER.refresh_token,598+ });599 })600 );601 602 it.effect(85 unmodified lines688 })689 );690 });691 692+const signedOut = (693+ platform: Option.Option<Env>,694+ cookie = `${SESSION_COOKIE}=tok123`695+) =>696+ Effect.forEach(["POST", "GET"], (method) =>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- });697+ Effect.map(698+ Effect.promise(() =>699+ signOutHandler(platform)({700+ request: new Request(`${WEB_URL}/auth/signout`, {701+ headers: { cookie },702+ method,703+ }),704+ })705+ ),706+ (response) => [707+ response.status,708+ response.headers.get("location"),709+ expiriesOf(response),710+ ]711+ )712+ );713 664- return [665- response.status,666- response.headers.get("location"),667- expiriesOf(response),668- ];669- });670-714 describe("sign-out", () => {715 const expired = [716 [SESSION_COOKIE, true],717 [HANDLE_COOKIE, true],718+ [RENEW_COOKIE, true],719 ];720 721+ it.effect(722+ "expires the session, handle and renewal cookies, then ends the platform's session too, by POST or by a plain link",723+ () =>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- });724+ Effect.gen(function* () {725+ expect(yield* signedOut(Option.some(unreachable))).toStrictEqual([726+ [302, `${PLATFORM_URL}/oauth/signout`, expired],727+ [302, `${PLATFORM_URL}/oauth/signout`, expired],728+ ]);729+ })730+ );731 732+ it.effect(733+ "ends the refresh token's grant on the platform, as the web's client",734+ () =>735+ Effect.gen(function* () {736+ const platform = recorder(() => new Response(null, { status: 200 }));737+738+ const [one] = yield* signedOut(739+ Option.some(envWith(platform.fetch)),740+ `${SESSION_COOKIE}=tok123; ${RENEW_COOKIE}=1700000000.alice:grant1:refresh-secret`741+ );742+743+ expect(one).toStrictEqual([744+ 302,745+ `${PLATFORM_URL}/oauth/signout`,746+ expired,747+ ]);748+ expect(749+ (yield* platform.seen).map(({ body, method, url }) => ({750+ form: Object.fromEntries(new URLSearchParams(body)),751+ method,752+ url,753+ }))754+ ).toContainEqual({755+ form: {756+ client_id: `${WEB_URL}/auth/client`,757+ token: "alice:grant1:refresh-secret",758+ token_type_hint: "refresh_token",759+ },760+ method: "POST",761+ url: `${PLATFORM_URL}/token`,762+ });763+ })764+ );765+766+ it.effect("goes home at once where there is no platform to sign out of", () =>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- });767+ Effect.gen(function* () {768+ expect(yield* signedOut(Option.none())).toStrictEqual([769+ [302, "/", expired],770+ [302, "/", expired],771+ ]);772+ })773+ );774 });775 776 const whoami = (env: Env, headers: Readonly<Record<string, string>> = {}) =>777 Effect.promise(() =>694- whoamiHandler((request) => serverClientOver(backend)(env, request))({778+ whoamiHandler(env, (request) => serverClientOver(backend)(env, request))({779 request: get("/auth/whoami", headers),780 })781 );782 59 unmodified lines842 })843 );844 845 it.effect(762- "answers {} and expires both cookies when the platform no longer knows the session",846+ "answers {} and expires both cookies when the platform no longer knows the session, keeping the refresh token for a renewal",847 () =>848 Effect.gen(function* () {849 const platform = recorder((request) =>850 request.headers.has("authorization")70 unmodified lines921 expect(922 cookiesOf(response)923 .map(({ name }) => name)924 .filter((name) => name !== "__Host-sign-in")841- ).toStrictEqual([SESSION_COOKIE]);925+ ).toStrictEqual([SESSION_COOKIE, RENEW_COOKIE]);926 })927 );928 929 it.effect("is not believed for another session: the platform is asked", () =>36 unmodified lines966 const decodeDocument = Schema.decodeUnknownEffect(967 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))968 );969 970+const RENEWED = {971+ access_token: "alice:grant1:tok-renewed",972+ expires_in: 3600,973+ refresh_token: "alice:grant1:refresh-renewed",974+ scope: "",975+ token_type: "bearer",976+};977+978+// A renewal cookie whose token lapses `in` seconds from now.979+const renewalCookie = (lapsesIn: number) =>980+ Effect.map(981+ Clock.currentTimeMillis,982+ (now) =>983+ `${RENEW_COOKIE}=${Math.floor(now / 1000) + lapsesIn}.alice:grant1:refresh-secret`984+ );985+986+const renewingPlatform = (token: () => Response) =>987+ recorder((request) =>988+ new URL(request.url).pathname === "/token"989+ ? token()990+ : whoamiReply(INES)(request)991+ );992+993+const asked = (994+ seen: readonly { readonly body: string; readonly url: string }[]995+) =>996+ seen.map(({ body, url }) =>997+ new URL(url).pathname === "/token"998+ ? Object.fromEntries(new URLSearchParams(body))999+ : new URL(url).pathname.replace(/\/$/u, "")1000+ );1001+1002+const renewedForm = {1003+ client_id: `${WEB_URL}/auth/client`,1004+ grant_type: "refresh_token",1005+ refresh_token: "alice:grant1:refresh-secret",1006+};1007+1008+const navigation = (1009+ path: string,1010+ cookie: string,1011+ mode: "navigate" | "cors" = "navigate"1012+) =>1013+ new Request(`${WEB_URL}${path}`, {1014+ headers: { cookie, "sec-fetch-mode": mode },1015+ });1016+1017+const drawn = (env: Env, request: Request) =>1018+ Effect.gen(function* () {1019+ const reached: (string | null)[] = [];1020+1021+ const entry = renewingEntry(env)({1022+ fetch: (handed: Request) => {1023+ reached.push(handed.headers.get("cookie"));1024+1025+ return new Response("page", {1026+ headers: { "content-type": "text/html" },1027+ });1028+ },1029+ });1030+1031+ const response = yield* Effect.promise(() => entry.fetch(request));1032+1033+ return { reached, response };1034+ });1035+1036+describe("renewing a session", () => {1037+ it.live(1038+ "whoami renews a session past its token's lapse by its refresh token, sets the new cookies and names the person",1039+ () =>1040+ Effect.gen(function* () {1041+ const platform = renewingPlatform(() => Response.json(RENEWED));1042+1043+ const response = yield* whoami(envWith(platform.fetch), {1044+ cookie: yield* renewalCookie(-10),1045+ });1046+1047+ const set = cookiesOf(response).filter(1048+ ({ attributes }) => !attributes.includes("max-age=0")1049+ );1050+1051+ const seen = yield* platform.seen;1052+1053+ expect({1054+ answer: yield* textOf(response),1055+ asked: asked(seen),1056+ bearer: seen1057+ .filter(({ url }) => new URL(url).pathname.startsWith("/rpc"))1058+ .map(({ authorization }) => authorization),1059+ set: set1060+ .filter(({ name }) => name !== HANDLE_COOKIE)1061+ .map(({ name, value }) => [1062+ name,1063+ decodeURIComponent(value).replace(/^\d+\./u, ""),1064+ ]),1065+ }).toStrictEqual({1066+ answer: '{"handle":"ines-v"}',1067+ asked: [renewedForm, "/rpc"],1068+ bearer: [`Bearer ${RENEWED.access_token}`],1069+ set: [1070+ [SESSION_COOKIE, RENEWED.access_token],1071+ [RENEW_COOKIE, RENEWED.refresh_token],1072+ ],1073+ });1074+ })1075+ );1076+1077+ it.live("renews a session whose token lapses within five minutes", () =>1078+ Effect.gen(function* () {1079+ const platform = renewingPlatform(() => Response.json(RENEWED));1080+1081+ yield* whoami(envWith(platform.fetch), {1082+ cookie: `${SESSION_COOKIE}=alice:grant1:tok-old; ${yield* renewalCookie(120)}`,1083+ });1084+1085+ expect(asked(yield* platform.seen)[0]).toStrictEqual(renewedForm);1086+ })1087+ );1088+1089+ it.live(1090+ "leaves a session alone while its token has more than five minutes to live",1091+ () =>1092+ Effect.gen(function* () {1093+ const platform = renewingPlatform(() => Response.json(RENEWED));1094+1095+ const response = yield* whoami(envWith(platform.fetch), {1096+ cookie: `${SESSION_COOKIE}=alice:grant1:tok-old; ${yield* renewalCookie(1800)}`,1097+ });1098+1099+ expect(asked(yield* platform.seen)).toStrictEqual(["/rpc"]);1100+ expect(cookiesOf(response).map(({ name }) => name)).not.toContain(1101+ RENEW_COOKIE1102+ );1103+ })1104+ );1105+1106+ it.live(1107+ "ends the session, every cookie of it, when the platform refuses the refresh token",1108+ () =>1109+ Effect.gen(function* () {1110+ const platform = renewingPlatform(1111+ () => new Response('{"error":"invalid_grant"}', { status: 400 })1112+ );1113+1114+ const response = yield* whoami(envWith(platform.fetch), {1115+ cookie: yield* renewalCookie(-10),1116+ });1117+1118+ expect(yield* textOf(response)).toBe("{}");1119+ expect(expiriesOf(response)).toStrictEqual([1120+ [SESSION_COOKIE, true],1121+ [HANDLE_COOKIE, true],1122+ [RENEW_COOKIE, true],1123+ ]);1124+ })1125+ );1126+1127+ it.live(1128+ "keeps the refresh token when the platform cannot be reached, for the next try",1129+ () =>1130+ Effect.gen(function* () {1131+ const response = yield* whoami(1132+ envWith(() => Promise.reject(new Error("down"))),1133+ { cookie: yield* renewalCookie(-10) }1134+ );1135+1136+ expect(yield* textOf(response)).toBe("{}");1137+ expect(cookiesOf(response).map(({ name }) => name)).not.toContain(1138+ RENEW_COOKIE1139+ );1140+ })1141+ );1142+1143+ it.live(1144+ "renews a page's session before the page is drawn, so it is drawn for the person, and sets the new cookies",1145+ () =>1146+ Effect.gen(function* () {1147+ const platform = renewingPlatform(() => Response.json(RENEWED));1148+1149+ const { reached, response } = yield* drawn(1150+ envWith(platform.fetch),1151+ navigation("/inbox", `theme=dark; ${yield* renewalCookie(-10)}`)1152+ );1153+1154+ expect({1155+ reached,1156+ set: cookiesOf(response).map(({ name }) => name),1157+ }).toStrictEqual({1158+ reached: [1159+ `theme=dark; ${SESSION_COOKIE}=${encodeURIComponent(RENEWED.access_token)}`,1160+ ],1161+ set: [SESSION_COOKIE, RENEW_COOKIE],1162+ });1163+ })1164+ );1165+1166+ it.live(1167+ "never renews for a page's own calls, nor on the sign-in paths, so none races a navigation",1168+ () =>1169+ Effect.gen(function* () {1170+ const renewal = yield* renewalCookie(-10);1171+1172+ for (const request of [1173+ navigation("/inbox", renewal, "cors"),1174+ navigation("/auth/callback?code=x&state=y", renewal),1175+ new Request(`${WEB_URL}/rpc`, {1176+ body: LIST_ASKS,1177+ headers: { cookie: renewal, "sec-fetch-mode": "navigate" },1178+ method: "POST",1179+ }),1180+ ]) {1181+ const { reached, response } = yield* drawn(unreachable, request);1182+1183+ expect([reached, response.headers.getSetCookie()]).toStrictEqual([1184+ [renewal],1185+ [],1186+ ]);1187+ }1188+ })1189+ );1190+});1191+1192 describe("the web's OAuth client", () => {1193 it.effect(1194 "is a public Client ID Metadata Document at its own URL, redirecting only to the callback",1195 () =>9 unmodified lines1205 );1206 expect(document).toStrictEqual(1207 expect.objectContaining({1208 client_id: `${WEB_URL}/auth/client`,903- grant_types: ["authorization_code"],1209+ grant_types: ["authorization_code", "refresh_token"],1210 redirect_uris: [`${WEB_URL}/auth/callback`],1211 response_types: ["code"],1212 token_endpoint_auth_method: "none",1213 })120 unmodified linesmodified:apps/web/test/workers-shim.ts+3 added
4 unmodified lines5 export const env: Env = {6 PLATFORM: untouchable<Fetcher>("PLATFORM"),7 PUBLIC_PLATFORM_URL: "http://localhost:8787",8 };9+10+// A route module's background work runs to its end in a test only when the test awaits it itself.11+export const waitUntil = (_promise: Promise<unknown>): void => undefined;modified:apps/web/package.json+1 added-1 removed
12 unmodified lines13 "build": "vite build",14 "routes": "bun scripts/route-tree.ts",15 "types": "wrangler types --include-runtime=false --strict-vars=false",16 "typecheck": "bun run routes && tsc --noEmit -p tsconfig.json",17- "test": "vitest run",17+ "test": "bun run routes && vitest run",18 "e2e": "playwright test -c playwright.config.ts"19 },20 "dependencies": {21 "@base-ui/react": "1.8.0",51 unmodified linesmodified:examples/burrow/bun.lock+2 added-2 removed
167 unmodified lines168 "@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],169 170 "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],171 172- "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="],172+ "acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],173 174 "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="],175 176 "ansi-regex": ["ansi-regex@6.4.0", "", {}, "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw=="],17 unmodified lines194 "empathic": ["empathic@2.1.0", "", {}, "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw=="],195 196 "environment": ["environment@1.1.0", "", {}, "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="],197 198- "execa": ["execa@10.1.0", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "figures": "^6.1.0", "get-stream": "^9.0.1", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.3.1", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "which-command": "^0.1.0", "yoctocolors": "^2.2.0" } }, "sha512-5HT/600HqXEtmkb9mK/PkTWw+bQSCzPnWiZ4/87wD3Hi0wFzCapOuNT9p4M08PDd+KLHdHvFhKjOWmNx/npRNQ=="],198+ "execa": ["execa@10.0.1", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "figures": "^6.1.0", "get-stream": "^9.0.1", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.3.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "which-command": "^0.1.0", "yoctocolors": "^2.1.2" } }, "sha512-ge98qjkRK4IB7tL7Ju/6qmm5LHoH1eEMt5FNZrz3f4UIYhF28lggX20z3FaX1sgc67msLEn0N0BscOs29iuwyw=="],199 200 "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="],201 202 "fast-string-truncated-width": ["fast-string-truncated-width@3.0.3", "", {}, "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g=="],120 unmodified linesmodified:packages/agent-kit/src/docs/connect-an-agent.ts+2 added-1 removed
8 unmodified lines9 "## The ways in",10 "",11 `- **The CLI.** Install it, sign in once, and the agent runs the same commands you would: ${cli("front")}, ${cli("claim <ask> --project <owner>/<name>")}, ${cli("check")}, \`git push\`, ${cli("verdict <ask> --project <owner>/<name>")}. Its commands take ${code("--json")}, and a refusal ends it with an exit code that says whether trying again can help.`,12 `- **Remote MCP** at ${code(`${platformUrl}/mcp`)}, signed in with the platform's own OAuth. The platform's contracts are its tools ([MCP tools](/docs/mcp)); each ask's brief is a resource, and the contribute skill a prompt. An agent with no shell browses a project's code with five read tools.`,13- `- **MCP over stdio**: ${cli("mcp")} serves the same tools from the CLI, with its stored token.`,13+ `- **MCP over stdio**: ${cli("mcp")} serves the same tools from the CLI, with its stored token, so an agent that can start a command needs no sign-in of its own: ${cli("login")} once is enough.`,14+ `- **MCP for anyone** at ${code(`${platformUrl}/mcp/public`)}: the tools that only read (projects, asks, verdicts, code), with no sign-in at all.`,15 `- **Skills**: each project's contribute skill is listed at ${code(`${webUrl}/.well-known/agent-skills/index.json`)}.`,16 `- **Plain text**: ${code(`${webUrl}/llms.txt`)} says how to take an ask and lists every command and project; ${code(`${webUrl}/llms-full.txt`)} adds every refusal, git, landings and events. Each project and each ask answers as Markdown too.`,17 "",18 "## What holds for every agent",10 unmodified linesmodified:packages/agent-kit/src/docs/reference.ts+1 added-1 removed
66 unmodified lines67 );68 69 export const mcpPage: DocSource = {70 body: ({ platformUrl }) => [71- `The platform serves its contracts as MCP tools at ${code(`${platformUrl}/mcp`)} over streamable HTTP, signed in with its own OAuth; ${code(`${Brand.cli} mcp`)} serves the same tools over stdio. A refusal comes back as the tool's error, its \`_tag\` intact. [Install](/install) has each client's setup.`,71+ `The platform serves its contracts as MCP tools at ${code(`${platformUrl}/mcp`)} over streamable HTTP, signed in with its own OAuth; ${code(`${Brand.cli} mcp`)} serves the same tools over stdio, and ${code(`${platformUrl}/mcp/public`)} serves the tools that only read to anyone, with no sign-in. A refusal comes back as the tool's error, its \`_tag\` intact. [Install](/install) has each client's setup.`,72 "",73 ...table(["Tool", "What it does", "Only reads"], mcpTools()),74 "",75 ],30 unmodified linesmodified:packages/agent-kit/src/docs/run-a-project.ts+2 added-2 removed
100 unmodified lines101 `${Brand.cli} fork --project <owner>/<name>`,102 `git remote add fork <remote>`,103 `git push fork HEAD:main`,104 `git fetch ${Brand.slug}`,105- `${Brand.cli} land --project <owner>/<name> --base $(git rev-parse ${Brand.slug}/main) --head $(git rev-parse HEAD) --message "<what it does>" --requestId <id>`105+ `${Brand.cli} land --project <owner>/<name> --base $(git rev-parse ${Brand.slug}/main) --head $(git rev-parse HEAD) --message "<what it does>" --requestId <id> --yes`106 ),107 "",108- `${code("--base")} is \`main\` as the platform last landed it: ${code(`git rev-parse ${Brand.slug}/main`)} after ${code(`git fetch ${Brand.slug}`)}, where ${code(Brand.slug)} is the remote ${cli("init")} added for the project. ${code("--head")} is the commit you pushed to the fork. ${code("--requestId")} is any 8 to 64 letters, digits, \`-\` or \`_\` you choose: sending the same one again returns the same receipt, and checks nothing twice. ${cli("finish")} takes the same three. If \`main\` moves past your base before the change lands, the platform merges it onto the new \`main\` itself, and refuses with \`StaleBase\` only when that merge conflicts.`,108+ `${code("--base")} is \`main\` as the platform last landed it: ${code(`git rev-parse ${Brand.slug}/main`)} after ${code(`git fetch ${Brand.slug}`)}, where ${code(Brand.slug)} is the remote ${cli("init")} added for the project. ${code("--head")} is the commit you pushed to the fork. ${code("--requestId")} is any 8 to 64 letters, digits, \`-\` or \`_\` you choose: sending the same one again returns its receipt as it stands, and checks nothing twice. ${cli("finish")} takes the same three. ${cli("land")} answers as soon as the stages a push hears pass, with an outcome of \`Checking\`: the checks run on the platform after it returns, as an answer's do, and the same command again, with the same ${code("--requestId")}, says where they stand, then names the landing. If \`main\` moves past your base before the change lands, the platform merges it onto the new \`main\` itself, and refuses with \`StaleBase\` only when that merge conflicts.`,109 "",110 "## Vouch",111 "",112 `${cli("vouch --project <owner>/<name> --handle <handle> --verdict vouch")} admits a person to claim, by landing a line in the vouch file; \`--verdict denounce\` bars them from claiming and posting.`,4 unmodified linesmodified:packages/agent-kit/src/command-doc.ts+1 added
27 unmodified lines28 flags: [29 "--url",30 "--profile",31 "--token-stdin",32+ "--paste",33 "--no-browser",34 "--no-git-config",35 "--json",36 ],215 unmodified linesmodified:packages/artifacts/src/repo-host/binding.ts+63 added-11 removed
89 unmodified lines90 ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)91 )92 );93 94-const attempt = <A>(run: () => Promise<A>) =>94+const tried = <A>(run: () => Promise<A>) =>95 Effect.tryPromise({96 catch: (error) => {97 const message = error instanceof Error ? error.message : String(error);98 8 unmodified lines107 },108 try: run,109 }).pipe(Effect.retry(whileLimited));110 111+/**112+ * Workers RPC puts a `Symbol.dispose` on every object a call returns, and113+ * where the service's own result carried a disposer, its call stays open until114+ * that is called: a result left to the garbage collector draws the runtime's115+ * "An RPC result was not disposed properly". Every result but a repo's handle116+ * is data, whole once it arrives, so each is disposed as soon as it lands.117+ */118+const disposed = <A>(result: A): Effect.Effect<A> =>119+ Effect.try(() => {120+ const dispose = Predicate.hasProperty(result, Symbol.dispose)121+ ? result[Symbol.dispose]122+ : undefined;123+124+ if (Predicate.isFunction(dispose)) {125+ dispose.call(result);126+ }127+ }).pipe(Effect.ignore, Effect.as(result));128+129+/** A call whose result is data: the handle alone is kept, by `withRepo`. */130+const attempt = <A>(run: () => Promise<A>) =>131+ tried(run).pipe(Effect.flatMap(disposed));132+133 const threw =134 (code: Code) =>135 (thrown: Thrown): boolean =>136 Option.contains(thrown.code, code);93 unmodified lines230 Schedule.while(({ attempt: asked, input }) => asked <= asksWhileMaking(input))231 );232 233 const handleOf = (binding: Artifacts, name: RepoName) =>212- attempt(() => binding.get(name)).pipe(234+ tried(() => binding.get(name)).pipe(235 Effect.retry(whileMaking),236 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))237 );238 124 unmodified lines363 : Effect.succeed(true)364 )365 );366 367+/** `readBlob` answers `null` for any other kind, and `readTree` throws for a non-tree. */368+const blobOrTree = (name: RepoName, repo: ArtifactsRepo, id: string) =>369+ call(name, () => repo.readBlob(id)).pipe(370+ Effect.flatMap((blob) =>371+ blob === null372+ ? attempt(() => repo.readTree(id)).pipe(373+ Effect.map((tree) => tree !== null),374+ Effect.catchIf(threw("INTERNAL_ERROR"), () =>375+ Effect.succeed(false)376+ ),377+ Effect.catchTag("Thrown", (thrown) =>378+ fromArtifactsError(name, thrown)379+ )380+ )381+ : Effect.succeed(true)382+ )383+ );384+385+/**386+ * Artifacts throws `INTERNAL_ERROR` for an object that is no commit387+ * (workers-types), as a full SHA in a URL may name a tree or a blob: that is388+ * no commit, as a missing one is.389+ */390+const commitAt = (name: RepoName, repo: ArtifactsRepo, sha: string) =>391+ attempt(() => repo.readCommit(sha)).pipe(392+ Effect.flatMap((found) =>393+ found === null ? Effect.succeedNone : Effect.asSome(commitOf(found))394+ ),395+ Effect.catchIf(threw("INTERNAL_ERROR"), ({ error }) =>396+ blobOrTree(name, repo, sha).pipe(397+ Effect.flatMap((other) =>398+ other ? Effect.succeedNone : Effect.die(error)399+ )400+ )401+ ),402+ Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))403+ );404+405 /** Artifacts throws `INTERNAL_ERROR` for an object that is no tree (workers-types). */406 const treeAt = (name: RepoName, repo: ArtifactsRepo, tree: string) =>407 attempt(() => repo.readTree(tree)).pipe(408 Effect.flatMap((found) =>179 unmodified lines588 )589 )590 ),591 readCommit: (name, sha) =>532- read(name, (repo) =>533- call(name, () => repo.readCommit(sha)).pipe(534- Effect.flatMap((found) =>535- found === null536- ? Effect.succeedNone537- : Effect.asSome(commitOf(found))538- )539- )540- ),592+ read(name, (repo) => commitAt(name, repo, sha)),593 readFile: (name, at, path) =>594 read(name, (repo) =>595 call(name, () => repo.readFile({ path, ref: refOf(at) })).pipe(596 Effect.flatMap((found) =>26 unmodified linesmodified:packages/artifacts/src/repo-host/rest.ts+44 added-8 removed
580 unmodified lines581 )582 )583 );584 585+ const treeOrBlob = (name: RepoName, id: ObjectId) =>586+ optional(587+ name,588+ httpGet(`${repoPath(name)}/blob/${id}`).pipe(Effect.flatMap(bytesOf))589+ ).pipe(590+ Effect.flatMap((blob) =>591+ Option.isSome(blob)592+ ? Effect.succeed(true)593+ : httpGet(`${repoPath(name)}/tree/${id}`).pipe(594+ Effect.flatMap(accepted),595+ Effect.as(true),596+ Effect.catchTag("Refused", (refused) =>597+ is("NOT_FOUND", "INTERNAL_ERROR")(refused)598+ ? Effect.succeed(false)599+ : Effect.die(refused)600+ )601+ )602+ )603+ );604+605+ // Artifacts answers 500 for an object that is no commit, as a full SHA a606+ // reader hands in (a raw URL, a code read's `at`) may name a tree or a blob.607+ const readCommit = (name: RepoName, sha: CommitSha) =>608+ httpGet(`${repoPath(name)}/commit/${sha}`).pipe(609+ Effect.flatMap(decoded(CommitReply)),610+ Effect.map(({ result }) => Option.some(commitOf(result))),611+ Effect.catchTag("Refused", (refused) =>612+ Match.value(refused).pipe(613+ Match.when(is("NOT_FOUND"), () =>614+ remoteOf(name).pipe(Effect.as(Option.none<Commit>()))615+ ),616+ Match.when(is("INTERNAL_ERROR"), () =>617+ treeOrBlob(name, ObjectId.make(sha)).pipe(618+ Effect.flatMap((other) =>619+ other ? Effect.succeedNone : Effect.die(refused)620+ )621+ )622+ ),623+ Match.orElse(Effect.die)624+ )625+ )626+ );627+628 const readTree = (name: RepoName, tree: ObjectId) =>629 httpGet(`${repoPath(name)}/tree/${tree}`).pipe(630 Effect.flatMap(decoded(TreeReply)),631 Effect.flatMap(({ result }) => entriesOf(result)),119 unmodified lines751 httpGet(`${repoPath(name)}/blob/${blob}`).pipe(752 Effect.flatMap(bytesOf)753 )754 ),712- readCommit: (name, sha) =>713- optional(714- name,715- httpGet(`${repoPath(name)}/commit/${sha}`).pipe(716- Effect.flatMap(decoded(CommitReply)),717- Effect.map(({ result }) => commitOf(result))718- )719- ),755+ readCommit,756 readFile: (name, at, path) =>757 optional(758 name,759 httpGet(47 unmodified linesmodified:packages/artifacts/src/repo-host/smart-http.ts+25 added-4 removed
50 unmodified lines51 // git's own receive-pack (2.56), and a server set to refuse rewinding a ref.52 // `fetch first` is git's client-side word and never reaches a server.53 const MOVED = ["stale ref", "incorrect old value provided", "non-fast-forward"];54 55+// An older receive-pack (2.47, Debian trixie's) says only that the update56+// failed, and why in a message: the ref's lock found it at another commit.57+const FAILED = "failed to update ref";58+59+const lockFoundMoved = (ref: RefName, said: string) =>60+ said.includes(`cannot lock ref '${ref}': is at `) &&61+ said.includes(" but expected ");62+63 // Artifacts' whole reply to a push it is too busy for: one side-band 364 // (fatal) packet and no report.65 const BUSY = "artifacts_git_receive_pack_busy";66 244 unmodified lines311 312 const isMoved = (reason: string) =>313 MOVED.some((moved) => reason.includes(moved));314 307-const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>308- cause instanceof Errors.GitPushError &&309- isMoved(cause.data.result.refs[ref]?.error ?? "");315+const refusedAsMoved = ({ cause }: GitFailure, ref: RefName, said: string) => {316+ if (!(cause instanceof Errors.GitPushError)) {317+ return false;318+ }319 320+ const reason = cause.data.result.refs[ref]?.error ?? "";321+322+ return (323+ isMoved(reason) || (reason.includes(FAILED) && lockFoundMoved(ref, said))324+ );325+};326+327 /**328 * One ref's compare-and-swap: the push's own ref discovery is the check, so329 * it stops before any pack is built if the tip is not `from`. `to` need not330 * descend from `from` (Artifacts takes such an update), so isomorphic-git's7 unmodified lines338 ) =>339 Effect.gen(function* () {340 const expected = Option.getOrElse(update.from, () => ABSENT);341 let found = ABSENT;342+ // What the server says beside its report, where an older git names why.343+ let said = "";344 345 const pushed = yield* git((signal) =>346 push({347 ...source,348 force: true,349 http,350+ onMessage: (message) => {351+ said += message;352+ },353 onPrePush: ({ remoteRef }) => {354 found = remoteRef.oid;355 356 return found === expected;18 unmodified lines375 })376 )377 ),378 Match.when(358- (refused) => refusedAsMoved(refused, update.ref),379+ (refused) => refusedAsMoved(refused, update.ref, said),380 () =>381 refsAt(remote, http).pipe(382 Effect.map((refs) =>383 RefOutcome.Stale({112 unmodified linesmodified:packages/artifacts/test/binding.test.ts+296 added-7 removed
15 unmodified lines16 FiberSet,17 FileSystem,18 Layer,19 Option,20+ Predicate,21 Redacted,22 Ref,23 } from "effect";24 import type { Scope } from "effect";35 unmodified lines60 61 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);62 };63 64+const pktOf = (payload: Uint8Array) => {65+ const length = (payload.length + 4).toString(16).padStart(4, "0");66+67+ return new Uint8Array([...new TextEncoder().encode(length), ...payload]);68+};69+70+const banded = (channel: number, payload: Uint8Array) =>71+ pktOf(new Uint8Array([channel, ...payload]));72+73+const text = (line: string) => new TextEncoder().encode(line);74+75+const flush = text("0000");76+77+/** git 2.47's receive-pack when a ref moved under a push: the reason in a message, the status only "failed". */78+const olderGitMovedReply = (ref: RefName, tip: string, base: string) =>79+ new Response(80+ new Uint8Array([81+ ...banded(82+ 2,83+ text(84+ `error: cannot lock ref '${ref}': is at ${tip} but expected ${base}\n`85+ )86+ ),87+ ...banded(88+ 1,89+ new Uint8Array([90+ ...pktOf(text("unpack ok\n")),91+ ...pktOf(text(`ng ${ref} failed to update ref\n`)),92+ ...flush,93+ ])94+ ),95+ ...flush,96+ ]),97+ { headers: { "content-type": "application/x-git-receive-pack-result" } }98+ );99+100+/** What the binding throws for an unexpected read, as workers-types gives it. */101+const internalError = () =>102+ Object.assign(new Error("An internal error occurred."), {103+ code: "INTERNAL_ERROR",104+ name: "ArtifactsError",105+ numericCode: 10_400,106+ });107+108 const busyReply = () =>109 new Response(fatal("artifacts_git_receive_pack_busy\n"), {110 headers: { "content-type": "application/x-git-receive-pack-result" },111 });349 unmodified lines461 })462 )463 );464 465+ it.live(466+ "reports a ref an older git found moved as Stale at its new tip, from the reason only its message gives",467+ () =>468+ within(({ intercept, store }) =>469+ Effect.gen(function* () {470+ const repos = yield* RepoHost;471+ const name = RepoName.make("raced-older");472+ const { client, first } = yield* seeded(name);473+ const ours = yield* client.commit("ours", [["a.txt", "2"]], [first]);474+475+ const theirs = yield* client.commit(476+ "theirs",477+ [["a.txt", "3"]],478+ [first]479+ );480+481+ yield* Ref.set(482+ intercept,483+ Option.some(() =>484+ store485+ .push(name, client.source, [486+ { from: Option.some(first), ref: main, to: theirs },487+ ])488+ .pipe(489+ Effect.orDie,490+ Effect.as(491+ Option.some(olderGitMovedReply(main, theirs, first))492+ )493+ )494+ )495+ );496+497+ expect(498+ yield* repos499+ .push(name, client.source, [500+ { from: Option.some(first), ref: main, to: ours },501+ ])502+ .pipe(Effect.orDie)503+ ).toStrictEqual([504+ RefOutcome.Stale({ ref: main, tip: Option.some(theirs) }),505+ ]);506+ })507+ )508+ );509+510 // Artifacts takes any update whose old value matches, and `/memory`511 // and `/local` apply it too: the compare-and-swap is the only check.512 it.live(513 "moves a ref whose tip is `from` to a `to` that is not a fast-forward",98 unmodified lines612 const commit = yield* host.readCommit(repo, CommitSha.make(sha));613 614 return Option.isNone(tree) &&615 (Option.isSome(blob) || Option.isSome(commit))526- ? yield* Effect.die(527- Object.assign(new Error("An internal error occurred."), {528- code: "INTERNAL_ERROR",529- name: "ArtifactsError",530- numericCode: 10_400,531- })532- )616+ ? yield* Effect.die(internalError())617 : tree;618 }),619 }),620 }621 )622 );623+624+ // A full SHA in a raw URL or a code read may name a tree or a blob, which625+ // the binding's `readCommit` throws `INTERNAL_ERROR` for, as its `readTree`626+ // does for a commit or a blob.627+ it.live("reads no commit at a tree's id or a blob's id", () =>628+ within(629+ () =>630+ Effect.gen(function* () {631+ const repos = yield* RepoHost;632+ const name = RepoName.make("kinds");633+ const { first } = yield* seeded(name);634+635+ const commit = yield* repos636+ .readCommit(name, first)637+ .pipe(Effect.orDie);638+639+ const tree = Option.getOrThrow(640+ Option.map(commit, (read) => read.tree)641+ );642+643+ const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);644+ const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;645+646+ expect(blob).not.toBe(tree);647+ expect(648+ yield* Effect.exit(repos.readCommit(name, CommitSha.make(tree)))649+ ).toStrictEqual(Exit.succeed(Option.none()));650+ expect(651+ yield* Effect.exit(repos.readCommit(name, CommitSha.make(blob)))652+ ).toStrictEqual(Exit.succeed(Option.none()));653+ }),654+ {655+ wrap: (host) => ({656+ ...host,657+ readCommit: (repo, sha) =>658+ Effect.gen(function* () {659+ const tree = yield* host.readTree(repo, ObjectId.make(sha));660+ const blob = yield* host.readBlob(repo, ObjectId.make(sha));661+662+ return Option.isSome(tree) || Option.isSome(blob)663+ ? yield* Effect.die(internalError())664+ : yield* host.readCommit(repo, sha);665+ }),666+ readTree: (repo, sha) =>667+ Effect.gen(function* () {668+ const tree = yield* host.readTree(repo, sha);669+ const blob = yield* host.readBlob(repo, sha);670+671+ return Option.isNone(tree) && Option.isSome(blob)672+ ? yield* Effect.die(internalError())673+ : tree;674+ }),675+ }),676+ }677+ )678+ );679+680+ it.live("still dies where the object it could not read is none of them", () =>681+ within(682+ () =>683+ Effect.gen(function* () {684+ const repos = yield* RepoHost;685+ const name = RepoName.make("failing");686+ const { first } = yield* seeded(name);687+688+ const read = yield* Effect.exit(repos.readCommit(name, first));689+690+ expect(Exit.hasDies(read)).toBeTruthy();691+ }),692+ {693+ wrap: (host) => ({694+ ...host,695+ readCommit: () => Effect.die(internalError()),696+ readTree: () => Effect.die(internalError()),697+ }),698+ }699+ )700+ );701 });702 703 describe("tokens and handles the binding takes", () => {704 it.live("leaves no live token on a repo it created, forked or imported", () =>180 unmodified lines885 )886 );887 });888 889+// The runtime gives each object an RPC call returns a disposer of its own,890+// which holds the far side's call open until it is called. This wrapper gives891+// one to every object the binding returns, a repo's handle aside, and records892+// each one given and each one called.893+const disposing = (binding: Artifacts) => {894+ const given: string[] = [];895+ const disposals: string[] = [];896+897+ const marked = <X>(method: string, call: () => Promise<X>): Promise<X> =>898+ Effect.runPromise(899+ Effect.map(Effect.promise(call), (result) => {900+ if (!Predicate.isObjectKeyword(result)) {901+ return result;902+ }903+904+ given.push(method);905+906+ return Object.defineProperty(result, Symbol.dispose, {907+ configurable: true,908+ enumerable: false,909+ value: () => {910+ disposals.push(method);911+ },912+ });913+ })914+ );915+916+ const wrapped: Artifacts = {917+ ...binding,918+ create: (name, opts) => marked("create", () => binding.create(name, opts)),919+ get: (name) =>920+ Effect.runPromise(921+ Effect.map(922+ Effect.promise(() => binding.get(name)),923+ (repo): ArtifactsRepo => ({924+ ...repo,925+ createToken: (scope, ttl) =>926+ marked("createToken", () => repo.createToken(scope, ttl)),927+ fork: (forked, opts) =>928+ marked("fork", () => repo.fork(forked, opts)),929+ info: () => marked("info", () => repo.info()),930+ listTokens: () => marked("listTokens", () => repo.listTokens()),931+ log: (opts) => marked("log", () => repo.log(opts)),932+ readBlob: (hash) => marked("readBlob", () => repo.readBlob(hash)),933+ readCommit: (hash) =>934+ marked("readCommit", () => repo.readCommit(hash)),935+ readFile: (args) => marked("readFile", () => repo.readFile(args)),936+ readTree: (hash) => marked("readTree", () => repo.readTree(hash)),937+ revokeToken: (token) =>938+ marked("revokeToken", () => repo.revokeToken(token)),939+ })940+ )941+ ),942+ import: (params) => marked("import", () => binding.import(params)),943+ };944+945+ return { disposals, given, wrapped };946+};947+948+describe("results the binding gives back", () => {949+ it.live(950+ "are each disposed once read, so no call holds Artifacts' side open",951+ () =>952+ Effect.gen(function* () {953+ const made = yield* world();954+ const { disposals, given, wrapped } = disposing(made.binding);955+956+ yield* Effect.gen(function* () {957+ const repos = yield* RepoHost;958+ const name = RepoName.make("results");959+ const { first } = yield* seeded(name);960+ const at = Revision.Branch({ name: BranchName.make("main") });961+962+ yield* repos.refs(name).pipe(Effect.orDie);963+ yield* repos.remote(name).pipe(Effect.orDie);964+ yield* repos965+ .readFile(name, at, RepoPath.make("a.txt"))966+ .pipe(Effect.orDie);967+ yield* repos.log(name, at, 5).pipe(Effect.orDie);968+969+ const commit = yield* repos970+ .readCommit(name, first)971+ .pipe(Effect.orDie);972+973+ const tree = Option.getOrThrow(974+ Option.map(commit, (read) => read.tree)975+ );976+977+ const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);978+ const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;979+980+ yield* repos.readBlob(name, blob).pipe(Effect.orDie);981+982+ const token = yield* repos983+ .mintToken(name, "read", Duration.minutes(5))984+ .pipe(Effect.orDie);985+986+ yield* repos.revokeToken(name, token.id).pipe(Effect.orDie);987+ yield* repos988+ .fork(name, RepoName.make("results--fork"))989+ .pipe(Effect.orDie);990+ }).pipe(991+ Effect.provide(992+ RepoHostBinding.layer(wrapped).pipe(993+ Layer.provide(Layer.succeed(Fetch, made.fetch))994+ )995+ )996+ );997+998+ expect(new Set(given)).toStrictEqual(999+ new Set([1000+ "create",1001+ "createToken",1002+ "fork",1003+ "info",1004+ "log",1005+ "readBlob",1006+ "readCommit",1007+ "readFile",1008+ "readTree",1009+ ])1010+ );1011+ expect(disposals.toSorted()).toStrictEqual(given.toSorted());1012+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))1013+ );1014+});1015+1016 describe("git smart HTTP over the Fetch port", () => {1017 const token = Redacted.make("test-token");1018 1019 it.live(348 unmodified linesmodified:packages/artifacts/test/repo-host-contract.tsnot shown
Its text is not shown, modified.
modified:packages/checks/src/check-runner.tsnot shown
Its text is not shown, modified.
modified:packages/checks/src/classify.tsnot shown
Its text is not shown, modified.
added:packages/checks/test/fixtures/runs/turbo-vitest-assertion.jsonnot shown
Its text is not shown, added.
added:packages/checks/test/fixtures/runs/turbo-vitest-timeout.jsonnot shown
Its text is not shown, added.
modified:packages/checks/test/classify.test.tsnot shown
Its text is not shown, modified.
modified:packages/config/src/vitest.tsnot shown
Its text is not shown, modified.
modified:packages/config/test/example-burrow.test.tsnot shown
Its text is not shown, modified.
modified:packages/git/src/gateway.tsnot shown
Its text is not shown, modified.
modified:packages/git/test/gateway.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/code-store/binding.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/deciders.tsnot shown
Its text is not shown, modified.
modified:packages/project/src/project.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/code-store.test.tsnot shown
Its text is not shown, modified.
modified:packages/project/test/deciders.test.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/src/contracts.tsnot shown
Its text is not shown, modified.
modified:packages/protocol/test/mcp.test.tsnot shown
Its text is not shown, modified.
modified:packages/rules/test/example-burrow.test.tsnot shown
Its text is not shown, modified.
modified:packages/rules/test/example-datekit.test.tsnot shown
Its text is not shown, modified.
modified:packages/telemetry/src/spans/binding.tsnot shown
Its text is not shown, modified.
modified:packages/telemetry/src/spans/memory.tsnot shown
Its text is not shown, modified.
modified:packages/telemetry/src/defects.tsnot shown
Its text is not shown, modified.
modified:packages/telemetry/src/spans.tsnot shown
Its text is not shown, modified.
modified:packages/telemetry/test/defects.test.tsnot shown
Its text is not shown, modified.
modified:packages/telemetry/test/spans.test.tsnot shown
Its text is not shown, modified.
modified:.gitignore+2 added
47 unmodified lines48 .impeccable/49 50 # Agent worktrees Claude Code makes inside the checkout.51 .claude/worktrees/52+53+explainer/modified:DESIGN.md+2 added
434 unmodified lines435 Square. The radius is 2 px (`--radius: 0.125rem`), and shadcn's base-lyra components square most corners. Borders are one-pixel hairlines; the current tab's 2 px ink underline is the one heavy line, and no edge of a card carries a colour. An empty state's border is dashed (an unfilled field), and so is the rule that parts disclosed agents from credit. Marks are lucide icons at 16 px (14 px in dense places), stroke 1.75, one family.436 437 **No logomark.** The wordmark is the product's name set in the UI sans. Where a file must stand for the site (the favicon, `apple-touch-icon.png`, the manifest's icons), it is the repeat button emoji (U+1F501) drawn as text in `public/icons/icon.svg`, plain: in the reader's own emoji font and colours, filling the square, with no ground of its own. The rasters are that one drawing, rendered in headless Chromium at 1024 px on a transparent ground and downscaled with Lanczos: 512 and 192 for the manifest, 180 for iOS, and 16, 32 and 48 in `favicon.ico`. Since the emoji fills the square, the manifest offers no maskable icon. `apps/web/test/icons.test.ts` holds the text, the bare ground and the sizes.438 439+**The unfurl's card.** `public/og.png` (1200 × 630) is the repeat button emoji, in Noto Color Emoji, beside the domain in capitals, in IBM Plex Sans at weight 600, on the dark paper (`#0a0a0a`), rendered in headless Chromium. The root's head names it as `og:image` at prod's absolute URL, with `twitter:card` set to `summary_large_image`, so every page unfurls with it; `apps/web/test/head.test.ts` holds the metas and `icons.test.ts` the size.440+441 ## Components442 443 ### Top bar444 196 unmodified lines