Skip to content

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

Publishing a template scrubs personal details first, and credits a Published by name

milind-soni901d29f2905e
diff --git a/packages/phone-protocol/src/share-card.ts b/packages/phone-protocol/src/share-card.ts
index 0df06c5ecd..f48a7c28d7 100644
--- a/packages/phone-protocol/src/share-card.ts
+++ b/packages/phone-protocol/src/share-card.ts
@@ -23,6 +23,15 @@ export interface TemplateCard {
counts: { bots: number; skills: number; routines: number; apps: number };
/** How many key- or password-shaped values were replaced before the folder was written. */
redacted: number;
+ /** What was taken out of its text before it left this computer: home and data folders, email addresses, phone numbers
+ * and the publisher's own names. Left out when nothing was. */
+ scrubbed?: { paths: number; emails: number; phones: number; names: number };
+ /** It holds something key- or token-shaped: Publish is refused until the template is made again without it. */
+ secret?: boolean;
+ /** What the "Published by" field starts with: the name it was last published under, else the profile's name. */
+ author?: string;
+ /** The name it was published under; left out for none ("Community"). */
+ publishedBy?: string;
/** Parts left out, in plain words ("Skill pricing changed while it was being shared"). */
skipped: string[];
status: TemplateStatus;
diff --git a/server/host/share.ts b/server/host/share.ts
index e193f43156..eb2532dc0d 100644
--- a/server/host/share.ts
+++ b/server/host/share.ts
@@ -1,4 +1,6 @@
// Templates' wiring: the share host, its HTTP routes and the share tool's internal route, from index.ts's records.
+import { userInfo } from "node:os";
+
import { botAvatarUrlFromStoredPath } from "../../shared/bot-avatar.ts";
import type { TemplateCard } from "../../shared/share-card.ts";
import type { WireBot, WireGroup } from "../../shared/wire.ts";
@@ -46,11 +48,23 @@ function botPicture(bot: BotRecord): string | undefined {
return stored ? `data:${stored.mime};base64,${stored.bytes.toString("base64")}` : undefined;
}
+/** This computer's user name; none where the system has no entry for the process's user. */
+function systemUserName(): string | undefined {
+ try {
+ return userInfo().username;
+ } catch {
+ return undefined;
+ }
+}
+
export function createShareWiring(deps: ShareWiringDeps) {
+ // A Team Cloud's profile is nobody's own, so it neither names the publisher nor is taken out for them.
+ const profileName = () => (deps.team ? undefined : deps.github.cfg().profile?.name?.trim() || undefined);
const host = createShareHost({
dataDir: deps.dataDir, bots: deps.bots, groups: deps.groups, routines: deps.routines, brief: deps.brief, botFolder: deps.botFolder,
collectTeamSkills: deps.collectTeamSkills, skillFiles: deps.skillFiles, picture: botPicture,
publisher: createCommunityPublisher({ access: deps.access, notOffered: deps.notOffered, selfHosted: deps.selfHosted }),
+ personNames: () => [systemUserName(), profileName()], suggestedCredit: profileName,
patch: (threadId, messageId, text, template) => deps.patchMessage(threadId, messageId, { text, template }),
});
const view = { publicBot: deps.publicBot, publicGroup: deps.publicGroup, broadcast: deps.broadcast };
diff --git a/server/package-export.ts b/server/package-export.ts
index 211f7f842a..73c412c2dd 100644
--- a/server/package-export.ts
+++ b/server/package-export.ts
@@ -313,6 +313,8 @@ export interface TeamExportInput {
mcpServers?: Readonly<Record<string, unknown>>;
skipped?: readonly TeamExportSkip[];
preset?: DefaultsPreset | null;
+ /** Sees the package before key- and password-shaped values are replaced, so a caller can refuse one instead. */
+ beforeRedaction?(definition: Readonly<PackageDefinition>): void;
}
export interface TeamExportResult {
@@ -693,6 +695,7 @@ export function createTeamPackageExport(input: TeamExportInput): TeamExportResul
if (packageSkills.size) definition.skills = { version: 1, entries: [...packageSkills.values()].map((skill) => ({ ...skill })) };
if (connections.length) definition.connections = connections;
+ input.beforeRedaction?.(definition);
const { document: redactedDocument, redacted } = redactPackageSecrets({
format: PACKAGE_FORMAT, version: packageVersionFor(definition), package: definition,
} as PackageDocument);
diff --git a/server/routes/share.ts b/server/routes/share.ts
index 71acf20860..30139ec838 100644
--- a/server/routes/share.ts
+++ b/server/routes/share.ts
@@ -13,7 +13,7 @@ import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";
import type { Routine } from "../routines.ts";
import { fetchGithubTemplate, GithubTemplateError } from "../share-github.ts";
import { publishToRepo, readRepoFolder, repoFolder, repoFolderOf, repoName, type GithubConnection } from "../share-github-repo.ts";
-import { cardText, readFolderFromDisk, ShareError, type ShareHost } from "../share.ts";
+import { cardText, creditName, readFolderFromDisk, ShareError, type ShareHost } from "../share.ts";
import type { TeamTemplates } from "../team-templates.ts";
import { zipFolder } from "../share-zip.ts";
import type { BotRecord, GroupRecord } from "../store.ts";
@@ -243,7 +243,11 @@ export function createShareRoutes(deps: ShareRouteDeps): RouteHandler {
host.delete(id);
return json(res, 200, { ok: true });
}
- if (method === "POST" && m[2] === "/publish") return json(res, 200, await host.publish(id));
+ if (method === "POST" && m[2] === "/publish") {
+ const author = creditName(((await readBody(req)) as { author?: unknown } | null)?.author);
+ if (author === null) return json(res, 400, { error: "Put a name in Published by, not an email address." });
+ return json(res, 200, await host.publish(id, { ...(author === undefined ? {} : { author }), names: [deps.who?.(auth)] }));
+ }
if (method === "POST" && m[2] === "/library") {
if (!deps.library) return json(res, 404, { error: NO_LIBRARY });
if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the team's admins add templates to its library." });
diff --git a/server/share-team-templates.test.ts b/server/share-team-templates.test.ts
index add60a8e99..d0e5a5c57d 100644
--- a/server/share-team-templates.test.ts
+++ b/server/share-team-templates.test.ts
@@ -74,6 +74,16 @@ function setup(options: { team?: boolean; github?: GithubConnection; fetchTempla
return { host, dataDir, request, call, made: () => host.export({ scope: "bot", bot: helper }, []) };
}
+describe("Publish over HTTP", () => {
+ it("takes Published by from the body, and refuses an email address in it", async () => {
+ const { request, made } = setup();
+ const card = made().card;
+ expect(await request(ADMIN, "POST", `/api/share/${card.id}/publish`, { author: "[email protected]" })).toEqual({ status: 400, body: { error: "Put a name in Published by, not an email address." } });
+ expect(await request(ADMIN, "POST", `/api/share/${card.id}/publish`, { author: " Olive " })).toMatchObject({ status: 200, body: { id: card.id, author: "Olive" } });
+ expect(await request(ADMIN, "POST", `/api/share/${card.id}/publish`, {})).toMatchObject({ status: 200, body: { author: "Olive" } });
+ });
+});
+
describe("a team's own templates", () => {
it("an admin adds one under team-files/templates/<slug>/; adding again replaces it and keeps the old one as <slug>.previous/", async () => {
const { request, made, dataDir } = setup();
diff --git a/server/share.test.ts b/server/share.test.ts
index 4cf9d0901a..d840932a4e 100644
--- a/server/share.test.ts
+++ b/server/share.test.ts
@@ -12,7 +12,7 @@ import { createShareToolRoute, importSource, type ShareToolContext } from "./rou
import { GithubTemplateError } from "./share-github.ts";
import { createCommunityPublisher, type CommunityResult } from "./share-publish.ts";
import { pagesHomeSignature } from "./pages/access.ts";
-import { createShareHost, readFolderFromDisk } from "./share.ts";
+import { createShareHost, creditName, readFolderFromDisk } from "./share.ts";
import type { Routine } from "./routines.ts";
import type { BotRecord } from "./store.ts";
@@ -38,7 +38,11 @@ function bot(overrides: Partial<BotRecord> = {}): BotRecord {
const routine = { id: "r1", name: "Morning sweep", botId: "bot-1", prompt: "Sweep the inbox.", runOn: "maus", enabled: true,
schedule: { type: "daily", time: "09:00", weekdays: [1, 2, 3, 4, 5] }, durationMinutes: 30 } as unknown as Routine;
-function host(options: { submit?: (submission: unknown) => Promise<CommunityResult>; signedIn?: boolean; bots?: BotRecord[]; picture?: (bot: BotRecord) => string | undefined; brief?: string } = {}) {
+/** A bot whose words hold no key, which Publish sends. */
+const clean = (overrides: Partial<BotRecord> = {}) => bot({ soul: "Be brief.", ...overrides });
+
+function host(options: { submit?: (submission: unknown) => Promise<CommunityResult>; signedIn?: boolean; bots?: BotRecord[]; picture?: (bot: BotRecord) => string | undefined; brief?: string;
+ personNames?: Array<string | undefined>; suggestedCredit?: string } = {}) {
const dataDir = scratch(), botFolder = scratch();
const patches: Array<{ messageId: string; card: TemplateCard }> = [];
const bots = options.bots ?? [bot()];
@@ -49,6 +53,8 @@ function host(options: { submit?: (submission: unknown) => Promise<CommunityResu
picture: options.picture ?? (() => undefined), botFolder: (id) => join(botFolder, id),
publisher: options.submit ? { ...publisher, submit: options.submit } : publisher,
patch: (_threadId, messageId, _text, card) => patches.push({ messageId, card }),
+ ...(options.personNames ? { personNames: () => options.personNames! } : {}),
+ ...(options.suggestedCredit ? { suggestedCredit: () => options.suggestedCredit } : {}),
});
return { share, dataDir, botFolder, patches, bots };
}
@@ -110,8 +116,8 @@ describe("making a template", () => {
describe("publishing", () => {
it("offers the folder and GitHub's upload page when this app isn't signed in or the service isn't there", async () => {
- const { share } = host({ signedIn: false });
- const made = share.export({ scope: "bot", bot: bot() }, []);
+ const { share } = host({ signedIn: false, bots: [clean()] });
+ const made = share.export({ scope: "bot", bot: clean() }, []);
expect(made.card.fallback).toBe("sign_in");
expect(await share.publish(made.card.id)).toMatchObject({ status: "draft", fallback: "sign_in" });
for (const status of [404, 501]) {
@@ -155,10 +161,10 @@ describe("publishing", () => {
it("sends a folder the Admin's checks accept: BotMRR v2 frontmatter, skills named as their folders, pictures as base64, paused routines, under the caps", async () => {
let sent: { slug: string; files: Record<string, string | { base64: string }> } | null = null;
- const pictured = bot({ id: "bot-2", name: "Painter" });
+ const pictured = clean({ id: "bot-2", name: "Painter" });
const png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
- const { share } = host({ bots: [bot(), pictured], picture: (each) => each.id === "bot-2" ? png : undefined, submit: async (submission) => { sent = submission as never; return { ok: false, reason: "failed", message: "x" }; } });
- const made = share.export({ scope: "department", section: "Ops", bots: [bot(), pictured] }, [routine]);
+ const { share } = host({ bots: [clean(), pictured], picture: (each) => each.id === "bot-2" ? png : undefined, submit: async (submission) => { sent = submission as never; return { ok: false, reason: "failed", message: "x" }; } });
+ const made = share.export({ scope: "department", section: "Ops", bots: [clean(), pictured] }, [routine]);
await share.publish(made.card.id);
const files = sent!.files;
expect(Object.keys(files).filter((path) => path.startsWith("avatars/"))).toHaveLength(1);
@@ -181,7 +187,7 @@ describe("publishing", () => {
expect(meta.routines.every((each: { enabledAfterInstall: boolean }) => each.enabledAfterInstall === false)).toBe(true);
for (const agent of meta.agents) for (const name of agent.skills ?? []) expect(files[`skills/${name}/SKILL.md`]).toBeTypeOf("string");
const single = host({ submit: async (submission) => { sent = submission as never; return { ok: false, reason: "failed", message: "x" }; } });
- await single.share.publish(single.share.export({ scope: "bot", bot: bot() }, []).card.id);
+ await single.share.publish(single.share.export({ scope: "bot", bot: clean() }, []).card.id);
expect(parseYaml(String(sent!.files["bot.md"]).match(/^---\n([\s\S]*?)\n---/)![1]!).agents).toHaveLength(1);
});
@@ -194,7 +200,7 @@ describe("publishing", () => {
it("re-draws every card that shows the template as it is published, fails and is deleted", async () => {
let answer: CommunityResult = { ok: false, reason: "failed", message: "You've published a lot today. Try again tomorrow." };
const { share, patches } = host({ submit: async () => answer });
- const made = share.export({ scope: "bot", bot: bot() }, []);
+ const made = share.export({ scope: "bot", bot: clean() }, []);
share.shown(made.card.id, "thread-1", "message-1");
expect(await share.publish(made.card.id)).toMatchObject({ status: "failed", error: "You've published a lot today. Try again tomorrow." });
expect(patches.map((patch) => patch.card.status)).toEqual(["publishing", "failed"]);
@@ -206,6 +212,98 @@ describe("publishing", () => {
});
});
+describe("publishing without the person's details", () => {
+ const botFile = (submission: unknown) => String((submission as { files: Record<string, string> }).files["bot.md"]);
+ const frontmatter = (text: string) => parseYaml(text.match(/^---\n([\s\S]*?)\n---/)![1]!);
+ const ok: CommunityResult = { ok: true, link: "https://github.com/milind-soni/openmausbot-teams/tree/a/teams/helper", prUrl: "https://github.com/milind-soni/openmausbot-teams/pull/1" };
+
+ it("never publishes a template with a key in what it carries, even scrubbed, and sends nothing", async () => {
+ let sent = 0;
+ const { share } = host({ submit: async () => { sent += 1; return ok; } });
+ const made = share.export({ scope: "bot", bot: bot() }, []);
+ expect(made.card.secret).toBe(true);
+ expect(await share.publish(made.card.id)).toMatchObject({ status: "failed", secret: true, error: expect.stringMatching(/looks like a key or token/) });
+ expect(sent).toBe(0);
+ const remade = share.export({ scope: "bot", bot: clean() }, []);
+ expect(remade.card.secret).toBeUndefined();
+ expect(await share.publish(remade.card.id)).toMatchObject({ status: "published" });
+ expect(sent).toBe(1);
+ });
+
+ it("takes home folders, the app's workspace folders, emails and phone numbers out of the folder before it can be published, and says how many", async () => {
+ let sent: unknown = null;
+ const words = "Work in /Users/janedoe/WorkSpace/acme. Reports go to /Users/janedoe/.openmausbot/workspaces/0b9c3a52-8d61-4f0e-a2b7-5c1e9d4f3a10/out.md. "
+ + "Ask [email protected] or +1 (415) 555-0132. Runs at anchorAt 1794748391525.";
+ const helper = clean({ description: words });
+ const { share } = host({ bots: [helper], submit: async (submission) => { sent = submission; return ok; } });
+ const made = share.export({ scope: "bot", bot: helper }, []);
+ expect(made.card.scrubbed).toEqual({ paths: 2, emails: 1, phones: 1, names: 0 });
+ const onDisk = readFileSync(join(made.dir, "bot.md"), "utf8");
+ expect(onDisk).toContain("Work in ~/WorkSpace/acme. Reports go to <workspace>/out.md. Ask <email> or <phone>. Runs at anchorAt 1794748391525.");
+ expect(share.get(made.card.id).details.bots[0]!.description).not.toMatch(/janedoe|acme\.io|555/);
+ await share.publish(made.card.id);
+ expect(botFile(sent)).not.toMatch(/janedoe|acme\.io|555-0132/);
+ expect((await share.publish(made.card.id)).scrubbed).toEqual({ paths: 2, emails: 1, phones: 1, names: 0 });
+ });
+
+ it("takes out what the bot wrote into the folder after the template was made", async () => {
+ let sent: unknown = null;
+ const { share } = host({ bots: [clean()], submit: async (submission) => { sent = submission; return ok; } });
+ const made = share.export({ scope: "bot", bot: clean() }, []);
+ const file = join(made.dir, "bot.md");
+ writeFileSync(file, readFileSync(file, "utf8").replace("Keeps the inbox tidy.", "Keeps C:\\Users\\Jane\\inbox tidy."));
+ const card = await share.publish(made.card.id);
+ expect(botFile(sent)).toContain("Keeps ~\\inbox tidy.");
+ expect(card.scrubbed).toEqual({ paths: 1, emails: 0, phones: 0, names: 0 });
+ });
+
+ 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; } });
+ const made = share.export({ scope: "bot", bot: clean() }, []);
+ expect(made.card.author).toBe("Jane Doe");
+ expect(frontmatter(readFileSync(join(made.dir, "bot.md"), "utf8")).author).toEqual({ name: "Community" });
+ const published = await share.publish(made.card.id, { author: "Jane D." });
+ expect(frontmatter(botFile(sent)).author).toEqual({ name: "Jane D." });
+ expect(published).toMatchObject({ status: "published", publishedBy: "Jane D.", author: "Jane D." });
+ await share.publish(made.card.id);
+ expect(frontmatter(botFile(sent)).author).toEqual({ name: "Jane D." });
+ const cleared = await share.publish(made.card.id, { author: "" });
+ expect(frontmatter(botFile(sent)).author).toEqual({ name: "Community" });
+ expect(cleared.publishedBy).toBeUndefined();
+ expect(cleared.author).toBe("");
+ });
+
+ it("credits the community when a bot publishes a template nobody named", async () => {
+ let sent: unknown = null;
+ const { share } = host({ bots: [clean()], suggestedCredit: "Jane Doe", submit: async (submission) => { sent = submission; return ok; } });
+ await share.publish(share.export({ scope: "bot", bot: clean() }, []).card.id);
+ expect(frontmatter(botFile(sent)).author).toEqual({ name: "Community" });
+ });
+
+ it("takes out the person's user name, and their profile name unless they publish under it", async () => {
+ let sent: unknown = null;
+ const helper = clean({ description: "Made by Jane Doe on janedoe's laptop for root." });
+ const { share } = host({ bots: [helper], personNames: ["janedoe", "Jane Doe"], suggestedCredit: "Jane Doe", submit: async (submission) => { sent = submission; return ok; } });
+ const made = share.export({ scope: "bot", bot: helper }, []);
+ expect(made.card.scrubbed).toEqual({ paths: 0, emails: 0, phones: 0, names: 1 });
+ await share.publish(made.card.id, { author: "Jane Doe" });
+ expect(frontmatter(botFile(sent)).agents[0].description).toBe("Made by Jane Doe on <name>'s laptop for root.");
+ const card = await share.publish(made.card.id, { author: "JD" });
+ expect(frontmatter(botFile(sent)).agents[0].description).toBe("Made by <name> on <name>'s laptop for root.");
+ expect(card.scrubbed).toEqual({ paths: 0, emails: 0, phones: 0, names: 2 });
+ });
+
+ it("reads Published by as one line of plain words and never an email address", () => {
+ expect(creditName(undefined)).toBeUndefined();
+ expect(creditName("")).toBe("");
+ expect(creditName(" Jane\n\u200b Doe ")).toBe("Jane Doe");
+ expect(creditName("[email protected]")).toBeNull();
+ expect(creditName(42)).toBeNull();
+ expect(creditName("x".repeat(300))).toHaveLength(100);
+ });
+});
+
describe("reading a folder from disk", () => {
it("reads only the template's files and nothing a link points out to", () => {
const outside = scratch(), folder = scratch();
diff --git a/server/share.ts b/server/share.ts
index 1e89be2b7e..2864db5e60 100644
--- a/server/share.ts
+++ b/server/share.ts
@@ -15,6 +15,7 @@ import {
redactPackageSecrets,
type PackageDocument,
} from "../shared/package-format.ts";
+import { addScrubCounts, emptyScrubCounts, personalNames, scrubTree, type ScrubCounts } from "../shared/publish-scrub.ts";
import type { TemplateAvatar, TemplateCard, TemplateDetails, TemplateScope } from "../shared/share-card.ts";
import { manifestDetails, packageDetails } from "../shared/share-details.ts";
import {
@@ -63,6 +64,11 @@ export interface ShareHostDeps {
/** The bot's own folder, where a template it makes is written for it to read and edit. */
botFolder(botId: string): string;
publisher: CommunityPublisher;
+ /** The person's own names here (this computer's user name, the profile's name): taken out of what a template carries
+ * unless one is the name it is published under. */
+ personNames?(): ReadonlyArray<string | undefined>;
+ /** What "Published by" starts with: the profile's name, where the profile is one person's. */
+ suggestedCredit?(): string | undefined;
/** Re-draws a template card already in a conversation. */
patch(threadId: string, messageId: string, text: string, card: TemplateCard): void;
}
@@ -79,6 +85,9 @@ const recordSchema = z.object({
prUrl: z.string().optional(),
error: z.string().optional(),
redacted: z.number().int().min(0),
+ scrubbed: z.object({ paths: z.number().int().min(0), emails: z.number().int().min(0), phones: z.number().int().min(0), names: z.number().int().min(0) }).optional(),
+ secret: z.boolean().optional(),
+ author: z.string().max(100).optional(),
skipped: z.array(z.string()),
avatars: z.array(z.object({ key: z.string(), name: z.string(), color: z.string(), picture: z.string().optional(), mascotExpression: z.string().optional(), mascotBody: z.string().optional() })),
cards: z.array(z.object({ threadId: z.string(), messageId: z.string() })),
@@ -96,6 +105,34 @@ const plainTagline = (scope: TemplateScope) => `A ${scope === "bot" ? "bot" : "d
const plainSummary = (scope: TemplateScope) => scope === "bot"
? `Shared from ${productName()}. The bot arrives as a new copy with its skills and routines; routines start paused and chat history never travels.`
: `Shared from ${productName()}. Its bots, skills, group chats and routines arrive as new copies; routines start paused and chat history never travels.`;
+/** The credit a template carries when its publisher gives no name. */
+export const COMMUNITY_CREDIT = "Community";
+const SECRET_REFUSAL = "This template holds something that looks like a key or token, so it can't be published. Remove it from the bot's instructions or skills, then make the template again.";
+
+/** "Published by" as one line of plain words: undefined when not given, "" when cleared, null for an email address. */
+export function creditName(value: unknown): string | null | undefined {
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== "string") return null;
+ const name = value.normalize("NFKC").replace(/[\p{Cc}\p{Cf}]+/gu, " ").replace(/\s+/g, " ").trim().slice(0, 100).trim();
+ return name.includes("@") ? null : name;
+}
+
+/** The package with the person's details taken out of every text, checked again. */
+function scrubbedPackage(document: PackageDocument, names: readonly string[]): { document: PackageDocument; counts: ScrubCounts } {
+ const { value, counts } = scrubTree(document.package, { names });
+ try {
+ return { document: parsePackageDocument({ ...document, package: value }, { trust: "file" }), counts };
+ } catch (error) {
+ throw new ShareError(error instanceof Error ? error.message : "This template can't be published.");
+ }
+}
+
+const withCredit = (document: PackageDocument, credit: string): PackageDocument =>
+ ({ ...document, package: { ...document.package, author: { name: credit || COMMUNITY_CREDIT } } });
+
+const shownCounts = ({ secrets: _secrets, ...counts }: ScrubCounts) => counts;
+const anyScrubbed = (counts: TemplateRecord["scrubbed"]) => Boolean(counts && Object.values(counts).some((count) => count > 0));
+
const skipWords = (skip: TeamExportSkip) => `${SKIP_WORDS[skip.reason] ?? "an item that can't be shared"} (${skip.part})`;
const slugOf = (name: string) => name.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "template";
@@ -272,6 +309,7 @@ export function createShareHost(deps: ShareHostDeps) {
const cardOf = (record: TemplateRecord, document?: PackageDocument): TemplateCard => {
const pkg = document?.package;
const fallback = record.status === "draft" || record.status === "failed" ? deps.publisher.availability() : null;
+ const credit = record.author ?? deps.suggestedCredit?.();
return {
id: record.id,
scope: record.scope,
@@ -285,6 +323,10 @@ export function createShareHost(deps: ShareHostDeps) {
apps: pkg?.requirements.apps.length ?? 0,
},
redacted: record.redacted,
+ ...(anyScrubbed(record.scrubbed) ? { scrubbed: record.scrubbed } : {}),
+ ...(record.secret ? { secret: true } : {}),
+ ...(credit !== undefined ? { author: credit } : {}),
+ ...(record.status === "published" && record.author ? { publishedBy: record.author } : {}),
skipped: record.skipped,
status: record.status,
...(record.link ? { link: record.link } : {}),
@@ -311,7 +353,11 @@ export function createShareHost(deps: ShareHostDeps) {
return card;
};
- function build(target: { scope: "bot"; bot: BotRecord } | { scope: "department"; section: string; bots: readonly BotRecord[] }, routines: readonly Routine[]) {
+ /** The names to take out of a template published under `credit`. */
+ const namesFor = (credit: string | undefined, more: ReadonlyArray<string | undefined> = []) =>
+ personalNames([...(deps.personNames?.() ?? []), ...more], credit);
+
+ function build(target: { scope: "bot"; bot: BotRecord } | { scope: "department"; section: string; bots: readonly BotRecord[] }, routines: readonly Routine[], names: readonly string[]) {
const bots = target.scope === "bot"
? [{ ...target.bot, section: undefined, chiefOfStaff: false }]
: target.bots.filter((bot) => !bot.hidden && (bot.section?.trim() ?? "") === target.section);
@@ -338,6 +384,7 @@ export function createShareHost(deps: ShareHostDeps) {
}
const brief = target.scope === "department" ? deps.brief(target.section)?.trim() : undefined;
const lead = target.scope === "bot" ? target.bot : undefined;
+ let credential = false;
let exported;
try {
exported = createTeamPackageExport({
@@ -345,7 +392,7 @@ export function createShareHost(deps: ShareHostDeps) {
name: lead ? lead.name : target.scope === "department" ? target.section : undefined,
tagline: (lead && firstLine(lead.title || lead.description, 160)) || plainTagline(target.scope),
summary: lead?.description?.trim().slice(0, 2_000) || plainSummary(target.scope),
- authorName: `${productName()} user`,
+ authorName: COMMUNITY_CREDIT,
bots,
groups: target.scope === "bot" ? [] : deps.groups(),
routines: target.scope === "bot" ? routines.filter((routine) => routine.botId === target.bot.id && routine.target !== "room-goal") : routines,
@@ -356,12 +403,15 @@ export function createShareHost(deps: ShareHostDeps) {
avatars,
mcpServers: {},
skipped: skills.skipped,
+ // Connections never travel in a template, so a key in one doesn't keep it from being published.
+ beforeRedaction: (definition) => { credential = scrubTree({ ...definition, connections: undefined }).counts.secrets > 0; },
});
} catch (error) {
if (error instanceof TeamExportError) throw new ShareError(error.message);
throw error;
}
- const { document, redacted } = templateDocument(exported.document, bots, exported.published.keys.bots);
+ const made = templateDocument(exported.document, bots, exported.published.keys.bots);
+ const { document, counts } = scrubbedPackage(made.document, names);
const keyOf = new Map(Object.entries(exported.published.keys.bots).map(([id, key]) => [key, id]));
const avatarsShown: TemplateAvatar[] = document.package.agents.slice(0, 12).map((agent) => {
const bot = bots.find((each) => each.id === keyOf.get(agent.key));
@@ -373,18 +423,19 @@ export function createShareHost(deps: ShareHostDeps) {
...(agent.appearance.mascotBody ? { mascotBody: agent.appearance.mascotBody } : {}),
};
});
- return { document, redacted: redacted + exported.redacted.length, skipped: [...exported.skipped.map(skipWords), ...fileSkips], avatars: avatarsShown };
+ return { document, redacted: made.redacted + exported.redacted.length, scrubbed: shownCounts(counts), secret: credential || counts.secrets > 0,
+ skipped: [...exported.skipped.map(skipWords), ...fileSkips], avatars: avatarsShown };
}
return {
/** Makes (or makes again, in the same folder) the template of a bot or a department. `writer` is the bot whose own
* folder receives it: the bot itself, or the Chief that shares its department; none for the department's Share. */
export(target: { scope: "bot"; bot: BotRecord } | { scope: "department"; section: string; bots: readonly BotRecord[] }, routines: readonly Routine[], writer?: BotRecord): { card: TemplateCard; dir: string; document: PackageDocument } {
- const built = build(target, routines);
const botId = target.scope === "bot" ? target.bot.id : writer?.id;
const section = target.scope === "department" ? target.section : undefined;
const existing = [...records.values()].find((record) => record.status !== "gone" && record.scope === target.scope &&
(target.scope === "bot" ? record.botId === botId : record.section === section && record.botId === botId));
+ const built = build(target, routines, namesFor(existing?.author ?? deps.suggestedCredit?.()));
const id = existing?.id ?? randomBytes(8).toString("hex");
const slug = built.document.package.id;
const dir = botId ? join(deps.botFolder(botId), "templates", slug) : join(deps.dataDir, "share", id, slug);
@@ -401,7 +452,7 @@ export function createShareHost(deps: ShareHostDeps) {
};
records.set(id, record);
const card = update(record, {
- dir, slug, redacted: built.redacted, skipped: built.skipped, avatars: built.avatars,
+ dir, slug, redacted: built.redacted, scrubbed: built.scrubbed, secret: built.secret, skipped: built.skipped, avatars: built.avatars,
status: "draft", error: undefined,
}, built.document);
return { card, dir, document: built.document };
@@ -438,25 +489,33 @@ 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);
- return { slug: record.slug, files: writeShareFolder(folderPackage(record.dir, record.scope), record.scope) };
+ const { document } = scrubbedPackage(folderPackage(record.dir, record.scope), namesFor(record.author ?? deps.suggestedCredit?.()));
+ return { slug: record.slug, files: writeShareFolder(document, record.scope) };
},
- async publish(id: string): Promise<TemplateCard> {
+ /** Publishes to the community repository under `author` ("Published by"; "" for none, left out for the last one
+ * used), with the person's details taken out first. `names` are more of the person's own names to take out. */
+ async publish(id: string, options: { author?: string; names?: ReadonlyArray<string | undefined> } = {}): Promise<TemplateCard> {
const record = records.get(id);
if (!record || record.status === "gone") throw new ShareError("This template was deleted.", 404);
if (record.status === "publishing") return lastCards.get(id) ?? cardOf(record);
- let document: PackageDocument;
+ const credit = options.author ?? record.author ?? "";
+ let document: PackageDocument, counts: ScrubCounts;
try {
- document = folderPackage(record.dir, record.scope);
+ ({ document, counts } = scrubbedPackage(folderPackage(record.dir, record.scope), 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));
+ 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 }, document);
+ update(record, { status: "publishing", error: undefined, author: credit, scrubbed }, 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/team-library.test.ts b/server/team-library.test.ts
index dfea85e42b..2aaa52e079 100644
--- a/server/team-library.test.ts
+++ b/server/team-library.test.ts
@@ -65,6 +65,16 @@ describe("team library", () => {
expect(() => parseTeamCatalog(unsafe)).toThrow("safe catalog path");
});
+ it("keeps who published an entry as one line, and drops a credit it can't show", () => {
+ const entry = catalog.teams[0]!;
+ const credited = (author: unknown) => parseTeamCatalog({ ...catalog, teams: [{ ...entry, author }] }).teams[0]!.author;
+ expect(credited("Jane Doe")).toBe("Jane Doe");
+ expect(credited({ name: " Jane\n Doe " })).toBe("Jane Doe");
+ expect(credited("x".repeat(101))).toBeUndefined();
+ expect(credited(42)).toBeUndefined();
+ expect(parseTeamCatalog(catalog).teams[0]).not.toHaveProperty("author");
+ });
+
it("accepts a catalog of hundreds of published templates", () => {
const entry = catalog.teams[0]!;
const teams = Array.from({ length: 500 }, (_, index) => {
diff --git a/server/team-library.ts b/server/team-library.ts
index 703af9fdb0..3fe384ba7c 100644
--- a/server/team-library.ts
+++ b/server/team-library.ts
@@ -28,6 +28,8 @@ export interface TeamCatalogEntry {
members: number;
skills: string[];
requires: { apps: string[] };
+ /** Who published it ("Published by"), as the template's own frontmatter credits them. */
+ author?: string;
}
export interface TeamCatalog {
@@ -68,6 +70,13 @@ function stringList(value: unknown, field: string, maxItems: number): string[] {
return value.map((item, index) => text(item, `${field}[${index}]`, 100));
}
+/** A catalog entry's credit, as a name or `{ name }`: one line of up to 100 characters, else none. */
+function catalogAuthor(value: unknown): string | undefined {
+ const name = typeof value === "string" ? value : isRecord(value) && typeof value.name === "string" ? value.name : undefined;
+ const line = name?.replace(/[\p{Cc}\p{Cf}]+/gu, " ").replace(/\s+/g, " ").trim();
+ return line && line.length <= 100 ? line : undefined;
+}
+
/** Validate the remotely maintained index before any of it reaches the renderer. */
export function parseTeamCatalog(value: unknown): TeamCatalog {
if (!isRecord(value) || value.format !== "openmaus.catalog" || value.version !== 1) {
@@ -113,6 +122,7 @@ export function parseTeamCatalog(value: unknown): TeamCatalog {
)
: (() => { throw new Error(`${field}.skills is invalid`); })(),
requires: { apps: stringList(requires.apps ?? [], `${field}.requires.apps`, 30) },
+ ...(catalogAuthor(raw.author) ? { author: catalogAuthor(raw.author)! } : {}),
};
});
return {
diff --git a/shared/publish-scrub.test.ts b/shared/publish-scrub.test.ts
new file mode 100644
index 0000000000..bd0ef80cad
--- /dev/null
+++ b/shared/publish-scrub.test.ts
@@ -0,0 +1,90 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { addScrubCounts, emptyScrubCounts, personalNames, scrubText, scrubTree, type ScrubCounts } from "./publish-scrub.ts";
+
+interface Vector { name: string; input: string; names?: string[]; output: string; counts: ScrubCounts }
+const VECTORS = JSON.parse(readFileSync(join(import.meta.dirname, "publish-scrub.vectors.json"), "utf8")) as Vector[];
+
+describe("scrubText", () => {
+ it.each(VECTORS.map((vector) => [vector.name, vector] as const))("%s", (_name, vector) => {
+ const names = vector.names ? personalNames(vector.names) : undefined;
+ const once = scrubText(vector.input, names ? { names } : {});
+ expect(once.text).toBe(vector.output);
+ expect(once.counts).toEqual(vector.counts);
+ const twice = scrubText(once.text, names ? { names } : {});
+ expect(twice.text).toBe(once.text);
+ expect(twice.counts).toEqual(emptyScrubCounts());
+ });
+
+ it("removes the shapes from the submissions that leaked", () => {
+ const leaked = [
+ "Work in /Users/arjunmehta/WorkSpace/clients/northwind before anything else.",
+ "Write the report to /Users/arjunmehta/.openmausbot/workspaces/0b9c3a52-8d61-4f0e-a2b7-5c1e9d4f3a10/reports/q4.md",
+ "Contact [email protected] or +91 98765 43210.",
+ ].join("\n");
+ const { text, counts } = scrubText(leaked);
+ expect(text).not.toMatch(/arjun|northwind-labs|98765/i);
+ expect(text).toContain("~/WorkSpace/clients/northwind");
+ expect(text).toContain("<workspace>/reports/q4.md");
+ expect(counts).toEqual({ paths: 2, emails: 1, phones: 1, names: 0, secrets: 0 });
+ });
+
+ it("leaves a routine's timestamps and ids alone", () => {
+ const routine = "schedule:\n type: once\n at: 1794748391525\nanchorAt: 1794748391525\nkey: routine-7c9e6679\nupdatedAt: 1764060000000";
+ expect(scrubText(routine).text).toBe(routine);
+ });
+
+ it("is quick on long hostile text", () => {
+ const hostile = ["+1 ".repeat(200_000), "/Users/".repeat(100_000), "a@".repeat(200_000), "/.openmausbot/x".repeat(50_000),
+ "-----BEGIN PRIVATE KEY-----\n".repeat(20_000), "Bearer ".repeat(100_000), "C:\\Users\\A B C D ".repeat(50_000)];
+ const started = performance.now();
+ for (const text of hostile) scrubText(text, { names: ["Jane Doe"] });
+ expect(performance.now() - started).toBeLessThan(3_000);
+ });
+});
+
+describe("personalNames", () => {
+ it("keeps real names and drops common words, short words, addresses and the credit", () => {
+ expect(personalNames(["root", "node", "omb", "bob", "[email protected]", " Jane Doe ", "janedoe", "", undefined, null])).toEqual(["Jane Doe", "janedoe"]);
+ expect(personalNames(["Jane Doe", "janedoe"], "jane doe")).toEqual(["janedoe"]);
+ expect(personalNames(["Jane Doe", "Jane Doe", "JANE DOE"])).toHaveLength(1);
+ });
+
+ it("matches a name as a whole word, in any letter case, with accents", () => {
+ const names = personalNames(["José Núñez"]);
+ expect(scrubText("josé núñez wrote this; JoséNúñez did not", { names }).text).toBe("<name> wrote this; JoséNúñez did not");
+ });
+
+ it("never treats a name as a pattern", () => {
+ const names = personalNames(["a.b.c (x)"]);
+ expect(scrubText("a.b.c (x) and aXbXc (x)", { names }).text).toBe("<name> and aXbXc (x)");
+ });
+});
+
+describe("scrubTree", () => {
+ it("scrubs every string in a copy and adds up what it found", () => {
+ const input = {
+ name: "Scout",
+ agents: [{ key: "scout", description: "Lives in /home/bob", appearance: { avatar: { data: "data:image/png;base64,/Users/bob+AIza" + "A".repeat(40) } } }],
+ skills: { entries: [{ name: "x", instructions: "Mail [email protected]", files: [{ path: "run.sh", content: "cd /Users/bob" }] }] },
+ setupMinutes: 5,
+ tags: ["/Users/bob/x", "plain"],
+ };
+ const { value, counts } = scrubTree(input);
+ expect(value.agents[0]!.description).toBe("Lives in ~");
+ expect(value.agents[0]!.appearance.avatar.data).toBe(input.agents[0]!.appearance.avatar.data);
+ expect(value.skills.entries[0]!.instructions).toBe("Mail <email>");
+ expect(value.skills.entries[0]!.files[0]!.content).toBe("cd /Users/bob");
+ expect(value.tags).toEqual(["~/x", "plain"]);
+ expect(value.setupMinutes).toBe(5);
+ expect(input.agents[0]!.description).toBe("Lives in /home/bob");
+ expect(counts).toEqual({ paths: 2, emails: 1, phones: 0, names: 0, secrets: 0 });
+ });
+
+ it("adds counts field by field", () => {
+ expect(addScrubCounts({ paths: 1, emails: 2, phones: 3, names: 4, secrets: 5 }, { paths: 1, emails: 1, phones: 1, names: 1, secrets: 1 }))
+ .toEqual({ paths: 2, emails: 3, phones: 4, names: 5, secrets: 6 });
+ });
+});
diff --git a/shared/publish-scrub.ts b/shared/publish-scrub.ts
new file mode 100644
index 0000000000..737989588a
--- /dev/null
+++ b/shared/publish-scrub.ts
@@ -0,0 +1,209 @@
+// What a template loses before it is published to a public repository: home-folder paths, the app's own data folders,
+// email addresses, phone numbers, key- and token-shaped values, and the publisher's own names. Deterministic and
+// idempotent: scrubbing scrubbed text changes nothing. No imports: the app scrubs before anything leaves the computer
+// and the MausBot Admin scrubs again before it commits, from the same file, tested on the same vectors.
+
+/** How many different values of each kind were taken out. */
+export interface ScrubCounts {
+ /** Home folders and the app's data folders. */
+ paths: number;
+ emails: number;
+ phones: number;
+ /** The publisher's own names: their computer's user name, and their profile name when it isn't their credit. */
+ names: number;
+ /** Key- and token-shaped values. A template holding one is never published, even scrubbed. */
+ secrets: number;
+}
+
+export interface ScrubOptions {
+ /** Whole words or phrases to replace with `<name>`; pass them through `personalNames` first. */
+ names?: readonly string[];
+}
+
+export const SCRUB_MARKS = { path: "~", workspace: "<workspace>", email: "<email>", phone: "<phone>", name: "<name>", secret: "<secret>" } as const;
+
+export const emptyScrubCounts = (): ScrubCounts => ({ paths: 0, emails: 0, phones: 0, names: 0, secrets: 0 });
+
+export function addScrubCounts(a: ScrubCounts, b: ScrubCounts): ScrubCounts {
+ return { paths: a.paths + b.paths, emails: a.emails + b.emails, phones: a.phones + b.phones, names: a.names + b.names, secrets: a.secrets + b.secrets };
+}
+
+/** The values taken out so far, by kind: the same address in two places counts once. */
+type Found = { [kind in keyof ScrubCounts]: Set<string> };
+const newFound = (): Found => ({ paths: new Set(), emails: new Set(), phones: new Set(), names: new Set(), secrets: new Set() });
+const countsOf = (found: Found): ScrubCounts =>
+ ({ paths: found.paths.size, emails: found.emails.size, phones: found.phones.size, names: found.names.size, secrets: found.secrets.size });
+const take = (found: Found, kind: keyof ScrubCounts, value: string, mark: string) => { found[kind].add(value); return mark; };
+
+// ---- Secrets -------------------------------------------------------------------------------------------------------
+
+/** Only shapes that are unmistakably a credential, so instructions that talk about keys keep their words. */
+const SECRET_SHAPES: RegExp[] = [
+ /\bsk-(?:ant-|proj-|live-|test-)?[A-Za-z0-9_-]{16,}/g,
+ /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/g,
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
+ /\bgl(?:pat|dt|rt)-[A-Za-z0-9_-]{20,}/g,
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}/g,
+ /\bxapp-\d-[A-Za-z0-9-]{20,}/g,
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
+ /\bAIza[0-9A-Za-z_-]{30,}/g,
+ /\bxai-[A-Za-z0-9_-]{20,}/g,
+ /\bgsk_[A-Za-z0-9]{40,}/g,
+ /\bhf_[A-Za-z0-9]{30,}/g,
+ /\bnpm_[A-Za-z0-9]{30,}/g,
+ /\bwhsec_[A-Za-z0-9_-]{20,}/g,
+ /\bom[dg]_[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g,
+ /\bbak_[A-Za-z0-9_-]{20,}/g,
+];
+/** The BEGIN line, the base64 lines under it and the END line when there is one: linear, with or without an END. */
+const PRIVATE_KEY = /-----BEGIN [A-Z ]{0,40}PRIVATE KEY-----(?:\r?\n[A-Za-z0-9+/=]{16,})*(?:\r?\n-----END [A-Z ]{0,40}PRIVATE KEY-----)?/g;
+/** A bearer token with letters and digits in it: "Bearer YOUR_TOKEN" in a skill's example stays. */
+const BEARER = /\b(Bearer\s+)([A-Za-z0-9._~+/=-]{20,})(?![A-Za-z0-9._~+/=-])/g;
+
+function scrubSecrets(text: string, found: Found): string {
+ let out = text.replace(PRIVATE_KEY, (match) => take(found, "secrets", match, SCRUB_MARKS.secret));
+ for (const shape of SECRET_SHAPES) out = out.replace(shape, (match) => take(found, "secrets", match, SCRUB_MARKS.secret));
+ return out.replace(BEARER, (match, lead: string, token: string) =>
+ /\d/.test(token) && /[A-Za-z]/.test(token) ? `${lead}${take(found, "secrets", token, SCRUB_MARKS.secret)}` : match);
+}
+
+// ---- Paths ---------------------------------------------------------------------------------------------------------
+
+/** 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. */
+const SEG = String.raw`[^\s\\/'"\`<>()\[\]{}|,;:*?]+`;
+/** A Windows user folder's name: one word, or "First Last" when a separator follows it. */
+const WIN_NAME = String.raw`(?:[A-Za-z0-9._-]{1,32}(?: [A-Z][A-Za-z0-9._-]{0,31}){1,2}(?=${SEP})|[A-Za-z0-9._-]{0,63}[A-Za-z0-9_-])`;
+/** Where a path starts: not inside a longer path or a web address (`example.com/home/about` keeps its path). */
+const PATH_START = String.raw`(?:(?<=file://)|(?<![A-Za-z0-9_.~\-\\/]))`;
+/** Folders under /Users and /home that belong to no one person. */
+const SHARED_HOMES = new Set(["shared", "linuxbrew", "guest"]);
+
+/** A path through the app's data folder (`.openmausbot`, `.openmausbot-profiles`, …) to `workspaces/<bot>` or
+ * `task-workspaces/<bot>/<conversation>`, up to 3 folders between them. */
+const WORKSPACE = new RegExp(
+ `(?:${PATH_START}(?:[A-Za-z]:${SEP}[Uu]sers${SEP}${WIN_NAME}|~|\\$HOME|%USERPROFILE%|[A-Za-z]:)?(?:${SEP}${SEG}){0,8}?)?` +
+ `${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");
+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));
+ 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);
+ });
+ return out.replace(MAC_LINUX_HOME, (match, _root: string, name: string) =>
+ SHARED_HOMES.has(name.toLowerCase()) ? match : take(found, "paths", match, SCRUB_MARKS.path));
+}
+
+// ---- 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;
+/** 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"]);
+const keepEmail = (local: string, domain: string, ending: string) => {
+ const host = domain.toLowerCase(), user = local.toLowerCase();
+ return FILE_ENDINGS.has(ending.toLowerCase()) || user === "git" || /^no-?reply$/.test(user) || host.endsWith("noreply.github.com")
+ || /(?:^|\.)example\.(?:com|org|net)$/.test(host) || /\.(?:example|test|invalid|localhost)$/.test(host);
+};
+
+/** `+` and a country code, then groups split by a space, dot or dash (8 to 15 digits in all). */
+const PHONE_INTERNATIONAL = /(?<![A-Za-z0-9_+/=%.-])\+\d{1,4}(?:[ .-]?\(\d{1,4}\))?(?:[ .-]\d{1,8}){1,5}(?![A-Za-z0-9_]|[.-]\d)/g;
+/** `+` and 10 to 15 digits with nothing between them. */
+const PHONE_BARE = /(?<![A-Za-z0-9_+/=%.-])\+\d{10,15}(?![A-Za-z0-9_]|[.-]\d)/g;
+/** (415) 555-0132, 415-555-0132, 415.555.0132. */
+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;
+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));
+ 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);
+ return out.replace(PHONE_TRUNK, (match: string) => digitCount(match) < 10 ? match : phone(match));
+}
+
+// ---- The publisher's own names -------------------------------------------------------------------------------------
+
+/** Names too common to replace everywhere: a Cloud home's user, a role, a word the template's text needs. */
+const COMMON_NAMES = new Set(["root", "admin", "administrator", "user", "users", "guest", "ubuntu", "debian", "fedora", "centos", "node", "runner",
+ "app", "apps", "home", "mac", "macbook", "owner", "default", "test", "tester", "dev", "developer", "ec2-user", "pi", "vagrant", "docker", "omb",
+ "mausbot", "openmausbot", "shared", "public", "community", "work", "team", "bot", "bots", "agent", "system", "linuxbrew", "codespace", "vscode",
+ "coder", "jovyan", "server", "local", "cloud", "workspace", "email", "phone", "secret", "name", "person", "human", "mausbot user"]);
+
+/** The names worth replacing in a template: trimmed, not an address, not a common word, not the credit itself. A single
+ * word needs 4 characters; longest first, so a full name goes before a part of it. */
+export function personalNames(candidates: ReadonlyArray<string | null | undefined>, credit?: string): string[] {
+ const kept = new Map<string, string>();
+ const creditKey = credit?.trim().replace(/\s+/g, " ").toLowerCase();
+ for (const raw of candidates) {
+ const name = raw?.trim().replace(/\s+/g, " ") ?? "";
+ const key = name.toLowerCase();
+ if (name.length < 3 || name.length > 64 || /[@\r\n<>]/.test(name) || COMMON_NAMES.has(key) || key === creditKey) continue;
+ if (!name.includes(" ") && name.length < 4) continue;
+ if (!/[\p{L}]/u.test(name)) continue;
+ kept.set(key, name);
+ }
+ return [...kept.values()].sort((a, b) => b.length - a.length || a.localeCompare(b));
+}
+
+const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+function scrubNames(text: string, names: readonly string[], found: Found): string {
+ let out = text;
+ for (const name of names) {
+ const words = name.split(" ").map(escapeRegExp).join("\\s+");
+ // Not inside a longer word or an identifier: `jane-helper` keeps its name.
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}_-])${words}(?![\\p{L}\\p{N}_-])`, "giu");
+ out = out.replace(pattern, () => take(found, "names", name.toLowerCase(), SCRUB_MARKS.name));
+ }
+ return out;
+}
+
+// ---- Text and trees ------------------------------------------------------------------------------------------------
+
+/** One text with every rule applied, in a fixed order: secrets, paths, emails and phone numbers, then names. Only the
+ * matched spans change; code fences, Markdown and YAML around them stay as they were. */
+export function scrubText(text: string, options: ScrubOptions = {}): { text: string; counts: ScrubCounts } {
+ const found = newFound();
+ return { text: scrubInto(text, options, found), counts: countsOf(found) };
+}
+
+function scrubInto(text: string, options: ScrubOptions, found: Found): string {
+ if (!text) return text;
+ let out = scrubSecrets(text, found);
+ out = scrubPaths(out, found);
+ out = scrubContacts(out, found);
+ return options.names?.length ? scrubNames(out, options.names, found) : out;
+}
+
+/** A key, an id or a skill's name: the person's names are never taken out of one, which would break it. */
+const IDENTIFIER = /^[a-z0-9][a-z0-9_-]{0,63}$/;
+
+/** Every string in a JSON-like value, scrubbed, in a copy. Picture bytes (`avatar.data`) and the files beside a skill
+ * (`files[].content`) are left as they are. */
+export function scrubTree<T>(value: T, options: ScrubOptions = {}): { value: T; counts: ScrubCounts } {
+ const found = newFound();
+ const walk = (node: unknown, key: string, parentKey: string): unknown => {
+ if (typeof node === "string") {
+ if ((key === "data" && parentKey === "avatar") || (key === "content" && parentKey === "files[]")) return node;
+ return scrubInto(node, IDENTIFIER.test(node) ? { ...options, names: [] } : options, found);
+ }
+ if (Array.isArray(node)) return node.map((item) => walk(item, `${key}[]`, key));
+ if (node && typeof node === "object" && Object.getPrototypeOf(node) === Object.prototype) {
+ return Object.fromEntries(Object.entries(node as Record<string, unknown>).map(([name, item]) => [name, walk(item, name, key)]));
+ }
+ return node;
+ };
+ return { value: walk(value, "", "") as T, counts: countsOf(found) };
+}
diff --git a/shared/publish-scrub.vectors.json b/shared/publish-scrub.vectors.json
new file mode 100644
index 0000000000..04ccf13fa6
--- /dev/null
+++ b/shared/publish-scrub.vectors.json
@@ -0,0 +1,249 @@
+[
+ {
+ "name": "a macOS home folder with a project under it",
+ "input": "Read /Users/janedoe/WorkSpace/acme-launch/notes.md first.",
+ "output": "Read ~/WorkSpace/acme-launch/notes.md first.",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "a Linux home folder, alone and in a path",
+ "input": "Logs go to /home/bob/logs; cd /home/bob",
+ "output": "Logs go to ~/logs; cd ~",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "the app's workspace folder of a bot",
+ "input": "Files live in /Users/janedoe/.openmausbot/workspaces/3f2b1c9e-1a2b-4c3d-9e8f-0123456789ab/reports/weekly.md",
+ "output": "Files live in <workspace>/reports/weekly.md",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "a profile data folder under ~",
+ "input": "在 ~/.openmausbot-profiles/default/workspaces/d1bd6e16-5403-4d90-baf1-2afa2b87a61b/ashare-data 使用 python3",
+ "output": "在 <workspace>/ashare-data 使用 python3",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "a conversation's task folder",
+ "input": "Saved to /home/omb/.openmausbot/task-workspaces/bot-1234/7c9e6679-7425-40de-944b-e07fc1f90ae7/out.csv",
+ "output": "Saved to <workspace>/out.csv",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "Windows homes, with backslashes, forward slashes and a two-word name",
+ "input": "C:\\Users\\John Smith\\Documents\\plan.docx, C:/Users/bob/x and c:\\users\\Ann\\Desktop",
+ "output": "~\\Documents\\plan.docx, ~/x and ~\\Desktop",
+ "counts": {
+ "paths": 3,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "a Windows path as a quoted YAML string writes it",
+ "input": "folder: \"C:\\\\Users\\\\jane\\\\proj\\\\src\"",
+ "output": "folder: \"~\\\\proj\\\\src\"",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "a Windows workspace folder",
+ "input": "C:\\Users\\Jane\\.openmausbot\\workspaces\\bot-123456\\file.md",
+ "output": "<workspace>\\file.md",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "shared homes and web addresses keep their paths",
+ "input": "See /Users/Shared/assets, /home/linuxbrew/.linuxbrew/bin and https://example.com/home/about or https://github.com/Users/x",
+ "output": "See /Users/Shared/assets, /home/linuxbrew/.linuxbrew/bin and https://example.com/home/about or https://github.com/Users/x",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "a file link",
+ "input": "Open file:///Users/jane/report.html",
+ "output": "Open file://~/report.html",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "emails go; git remotes, retina file names and example addresses stay",
+ "output": "Mail <email> or <email>; clone [email protected]:org/repo.git; [email protected]; [email protected]; [email protected]",
+ "counts": {
+ "paths": 0,
+ "emails": 2,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "phone numbers in clear formats",
+ "input": "Call +1 (415) 555-0132, 415-555-0132, (415) 555-0132, 415.555.0132, +44 20 7946 0958, +91 98765 43210, +919876543210 or 020 7946 0958.",
+ "output": "Call <phone>, <phone>, <phone>, <phone>, <phone>, <phone>, <phone> or <phone>.",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 5,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "timestamps, dates, ids, versions and addresses are not phone numbers",
+ "input": "anchorAt: 1794748391525\nat: 2026-11-25T10:00:00.000Z\nip 192.168.1.100, v1.2.3, 10.0.0.1:8080\nid 550e8400-e29b-41d4-a716-446655440000\ncron: 0 9 * * 1-5\ncount: 12,345,678\nscore +3.5 and x+1234567890\norder 2026-1125-0001",
+ "output": "anchorAt: 1794748391525\nat: 2026-11-25T10:00:00.000Z\nip 192.168.1.100, v1.2.3, 10.0.0.1:8080\nid 550e8400-e29b-41d4-a716-446655440000\ncron: 0 9 * * 1-5\ncount: 12,345,678\nscore +3.5 and x+1234567890\norder 2026-1125-0001",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "secrets of common shapes",
+ "input": "ANTHROPIC_API_KEY=sk-ant-api03-abcdefghijklmnopqrstuvwxyz012345\ntoken ghp_abcdefghijklmnopqrstuvwxyz0123456789\npat github_pat_11ABCDEFG0123456789_abcdefghijklmnop\nslack xoxb-1234567890-abcdefghijkl\naws AKIAIOSFODNN7EXAMPLE\ngoogle AIzaSyA-abcdefghijklmnopqrstuvwxyz12345",
+ "output": "ANTHROPIC_API_KEY=<secret>\ntoken <secret>\npat <secret>\nslack <secret>\naws <secret>\ngoogle <secret>",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 6
+ }
+ },
+ {
+ "name": "a bearer token goes; a placeholder stays",
+ "input": "Authorization: Bearer YOUR_ACCESS_TOKEN_HERE\nAuthorization: Bearer abcd1234efgh5678ijkl9012mnop",
+ "output": "Authorization: Bearer YOUR_ACCESS_TOKEN_HERE\nAuthorization: Bearer <secret>",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 1
+ }
+ },
+ {
+ "name": "a private key block",
+ "input": "Key:\n-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAabcdefghijklmnopqrstuv\nabcdefghijklmnopqrstuvwxyz0123456789+/\n-----END RSA PRIVATE KEY-----\nDone.",
+ "output": "Key:\n<secret>\nDone.",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 1
+ }
+ },
+ {
+ "name": "words about keys stay",
+ "input": "Ask the person for their API key, then set the token in Settings. Never paste a password here.",
+ "output": "Ask the person for their API key, then set the token in Settings. Never paste a password here.",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "code fences and Markdown around a path stay as they were",
+ "input": "## Setup\n\n```bash\ncd /Users/janedoe/projects/site\nnpm run build\n```\n\n- Done by **/Users/janedoe**",
+ "output": "## Setup\n\n```bash\ncd ~/projects/site\nnpm run build\n```\n\n- Done by **~**",
+ "counts": {
+ "paths": 1,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "the person's own names, whole words only",
+ "input": "Written by Jane Doe (janedoe). Janedoes and jane stay.",
+ "names": [
+ "janedoe",
+ "Jane Doe"
+ ],
+ "output": "Written by <name> (<name>). Janedoes and jane stay.",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 2,
+ "secrets": 0
+ }
+ },
+ {
+ "name": "the publisher's markers are not scrubbed again",
+ "input": "~/x <workspace>/y <email> <phone> <name> <secret> «redacted 40 chars»",
+ "names": [
+ "janedoe"
+ ],
+ "output": "~/x <workspace>/y <email> <phone> <name> <secret> «redacted 40 chars»",
+ "counts": {
+ "paths": 0,
+ "emails": 0,
+ "phones": 0,
+ "names": 0,
+ "secrets": 0
+ }
+ }
+]
diff --git a/src/components/TeamLibraryPanel.tsx b/src/components/TeamLibraryPanel.tsx
index 7b53877560..a715ef3a42 100644
--- a/src/components/TeamLibraryPanel.tsx
+++ b/src/components/TeamLibraryPanel.tsx
@@ -12,6 +12,7 @@ import { ArrowLeft, Check, ExternalLink, Github, Loader2, Plus, Search, Users, X
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { catalogCopy, catalogMatches, type TeamCatalog, type TeamCatalogEntry } from "@/lib/team-catalog";
+import { creditShown } from "@/lib/template-share";
import { ReadyBotGallery } from "./ReadyBotGallery";
import { OrgLibraryTab } from "./TeamLibraryPanelOrg";
@@ -350,12 +351,14 @@ export function TeamLibraryPanel({
<div className="grid grid-cols-1 gap-x-10 md:grid-cols-2">
{visibleTeams.map((entry) => {
const copy = catalogCopy(entry);
+ const credit = creditShown(entry.author);
return (
<article key={entry.slug} className="flex min-h-[104px] items-center gap-3 border-b border-hairline/35 px-1 py-4">
<TeamGlyph />
<div className="min-w-0 flex-1">
<h3 className="truncate text-[13px] font-medium text-ink">{copy.name}</h3>
<p className="mt-0.5 truncate text-[13px] text-ink-secondary">{copy.outcome ?? copy.summary}</p>
+ {credit && <p dir="auto" data-catalog-published-by className="mt-0.5 truncate text-[12px] text-ink-tertiary">{t("template.publishedBy", { name: credit })}</p>}
<p className="mt-1 truncate text-[12px] text-ink-tertiary">
{entry.members === 1 ? t("template.botsOne") : t("template.botsMany", { count: entry.members })}
{entry.skills.length > 0 && ` · ${entry.skills.length === 1 ? t("template.skillsOne") : t("template.skillsMany", { count: entry.skills.length })}`}
diff --git a/src/components/TemplateCard.test.ts b/src/components/TemplateCard.test.ts
index 1c33b02ed9..1fc8aea241 100644
--- a/src/components/TemplateCard.test.ts
+++ b/src/components/TemplateCard.test.ts
@@ -95,13 +95,51 @@ describe("a template's chat card", () => {
const { container, unmount } = render(draft);
try {
button(container, "Publish")!.click();
- await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/share/tpl1/publish", { method: "POST", body: "{}" }));
+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/share/tpl1/publish", { method: "POST", body: JSON.stringify({ author: "" }) }));
await vi.waitFor(() => expect(container.textContent).toContain("Copy link"));
button(container, "View on GitHub")!.click();
expect(openExternalLink).toHaveBeenCalledWith("https://github.com/x/y/tree/abc/teams/quill");
} finally { unmount(); }
});
+ it("says what was taken out before publishing, in one line", () => {
+ expect(shown({ ...draft, scrubbed: { paths: 3, emails: 1, phones: 0, names: 0 } })).toContain("We removed 3 local paths and 1 email before publishing");
+ expect(shown({ ...draft, scrubbed: { paths: 1, emails: 0, phones: 2, names: 1 } })).toContain("We removed 1 local path, 2 phone numbers, and 1 mention of your name before publishing");
+ expect(shown(draft)).not.toContain("We removed");
+ });
+
+ it("refuses to publish a template with a key in it, in one line", () => {
+ const { container, unmount } = render({ ...draft, secret: true, status: "failed", error: "This template holds something that looks like a key or token." });
+ try {
+ expect(button(container, "Try again")!.disabled).toBe(true);
+ expect(container.querySelector("[data-template-secret]")!.textContent).toBe("It holds a key or token, so it can't be published. Remove it from the bot, then update the template.");
+ expect(container.textContent).not.toContain("This template holds something");
+ } finally { unmount(); }
+ });
+
+ it("publishes under the name in Published by, which starts as the suggested one and can be changed or cleared", async () => {
+ api.mockResolvedValue({ ...draft, status: "published", link: "https://github.com/x/y/tree/abc/teams/quill", publishedBy: "Sam Rivera" });
+ const { container, unmount } = render({ ...draft, author: "Sam" });
+ try {
+ const field = container.querySelector<HTMLInputElement>("[data-template-author]")!;
+ expect(field.value).toBe("Sam");
+ expect(container.querySelector(`label[for="${field.id}"]`)!.textContent).toBe("Published by");
+ expect(field.placeholder).toBe("Community");
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ flushSync(() => { setter.call(field, " Sam Rivera "); field.dispatchEvent(new Event("input", { bubbles: true })); });
+ button(container, "Publish")!.click();
+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/share/tpl1/publish", { method: "POST", body: JSON.stringify({ author: "Sam Rivera" }) }));
+ await vi.waitFor(() => expect(container.querySelector("[data-template-published-by]")?.textContent).toBe("Published by Sam Rivera"));
+ expect(container.querySelector("[data-template-author]")).toBeNull();
+ } finally { unmount(); }
+ });
+
+ it("names nobody on a published card credited to the community", () => {
+ expect(shown({ ...draft, status: "published", link: "https://github.com/x/y/tree/a/teams/q", publishedBy: "Community" })).not.toContain("Published by");
+ expect(shown({ ...draft, status: "published", link: "https://github.com/x/y/tree/a/teams/q", publishedBy: "MausBot user" })).not.toContain("Published by");
+ expect(shown({ ...draft, publishedBy: "Sam" })).not.toContain("Published by Sam");
+ });
+
it("turns a refused publish into the failed state with the server's sentence", async () => {
api.mockRejectedValueOnce(new Error("The community service is busy. Try again in a minute."));
const { container, unmount } = render(draft);
diff --git a/src/components/TemplateCard.tsx b/src/components/TemplateCard.tsx
index 3eda62ec01..dc9b0ddc9b 100644
--- a/src/components/TemplateCard.tsx
+++ b/src/components/TemplateCard.tsx
@@ -11,7 +11,7 @@ import { openExternalLink } from "@/lib/app-links";
import { cn } from "@/lib/cn";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
-import { addToTeamTemplates, askBot, countsLine, deleteTemplate, githubConnection, publishTemplate, publishToRepo, saveTemplateFolder, templateDetails } from "@/lib/template-share";
+import { addToTeamTemplates, askBot, countsLine, creditShown, deleteTemplate, githubConnection, publishTemplate, publishToRepo, saveTemplateFolder, scrubbedLine, templateDetails } from "@/lib/template-share";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { useModalDialog } from "@/hooks/use-modal-dialog";
import { useStore, type Message } from "@/state/store";
@@ -54,9 +54,11 @@ export function TemplateFaces({ avatars, size = 32 }: { avatars: readonly Templa
);
}
-/** Faces, name, status, one line, counts and the promise that nothing private travels. */
+/** Faces, name, status, one line, counts, who published it and the promise that nothing private travels. */
export function TemplateCardBody({ card }: { card: TemplateCard }) {
const counts = countsLine(card);
+ const scrubbed = scrubbedLine(card);
+ const publishedBy = card.status === "published" ? creditShown(card.publishedBy) : null;
return (
<div data-template-status={card.status} className="flex min-w-0 items-start gap-3">
<TemplateFaces avatars={card.avatars} />
@@ -70,7 +72,9 @@ export function TemplateCardBody({ card }: { card: TemplateCard }) {
</div>
{card.tagline && <p dir="auto" className="mt-0.5 truncate text-[13px] text-ink-secondary" title={card.tagline}>{card.tagline}</p>}
{counts && <p className="mt-0.5 text-[12px] text-ink-tertiary">{counts}</p>}
+ {publishedBy && <p dir="auto" data-template-published-by className="mt-0.5 truncate text-[12px] text-ink-tertiary">{t("template.publishedBy", { name: publishedBy })}</p>}
<p className="mt-0.5 text-[12px] text-ink-tertiary">{t("template.neverShared")}</p>
+ {scrubbed && <p data-template-scrubbed className="mt-0.5 text-[12px] text-ink-tertiary">{scrubbed}</p>}
{card.redacted > 0 && <p className="mt-0.5 text-[12px] text-ink-tertiary">{card.redacted === 1 ? t("template.redactedOne") : t("template.redactedMany", { count: card.redacted })}</p>}
{card.skipped.length > 0 && <p dir="auto" className="mt-0.5 text-[12px] text-ink-tertiary">{t("template.skipped", { list: card.skipped.join(", ") })}</p>}
</div>
@@ -85,7 +89,9 @@ export function useTemplateActions(initial: TemplateCard) {
const [error, setError] = useState("");
const [saved, setSaved] = useState<string | null>(null);
const [teamNote, setTeamNote] = useState<string | null>(null);
+ const [author, setAuthor] = useState(initial.author ?? "");
useEffect(() => setCard(initial), [initial]);
+ useEffect(() => setAuthor(initial.author ?? ""), [initial.id, initial.author]);
const run = async (kind: NonNullable<typeof busy>, work: () => Promise<void>) => {
if (busy) return;
setBusy(kind);
@@ -99,7 +105,7 @@ export function useTemplateActions(initial: TemplateCard) {
}
};
return {
- card, busy, error, saved, teamNote,
+ card, busy, error, saved, teamNote, author, setAuthor,
/** Adds it to the Team Cloud's own templates, replacing one of the same name there. */
addToTeam: (team: string) => run("team", async () => {
setTeamNote(null);
@@ -109,7 +115,7 @@ export function useTemplateActions(initial: TemplateCard) {
publish: () => run("publish", async () => {
setCard((current) => ({ ...current, status: "publishing", error: undefined }));
try {
- setCard(await publishTemplate(card.id));
+ setCard(await publishTemplate(card.id, author.trim()));
} catch (cause) {
setCard((current) => ({ ...current, status: "failed", error: cause instanceof Error ? cause.message : undefined }));
}
@@ -146,12 +152,14 @@ export function TemplateButtons({ actions, primary, view, extra }: {
}) {
const { card, busy } = actions;
if (card.status === "gone") return null;
+ const publishable = !card.fallback && !(card.status === "published" && card.link);
const saveButton = (
<button type="button" data-template-save onClick={() => void actions.save()} disabled={busy !== null} className={cn(card.fallback ? ASK_PRIMARY_BUTTON : cn(ASK_CHIP, ASK_CHIP_IDLE))}>
{busy === "save" ? <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" /> : <FolderDown size={14} aria-hidden="true" />}{t("template.saveFolder")}
</button>
);
- return (
+ return (<>
+ {publishable && <PublishedByField actions={actions} />}
<div className="mt-2.5 flex flex-wrap items-center gap-1.5">
{card.fallback ? <>
{saveButton}
@@ -164,13 +172,27 @@ export function TemplateButtons({ actions, primary, view, extra }: {
<ArrowUpRight size={14} aria-hidden="true" />{view.label}
</button>}
</> : (
- <button type="button" data-template-publish onClick={() => void actions.publish()} disabled={busy !== null || card.status === "publishing"} className={ASK_PRIMARY_BUTTON}>
+ <button type="button" data-template-publish onClick={() => void actions.publish()} disabled={busy !== null || card.status === "publishing" || card.secret === true} className={ASK_PRIMARY_BUTTON}>
{card.status === "publishing" ? <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" /> : <Upload size={14} aria-hidden="true" />}
{card.status === "failed" ? t("common.tryAgain") : primary}
</button>
)}
{extra}
</div>
+ </>);
+}
+
+/** The one field Publish has: the name the template is credited to, empty for "Community". */
+function PublishedByField({ actions }: { actions: TemplateActions }) {
+ const id = useId();
+ const locked = actions.busy !== null || actions.card.status === "publishing";
+ return (
+ <div className="mt-2.5 flex min-w-0 items-center gap-2">
+ <label htmlFor={id} className="shrink-0 text-[12px] text-ink-secondary">{t("template.publishedByLabel")}</label>
+ <input id={id} data-template-author dir="auto" value={actions.author} maxLength={100} disabled={locked} spellCheck={false} autoComplete="name"
+ onChange={(event) => actions.setAuthor(event.target.value)} placeholder={t("template.publishedByEmpty")}
+ className="h-7 min-w-0 flex-1 rounded-lg border border-hairline bg-inset px-2 text-[12px] text-ink focus:border-focus focus:outline-none disabled:opacity-60" />
+ </div>
);
}
@@ -179,7 +201,8 @@ export function TemplateNotes({ actions }: { actions: TemplateActions }) {
const { card, error, saved, teamNote } = actions;
return <>
{card.fallback && <p className="mt-1.5 text-[12px] text-ink-secondary">{t(card.fallback === "sign_in" ? "template.signInToPublish" : "template.publishUnavailable")}</p>}
- {card.status === "failed" && card.error && <p role="alert" dir="auto" className="mt-1.5 text-[12px] text-danger">{card.error}</p>}
+ {card.secret && card.status !== "gone" && card.status !== "published" && !card.fallback && <p role="alert" data-template-secret className="mt-1.5 text-[12px] text-danger">{t("template.secretFound")}</p>}
+ {card.status === "failed" && card.error && !card.secret && <p role="alert" dir="auto" className="mt-1.5 text-[12px] text-danger">{card.error}</p>}
{error && <p role="alert" dir="auto" className="mt-1.5 text-[12px] text-danger">{error}</p>}
{saved && <p role="status" dir="auto" className="mt-1.5 truncate text-[12px] text-ink-secondary" title={saved}>{t("template.savedTo", { path: saved })}</p>}
{teamNote && <p role="status" dir="auto" className="mt-1.5 text-[12px] text-ink-secondary">{teamNote}</p>}
diff --git a/src/lib/team-catalog.ts b/src/lib/team-catalog.ts
index 1897b634a8..f002967df4 100644
--- a/src/lib/team-catalog.ts
+++ b/src/lib/team-catalog.ts
@@ -17,6 +17,8 @@ export interface TeamCatalogEntry {
members: number;
skills: string[];
requires: { apps: string[] };
+ /** Who published it. */
+ author?: string;
}
export interface TeamCatalog {
diff --git a/src/lib/template-share.test.ts b/src/lib/template-share.test.ts
index 0ba5bda5fd..4181915954 100644
--- a/src/lib/template-share.test.ts
+++ b/src/lib/template-share.test.ts
@@ -2,7 +2,7 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
-import { addedLine, countsLine, folderFiles, TEMPLATE_FOLDER_MAX_BYTES } from "./template-share";
+import { addedLine, countsLine, creditShown, folderFiles, scrubbedLine, TEMPLATE_FOLDER_MAX_BYTES } from "./template-share";
import { templateDetailsOf } from "./template-details";
const fixture = (name: string) => JSON.parse(readFileSync(join(import.meta.dirname, "..", "..", "shared", "package-fixtures", name), "utf8"));
@@ -16,6 +16,18 @@ describe("a template's words", () => {
expect(addedLine({ appsToConnect: 0 })).toBe("Added");
expect(addedLine({ appsToConnect: 3 })).toBe("Added · 3 apps to connect");
});
+
+ it("says what was taken out in one sentence, and nothing when nothing was", () => {
+ expect(scrubbedLine({ scrubbed: { paths: 3, emails: 1, phones: 0, names: 0 } })).toBe("We removed 3 local paths and 1 email before publishing");
+ expect(scrubbedLine({ scrubbed: { paths: 0, emails: 2, phones: 1, names: 0 } })).toBe("We removed 2 emails and 1 phone number before publishing");
+ expect(scrubbedLine({ scrubbed: { paths: 0, emails: 0, phones: 0, names: 0 } })).toBe("");
+ expect(scrubbedLine({})).toBe("");
+ });
+
+ it("shows a credit only when it names somebody", () => {
+ expect(creditShown(" Jane Doe ")).toBe("Jane Doe");
+ for (const nobody of [undefined, "", " ", "Community", "MausBot community", "MausBot user", "mausbot USER"]) expect(creditShown(nobody)).toBeNull();
+ });
});
describe("a folder chosen in a browser", () => {
diff --git a/src/lib/template-share.ts b/src/lib/template-share.ts
index 0b46a65525..f3b789e5b2 100644
--- a/src/lib/template-share.ts
+++ b/src/lib/template-share.ts
@@ -1,6 +1,6 @@
import type { TeamTemplate, TemplateCard, TemplateDetails, TemplateRepoPublish } from "../../shared/share-card";
import { SKILL_FILE_LIMITS, skillFilePathProblem } from "../../shared/skill-files";
-import { t } from "./i18n";
+import { activeLocale, t } from "./i18n";
import { api, type Action, type Bot, type Group } from "@/state/store";
import type { Routine } from "@/lib/routines";
import { serverFetch } from "./relay-server";
@@ -30,7 +30,9 @@ const post = (body: unknown) => ({ method: "POST", body: JSON.stringify(body) })
export const exportDepartment = (department: string) => api<TemplateCard>("/api/share/export", post({ department }));
export const templateDetails = (id: string) => api<{ card: TemplateCard; details: TemplateDetails }>(`/api/share/${encodeURIComponent(id)}`);
-export const publishTemplate = (id: string) => api<TemplateCard>(`/api/share/${encodeURIComponent(id)}/publish`, post({}));
+/** `author` is "Published by": "" publishes it as the community's. */
+export const publishTemplate = (id: string, author?: string) =>
+ api<TemplateCard>(`/api/share/${encodeURIComponent(id)}/publish`, post(author === undefined ? {} : { author }));
export const deleteTemplate = (id: string) => api<{ ok: true }>(`/api/share/${encodeURIComponent(id)}`, { method: "DELETE" });
export type ImportSource = { url: string } | { path: string } | { files: Record<string, string> } | { library: string };
@@ -76,6 +78,27 @@ export function countsLine(card: Pick<TemplateCard, "scope" | "counts">): string
].join(" · ");
}
+/** "We removed 3 local paths and 1 email before publishing"; empty when nothing was taken out. */
+export function scrubbedLine(card: Pick<TemplateCard, "scrubbed">): string {
+ const { paths = 0, emails = 0, phones = 0, names = 0 } = card.scrubbed ?? {};
+ const parts = [
+ ...(paths ? [paths === 1 ? t("template.scrub.pathsOne") : t("template.scrub.pathsMany", { count: paths })] : []),
+ ...(emails ? [emails === 1 ? t("template.scrub.emailsOne") : t("template.scrub.emailsMany", { count: emails })] : []),
+ ...(phones ? [phones === 1 ? t("template.scrub.phonesOne") : t("template.scrub.phonesMany", { count: phones })] : []),
+ ...(names ? [names === 1 ? t("template.scrub.namesOne") : t("template.scrub.namesMany", { count: names })] : []),
+ ];
+ return parts.length ? t("template.scrubbed", { list: new Intl.ListFormat(activeLocale(), { type: "conjunction" }).format(parts) }) : "";
+}
+
+/** Credits that name nobody: what templates carried before "Published by", and the community's own. */
+const NOBODY = new Set(["community", "mausbot community", "mausbot user", "openmausbot user", "a mausbot user"]);
+
+/** The name a "Published by" line shows, or null when the credit names nobody. */
+export function creditShown(name: string | undefined): string | null {
+ const trimmed = name?.trim();
+ return trimmed && !NOBODY.has(trimmed.toLowerCase()) ? trimmed : null;
+}
+
/** Puts the template's folder on this device: a folder the person picks on the desktop app, a .zip download elsewhere.
* The folder's path when it was written, null when cancelled or downloaded. */
export async function saveTemplateFolder(card: Pick<TemplateCard, "id" | "name">): Promise<string | null> {
diff --git a/src/locales/en.json b/src/locales/en.json
index 212c75c8f7..4554813625 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -11539,6 +11539,19 @@
"template.neverShared": "Chats, memory and keys are never shared",
"template.redactedOne": "1 item redacted",
"template.redactedMany": "{count} items redacted",
+ "template.scrubbed": "We removed {list} before publishing",
+ "template.scrub.pathsOne": "1 local path",
+ "template.scrub.pathsMany": "{count} local paths",
+ "template.scrub.emailsOne": "1 email",
+ "template.scrub.emailsMany": "{count} emails",
+ "template.scrub.phonesOne": "1 phone number",
+ "template.scrub.phonesMany": "{count} phone numbers",
+ "template.scrub.namesOne": "1 mention of your name",
+ "template.scrub.namesMany": "{count} mentions of your name",
+ "template.secretFound": "It holds a key or token, so it can't be published. Remove it from the bot, then update the template.",
+ "template.publishedBy": "Published by {name}",
+ "template.publishedByLabel": "Published by",
+ "template.publishedByEmpty": "Community",
"template.skipped": "Left out: {list}",
"template.failed": "Something went wrong. Try again.",
"template.saveFolder": "Save folder…",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 53bed26217..41e39a9e38 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -11529,6 +11529,19 @@
"template.neverShared": "Conversas, memória e chaves nunca são compartilhadas",
"template.redactedOne": "1 item ocultado",
"template.redactedMany": "{count} itens ocultados",
+ "template.scrubbed": "Removemos {list} antes de publicar",
+ "template.scrub.pathsOne": "1 caminho local",
+ "template.scrub.pathsMany": "{count} caminhos locais",
+ "template.scrub.emailsOne": "1 e-mail",
+ "template.scrub.emailsMany": "{count} e-mails",
+ "template.scrub.phonesOne": "1 número de telefone",
+ "template.scrub.phonesMany": "{count} números de telefone",
+ "template.scrub.namesOne": "1 menção ao seu nome",
+ "template.scrub.namesMany": "{count} menções ao seu nome",
+ "template.secretFound": "Ele contém uma chave ou um token, então não pode ser publicado. Remova do bot e depois atualize o modelo.",
+ "template.publishedBy": "Publicado por {name}",
+ "template.publishedByLabel": "Publicado por",
+ "template.publishedByEmpty": "Comunidade",
"template.skipped": "Ficou de fora: {list}",
"template.failed": "Algo deu errado. Tente de novo.",
"template.saveFolder": "Salvar pasta…",