Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions demos/01-cursor-coding-app/server/disposition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// The Content-Disposition for a file the agent made. A header value is bytes, not text: Node's
// setHeader throws ERR_INVALID_CHAR on a raw 报告.md or an emoji in `filename="..."`, so the preview
// and the download answered 500 for exactly the files a non-English agent writes. RFC 6266 is the
// way out, the same shape the HarnessRouter gateway sends: an ASCII stand-in every client can read,
// plus `filename*` with the real name percent-encoded, which every current browser prefers.
// encodeURIComponent leaves ! ' ( ) * ~ alone and RFC 5987 does not allow them unescaped, so those
// are escaped here too.
export function contentDisposition(kind: 'inline' | 'attachment', filename: string): string {
let name = (filename || '').split(/[\\/]/).pop()?.trim() || '';
if (name === '' || name === '.' || name === '..') name = 'download';
// One `_` per character, not per UTF-16 unit, so an emoji leaves one placeholder. Control
// characters are outside the range too, so a line break can never start a header of its own.
let ascii = name.replace(/[^\x20-\x7e]/gu, '_').replace(/["\\]/g, '').slice(0, 120);
if (ascii.replace(/[\s.]/g, '') === '') ascii = 'download';
const star = encodeURIComponent(name).replace(/[!'()*~]/g,
(c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
return `${kind}; filename="${ascii}"; filename*=UTF-8''${star}`;
}
6 changes: 3 additions & 3 deletions demos/01-cursor-coding-app/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express, { type Request, type Response } from 'express';
import { authenticate, DEMO_USERS } from './auth.js';
import { contentDisposition } from './disposition.js';
import { OwnershipStore } from './store.js';
import type { RunRecord } from './types.js';

Expand Down Expand Up @@ -251,7 +252,7 @@ app.get('/api/sessions/:sessionId/files/:fileId/preview', async (req, res) => {
if (!upstream.ok || !upstream.body) return res.status(upstream.status).json({ error: 'Preview unavailable' });
const mediaType = officeTypes.has(found.file.media_type) ? 'application/pdf' : found.file.media_type || 'application/octet-stream';
res.setHeader('Content-Type', mediaType);
res.setHeader('Content-Disposition', `inline; filename="${path.basename(found.file.path).replace(/["\r\n]/g, '_')}"`);
res.setHeader('Content-Disposition', contentDisposition('inline', found.file.path));
const bytes = Buffer.from(await upstream.arrayBuffer());
res.send(bytes);
} catch (error) {
Expand All @@ -265,9 +266,8 @@ app.get('/api/sessions/:sessionId/files/:fileId/download', async (req, res) => {
if (!found) return;
const upstream = await fetch(`${apiBase}/v1/containers/${encodeURIComponent(found.record.sessionId)}/files/${encodeURIComponent(found.file.file_id)}/content`, { headers: upstreamHeaders() });
if (!upstream.ok || !upstream.body) return res.status(upstream.status).json({ error: 'Download unavailable' });
const filename = path.basename(found.file.path).replace(/["\r\n]/g, '_');
res.setHeader('Content-Type', found.file.media_type || 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Disposition', contentDisposition('attachment', found.file.path));
res.send(Buffer.from(await upstream.arrayBuffer()));
} catch (error) {
errorResponse(res, error);
Expand Down
32 changes: 32 additions & 0 deletions demos/01-cursor-coding-app/tests/disposition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import { validateHeaderValue } from 'node:http';
import test from 'node:test';
import { contentDisposition } from '../server/disposition.js';

// validateHeaderValue is the check res.setHeader makes, the one that threw on the raw name.
const cases: [string, string, string][] = [
['notes.txt', 'notes.txt', 'notes.txt'],
['报告.md', '__.md', '%E6%8A%A5%E5%91%8A.md'],
['季度 汇总.xlsx', '__ __.xlsx', '%E5%AD%A3%E5%BA%A6%20%E6%B1%87%E6%80%BB.xlsx'],
['🚀 launch.png', '_ launch.png', '%F0%9F%9A%80%20launch.png'],
['say "hi".txt', 'say hi.txt', 'say%20%22hi%22.txt'],
['café (1).md', 'caf_ (1).md', 'caf%C3%A9%20%281%29.md'],
['a\r\nset-cookie: x=1.txt', 'a__set-cookie: x=1.txt', 'a%0D%0Aset-cookie%3A%20x%3D1.txt'],
['out/deep/report.pdf', 'report.pdf', 'report.pdf'],
['', 'download', 'download'],
];

for (const [name, fallback, star] of cases) {
test(`a file named ${JSON.stringify(name)} gets a header Node will send`, () => {
for (const kind of ['inline', 'attachment'] as const) {
const value = contentDisposition(kind, name);
assert.equal(value, `${kind}; filename="${fallback}"; filename*=UTF-8''${star}`);
assert.doesNotThrow(() => validateHeaderValue('Content-Disposition', value));
}
});
}

test('the header these routes used to send is the one Node refuses', () => {
assert.throws(() => validateHeaderValue('Content-Disposition', 'attachment; filename="报告.md"'),
{ code: 'ERR_INVALID_CHAR' });
});
18 changes: 18 additions & 0 deletions demos/02-lumacare/server/disposition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// The Content-Disposition for a file the agent made. A header value is bytes, not text: Node's
// setHeader throws ERR_INVALID_CHAR on a raw 报告.md or an emoji in `filename="..."`, so the preview
// and the download answered 500 for exactly the files a non-English agent writes. RFC 6266 is the
// way out, the same shape the HarnessRouter gateway sends: an ASCII stand-in every client can read,
// plus `filename*` with the real name percent-encoded, which every current browser prefers.
// encodeURIComponent leaves ! ' ( ) * ~ alone and RFC 5987 does not allow them unescaped, so those
// are escaped here too.
export function contentDisposition(kind: 'inline' | 'attachment', filename: string): string {
let name = (filename || '').split(/[\\/]/).pop()?.trim() || '';
if (name === '' || name === '.' || name === '..') name = 'download';
// One `_` per character, not per UTF-16 unit, so an emoji leaves one placeholder. Control
// characters are outside the range too, so a line break can never start a header of its own.
let ascii = name.replace(/[^\x20-\x7e]/gu, '_').replace(/["\\]/g, '').slice(0, 120);
if (ascii.replace(/[\s.]/g, '') === '') ascii = 'download';
const star = encodeURIComponent(name).replace(/[!'()*~]/g,
(c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
return `${kind}; filename="${ascii}"; filename*=UTF-8''${star}`;
}
6 changes: 3 additions & 3 deletions demos/02-lumacare/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import express, { type Request, type Response } from 'express';
import { authenticate, DEMO_USERS } from './auth.js';
import { contentDisposition } from './disposition.js';
import { OwnershipStore } from './store.js';
import type { RunRecord } from './types.js';

Expand Down Expand Up @@ -297,7 +298,7 @@ app.get('/api/sessions/:sessionId/files/:fileId/preview', async (req, res) => {
if (!upstream.ok || !upstream.body) return res.status(upstream.status).json({ error: 'Preview unavailable' });
const mediaType = officeTypes.has(found.file.media_type) ? 'application/pdf' : found.file.media_type || 'application/octet-stream';
res.setHeader('Content-Type', mediaType);
res.setHeader('Content-Disposition', `inline; filename="${path.basename(found.file.path).replace(/["\r\n]/g, '_')}"`);
res.setHeader('Content-Disposition', contentDisposition('inline', found.file.path));
const bytes = Buffer.from(await upstream.arrayBuffer());
res.send(bytes);
} catch (error) {
Expand All @@ -311,9 +312,8 @@ app.get('/api/sessions/:sessionId/files/:fileId/download', async (req, res) => {
if (!found) return;
const upstream = await fetch(`${apiBase}/v1/containers/${encodeURIComponent(found.record.sessionId)}/files/${encodeURIComponent(found.file.file_id)}/content`, { headers: upstreamHeaders() });
if (!upstream.ok || !upstream.body) return res.status(upstream.status).json({ error: 'Download unavailable' });
const filename = path.basename(found.file.path).replace(/["\r\n]/g, '_');
res.setHeader('Content-Type', found.file.media_type || 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Content-Disposition', contentDisposition('attachment', found.file.path));
res.send(Buffer.from(await upstream.arrayBuffer()));
} catch (error) {
errorResponse(res, error);
Expand Down
32 changes: 32 additions & 0 deletions demos/02-lumacare/tests/disposition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import assert from 'node:assert/strict';
import { validateHeaderValue } from 'node:http';
import test from 'node:test';
import { contentDisposition } from '../server/disposition.js';

// validateHeaderValue is the check res.setHeader makes, the one that threw on the raw name.
const cases: [string, string, string][] = [
['notes.txt', 'notes.txt', 'notes.txt'],
['报告.md', '__.md', '%E6%8A%A5%E5%91%8A.md'],
['季度 汇总.xlsx', '__ __.xlsx', '%E5%AD%A3%E5%BA%A6%20%E6%B1%87%E6%80%BB.xlsx'],
['🚀 launch.png', '_ launch.png', '%F0%9F%9A%80%20launch.png'],
['say "hi".txt', 'say hi.txt', 'say%20%22hi%22.txt'],
['café (1).md', 'caf_ (1).md', 'caf%C3%A9%20%281%29.md'],
['a\r\nset-cookie: x=1.txt', 'a__set-cookie: x=1.txt', 'a%0D%0Aset-cookie%3A%20x%3D1.txt'],
['out/deep/report.pdf', 'report.pdf', 'report.pdf'],
['', 'download', 'download'],
];

for (const [name, fallback, star] of cases) {
test(`a file named ${JSON.stringify(name)} gets a header Node will send`, () => {
for (const kind of ['inline', 'attachment'] as const) {
const value = contentDisposition(kind, name);
assert.equal(value, `${kind}; filename="${fallback}"; filename*=UTF-8''${star}`);
assert.doesNotThrow(() => validateHeaderValue('Content-Disposition', value));
}
});
}

test('the header these routes used to send is the one Node refuses', () => {
assert.throws(() => validateHeaderValue('Content-Disposition', 'attachment; filename="报告.md"'),
{ code: 'ERR_INVALID_CHAR' });
});
Loading