Move secrets between users and computers without the model seeing them

A new personal env scope (paradigm user: one user's secret for one bot)
beats every other scope, reaches only that user's runs of that bot, and
is redacted like any secret. Bots take secrets in with request_secret,
which puts a [secret-request:ID] card in the chat: the user types the
value into a masked input there, never into a message, and the bot is
told only the key. Bots show secrets with capture_secret (a task's
computer tool that saves a file or a command's output straight to a
personal env, then redacts it from the rest of the run) and show_secret
(an env by key): both give a [secret:ID] chip whose Reveal and Copy fetch
the value on click, for its own user (personal) or a super admin
(anything else), logged by key. Values never go into messages, page
props, history, Copy chat or logs. Users manage their own secrets on
Settings > Secrets; the Environment page lists everyone's, remove only.
Deleting a bot or user removes its personal secrets, and SecretsNote
tells bots never to ask for or print secrets in chat.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-25 16:51:32 +01:00
co-authored by Claude Opus 5.5
parent 83ff79b9c3
commit 69988e08fc
78 changed files with 2472 additions and 52 deletions
@@ -0,0 +1,22 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { SecretRequestView } from "@/src/types";
type Params = {
request_id: number;
/**
* The secret the user typed; none declines the request.
*/
value?: string;
};
/**
* Saves the secret a bot asked for from its card, or declines it,
* returning the request as it now stands (never the value).
*/
export default async function decideSecretRequest({ request_id, value }: Params) {
return await fetchApi<{ request_id: number; value?: string }, APIResponseObject<SecretRequestView>>(
`/api/admin/secret-requests/${value === undefined ? "decline" : "answer"}-request`,
{ method: "POST", body: value === undefined ? { request_id } : { request_id, value } },
);
}
@@ -0,0 +1,55 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useEffect, useState } from "react";
import type { SecretRefView } from "@/src/types";
type Params = {
env_id: number;
};
/**
* Secret refs already read, by id. Only the key and whether the viewer may
* reveal it: the value is fetched on Reveal or Copy and never cached here.
*/
const loaded = new Map<number, Promise<SecretRefView | null>>();
function loadSecret({ env_id }: Params) {
const cached = loaded.get(env_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<SecretRefView>>(
`/api/admin/secrets/get-secret?env_id=${env_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(env_id, pending);
return pending;
}
/**
* A secret a bot showed (`[secret:ID]`), for its masked chip.
*/
export default function useSecretRef({ env_id }: Params) {
const [view, setView] = useState<SecretRefView | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let live = true;
loadSecret({ env_id }).then((result) => {
if (!live) return;
setView(result);
setLoading(false);
});
return () => {
live = false;
};
}, [env_id]);
return { view, loading };
}
@@ -0,0 +1,65 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { SecretRequestView } from "@/src/types";
type Params = {
request_id: number;
};
/**
* Secret requests already read, by id, so a thread naming one twice asks
* once. An answer replaces its entry.
*/
const loaded = new Map<number, Promise<SecretRequestView | null>>();
function loadRequest({ request_id }: Params) {
const cached = loaded.get(request_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<SecretRequestView>>(
`/api/admin/secret-requests/get-request?request_id=${request_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(request_id, pending);
return pending;
}
/**
* A secret a bot asked for (`[secret-request:ID]`), for its chip and card:
* read when the chip renders, so it shows whether it's still waiting.
* Only the user it was asked of can read it; anyone else gets null.
*/
export default function useSecretRequest({ request_id }: Params) {
const [view, setViewState] = useState<SecretRequestView | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let live = true;
loadRequest({ request_id }).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
});
return () => {
live = false;
};
}, [request_id]);
const setView = useCallback(
(next: SecretRequestView) => {
loaded.set(request_id, Promise.resolve(next));
setViewState(next);
},
[request_id],
);
return { view, loading, setView };
}
@@ -7,6 +7,8 @@ import {
FileRefHrefPrefix,
HookProposalRefHrefPrefix,
ProposalRefHrefPrefix,
SecretRefHrefPrefix,
SecretRequestRefHrefPrefix,
TakeOverRefHrefPrefix,
WorkspaceRefHrefPrefix,
} from "@/src/utils/link-computer-refs";
@@ -17,6 +19,8 @@ import FileRefChip from "./file-ref-chip";
import FolderRefChip from "./folder-ref-chip";
import HookProposalRefChip from "./hook-proposal-ref-chip";
import ProposalRefChip from "./proposal-ref-chip";
import SecretRefChip from "./secret-ref-chip";
import SecretRequestRefChip from "./secret-request-ref-chip";
import TakeOverChip from "./take-over-chip";
import WorkspaceRefChip from "./workspace-ref-chip";
@@ -26,7 +30,9 @@ import WorkspaceRefChip from "./workspace-ref-chip";
* computer, a bot it named a link to that bot's conversation, a workspace
* a link to that workspace, a file it saved a chip that downloads it, a
* folder it named a chip that opens it in the files browser, an MCP server,
* tool, skill or hook it proposed a chip that opens the confirm card;
* tool, skill or hook it proposed a chip that opens the confirm card, a
* secret it showed a masked chip, a secret it asked for a chip that opens
* the card it's typed into;
* anything else opens in a new tab.
*/
export default function MarkdownLink({ href, children }: ComponentProps<"a">) {
@@ -81,6 +87,18 @@ export default function MarkdownLink({ href, children }: ComponentProps<"a">) {
if (proposal_id) return <HookProposalRefChip proposal_id={proposal_id} />;
}
if (href?.startsWith(SecretRefHrefPrefix)) {
const env_id = Number(href.slice(SecretRefHrefPrefix.length));
if (env_id) return <SecretRefChip env_id={env_id} />;
}
if (href?.startsWith(SecretRequestRefHrefPrefix)) {
const request_id = Number(href.slice(SecretRequestRefHrefPrefix.length));
if (request_id) return <SecretRequestRefChip request_id={request_id} />;
}
const folder_ref = parseFolderRefHref({ href });
if (folder_ref) return <FolderRefChip spec={folder_ref.spec} path={folder_ref.path} />;
@@ -0,0 +1,28 @@
import Button from "@moduletrace/twui/layout/Button";
import type { LucideIcon } from "lucide-react";
type Props = {
title: string;
icon: LucideIcon;
onClick: () => void;
};
/**
* One of a secret chip's icon buttons (Reveal, Copy).
*/
export default function SecretChipButton({ title, icon: Icon, onClick }: Props) {
return (
<Button
type="button"
variant="ghost"
color="gray"
size="smaller"
title={title}
aria-label={title}
className="h-5 w-5 shrink-0 p-0!"
onClick={onClick}
>
<Icon size={13} aria-hidden />
</Button>
);
}
@@ -0,0 +1,81 @@
import { useState } from "react";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import { Check, Copy, Eye, EyeOff, KeyRound } from "lucide-react";
import revealSecret from "@/src/functions/frontend/reveal-secret";
import copyPendingText from "@/src/utils/copy-pending-text";
import useSecretRef from "../(hooks)/use-secret-ref";
import SecretChipButton from "./secret-chip-button";
type Props = {
env_id: number;
};
/**
* A secret a bot showed (`secretRef`): its key, masked, with Reveal and
* Copy for whoever may see it (`canRevealEnv`). The value is fetched only
* on a click, held only while shown, and never in the page or the thread.
*/
export default function SecretRefChip({ env_id }: Props) {
const { view, loading } = useSecretRef({ env_id });
const [value, setValue] = useState<string>();
const [copied, setCopied] = useState(false);
const [error, setError] = useState<string>();
if (!view) {
return (
<Span className="font-bold">{loading ? `secret ${env_id}` : `secret ${env_id} (not available)`}</Span>
);
}
const reveal = async () => {
if (value !== undefined) {
setValue(undefined);
return;
}
setError(undefined);
try {
setValue(await revealSecret({ env_id }));
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
};
const copy = async () => {
setError(undefined);
const ok = await copyPendingText({ text: revealSecret({ env_id }) }).catch((e: Error) => {
setError(e.message);
return false;
});
if (!ok) return;
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<Row
title={view.description || view.key}
className="inline-flex h-6 max-w-full gap-1! flex-nowrap items-center align-middle rounded-default border border-hairline px-2 text-[13px] text-ink"
>
<KeyRound size={14} aria-hidden className="shrink-0" />
<Span className="font-bold whitespace-nowrap">{view.key}</Span>
<Span className="font-mono truncate select-all">{value ?? "••••••••"}</Span>
{view.can_reveal ? (
<>
<SecretChipButton
title={value === undefined ? `Reveal ${view.key}` : `Hide ${view.key}`}
icon={value === undefined ? Eye : EyeOff}
onClick={reveal}
/>
<SecretChipButton title={`Copy ${view.key}`} icon={copied ? Check : Copy} onClick={copy} />
</>
) : null}
{error ? <Span className="text-[12px] text-ink-secondary whitespace-nowrap">{error}</Span> : null}
</Row>
);
}
@@ -0,0 +1,38 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type { SecretRequestView } from "@/src/types";
import SecretRequestCard from "./secret-request-card";
const token: SecretRequestView = {
id: 4,
key: "GITHUB_TOKEN",
description: "GitHub personal access token with repo scope",
reason: "To list your repositories with gh.",
status: "pending",
bot_id: 6,
bot_name: "Ada",
env_id: null,
};
function render({ view }: { view: SecretRequestView }) {
return renderToString(<SecretRequestCard view={view} onDecided={() => {}} onDone={() => {}} />);
}
describe("SecretRequestCard", () => {
test("asks for it in a masked input, with the bot's reason", () => {
const html = render({ view: token });
expect(html).toContain("GitHub personal access token with repo scope");
expect(html).toContain("To list your repositories with gh.");
expect(html).toContain(`type="password"`);
expect(html).toContain(">Save<");
});
test("once answered, offers no input or buttons", () => {
const saved = render({ view: { ...token, status: "saved", env_id: 9 } });
expect(saved).not.toContain(`type="password"`);
expect(saved).not.toContain(">Save<");
expect(render({ view: { ...token, status: "declined" } })).toContain("Nothing was saved");
});
});
@@ -0,0 +1,135 @@
import { useContext, useState } from "react";
import Input from "@moduletrace/twui/form/Input";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { AppContext } from "@/src/pages/__root";
import type { SecretRequestView } from "@/src/types";
import decideSecretRequest from "../(functions)/decide-secret-request";
import sendBotMessage from "../(functions)/send-bot-message";
import secretRequestMessage from "../(utils)/secret-request-message";
import MessageDetailsHeading from "./message-details-heading";
type Props = {
view: SecretRequestView;
onDecided: (view: SecretRequestView) => void;
onDone: () => void;
};
/**
* The card a user types a secret a bot asked for into. The value goes
* from here to the app only: it's saved encrypted as their personal secret
* for the bot, never put in a message, and the bot (and its model
* provider) only learns its key. Saving or declining tells the bot in chat.
*/
export default function SecretRequestCard({ view, onDecided, onDone }: Props) {
const { pageProps } = useContext(AppContext);
const [value, setValue] = useState("");
const [busy, setBusy] = useState<"save" | "decline">();
const [error, setError] = useState<string>();
const open = view.status == "pending";
const decide = async (decision: "save" | "decline") => {
if (decision == "save" && !value) {
setError(`Enter the value first.`);
return;
}
const question =
decision == "save"
? `Save ${view.key} for ${view.bot_name}? Its runs for you get it on their computers; it's never shown to the bot.`
: `Decline? Nothing will be saved.`;
if (!window.confirm(question)) return;
setBusy(decision);
setError(undefined);
const res = await decideSecretRequest({
request_id: view.id,
value: decision == "save" ? value : undefined,
}).catch(() => null);
if (!res?.success || !res.singleRes) {
setBusy(undefined);
setError(res?.msg || `Couldn't ${decision} it.`);
return;
}
setValue("");
onDecided(res.singleRes);
await sendBotMessage({
bot_id: Number(pageProps?.bot?.id) || 0,
workspace_id: pageProps?.workspace?.id || null,
text: secretRequestMessage({ view: res.singleRes }),
media_ids: [],
}).catch(() => null);
setBusy(undefined);
onDone();
};
return (
<Stack className="w-full gap-0! items-stretch">
<MessageDetailsHeading>What it is</MessageDetailsHeading>
<Span className="text-[13px] leading-5 text-ink break-words">{view.description}</Span>
<Span className="mt-1 text-[12px] leading-4 text-ink-secondary">{`Saved as ${view.key}, for your runs of ${view.bot_name} only.`}</Span>
<MessageDetailsHeading>Why (written by the bot)</MessageDetailsHeading>
<Span className="whitespace-pre-wrap text-[13px] leading-5 text-ink break-words">{view.reason}</Span>
{open ? (
<Stack className="mt-5 w-full gap-2! items-stretch">
<Input
id={`secret-request-${view.id}`}
title={view.key}
label={view.key}
showLabel
type="password"
autoComplete="off"
placeholder="Paste or type it here, not in the chat"
info="Encrypted before it's stored. The bot and its model never see it."
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</Stack>
) : (
<Span className="mt-4 text-[13px] leading-5 text-ink">
{view.status == "saved" ? `Saved. You can replace or remove it in Settings, under Secrets.` : `Declined. Nothing was saved.`}
</Span>
)}
{error ? <Span className="mt-2 text-[13px] leading-5 text-ink">{error}</Span> : null}
{open ? (
<Row className="mt-5 w-full gap-2! justify-end">
<Button
type="button"
variant="outlined"
color="gray"
size="small"
title="Decline: nothing is saved"
loading={busy == "decline"}
disabled={Boolean(busy)}
onClick={() => decide("decline")}
>
Decline
</Button>
<Button
type="button"
size="small"
title={`Save ${view.key}`}
loading={busy == "save"}
disabled={Boolean(busy)}
onClick={() => decide("save")}
>
Save
</Button>
</Row>
) : null}
</Stack>
);
}
@@ -0,0 +1,72 @@
import { useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import Button from "@moduletrace/twui/layout/Button";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { KeyRound } from "lucide-react";
import useSecretRequest from "../(hooks)/use-secret-request";
import SecretRequestCard from "./secret-request-card";
type Props = {
request_id: number;
};
const StatusLabels = {
pending: "waiting for you",
saved: "saved",
declined: "declined",
} as const;
/**
* A secret a bot asked for (`secretRequestRef`): a chip naming its key and
* where it stands, which opens the card the user types it into. Anyone it
* wasn't asked of sees its number only.
*/
export default function SecretRequestRefChip({ request_id }: Props) {
const { view, loading, setView } = useSecretRequest({ request_id });
const [open, setOpen] = useState(false);
if (!view) {
return (
<Span className="font-bold">
{loading ? `secret request ${request_id}` : `secret request ${request_id} (not available)`}
</Span>
);
}
const status = StatusLabels[view.status];
return (
<Modal
target={
<Button
type="button"
variant="outlined"
color="gray"
size="smaller"
title={view.status == "pending" ? `Enter ${view.key}` : `${view.key}: ${status}`}
className="inline-flex h-6 gap-1.5! flex-nowrap align-middle px-2! text-[13px] font-bold text-ink whitespace-nowrap"
>
<KeyRound size={14} aria-hidden className="shrink-0" />
{`${view.key} · ${status}`}
</Button>
}
targetWrapperProps={{ className: "inline-flex align-middle" }}
open={open}
setOpen={setOpen}
className="max-w-xl bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{`${view.bot_name} asks for ${view.key}`}</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`Type it here rather than in the chat: what you write in the chat goes to the bot's model provider, this never does.`}
</Span>
</Stack>
<Stack className="mt-2 max-h-[65vh] w-full gap-0! items-stretch overflow-y-auto">
<SecretRequestCard view={view} onDecided={setView} onDone={() => setOpen(false)} />
</Stack>
</Modal>
);
}
@@ -0,0 +1,15 @@
import type { SecretRequestView } from "@/src/types";
type Params = {
view: SecretRequestView;
};
/**
* What the chat tells the bot once the user answered its secret request,
* so it carries on. Only the key: the value never goes into a message.
*/
export default function secretRequestMessage({ view }: Params) {
if (view.status == "declined") return `I declined to give ${view.key} (secret request #${view.id}).`;
return `I saved ${view.key} (secret request #${view.id}). It's set as $${view.key} on your computers from your next run.`;
}
@@ -41,6 +41,7 @@ const Descriptions: Record<EnvScope["paradigm"], string> = {
computer:
"For this computer only. Beats a workspace, loses to the bot's own.",
bot: "For this bot only, everywhere it works. Beats the workspace, the computer and general.",
user: "For one user's runs of one bot, set from the chat. Beats everything else.",
};
/**
@@ -0,0 +1,110 @@
import { useState } from "react";
import Input from "@moduletrace/twui/form/Input";
import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Pencil, Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
import RowIconButton from "@/src/components/general/row-icon-button";
import type { PersonalSecret } from "@/src/types";
type Props = {
secret: PersonalSecret;
/**
* Whose it is, for the super admin's list of everyone's.
*/
show_user?: boolean;
busy?: boolean;
/**
* Saves a new value; without it the row can only be removed.
*/
onReplace?: (params: { secret: PersonalSecret; value: string }) => Promise<boolean>;
onRemove: (params: { secret: PersonalSecret }) => void;
};
/**
* One personal secret: its key, what it's for, which bot (and whose), and
* never its value. Replace opens a masked input in place.
*/
export default function PersonalSecretRow({ secret, show_user, busy, onReplace, onRemove }: Props) {
const [editing, setEditing] = useState(false);
const [value, setValue] = useState("");
const save = async () => {
if (!value || !onReplace) return;
if (await onReplace({ secret, value })) {
setValue("");
setEditing(false);
}
};
return (
<Stack
className={twMerge(
"w-full gap-3! items-stretch py-3 px-4",
"border-0 border-b border-solid border-hairline last:border-b-0",
)}
>
<Row className="w-full gap-3! flex-nowrap items-start justify-between">
<Stack className="gap-0.5! min-w-0">
<Span className="text-sm font-bold leading-5 text-ink truncate">{secret.key}</Span>
{secret.description ? (
<Span className="text-[13px] leading-[18px] text-ink-secondary break-words">{secret.description}</Span>
) : null}
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`${show_user ? `${secret.user_name}, for ` : "For "}${secret.bot_name}`}
</Span>
</Stack>
<Row className="gap-1! flex-nowrap shrink-0">
{onReplace ? (
<RowIconButton
icon={Pencil}
title={`Replace ${secret.key}`}
disabled={busy}
onClick={() => setEditing(!editing)}
/>
) : null}
<RowIconButton
icon={Trash2}
title={`Remove ${secret.key}`}
loading={busy}
disabled={busy}
onClick={() => onRemove({ secret })}
/>
</Row>
</Row>
{editing ? (
<Row className="w-full gap-2! flex-nowrap items-end">
<Input
id={`personal-secret-${secret.id}`}
title={`New value for ${secret.key}`}
label="New value"
showLabel
type="password"
autoComplete="off"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Button
type="button"
variant="outlined"
color="gray"
size="small"
title="Cancel"
onClick={() => {
setValue("");
setEditing(false);
}}
>
Cancel
</Button>
<Button type="button" size="small" title={`Save ${secret.key}`} loading={busy} disabled={busy || !value} onClick={save}>
Save
</Button>
</Row>
) : null}
</Stack>
);
}
@@ -0,0 +1,49 @@
import type { PersonalSecret } from "@/src/types";
import SettingsGroup from "../settings-group";
import SettingsList from "../settings-list";
import SettingsStatus from "../settings-status";
import PersonalSecretRow from "./personal-secret-row";
type Props = {
title: string;
description: string;
secrets: PersonalSecret[];
show_user?: boolean;
busy_id?: number;
status?: { error?: boolean; success?: boolean; msg?: string };
onReplace?: (params: { secret: PersonalSecret; value: string }) => Promise<boolean>;
onRemove: (params: { secret: PersonalSecret }) => void;
};
/**
* A list of personal secrets (set from the chat), values never shown: the
* user's own on the Secrets page, everyone's on the Environment page.
*/
export default function PersonalSecretsGroup({
title,
description,
secrets,
show_user,
busy_id,
status,
onReplace,
onRemove,
}: Props) {
return (
<SettingsGroup title={title} description={description}>
<SettingsList is_empty={!secrets.length} empty="No secrets saved yet.">
{secrets.map((secret) => (
<PersonalSecretRow
key={secret.id}
secret={secret}
show_user={show_user}
busy={busy_id == secret.id}
onReplace={onReplace}
onRemove={onRemove}
/>
))}
</SettingsList>
<SettingsStatus status={status} />
</SettingsGroup>
);
}
@@ -2,14 +2,17 @@ import { useContext, useState } from "react";
import { AppContext } from "@/src/pages/__root";
import type { EnvsMutationResult, EnvsOverviewPayload } from "@/src/types";
import EnvsGroup from "../../(partials)/envs/envs-group";
import postEnvApi from "../../(functions)/post-env-api";
import PersonalSecretsGroup from "../../(partials)/secrets/personal-secrets-group";
import EnvScopeSelect from "../(partials)/env-scope-select";
import KnownEnvsGroup from "../(partials)/known-envs-group";
import scopeValue, { envInScope } from "../(utils)/scope-value";
/**
* Pick where (general, a workspace, a bot or a computer), then that scope's
* envs. General also lists the app settings. Every change saves at once and
* refreshes the page data.
* envs. General also lists the app settings. Below, every user's personal
* secrets (set from the chat), which can only be removed here. Every change
* saves at once and refreshes the page data.
*/
export default function EnvironmentSettingsSection() {
const { pageProps } = useContext(AppContext);
@@ -20,6 +23,7 @@ export default function EnvironmentSettingsSection() {
* Remounts the lists when the data changes under them.
*/
const [version, setVersion] = useState(0);
const [removing, setRemoving] = useState<number>();
if (!overview) return null;
@@ -60,6 +64,23 @@ export default function EnvironmentSettingsSection() {
onChanged={changed}
onError={failed}
/>
<PersonalSecretsGroup
title="Personal secrets"
description="What users gave their bots from the chat, each for one user's runs of one bot. Only its user can see or replace one; you can remove it."
secrets={overview.personal || []}
show_user
busy_id={removing}
onRemove={async ({ secret }) => {
if (!window.confirm(`Remove ${secret.user_name}'s ${secret.key} for ${secret.bot_name}?`)) return;
setRemoving(secret.id);
const res = await postEnvApi({ path: "delete-env", body: { env_id: secret.id } }).catch(() => null);
setRemoving(undefined);
if (res?.success && res.singleRes) changed(res.singleRes, res.msg || "Removed.");
else failed(res?.msg || "Couldn't remove it.");
}}
/>
</>
);
}
@@ -0,0 +1,59 @@
import { useContext, useState } from "react";
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { AppContext } from "@/src/pages/__root";
import type { PersonalSecret } from "@/src/types";
import PersonalSecretsGroup from "../../(partials)/secrets/personal-secrets-group";
/**
* The user's own personal secrets, with Replace and Remove. Every change
* saves at once and refreshes the list.
*/
export default function SecretsSettingsSection() {
const { pageProps } = useContext(AppContext);
const [secrets, setSecrets] = useState<PersonalSecret[]>(pageProps?.personal_secrets || []);
const [busy_id, setBusyId] = useState<number>();
const [status, setStatus] = useState<{ error?: boolean; success?: boolean; msg?: string }>();
const post = async ({ path, body }: { path: "save-secret" | "delete-secret"; body: Record<string, unknown> }) => {
const res = await fetchApi<Record<string, unknown>, APIResponseObject<PersonalSecret[]>>(
`/api/admin/secrets/${path}`,
{ method: "POST", body },
).catch(() => null);
if (res?.success && res.singleRes) {
setSecrets(res.singleRes);
setStatus({ success: true, msg: res.msg || "Saved." });
return true;
}
setStatus({ error: true, msg: res?.msg || "Couldn't save it." });
return false;
};
return (
<PersonalSecretsGroup
title="Your secrets"
description="Each one is for one bot and only your runs of it. Bots ask for them with a card in the chat, never in a message."
secrets={secrets}
busy_id={busy_id}
status={status}
onReplace={async ({ secret, value }) => {
if (!window.confirm(`Replace ${secret.key} for ${secret.bot_name}?`)) return false;
setBusyId(secret.id);
const ok = await post({ path: "save-secret", body: { env_id: secret.id, value } });
setBusyId(undefined);
return ok;
}}
onRemove={async ({ secret }) => {
if (!window.confirm(`Remove ${secret.key} for ${secret.bot_name}? Its computers drop it on their next run.`)) return;
setBusyId(secret.id);
await post({ path: "delete-secret", body: { env_id: secret.id } });
setBusyId(undefined);
}}
/>
);
}
@@ -0,0 +1,23 @@
import type { PagePropsType } from "@/src/types";
import type { BunextPageServerFn } from "@moduletrace/bunext/types";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabPersonalSecrets from "@/src/functions/backend/db/envs/grab-personal-secrets";
import grabSettingsServerProps from "../(functions)/grab-settings-server-props";
/**
* Every user's own personal secrets: keys only, never values.
*/
export const server: BunextPageServerFn<PagePropsType> = async (params) => {
const settings = await grabSettingsServerProps(params);
if (!settings.props) return settings;
const { user } = await userAuth({ req: params.req });
return {
props: {
...settings.props,
personal_secrets: user?.id ? await grabPersonalSecrets({ user_id: user.id }) : [],
},
};
};
@@ -0,0 +1,16 @@
import SecretsSettingsSection from "./(sections)/secrets-settings-section";
import SettingsShell from "../(partials)/settings-shell";
import settingsPageMeta from "../(functions)/settings-page-meta";
export default function AdminSettingsSecretsPage() {
return (
<SettingsShell
title="Secrets"
description="Passwords, tokens and keys you gave your bots from the chat, or they saved for you. Bots use them by name and never see them."
>
<SecretsSettingsSection />
</SettingsShell>
);
}
export const meta = settingsPageMeta({ label: "Secrets" });