Skip to content

Commit b274a91

Browse files
longtngoclaude
andcommitted
chore(fork): land the improve-code run of 2026-09-06
Thirty-two commits from one improve-code pass, each already gated and squash-merged onto the integration branch. Landed here as one commit. Security and auth: /viewer no longer waives authentication for a request that merely looks local; a browser session is bound to the scheme, host and port it was paired from, so a stolen cookie replayed against another address is rejected; the device address recorded for a proxied request is the client's, not the proxy's. Correctness: an unborn repository reports no head sha instead of the literal "HEAD"; detaching every repository no longer skips the revert drift check; a workspace member the server cannot read is recorded rather than dropped; a standing checkpoint capture failure is reported once instead of once per turn; the model-server stop escalates to SIGKILL instead of waiting forever. Startup and pulls: the automatic project pull runs off the readiness path and is bounded by a startup budget, so a slow remote cannot hold the port; it also skips a checkout that has a thread working in it. Performance: thread activities are indexed by kind (131ms to 0.1ms on the real 1.27M-row database); an environment's presentation no longer notifies when nothing it shows changed. Cleanups and docs: four dead or duplicated code paths removed; the fork invariant registry gained the FORCE_KILL_AFTER entry and lost five stale claims; AGENTS.md's web test command and test-project inventory corrected. Gate: pnpm verify green on this exact tree - fmt:check, typecheck, lint, crew:xref and every test project, 1,181 test files, 0 failures. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 4954faf commit b274a91

75 files changed

