The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 10:45 UTC
fix(server): keep connection tickets out of request traces (#27904)
maria committed
Oct 31, 2026 at 01:54 UTC
53a986eb49ede57406da9ce9cfd54c7e3a019b58
5 files changed
+138
-7
apps/server/src/config.ts
+8
@@ -192,6 +192,14 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
192
],
193
{ concurrency: "unbounded" },
194
);
195
+ // Logs, traces and the database are written with the process umask; keep them owner-only.
196
+ yield* fs
197
+ .chmod(derivedPaths.stateDir, 0o700)
198
+ .pipe(
199
+ Effect.catch((cause) =>
200
+ Effect.logWarning("Could not restrict state directory permissions.", { cause }),
201
+ ),
202
+ );
203
204
const swept = sweepStalePendingAttachments({
205
attachmentsDir: derivedPaths.attachmentsDir,
apps/server/src/serverLogger.test.ts
+18
@@ -179,6 +179,24 @@ describe("ServerLoggerLive", () => {
179
}),
180
);
181
182
+ it.effect("exports logged request failures without their connection tickets", () =>
183
+ Effect.gen(function* () {
184
+ const { requests } = yield* logInSpanThrough(
185
+ { otlpLogsUrl: "https://collector.example.com/v1/logs" },
186
+ Effect.logError(
187
+ Cause.die(
188
+ new Error("RequestParseError (GET /ws?wsTicket=ticket-secret&dpop=proof-secret)"),
189
+ ),
190
+ ),
191
+ );
192
+
193
+ const body = requests.map((request) => request.body).join("\n");
194
+ assert.include(body, "wsTicket=<redacted>&dpop=<redacted>");
195
+ assert.notInclude(body, "ticket-secret");
196
+ assert.notInclude(body, "proof-secret");
197
+ }),
198
+ );
199
+
200
it.effect("prints a cause passed as a log field instead of collapsing it", () =>
201
Effect.gen(function* () {
202
const output = yield* printThroughConsole({
apps/server/src/serverLogger.ts
+8
-2
@@ -11,9 +11,15 @@ import * as OtlpLogger from "effect/observability/OtlpLogger";
11
12
import * as ServerConfig from "./config.ts";
13
14
+// HTTP errors logged with --log-ws-events carry the request URL and its connection ticket.
15
+const redactingCredentials = <Output>(logger: Logger.Logger<unknown, Output>) =>
16
+ Logger.make<unknown, Output>((options) =>
17
+ logger.log({ ...options, cause: SharedObservability.redactCauseCredentials(options.cause) }),
18
+ );
19
+
20
// consolePretty collapses Cause fields via util.inspect; render them with Cause.pretty like standalone arguments.
21
const consolePretty = (): Logger.Logger<unknown, void> => {
16
- const pretty = Logger.consolePretty();
22
+ const pretty = redactingCredentials(Logger.consolePretty());
23
return Logger.make((options) =>
24
pretty.log({
25
...options,
@@ -56,7 +62,7 @@ export const layer = Effect.gen(function* () {
62
exportInterval: `${logs.exportIntervalMs} millis`,
63
headers: logs.headers,
64
resource: ServerConfig.otlpResource(config, hostName),
59
- });
65
+ }).pipe(Effect.map(redactingCredentials));
66
67
// Logger.layer replaces the whole set; name every logger here.
68
// OTLP includes traced messages as log records, so also using tracerLogger would duplicate in-span exports.
packages/shared/src/observability.test.ts
+67
@@ -367,6 +367,73 @@ describe("observability", () => {
367
),
368
);
369
370
+ it.effect("keeps WebSocket credentials out of trace files and exported spans", () =>
371
+ Effect.scoped(
372
+ Effect.gen(function* () {
373
+ const fileSystem = yield* FileSystem.FileSystem;
374
+ const path = yield* Path.Path;
375
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
376
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
377
+ const sink = yield* makeTraceSink({
378
+ filePath: tracePath,
379
+ maxBytes: 1024 * 1024,
380
+ maxFiles: 2,
381
+ batchWindowMs: 10_000,
382
+ });
383
+ const delegates: Array<Tracer.NativeSpan> = [];
384
+ const tracer = yield* makeLocalFileTracer({
385
+ filePath: tracePath,
386
+ maxBytes: 1024 * 1024,
387
+ maxFiles: 2,
388
+ batchWindowMs: 10_000,
389
+ sink,
390
+ delegate: Tracer.make({
391
+ span: (options) => {
392
+ const span = new Tracer.NativeSpan(options);
393
+ delegates.push(span);
394
+ return span;
395
+ },
396
+ }),
397
+ });
398
+ const url = "/ws?wsTicket=ticket-secret&dpop=proof-secret&clientSurface=web";
399
+
400
+ yield* Effect.annotateCurrentSpan({
401
+ "url.full": `http://127.0.0.1:3773${url}`,
402
+ "url.query": url.slice(4),
403
+ }).pipe(
404
+ Effect.withSpan("GET", { kind: "server" }),
405
+ Effect.provideService(Tracer.Tracer, tracer),
406
+ );
407
+ yield* Effect.die(new Error(`RequestParseError (GET ${url})`)).pipe(
408
+ Effect.tapCause((cause) => Effect.logError(cause)),
409
+ Effect.withSpan("DeviceHubProxy.proxyWebSocket"),
410
+ Effect.provideService(Tracer.Tracer, tracer),
411
+ Effect.provide(Logger.layer([Logger.tracerLogger], { mergeWithExisting: false })),
412
+ Effect.exit,
413
+ );
414
+ yield* sink.close();
415
+
416
+ const written = yield* fileSystem.readFileString(tracePath);
417
+ const exported = delegates.map((span) =>
418
+ JSON.stringify({
419
+ attributes: Object.fromEntries(span.attributes),
420
+ events: span.events.map(([, , attributes]) => attributes),
421
+ exit:
422
+ span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
423
+ ? Cause.pretty(span.status.exit.cause)
424
+ : "",
425
+ }),
426
+ );
427
+ for (const text of [written, ...exported]) {
428
+ assert.notInclude(text, "ticket-secret");
429
+ assert.notInclude(text, "proof-secret");
430
+ }
431
+ assert.include(written, "wsTicket=<redacted>&dpop=<redacted>&clientSurface=web");
432
+ assert.include(exported.join("\n"), "effect.cause");
433
+ }),
434
+ ),
435
+ );
436
+
437
it.effect("drops only the invalid trace record when serialization fails", () =>
438
Effect.scoped(
439
Effect.gen(function* () {
packages/shared/src/observability.ts
+37
-5
@@ -403,6 +403,12 @@ function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
403
};
404
}
405
406
+// WebSocket tickets and their DPoP proofs ride in URL queries and stay valid after the request.
407
+const URL_CREDENTIAL_PARAMS = /(^|[?&"\s])(wsTicket|dpop)=[^&#"\\\s]*/g;
408
+
409
+const redactUrlCredentials = (text: string) =>
410
+ text.replace(URL_CREDENTIAL_PARAMS, "$1$2=<redacted>");
411
+
412
export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
413
const sink = yield* makeAsyncRotatingFileSink({
414
filePath: options.filePath,
@@ -520,7 +526,7 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac
526
filePath: options.filePath,
527
push(record) {
528
try {
523
- const text = `${JSON.stringify(record)}\n`;
529
+ const text = `${redactUrlCredentials(JSON.stringify(record))}\n`;
530
const bytes = Buffer.byteLength(text);
531
if (bytes > options.maxBytes) return;
532
if (bufferBytes + bytes > maxBufferBytes) {
@@ -541,6 +547,24 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac
547
} satisfies TraceSink;
548
});
549
550
+// Effect's HTTP errors, including failed upgrades, put the request URL in their message.
551
+export function redactCauseCredentials(cause: Cause.Cause<unknown>): Cause.Cause<unknown> {
552
+ if (cause.reasons.length === 0 || Cause.hasInterruptsOnly(cause)) {
553
+ return cause;
554
+ }
555
+ const pretty = Cause.pretty(cause);
556
+ const redacted = redactUrlCredentials(pretty);
557
+ return redacted === pretty ? cause : Cause.die(new Error(redacted));
558
+}
559
+
560
+function redactExitCredentials(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {
561
+ if (ExitRuntime.isSuccess(exit)) {
562
+ return exit;
563
+ }
564
+ const cause = redactCauseCredentials(exit.cause);
565
+ return cause === exit.cause ? exit : ExitRuntime.failCause(cause);
566
+}
567
+
568
class LocalFileSpan implements Tracer.Span {
569
readonly _tag = "Span";
570
readonly name: string;
@@ -590,7 +614,7 @@ class LocalFileSpan implements Tracer.Span {
614
endTime,
615
exit: traceExit,
616
};
593
- this.delegate.end(endTime, traceExit);
617
+ this.delegate.end(endTime, redactExitCredentials(traceExit));
618
619
if (this.sampled) {
620
this.push(spanToTraceRecord(this));
@@ -598,12 +622,20 @@ class LocalFileSpan implements Tracer.Span {
622
}
623
624
attribute(key: string, value: unknown): void {
601
- this.attributes.set(key, value);
602
- this.delegate.attribute(key, value);
625
+ const recorded =
626
+ (key === "url.full" || key === "url.query") && typeof value === "string"
627
+ ? redactUrlCredentials(value)
628
+ : value;
629
+ this.attributes.set(key, recorded);
630
+ this.delegate.attribute(key, recorded);
631
}
632
633
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
606
- const nextAttributes = attributes ?? {};
634
+ const cause = attributes?.["effect.cause"];
635
+ const nextAttributes =
636
+ typeof cause === "string"
637
+ ? { ...attributes, "effect.cause": redactUrlCredentials(cause) }
638
+ : (attributes ?? {});
639
this.events.push([name, startTime, nextAttributes]);
640
this.delegate.event(name, startTime, nextAttributes);
641
}