fix: pass paths to PowerShell as Base64, validate files one by one
Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
1 parent
1ed04fe9be
commit
6360c75ff8
3 files changed
+128
-40
No files matched your search
@@ -33,7 +33,7 @@ const IMAGE_APPS = new Set(["claude-code", "codex", "gemini", "opencode"]);
|
||||
* @returns {string}
|
||||
*/
|
||||
export function clipboardScript(outDir, stamp) {
|
||||
const dir = quote(outDir);
|
||||
const dir = decode(outDir);
|
||||
const name = `paste-${String(stamp).replace(/[^\w-]/g, "")}.png`;
|
||||
|
||||
return [
|
||||
@@ -150,11 +150,13 @@ export function parsePickerResult(res) {
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sizeScript(paths) {
|
||||
const list = (Array.isArray(paths) ? paths : []).map(quote).join(", ");
|
||||
const list = (Array.isArray(paths) ? paths : []).map(String).join("\n");
|
||||
return [
|
||||
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
|
||||
"$tab = [char]9",
|
||||
`$paths = @(${list})`,
|
||||
// One path per line (a file name has no newline), as Base64: no byte of
|
||||
// a name is ever part of the script itself.
|
||||
`$paths = @(${decode(list)}.Split([char]10) | Where-Object { $_ -ne '' })`,
|
||||
"foreach ($p in $paths) {",
|
||||
" if (Test-Path -LiteralPath $p -PathType Container) {",
|
||||
' Write-Output ("DIR" + $tab + $p)',
|
||||
@@ -253,7 +255,54 @@ function toBytes(text) {
|
||||
return Number.isFinite(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/** A PowerShell single-quoted string. */
|
||||
function quote(text) {
|
||||
return `'${String(text).replace(/'/g, "''")}'`;
|
||||
/**
|
||||
* PowerShell that yields `text` - without the text itself being in the
|
||||
* script.
|
||||
*
|
||||
* A path or a name comes from the outside, and PowerShell reads more than the
|
||||
* ASCII apostrophe as a quote (U+2018, U+2019, U+201A, U+201B too), so no
|
||||
* quoting is safe enough. The text goes in as Base64 of its UTF-8 bytes - an
|
||||
* alphabet with no quote, no `$`, no space - and is decoded by PowerShell.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string}
|
||||
*/
|
||||
function decode(text) {
|
||||
return `[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64(utf8(text))}'))`;
|
||||
}
|
||||
|
||||
/** The UTF-8 bytes of a text (a lone surrogate becomes U+FFFD). */
|
||||
function utf8(text) {
|
||||
const bytes = [];
|
||||
for (const char of String(text)) {
|
||||
let code = char.codePointAt(0);
|
||||
if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd;
|
||||
if (code < 0x80) {
|
||||
bytes.push(code);
|
||||
} else if (code < 0x800) {
|
||||
bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
|
||||
} else if (code < 0x10000) {
|
||||
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
} else {
|
||||
bytes.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/** Base64 of bytes (no Buffer, no btoa: the mods do not have to have them). */
|
||||
function base64(bytes) {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i += 3) {
|
||||
const a = bytes[i];
|
||||
const b = bytes[i + 1];
|
||||
const c = bytes[i + 2];
|
||||
out += BASE64[a >> 2];
|
||||
out += BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)];
|
||||
out += b === undefined ? "=" : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)];
|
||||
out += c === undefined ? "=" : BASE64[c & 63];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+36
-27
@@ -40,7 +40,7 @@ import { keyIntent } from "./keys.js";
|
||||
import { decide, shouldDrain, shouldStartCountdown, sendNow as sendToTerminal } from "./delivery.js";
|
||||
import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js";
|
||||
import * as catalog from "./catalog.js";
|
||||
import { LIMITS, validate, validateMany, mention, removeMention, kindOf } from "./attachments.js";
|
||||
import { LIMITS, validate, mention, removeMention, kindOf } from "./attachments.js";
|
||||
import {
|
||||
clipboardScript,
|
||||
parseClipboardResult,
|
||||
@@ -1141,24 +1141,24 @@ export default class Composer extends View {
|
||||
this.state = reduce(this.state, { type: "attachment_update", agent: key, id, patch: { state: "adding" } });
|
||||
cx.notify();
|
||||
cx.spawn(async (cx) => {
|
||||
let current = file;
|
||||
if (!Number.isFinite(file.bytes)) {
|
||||
let bytes = file.bytes;
|
||||
if (!Number.isFinite(bytes)) {
|
||||
const measured = (await this.measure([file.path])).files[0];
|
||||
const check = measured && Number.isFinite(measured.bytes) ? validate({ ...file, bytes: measured.bytes }) : null;
|
||||
if (!check || !check.ok) {
|
||||
this.state = reduce(this.state, {
|
||||
type: "attachment_update",
|
||||
agent: key,
|
||||
id,
|
||||
patch: { state: "error", error: check ? check.reason : SIZE_ERROR },
|
||||
});
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
current = { ...file, bytes: measured.bytes };
|
||||
this.state = reduce(this.state, { type: "attachment_update", agent: key, id, patch: { bytes: measured.bytes } });
|
||||
bytes = measured && Number.isFinite(measured.bytes) ? measured.bytes : undefined;
|
||||
}
|
||||
await this.putAttachment(agent, current, cx);
|
||||
const check = bytes === undefined ? null : validate({ ...file, bytes });
|
||||
if (!check || !check.ok) {
|
||||
this.state = reduce(this.state, {
|
||||
type: "attachment_update",
|
||||
agent: key,
|
||||
id,
|
||||
patch: { state: "error", error: check ? check.reason : SIZE_ERROR },
|
||||
});
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
this.state = reduce(this.state, { type: "attachment_update", agent: key, id, patch: { bytes } });
|
||||
await this.putAttachment(agent, { ...file, bytes }, cx);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1353,6 +1353,10 @@ export default class Composer extends View {
|
||||
}
|
||||
if (measured.dirs.length) this.notice(DIR_NOTICE, "error");
|
||||
this.addFiles(measured.files, "drop", cx);
|
||||
// A path that is not there any more is said, not skipped in silence.
|
||||
if (measured.missing.length) {
|
||||
this.notice(`Nie znaleziono pliku: ${measured.missing.map(nameOf).join(", ")}`, "error", cx);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1410,27 +1414,32 @@ export default class Composer extends View {
|
||||
origin,
|
||||
};
|
||||
});
|
||||
const known = files.filter((file) => file.bytes !== undefined);
|
||||
|
||||
const check = validateMany(known);
|
||||
if (!check.ok) {
|
||||
this.notice(check.reason, "error", cx);
|
||||
return;
|
||||
}
|
||||
// The whole batch may be 100 files at most; every file is judged on its
|
||||
// own - a file that is too big does not take the good ones with it.
|
||||
if ((this.state.attachments[key] ?? []).length + files.length > LIMITS.filesPerAction) {
|
||||
this.notice(`Za dużo plików (limit ${LIMITS.filesPerAction})`, "error", cx);
|
||||
return;
|
||||
}
|
||||
|
||||
const known = [];
|
||||
let problem = "";
|
||||
for (const file of files) {
|
||||
const unknown = file.bytes === undefined;
|
||||
let error = "";
|
||||
if (file.bytes === undefined) {
|
||||
error = SIZE_ERROR;
|
||||
} else {
|
||||
const check = validate(file);
|
||||
if (!check.ok) error = check.reason;
|
||||
}
|
||||
if (error) problem = error;
|
||||
else known.push(file);
|
||||
this.state = reduce(this.state, {
|
||||
type: "attach",
|
||||
agent: key,
|
||||
file: unknown ? { ...file, state: "error", error: SIZE_ERROR } : { ...file, state: "adding" },
|
||||
file: error ? { ...file, state: "error", error } : { ...file, state: "adding" },
|
||||
});
|
||||
}
|
||||
if (files.some((file) => file.bytes === undefined)) this.notice(SIZE_ERROR, "error");
|
||||
if (problem) this.notice(problem, "error");
|
||||
this.scheduleDraftSave(cx);
|
||||
cx.notify();
|
||||
|
||||
|
||||
@@ -18,11 +18,29 @@ test("clipboardScript: files first (with sizes, directories apart), then image,
|
||||
assert.ok(s.includes(".Length"));
|
||||
assert.ok(s.includes("IMAGE"));
|
||||
assert.ok(s.includes("NONE"));
|
||||
assert.ok(s.includes("C:\\out dir"));
|
||||
assert.equal(decodedStrings(s).includes("C:\\out dir"), true);
|
||||
});
|
||||
|
||||
test("clipboardScript quotes a path with an apostrophe", () => {
|
||||
assert.ok(clipboardScript("C:\\o'brien", "1").includes("C:\\o''brien"));
|
||||
// What a script carries as Base64 (the only way text from outside gets in).
|
||||
const decodedStrings = (script) =>
|
||||
[...script.matchAll(/FromBase64String\('([A-Za-z0-9+/=]*)'\)/g)].map((m) => Buffer.from(m[1], "base64").toString("utf8"));
|
||||
|
||||
const NASTY = ["C:\\it\u2019s.txt", "C:\\it\u2018s.txt", "C:\\a\u201As\u201Bb.txt", "C:\\o'brien.txt", "C:\\$env:USERNAME.txt", 'C:\\"; Remove-Item x #.txt', "C:\\zażółć gęślą.txt"];
|
||||
|
||||
test("clipboardScript: the folder is Base64, never a literal (any quote, $, or text)", () => {
|
||||
for (const dir of NASTY) {
|
||||
const s = clipboardScript(dir, "1");
|
||||
assert.deepEqual(decodedStrings(s), [dir]);
|
||||
for (const raw of ["\u2019", "\u2018", "\u201A", "\u201B", "$env:USERNAME", "Remove-Item x", "o'brien", "zażółć"]) {
|
||||
if (dir.includes(raw)) assert.equal(s.includes(raw), false, `${raw} in the script`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("clipboardScript: the stamp can only be harmless characters", () => {
|
||||
const s = clipboardScript("C:\o", "1'$(x)'");
|
||||
assert.equal(s.includes("$(x)"), false);
|
||||
assert.ok(s.includes("paste-1x.png"));
|
||||
});
|
||||
|
||||
test("parseClipboardResult: image with its size", () => {
|
||||
@@ -92,10 +110,12 @@ test("parsePickerResult: path and bytes, cancelled -> []", () => {
|
||||
assert.deepEqual(parsePickerResult(null), []);
|
||||
});
|
||||
|
||||
test("sizeScript: one call for the whole batch, paths quoted", () => {
|
||||
const s = sizeScript(["C:\\a b\\it's.txt", "D:\\x.png"]);
|
||||
assert.ok(s.includes("'C:\\a b\\it''s.txt'"));
|
||||
assert.ok(s.includes("'D:\\x.png'"));
|
||||
test("sizeScript: one call for the whole batch, the paths only as Base64", () => {
|
||||
const s = sizeScript(NASTY);
|
||||
assert.deepEqual(decodedStrings(s), [NASTY.join("\n")]);
|
||||
for (const raw of ["\u2019", "\u2018", "\u201A", "\u201B", "$env:USERNAME", "Remove-Item x", "o'brien", "zażółć"]) {
|
||||
assert.equal(s.includes(raw), false, `${raw} in the script`);
|
||||
}
|
||||
assert.ok(s.includes("-LiteralPath"));
|
||||
assert.ok(s.includes("DIR"));
|
||||
assert.ok(s.includes("SIZE"));
|
||||
@@ -136,3 +156,13 @@ test("supportsImages", () => {
|
||||
assert.equal(supportsImages(null), false);
|
||||
assert.equal(supportsImages(""), false);
|
||||
});
|
||||
|
||||
test("sizeScript: an empty batch decodes to nothing", () => {
|
||||
assert.deepEqual(decodedStrings(sizeScript([])), [""]);
|
||||
});
|
||||
|
||||
test("Base64 of every length of tail round-trips (padding)", () => {
|
||||
for (const text of ["", "a", "ab", "abc", "abcd", "ęą", "😀x", "a\nb"]) {
|
||||
assert.deepEqual(decodedStrings(sizeScript([text])), [text]);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user