Lines changed: 3334 additions & 780 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -127,18 +127,24 @@ These rules override the ones above for this fork only.
127127
zero successes, zero failures. Local `pnpm verify` (and the pre-push hook that now runs it) is
128128
the entire safety net.
129129
- `pnpm test` runs each package's own `test` script **from that package's directory**. For the web
130-
app that is `vp test run --passWithNoTests --project unit`.
130+
app that is `vp test run --passWithNoTests --project unit --project dom`. Run it with both, or
131+
with neither - `--project unit` alone silently skips all 34 `*.dom.test.tsx` files and still
132+
reports a green run, which is exactly how a failing DOM test survived a "passes in isolation"
133+
check on 2026-09-07.
131134
- **Run web tests from `apps/web`, not from the repo root.** A root-level path filter
132135
(`vp test run apps/web/...`) uses the root config, which has no `.wasm?inline` handling, so
133136
`src/terminal/ghostty/runtimeAbi.test.ts` dies in transform. Measured 2026-08-26: 312 files pass,
134137
that one file fails, **0 tests fail**, exit 1 — a red run with nothing actually broken. The same
135-
file passes 9/9 from `apps/web`. Named projects only resolve there too; at the root both
136-
`--project unit` and `--project browser` error with `No projects matched the filter`.
137-
- There is **no `browser` test project and no browser test file**. `apps/web/vite.config.ts`
138-
registers only `unitTestProject`, and no `*.browser.tsx` source file exists — the nine
139-
`__screenshots__/*.browser.tsx` entries are PNG **directories** left by tests that were deleted,
140-
and none of them is tracked in git. An earlier version of this note said those files existed but
141-
ran nowhere; nothing is going uncovered.
138+
file passes 9/9 from `apps/web`. Named projects only resolve there too: at the root even
139+
`--project dom`, which does exist in `apps/web`, errors with
140+
`No projects matched the filter "dom"`. (Verified 2026-09-07 with `dom` rather than a name that
141+
exists nowhere, so it distinguishes "the root cannot resolve named projects" from "that project
142+
is not defined".)
143+
- **`apps/web/vite.config.ts` registers two test projects, `unit` and `dom`** — the `dom` one runs
144+
`src/**/*.dom.test.tsx` under happy-dom with a 120s hook and test timeout.
145+
- There is **no `browser` test project and no browser test file**, and no `*.browser.tsx` source
146+
file exists — the nine `__screenshots__/*.browser.tsx` entries are PNG **directories** left by
147+
tests that were deleted, and none of them is tracked in git. Nothing is going uncovered.
142148

143149
## Pull requests
144150

‎apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,19 @@ describe("snapshotCookieDatabase", () => {
5151
});
5252
const source = path.join(sourceDirectory, "Cookies");
5353
yield* fileSystem.writeFileString(source, "not a sqlite database");
54-
const prefix = `t3code-cookie-failed-${process.pid}-`;
55-
const error = yield* snapshotCookieDatabase(source, prefix).pipe(
54+
// A parent this test owns. Watching the shared system temp directory
55+
// instead would mean reading six figures of unrelated entries, which
56+
// stalls for seconds whenever anything else is writing there, and would
57+
// key the assertion on a pid prefix that the OS recycles.
58+
const snapshotParent = yield* fileSystem.makeTempDirectoryScoped({
59+
prefix: "t3code-cookie-failed-parent-",
60+
});
61+
const error = yield* snapshotCookieDatabase(source, snapshotParent).pipe(
5662
Effect.scoped,
5763
Effect.flip,
5864
);
5965
expect(error._tag).toBe("SqlError");
60-
const temporaryEntries = yield* fileSystem.readDirectory(path.dirname(sourceDirectory));
61-
expect(temporaryEntries.some((entry) => entry.startsWith(prefix))).toBe(false);
66+
expect(yield* fileSystem.readDirectory(snapshotParent)).toEqual([]);
6267
}),
6368
),
6469
);
@@ -76,8 +81,16 @@ describe("snapshotCookieDatabase", () => {
7681
const sql = yield* SqlClient.SqlClient;
7782
yield* sql`CREATE TABLE cookies(name TEXT NOT NULL)`;
7883
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: source })));
79-
const snapshot = yield* snapshotCookieDatabase(source).pipe(Effect.scoped);
84+
const snapshotParent = yield* fileSystem.makeTempDirectoryScoped({
85+
prefix: "t3code-cookie-cleanup-parent-",
86+
});
87+
const snapshot = yield* snapshotCookieDatabase(source, snapshotParent).pipe(Effect.scoped);
88+
// The snapshot really was made under the parent we gave it. Without this
89+
// the cleanup assertions below hold vacuously for a build that ignored
90+
// the parameter and wrote to the shared system temp directory instead.
91+
expect(snapshot.startsWith(`${snapshotParent}${path.sep}`)).toBe(true);
8092
expect(yield* fileSystem.exists(snapshot)).toBe(false);
93+
expect(yield* fileSystem.readDirectory(snapshotParent)).toEqual([]);
8194
}),
8295
),
8396
);

