Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Publish uploads only what a template carries, without picture metadata, and the scrub catches more shapes

milind-soni995bc862dc34
diff --git a/server/share-allow-list.ts b/server/share-allow-list.ts
new file mode 100644
index 0000000000..adbe390be8
--- /dev/null
+++ b/server/share-allow-list.ts
@@ -0,0 +1,107 @@
+// What a template may carry when it is published. Publish reads the template's folder again, and the bot or the person
+// may have edited it since it was made, so the package is rebuilt from an allow-list: a field not named here never
+// leaves this computer. Security: connections (MCP addresses and value names), a bot's connections, starter memory and
+// approval level, presets, the publisher stamp and every SKILL.md frontmatter field but name and description are left
+// out, and each picture loses its metadata (camera, place, time, editor) with its pixels untouched.
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
+
+import type { PackageAgent, PackageDefinition, PackageDocument, PackageSkill } from "../shared/package-format.ts";
+import { withoutPictureMetadata } from "./workspace-banner.ts";
+
+type Picked<T> = { [K in keyof T]?: T[K] };
+
+/** Only the named fields of `value`, those it has. */
+function pick<T extends object, K extends keyof T>(value: T, keys: readonly K[]): Pick<T, K> {
+ const out: Picked<T> = {};
+ for (const key of keys) if (value[key] !== undefined) out[key] = value[key];
+ return out as Pick<T, K>;
+}
+
+/** What the card's "Left out" line says for each kind of field taken off. */
+const LEFT_OUT = {
+ connections: "connection addresses",
+ agentConnections: "the connections a bot uses",
+ seed: "a bot's starter memory",
+ approval: "a bot's approval level",
+ presets: "preset bots",
+ skillFields: "skill settings other than name and description",
+ picture: "a picture that couldn't be read",
+ other: "fields a template doesn't carry",
+} as const;
+
+const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/;
+
+/** A SKILL.md with only `name` and `description` in its frontmatter; unchanged when that is all it has. */
+function skillText(instructions: string, skill: Pick<PackageSkill, "name" | "description">): { text: string; trimmed: boolean } {
+ const match = FRONTMATTER.exec(instructions);
+ let meta: unknown;
+ try {
+ meta = match ? parseYaml(match[1]!, { maxAliasCount: 0 }) : null;
+ } catch {
+ meta = null;
+ }
+ const keys = meta && typeof meta === "object" && !Array.isArray(meta) ? Object.keys(meta) : [];
+ if (match && keys.every((key) => key === "name" || key === "description")) return { text: instructions, trimmed: false };
+ const body = match ? instructions.slice(match[0].length) : instructions;
+ const head = stringifyYaml({ name: skill.name, description: skill.description }, { lineWidth: 0 }).trimEnd();
+ return { text: `---\n${head}\n---\n${body.startsWith("\n") ? "" : "\n"}${body}`, trimmed: true };
+}
+
+/** The package as it may be published, and what was taken off it, in words for the card. */
+export function publicTemplate(document: PackageDocument): { document: PackageDocument; leftOut: string[] } {
+ const pkg = document.package;
+ const left = new Set<string>();
+ const known = new Set<string>(["id", "release", "name", "tagline", "summary", "notes", "category", "author", "license", "featured", "tags", "outcomes",
+ "setupMinutes", "requirements", "team", "agents", "rooms", "routines", "playbooks", "skills", "examples"]);
+ if (pkg.connections?.length) left.add(LEFT_OUT.connections);
+ if (pkg.presets?.length) left.add(LEFT_OUT.presets);
+ if (Object.keys(pkg).some((key) => !known.has(key) && key !== "connections" && key !== "presets")) left.add(LEFT_OUT.other);
+ if (pkg.author.url) left.add(LEFT_OUT.other);
+
+ const agents = pkg.agents.map((agent): PackageAgent => {
+ if (agent.connections?.length) left.add(LEFT_OUT.agentConnections);
+ if (agent.seed) left.add(LEFT_OUT.seed);
+ if (agent.approval) left.add(LEFT_OUT.approval);
+ const { avatar, ...look } = agent.appearance;
+ let picture = avatar;
+ if (avatar) {
+ const clean = withoutPictureMetadata(Buffer.from(avatar.data, "base64"));
+ if (clean) picture = { ...avatar, data: clean.toString("base64") };
+ else { picture = undefined; left.add(LEFT_OUT.picture); }
+ }
+ return {
+ ...pick(agent, ["key", "name", "title", "description", "soul", "recordBrowserSteps", "playbooks", "skills"]),
+ appearance: { ...pick(look, ["color", "mascotExpression", "mascotBody"]), ...(picture ? { avatar: pick(picture, ["mime", "data", "crop"]) } : {}) },
+ ...(agent.tools?.off.length ? { tools: { off: [...agent.tools.off] } } : {}),
+ } as PackageAgent;
+ });
+
+ const skills = pkg.skills && {
+ version: pkg.skills.version,
+ entries: pkg.skills.entries.map((skill) => {
+ const { text, trimmed } = skillText(skill.instructions, skill);
+ if (trimmed || skill.source || skill.license || skill.compatibility) left.add(LEFT_OUT.skillFields);
+ return { ...pick(skill, ["name", "description", "files"]), instructions: text } as PackageSkill;
+ }),
+ };
+
+ const definition = {
+ ...pick(pkg, ["id", "release", "name", "tagline", "summary", "notes", "category", "license", "featured", "tags", "outcomes", "setupMinutes"]),
+ author: { name: pkg.author.name },
+ requirements: {
+ apps: pkg.requirements.apps.map((app) => pick(app, ["slug", "label", "reason", "optional"])),
+ capabilities: [...pkg.requirements.capabilities],
+ ...(pkg.requirements.platforms ? { platforms: [...pkg.requirements.platforms] } : {}),
+ },
+ ...(pkg.team ? { team: pick(pkg.team, ["name", "brief", "leader"]) } : {}),
+ agents,
+ ...(pkg.rooms ? { rooms: pkg.rooms.map((room) => ({ ...pick(room, ["key", "name", "members", "bulletin"]),
+ defaultResponder: pick(room.defaultResponder as { kind: "agent"; agent: string }, ["kind", "agent"]) })) } : {}),
+ ...(pkg.routines ? { routines: pkg.routines.map((routine) => pick(routine, ["key", "name", "agent", "room", "prompt", "runOn", "schedule",
+ "durationMinutes", "timeoutMinutes", "overlap", "continuity", "runOnStartup", "enabledAfterInstall"])) } : {}),
+ ...(pkg.playbooks ? { playbooks: pkg.playbooks.map((playbook) => pick(playbook, ["key", "name", "summary", "triggers", "instructions"])) } : {}),
+ ...(skills ? { skills } : {}),
+ ...(pkg.examples ? { examples: pkg.examples.map((example) => pick(example, ["title", "input", "output"])) } : {}),
+ } as PackageDefinition;
+ return { document: { format: document.format, version: document.version, package: definition }, leftOut: [...left] };
+}
diff --git a/server/share.test.ts b/server/share.test.ts
index c4395e2156..82ecf69b73 100644
--- a/server/share.test.ts
+++ b/server/share.test.ts
@@ -3,7 +3,7 @@ import type { ServerResponse } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { parse as parseYaml } from "yaml";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import { redactSecretsInText } from "../shared/redact.ts";
import type { TemplateCard } from "../shared/share-card.ts";
@@ -257,6 +257,68 @@ describe("publishing without the person's details", () => {
expect(card.scrubbed).toEqual({ paths: 1, emails: 0, phones: 0, names: 0 });
});
+ it("uploads only the fields a template carries from a folder edited to hold connections, memory, approval and unknown keys", async () => {
+ let sent: { files: Record<string, string | { base64: string }> } | null = null;
+ const { share, patches } = host({ bots: [clean()], submit: async (submission) => { sent = submission as never; return ok; } });
+ const made = share.export({ scope: "bot", bot: clean() }, []);
+ share.shown(made.card.id, "thread-1", "message-1");
+ const file = join(made.dir, "bot.md");
+ const [, head, body] = readFileSync(file, "utf8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)!;
+ const meta = parseYaml(head!);
+ meta.author = { name: "Community", url: "https://example.com/me" };
+ meta.publisher = { organization: "acme", name: "Acme" };
+ meta.privateNotes = "UNKNOWN_TOP_LEVEL";
+ meta.connections = [{ key: "crm", label: "CRM", reason: "Used by Helper", mcp: { transport: "http", url: "https://crm.example.com/mcp/CONNECTION_PATH", valueNames: ["X-CRM-TOKEN"] } }];
+ meta.presets = [{ key: "p", name: "PRESET_NAME", bot: {} }];
+ Object.assign(meta.agents[0], { connections: ["crm"], seed: { memory: { "MEMORY.md": "SEED_MEMORY_LINE" } }, approval: "ask", model: "UNKNOWN_AGENT_KEY" });
+ meta.agents[0].appearance.ring = "UNKNOWN_LOOK";
+ writeFileSync(file, `---\n${stringifyYaml(meta)}---\n${body}`);
+ const skill = join(made.dir, "skills", "triage", "SKILL.md");
+ writeFileSync(skill, readFileSync(skill, "utf8").replace("description: Sort the inbox.", "description: Sort the inbox.\nallowed-tools: Bash(SKILL_TOOL:*)\nmetadata:\n owner: SKILL_OWNER"));
+
+ const card = await share.publish(made.card.id);
+ expect(card.status).toBe("published");
+ const everything = JSON.stringify(sent!.files);
+ for (const gone of ["UNKNOWN_TOP_LEVEL", "CONNECTION_PATH", "X-CRM-TOKEN", "PRESET_NAME", "SEED_MEMORY_LINE", "UNKNOWN_AGENT_KEY", "UNKNOWN_LOOK", "SKILL_TOOL", "SKILL_OWNER", "example.com/me", "acme"]) {
+ expect(everything).not.toContain(gone);
+ }
+ const published = frontmatter(botFile(sent));
+ expect(published).not.toHaveProperty("connections");
+ expect(published).not.toHaveProperty("publisher");
+ expect(published.author).toEqual({ name: "Community" });
+ expect(Object.keys(published.agents[0]).sort()).toEqual(["appearance", "description", "key", "name", "skills", "soul", "title", "tools"]);
+ expect(frontmatter(String(sent!.files["skills/triage/SKILL.md"]))).toEqual({ name: "triage", description: "Sort the inbox." });
+ expect(card.skipped).toEqual(expect.arrayContaining(["connection addresses", "the connections a bot uses", "a bot's starter memory", "a bot's approval level",
+ "preset bots", "skill settings other than name and description", "fields a template doesn't carry"]));
+ expect(patches.at(-1)!.card.skipped).toEqual(card.skipped);
+ expect(readFileSync(file, "utf8")).not.toMatch(/SEED_MEMORY_LINE|CONNECTION_PATH|approval/);
+ });
+
+ it("takes a picture's metadata out before it is uploaded, its pixels as they were", async () => {
+ let sent: { files: Record<string, string | { base64: string }> } | null = null;
+ const segment = (marker: number, payload: Buffer) => Buffer.concat([Buffer.from([0xff, marker, (payload.length + 2) >> 8, (payload.length + 2) & 0xff]), payload]);
+ const pixels = Buffer.from([0x12, 0x34, 0x56]);
+ const jpeg = Buffer.concat([
+ Buffer.from([0xff, 0xd8]),
+ segment(0xe0, Buffer.from("JFIF\0\x01\x01\0\0\x01\0\x01\0\0", "latin1")),
+ segment(0xe1, Buffer.from("Exif\0\0GPS 37.7749 -122.4194 Canon EOS", "latin1")),
+ segment(0xfe, Buffer.from("taken at home", "latin1")),
+ segment(0xc0, Buffer.from([8, 0, 1, 0, 1, 1, 1, 0x11, 0])),
+ segment(0xda, Buffer.from([1, 1, 0, 0, 0x3f, 0])),
+ pixels,
+ Buffer.from([0xff, 0xd9]),
+ ]);
+ const pictured = clean();
+ const { share } = host({ bots: [pictured], picture: () => `data:image/jpeg;base64,${jpeg.toString("base64")}`, submit: async (submission) => { sent = submission as never; return ok; } });
+ await share.publish(share.export({ scope: "bot", bot: pictured }, []).card.id);
+ const [path, value] = Object.entries(sent!.files).find(([name]) => name.startsWith("avatars/"))!;
+ expect(path).toMatch(/\.jpg$/);
+ const uploaded = Buffer.from((value as { base64: string }).base64, "base64");
+ expect(uploaded.toString("latin1")).not.toMatch(/Exif|GPS|Canon|taken at home/);
+ expect(uploaded.includes(pixels)).toBe(true);
+ expect(uploaded.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));
+ });
+
it("credits the name in Published by, the community when it is cleared, and the last one when a bot publishes", async () => {
let sent: unknown = null;
const { share } = host({ bots: [clean()], suggestedCredit: "Jane Doe", submit: async (submission) => { sent = submission; return ok; } });
diff --git a/server/share.ts b/server/share.ts
index 6df7410139..6b2c782329 100644
--- a/server/share.ts
+++ b/server/share.ts
@@ -35,6 +35,7 @@ import { writeFileAtomic } from "./atomic.ts";
import { productName } from "./brand.ts";
import { createTeamPackageExport, TeamExportError, type ExportablePackageSkill, type TeamExportSkip } from "./package-export.ts";
import type { Routine } from "./routines.ts";
+import { publicTemplate } from "./share-allow-list.ts";
import { COMMUNITY_MAX_BYTES, COMMUNITY_MAX_FILES, type CommunityPublisher } from "./share-publish.ts";
import type { BotRecord, GroupRecord } from "./store.ts";
import { parseTeamManifest } from "./team-manifest.ts";
@@ -488,7 +489,7 @@ export function createShareHost(deps: ShareHostDeps) {
files(id: string): { slug: string; files: Record<string, string | Uint8Array> } {
const record = records.get(id);
if (!record || record.status === "gone") throw new ShareError("This template was deleted.", 404);
- const { document } = scrubbedPackage(folderPackage(record.dir, record.scope), namesFor(record.author ?? deps.suggestedCredit?.()));
+ const { document } = scrubbedPackage(publicTemplate(folderPackage(record.dir, record.scope)).document, namesFor(record.author ?? deps.suggestedCredit?.()));
return { slug: record.slug, files: writeShareFolder(document, record.scope) };
},
@@ -500,22 +501,28 @@ export function createShareHost(deps: ShareHostDeps) {
if (record.status === "publishing") return lastCards.get(id) ?? cardOf(record);
if (deps.publisher.availability()) return update(record, { status: "draft", error: undefined });
const credit = options.author ?? record.author ?? "";
- let document: PackageDocument, counts: ScrubCounts;
+ let document: PackageDocument, counts: ScrubCounts, leftOut: string[];
try {
- ({ document, counts } = scrubbedPackage(folderPackage(record.dir, record.scope), namesFor(credit, options.names)));
+ const allowed = publicTemplate(folderPackage(record.dir, record.scope));
+ leftOut = allowed.leftOut;
+ ({ document, counts } = scrubbedPackage(allowed.document, namesFor(credit, options.names)));
} catch (error) {
if (error instanceof ShareError) return update(record, { status: "failed", error: error.message });
throw error;
}
if (record.secret || counts.secrets > 0) return update(record, { status: "failed", error: SECRET_REFUSAL, secret: true }, document);
document = withCredit(document, credit);
- if (Object.values(counts).some((count) => count > 0) && ownFolder(record)) writeFolder(record.dir, writeShareFolder(document, record.scope));
+ if ((leftOut.length || Object.values(counts).some((count) => count > 0)) && ownFolder(record)) {
+ rmSync(record.dir, { recursive: true, force: true });
+ writeFolder(record.dir, writeShareFolder(document, record.scope));
+ }
+ const skipped = [...new Set([...record.skipped, ...leftOut])];
const scrubbed = shownCounts(addScrubCounts({ ...emptyScrubCounts(), ...record.scrubbed }, counts));
const files = writeShareFolder(withoutSkillFiles(document), record.scope);
const bytes = Object.values(files).reduce((sum, value) => sum + (typeof value === "string" ? Buffer.byteLength(value) : value.byteLength), 0);
if (Object.keys(files).length > COMMUNITY_MAX_FILES) return update(record, { status: "failed", error: `A template can have at most ${COMMUNITY_MAX_FILES} files.` }, document);
if (bytes > COMMUNITY_MAX_BYTES) return update(record, { status: "failed", error: "This template is bigger than 4 MB. Leave out large pictures or skills, then publish again." }, document);
- update(record, { status: "publishing", error: undefined, scrubbed, ...(options.author === undefined ? {} : { author: options.author }) }, document);
+ update(record, { status: "publishing", error: undefined, scrubbed, skipped, ...(options.author === undefined ? {} : { author: options.author }) }, document);
const result = await deps.publisher.submit({
slug: record.slug,
files: Object.fromEntries(Object.entries(files).map(([path, value]) => [path, typeof value === "string" ? value : { base64: Buffer.from(value).toString("base64") }])),
diff --git a/server/workspace-banner.test.ts b/server/workspace-banner.test.ts
index a058ee572f..962eaa4327 100644
--- a/server/workspace-banner.test.ts
+++ b/server/workspace-banner.test.ts
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
-import { BANNER_MAX_BYTES, BANNER_REFUSALS, bannerMime, checkBanner } from "./workspace-banner.ts";
+import { BANNER_MAX_BYTES, BANNER_REFUSALS, bannerMime, checkBanner, withoutPictureMetadata } from "./workspace-banner.ts";
/** Small pictures a real encoder made, each carrying a camera make and model, a colour profile and text (EXIF, ICC, and a
* comment or XMP or text chunks). */
@@ -47,6 +47,14 @@ describe("a workspace's banner picture, as the server keeps it", () => {
expect(has(webp, "VP8")).toBe(true);
});
+ it("a template's picture loses the same metadata with no size limit, and anything else comes back as nothing", () => {
+ for (const sample of [JPEG_WITH_METADATA, WEBP_WITH_METADATA, PNG_WITH_METADATA]) {
+ expect(withoutPictureMetadata(sample)).toEqual(kept(sample).bytes);
+ }
+ expect(withoutPictureMetadata(Buffer.from("<svg/>"))).toBeNull();
+ expect(withoutPictureMetadata(JPEG_WITH_METADATA.subarray(0, 40))).toBeNull();
+ });
+
it("anything but a PNG, JPEG or WebP is refused in plain words, and so is one too big, too wide, moving or broken", () => {
const gif = Buffer.from("GIF89a\x01\x00\x01\x00\x00\x00\x00;", "latin1");
const svg = Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>");
diff --git a/server/workspace-banner.ts b/server/workspace-banner.ts
index 5943d79d94..8e0d911043 100644
--- a/server/workspace-banner.ts
+++ b/server/workspace-banner.ts
@@ -132,6 +132,18 @@ function cleanWebp(bytes: Buffer): CheckedBanner {
return { bytes: Buffer.concat([header, body]), mime: "image/webp", width, height };
}
+/** A still PNG, JPEG or WebP with every chunk or segment that can carry metadata taken out and its pixels' bytes as they
+ * were (nothing is decoded or encoded again); null for anything else, an animation, or a file it can't read. */
+export function withoutPictureMetadata(bytes: Buffer): Buffer | null {
+ const mime = bannerMime(bytes);
+ if (!mime) return null;
+ try {
+ return (mime === "image/png" ? cleanPng(bytes) : mime === "image/jpeg" ? cleanJpeg(bytes) : cleanWebp(bytes)).bytes;
+ } catch {
+ return null;
+ }
+}
+
/** The upload as it may be kept, or why not, in words the person can act on. */
export function checkBanner(bytes: Buffer): BannerCheck {
const mime = bannerMime(bytes);
diff --git a/shared/publish-scrub.ts b/shared/publish-scrub.ts
index 652ab235d4..c88cb6d3ba 100644
--- a/shared/publish-scrub.ts
+++ b/shared/publish-scrub.ts
@@ -70,6 +70,8 @@ function scrubSecrets(text: string, found: Found): string {
// ---- Paths ---------------------------------------------------------------------------------------------------------
+const decodeURIComponentSafe = (value: string) => { try { return decodeURIComponent(value); } catch { return value; } };
+
/** A path separator, also as it is written inside a quoted YAML or JSON string (`\\`). */
const SEP = String.raw`(?:\\{1,2}|/)`;
/** One path segment without spaces. */
@@ -88,11 +90,23 @@ const WORKSPACE = new RegExp(
`${SEP}\\.openmausbot[A-Za-z0-9._-]*(?:${SEP}${SEG}){0,3}?${SEP}(?:task-workspaces${SEP}[A-Za-z0-9_-]+(?:${SEP}[A-Za-z0-9_-]{8,})?|workspaces${SEP}[A-Za-z0-9_-]+)(?![A-Za-z0-9_-])`,
"g",
);
-const MAC_LINUX_HOME = new RegExp(`${PATH_START}/(Users|home)/([A-Za-z0-9._-]{0,63}[A-Za-z0-9_-])(?![A-Za-z0-9_-])`, "g");
+/** A home under a mounted disk or a WSL view of Windows: `/Volumes/<disk>/Users/x`, `/mnt/c/Users/x`. */
+const MOUNT = String.raw`(?:/Volumes/[^/\r\n'"\`<>]{1,64}|/mnt/[A-Za-z])?`;
+const MAC_LINUX_HOME = new RegExp(`${PATH_START}${MOUNT}/(Users|home)/((?:[A-Za-z0-9._-]|%20){0,63}[A-Za-z0-9_-])(?![A-Za-z0-9_-]|%20)`, "g");
+/** A home on another machine or a WSL distribution: a UNC path to `Users` or `home`, such as `\\server\Users\x` or `\\wsl$\Ubuntu\home\x`. */
+const UNC_HOME = new RegExp(String.raw`(?<![A-Za-z0-9_\\])\\{2,4}[A-Za-z0-9.$_-]{1,64}\\{1,2}(?:[A-Za-z0-9._$-]{1,64}\\{1,2})?(Users|home)\\{1,2}(${WIN_NAME})(?![A-Za-z0-9_-])`, "gi");
+/** A home folder written percent-encoded, as a link or a query holds it: `%2FUsers%2Fx`, `C%3A%5CUsers%5Cx`. */
+const ENCODED_HOME = /(?:[A-Za-z]%3A)?%(?:2F|5C)(Users|home)%(?:2F|5C)((?:[A-Za-z0-9._-]|%20){1,64}?)(?=%(?:2F|5C)|[^A-Za-z0-9._%-]|$)/gi;
const WINDOWS_HOME = new RegExp(`(?<![A-Za-z0-9_])[A-Za-z]:${SEP}[Uu]sers${SEP}(${WIN_NAME})(?![A-Za-z0-9_-])`, "g");
function scrubPaths(text: string, found: Found): string {
let out = text.replace(WORKSPACE, (match) => take(found, "paths", match, SCRUB_MARKS.workspace));
+ const home = (match: string, name: string) => {
+ const lower = decodeURIComponentSafe(name).trim().toLowerCase();
+ return SHARED_HOMES.has(lower) || lower === "public" || lower === "default" ? match : take(found, "paths", match, SCRUB_MARKS.path);
+ };
+ out = out.replace(ENCODED_HOME, (match, _root: string, name: string) => home(match, name));
+ out = out.replace(UNC_HOME, (match, _root: string, name: string) => home(match, name));
out = out.replace(WINDOWS_HOME, (match, name: string) => {
const lower = name.toLowerCase();
return SHARED_HOMES.has(lower) || lower === "public" || lower === "default" ? match : take(found, "paths", match, SCRUB_MARKS.path);
@@ -103,7 +117,8 @@ function scrubPaths(text: string, found: Found): string {
// ---- Emails and phone numbers --------------------------------------------------------------------------------------
-const EMAIL = /(?<![A-Za-z0-9._%+-])([A-Za-z0-9._%+-]{1,64})@((?:[A-Za-z0-9-]{1,63}\.)+([A-Za-z]{2,24}))(?![A-Za-z0-9-]|\.[A-Za-z0-9])/g;
+/** Also with a full-width @ or `%40`, and with letters of any script (an internationalised domain). */
+const EMAIL = /(?<![\p{L}\p{N}._%+-])([\p{L}\p{N}._+-]{1,64}?)(?:@|@|%40)((?:[\p{L}\p{N}-]{1,63}\.)+(\p{L}{2,24}))(?![\p{L}\p{N}-]|\.[\p{L}\p{N}])/gu;
/** Addresses nobody owns, and `[email protected]`-style file names. */
const FILE_ENDINGS = new Set(["png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "bmp", "pdf", "js", "mjs", "cjs", "ts", "tsx", "jsx", "css", "scss",
"json", "md", "py", "rb", "go", "rs", "java", "sh", "txt", "htm", "html", "xml", "yml", "yaml", "toml", "lock", "zip", "tar", "gz", "wasm", "map"]);
@@ -121,15 +136,18 @@ const PHONE_BARE = /(?<![A-Za-z0-9_+/=%.-])\+\d{10,15}(?![A-Za-z0-9_]|[.-]\d)/g;
const PHONE_NANP = /(?<![A-Za-z0-9_.+-])(?:\(\d{3}\)\s?|\d{3}[-.])\d{3}[-.]\d{4}(?![A-Za-z0-9_]|[.-]\d)/g;
/** 020 7946 0958, 0800-123-4567: a trunk 0 and three groups. */
const PHONE_TRUNK = /(?<![A-Za-z0-9_.+-])0\d{2,4}[ -]\d{3,4}[ -]\d{3,4}(?![A-Za-z0-9_]|[ .-]\d)/g;
+/** Without a `+`, only spaced groups a timestamp or an id never has: 415 555 0132, (415) 555 0132, 98765 43210. */
+const PHONE_SPACED = /(?<![A-Za-z0-9_.+:/-])(?:\(?[2-9]\d{2}\)? \d{3} \d{4}|[6-9]\d{4} \d{5})(?![A-Za-z0-9_]|[ .:-]\d)/g;
const digitCount = (value: string) => value.replace(/\D/g, "").length;
function scrubContacts(text: string, found: Found): string {
let out = text.replace(EMAIL, (match, local: string, domain: string, ending: string) =>
- keepEmail(local, domain, ending) ? match : take(found, "emails", match.toLowerCase(), SCRUB_MARKS.email));
+ keepEmail(local, domain, ending) ? match : take(found, "emails", `${local}@${domain}`.toLowerCase(), SCRUB_MARKS.email));
const phone = (match: string) => take(found, "phones", match.replace(/\D/g, ""), SCRUB_MARKS.phone);
out = out.replace(PHONE_INTERNATIONAL, (match: string) => digitCount(match) < 8 || digitCount(match) > 15 ? match : phone(match));
out = out.replace(PHONE_BARE, phone);
out = out.replace(PHONE_NANP, phone);
+ out = out.replace(PHONE_SPACED, phone);
return out.replace(PHONE_TRUNK, (match: string) => digitCount(match) < 10 ? match : phone(match));
}
@@ -182,9 +200,24 @@ export function scrubText(text: string, options: ScrubOptions = {}): { text: str
return { text: scrubInto(text, options, found), counts: countsOf(found) };
}
+/** Bidirectional overrides and isolates (text that reads differently than it shows) and control characters other than
+ * tab and line breaks: they go before anything else is looked at, so none can hide a match. */
+const hidden = (code: number) => (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) || (code >= 0x7f && code <= 0x9f)
+ || (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069);
+
+function withoutHidden(text: string): string {
+ let out = "", from = 0;
+ for (let at = 0; at < text.length; at += 1) {
+ if (!hidden(text.charCodeAt(at))) continue;
+ out += text.slice(from, at);
+ from = at + 1;
+ }
+ return from === 0 ? text : out + text.slice(from);
+}
+
function scrubInto(text: string, options: ScrubOptions, found: Found): string {
if (!text) return text;
- let out = scrubSecrets(text, found);
+ let out = scrubSecrets(withoutHidden(text), found);
out = scrubPaths(out, found);
out = scrubContacts(out, found);
return options.names?.length ? scrubNames(out, options.names, found) : out;
diff --git a/shared/publish-scrub.vectors.json b/shared/publish-scrub.vectors.json
index b694ff6571..6a8f81669d 100644
--- a/shared/publish-scrub.vectors.json
+++ b/shared/publish-scrub.vectors.json
@@ -246,6 +246,66 @@
"secrets": 0
}
},
+ {
+ "name": "emails written with a full-width @, as %40 or with an internationalised domain",
+ "input": "Mail jane@acme.io, jane%40acme.io, josé@münchen.de or 太郎@例え.日本; [email protected] and [email protected] stay.",
+ "output": "Mail <email>, <email>, <email> or <email>; [email protected] and [email protected] stay.",
+ "counts": {
+ "paths": 0,
+ "emails": 3,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "phone numbers without a + in spaced groups; timestamps, dates and ids stay",
+ "input": "Call 415 555 0132, (415) 555 0132 or 98765 43210. Not 1794748391525, 2026 11 25, 100 200 3000, 12:30 555 1234 or 1234 5678 9012 3456.",
+ "output": "Call <phone>, <phone> or <phone>. Not 1794748391525, 2026 11 25, 100 200 3000, 12:30 555 1234 or 1234 5678 9012 3456.",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 2,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "WSL, UNC and mounted-disk homes",
+ "input": "/mnt/c/Users/jane/Desktop, \\\\wsl$\\Ubuntu\\home\\jane\\x, \\\\fileserver\\Users\\jane\\docs, \\\\nas\\c$\\Users\\Bob Smith\\x, /Volumes/Macintosh HD/Users/jane/x; \\\\server\\Users\\Public stays.",
+ "output": "~/Desktop, ~\\x, ~\\docs, ~\\x, ~/x; \\\\server\\Users\\Public stays.",
+ "counts": {
+ "paths": 5,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "percent-encoded homes",
+ "input": "file:///Users/Jane%20Doe/x.md, ?path=%2FUsers%2Fjanedoe%2Fnotes, C%3A%5CUsers%5Cjane%5Cx; %2FUsers%2FShared stays.",
+ "output": "file://~/x.md, ?path=~%2Fnotes, ~%5Cx; %2FUsers%2FShared stays.",
+ "counts": {
+ "paths": 3,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "bidirectional overrides and control characters go; tabs, line breaks and right-to-left text stay",
+ "input": "safe ‮txt.exe‬ and a bell\u0007 here\tthen\nשלום עולם",
+ "output": "safe txt.exe and a bell here\tthen\nשלום עולם",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
{
"name": "the publisher's markers are not scrubbed again",
"input": "~/x <workspace>/y <email> <phone> <name> <secret> «redacted 40 chars»",