From 6ae5014a2411d2739088819fee8ec558274a894f Mon Sep 17 00:00:00 2001 From: zerone0x <39543393+zerone0x@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:13:54 +0000 Subject: [PATCH 1/6] fix(remote): drop a remote artifact whose name cannot be a file name Drop capture artifacts with an unusable destination before making filesystem calls. Keep the action outcome and attach a local dropped-artifact reason and warning. Record stop retains its generated filename fallback. Fixes #4661 --- .../daemon-artifacts-capture.test.ts | 53 ++++++++++ packages/remote/src/daemon-artifacts.ts | 99 ++++++++++++++----- 2 files changed, 127 insertions(+), 25 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index 9dab58b72a..f062069c60 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -165,3 +165,56 @@ test.for([ await closeLoopbackServer(server); } }); + +test('a remote artifact named with a NUL byte is dropped and the action result is kept', async (t) => { + if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; + const root = mkdtempForTestSync('agent-device-remote-artifact-nul-'); + const cwd = path.join(root, 'cwd'); + fs.mkdirSync(cwd); + const requested: string[] = []; + const server = http.createServer((req, res) => { + requested.push(req.url ?? ''); + res.end('artifact-bytes'); + }); + try { + const port = await listenOnLoopback(server); + const response = await materializeRemoteArtifacts( + { baseUrl: `http://127.0.0.1:${port}`, token: 'secret' }, + { token: 'secret', command: 'snapshot', session: 'capture', positionals: [], meta: { cwd } }, + { + ok: true, + data: { + nodes: 3, + path: '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/daemon/x', + artifacts: [ + { + artifactId: 'nul', + field: 'path', + artifactType: 'screenshot', + path: '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/daemon/x', + fileName: 'shot\0.png', + }, + ], + }, + }, + createTestHostEnvironment(), + path.join(root, 'state'), + ); + expect(response).toEqual({ + ok: true, + data: { + nodes: 3, + path: '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/daemon/x', + artifacts: [], + droppedArtifacts: [{ field: 'path', reason: 'artifact_name_invalid' }], + warnings: [ + 'The remote artifact for "path" was not downloaded: its name cannot be a file name.', + ], + }, + }); + expect(requested).toEqual([]); + expect(fs.readdirSync(cwd)).toEqual([]); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 33bbdfd529..53257d0aac 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -542,6 +542,8 @@ async function downloadResponseArtifacts( const nextData: Record = { ...(data ?? {}) }; const nextArtifacts: DaemonArtifact[] = []; const recording = isRecordStop(req) ? recordingDelivery() : undefined; + const dropped: DroppedArtifact[] = []; + const delivery = { nextData, nextArtifacts, recording, dropped }; for (const artifact of artifacts) { if (isSessionScriptArtifact(artifact)) { await scripts?.publish(artifact, nextData, nextArtifacts); @@ -551,35 +553,60 @@ async function downloadResponseArtifacts( nextArtifacts.push(artifact); continue; } - if (typeof artifact.field !== 'string' || isClientOwnedResponseField(artifact.field)) continue; - const destination = resolveMaterializedArtifactPath(artifact, req, host); - const materializedPath = await downloadRemoteArtifact({ - ...endpoint, - artifactId: artifact.artifactId, - destinationPath: destination.path, - requestScope: req.meta, - // #2246: `test-artifacts` is the one directory-shaped artifact type today — known from the - // response, before any bytes arrive, so cleanup-on-error can be decided up front instead of - // racing the response headers (a directory destination must never be `rm`'d wholesale; see - // `downloadRemoteArtifact`). - isDirectory: recording === undefined && artifact.artifactType === 'test-artifacts', - stagedFile: recording !== undefined, - }); - recording?.add(artifact.field, materializedPath, destination.fallback); - // Directory artifacts download into a caller-owned root, then atomically publish their one - // top-level entry beneath it. Use the path the download actually published rather than the - // root hint sent over the wire; otherwise `artifactsDir` loses its suite invocation segment. - nextData[artifact.field] = materializedPath; - nextArtifacts.push({ - ...artifact, - localPath: materializedPath, - }); + await downloadOneArtifact(endpoint, req, host, artifact, delivery); } nextData.artifacts = nextArtifacts; recording?.report(nextData); + if (dropped.length > 0) discloseDroppedArtifacts(nextData, dropped); return { ok: true, data: nextData }; } +async function downloadOneArtifact( + endpoint: Required, + req: DaemonWireRequest, + host: HostEnvironment, + artifact: DaemonArtifact & { artifactId: string }, + { + nextData, + nextArtifacts, + recording, + dropped, + }: { + nextData: Record; + nextArtifacts: DaemonArtifact[]; + recording: { add(field: string, written: string, fallback: boolean): void } | undefined; + dropped: DroppedArtifact[]; + }, +): Promise { + if (typeof artifact.field !== 'string' || isClientOwnedResponseField(artifact.field)) return; + const destination = resolveMaterializedArtifactPath(artifact, req, host); + if (!destination || destination.path.includes('\0')) { + dropped.push({ field: artifact.field, reason: 'artifact_name_invalid' }); + return; + } + const materializedPath = await downloadRemoteArtifact({ + ...endpoint, + artifactId: artifact.artifactId, + destinationPath: destination.path, + requestScope: req.meta, + // #2246: `test-artifacts` is the one directory-shaped artifact type today — known from the + // response, before any bytes arrive, so cleanup-on-error can be decided up front instead of + // racing the response headers (a directory destination must never be `rm`'d wholesale; see + // `downloadRemoteArtifact`). + isDirectory: recording === undefined && artifact.artifactType === 'test-artifacts', + stagedFile: recording !== undefined, + }); + recording?.add(artifact.field, materializedPath, destination.fallback); + // Directory artifacts download into a caller-owned root, then atomically publish their one + // top-level entry beneath it. Use the path the download actually published rather than the + // root hint sent over the wire; otherwise `artifactsDir` loses its suite invocation segment. + nextData[artifact.field] = materializedPath; + nextArtifacts.push({ + ...artifact, + localPath: materializedPath, + }); +} + const RECORDING_DESTINATION_REASONS = { // A remote recording was saved to the current directory because the request named no destination; // a warning. @@ -648,10 +675,29 @@ function isClientOwnedResponseField(field: string): boolean { field === 'artifacts' || field === 'savedScript' || field === 'scriptDeliveryFailure' || + field === 'droppedArtifacts' || field === 'warnings' ); } +/** A response artifact the client did not download, and why. */ +type DroppedArtifact = { field: string; reason: 'artifact_name_invalid' }; + +/** + * Adds the artifacts this client dropped, and one warning for each, to a response body. The action + * keeps its own outcome; only the dropped artifacts are missing from `artifacts`. + */ +function discloseDroppedArtifacts(data: Record, dropped: DroppedArtifact[]): void { + data.droppedArtifacts = dropped; + data.warnings = [ + ...(Array.isArray(data.warnings) ? data.warnings : []), + ...dropped.map( + ({ field }) => + `The remote artifact for ${JSON.stringify(field)} was not downloaded: its name cannot be a file name.`, + ), + ]; +} + // Only a successfully published version can name a caller's savedScript destination. function withoutScriptFieldOwner( data: DaemonResponseData | undefined, @@ -684,12 +730,13 @@ function isRecordStop(req: DaemonWireRequest): boolean { /** * A path from this request wins. A record stop without one can use only a plain name in cwd. * Trace and perf stop or report can still use an echoed destination from an earlier request. + * A non-string response file name cannot provide a fallback destination. */ function resolveMaterializedArtifactPath( artifact: DaemonArtifact, req: DaemonWireRequest, host: HostEnvironment, -): { path: string; fallback: boolean } { +): { path: string; fallback: boolean } | undefined { const requestedPath = req.meta?.clientArtifactPaths?.[artifact.field]; if (hasNonEmptyString(requestedPath)) return { path: requestedPath, fallback: false }; if (isRecordStop(req)) { @@ -703,7 +750,9 @@ function resolveMaterializedArtifactPath( if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) { return { path: artifact.localPath, fallback: false }; } - const responseName = path.basename(artifact.fileName?.trim() ?? ''); + const rawName: unknown = artifact.fileName ?? ''; + if (typeof rawName !== 'string') return undefined; + const responseName = path.basename(rawName.trim()); const fileName = responseName && responseName !== '.' && responseName !== '..' ? responseName From 889c8487805eac2798fef359961ccfca853393fe Mon Sep 17 00:00:00 2001 From: zerone0x <39543393+zerone0x@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:07:42 +0000 Subject: [PATCH 2/6] chore(gates): track dropped remote artifacts in the wire ledger --- test/wire-compat/ledger.json | 14 ++++++++------ test/wire-compat/surface.ts | 2 ++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 86acdb9c2b..d527bb8bf1 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -155,7 +155,7 @@ "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:f8edfda6b7f3172392f7649ee68edd87ac1f489da57c0c0e5cb57347803bb184", + "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:6ba52a8f4bf87286ec237d07d14c1c064248716facd5f002435bb0ebd0ef0a91", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", @@ -212,7 +212,9 @@ "packages/daemon-contracts/src/daemon-resolution.ts#DAEMON_CAPABILITIES": "sha256:3478986d0e7b0e55e965c087a7b1dfd3cc018abdb372dba256cf90d27e63ed0b", "packages/daemon-contracts/src/daemon-resolution.ts#DaemonCapability": "sha256:2a5acf280a72e3d54c5ad7b52aece3ced37a30e4e721ef106a98e3bbd18ddbc3", "packages/daemon-contracts/src/daemon-resolution.ts#readDaemonCapabilities": "sha256:e410d36be74d307f7e5d8ddae63af5aae77f8eef77951ce9eeb7724f2fefae88", - "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:aa3ea996bdd1329d88570ba87c03026946dd33f34172c0eccd5a6ac3d38e9884", + "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", + "packages/remote/src/daemon-artifacts.ts#downloadOneArtifact": "sha256:dd8726c99d2e5a4c63ad5f66392732d0116496af50251d7d03007d605b29012d", + "packages/remote/src/daemon-artifacts.ts#DroppedArtifact": "sha256:c340f0a9a4b99d0664f8c32ac78b3a054c95e7f171cf3531331f7cdc143e0cfb", "packages/remote/src/session-script-destination.ts#SessionScriptDelivery": "sha256:741fafbb8e2b43e2e967b2f4206f1d60017a636f63e3cde68b6258fd4efefa18", "packages/remote/src/script-version-publisher.ts#publishScriptVersion": "sha256:b37b9391d20f535ca9c0858f92ed37943297c7acbf1fb10f8cad5cd5b53423eb", "packages/remote/src/script-version-publisher.ts#PublishOutcome": "sha256:a4ae6fc3298d3c560719591372edddbfa83ce749f4cf3f3e2ed1d8369313bd2d", @@ -499,8 +501,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", - "digest": "sha256:f8edfda6b7f3172392f7649ee68edd87ac1f489da57c0c0e5cb57347803bb184", - "rationale": "#4518 client-side only. Remote record stop uses a destination from the current request. Without one, it uses one plain file name or a generated name in cwd. Trace and perf retain the existing path rules. The request, headers, and response framing are unchanged." + "digest": "sha256:6ba52a8f4bf87286ec237d07d14c1c064248716facd5f002435bb0ebd0ef0a91", + "rationale": "#4518 and #4661 change client-side destination selection. Remote record stop still uses the current request destination, a plain name, or a generated name in cwd. Other captures can decline a non-string fallback filename locally. Daemons send the same artifact fields with the same framing." }, { "declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES", @@ -644,8 +646,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#downloadResponseArtifacts", - "digest": "sha256:aa3ea996bdd1329d88570ba87c03026946dd33f34172c0eccd5a6ac3d38e9884", - "rationale": "#4518 client-side only. Remote record stop downloads to a current request destination or reports a local cwd fallback after publishing. Released daemons supply the same artifact fields, and chunk downloads use the existing artifact order. The request, headers, and response framing are unchanged." + "digest": "sha256:ba600575e06995bc903c107477b23f7853e920751452a50a9734fab6677326bf", + "rationale": "#4518 and #4661 change client-side delivery. Record stop keeps its request destination and cwd fallback behavior. The client can skip an unusable destination and append a local reason and warning after parsing the daemon response. The daemon protocol still uses the same request fields, headers, and response framing." }, { "declaration": "packages/kernel/src/contracts.ts#DaemonInstallSource", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 9a34bf3c5b..758e0b41da 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -457,6 +457,8 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'fetchRemoteArtifact', 'materializeRemoteArtifacts', 'downloadResponseArtifacts', + 'downloadOneArtifact', + 'DroppedArtifact', 'resolveMaterializedArtifactPath', ), // The client functions and types that write the remote open --save-script request field and From 4b00076463bebad6e8570cc9a64fbee9dba378f8 Mon Sep 17 00:00:00 2001 From: zerone0x <39543393+zerone0x@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:17:37 +0000 Subject: [PATCH 3/6] fix(remote): validate fallback artifact basenames --- .../daemon-artifacts-capture.test.ts | 41 +++++++++++++------ packages/remote/src/daemon-artifacts.ts | 3 +- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index f062069c60..d48e98d43f 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -78,8 +78,8 @@ type MaterializationCase = { positionals?: string[]; registered?: string; localPath: string; - fileName: string; - expected: string; + fileName?: string; + expected?: string; }; test.for([ @@ -98,6 +98,11 @@ test.for([ fileName: '../../x', expected: 'cwd/x', }, + { + name: 'an omitted file name generates a destination in cwd', + command: 'snapshot', + localPath: 'outside/shot.png', + }, { name: 'a close does not authorize an unrelated response artifact destination', command: 'close', @@ -150,7 +155,7 @@ test.for([ artifactType: 'screenshot', path: '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/daemon/x', localPath: inRoot(c.localPath), - fileName: c.fileName, + ...(c.fileName === undefined ? {} : { fileName: c.fileName }), }, ], }, @@ -158,23 +163,33 @@ test.for([ createTestHostEnvironment(), inRoot('state'), ); - expect(response.ok && response.data?.path).toBe(inRoot(c.expected)); - expect(fs.readFileSync(inRoot(c.expected), 'utf8')).toBe('artifact-bytes'); + const saved = response.ok && response.data?.path; + expect(saved).toEqual(c.expected ? inRoot(c.expected) : expect.any(String)); + if (!c.expected) { + expect(path.dirname(String(saved))).toBe(inRoot('cwd')); + expect(path.basename(String(saved))).toMatch(/^path-\d+$/); + } + expect(fs.readFileSync(String(saved), 'utf8')).toBe('artifact-bytes'); expect(fs.existsSync(inRoot('outside'))).toBe(false); } finally { await closeLoopbackServer(server); } }); -test('a remote artifact named with a NUL byte is dropped and the action result is kept', async (t) => { +test.for([ + { name: 'a NUL byte', field: 'path', fileName: 'shot\0.png' }, + { name: 'explicit null', field: 'path', fileName: null as unknown as string }, + { name: 'a drive prefix on the response basename', field: 'path', fileName: 'subdir/C:shot.png' }, + { name: 'a drive prefix on the generated basename', field: 'subdir/c:path', fileName: '' }, +])('a remote artifact with $name is dropped and the action result is kept', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; - const root = mkdtempForTestSync('agent-device-remote-artifact-nul-'); + const root = mkdtempForTestSync('agent-device-remote-artifact-invalid-name-'); const cwd = path.join(root, 'cwd'); fs.mkdirSync(cwd); const requested: string[] = []; const server = http.createServer((req, res) => { requested.push(req.url ?? ''); - res.end('artifact-bytes'); + res.writeHead(404).end(); }); try { const port = await listenOnLoopback(server); @@ -188,11 +203,11 @@ test('a remote artifact named with a NUL byte is dropped and the action result i path: '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/daemon/x', artifacts: [ { - artifactId: 'nul', - field: 'path', + artifactId: 'invalid', + field: c.field, artifactType: 'screenshot', path: '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/daemon/x', - fileName: 'shot\0.png', + fileName: c.fileName, }, ], }, @@ -206,9 +221,9 @@ test('a remote artifact named with a NUL byte is dropped and the action result i nodes: 3, path: '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/daemon/x', artifacts: [], - droppedArtifacts: [{ field: 'path', reason: 'artifact_name_invalid' }], + droppedArtifacts: [{ field: c.field, reason: 'artifact_name_invalid' }], warnings: [ - 'The remote artifact for "path" was not downloaded: its name cannot be a file name.', + `The remote artifact for "${c.field}" was not downloaded: its name cannot be a file name.`, ], }, }); diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 53257d0aac..564ab7f1f5 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -750,13 +750,14 @@ function resolveMaterializedArtifactPath( if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) { return { path: artifact.localPath, fallback: false }; } - const rawName: unknown = artifact.fileName ?? ''; + const { fileName: rawName = '' }: { fileName?: unknown } = artifact; if (typeof rawName !== 'string') return undefined; const responseName = path.basename(rawName.trim()); const fileName = responseName && responseName !== '.' && responseName !== '..' ? responseName : `${path.basename(artifact.field)}-${Date.now()}`; + if (/^[a-z]:/i.test(fileName)) return undefined; return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: false }; } From 975b9ca1b59e89dbdcd39e29fdecbb049d1f23aa Mon Sep 17 00:00:00 2001 From: zerone0x <39543393+zerone0x@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:17:37 +0000 Subject: [PATCH 4/6] chore(gates): record remote fallback validation in the wire ledger --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index d527bb8bf1..2166690039 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -155,7 +155,7 @@ "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:6ba52a8f4bf87286ec237d07d14c1c064248716facd5f002435bb0ebd0ef0a91", + "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:a3945e32095da7e0e3390294c37cf5eb8a0d302608131031b05b2d55af9da0bc", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", @@ -501,8 +501,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", - "digest": "sha256:6ba52a8f4bf87286ec237d07d14c1c064248716facd5f002435bb0ebd0ef0a91", - "rationale": "#4518 and #4661 change client-side destination selection. Remote record stop still uses the current request destination, a plain name, or a generated name in cwd. Other captures can decline a non-string fallback filename locally. Daemons send the same artifact fields with the same framing." + "digest": "sha256:a3945e32095da7e0e3390294c37cf5eb8a0d302608131031b05b2d55af9da0bc", + "rationale": "#4518 and #4661 change client-side destination selection. Remote record stop still uses the current request destination, a plain name, or a generated name in cwd. Other captures can decline an explicit non-string or drive-qualified fallback name locally. Daemons send the same artifact fields with the same framing." }, { "declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES", From a2b60e15a1436afc3b8180e877a965943cb7dca1 Mon Sep 17 00:00:00 2001 From: zerone0x <39543393+zerone0x@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:14:14 +0000 Subject: [PATCH 5/6] fix(remote): preserve host artifact filename rules --- .../daemon-artifacts-capture.test.ts | 109 +++++++++++++----- .../daemon-artifacts-record-download.test.ts | 41 ++++++- packages/remote/src/daemon-artifacts.ts | 22 +++- 3 files changed, 133 insertions(+), 39 deletions(-) diff --git a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts index d48e98d43f..4698ce5a51 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-capture.test.ts @@ -8,6 +8,7 @@ import { listenOnLoopback, mkdtempForTestSync, skipWhenLoopbackUnavailable, + withMockedPlatform, } from '@agent-device/test-kit'; import { materializeRemoteArtifacts, prepareRemoteRequestArtifacts } from '../daemon-artifacts.ts'; @@ -78,17 +79,37 @@ type MaterializationCase = { positionals?: string[]; registered?: string; localPath: string; + field?: string; fileName?: string; expected?: string; + generatedName?: RegExp; }; +const posixNameCases: MaterializationCase[] = [ + { + name: 'POSIX keeps a colon in the response basename', + command: 'snapshot', + localPath: 'outside/shot.png', + fileName: 'C:shot.png', + expected: 'cwd/C:shot.png', + }, + { + name: 'POSIX keeps a colon in the generated basename', + command: 'snapshot', + localPath: 'outside/shot.png', + field: 'subdir/c:path', + fileName: '', + generatedName: /^c:path-\d+$/, + }, +]; + test.for([ { - name: 'a registered destination wins over a response localPath', + name: 'a registered destination wins over a response localPath and invalid name', command: 'screenshot', registered: 'client/shot.png', localPath: 'outside/shot.png', - fileName: 'shot.png', + fileName: 'shot\0.png', expected: 'client/shot.png', }, { @@ -126,10 +147,12 @@ test.for([ fileName: 'cpu.trace', expected: 'client/cpu.trace', }, + ...(process.platform === 'win32' ? [] : posixNameCases), ])('remote artifact materialization: $name', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; const root = mkdtempForTestSync('agent-device-remote-artifact-path-'); const inRoot = (relative: string) => path.join(root, relative); + const field = c.field ?? 'path'; const server = http.createServer((_req, res) => res.end('artifact-bytes')); try { const port = await listenOnLoopback(server); @@ -142,7 +165,7 @@ test.for([ positionals: c.positionals ?? ['stop'], meta: { cwd: inRoot('cwd'), - ...(c.registered ? { clientArtifactPaths: { path: inRoot(c.registered) } } : {}), + ...(c.registered ? { clientArtifactPaths: { [field]: inRoot(c.registered) } } : {}), }, }, { @@ -151,7 +174,7 @@ test.for([ artifacts: [ { artifactId: 'a1', - field: 'path', + field, artifactType: 'screenshot', path: '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/daemon/x', localPath: inRoot(c.localPath), @@ -163,11 +186,11 @@ test.for([ createTestHostEnvironment(), inRoot('state'), ); - const saved = response.ok && response.data?.path; + const saved = response.ok && response.data?.[field]; expect(saved).toEqual(c.expected ? inRoot(c.expected) : expect.any(String)); if (!c.expected) { expect(path.dirname(String(saved))).toBe(inRoot('cwd')); - expect(path.basename(String(saved))).toMatch(/^path-\d+$/); + expect(path.basename(String(saved))).toMatch(c.generatedName ?? /^path-\d+$/); } expect(fs.readFileSync(String(saved), 'utf8')).toBe('artifact-bytes'); expect(fs.existsSync(inRoot('outside'))).toBe(false); @@ -176,11 +199,29 @@ test.for([ } }); -test.for([ +type InvalidNameCase = { + name: string; + field: string; + fileName: string | null; + platform?: NodeJS.Platform; +}; + +test.for([ { name: 'a NUL byte', field: 'path', fileName: 'shot\0.png' }, - { name: 'explicit null', field: 'path', fileName: null as unknown as string }, - { name: 'a drive prefix on the response basename', field: 'path', fileName: 'subdir/C:shot.png' }, - { name: 'a drive prefix on the generated basename', field: 'subdir/c:path', fileName: '' }, + { name: 'a NUL byte in the directory part', field: 'path', fileName: 'bad\0/shot.png' }, + { name: 'explicit null', field: 'path', fileName: null }, + { + name: 'a Windows drive prefix on the response basename', + field: 'path', + fileName: 'subdir/C:shot.png', + platform: 'win32', + }, + { + name: 'a Windows drive prefix on the generated basename', + field: 'subdir/c:path', + fileName: '', + platform: 'win32', + }, ])('a remote artifact with $name is dropped and the action result is kept', async (c, t) => { if (await skipWhenLoopbackUnavailable(t, 'remote artifact download')) return; const root = mkdtempForTestSync('agent-device-remote-artifact-invalid-name-'); @@ -193,27 +234,35 @@ test.for([ }); try { const port = await listenOnLoopback(server); - const response = await materializeRemoteArtifacts( - { baseUrl: `http://127.0.0.1:${port}`, token: 'secret' }, - { token: 'secret', command: 'snapshot', session: 'capture', positionals: [], meta: { cwd } }, - { - ok: true, - data: { - nodes: 3, - path: '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/daemon/x', - artifacts: [ - { - artifactId: 'invalid', - field: c.field, - artifactType: 'screenshot', - path: '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/daemon/x', - fileName: c.fileName, - }, - ], + const response = await withMockedPlatform(c.platform ?? process.platform, () => + materializeRemoteArtifacts( + { baseUrl: `http://127.0.0.1:${port}`, token: 'secret' }, + { + token: 'secret', + command: 'snapshot', + session: 'capture', + positionals: [], + meta: { cwd }, }, - }, - createTestHostEnvironment(), - path.join(root, 'state'), + { + ok: true, + data: { + nodes: 3, + path: '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/daemon/x', + artifacts: [ + { + artifactId: 'invalid', + field: c.field, + artifactType: 'screenshot', + path: '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/daemon/x', + fileName: c.fileName as string, + }, + ], + }, + }, + createTestHostEnvironment(), + path.join(root, 'state'), + ), ); expect(response).toEqual({ ok: true, diff --git a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts index 5bfae0ff0f..f0304edc06 100644 --- a/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts +++ b/packages/remote/src/__tests__/daemon-artifacts-record-download.test.ts @@ -14,20 +14,30 @@ import { materializeRemoteArtifacts } from '../daemon-artifacts.ts'; async function withRecordingServer( t: TestContext, - run: (cwd: string, stop: ReturnType) => Promise, + run: ( + cwd: string, + stop: ReturnType, + artifactRequests: string[], + ) => Promise, ): Promise { if (await skipWhenLoopbackUnavailable(t, 'remote recording download')) return; const root = mkdtempForTestSync('agent-device-record-download-'); const cwd = path.join(root, 'cwd'); fs.mkdirSync(cwd); + const artifactRequests: string[] = []; // Each artifact's bytes are its own id, served as binary so the body is never read as HTML. const server = http.createServer((req, res) => { + artifactRequests.push(req.url ?? ''); res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(path.basename(req.url ?? '')); }); try { const port = await listenOnLoopback(server); - await run(cwd, recordStop(`http://127.0.0.1:${port}`, cwd, path.join(root, 'state'))); + await run( + cwd, + recordStop(`http://127.0.0.1:${port}`, cwd, path.join(root, 'state')), + artifactRequests, + ); } finally { await closeLoopbackServer(server); } @@ -81,7 +91,10 @@ test('record stop ignores the daemon localPath and warns about the cwd download' test('record stop uses the destination named in the current request', async (t) => { await withRecordingServer(t, async (cwd, stop) => { const hostile = path.resolve(cwd, '../hostile.mp4'); - const data = await stop([{ ...video, localPath: hostile }], '../requested.mp4'); + const data = await stop( + [{ ...video, localPath: hostile, fileName: 'clip\0.mp4' }], + '../requested.mp4', + ); const requested = path.resolve(cwd, '../requested.mp4'); expect(fs.existsSync(hostile)).toBe(false); expect(fs.readFileSync(requested, 'utf8')).toBe('video'); @@ -129,6 +142,28 @@ test.for([ }); }); +test.for([ + { field: 'outPath', artifactType: 'screen-recording' }, + { field: 'chunkPath', artifactType: 'screen-recording-chunk' }, + { field: 'telemetryPath', artifactType: 'screen-recording-telemetry' }, +])('unnamed record stop drops a NUL in the $field artifact name', async (artifact, t) => { + await withRecordingServer(t, async (cwd, stop, artifactRequests) => { + const { field } = artifact; + const data = await stop([{ ...video, ...artifact, fileName: 'clip\0.mp4' }]); + expect(data).toMatchObject({ + outPath: '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/daemon/other.mp4', + artifacts: [], + droppedArtifacts: [{ field, reason: 'artifact_name_invalid' }], + warnings: [ + `The remote artifact for "${field}" was not downloaded: its name cannot be a file name.`, + ], + }); + expect(data?.recordingDestinationWarnings).toBeUndefined(); + expect(artifactRequests).toEqual([]); + expect(fs.readdirSync(cwd)).toEqual([]); + }); +}); + test('record stop downloads each chunk and telemetry to cwd', async (t) => { await withRecordingServer(t, async (cwd, stop) => { const data = await stop( diff --git a/packages/remote/src/daemon-artifacts.ts b/packages/remote/src/daemon-artifacts.ts index 564ab7f1f5..ab538a7c3c 100644 --- a/packages/remote/src/daemon-artifacts.ts +++ b/packages/remote/src/daemon-artifacts.ts @@ -730,7 +730,7 @@ function isRecordStop(req: DaemonWireRequest): boolean { /** * A path from this request wins. A record stop without one can use only a plain name in cwd. * Trace and perf stop or report can still use an echoed destination from an earlier request. - * A non-string response file name cannot provide a fallback destination. + * A NUL in a response file name cannot provide a fallback destination. */ function resolveMaterializedArtifactPath( artifact: DaemonArtifact, @@ -744,21 +744,31 @@ function resolveMaterializedArtifactPath( if (hasNonEmptyString(requested)) { return { path: resolveAbsoluteClientPath(requested, req.meta?.cwd, host), fallback: false }; } + if (typeof artifact.fileName === 'string' && artifact.fileName.includes('\0')) return undefined; const fileName = localFileName(artifact.fileName) ?? `recording-${crypto.randomUUID()}`; return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: true }; } if (hasNonEmptyString(artifact.localPath) && finishesEarlierClientCapture(req)) { return { path: artifact.localPath, fallback: false }; } + const fallbackPath = resolveOrdinaryArtifactFallbackPath(artifact, req.meta?.cwd ?? host.cwd); + return fallbackPath ? { path: fallbackPath, fallback: false } : undefined; +} + +function resolveOrdinaryArtifactFallbackPath( + artifact: DaemonArtifact, + cwd: string, +): string | undefined { const { fileName: rawName = '' }: { fileName?: unknown } = artifact; - if (typeof rawName !== 'string') return undefined; - const responseName = path.basename(rawName.trim()); + if (typeof rawName !== 'string' || rawName.includes('\0')) return undefined; + const pathRules = process.platform === 'win32' ? path.win32 : path.posix; + const responseName = pathRules.basename(rawName.trim()); const fileName = responseName && responseName !== '.' && responseName !== '..' ? responseName - : `${path.basename(artifact.field)}-${Date.now()}`; - if (/^[a-z]:/i.test(fileName)) return undefined; - return { path: path.resolve(req.meta?.cwd ?? host.cwd, fileName), fallback: false }; + : `${pathRules.basename(artifact.field)}-${Date.now()}`; + if (pathRules === path.win32 && /^[a-z]:/i.test(fileName)) return undefined; + return pathRules.resolve(cwd, fileName); } function localFileName(value: unknown): string | undefined { From 192b54f64dbc6ad92b89abe156f232a8a33e43ac Mon Sep 17 00:00:00 2001 From: zerone0x <39543393+zerone0x@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:14:14 +0000 Subject: [PATCH 6/6] chore(gates): record revised artifact name validation --- test/wire-compat/ledger.json | 7 ++++--- test/wire-compat/surface.ts | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 2166690039..f23ff55f4c 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -155,7 +155,8 @@ "packages/remote/src/daemon-artifacts.ts#downloadRemoteArtifact": "sha256:3f3b6c01601c54ab2c76c8cb0946de623da4d24ba32254c75ae8a3993f66adcf", "packages/remote/src/daemon-artifacts.ts#isRemoteDaemon": "sha256:0f6a714c5f60ce4e8548d811b516d8b6241eca9f7e5414733732da395b8a00e7", "packages/remote/src/daemon-artifacts.ts#materializeRemoteArtifacts": "sha256:6d9aba219e6fafbdbcef76d30ed99fbb4f61dcc525242a0a76c3dc1bdacd24e2", - "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:a3945e32095da7e0e3390294c37cf5eb8a0d302608131031b05b2d55af9da0bc", + "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", + "packages/remote/src/daemon-artifacts.ts#resolveOrdinaryArtifactFallbackPath": "sha256:e8b1cb5243194e1d4fc7e376979ca5aae3aaf55cfdd33102e1410b2033fb3a4f", "packages/remote/src/remote-request-diagnostics.ts#RemoteDaemonErrorPayload": "sha256:8fbcbcdf4bae7b66a08e465a72593794f36364759f18f1a814cd39dfdb76f309", "packages/remote/src/remote-request-diagnostics.ts#RemoteDiagnosticsEndpoint": "sha256:c1d5fe2fe90c425502cf8b7c87d6606374d6af65b4e9faf942a416f683930bdc", "packages/remote/src/remote-request-diagnostics.ts#buildRemoteRequestDiagnosticsUrl": "sha256:30a1a9bf0df24d3564a616699916a3bb4360c2b4d21c4ad0562fb0c1e738d0a9", @@ -501,8 +502,8 @@ }, { "declaration": "packages/remote/src/daemon-artifacts.ts#resolveMaterializedArtifactPath", - "digest": "sha256:a3945e32095da7e0e3390294c37cf5eb8a0d302608131031b05b2d55af9da0bc", - "rationale": "#4518 and #4661 change client-side destination selection. Remote record stop still uses the current request destination, a plain name, or a generated name in cwd. Other captures can decline an explicit non-string or drive-qualified fallback name locally. Daemons send the same artifact fields with the same framing." + "digest": "sha256:06dc215c06a9d2ea5a3821faf31b297a2e2f63928672c08c637b132beee726be", + "rationale": "#4518 and #4661 change client-side destination selection. Authorized destinations keep precedence. Fallbacks reject NUL names, and ordinary captures reject explicit non-string names and Windows drive-qualified basenames under Windows path rules. Daemons send the same artifact fields with the same framing." }, { "declaration": "packages/daemon/src/server/http/http-server.ts#MAX_HTTP_RPC_BODY_BYTES", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 758e0b41da..902290c7e4 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -460,6 +460,7 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'downloadOneArtifact', 'DroppedArtifact', 'resolveMaterializedArtifactPath', + 'resolveOrdinaryArtifactFallbackPath', ), // The client functions and types that write the remote open --save-script request field and // read the session-script artifact fields (ADR 0016).