‎apps/desktop/src/preview/BrowserImport/CookieDatabase.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,14 +83,22 @@ export const bareHost = (host: string): string => (host.startsWith(".") ? host.s
8383
* browser's own file for writing.
8484
*
8585
* Scoped: the temporary directory goes away when the caller's scope closes.
86+
*
87+
* `parentDirectory` places the snapshot under a directory the caller owns; it
88+
* defaults to the system temp directory. Callers that want to observe the
89+
* snapshot's cleanup pass one, so they can watch a directory holding only their
90+
* own entries.
8691
*/
8792
export const snapshotCookieDatabase = Effect.fn("CookieDatabase.snapshotCookieDatabase")(function* (
8893
cookiePath: string,
89-
tempPrefix = "t3code-cookie-import-",
94+
parentDirectory?: string,
9095
) {
9196
const fileSystem = yield* FileSystem.FileSystem;
9297
const path = yield* Path.Path;
93-
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: tempPrefix });
98+
const directory = yield* fileSystem.makeTempDirectoryScoped({
99+
prefix: "t3code-cookie-import-",
100+
directory: parentDirectory,
101+
});
94102
const target = path.join(directory, path.basename(cookiePath));
95103
yield* Effect.gen(function* () {
96104
const sql = yield* SqlClient.SqlClient;

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ export interface AuthenticatedSession {
7171
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
7272
readonly proofKeyThumbprint?: string;
7373
readonly expiresAt?: DateTime.DateTime;
74+
/** `Origin` recorded in the session token at mint, when one was sent. */
75+
readonly httpOrigin?: string;
7476
}
7577

7678
const serverAuthInternalErrorContext = {
@@ -354,6 +356,7 @@ export class ServerAuthInvalidCredentialError extends Schema.TaggedErrorClass<Se
354356
{
355357
diagnostic: Schema.optional(Schema.String),
356358
dpopFailureReason: Schema.optionalKey(DpopFailureReason),
359+
originMismatch: Schema.optionalKey(Schema.Boolean),
357360
cause: Schema.optional(Schema.Defect()),
358361
},
359362
) {
@@ -370,8 +373,12 @@ export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
370373
export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
371374
export const serverAuthCredentialReason = (
372375
error: ServerAuthCredentialError,
373-
): "missing_credential" | "invalid_credential" =>
374-
error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
376+
): "missing_credential" | "invalid_credential" | "origin_mismatch" =>
377+
error._tag === "ServerAuthMissingCredentialError"
378+
? "missing_credential"
379+
: error.originMismatch === true
380+
? "origin_mismatch"
381+
: "invalid_credential";
375382

376383
export const serverAuthDpopFailureReason = (
377384
error: ServerAuthCredentialError,
@@ -426,6 +433,7 @@ export class EnvironmentAuth extends Context.Service<
426433
readonly createBrowserSession: (
427434
credential: string,
428435
requestMetadata: AuthClientMetadata,
436+
httpOrigin?: string,
429437
) => Effect.Effect<
430438
{
431439
readonly response: AuthBrowserSessionResult;
@@ -566,6 +574,46 @@ function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string |
566574
return token.length > 0 ? token : null;
567575
}
568576

577+
/**
578+
* The request's `Origin`, or undefined when the caller sent none. Electron and
579+
* every non-browser client fall in the second case; the origin gate fails open
580+
* there by design.
581+
*/
582+
export function readRequestHttpOrigin(
583+
request: HttpServerRequest.HttpServerRequest,
584+
): string | undefined {
585+
const header = request.headers["origin"];
586+
if (typeof header !== "string") return undefined;
587+
const value = header.trim();
588+
return value.length > 0 ? value : undefined;
589+
}
590+
591+
/**
592+
* True unless both sides are present and disagree. Absence on either side is a
593+
* deliberate fail-open: pre-change sessions carry no claim, and non-browser
594+
* callers send no `Origin`.
595+
*/
596+
export function httpOriginMatches(
597+
recorded: string | undefined,
598+
observed: string | undefined,
599+
): boolean {
600+
if (recorded === undefined || observed === undefined) return true;
601+
return recorded === observed;
602+
}
603+
604+
/** Bearer/DPoP only, for the fall-through when a cookie is origin-rejected. */
605+
function selectNonCookieRequestCredential(request: HttpServerRequest.HttpServerRequest) {
606+
const bearerToken = parseBearerToken(request);
607+
if (bearerToken !== null) {
608+
return { token: bearerToken, source: "bearer" } as const;
609+
}
610+
const dpopToken = parseDpopToken(request);
611+
if (dpopToken !== null) {
612+
return { token: dpopToken, source: "dpop" } as const;
613+
}
614+
return undefined;
615+
}
616+
569617
export function selectRequestCredential(
570618
request: HttpServerRequest.HttpServerRequest,
571619
cookieName: string,
@@ -632,6 +680,7 @@ export const make = Effect.gen(function* () {
632680
scopes: session.scopes,
633681
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
634682
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
683+
...(session.httpOrigin ? { httpOrigin: session.httpOrigin } : {}),
635684
})),
636685
mapSessionVerificationErrors,
637686
);
@@ -691,6 +740,55 @@ export const make = Effect.gen(function* () {
691740
if (!credential?.token) {
692741
return Effect.fail(new ServerAuthMissingCredentialError({}));
693742
}
743+
const verified = verifySelectedCredential(request, credential);
744+
// A shortcut, not the guard. Bearer and DPoP sessions never carry a recorded
745+
// origin - only `createBrowserSession` threads one in - so the comparison
746+
// below would pass them anyway. What protects a bearer client is the
747+
// fall-through: a cookie is selected BEFORE bearer is ever looked at, so a
748+
// bearer client that also carries a stale cookie IS a cookie client here,
749+
// and scoping on the source cannot exclude it. Measured: removing this
750+
// return changes no test; removing the fall-through breaks two.
751+
if (credential.source !== "cookie" && credential.source !== "legacy-cookie") {
752+
return verified;
753+
}
754+
// A cookie rides along on any same-site request, so it is the only source
755+
// that can be replayed by a page the user did not open. Compare the origin
756+
// it was minted from against the one this request came from; on a mismatch
757+
// fall through to whatever non-cookie credential the caller also sent, so a
758+
// bearer client is authenticated on the credential it intended rather than
759+
// sunk by a stale cookie it never meant to use.
760+
const observedOrigin = readRequestHttpOrigin(request);
761+
return verified.pipe(
762+
Effect.flatMap((session) => {
763+
if (httpOriginMatches(session.httpOrigin, observedOrigin)) {
764+
return Effect.succeed(session);
765+
}
766+
const fallback = selectNonCookieRequestCredential(request);
767+
if (fallback) {
768+
return verifySelectedCredential(request, fallback);
769+
}
770+
return Effect.logWarning("Rejected a session cookie minted from another origin.").pipe(
771+
Effect.annotateLogs({
772+
recordedOrigin: session.httpOrigin,
773+
observedOrigin,
774+
}),
775+
Effect.andThen(
776+
Effect.fail(
777+
new ServerAuthInvalidCredentialError({
778+
diagnostic: "Session cookie was minted from a different origin.",
779+
originMismatch: true,
780+
}),
781+
),
782+
),
783+
);
784+
}),
785+
);
786+
};
787+
788+
const verifySelectedCredential = (
789+
request: HttpServerRequest.HttpServerRequest,
790+
credential: { readonly token: string; readonly source: string },
791+
): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
694792
const dpopToken = parseDpopToken(request);
695793
return authenticateToken(credential.token).pipe(
696794
Effect.flatMap((session) => {
@@ -775,6 +873,7 @@ export const make = Effect.gen(function* () {
775873
const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = (
776874
credential,
777875
requestMetadata,
876+
httpOrigin,
778877
) =>
779878
bootstrapCredentials.consume(credential).pipe(
780879
Effect.mapError(toBootstrapExchangeError),
@@ -788,6 +887,7 @@ export const make = Effect.gen(function* () {
788887
...requestMetadata,
789888
...(grant.label ? { label: grant.label } : {}),
790889
},
890+
...(httpOrigin ? { httpOrigin } : {}),
791891
})
792892
.pipe(
793893
Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),

‎apps/server/src/auth/SessionStore.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export interface IssuedSession {
4141
readonly expiresAt: DateTime.DateTime;
4242
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
4343
readonly proofKeyThumbprint?: string;
44+
readonly httpOrigin?: string;
4445
}
4546

4647
export interface VerifiedSession {
@@ -52,6 +53,7 @@ export interface VerifiedSession {
5253
readonly subject: string;
5354
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
5455
readonly proofKeyThumbprint?: string;
56+
readonly httpOrigin?: string;
5557
}
5658

5759
export type SessionCredentialChange =
@@ -370,6 +372,8 @@ export class SessionStore extends Context.Service<
370372
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
371373
readonly client?: AuthClientMetadata;
372374
readonly proofKeyThumbprint?: string;
375+
/** Request `Origin` this session was minted from, signed into the token. */
376+
readonly httpOrigin?: string;
373377
/**
374378
* Atomically revoke active sessions with the same subject and method
375379
* before storing this session.
@@ -427,6 +431,7 @@ const SessionClaims = Schema.Struct({
427431
scopes: AuthEnvironmentScopes,
428432
method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
429433
jkt: Schema.optionalKey(Schema.String),
434+
org: Schema.optionalKey(Schema.String),
430435
iat: Schema.Number,
431436
exp: Schema.Number,
432437
});
@@ -637,6 +642,7 @@ export const make = Effect.gen(function* () {
637642
scopes: input?.scopes ?? AuthStandardClientScopes,
638643
method: input?.method ?? "browser-session-cookie",
639644
...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
645+
...(input?.httpOrigin ? { org: input.httpOrigin } : {}),
640646
iat: issuedAt.epochMilliseconds,
641647
exp: expiresAt.epochMilliseconds,
642648
};
@@ -713,6 +719,7 @@ export const make = Effect.gen(function* () {
713719
expiresAt: expiresAt,
714720
scopes: claims.scopes,
715721
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
722+
...(claims.org ? { httpOrigin: claims.org } : {}),
716723
} satisfies IssuedSession;
717724
},
718725
);
@@ -775,6 +782,7 @@ export const make = Effect.gen(function* () {
775782
subject: claims.sub,
776783
scopes: claims.scopes,
777784
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
785+
...(claims.org ? { httpOrigin: claims.org } : {}),
778786
} satisfies VerifiedSession;
779787
},
780788
);

‎apps/server/src/auth/http.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@ export const authHttpApiLayer = HttpApiBuilder.group(
286286
const result = yield* serverAuth.createBrowserSession(
287287
args.payload.credential,
288288
deriveAuthClientMetadata({ request }),
289+
EnvironmentAuth.readRequestHttpOrigin(request),
289290
);
290291
yield* appendSessionCookie(
291292
sessions.cookieName,

‎apps/server/src/auth/utils.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
33
import {
44
deriveAuthClientMetadata,
55
isRemoteReachableHost,
6+
resolveClientIpAddress,
67
resolveSessionCookieName,
78
} from "./utils.ts";
89

@@ -160,3 +161,47 @@ describe("session cookie isolation", () => {
160161
expect(isRemoteReachableHost("192.168.1.50")).toBe(true);
161162
});
162163
});
164+
describe("resolveClientIpAddress", () => {
165+
// The reported case: a co-located proxy makes every remote device look local.
166+
it("reports the forwarded client when the peer is the local proxy", () => {
167+
expect(
168+
resolveClientIpAddress({ socketAddress: "127.0.0.1", forwardedFor: "203.0.113.7" }),
169+
).toBe("203.0.113.7");
170+
});
171+
172+
it("takes the original client from the left of a proxy chain", () => {
173+
expect(
174+
resolveClientIpAddress({
175+
socketAddress: "::1",
176+
forwardedFor: "203.0.113.7, 198.51.100.2, 127.0.0.1",
177+
}),
178+
).toBe("203.0.113.7");
179+
});
180+
181+
// The direction that costs something. The recorded address is shown as the connecting
182+
// device, so a remote client that sets this header must not get to choose what the
183+
// audit screen says about it.
184+
it("ignores the header from a remote peer, which could be forging it", () => {
185+
expect(resolveClientIpAddress({ socketAddress: "203.0.113.7", forwardedFor: "10.0.0.1" })).toBe(
186+
"203.0.113.7",
187+
);
188+
});
189+
190+
it("keeps the loopback peer when no proxy set the header", () => {
191+
expect(resolveClientIpAddress({ socketAddress: "127.0.0.1", forwardedFor: undefined })).toBe(
192+
"127.0.0.1",
193+
);
194+
});
195+
196+
it("keeps the loopback peer when the header is present but empty", () => {
197+
expect(resolveClientIpAddress({ socketAddress: "127.0.0.1", forwardedFor: " , " })).toBe(
198+
"127.0.0.1",
199+
);
200+
});
201+
202+
it("reports nothing when the socket had no address and no proxy spoke for it", () => {
203+
expect(
204+
resolveClientIpAddress({ socketAddress: undefined, forwardedFor: "203.0.113.7" }),
205+
).toBeUndefined();
206+
});
207+
});

0 commit comments

Comments
 (0)