Skip to content

Commit 95d7c70

Browse files
Merge branch 'main' into fix/strip-appimage-env-from-terminal
2 parents dbd8834 + 7b8d126 commit 95d7c70

23 files changed

Lines changed: 276 additions & 28 deletions

‎apps/server/src/imageMime.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,63 @@ describe("imageMime", () => {
3232
});
3333
});
3434

35+
it("rejects payload with characters outside the base64 alphabet", () => {
36+
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
37+
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
38+
});
39+
40+
it("rejects structurally malformed base64", () => {
41+
// '=' before the trailing padding position
42+
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
43+
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
44+
// more than two padding characters
45+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
46+
// length not a multiple of 4
47+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
48+
});
49+
50+
it("accepts base64 with one or two trailing padding characters", () => {
51+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
52+
mimeType: "image/png",
53+
base64: "SGVsbA==",
54+
});
55+
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
56+
mimeType: "image/png",
57+
base64: "SGVsbG8h",
58+
});
59+
});
60+
61+
it("rejects empty and whitespace-only payloads", () => {
62+
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
63+
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
64+
});
65+
66+
it("parses a case-insensitive scheme and mime type", () => {
67+
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
68+
mimeType: "image/png",
69+
base64: "SGVsbG8=",
70+
});
71+
});
72+
73+
it("parses a multi-megabyte payload from a deep call stack", () => {
74+
// Regression: matching the payload with a regex borrowed the JS call
75+
// stack, so a ~10 MB image parsed inside fiber execution threw
76+
// "RangeError: Maximum call stack size exceeded".
77+
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
78+
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
79+
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
80+
const findMaxDepth = (depth: number): number => {
81+
try {
82+
return findMaxDepth(depth + 1);
83+
} catch {
84+
return depth;
85+
}
86+
};
87+
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
88+
expect(result?.mimeType).toBe("image/png");
89+
expect(result?.base64.length).toBe(14_000_000);
90+
});
91+
3592
it("does not read inherited keys from mime extension map", () => {
3693
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
3794
});

‎apps/server/src/imageMime.ts‎

Lines changed: 63 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,43 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
2929
".webp",
3030
]);
3131

32+
// Whether `code` is a character the base64 payload may contain, aside from
33+
// the whitespace handled separately below.
34+
function isBase64Char(code: number): boolean {
35+
return (
36+
(code >= 0x61 && code <= 0x7a) || // a-z
37+
(code >= 0x41 && code <= 0x5a) || // A-Z
38+
(code >= 0x30 && code <= 0x39) || // 0-9
39+
code === 0x2b || // +
40+
code === 0x2f || // /
41+
code === 0x3d // =
42+
);
43+
}
44+
45+
function isBase64Whitespace(code: number): boolean {
46+
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
47+
}
48+
49+
// Data URLs carry the full image payload, so this parser must never run a
50+
// regex across the payload: V8's regex engine borrows the JS call stack, and
51+
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
52+
// execution) throws "Maximum call stack size exceeded".
3253
export function parseBase64DataUrl(
3354
dataUrl: string,
3455
): { readonly mimeType: string; readonly base64: string } | null {
35-
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
36-
if (!match) return null;
56+
const trimmed = dataUrl.trim();
57+
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
58+
59+
const commaIndex = trimmed.indexOf(",");
60+
if (commaIndex === -1) return null;
61+
const header = trimmed.slice(5, commaIndex);
62+
if (header.length === 0) return null;
3763

3864
const headerParts: Array<string> = [];
39-
for (const part of (match[1] ?? "").split(";")) {
40-
const trimmed = part.trim();
41-
if (trimmed.length > 0) {
42-
headerParts.push(trimmed);
65+
for (const part of header.split(";")) {
66+
const partTrimmed = part.trim();
67+
if (partTrimmed.length > 0) {
68+
headerParts.push(partTrimmed);
4369
}
4470
}
4571
if (headerParts.length < 2) {
@@ -51,8 +77,37 @@ export function parseBase64DataUrl(
5177
}
5278

5379
const mimeType = headerParts[0]?.toLowerCase();
54-
const base64 = match[2]?.replace(/\s+/g, "");
55-
if (!mimeType || !base64) return null;
80+
if (!mimeType) return null;
81+
82+
const payload = trimmed.slice(commaIndex + 1);
83+
const runs: Array<string> = [];
84+
let runStart = -1;
85+
for (let index = 0; index < payload.length; index += 1) {
86+
const code = payload.charCodeAt(index);
87+
if (isBase64Char(code)) {
88+
if (runStart === -1) runStart = index;
89+
continue;
90+
}
91+
if (!isBase64Whitespace(code)) return null;
92+
if (runStart !== -1) {
93+
runs.push(payload.slice(runStart, index));
94+
runStart = -1;
95+
}
96+
}
97+
if (runStart !== -1) {
98+
runs.push(payload.slice(runStart));
99+
}
100+
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
101+
if (base64.length === 0 || base64.length % 4 !== 0) return null;
102+
const firstPad = base64.indexOf("=");
103+
if (firstPad !== -1) {
104+
// '=' is only valid as one or two trailing padding characters; Node's
105+
// decoder would otherwise silently truncate at the first '='.
106+
if (base64.length - firstPad > 2) return null;
107+
for (let index = firstPad; index < base64.length; index += 1) {
108+
if (base64.charCodeAt(index) !== 0x3d) return null;
109+
}
110+
}
56111

57112
return { mimeType, base64 };
58113
}

‎apps/server/src/keybindings.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,28 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
411411
}).pipe(Effect.provide(makeKeybindingsLayer())),
412412
);
413413

