Skip to content
Myr
Landed

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

authored by oscar · committed by the platform · parent 5157dd9 · Browse files · 111 files+4456 added−418 removed
This landing

State

Landed as f7b8ef2

By oscar

Credit

Diff stats

111 files+4456 added−418 removed

  • tests:+2781 added−137 removed
  • other:+1675 added−281 removed

111 files+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 lines
742 ]743 );744745 for (const evidence of run.evidence) {746 const said = evidence.signature ?? evidence.threw;747746 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 }752753 const declared = Array.isReadonlyArrayNonEmpty(policy.ratchets);
58 unmodified lines
modified:apps/cli/src/local/login.ts+165 added-64 removed
29 unmodified lines
3031import { currentEnv } from "../credential-helper.ts";32import { Credentials, gitHelperConfig } from "../credentials.ts";33import type { Profile } from "../credentials.ts";34import {35 CLI_CODE_PATH,36 cliClientIdOf,37 revoke,38 tradeCode,39} from "../oauth-token.ts";40import type { Issued } from "../oauth-token.ts";41import { Output } from "../output.ts";4243const SLUG = Brand.slug.toUpperCase();4445const LOOPBACK = "127.0.0.1";4647const SIGN_IN_WAIT = "5 minutes";4842const clientIdOf = (origin: string) => `${origin}/oauth/cli`;4349export const Loopback = Context.Reference<{50 readonly listen: (address: {51 readonly hostname: string;52 readonly port: number;
200 unmodified lines
253 })254 );255 });256252const tokenFromStdin = Effect.gen(function* () {257const firstLine = Effect.gen(function* () {258 const { stdin } = yield* Stdio.Stdio;259260 const [line = ""] = yield* stdin.pipe(261 Stream.decodeText(),
2 unmodified lines
264 Stream.runCollect,265 Effect.orElseSucceed((): readonly string[] => [])266 );267263 const token = line.trim();268 return line.trim();269});270271const tokenFromStdin = Effect.gen(function* () {272 const token = yield* firstLine;273274 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 lines
363 returned: Deferred.await(returned),364 };365});366358const TokenResponse = Schema.Struct({359 access_token: Schema.RedactedFromValue(Schema.NonEmptyString),360 token_type: Schema.String,361});367const 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 });371363const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);364372const 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)));378379const 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);386375 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();395378 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 );390391 if (response.status !== 200) {392 return yield* refused;393 }394395 const body = yield* decodeTokenResponse(yield* response.json);396397 if (body.token_type.toLowerCase() !== "bearer") {398 return yield* refused;399 }400401 return body.access_token;402 }).pipe(403 Effect.provide(FetchHttpClient.layer),404 Effect.mapError(() => refused)405 );396 return authorize;397};398399const tokenFromBrowser = (url: string, opens: boolean) =>400 Effect.scoped(
2 unmodified lines
403 const verifier = yield* randomText(32);404 const state = yield* randomText(32);405 const { redirectUri, returned } = yield* loopback;406416 const authorize = new URL("/authorize", url);417418 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 });413414 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 );420421 if (opens) {422 yield* (yield* Browser).open(authorize.href);
29 unmodified lines
452 return yield* exchange({ code, redirectUri, url, verifier });453 })454 );455456/**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 */462const 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}`;467468 const authorize = authorizeAt({469 challenge: yield* challengeOf(verifier),470 redirectUri,471 state: yield* randomText(32),472 url,473 });474475 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 );478479 if (opens) {480 yield* (yield* Browser).open(authorize.href);481 }482483 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 );494495 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 }500501 return yield* exchange({ code, redirectUri, url, verifier });502 });503504// A token given by hand, a pasted code's, or the loopback's: one way per sign-in.505const 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 }519520 if (way.tokenStdin) {521 const given: Issued = {522 expiresAt: Option.none(),523 refreshToken: Option.none(),524 token: yield* tokenFromStdin,525 };526527 return given;528 }529530 return way.paste531 ? yield* tokenFromPaste(url, way.opens)532 : yield* tokenFromBrowser(url, way.opens);533 });534535const verify = (url: string, token: Redacted.Redacted) =>536 Effect.scoped(537 Effect.gen(function* () {538 const client = yield* (yield* PlatformClient).connect({ token, url });
57 unmodified lines
596 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 lines
623 const env = yield* currentEnv;624 const name = profileName(given.profile, env);625 const url = yield* platformOf(given.url, given.profile, env);626555 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 });632562 const handle = yield* verify(url, token);633 const handle = yield* verify(url, issued.token);634564 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 });648649 const commands = gitHelperConfig(url);650651 if (!given.noGitConfig) {
72 unmodified lines
724 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);730731 // 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 );747748 // git keeps asking the helper for a platform another profile is still on.749 const unused: string[] = [];750751 for (const url of yield* helperUrls(env)) {
14 unmodified lines
766 }767768 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 lines
modified:apps/cli/src/credentials.ts+116 added-14 removed
1import { Brand } from "@repo/brand";2import { Handle } from "@repo/protocol/ids";3import {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";1819import { renew } from "./oauth-token.ts";2021// 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.24export 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 lines
50 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") {}6061const Store = Schema.fromJsonString(
22 unmodified lines
84const FILE_MODE = 0o600;8586const DIR_MODE = 0o700;8788/** Renewed this long before it lapses, so no call carries a token that dies on the way. */89export const RENEW_MARGIN = Duration.minutes(1);9091const sameToken = (one: Redacted.Redacted, other: Redacted.Redacted) =>92 Redacted.value(one) === Redacted.value(other);9394/** Replaced whole on every write so no reader sees half of one. */95export const CredentialsFile = Layer.effect(Credentials)(96 Effect.gen(function* () {97 const fs = yield* FileSystem.FileSystem;
60 unmodified lines
158 })159 )160 );161162 /**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;172173 if (174 profile.refreshToken === undefined ||175 profile.expiresAt === undefined ||176 profile.expiresAt - Duration.toMillis(RENEW_MARGIN) > now177 ) {178 return profile;179 }180181 const { refreshToken } = profile;182183 const issued = yield* renew(profile.url, refreshToken).pipe(184 Effect.option185 );186187 if (Option.isNone(issued)) {188 const latest = Option.fromNullishOr((yield* readable)[name]);189190 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 }200201 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 };213214 // 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);218219 return renewed;220 });221222 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 });232233 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 );249163 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 );263264 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;280179 const { [name]: _removed, ...rest } = profiles;180181 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 lines
added: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.5import { Clock, Effect, Option, Redacted, Schema } from "effect";6import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";78export const CLI_CLIENT_PATH = "/oauth/cli";910// Where the platform shows a code to paste: its page for a browser on another machine.11export const CLI_CODE_PATH = "/oauth/cli/code";1213export const cliClientIdOf = (origin: string) => `${origin}${CLI_CLIENT_PATH}`;1415const Secret = Schema.RedactedFromValue(Schema.NonEmptyString);1617const 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});2324const decodeTokenAnswer = Schema.decodeUnknownEffect(TokenAnswer);2526export class TokenRefused extends Schema.TaggedError<TokenRefused>()(27 "TokenRefused",28 {}29) {}3031/** What the endpoint issued: a token, and when it lapses and how to renew it, where it says. */32export interface Issued {33 readonly expiresAt: Option.Option<number>;34 readonly refreshToken: Option.Option<Redacted.Redacted>;35 readonly token: Redacted.Redacted;36}3738const post = (url: string, fields: Readonly<Record<string, string>>) =>39 Effect.gen(function* () {40 const client = yield* HttpClient.HttpClient;4142 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));4950const issue = (url: string, fields: Readonly<Record<string, string>>) =>51 Effect.gen(function* () {52 const response = yield* post(url, fields);5354 if (response.status !== 200) {55 return yield* new TokenRefused();56 }5758 const answer = yield* decodeTokenAnswer(yield* response.json);5960 if (answer.token_type.toLowerCase() !== "bearer") {61 return yield* new TokenRefused();62 }6364 const now = yield* Clock.currentTimeMillis;6566 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 };7475 return issued;76 }).pipe(Effect.mapError(() => new TokenRefused()));7778export 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 });9192export 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 });9899/**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 */104export 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 lines
56 )57 )58);5960const 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.62const 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 lines
74 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 lines
99100export 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;104105 const profile = yield* credentials.current;106107 if (Option.isSome(profile)) {102 return over(profile.value.url, Option.some(profile.value.token));108 const { url } = profile.value;109110 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 }120121 const url = yield* Config.option(122 Config.NonEmptyString(URL_VARIABLE)
1 unmodified line
124125 // 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 lines
5 Claim,6 Credits,7 Finish,8 FrontPage,9 Land,10 LedgerOf,11 ListAsks,12 ListDiscussions,13 ListProjects,
615 unmodified lines
629const submitted = viewOf(SubmitAnswer.successSchema, receipt);630631const finished = viewOf(Finish.successSchema, receipt);632633// The checks run after `land` returns; the same request sent again reads where they stand.634const 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);641642const isReceipt = Schema.is(LandReceipt);643644/** `finish` and `land` refuse stages 0–1 inside a success's receipt; the command prints them as refusals and exits 1. */645export const refusalsIn = (
7 unmodified lines
653export 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 lines
modified:apps/cli/test/local/login.test.ts+177 added-1 removed
13 unmodified lines
14import {15 Clock,16 ConfigProvider,17 Context,18 Deferred,19 Effect,20 Exit,21 Fiber,22 FileSystem,
164 unmodified lines
187interface 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}195196const cli = (argv: readonly string[], run: Run) =>
10 unmodified lines
207 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 lines
759 30_000760 );761});762763const 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 );776777describe(`${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;787788 const fiber = yield* Effect.forkChild(789 cli(["login", "--url", server.origin, "--no-browser"], run)790 );791792 yield* visit(yield* signInUrl(server.origin));793794 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();795796 const renewal = yield* renewalOf(env, "default");797798 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 );809810 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 );830831 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` };839840 yield* cli(["login", "--url", server.origin, "--token-stdin"], run);841842 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});848849// Where the platform's code page would show the code: the sign-in's last redirect, not followed.850const shownCode = (at: string) =>851 Effect.gen(function* () {852 const client = yield* HttpClient.HttpClient;853 const response = yield* client.get(at);854855 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 );865866describe(`${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>();875876 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 );883884 const shown = yield* signInUrl(server.origin);885 const code = yield* shownCode(shown);886887 yield* Deferred.succeed(888 pasted,889 new TextEncoder().encode(` ${code ?? ""} \n`)890 );891892 expect(Exit.isSuccess(yield* Fiber.join(fiber))).toBeTruthy();893894 const [query] = yield* server.authorizations;895896 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 );912913 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"));919920 const exit = yield* cli(["login", "--paste", "--token-stdin"], {921 env,922 seams: platform.layer,923 stdin: `${given}\n`,924 });925926 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});933934describe(`${Brand.cli} logout`, () => {935 it.live(936 "removes the profile and the git config that names the helper for its platform",937 () =>
80 unmodified lines
modified:apps/cli/test/credentials.test.ts+145 added-2 removed
17 unmodified lines
18 CredentialsUnwritable,19 gitHelperConfig,20} from "../src/credentials.ts";21import type { Profile } from "../src/credentials.ts";22import { oauthServer, refreshTokenOf, renewedTokenOf } from "./oauth-server.ts";2324const SLUG = Brand.slug.toUpperCase();2526const token = "tok-default-0123456789abcdefghijklmnopqrstuvwxyz";
126 unmodified lines
153 const credentials = yield* credentialsIn(env);154155 yield* credentials.put("default", defaultProfile);156156 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 lines
202 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))203 );204});205206const 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 }));212213describe("a stored browser sign-in, near its token's lapse", () => {214 const signedIn = "tok-signed-in-0123456789abcdefghijklmnopqrstuvwxyz";215216 const given = "refresh-given";217218 // 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 );230231 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);238239 yield* credentials.put(240 "default",241 yield* browserProfile(server.origin, 30_000)242 );243244 const read = yield* credentials.current;245 const again = yield* (yield* credentialsIn(env)).current;246247 const renewed = {248 refreshToken: refreshTokenOf(1),249 token: renewedTokenOf(signedIn, 0),250 };251252 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 );269270 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);275276 yield* credentials.put("alice", yield* browserProfile(server.origin, 0));277278 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 );288289 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);294295 yield* credentials.put(296 "default",297 yield* browserProfile(server.origin, 10 * 60_000)298 );299300 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 );306307 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 });316317 const { env } = yield* configHome;318 const credentials = yield* credentialsIn(env);319320 yield* credentials.put(321 "default",322 yield* browserProfile(server.origin, 0)323 );324325 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 );331332 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);338339 yield* credentials.put("default", defaultProfile);340341 expect(seen(yield* credentials.current)).toStrictEqual(342 seen(Option.some(defaultProfile))343 );344 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))345 );346});347348describe("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 lines
added:apps/cli/test/land-view.test.ts+60 added
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import type { Land } from "@repo/protocol/contracts";4import { Outcome } from "@repo/protocol/domain/outcome";5import {6 CommitSha,7 LandedSha,8 ProjectName,9 RequestId,10} from "@repo/protocol/ids";11import { StaleBase } from "@repo/protocol/refusal";12import { Option } from "effect";1314import { refusalsIn, views } from "../src/render.ts";1516const base = CommitSha.make("4c2e6a8b0d2f4a6c8e0b2d4f6a8c0e2b4d6f8a0c");1718const head = CommitSha.make("9f1e3d5c7b9a1f3e5d7c9b1a3f5e7d9c1b3a5f7e");1920const main = LandedSha.make("2b4d6f8a0c2e4a6c8e0b2d4f6a8c0e2b4d6f8a0c");2122type Receipt = typeof Land.successSchema.Type;2324const receiptWith = (outcome: Outcome): Receipt => ({25 base,26 head,27 outcome,28 project: ProjectName.make("alice/datekit"),29 requestId: RequestId.make("land-alice-01"),30});3132const textOf = (receipt: Receipt) =>33 Option.match(views.land(receipt), {34 onNone: () => "",35 onSome: ({ markdown, text }) => text ?? markdown,36 });3738describe("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 });4647 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 });5253 it("refused, is the command's refusal, as finish's is", () => {54 const stale = new StaleBase({ base, conflicts: [], main });5556 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 lines
45export 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}1314interface Grant {15 readonly challenge: string;16 readonly clientId: string;17 readonly redirectUri: string;18}1916const 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});20const TokenForm = Schema.Record(Schema.String, Schema.String);2122/** Base64url without padding, as RFC 7636 §4.2 spells the S256 challenge. */23const base64url = (bytes: Uint8Array) =>24 btoa(String.fromCodePoint(...bytes))
11 unmodified lines
3637const refused = (error: string) =>38 HttpServerResponse.jsonUnsafe({ error }, { status: 400 });3940export const refreshTokenOf = (count: number) => `refresh-${count}`;4142export const renewedTokenOf = (token: string, count: number) =>43 `${token}-renewed-${count}`;4445/**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 */50export 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);5859 // 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 );6364 // Seconds each token lives, as the platform's default says.65 const lifetime = 3600;6667 const tokens = (accessToken: string) =>68 Effect.gen(function* () {69 const count = yield* Ref.updateAndGet(refreshes, (n) => n + 1);70 const refreshToken = refreshTokenOf(count);7172 yield* Ref.update(live, (all) => [...all.slice(-1), refreshToken]);7374 return HttpServerResponse.jsonUnsafe({75 access_token: accessToken,76 expires_in: lifetime,77 refresh_token: refreshToken,78 token_type: "bearer",79 });80 });8182 const authorize = (query: URLSearchParams) =>83 Effect.gen(function* () {84 yield* Ref.update(authorizations, (all) => [...all, query]);85
30 unmodified lines
116117 return HttpServerResponse.redirect(back.href, { status: 302 });118 });11986 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);12490 yield* Ref.update(grants, (all) => {91 const left = new Map(all);125 yield* Ref.update(grants, (all) => {126 const left = new Map(all);12793 left.delete(form.code);128 left.delete(code);12995 return left;130 return left;131 });132133 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 }141142 return yield* tokens(options.token);143 });14498 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]);148108 return HttpServerResponse.jsonUnsafe({109 access_token: options.token,110 token_type: "bearer",149 const presented = form.refresh_token ?? "";150151 if (152 options.refuseRenewals === true ||153 !(yield* Ref.get(live)).includes(presented)154 ) {155 return refused("invalid_grant");156 }157158 return yield* tokens(159 renewedTokenOf(options.token, yield* Ref.get(refreshes))160 );161 });162163 const revoked = (form: Readonly<Record<string, string>>) =>164 Effect.gen(function* () {165 yield* Ref.update(revocations, (all) => [...all, form]);166167 if ((yield* Ref.get(live)).includes(form.token ?? "")) {168 yield* Ref.set(live, []);169 }170171 return HttpServerResponse.empty({ status: 200 });172 });173174 const token = Effect.gen(function* () {175 const form = yield* HttpServerRequest.schemaBodyUrlParams(TokenForm);176177 if (form.grant_type === "authorization_code") {178 return yield* traded(form);179 }180181 if (form.grant_type === "refresh_token") {182 return yield* renewed(form);183 }184185 return form.grant_type === undefined && form.token !== undefined186 ? yield* revoked(form)187 : refused("unsupported_grant_type");188 }).pipe(Effect.orElseSucceed(() => refused("invalid_request")));189190 const app = Effect.gen(function* () {191 const request = yield* HttpServerRequest.HttpServerRequest;
20 unmodified lines
212 "port" in address213 ? `http://127.0.0.1:${address.port}`214 : yield* Effect.die("the test server listens on a socket, not a port");215140 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 line
2import { Brand } from "@repo/brand";3import { Contracts } from "@repo/protocol/contracts";4import { AskId, Handle, KindName } from "@repo/protocol/ids";5import { unanswered } from "@repo/protocol/testing";6import { ConfigProvider, Effect, Layer, Option, Redacted } from "effect";6import { ConfigProvider, Effect, Layer, Option, Redacted, Ref } from "effect";7import { FetchHttpClient } from "effect/http";89import { Credentials } from "../src/credentials.ts";10import type { Profile } from "../src/credentials.ts";
34 unmodified lines
45 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 });5152const profileOn = (url: string, token: string): Profile => ({53 token: Redacted.make(token),
31 unmodified lines
85 expect(yield* platform.seen).toStrictEqual([`Bearer ${knownToken}`]);86 }).pipe(Effect.scoped)87 );8889 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);9596 // 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 });112113 const run = yield* runProgram(["status", "--json"], {114 client: remote(renewing),115 handlers,116 });117118 expect(run.code).toBe(0);119 expect(yield* platform.seen).toStrictEqual([`Bearer ${knownToken}`]);120 }).pipe(Effect.scoped)121 );122123 it.live("status says whom the platform takes the caller for", () =>124 Effect.gen(function* () {125 const platform = yield* httpPlatform(handlers);126
125 unmodified lines
modified:apps/cli/test/repo-context.test.ts+1 added-1 removed
129 unmodified lines
130 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};137138describe("the repo the CLI stands in", () => {
62 unmodified lines
modified:apps/platform/src/adapters/answer-runs-workflow.ts+8 added-2 removed
1 unmodified line
2import type { ProjectName } from "@repo/protocol/ids";3import { Effect, Layer, Schema } from "effect";45import { AnswerParams } from "../answer-runs.ts";6import { disposed } from "./rpc-result.ts";78export interface AnswerInstance {9 readonly id: string;10 readonly restart: () => Promise<void>;
18 unmodified lines
29]);3031const 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 );3637 if (ended.has(status)) {38 yield* Effect.tryPromise(() => instance.restart());39 }
12 unmodified lines
5253 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 lines
modified:apps/platform/src/adapters/do-projects.ts+2 added
15 unmodified lines
16 ExitEncoded,17 ProjectMethod,18 SuccessOf,19} from "../project-calls.ts";20import { disposed } from "./rpc-result.ts";2122export interface ProjectStub {23 readonly call: (request: typeof CallRequest.Encoded) => Promise<ExitEncoded>;24}
26 unmodified lines
51 const request = yield* encodeCall(method, args);5253 // 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 );5859 return yield* decodeReply(method, reply);
140 unmodified lines
modified:apps/platform/src/adapters/rate-limits.ts+2 added
3 unmodified lines
4import { Effect, Layer, Ref } from "effect";56import { RateLimits } from "../rate-limits.ts";7import type { Limited } from "../rate-limits.ts";8import { disposed } from "./rpc-result.ts";910export type Limits = Readonly<Record<Limited, number>>;1112// Mirrors each binding's `simple.limit` in wrangler.jsonc: a binding can't say its own limit.
26 unmodified lines
39 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 lines
added:apps/platform/src/adapters/rpc-result.ts+21 added
1import { Effect, Predicate } from "effect";23/**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 */12export 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;1718 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 lines
17 Redacted,18 Schema,19} from "effect";2021import { disposed } from "./rpc-result.ts";2223// Each token is revoked when its job ends, so this bounds only a revoke that failed.24export const jobTokenTtl = Duration.minutes(5);2526export type SandboxMethod =
121 unmodified lines
148 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 lines
modified:apps/platform/src/auth/attempts/binding.ts+2 added
1import { Effect, Layer } from "effect";23import { disposed } from "../../adapters/rpc-result.ts";4import { SignInAttempts } from "../attempts.ts";56export 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 line
2// the brand's, onboarded for sending on the account.3import { Brand } from "@repo/brand";4import { Effect, Layer } from "effect";56import { disposed } from "../../adapters/rpc-result.ts";7import { MailFailed, Mailer } from "../mailer.ts";89export const MAIL_FROM = {10 email: `no-reply@${Brand.domain}`,
13 unmodified lines
24 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
1import { Brand } from "@repo/brand";23export const CLI_CLIENT_PATH = "/oauth/cli";45// Where a sign-in for `login --paste` ends: a page that shows the code, for a browser on another machine than the CLI.6export const CLI_CODE_PATH = "/oauth/cli/code";78export const cliClientId = (origin: string) => `${origin}${CLI_CLIENT_PATH}`;97// 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).13export 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 lines
36 byPassword,37 chosenDisplayName,38 chosenHandle,39 completed,40 CSRF_COOKIE,40 csrfCookieName,41 csrfOf,42 csrfCookie,43 failedPage,44 freshCsrf,45 HeldHandles,
365 unmodified lines
411 noEmail:412 "Google did not share a verified email for that account. Sign up with an email and password instead.",413} as const;414414// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.415const 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 */422export const googleCookieName = (challenge: string) =>423 `__Host-google-sign-in-${challenge.slice(0, 16)}`;424425// `SameSite=Lax`: Google's redirect back is a cross-site top-level navigation, which a `Strict` cookie misses.426const googleCookie = {427 httpOnly: true,428 path: "/",429 sameSite: "lax",430 secure: true,431} as const;432433// Only this leg's cookie: another in progress in this browser keeps its own.434const legDone =424const 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 );443444// Carries the challenge of the verifier in this browser's cookie, so only this browser finishes the leg.445const GoogleLeg = Schema.Struct({446 challenge: Schema.String,
71 unmodified lines
518 },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.orDie
10 unmodified lines
537 ).pipe(Effect.mapError(() => startAgain));538539 const pending = yield* openState(cookieKey, sealed);540530 if (request.cookies[CSRF_COOKIE] !== pending.csrf) {541 if (csrfOf(request, pending.csrf) !== pending.csrf) {542 return yield* startAgain;543 }544545 return yield* toGoogle(client, pending.request, Option.none());
30 unmodified lines
576 ),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.orDie
117 unmodified lines
702 ).pipe(Effect.mapError(() => startAgain));703704 const leg = yield* legs.open(cookieKey, query.state);705695 const verifier = request.cookies[GOOGLE_COOKIE] ?? "";706 const verifier = request.cookies[googleCookieName(leg.challenge)] ?? "";707708 if ((yield* challengeOf(verifier)) !== leg.challenge) {709 return yield* startAgain;710 }
19 unmodified lines
730 return yield* signInPageFor(731 leg.request,732 401,733 confirmed.failure.reason723 ).pipe(Effect.flatMap(legDone));734 ).pipe(Effect.flatMap(legDone(leg.challenge)));735 }736737 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 });741731 return yield* legDone(answered);742 return yield* legDone(leg.challenge)(answered);743 });744745const PostedProfile = Schema.Struct({746 csrf: Schema.String,
23 unmodified lines
770 const pending = yield* pendingHandles.open(cookieKey, form.request);771772 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 lines
modified:apps/platform/src/auth/pages.ts+26 added-1 removed
120 unmodified lines
121.or .line{flex:1;height:1px;background-color:var(--rule)}122.aside{margin:24px 0 0;text-align:center}123pre{margin:8px 0 12px;padding:8px 12px;overflow-x:auto;background-color:var(--surface);border:1px solid var(--rule)}124code{font-family:"IBM Plex Mono",ui-monospace,"SF Mono",Menlo,Consolas,monospace;font-size:.8125rem;overflow-wrap:anywhere}125code.paste{display:block;padding:12px;border:1px solid var(--rule);border-radius:2px;user-select:all}126ul{margin:0;padding-left:1.25rem}127li{margin:0 0 8px}128`;129
67 unmodified lines
197 return "";198 }199200 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 }205206 const name = `<strong>${escapeHtml(asker.clientName)}</strong>`;207
275 unmodified lines
483 after: `Remembered it? <a href="${escapeHtml(signInHref)}">Sign in</a>`,484 }485 );486487/**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 */491export 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 );508509export const problemPage = (message: string, home = "/") =>510 page(511 "Sign-in problem",512 `<h1>Signing in did not work</h1>
5 unmodified lines
added:apps/platform/src/auth/resource.ts+77 added
1import { Effect } from "effect";23// 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`.11const asPlatform = (origin: string) => (resource: string) => {12 const url = URL.parse(resource);1314 return url !== null &&15 url.origin === origin &&16 url.username === "" &&17 url.password === "" &&18 url.search === "" &&19 url.hash === ""20 ? origin21 : resource;22};2324const withResources = (params: URLSearchParams, origin: string) => {25 const named = new URLSearchParams(params);2627 named.delete("resource");2829 for (const resource of params.getAll("resource").map(asPlatform(origin))) {30 named.append("resource", resource);31 }3233 return named;34};3536// An authorize request's `resource`, read as the platform's where it names a URL on it.37export const authorizeNamingPlatform = (request: Request, origin: string) => {38 const url = new URL(request.url);3940 if (!url.searchParams.has("resource")) {41 return request;42 }4344 url.search = withResources(url.searchParams, origin).toString();4546 return new Request(url, request);47};4849const isForm = (request: Request) =>50 request.method === "POST" &&51 (request.headers.get("content-type") ?? "").startsWith(52 "application/x-www-form-urlencoded"53 );5455// A token request's `resource`, in its form body, read the same way.56export 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);6162 if (!params.has("resource")) {63 return request;64 }6566 const headers = new Headers(request.headers);6768 headers.delete("content-length");6970 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 lines
28 handleKey,29} from "./accounts.ts";30import type { Account } from "./accounts.ts";31import { SignInAttempts } from "./attempts.ts";32import { CLI_CLIENT_PATH, cliClientMetadata } from "./cli-client.ts";32import {33 CLI_CLIENT_PATH,34 CLI_CODE_PATH,35 cliClientMetadata,36} from "./cli-client.ts";37import { codeMatches, codeTag, deadTag, freshCode } from "./codes.ts";38import type { CodePurpose } from "./codes.ts";39import { firstPartyOf } from "./first-party.ts";40import { Mailer } from "./mailer.ts";41import { OAuthStore } from "./oauth-store.ts";42import {43 ACCOUNT_PATHS,44 addEmailPage,45 cliCodePage,46 codePage,47 continuePage,48 problemPage,49 resetPage,
13 unmodified lines
63 sessionAccount,64 withoutSession,65 withSession,66} from "./platform-session.ts";67import { authorizeNamingPlatform, tokenNamingPlatform } from "./resource.ts";68import {69 AuthRequest,70 openState,71 sealing,
50 unmodified lines
122export 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 lines
182const STAND_IN_HASH = PasswordHash.make(183 `pbkdf2-sha256$${PasswordPolicy.iterations}$${"A".repeat(22)}$${"A".repeat(43)}`184);185179export 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 */192export const csrfCookieName = (csrf: string) =>193 `__Host-sign-in-${csrf.slice(0, 16)}`;194195export const csrfOf = (196 request: HttpServerRequest.HttpServerRequest,197 csrf: string198): string | undefined => request.cookies[csrfCookieName(csrf)];199200export const csrfCookie = {201 httpOnly: true,202 path: "/",203 sameSite: "strict",204 secure: true,205} as const;206188const BASE_CSP =189 "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'";190207// CSP's host grammar cannot name an IPv6 literal host, so only its scheme.208const redirectSource = (redirectUri: string) =>209 Option.fromNullishOr(URL.parse(redirectUri)).pipe(210 Option.filter(({ origin }) => origin !== "null"),
1 unmodified line
212 hostname.startsWith("[") ? protocol : origin213 )214 );215200// 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.219const 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("; ");238239export const htmlPage = (240 body: string,241 status: number,
147 unmodified lines
389390const 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.orDie
4 unmodified lines
402 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);409410// The form a request posted, if it posted one: its CSRF token names the cookie to clear.411const postedCsrf = Effect.gen(function* () {412 const request = yield* HttpServerRequest.HttpServerRequest;413414 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});423424// 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 now
2 unmodified lines
430export 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;438439 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 );451406 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 });459460 // 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 });472473 return yield* Option.match(account, {474 onNone: () => Effect.succeed(cleared),475 onSome: (found) => withSession(cookieKey, found)(cleared),476 });477 });478479const offeredSignIn = (480 request: AuthRequest,
74 unmodified lines
555// Someone signed in here already is asked only to continue; anyone else, to sign in.556const showSignIn = (request: HttpServerRequest.HttpServerRequest) =>557 Effect.gen(function* () {558 const api = yield* oauthApi;559 const { origin } = yield* Authorization;560 const { cookieKey } = yield* SignInKeys;561562 const web = yield* HttpServerRequest.toWeb(request).pipe(Effect.orDie);563511 const parsed = yield* provider(() => api.parseAuthRequest(web));564 const parsed = yield* provider(() =>565 api.parseAuthRequest(authorizeNamingPlatform(web, origin))566 );567568 const account = yield* sessionAccount(cookieKey, request);569570 return yield* Option.match(account, {
905 unmodified lines
1476 headers: { "cache-control": "public, max-age=300" },1477 });1478});14791480// The code is shown, never kept: it is worth nothing without the CLI's verifier.1481const cliCode = Effect.gen(function* () {1482 const { webUrl } = yield* SignInHome;14831484 const { code } = yield* HttpServerRequest.schemaSearchParams(1485 Schema.Struct({ code: Schema.optionalKey(Schema.NonEmptyString) })1486 ).pipe(Effect.orElseSucceed(() => ({ code: undefined })));14871488 return htmlPage(1489 cliCodePage(1490 code,1491 Option.getOrElse(webUrl, () => "/")1492 ),1493 code === undefined ? 400 : 2001494 );1495});14961497const authorizationServer = (request: HttpServerRequest.HttpServerRequest) =>1498 Effect.gen(function* () {1427 const { context, server } = yield* Authorization;1499 const { context, origin, server } = yield* Authorization;15001501 const store = yield* OAuthStore;15021431 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 );15071508 const response = yield* Effect.promise(() =>1509 server.fetch(web, { OAUTH_KV: store }, context)1510 );
67 unmodified lines
1578 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);15831584 for (const path of AUTHORIZATION_SERVER_PATHS) {1585 yield* add("*", path, authorizationServer);1586 }
2 unmodified lines
modified:apps/platform/src/visibility/state.ts+3 added-1 removed
6 unmodified lines
7 SaltSource,8} from "@repo/project/visibility/state";9import { Effect, Layer, Schema } from "effect";1011import { disposed } from "../adapters/rpc-result.ts";12import { AdmissionParams, admissionId } from "../answer-runs.ts";13import type { PlatformConfig } from "../platform.ts";14import { layerRepos } from "./layer-repos.ts";15
33 unmodified lines
49 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 lines
modified:apps/platform/src/workflows/answer/lanes.ts+3 added
122 unmodified lines
123 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 lines
modified:apps/platform/src/home.ts+1 added
106 unmodified lines
107 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 lines
modified:apps/platform/src/project-do.ts+8 added-3 removed
128 unmodified lines
129 override webSocketMessage(socket: WebSocket): Promise<void> {130 return this.#watched((room) => room.heard(socket));131 }132133 // 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 lines
8import { FrontPage } from "@repo/project/front-page";9import { Projects } from "@repo/project/projects";10import { StandingPostures } from "@repo/project/standing-posture";11import { authenticated, bearerToken } from "@repo/protocol/authenticate";12import { Client, Contracts, surfaced } from "@repo/protocol/contracts";12import {13 Client,14 Contracts,15 surfaced,16 surfacedToAnyone,17} from "@repo/protocol/contracts";18import { ProjectName } from "@repo/protocol/ids";19import { toToolkit } from "@repo/protocol/mcp";20import { briefResources, skillPrompt } from "@repo/protocol/mcp-extras";21import { Authenticated } from "@repo/protocol/principal";
58 unmodified lines
80 /^\/(?:install\.sh|releases\/(?:manifest\.json|[^/]+\/[^/]+))$/u;8182const SKILLS_PATH = /^\/\.well-known\/agent-skills\/.+$/u;8384// MCP for anyone: it reads what anyone may, so it takes no credential and refuses none.85export const PUBLIC_MCP_PATH = "/mcp/public";8687// 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.90const isExempt = (path: string) =>
3 unmodified lines
94 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;100101const PROTECTED_RESOURCE_PATH = "/.well-known/oauth-protected-resource";102103const originOf = (request: HttpServerRequest.HttpServerRequest) =>
112 unmodified lines
216 );217 })218);219220// A call from the MCP for anyone carries no credential, so it runs as anyone even when its client sent one.221const forwardNoCredential = RpcMiddleware.layerClient(222 Authenticated,223 ({ next, request }) => next(request)224);225226const projection = toToolkit(surfaced("mcp"), Effect.service(Client));227228const anyoneProjection = toToolkit(229 surfacedToAnyone("mcp"),230 Effect.service(Client)231);232233// Made from the skill's parts, not its `SKILL.md`, whose hash is a promise the234// router's build may not await.235const contribute = skillPrompt(236 platformSkillParts({ commands: commandDocs(Contracts) })
17 unmodified lines
254 }).pipe(Layer.provide(signedInOnly))255 )256);257258// Its own server, toolkit and client, so nothing it is built from is shared with the signed-in one's.259const 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);278279const rpcIn = (serialization: Layer.Layer<RpcSerialization.RpcSerialization>) =>280 RpcServer.toHttpEffect(Contracts).pipe(Effect.provide(serialization));281282const rpc = HttpRouter.use((router) =>
136 unmodified lines
419 discovery,420 raw,421 git,422 mcp,423 mcpForAnyone,424 rpc,425 releaseRoutes,426 agentSkillRoutes,427 identifyCaller
3 unmodified lines
modified:apps/platform/src/watch.ts+19 added-4 removed
178 unmodified lines
179 heard: (socket: WebSocket) => catchUp([socket]),180 };181};182183// Codes a close only reports, which `close()` refuses to send.184const reportOnly: ReadonlySet<number> = new Set([1005, 1006, 1015]);185185export 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.188export 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;204205interface Upgraded {206 readonly webSocket: WebSocket | null;207}
150 unmodified lines
modified:apps/platform/src/well-known.ts+60 added-8 removed
149 unmodified lines
150 onSome: (sha) => keptSkillAt(project, sha),151 })152 );153154const LISTED_SKILL_VERSION = 1;155156// 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.160const 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)}`;174175 return yield* cache.through(176 key,177 Effect.gen(function* () {178 const kept = Option.flatMap(yield* store.get(key), decodeKept);179180 if (Option.isSome(kept)) {181 return Option.fromUndefinedOr(kept.value.content);182 }183184 const read = yield* landedSkill(project);185186 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 );200201 return read;202 })203 );204 });205206const decodeKey = Schema.decodeUnknownOption(ProjectKey);207208const INDEX_VERSION = 1;209
4 unmodified lines
214const decodeKeptIndex = Schema.decodeOption(KeptIndex);215216const encodeKeptIndex = Schema.encodeEffect(KeptIndex);217166const indexOf = (projects: readonly ProjectName[]) =>218const 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 lines
281 if (Option.isSome(kept)) {282 return kept.value.content;283 }284233 const built = yield* indexOf(listed.map(({ project }) => project));285 const built = yield* indexOf(listed);286287 yield* encodeKeptIndex({ content: built }).pipe(288 Effect.flatMap((text) => store.put(key, text)),289 Effect.catch((error) =>
91 unmodified lines
modified:apps/platform/test/workflows/answer.fixtures.ts+55 added
536 unmodified lines
537 requestId: receipt.requestId,538 } satisfies Admitted;539 });540541export const ownMessage = "Split words on runs of spaces";542543/** Alice's own change, pushed to her working fork and sent to `land`, which queues it. */544export const landedOwn = Effect.gen(function* () {545 yield* advanceTo("2026-10-07T12:00:00Z");546547 const api = yield* Projects.use((each) => each.create(project)).pipe(548 Effect.orDie549 );550551 yield* api.initProject(alice, {}).pipe(Effect.orDie);552553 const first = yield* Pusher.use((each) =>554 each.push(repo, Option.none(), start)555 );556557 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);558559 const { fork } = yield* api.fork(alice).pipe(Effect.orDie);560 const opened = LandedSha.make(first);561562 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 );569570 const merged = yield* LanderCalls.use((calls) =>571 calls.preview({ base: first, fork, head, main: opened, repo })572 );573574 const request = {575 base: first,576 head,577 message: ownMessage,578 requestId: RequestId.make("land-alice-01"),579 };580581 const receipt = yield* api.land(alice, request).pipe(Effect.orDie);582583 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});595596export 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 lines
modified:apps/platform/test/workflows/answer.test.ts+62 added-1 removed
36 unmodified lines
37 Answer,38 OutcomeJson,39 runWorkflow,40} from "../../src/workflows/answer.ts";41import { failingPathsOf } from "../../src/workflows/answer/lanes.ts";41import { failingPathsOf, laneLog } from "../../src/workflows/answer/lanes.ts";42import { runAnswer } from "../../src/workflows/answer/program.ts";43import { memoSteps } from "../../src/workflows/step.ts";44import type { StepRunner, WorkflowSteps } from "../../src/workflows/step.ts";45import { fakeEnv } from "../fake-env.ts";
8 unmodified lines
54 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 lines
884 })885 );886});887888describe(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});913914describe(failingPathsOf, () => {915 it("names the repo files a failure points at, tests and absolute paths left out", () => {916 expect(917 failingPathsOf(
155 unmodified lines
1073 expect(engine.ran).toStrictEqual(["load"]);1074 })1075 );1076});10771078describe("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;10841085 yield* scriptProjectLanes(own.admitted.merged, { result: "passed" });10861087 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);10911092 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.3import { describe, expect, it } from "@effect/vitest";4import { CommitSha, LayerName, ProjectName } from "@repo/protocol/ids";4import { AnswerRuns } from "@repo/project/answer-runs";5import type { AnswerQueue } from "@repo/project/answer-runs";6import {7 CommitSha,8 LayerName,9 ProjectName,10 RequestId,11} from "@repo/protocol/ids";12import { untouchable } from "@repo/testkit/untouchable";13import { Effect } from "effect";1415import { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";16import type { AnswerWorkflow } from "../src/adapters/answer-runs-workflow.ts";17import { AdmissionParams, admissionId } from "../src/answer-runs.ts";1819const INSTANCE_ID = /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u;20
32 unmodified lines
53 named: heads.every((head, at) => (ids[at] ?? "").endsWith(`-${head}`)),54 }).toStrictEqual({ distinct: 2, fit: true, named: true });55 });56});5758describe("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>();6566 // 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 });7576 const workflow: AnswerWorkflow = {77 create: ({ id }) => {78 if (started.has(id)) {79 return Promise.reject(new Error("the id is taken"));80 }8182 started.add(id);8384 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 };101102 const runs = yield* AnswerRuns.pipe(103 Effect.provide(104 AnswerRunsWorkflow(workflow, ProjectName.make("alice/datekit"))105 )106 );107108 const requestId = RequestId.make("request-0001");109 const queue = untouchable<AnswerQueue>("AnswerQueue");110111 yield* runs.start(requestId, queue);112 yield* runs.start(requestId, queue);113114 expect(disposals).toStrictEqual(["create", "status", "get"]);115 })116 );117});
modified:apps/platform/test/auth.test.ts+17 added
104 unmodified lines
105 });106 })107 );108109 // 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));116117 const responses = yield* Effect.forEach(118 [`${metadataUrl}/mcp`, `${metadataUrl}/mcp/public`],119 (url) => fetch(new Request(url))120 );121122 expect(responses.map(({ status }) => status)).toStrictEqual([404, 404]);123 })124 );125126 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 lines
modified:apps/platform/test/do-projects.test.ts+63 added-1 removed
18 unmodified lines
19 RequestId,20} from "@repo/protocol/ids";21import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";22import { advanceTo } from "@repo/testkit/clock";23import { Effect, Fiber, Layer, Option, Redacted, Ref, Schema } from "effect";23import {24 Effect,25 Fiber,26 Layer,27 Option,28 Predicate,29 Redacted,30 Ref,31 Schema,32} from "effect";3334import { DoProjects } from "../src/adapters/do-projects.ts";35import type { ProjectNamespace } from "../src/adapters/do-projects.ts";36import {
170 unmodified lines
207 other: yield* outcomeOf(projects.get(other)),208 };209});210211// 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.213const disposing = (214 namespace: ProjectNamespace,215 disposals: string[]216): ProjectNamespace => ({217 get: (id) => {218 const stub = namespace.get(id);219220 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});242243describe("Projects over the Project DO namespace", () => {244 it("takes the Worker's PROJECT binding", () => {245 expectTypeOf<Env["PROJECT"]>().toExtend<ProjectNamespace>();246 });
88 unmodified lines
335 ]);336 }).pipe(Effect.provide(world))337 );338339 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);346347 yield* Effect.gen(function* () {348 const made = yield* (yield* Projects).create(project);349350 yield* made.initProject(alice, {});351 yield* made.status(bob);352 }).pipe(353 Effect.provide(DoProjects(recording).pipe(Layer.provide(unlisted)))354 );355356 expect(disposals).toStrictEqual(["listAsks", "initProject", "status"]);357 }).pipe(Effect.provide(world))358 );359360 // 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 lines
modified:apps/platform/test/generated.test.ts+15 added-5 removed
322 unmodified lines
323 message: "Change the project",324 requestId: RequestId.make(requestId),325 };326327 return { api, land: () => api.land(alice, request).pipe(Effect.orDie) };327 const send = api.land(alice, request).pipe(Effect.orDie);328329 // `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 });333334const landedSha = (outcome: Outcome) =>335 Outcome.guards.Landed(outcome) ? Option.some(outcome.sha) : Option.none();
127 unmodified lines
463 }).pipe(Effect.provide(world))464 );465466 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 lines
478 );479480 yield* Mishaps.use((each) => each.next("lost"));481478 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);486487 // 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);490491 const again = yield* changed.land();492493 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 lines
modified:apps/platform/test/google.test.ts+96 added-7 removed
18 unmodified lines
19import { Email } from "../src/auth/accounts.ts";20import {21 GOOGLE_DISCOVERY,22 googleAuthorizeUrl,23 googleCookieName,24 GoogleKeysPerIsolate,25 googlePerson,26} from "../src/auth/google.ts";27import type { GoogleKeys } from "../src/auth/google.ts";28import { Identities, IdentityTaken } from "../src/auth/identities.ts";29import { IdentitiesMemory } from "../src/auth/identities/memory.ts";30import { hashPassword } from "../src/auth/password.ts";31import { tokenReader } from "../src/auth/provider.ts";32import { csrfCookieName } from "../src/auth/sign-in.ts";33import { SignInFailed } from "../src/auth/state.ts";34import { decodeEnv, InvalidEnv } from "../src/platform.ts";35import worker from "../src/worker.ts";36import { fakeEnv, passwordPepper } from "./fake-env.ts";
15 unmodified lines
52} from "./google.fixtures.ts";53import {54 authorizeUrl,55 codeOf,56 cspOf,57 formOf,58 origin,59 port,60 tokenRequest,61} from "./oauth.fixtures.ts";6263const alicePassword = "correct horse battery";
498 unmodified lines
562563 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 );572573 it.live(
42 unmodified lines
616617 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 );628629 it.live(
33 unmodified lines
663 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 );676677 it.live(
92 unmodified lines
770 });771772const isPickHandle = (page: Page) => page.html.includes("Set up your profile");773774const 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);782783describe("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();789790 const first = yield* continueWithGoogle(world);791792 const second = yield* continueWithGoogle(world);793794 const [firstCookie, secondCookie] = yield* Effect.forEach(795 [first, second],796 (started) => Effect.map(challengeIn(started), googleCookieName)797 );798799 const firstBack = yield* backFromGoogle(world, first, { sub: "1042" });800801 const kept = [firstCookie, secondCookie].map((name) =>802 Option.isSome(world.browser.cookie(name ?? ""))803 );804805 const secondBack = yield* backFromGoogle(world, second, {806 sub: "2077",807 });808809 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 );822823 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();828829 const started = yield* continueWithGoogle(world);830831 const name = googleCookieName(yield* challengeIn(started));832833 const line =834 started.headers835 .getSetCookie()836 .find((each) => each.startsWith(`${name}=`)) ?? "";837838 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});849850describe("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 lines
941 {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 lines
modified:apps/platform/test/mcp.test.ts+105 added-3 removed
2 unmodified lines
3import { readManaged } from "@repo/agent-kit/generated-file";4import { platformSkill } from "@repo/agent-kit/platform";5import { Brand } from "@repo/brand";6import { CheckAt } from "@repo/checks/check-runner";7import { Contracts, EnvSchemaOf, Surfaces } from "@repo/protocol/contracts";7import {8 Contracts,9 EnvSchemaOf,10 Surfaces,11 surfacedToAnyone,12} from "@repo/protocol/contracts";13import type { Contract, ContractOn } from "@repo/protocol/contracts";14import { Ask, AskListing } from "@repo/protocol/domain/ask";15import { CheckSpec } from "@repo/protocol/domain/check";16import { ProjectListing } from "@repo/protocol/domain/front-page";
142 unmodified lines
159 ["resources/read", "uri"],160 ["tools/call", "name"],161]);162158const mcpRequest = (163const mcpRequestAt = (164 path: string,165 method: string,166 params: Readonly<Record<string, Schema.Json>>,167 token?: string168) => {
14 unmodified lines
183 if (token !== undefined) {184 headers.set("authorization", `Bearer ${token}`);185 }186181 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 lines
195 method: "POST",196 });197};198199const mcpRequest = (200 method: string,201 params: Readonly<Record<string, Schema.Json>>,202 token?: string203) => mcpRequestAt("/mcp", method, params, token);204205const ToolNames = Schema.Struct({206 tools: Schema.Array(Schema.Struct({ name: Schema.String })),207});208209const Reply = Schema.fromJsonString(210 Schema.Struct({211 error: Schema.optionalKey(Schema.Struct({ message: Schema.String })),212 result: Schema.optionalKey(Schema.Unknown),
487 unmodified lines
700 expect(statuses).toStrictEqual([401, 401, 401]);701 })702 );703704 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;709710 const response = yield* fetch(711 mcpRequestAt("/mcp/public", "tools/list", {})712 );713714 const { tools } = yield* replyOf(response).pipe(715 Effect.flatMap(({ result }) =>716 Schema.decodeUnknownEffect(ToolNames)(result)717 )718 );719720 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 );730731 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;736737 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 );749750 const { result } = yield* replyOf(response);751752 const answered =753 yield* Schema.decodeUnknownEffect(Answered)(result);754755 return [response.status, answered.isError];756 })757 );758759 expect(asked).toStrictEqual([760 [200, false],761 [200, false],762 ]);763 })764 );765766 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;771772 const response = yield* fetch(773 mcpRequestAt("/mcp/public", "tools/call", {774 arguments: { ask: fixWeek, project },775 name: "claim",776 })777 );778779 const { error, result } = yield* replyOf(response);780781 expect(782 error !== undefined ||783 Schema.is(Schema.Struct({ isError: Schema.Literal(true) }))(784 result785 )786 ).toBeTruthy();787 })788 );789790 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 lines
modified:apps/platform/test/oauth.fixtures.ts+67 added-18 removed
10 unmodified lines
11import { MailerMemory } from "../src/auth/mailer/memory.ts";12import { OAuthStore } from "../src/auth/oauth-store.ts";13import { OAuthStoreMemory } from "../src/auth/oauth-store/memory.ts";14import { oauthProvider, signInSettings } from "../src/auth/provider.ts";15import { csrfCookieName } from "../src/auth/sign-in.ts";16import { decodeEnv } from "../src/platform.ts";17import { fakeEnv } from "./fake-env.ts";1819export const origin = "https://platform.test";
9 unmodified lines
29export const redirectUri = `http://127.0.0.1:${port}/callback`;3031export const namedPerson = "carol";3232const 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.34export const webOrigin = "https://web.test";3536export const webClient = `${webOrigin}/auth/client`;3738export const webCallback = `${webOrigin}/auth/callback`;3940const worldEnv = (web: boolean) => {41 const env = {42 ...fakeEnv(),43 SESSION_TOKENS: JSON.stringify({44 "carol-token-0123456789abcdef01234567": namedPerson,45 }),46 };4748 return web ? { ...env, PUBLIC_WEB_URL: webOrigin } : env;49};5051const 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 });6061const context = untouchable<ExecutionContext>("ExecutionContext");6263const platformFetch = (request: Request) =>64 Promise.resolve(
3 unmodified lines
68const decodeTokenRecord = Schema.decodeUnknownEffect(69 Schema.Record(Schema.String, Schema.Unknown)70);7150export const signInWorld = (options: { readonly mailFails?: boolean } = {}) =>72export 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 );7980 const accounts = yield* Effect.provide(81 Effect.service(Accounts),82 AccountsMemory.layer
24 unmodified lines
107 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);113114 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 lines
170): 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 line
180 csrf: field(html, "csrf"),181 request: field(html, "request"),182 });183184// Each directive's sources, by name: a source counts only under the directive it was written in.185export 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 );193194export 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 );200161export const authorizeUrl = (state = "state-1", redirect = redirectUri) => {201export const authorizeUrl = (202 state = "state-1",203 redirect = redirectUri,204 client = cliClient205) => {206 const url = new URL("/authorize", origin);207208 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 lines
229 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 });238195export const tokenRequest = (code: string, codeVerifier = verifier) =>239export 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 lines
12import type { Account } from "../src/auth/accounts.ts";13import { AccountsMemory } from "../src/auth/accounts/memory.ts";14import { SignInAttempts } from "../src/auth/attempts.ts";15import { SignInAttemptsMemory } from "../src/auth/attempts/memory.ts";16import { cliClientMetadata } from "../src/auth/cli-client.ts";16import { CLI_CODE_PATH, cliClientMetadata } from "../src/auth/cli-client.ts";17import { codeMatches, codeTag, deadTag, freshCode } from "../src/auth/codes.ts";18import type { CodePurpose } from "../src/auth/codes.ts";19import { ACCOUNT_PATHS, SESSION_PATHS } from "../src/auth/pages.ts";20import {
3 unmodified lines
24 verifyPassword,25} from "../src/auth/password.ts";26import { sessionAccount, withSession } from "../src/auth/platform-session.ts";27import { tokenReader } from "../src/auth/provider.ts";28import { csrfCookieName } from "../src/auth/sign-in.ts";29import { openState, sealState, SignInFailed } from "../src/auth/state.ts";30import type { PendingSignIn } from "../src/auth/state.ts";31import worker from "../src/worker.ts";32import {
4 unmodified lines
37import {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";54import type { World } from "./oauth.fixtures.ts";5556const pepper = Redacted.make(passwordPepper);
145 unmodified lines
202 );203});204205describe("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 lines
475 });476477const alicePassword = "correct horse battery";478469const 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.480const lockedDown = (formAction: readonly string[]) => ({481 "default-src": ["'none'"],482 "form-action": ["'self'", ...formAction],483 "frame-ancestors": ["'none'"],484 "style-src": ["'unsafe-inline'"],485});486487describe("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 lines
542543 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 lines
606 )607 )608 .pipe(Effect.flatMap(read));609595 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 lines
1607 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 lines
1637 password: page.html.includes('name="password"'),1638 status: page.response.status,1639});16401641// A code given back to `redirect`, wherever that is.1642const 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);16521653const 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 );16631664 return yield* Effect.promise(() => response.json()).pipe(1665 Effect.flatMap(Schema.decodeUnknownEffect(TokenResponse)),1666 Effect.map(({ access_token }) => access_token),1667 Effect.orDie1668 );1669 });16701671// A password sign-in for `client`, from a page opened in a browser that holds `jar` as well.1672const 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 );16961697// The sign-in cookies an answer clears, by name.1698const 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("=")));17071708describe("a CLI sign-in by pasted code", () => {1709 const codePage = `${origin}${CLI_CODE_PATH}`;17101711 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();17161717 yield* signUp(world, "alice", alicePassword);17181719 const page = yield* world1720 .fetch(new Request(authorizeUrl("state-1", codePage)))1721 .pipe(Effect.flatMap(read));17221723 const form = yield* formIn(page);17241725 const signedIn = yield* signInWithJar(world, form, [form.cookie]);17261727 const code = yield* codeAt(signedIn, codePage);17281729 const shown = yield* world1730 .fetch(new Request(signedIn.headers.get("location") ?? ""))1731 .pipe(Effect.flatMap(read));17321733 const token = yield* tokenAt(world, code, cliClient, codePage);17341735 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("&", "&amp;")}</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 );17561757 it.live("gives no token for a shown code without the CLI's verifier", () =>1758 Effect.gen(function* () {1759 const world = yield* signInWorld();17601761 yield* signUp(world, "alice", alicePassword);17621763 const form = yield* formIn(1764 yield* world1765 .fetch(new Request(authorizeUrl("state-1", codePage)))1766 .pipe(Effect.flatMap(read))1767 );17681769 const code = yield* signInWithJar(world, form, [form.cookie]).pipe(1770 Effect.flatMap((response) => codeAt(response, codePage))1771 );17721773 const response = yield* world.fetch(1774 tokenRequest(1775 code,1776 "another-verifier-0123456789abcdefghijklmnopqrstu",1777 cliClient,1778 codePage1779 )1780 );17811782 expect(response.status).toBe(400);1783 })1784 );17851786 it.live("says there is no code when the sign-in did not finish", () =>1787 Effect.gen(function* () {1788 const world = yield* signInWorld();17891790 const shown = yield* world1791 .fetch(new Request(`${codePage}?error=access_denied&state=state-1`))1792 .pipe(Effect.flatMap(read));17931794 expect([1795 shown.response.status,1796 shown.html.includes("No code to paste"),1797 ]).toStrictEqual([400, true]);1798 })1799 );1800});18011802describe("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();18081809 yield* signUp(world, "alice", alicePassword);18101811 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];18141815 const done = yield* signInWithJar(world, first, jar);1816 const after = yield* signInWithJar(world, second, jar);18171818 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});18331834describe("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 });18401841 yield* signUp(world, "alice", alicePassword);18421843 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));18481849 const form = yield* formIn(page);18501851 const code = yield* signInWithJar(world, form, [form.cookie]).pipe(1852 Effect.flatMap((response) => codeAt(response, webCallback))1853 );18541855 return yield* tokenAt(world, code, webClient, webCallback);1856 })1857 );18581859 const sessions = OAuthSessions(tokenReader(world.store));18601861 expect(1862 yield* Effect.forEach(tokens, (token) =>1863 Effect.map(sessions.verify(token), Option.isSome)1864 )1865 ).toStrictEqual([true, true]);1866 })1867 );18681869 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();18741875 yield* signUp(world, "alice", alicePassword);18761877 const tokens = yield* Effect.forEach(["state-1", "state-2"], (state) =>1878 Effect.gen(function* () {1879 const form = yield* formIn(yield* openSignIn(world, state));18801881 const code = yield* signInWithJar(world, form, [form.cookie]).pipe(1882 Effect.flatMap(codeIn)1883 );18841885 return yield* tokenAt(world, code);1886 })1887 );18881889 const sessions = OAuthSessions(tokenReader(world.store));18901891 expect(1892 yield* Effect.forEach(tokens, (token) =>1893 Effect.map(sessions.verify(token), Option.isSome)1894 )1895 ).toStrictEqual([false, true]);1896 })1897 );1898});18991900describe("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 lines
2307 expect([before, yield* opened()]).toStrictEqual([true, false]);2308 }).pipe(Effect.provide(AccountsMemory.layer))2309 );2310});23112312// 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.2315const mcpEndpoint = `${origin}/mcp`;23162317const TokenOutcome = Schema.Struct({2318 access_token: Schema.optionalKey(Schema.String),2319 error: Schema.optionalKey(Schema.String),2320 refresh_token: Schema.optionalKey(Schema.String),2321});23222323const 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 );23292330const 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 });23362337const 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 });23452346 if (resource !== undefined) {2347 fields.set("resource", resource);2348 }23492350 return toToken(fields);2351};23522353const refresh = (refreshToken: string, resource: string) =>2354 toToken({2355 client_id: cliClient,2356 grant_type: "refresh_token",2357 refresh_token: refreshToken,2358 resource,2359 });23602361const authorizeNaming = (resource?: string) => {2362 const url = authorizeUrl();23632364 if (resource !== undefined) {2365 url.searchParams.set("resource", resource);2366 }23672368 return new Request(url);2369};23702371// Alice's password sign-in, from an authorize request that names `resource` if given.2372const codeNaming = (world: World, resource?: string) =>2373 Effect.gen(function* () {2374 yield* signUp(world, "alice", alicePassword);23752376 const form = yield* world.fetch(authorizeNaming(resource)).pipe(2377 Effect.flatMap(read),2378 Effect.flatMap((page) => formIn(page))2379 );23802381 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 });23962397describe("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();24032404 const code = yield* codeNaming(world, mcpEndpoint);24052406 const { body, status } = yield* world2407 .fetch(tradeCode(code, mcpEndpoint))2408 .pipe(Effect.flatMap(outcomeOf));24092410 expect([2411 status,2412 body.error,2413 body.access_token === undefined,2414 ]).toStrictEqual([200, undefined, false]);2415 })2416 );24172418 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();24232424 const code = yield* codeNaming(world, origin);24252426 const { body, status } = yield* world2427 .fetch(tradeCode(code, mcpEndpoint))2428 .pipe(Effect.flatMap(outcomeOf));24292430 expect([status, body.error]).toStrictEqual([200, undefined]);2431 })2432 );24332434 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();24392440 const code = yield* codeNaming(world);24412442 const traded = yield* world2443 .fetch(tradeCode(code))2444 .pipe(Effect.flatMap(outcomeOf));24452446 const none: readonly number[] = [];24472448 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 );24632464 expect(statuses).toStrictEqual([200, 200, 200]);2465 })2466 );24672468 it.live("still refuses a resource on another origin", () =>2469 Effect.gen(function* () {2470 const world = yield* signInWorld();24712472 const code = yield* codeNaming(world);24732474 const traded = yield* world2475 .fetch(tradeCode(code, "https://elsewhere.test/mcp"))2476 .pipe(Effect.flatMap(outcomeOf));24772478 const asked = yield* world.fetch(2479 authorizeNaming("https://elsewhere.test")2480 );24812482 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
1import { describe, expect, it } from "@effect/vitest";2import { AnswerRuns } from "@repo/project/answer-runs";3import type { AnswerQueue } from "@repo/project/answer-runs";4import { ProjectGenerator } from "@repo/project/generated";5import { RequestId } from "@repo/protocol/ids";5import { keyOf, RequestId } from "@repo/protocol/ids";6import { UnknownProject } from "@repo/protocol/refusal";7import { advanceTo, at } from "@repo/testkit/clock";8import { untouchable } from "@repo/testkit/untouchable";9import { Context, DateTime, Deferred, Effect, Layer, Option } from "effect";9import {10 Context,11 DateTime,12 Deferred,13 Effect,14 Exit,15 Layer,16 Option,17} from "effect";1819import { AnswerRunsWorkflow } from "../src/adapters/answer-runs-workflow.ts";20import type { AnswerWorkflow } from "../src/adapters/answer-runs-workflow.ts";21import { DoBackground } from "../src/adapters/background.ts";
323 unmodified lines
345 ]);346 });347348 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>[] = [];353354 const closes: (readonly [number | undefined, string | undefined])[] =355 [];356357 // 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();361362 builds.push(building);363364 return building;365 },366 id: untouchable<DurableObjectId>("DurableObjectId", {367 name: keyOf(project),368 }),369 storage: untouchable<DurableObjectStorage>("storage"),370 });371372 const socket = untouchable<WebSocket>("WebSocket", {373 close: (code?: number, reason?: string) => {374 closes.push([code, reason]);375 },376 });377378 const object = new Project(state, fakeEnv());379380 const built = yield* Effect.exit(381 Effect.tryPromise(() => Promise.all(builds))382 );383384 // 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);387388 expect({ built: Exit.isFailure(built), closes }).toStrictEqual({389 built: true,390 closes: [[1000, "bye"]],391 });392 })393 );394395 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 lines
modified:apps/platform/test/raw.test.ts+43 added-1 removed
51 unmodified lines
5253 return sha;54 }).pipe(Effect.orDie, Effect.provide(world));5556 // 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));6162 const entries = Option.getOrThrow(63 yield* host.readTree(repo, commit.tree)64 );6566 return [67 commit.tree,68 ...entries.flatMap(({ name, sha }) =>69 name === "README.md" ? [sha] : []70 ),71 ];72 }).pipe(Effect.orDie, Effect.provide(world));7374 const cached = yield* Option.match(reads, {75 onNone: () => Effect.succeed(world),76 onSome: (count) =>77 Effect.map(Layer.build(CodeCacheLive(100)), (cache) => {
24 unmodified lines
102 MemorySessions.layer({})103 )104 );10588 return { fetch, first };106 return { fetch, first, others };107 });108109const platform = platformWith(Option.none());110
97 unmodified lines
208 expect(answers).toStrictEqual(answers.map(() => [404, ""]));209 })210 );211212 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;217218 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 );228229 expect(answers).toStrictEqual([230 [404, "", "nosniff"],231 [404, "", "nosniff"],232 ]);233 })234 );235236 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 lines
modified:apps/platform/test/sandbox-adapters.test.ts+66 added
42 unmodified lines
43 FiberSet,44 Layer,45 Logger,46 Option,47 Predicate,48 Redacted,49 Result,50 Schema,51} from "effect";5253import { CheckRunnerSandbox } from "../src/adapters/check-runner-sandbox.ts";54import type { SandboxBinding } from "../src/adapters/check-runner-sandbox.ts";55import { LanderSandbox } from "../src/adapters/lander-sandbox.ts";56import type { SandboxMethod } from "../src/adapters/sandbox-credentials.ts";5758const project = ProjectName.make("alice/datekit");5960const canonical = RepoName.make("alice__datekit");
677 unmodified lines
738 expect(leaked(JSON.stringify(lines), minted)).toStrictEqual([]);739 })740 );741});742743// 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.745const 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 );768769describe("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[] = [];775776 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 });789790 const exits = yield* Effect.forEach(everyJob(ok), (job) =>791 Effect.exit(job)792 );793794 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 lines
34import type { ProjectNamespace } from "../src/adapters/do-projects.ts";35import { decodeEnv } from "../src/platform.ts";36import { workerPorts } from "../src/ports.ts";37import {38 closeEnd,39 ProjectSockets,40 WATCH_TAG,41 WatchFrame,42 watchHandler,
519 unmodified lines
562 }).pipe(Effect.provide(doWorld))563 );564});565566// Records every `close()`, and refuses a code a close only reports, as workerd does.567const closingSocket = () => {568 const closes: (readonly [number | undefined, string | undefined])[] = [];569570 const socket = untouchable<WebSocket>("WebSocket", {571 close: (code?: number, reason?: string) => {572 closes.push([code, reason]);573574 if (code === 1005 || code === 1006 || code === 1015) {575 throw new DOMException(576 `Invalid WebSocket close code: ${code}.`,577 "InvalidAccessError"578 );579 }580 },581 });582583 return { closes, socket };584};585586describe("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();592593 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 });596597 expect(closes).toStrictEqual([598 [1000, "bye"],599 [4000, ""],600 [1000, ""],601 ]);602 })603 );604605 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();610611 yield* closeEnd(socket, {612 code: 1006,613 reason: "WebSocket disconnected without sending Close frame.",614 wasClean: false,615 });616617 expect(closes).toStrictEqual([]);618 })619 );620});621622const socketPair = (gone: (socket: WebSocket) => void) => {623 const events = new EventTarget<WebSocketEventMap>();624 const held: string[] = [];625 let listening = false;
222 unmodified lines
modified:apps/platform/test/well-known.test.ts+2 added-2 removed
302 unmodified lines
303 );304305describe("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 lines
403 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 lines
modified: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 lines
10# 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.12FROM docker.io/cloudflare/sandbox:1.0.0 AS shim13FROM 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.14FROM docker.io/library/node:24-trixie-slim16FROM docker.io/library/node:26-trixie-slim1718RUN 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 enable2324COPY --from=shim /usr/local/bin/sandbox-shim /usr/local/bin/sandbox-shim25COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
8 unmodified lines
modified:apps/sandbox/src/checker.ts+8 added-3 removed
14 unmodified lines
15import { blocked, check } from "./checker/run.ts";16import { hasGateways, SdkChecker } from "./checker/sdk.ts";17import { answerJob } from "./job.ts";18import type { Job } from "./job.ts";19import { disposed } from "./rpc-result.ts";20import { jobTelemetry } from "./telemetry.ts";2122const DEFAULT_IMAGE = "checker:default";23
81 unmodified lines
105 }),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 the
35 unmodified lines
155 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 lines
modified:apps/sandbox/src/lander.ts+9 added-4 removed
16 unmodified lines
17import type { Box } from "./box.ts";18import { SdkBox } from "./box/sdk.ts";19import { answerJob } from "./job.ts";20import { bundleRules, compose, land, merge } from "./lander/run.ts";21import { passedOn } from "./rpc-result.ts";2223export const landImage = "land";2425// A Lander job names no repo: a repo's name is no id (AGENTS.md principle 7).
118 unmodified lines
144145export 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));150151export 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));156157export 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));162163export 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
1import { Effect, Predicate } from "effect";23/**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 */11export 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;1617 if (Predicate.isFunction(dispose)) {18 dispose.call(result);19 }20 }).pipe(Effect.ignore, Effect.as(result));2122/**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 */29export 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 lines
706707const 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 lines
745746 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 });753754 boxes.push(box);755756 // The Worker's other exports are not the Checker's to touch: only
123 unmodified lines
880 })881 );882883 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 });895896 const wire = yield* encodedWire();897898 yield* Effect.forEach([wire, wire, wire], (each) =>899 Effect.promise(() => runCheck(world.checkers, each))900 );901902 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 );918919 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 lines
modified:apps/sandbox/test/fake-box.ts+5 added-2 removed
217 unmodified lines
218219 return buffer;220};221222export const fakeContainer = ({ running = true } = {}) => {222export 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>();228229 const gateway = (description: string) => {
25 unmodified lines
255 }),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 lines
modified:apps/sandbox/test/lander.test.ts+51 added-1 removed
24 unmodified lines
25} from "effect";2627import { Box } from "../src/box.ts";28import { Lander, landerJobs, runMerge } from "../src/lander.ts";29import type { LanderJobs } from "../src/lander.ts";30import { bundleRules, compose, land, merge } from "../src/lander/run.ts";31import { landScript, mergeScript } from "../src/lander/script.ts";32import {33 bob,
259 unmodified lines
293 territory: ".",294 vouched: true,295});296297// 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.296describe("the Lander's git", () => {299describe("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 lines
1095 url: "https://artifacts.invalid/datekit.git",1096 },1097};10981099const notThisJob = () => Promise.reject(new Error("not this job"));11001101describe("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[] = [];11071108 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 );11171118 // 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 };11341135 const wire = yield* Schema.encodeEffect(MergeWire)(idleMerge);11361137 const passed = yield* Effect.promise(() =>1138 runMerge({ LANDER: { getByName: () => jobs } }, wire)1139 );11401141 expect(passed).toStrictEqual(reply);1142 expect(Predicate.hasProperty(passed, Symbol.dispose)).toBeFalsy();1143 expect(disposals).toStrictEqual(["merge"]);1144 })1145 );11461147 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 lines
modified:apps/sandbox/test/telemetry.test.ts+4 added-1 removed
113 unmodified lines
114 const { spans } = yield* observed(checkJob, checkWire, () =>115 Effect.die(new TypeError(`no file at ${sealedPath}`))116 );117118 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 );124125 it.effect("carries none of its tokens in a line it logs", () =>
41 unmodified lines
added: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 lines
34import { backend } from "#backend";56import { forwarded } from "../../../features/agents/forward.ts";7import { keptPage } from "../../../server/kept-pages.ts";89const { GET, HEAD } = forwarded(backend, env);1011export 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 lines
9 askMarkdownResponse,10 noAskAt,11} from "../../../../features/ask/markdown.ts";12import { serverClient } from "../../../../server/client.ts";13import { keptPage } from "../../../../server/kept-pages.ts";1415export interface AskParams {16 readonly ask: string;17 readonly project: string;
36 unmodified lines
5455export 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
1import { createFileRoute } from "@tanstack/react-router";2import { env } from "cloudflare:workers";34import { serverClient } from "../../../server/client.ts";5import { keptPage } from "../../../server/kept-pages.ts";6import { projectLlmsHandler } from "../../../server/llms.ts";78export 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 lines
5import { signOutHandler } from "../../server/session.ts";67// A development build serves the dev world, which has no platform to sign out of, as in `signin.ts`.8const 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);1112export const Route = createFileRoute("/auth/signout")({13 server: {
6 unmodified lines
modified:apps/web/src/routes/auth/whoami.ts+1 added-1 removed
5 unmodified lines
67export 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 lines
106 "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.";107108const ICON_PATH = "/icons/icon.svg";109110// 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.112export const OG_IMAGE_URL = `https://${Brand.domain}/og.png`;113114// Fonts are fetched without credentials whatever their origin, so the preload says so too,115// or the browser fetches the file twice.116const fontPreload = (href: string) =>117 ({
23 unmodified lines
141 { 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});152153export const Route = createRootRoute({
7 unmodified lines
modified:apps/web/src/routes/llms[.]txt.ts+6 added-3 removed
1import { createFileRoute } from "@tanstack/react-router";2import { env } from "cloudflare:workers";34import { serverClient } from "../server/client.ts";5import { keptPage } from "../server/kept-pages.ts";6import { frontLlmsHandler } from "../server/llms.ts";78export 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.8import { Effect } from "effect";910export const KEPT_NOWHERE = "private, no-store";11
8 unmodified lines
20 .split(",")21 .map((directive) => directive.trim().toLowerCase())22 .filter((directive) => directive !== "");2322const speaksForSomeone = (request: Request) =>24export const speaksForSomeone = (request: Request) =>25 request.headers.has("cookie") || request.headers.has("authorization");2627// A field-naming directive (`private="set-cookie"`) lets the cache store the answer with that field stripped.28const unsafeFor = (cacheControl: string | null) =>
107 unmodified lines
added: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.8import { waitUntil } from "cloudflare:workers";9import { Clock, Effect, Option, Schema } from "effect";1011import { EDGE_STALE_SECONDS, speaksForSomeone } from "./edge-cache.ts";1213/** One answer as it was kept, and the instant, in epoch milliseconds, it was read from the platform. */14export interface KeptPage {15 readonly body: string;16 readonly cacheControl: string;17 readonly contentType: string;18 readonly keptAt: number;19}2021export 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}2728const directivesOf = (cacheControl: string) =>29 cacheControl30 .split(",")31 .map((directive) => directive.trim().toLowerCase())32 .filter((directive) => directive !== "");3334// An answer kept by nobody, or one that forbids serving it stale, is never kept here either.35const NOT_KEPT = new Set([36 "private",37 "no-store",38 "no-cache",39 "must-revalidate",40 "proxy-revalidate",41]);4243const MAX_AGE = "max-age=";4445const MaxAge = Schema.FiniteFromString.check(Schema.isGreaterThan(0));4647const decodeMaxAge = Schema.decodeUnknownOption(MaxAge);4849/** How long the route says its answer is fresh, in seconds; none when it may not be kept. */50const maxAgeOf = (cacheControl: string): Option.Option<number> => {51 const directives = directivesOf(cacheControl);5253 const forbids = directives.some(54 (directive) =>55 NOT_KEPT.has(directive) ||56 directive.startsWith("private=") ||57 directive.startsWith("no-cache=")58 );5960 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};7071// Kept by its path alone, so a query string never makes a second copy.72export const keptKeyOf = (request: Request) => {73 const { origin, pathname } = new URL(request.url);7475 return `${origin}${pathname}`;76};7778const answerOf = ({ body, cacheControl, contentType }: KeptPage) =>79 new Response(body, {80 headers: { "cache-control": cacheControl, "content-type": contentType },81 status: 200,82 });8384const keepable = (response: Response) => {85 const cacheControl = response.headers.get("cache-control");86 const contentType = response.headers.get("content-type");8788 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};9697/**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 */101const 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);109110 if (Option.isNone(kept)) {111 return response;112 }113114 const page: KeptPage = {115 ...kept.value,116 body: yield* Effect.promise(() => response.text()),117 keptAt: yield* Clock.currentTimeMillis,118 };119120 yield* keeper.inBackground(keeper.put(key, page));121122 return answerOf(page);123 });124125const MILLIS = 1000;126127/**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 */132export 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 }142143 const key = keptKeyOf(request);144 const kept = yield* keeper.get(key);145146 if (Option.isNone(kept)) {147 return yield* readAndKeep(keeper, key, render);148 }149150 const page = kept.value;151 const age = (yield* Clock.currentTimeMillis) - page.keptAt;152 const fresh = Option.getOrElse(maxAgeOf(page.cacheControl), () => 0);153154 if (age <= fresh * MILLIS) {155 return answerOf(page);156 }157158 if (age <= (fresh + EDGE_STALE_SECONDS) * MILLIS) {159 yield* keeper.inBackground(160 Effect.asVoid(readAndKeep(keeper, key, render))161 );162163 return answerOf(page);164 }165166 return yield* readAndKeep(keeper, key, render);167 });168169/** A route's handler with its answer kept by `keeper`. */170export 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 );182183const KeptHeaders = Schema.Struct({184 cacheControl: Schema.NonEmptyString,185 contentType: Schema.NonEmptyString,186 keptAt: Schema.FiniteFromString,187});188189const decodeKeptHeaders = Schema.decodeUnknownOption(KeptHeaders);190191const KEPT_AT = "x-kept-at";192193const KEPT_CACHE_CONTROL = "x-kept-cache-control";194195const quietly = (work: Effect.Effect<void>) =>196 Effect.catchCause(work, (cause) =>197 Effect.logWarning("an agent's page was not kept", cause)198 );199200/**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 */205export 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});266267/** Keeps nothing, so every request reads the route: `vite dev`'s, as Workers Cache is off there too. */268export const keepsNothing: PageKeeper = {269 get: () => Effect.succeedNone,270 inBackground: () => Effect.void,271 put: () => Effect.void,272};273274// A cache of its own, so no entry in it is ever the edge's answer to a page.275const AGENT_PAGES = "agent-pages";276277/** The deployed Worker's keeper, a cache of the colo's own; `vite dev` keeps nothing. */278export 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.6import { Brand } from "@repo/brand";7import { Client } from "@repo/protocol/contracts";8import { Handle as HandleSchema } from "@repo/protocol/ids";9import type { Handle } from "@repo/protocol/ids";8import { Data, Effect, Option, Redacted, Schema } from "effect";10import { Clock, Data, Effect, Option, Redacted, Result, Schema } from "effect";11import type { Layer } from "effect";1213// `__Host-` keeps it to this exact origin over HTTPS, so no sibling host on the same `workers.dev` subdomain can set or shadow it.14export const SESSION_COOKIE = "__Host-session";1516export const HANDLE_COOKIE = "__Host-handle";1718export const RENEW_COOKIE = "__Host-renew";1920// As long as the platform's refresh token lasts by default; the platform ends it sooner if it must.21const RENEW_SECONDS = 30 * 24 * 60 * 60;2223// A session is renewed this long before its token lapses, so a page drawn now still has its token when it calls.24const RENEW_MARGIN_SECONDS = 5 * 60;2526const SIGN_IN_COOKIE = "__Host-sign-in";2728const SIGN_IN_SECONDS = 600;29
63 unmodified lines
93 lockedCookie(SESSION_COOKIE, token, maxAgeSeconds);9495export const clearedCookie = () => lockedCookie(SESSION_COOKIE, "", 0);9697// A session the platform no longer takes: its refresh token stays, for the next navigation to renew it with.98export const clearedCookies = () => [99 clearedCookie(),100 lockedCookie(HANDLE_COOKIE, "", 0),101];102103// A session ended: signed out, or its refresh token refused.104const endedCookies = () => [105 ...clearedCookies(),106 lockedCookie(RENEW_COOKIE, "", 0),107];108109const clearedSignIn = () => lockedCookie(SIGN_IN_COOKIE, "", 0);110111export const settingCookies = (112 headers: HeadersInit,
195 unmodified lines
308309const 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});315316type TokenAnswer = typeof TokenAnswer.Type;317318const decodeTokenAnswer = Schema.decodeEffect(319 Schema.fromJsonString(TokenAnswer)320);321302const exchange = (303 env: Env,304 input: {305 readonly code: string;306 readonly origin: string;307 readonly verifier: string;308 }309) =>322const 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 lines
355356 return answer;357 });358359const 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 });374375// `<lapse>.<refresh token>`: the token's lapse in epoch seconds, then the token that renews it.376const Renewal = Schema.Struct({ lapse: Schema.Int, refreshToken: Token });377378type Renewal = typeof Renewal.Type;379380const decodeRenewal = Schema.decodeUnknownOption(Renewal);381382const renewalFrom = (request: Request) =>383 Option.flatMap(cookieValue(request, RENEW_COOKIE), (value) => {384 const at = value.indexOf(".");385386 return at > 0387 ? decodeRenewal({388 lapse: Number(value.slice(0, at)),389 refreshToken: value.slice(at + 1),390 })391 : Option.none();392 });393394/** The cookies an answer from `/token` sets: the session, and the refresh token beside it with its lapse. */395const sessionCookies = (answer: TokenAnswer) =>396 Effect.map(Clock.currentTimeMillis, (now) => {397 const lapse = Math.floor(now / 1000) + answer.expires_in;398399 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 });415416export 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}421422/**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 */428export const renewedSession = (env: Env, request: Request) =>429 Effect.gen(function* () {430 const renewal = renewalFrom(request);431432 if (Option.isNone(renewal)) {433 return Option.none<Renewed>();434 }435436 const now = Math.floor((yield* Clock.currentTimeMillis) / 1000);437438 if (439 Option.isSome(credentialFrom(request)) &&440 renewal.value.lapse - RENEW_MARGIN_SECONDS > now441 ) {442 return Option.none<Renewed>();443 }444445 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);450451 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 }457458 return answer.failure.status === 502459 ? Option.none<Renewed>()460 : Option.some<Renewed>({461 cookies: endedCookies(),462 token: Option.none(),463 });464 });465466/** The request as it goes on after a renewal: its session cookie holds the renewed token, or none. */467export const withRenewedSession = (request: Request, renewed: Renewed) => {468 const headers = new Headers(request.headers);469470 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 );480481 const session = Option.map(482 renewed.token,483 (token) => `${SESSION_COOKIE}=${encodeURIComponent(token)}`484 );485486 headers.set("cookie", [...others, ...Option.toArray(session)].join("; "));487488 return new Request(request, { headers });489};490491export 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 });497498/**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 */503export 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/");518519 const renewed = navigates520 ? yield* renewedSession(env, request)521 : Option.none<Renewed>();522523 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 });541542export const callbackHandler =543 (env: Env, clientFor: (request: Request) => Layer.Layer<Client>) =>544 ({ request }: Handled): Promise<Response> =>545 Effect.runPromise(
30 unmodified lines
576 Effect.catchCause(() => Effect.succeedNone)577 );578579 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 lines
589 );590591/**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 */598export 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 }606607 const env = platform.value;608609 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 });618619 return redirect(620 new URL(PLATFORM_SIGN_OUT, env.PUBLIC_PLATFORM_URL).href,621 endedCookies()622 );623 })624 );625626const whoAnswer = (627 who: { readonly handle?: Handle },
2 unmodified lines
630 Response.json(who, {631 headers: settingCookies({ "cache-control": "no-store" }, cookies),632 });633634const 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 });668669// 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.670export 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 );685686export 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 lines
modified:apps/web/src/server.ts+3 added-1 removed
1import handler from "@tanstack/react-start/server-entry";2import { env } from "cloudflare:workers";34import { addressedEntry } from "./server/addresses.ts";5import { edgeEntry } from "./server/edge-cache.ts";6import { renewingEntry } from "./server/session.ts";76export default edgeEntry(addressedEntry(handler));8export default edgeEntry(renewingEntry(env)(addressedEntry(handler)));
modified:apps/web/test/client-session.test.ts+3 added-1 removed
12 unmodified lines
13 "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 lines
modified:apps/web/test/edge-cache.test.ts+4 added-2 removed
263 unmodified lines
264 expect(kept(response).cacheControl).toBe(KEPT_NOWHERE);265 })266 );267268 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 lines
276 .trim();277278 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 lines
modified:apps/web/test/head.test.ts+9 added-1 removed
1 unmodified line
2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";45import { pageHead } from "../src/features/shared/head.ts";6import { rootHead } from "../src/routes/__root.tsx";6import { OG_IMAGE_URL, rootHead } from "../src/routes/__root.tsx";78const keyOf = (meta: Readonly<Record<string, string>>) =>9 meta.name ?? meta.property ?? (meta.title === undefined ? "" : "title");10
42 unmodified lines
53 expect(metas["og:description"]).toBe(metas.description);54 expect(metas["og:title"]).toBe(Brand.name);55 expect(metas["og:type"]).toBe("website");56 });5758 it("gives every page the card as a large image, at its absolute URL", () => {59 const metas = metasOf(rootHead());6061 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 lines
57 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
1import { describe, expect, it } from "@effect/vitest";2import { Effect, Option, Ref } from "effect";3import { TestClock } from "effect/testing";45import { EDGE_STALE_SECONDS } from "../src/server/edge-cache.ts";6import { keptKeyOf, servedKept } from "../src/server/kept-pages.ts";7import type { KeptPage, PageKeeper } from "../src/server/kept-pages.ts";8import { SESSION_COOKIE } from "../src/server/session.ts";910const WEB_URL = "https://web-test.example.workers.dev";1112const AGENT_PAGE = { "cache-control": "public, max-age=60" } as const;1314const get = (path: string, headers: HeadersInit = {}) =>15 new Request(`${WEB_URL}${path}`, { headers });1617/** A keeper in memory whose background work waits until the test runs it. */18const 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>[]>([]);2122 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 };2930 // 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 );4142 return { keeper, pages, pending, runBackground };43});4445/** The route: each read answers the next version of the page, and is counted. */46const 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 }));6162const bodyOf = (response: Response) => Effect.promise(() => response.text());6364describe("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);7273 const first = yield* bodyOf(yield* served(get("/llms.txt"), render));74 yield* runBackground;75 yield* TestClock.adjust("59 seconds");7677 const second = yield* bodyOf(78 yield* served(get("/llms.txt?again"), render)79 );8081 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 );9495 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);102103 yield* served(get("/oscabriel/datekit/llms.txt"), render);104 yield* runBackground;105 yield* TestClock.adjust("2 minutes");106107 const stale = yield* served(get("/oscabriel/datekit/llms.txt"), render);108109 // 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;112113 yield* runBackground;114115 const after = yield* served(get("/oscabriel/datekit/llms.txt"), render);116117 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 );136137 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);144145 yield* served(get("/llms.txt"), render);146 yield* runBackground;147 yield* TestClock.adjust(`${60 + EDGE_STALE_SECONDS + 1} seconds`);148149 const late = yield* bodyOf(yield* served(get("/llms.txt"), render));150151 expect({ late, reads: yield* Ref.get(reads) }).toStrictEqual({152 late: "version 2",153 reads: 2,154 });155 })156 );157158 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);169170 yield* served(get("/llms.txt"), render);171 yield* runBackground;172173 const asked = yield* bodyOf(174 yield* served(get("/llms.txt", headers), render)175 );176177 yield* runBackground;178179 const keptBeforeSecond = (yield* Ref.get(pages)).size;180181 yield* Ref.set(pages, new Map());182 yield* served(get("/llms.txt", headers), render);183 yield* runBackground;184185 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 );198199 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);219220 const first = yield* served(get("/llms.txt"), render);221 yield* runBackground;222 yield* served(get("/llms.txt"), render);223224 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});232233describe("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 );238239 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 lines
80 "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 lines
modified:apps/web/test/session.test.ts+341 added-35 removed
1import { describe, expect, it } from "@effect/vitest";2import { Handle } from "@repo/protocol/ids";3import { untouchable } from "@repo/testkit/untouchable";4import { Effect, Option, Schema } from "effect";4import { Clock, Effect, Option, Schema } from "effect";5import { createElement } from "react";6import { renderToStaticMarkup } from "react-dom/server";78import { devPeople } from "../src/dev/seed.ts";
8 unmodified lines
17 clientMetadataHandler,18 credentialFrom,19 HANDLE_COOKIE,20 pkce,21 RENEW_COOKIE,22 renewingEntry,23 SESSION_COOKIE,24 sessionCookie,25 signInHandler,26 signOutHandler,
521 unmodified lines
548 })549 );550551 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");556557 const shown = `${yield* textOf(response)}\n${response.headers.get("location") ?? ""}`;558559 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 );568569 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");575576 const renewal = cookiesOf(response).find(577 ({ name }) => name === RENEW_COOKIE578 );579580 const [lapse = "", token] = decodeURIComponent(581 renewal?.value ?? ""582 ).split(".");583584 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 );601602 it.effect(
85 unmodified lines
688 })689 );690});691692const signedOut = (693 platform: Option.Option<Env>,694 cookie = `${SESSION_COOKIE}=tok123`695) =>696 Effect.forEach(["POST", "GET"], (method) =>655const 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 );713664 return [665 response.status,666 response.headers.get("location"),667 expiriesOf(response),668 ];669 });670714describe("sign-out", () => {715 const expired = [716 [SESSION_COOKIE, true],717 [HANDLE_COOKIE, true],718 [RENEW_COOKIE, true],719 ];720721 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 );731732 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 }));737738 const [one] = yield* signedOut(739 Option.some(envWith(platform.fetch)),740 `${SESSION_COOKIE}=tok123; ${RENEW_COOKIE}=1700000000.alice:grant1:refresh-secret`741 );742743 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 );765766 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});775776const 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 lines
842 })843 );844845 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 lines
921 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 );928929 it.effect("is not believed for another session: the platform is asked", () =>
36 unmodified lines
966const decodeDocument = Schema.decodeUnknownEffect(967 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown))968);969970const 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};977978// A renewal cookie whose token lapses `in` seconds from now.979const renewalCookie = (lapsesIn: number) =>980 Effect.map(981 Clock.currentTimeMillis,982 (now) =>983 `${RENEW_COOKIE}=${Math.floor(now / 1000) + lapsesIn}.alice:grant1:refresh-secret`984 );985986const renewingPlatform = (token: () => Response) =>987 recorder((request) =>988 new URL(request.url).pathname === "/token"989 ? token()990 : whoamiReply(INES)(request)991 );992993const 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 );10011002const renewedForm = {1003 client_id: `${WEB_URL}/auth/client`,1004 grant_type: "refresh_token",1005 refresh_token: "alice:grant1:refresh-secret",1006};10071008const 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 });10161017const drawn = (env: Env, request: Request) =>1018 Effect.gen(function* () {1019 const reached: (string | null)[] = [];10201021 const entry = renewingEntry(env)({1022 fetch: (handed: Request) => {1023 reached.push(handed.headers.get("cookie"));10241025 return new Response("page", {1026 headers: { "content-type": "text/html" },1027 });1028 },1029 });10301031 const response = yield* Effect.promise(() => entry.fetch(request));10321033 return { reached, response };1034 });10351036describe("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));10421043 const response = yield* whoami(envWith(platform.fetch), {1044 cookie: yield* renewalCookie(-10),1045 });10461047 const set = cookiesOf(response).filter(1048 ({ attributes }) => !attributes.includes("max-age=0")1049 );10501051 const seen = yield* platform.seen;10521053 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 );10761077 it.live("renews a session whose token lapses within five minutes", () =>1078 Effect.gen(function* () {1079 const platform = renewingPlatform(() => Response.json(RENEWED));10801081 yield* whoami(envWith(platform.fetch), {1082 cookie: `${SESSION_COOKIE}=alice:grant1:tok-old; ${yield* renewalCookie(120)}`,1083 });10841085 expect(asked(yield* platform.seen)[0]).toStrictEqual(renewedForm);1086 })1087 );10881089 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));10941095 const response = yield* whoami(envWith(platform.fetch), {1096 cookie: `${SESSION_COOKIE}=alice:grant1:tok-old; ${yield* renewalCookie(1800)}`,1097 });10981099 expect(asked(yield* platform.seen)).toStrictEqual(["/rpc"]);1100 expect(cookiesOf(response).map(({ name }) => name)).not.toContain(1101 RENEW_COOKIE1102 );1103 })1104 );11051106 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 );11131114 const response = yield* whoami(envWith(platform.fetch), {1115 cookie: yield* renewalCookie(-10),1116 });11171118 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 );11261127 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 );11351136 expect(yield* textOf(response)).toBe("{}");1137 expect(cookiesOf(response).map(({ name }) => name)).not.toContain(1138 RENEW_COOKIE1139 );1140 })1141 );11421143 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));11481149 const { reached, response } = yield* drawn(1150 envWith(platform.fetch),1151 navigation("/inbox", `theme=dark; ${yield* renewalCookie(-10)}`)1152 );11531154 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 );11651166 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);11711172 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);11821183 expect([reached, response.headers.getSetCookie()]).toStrictEqual([1184 [renewal],1185 [],1186 ]);1187 }1188 })1189 );1190});11911192describe("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 lines
1205 );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 lines
modified:apps/web/test/workers-shim.ts+3 added
4 unmodified lines
5export const env: Env = {6 PLATFORM: untouchable<Fetcher>("PLATFORM"),7 PUBLIC_PLATFORM_URL: "http://localhost:8787",8};910// A route module's background work runs to its end in a test only when the test awaits it itself.11export const waitUntil = (_promise: Promise<unknown>): void => undefined;
modified:apps/web/package.json+1 added-1 removed
12 unmodified lines
13 "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 lines
modified:examples/burrow/bun.lock+2 added-2 removed
167 unmodified lines
168 "@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],169170 "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],171172 "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=="],173174 "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="],175176 "ansi-regex": ["ansi-regex@6.4.0", "", {}, "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw=="],
17 unmodified lines
194 "empathic": ["empathic@2.1.0", "", {}, "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw=="],195196 "environment": ["environment@1.1.0", "", {}, "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="],197198 "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=="],199200 "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=="],201202 "fast-string-truncated-width": ["fast-string-truncated-width@3.0.3", "", {}, "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g=="],
120 unmodified lines
modified:packages/agent-kit/src/docs/connect-an-agent.ts+2 added-1 removed
8 unmodified lines
9 "## 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 lines
modified:packages/agent-kit/src/docs/reference.ts+1 added-1 removed
66 unmodified lines
67 );6869export 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 lines
modified:packages/agent-kit/src/docs/run-a-project.ts+2 added-2 removed
100 unmodified lines
101 `${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 lines
modified:packages/agent-kit/src/command-doc.ts+1 added
27 unmodified lines
28 flags: [29 "--url",30 "--profile",31 "--token-stdin",32 "--paste",33 "--no-browser",34 "--no-git-config",35 "--json",36 ],
215 unmodified lines
modified:packages/artifacts/src/repo-host/binding.ts+63 added-11 removed
89 unmodified lines
90 ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)91 )92);9394const attempt = <A>(run: () => Promise<A>) =>94const tried = <A>(run: () => Promise<A>) =>95 Effect.tryPromise({96 catch: (error) => {97 const message = error instanceof Error ? error.message : String(error);98
8 unmodified lines
107 },108 try: run,109 }).pipe(Effect.retry(whileLimited));110111/**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 */118const disposed = <A>(result: A): Effect.Effect<A> =>119 Effect.try(() => {120 const dispose = Predicate.hasProperty(result, Symbol.dispose)121 ? result[Symbol.dispose]122 : undefined;123124 if (Predicate.isFunction(dispose)) {125 dispose.call(result);126 }127 }).pipe(Effect.ignore, Effect.as(result));128129/** A call whose result is data: the handle alone is kept, by `withRepo`. */130const attempt = <A>(run: () => Promise<A>) =>131 tried(run).pipe(Effect.flatMap(disposed));132133const threw =134 (code: Code) =>135 (thrown: Thrown): boolean =>136 Option.contains(thrown.code, code);
93 unmodified lines
230 Schedule.while(({ attempt: asked, input }) => asked <= asksWhileMaking(input))231);232233const 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 lines
363 : Effect.succeed(true)364 )365 );366367/** `readBlob` answers `null` for any other kind, and `readTree` throws for a non-tree. */368const 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 );384385/**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 */390const 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 );404405/** Artifacts throws `INTERNAL_ERROR` for an object that is no tree (workers-types). */406const treeAt = (name: RepoName, repo: ArtifactsRepo, tree: string) =>407 attempt(() => repo.readTree(tree)).pipe(408 Effect.flatMap((found) =>
179 unmodified lines
588 )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 lines
modified:packages/artifacts/src/repo-host/rest.ts+44 added-8 removed
580 unmodified lines
581 )582 )583 );584585 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 );604605 // 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 );627628 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 lines
751 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 lines
modified:packages/artifacts/src/repo-host/smart-http.ts+25 added-4 removed
50 unmodified lines
51// 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.53const MOVED = ["stale ref", "incorrect old value provided", "non-fast-forward"];5455// 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.57const FAILED = "failed to update ref";5859const lockFoundMoved = (ref: RefName, said: string) =>60 said.includes(`cannot lock ref '${ref}': is at `) &&61 said.includes(" but expected ");6263// Artifacts' whole reply to a push it is too busy for: one side-band 364// (fatal) packet and no report.65const BUSY = "artifacts_git_receive_pack_busy";66
244 unmodified lines
311312const isMoved = (reason: string) =>313 MOVED.some((moved) => reason.includes(moved));314307const refusedAsMoved = ({ cause }: GitFailure, ref: RefName) =>308 cause instanceof Errors.GitPushError &&309 isMoved(cause.data.result.refs[ref]?.error ?? "");315const refusedAsMoved = ({ cause }: GitFailure, ref: RefName, said: string) => {316 if (!(cause instanceof Errors.GitPushError)) {317 return false;318 }319320 const reason = cause.data.result.refs[ref]?.error ?? "";321322 return (323 isMoved(reason) || (reason.includes(FAILED) && lockFoundMoved(ref, said))324 );325};326327/**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's
7 unmodified lines
338) =>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 = "";344345 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;355356 return found === expected;
18 unmodified lines
375 })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 lines
modified:packages/artifacts/test/binding.test.ts+296 added-7 removed
15 unmodified lines
16 FiberSet,17 FileSystem,18 Layer,19 Option,20 Predicate,21 Redacted,22 Ref,23} from "effect";24import type { Scope } from "effect";
35 unmodified lines
6061 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);62};6364const pktOf = (payload: Uint8Array) => {65 const length = (payload.length + 4).toString(16).padStart(4, "0");6667 return new Uint8Array([...new TextEncoder().encode(length), ...payload]);68};6970const banded = (channel: number, payload: Uint8Array) =>71 pktOf(new Uint8Array([channel, ...payload]));7273const text = (line: string) => new TextEncoder().encode(line);7475const flush = text("0000");7677/** git 2.47's receive-pack when a ref moved under a push: the reason in a message, the status only "failed". */78const 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 );99100/** What the binding throws for an unexpected read, as workers-types gives it. */101const internalError = () =>102 Object.assign(new Error("An internal error occurred."), {103 code: "INTERNAL_ERROR",104 name: "ArtifactsError",105 numericCode: 10_400,106 });107108const busyReply = () =>109 new Response(fatal("artifacts_git_receive_pack_busy\n"), {110 headers: { "content-type": "application/x-git-receive-pack-result" },111 });
349 unmodified lines
461 })462 )463 );464465 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]);474475 const theirs = yield* client.commit(476 "theirs",477 [["a.txt", "3"]],478 [first]479 );480481 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 );496497 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 );509510 // 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 lines
612 const commit = yield* host.readCommit(repo, CommitSha.make(sha));613614 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 );623624 // 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);634635 const commit = yield* repos636 .readCommit(name, first)637 .pipe(Effect.orDie);638639 const tree = Option.getOrThrow(640 Option.map(commit, (read) => read.tree)641 );642643 const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);644 const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;645646 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));661662 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);670671 return Option.isNone(tree) && Option.isSome(blob)672 ? yield* Effect.die(internalError())673 : tree;674 }),675 }),676 }677 )678 );679680 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);687688 const read = yield* Effect.exit(repos.readCommit(name, first));689690 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});702703describe("tokens and handles the binding takes", () => {704 it.live("leaves no live token on a repo it created, forked or imported", () =>
180 unmodified lines
885 )886 );887});888889// 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.893const disposing = (binding: Artifacts) => {894 const given: string[] = [];895 const disposals: string[] = [];896897 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 }903904 given.push(method);905906 return Object.defineProperty(result, Symbol.dispose, {907 configurable: true,908 enumerable: false,909 value: () => {910 disposals.push(method);911 },912 });913 })914 );915916 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 };944945 return { disposals, given, wrapped };946};947948describe("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);955956 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") });961962 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);968969 const commit = yield* repos970 .readCommit(name, first)971 .pipe(Effect.orDie);972973 const tree = Option.getOrThrow(974 Option.map(commit, (read) => read.tree)975 );976977 const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);978 const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;979980 yield* repos.readBlob(name, blob).pipe(Effect.orDie);981982 const token = yield* repos983 .mintToken(name, "read", Duration.minutes(5))984 .pipe(Effect.orDie);985986 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 );997998 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});10151016describe("git smart HTTP over the Fetch port", () => {1017 const token = Redacted.make("test-token");10181019 it.live(
348 unmodified lines
modified: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 lines
48.impeccable/4950# Agent worktrees Claude Code makes inside the checkout.51.claude/worktrees/5253explainer/
modified:DESIGN.md+2 added
434 unmodified lines
435Square. 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.436437**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.438439**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.440441## Components442443### Top bar444
196 unmodified lines