414+
it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () =>
415+
Effect.gen(function* () {
416+
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
417+
yield* writeKeybindingsConfig(keybindingsConfigPath, [
418+
{ key: "mod+r", command: "script.run-tests.run" },
419+
{ key: "mod+alt+r", command: "script.run-tests.run" },
420+
]);
421+
yield* Effect.gen(function* () {
422+
const keybindings = yield* Keybindings.Keybindings;
423+
return yield* keybindings.upsertKeybindingRule({
424+
key: "mod+alt+r",
425+
command: "script.run-tests.run",
426+
replace: { key: "mod+r", command: "script.run-tests.run" },
427+
});
428+
});
429+
430+
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
431+
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
432+
assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
433+
}).pipe(Effect.provide(makeKeybindingsLayer())),
434+
);
435+
414436
it.effect("removes only the targeted custom keybinding", () =>
415437
Effect.gen(function* () {
416438
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;

‎apps/server/src/keybindings.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,9 @@ const make = Effect.gen(function* () {
644644
const nextConfig = [
645645
...customConfig.filter((entry) => {
646646
if (replaceTarget) {
647-
return !isSameKeybindingRule(entry, replaceTarget);
647+
return (
648+
!isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
649+
);
648650
}
649651
return !isSameKeybindingRule(entry, rule);
650652
}),

‎apps/server/src/provider/Drivers/CursorDriver.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
101101
defaultConfig: (): CursorSettings => decodeCursorSettings({}),
102102
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
103103
Effect.gen(function* () {
104+
const crypto = yield* Crypto.Crypto;
104105
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
105106
const fileSystem = yield* FileSystem.FileSystem;
106107
const path = yield* Path.Path;
@@ -133,6 +134,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
133134

134135
const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(
135136
Effect.map(stampIdentity),
137+
Effect.provideService(Crypto.Crypto, crypto),
136138
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
137139
Effect.provideService(FileSystem.FileSystem, fileSystem),
138140
Effect.provideService(Path.Path, path),

‎apps/server/src/provider/Drivers/GrokDriver.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
8484
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
8585
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
8686
Effect.gen(function* () {
87+
const crypto = yield* Crypto.Crypto;
8788
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
8889
const httpClient = yield* HttpClient.HttpClient;
8990
const serverSettings = yield* ServerSettingsService;
@@ -114,6 +115,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
114115

115116
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
116117
Effect.map(stampIdentity),
118+
Effect.provideService(Crypto.Crypto, crypto),
117119
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
118120
);
119121

‎apps/server/src/provider/Layers/CursorAdapter.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
228228
assert.isDefined(delta);
229229
if (delta?.type === "content.delta") {
230230
assert.equal(delta.payload.delta, "hello from mock");
231-
assert.match(String(delta.itemId), /^assistant:mock-session-1:segment:0$/);
231+
assert.match(String(delta.itemId), /^assistant:mock-session-1:runtime:[^:]+:segment:0$/);
232232
}
233233

234234
const assistantCompleted = runtimeEvents.find(
@@ -687,7 +687,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
687687
if (contentDelta?.type === "content.delta") {
688688
assert.equal(String(contentDelta.turnId), String(turn.turnId));
689689
assert.equal(contentDelta.payload.delta, "hello from mock");
690-
assert.equal(String(contentDelta.itemId), "assistant:mock-session-1:segment:0");
690+
assert.match(
691+
String(contentDelta.itemId),
692+
/^assistant:mock-session-1:runtime:[^:]+:segment:0$/,
693+
);
691694
}
692695
});
693696

‎apps/server/src/provider/Layers/CursorAdapter.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,7 @@ export function makeCursorAdapter(
558558
: {}),
559559
...acpNativeLoggers,
560560
}).pipe(
561+
Effect.provideService(Crypto.Crypto, crypto),
561562
Effect.provideService(Scope.Scope, sessionScope),
562563
Effect.mapError(
563564
(cause) =>

‎apps/server/src/provider/Layers/CursorProvider.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as NodeOS from "node:os";
22

33
import * as NodeServices from "@effect/platform-node/NodeServices";
4+
import type * as Crypto from "effect/Crypto";
45
import * as Effect from "effect/Effect";
56
import * as FileSystem from "effect/FileSystem";
67
import * as Path from "effect/Path";
@@ -28,7 +29,7 @@ const runNode = <A, E>(
2829
effect: Effect.Effect<
2930
A,
3031
E,
31-
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
32+
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
3233
>,
3334
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
3435

‎apps/server/src/provider/Layers/CursorProvider.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type {
1111
import { ProviderDriverKind } from "@t3tools/contracts";
1212
import type * as EffectAcpSchema from "effect-acp/schema";
1313
import { causeErrorTag } from "@t3tools/shared/observability";
14+
import * as Crypto from "effect/Crypto";
1415
import * as DateTime from "effect/DateTime";
1516
import * as Effect from "effect/Effect";
1617
import * as Exit from "effect/Exit";
@@ -992,7 +993,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
992993
): Effect.fn.Return<
993994
ServerProviderDraft,
994995
never,
995-
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
996+
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
996997
> {
997998
const checkedAt = DateTime.formatIso(yield* DateTime.now);
998999
const fallbackModels = getCursorFallbackModels(cursorSettings);

0 commit comments

Comments
 (0)