Fix review findings: secrets in snapshots, URL spoofing, migration data loss

Adversarial review of the branch produced findings across four areas.
This addresses them, plus the Windows CI environment.

Secrets. commit_container_snapshot baked the container's full env into
the per-project snapshot image, so the shared OAuth token — and the AWS
keys, git token and gateway master key — outlived revocation and were
readable via docker inspect. Verified against Engine 29.6 that a commit
body's config merges over the container's: keys cannot be dropped but
can be overwritten, so all of them now commit as KEY=. clear_claude_token
additionally rewrites images from earlier builds and reports honestly
when a tag could not be rewritten.

The recommendation to move the token out of env entirely was not taken,
with reasoning: apiKeyHelper is a different auth method that outranks
CLAUDE_CODE_OAUTH_TOKEN rather than a transport for it, and no
file-based delivery exists. The durable exposure — the image — is what
is closed here. Separately noted, not fixed: entrypoint.sh captures the
token into the scheduler's .env inside the persisted volume.

URL spoofing. Three call sites reached openUrl with container-controlled
strings, one of which the review missed (the WebLinksAddon handler).
The sign-in URL was scraped from container output with a longest-match
tie-break and no userinfo check, so claude.ai@evil.tld rendered as
"claude.ai…" in a truncating element. There is now one sanitizer in
front of every sink — scheme allowlist, no userinfo, C0/C1 and quote
rejection, host allowlist for the sign-in case, first-match — and the
origin renders un-truncated. The toast is keyed so a changed URL
remounts, closing a bait-and-switch where the user read one URL and
clicked another.

Migration. The rollback pin was best-effort: a tag failure was logged
and the migration continued past remove_container, after which the
final commit overwrote the only copy of the old system layer. It now
aborts before anything destructive and reads the tag back. /var was
destroyed while the ordinary recreate path preserves it — making the
"safe" alternative to Reset more destructive than Reset's alternative;
data-bearing subtrees are now detected and disclosed in the pre-flight
rather than copied, since tarring a live database onto a different
base's packages is a corruption risk. resume_migration now verifies the
migration-state label instead of reporting success for a container that
never swapped. dismiss actually resolves the record rather than leaving
the feature permanently refusing to migrate. Start and Reset are guarded
while a migration is live.

Lifecycle. The gateway no longer publishes on 0.0.0.0 — bind address and
advertised URL are derived together so they cannot drift. Disabling it
now stops it. App exit runs teardown concurrently under a budget with a
visible shutting-down state instead of blocking for minutes. Auto-starts
retry when Docker is not up yet, and the polling-recovery path now
reconciles, so interrupted migrations are still recovered. Auth-bridge
forwards are capped, closing a container-driven fd exhaustion.

Windows CI. build-windows failed on this branch with "linker link.exe
not found". The runner had no MSVC build tools and the workflow assumed
a hand-provisioned machine, so a bare runner registers, accepts jobs and
fails at link time after downloading the whole crate graph. The job now
installs the VC++ workload when vswhere cannot find it, matching how it
already conditionally installs Rust and Node.

192 Rust tests, 274 frontend tests, both builds clean, zero warnings.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-09 19:35:39 -07:00
co-authored by Claude Opus 5
parent eb1324cb16
commit 2de00b3c55
43 changed files with 4348 additions and 346 deletions
@@ -22,6 +22,7 @@ const STALE: ContainerStaleness = {
apt_delta: ["socat", "bubblewrap"],
npm_global_delta: [],
verbatim_paths: [],
unpreserved_data: [],
outdated_package_count: 61,
probe_error: null,
};
@@ -30,6 +31,7 @@ function migration(overrides: Partial<ContainerMigration> = {}): ContainerMigrat
return {
staleness: STALE,
probing: false,
probeSettled: true,
running: false,
recovered: false,
interrupted: null,
@@ -41,7 +43,7 @@ function migration(overrides: Partial<ContainerMigration> = {}): ContainerMigrat
resume: vi.fn(async () => {}),
keep: vi.fn(async () => {}),
rollback: vi.fn(async () => {}),
dismiss: vi.fn(),
dismiss: vi.fn(async () => {}),
refresh: vi.fn(async () => {}),
...overrides,
};
@@ -153,18 +155,95 @@ describe("MigrateContainerModal", () => {
});
});
it("does not ask to copy paths when there are none to copy", async () => {
it("never derives copy_paths from a delta the probe may not have read", async () => {
// The regression: `copy_paths: copyPaths && verbatim.length > 0` read the
// toggle's meaning off `staleness`, which is null while the ~6 s probe
// runs. That sent `copy_paths: false` to a backend that recomputes the
// real set but honours the flag — files silently not copied, while this
// dialog said there was nothing to copy. The toggle's own value is the
// only thing that may be sent; the backend skips the step when *its* set
// comes out empty, which is the only place that knows.
const { m } = await renderModal({ ...STALE, verbatim_paths: [] });
fireEvent.click(
screen.getByRole("button", { name: "Update container base" }),
);
expect(m.start).toHaveBeenCalledWith({
replay_packages: true,
copy_paths: false,
copy_paths: true,
keep_rollback: true,
});
});
it("cannot be started until the probe has settled, and says so", async () => {
await renderModal(null, { probeSettled: false, probing: true });
expect(
screen.getByRole("button", { name: "Update container base" }),
).toBeDisabled();
expect(
screen.getByText(/lists below are not complete until it finishes/i),
).toBeInTheDocument();
// "None found" and "not checked yet" must not be the same sentence.
expect(
screen.getByText(/Still checking which apt packages/i),
).toBeInTheDocument();
expect(screen.getByText("Not checked yet.")).toBeInTheDocument();
expect(
screen.queryByText(/No extra apt packages were found/i),
).not.toBeInTheDocument();
});
it("names the data under /var that the update destroys and cannot restore", async () => {
await renderModal({
...STALE,
unpreserved_data: [
{ path: "/var/lib/postgresql", bytes: 41_000_000, file_count: 912 },
],
});
const panel = screen.getByTestId("migration-unpreserved");
expect(panel.textContent).toMatch(/\/var\/lib\/postgresql/);
expect(panel.textContent).toMatch(/41\.0 MB in 912 files/);
expect(panel.textContent).toMatch(/reinstalling the package does not bring it back/i);
});
it("says plainly that /var is not carried across even when nothing is at risk", async () => {
await renderModal();
const panel = screen.getByTestId("migration-unpreserved");
expect(panel.textContent).toMatch(/nothing here to lose/i);
expect(panel.textContent).toMatch(/Data written under \/var is not carried across/i);
});
it("offers Resume rather than Keep on a container that is mid-swap", async () => {
// Keep drops the rollback image, and on an unfinished migration
// `:latest` still points at the old lineage — so Keep here deletes the
// only way back from a container the app can no longer reason about.
const { m } = await renderModal(STALE, {
interrupted: {
phase: "interrupted",
from_image_id: "sha256:aaa",
to_base_id: "sha256:bbb",
started_at: "2026-08-09T10:00:00Z",
report: null,
rollback_image: "triple-c-snapshot-p1:pre-migration-20260809-100000",
staging_path: null,
options: { replay_packages: true, copy_paths: true, keep_rollback: true },
plan: null,
},
report: {
phase: "failed",
packages_requested: [],
packages_installed: [],
packages_failed: [],
paths_copied: [],
features_restored: [],
rollback_available: true,
message: "saving it failed",
},
});
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Resume update" }));
expect(m.resume).toHaveBeenCalledTimes(1);
});
it("does not start anything on cancel", async () => {
const { m, onClose } = await renderModal();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
@@ -5,8 +5,10 @@ import Button from "../ui/Button";
import Toggle from "../ui/Toggle";
import { SwitchRow } from "../ui/Field";
import MigrationReportCard from "./MigrationReportCard";
import MigrationInterruptedCard from "./MigrationInterruptedCard";
import type { ContainerMigration } from "../../hooks/useContainerMigration";
import {
DATA_NOT_CARRIED,
KEPT_AUTOMATICALLY,
KEPT_WHY,
LOST_WITHOUT_REPLAY,
@@ -14,6 +16,7 @@ import {
REPLAY_COST,
ROLLBACK_DISK_COST,
ROLLBACK_SCOPE,
formatDataSize,
formatSnapshotDate,
} from "./migrationCopy";
@@ -85,10 +88,12 @@ export default function MigrateContainerModal({
const [keepRollback, setKeepRollback] = useState(true);
const logRef = useRef<HTMLDivElement>(null);
const { running, report, log, phaseMessage, busy } = migration;
const { running, report, interrupted, log, phaseMessage, busy, probeSettled } =
migration;
const aptDelta = staleness?.apt_delta ?? [];
const npmDelta = staleness?.npm_global_delta ?? [];
const verbatim = staleness?.verbatim_paths ?? [];
const atRisk = staleness?.unpreserved_data ?? [];
const gains = staleness?.missing_features ?? [];
const snapshot = formatSnapshotDate(staleness?.snapshot_created_at ?? null);
@@ -100,13 +105,44 @@ export default function MigrateContainerModal({
const start = () => {
const options: MigrationOptions = {
// Deliberately *not* `&& verbatim.length > 0`. That looked like a
// harmless optimisation but read the toggle's meaning off a probe that
// may not have landed, so a null `staleness` sent `copy_paths: false`
// and the backend — which recomputes the real set but honours the flag —
// skipped files that did exist. The backend already skips the step when
// its own set comes out empty; that is the only place that knows.
replay_packages: replayPackages,
copy_paths: copyPaths && verbatim.length > 0,
copy_paths: copyPaths,
keep_rollback: keepRollback,
};
void migration.start(options);
};
// ---- Unfinished ---------------------------------------------------------
// Ahead of the report, for the reason spelled out in MigrationInterruptedCard:
// Keep is not a legitimate action on a container that is mid-swap.
if (interrupted) {
return (
<Modal
title={`Update container base — ${projectName}`}
onClose={onClose}
widthClassName="w-[34rem]"
footer={
<Button size="md" variant="ghost" onClick={onClose}>
Close
</Button>
}
>
<MigrationInterruptedCard
record={interrupted}
busy={busy || running}
onResume={() => void migration.resume()}
onRollback={() => void migration.rollback().then(onClose)}
/>
</Modal>
);
}
// ---- Outcome ------------------------------------------------------------
if (report) {
return (
@@ -125,10 +161,7 @@ export default function MigrateContainerModal({
busy={busy}
onKeep={() => void migration.keep().then(onClose)}
onRollback={() => void migration.rollback().then(onClose)}
onDismiss={() => {
migration.dismiss();
onClose();
}}
onDismiss={() => void migration.dismiss().then(onClose)}
/>
</Modal>
);
@@ -187,13 +220,35 @@ export default function MigrateContainerModal({
<Button size="md" variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button size="md" variant="primary" onClick={start}>
<Button
size="md"
variant="primary"
disabled={!probeSettled}
onClick={start}
>
Update container base
</Button>
</>
}
>
<div className="space-y-3">
{/* 0. Until the probe lands, every list below is "not known" wearing
"empty"'s clothes. Say which one it is, and do not let the run
start on an unread delta. */}
{!probeSettled && (
<section
className="border border-[var(--warning)]/40 bg-[var(--warning-muted)] rounded-[var(--radius-panel)] px-3.5 py-3"
role="status"
aria-live="polite"
>
<p className="text-xs text-[var(--text-primary)] leading-snug">
Still working out what this container has that the current base
does not. The lists below are not complete until it finishes, so
the update cannot start yet.
</p>
</section>
)}
{/* 1. Reassurance first. Not a choice — a statement of fact. */}
<Section title="Kept automatically">
<BulletList items={KEPT_AUTOMATICALLY} />
@@ -203,6 +258,51 @@ export default function MigrateContainerModal({
</p>
</Section>
{/* 1b. The one thing that is genuinely destroyed. Directly under the
reassurance, because a user who reads only the top of this dialog
must not come away thinking nothing is at stake. */}
<section
className="border border-[var(--error)]/40 bg-[var(--error-muted)] rounded-[var(--radius-panel)] px-3.5 py-3 space-y-2"
data-testid="migration-unpreserved"
>
<h3 className="text-[13px] font-medium text-[var(--text-primary)]">
{atRisk.length > 0
? `Destroyed, and not restored by this update (${atRisk.length})`
: "Not carried across"}
</h3>
<p className="text-xs text-[var(--text-secondary)] leading-snug">
{DATA_NOT_CARRIED}
</p>
{probeSettled ? (
atRisk.length > 0 ? (
<ul className="space-y-1 pl-4 list-disc marker:text-[var(--text-disabled)]">
{atRisk.map((d) => (
<li
key={d.path}
className="text-xs leading-snug text-[var(--text-primary)]"
>
<span className="font-mono break-all">{d.path}</span>
<span className="text-[var(--text-secondary)]">
{" "}
{formatDataSize(d.bytes)} in {d.file_count} file
{d.file_count === 1 ? "" : "s"}
</span>
</li>
))}
</ul>
) : (
<p className="text-xs text-[var(--text-secondary)]">
Nothing was found under <code className="font-mono">/var</code>{" "}
on this container, so there is nothing here to lose.
</p>
)
) : (
<p className="text-xs text-[var(--text-secondary)]">
Not checked yet.
</p>
)}
</section>
{/* 2. The apt replay. */}
<Section
title={`Reinstalled from the new base's repos (${aptDelta.length})`}
@@ -216,7 +316,12 @@ export default function MigrateContainerModal({
>
{aptDelta.length === 0 ? (
<p className="text-xs text-[var(--text-secondary)]">
No extra apt packages were found on this container.
{/* "None found" and "not looked yet" are different sentences.
Printing the first while the probe is still running is how a
user ends up believing a delta was empty when it was unread. */}
{probeSettled
? "No extra apt packages were found on this container."
: "Still checking which apt packages this container added."}
</p>
) : (
<BulletList items={aptDelta} mono />
@@ -232,10 +337,16 @@ export default function MigrateContainerModal({
<p className="text-xs text-[var(--text-secondary)]">{REPLAY_COST}</p>
</Section>
{/* 3. Verbatim copies — usually nothing, so usually not shown at all. */}
{verbatim.length > 0 && (
{/* 3. Verbatim copies — usually nothing once the probe has settled, so
usually not shown at all. Shown while it has not, because a hidden
section reads as "there is nothing here". */}
{(verbatim.length > 0 || !probeSettled) && (
<Section
title={`Copied across as-is (${verbatim.length})`}
title={
probeSettled
? `Copied across as-is (${verbatim.length})`
: "Copied across as-is"
}
control={
<Toggle
label="Copy user-authored files across as-is"
@@ -251,7 +362,13 @@ export default function MigrateContainerModal({
<code className="font-mono">/workspace</code> that belongs to no
package, so it cannot be reinstalled from a repository.
</p>
<BulletList items={verbatim} mono />
{probeSettled ? (
<BulletList items={verbatim} mono />
) : (
<p className="text-xs text-[var(--text-secondary)]">
Still checking what is there.
</p>
)}
</Section>
)}
@@ -0,0 +1,74 @@
import type { MigrationState } from "../../lib/types";
import Button from "../ui/Button";
import StatusIndicator from "../ui/StatusIndicator";
import { ROLLBACK_SCOPE, formatSnapshotDate } from "./migrationCopy";
interface Props {
record: MigrationState;
/** Disables the action row while resume/rollback is in flight. */
busy?: boolean;
onResume: () => void;
onRollback: () => void;
}
/**
* A migration that got past the container swap and stopped there.
*
* This is deliberately **not** [`MigrationReportCard`]. That card's primary
* action is Keep, which means "accept this and drop the rollback image" — and
* on an unfinished migration `triple-c-snapshot-<id>:latest` still points at
* the *old* lineage, so Keep would delete the only way back while leaving a
* container the app can no longer reason about. The backend's own message on
* this record says to resume; offering Keep beside it was the UI contradicting
* the backend and losing.
*
* So the two actions here are Resume and Roll back, and nothing else. It is
* shown ahead of any report, whether the record was found on mount or produced
* by a run that just failed — those are the same situation.
*/
export default function MigrationInterruptedCard({
record,
busy = false,
onResume,
onRollback,
}: Props) {
const started = formatSnapshotDate(record.started_at);
return (
<div className="space-y-2">
<StatusIndicator
tone="error"
label="The container base update did not finish"
className="text-[13px] font-semibold"
/>
<p className="text-xs text-[var(--text-secondary)] leading-snug">
This container is part-way onto the new base: it was replaced, but the
result was never saved
{started ? `. The update started ${started}` : ""}. Resuming replays the
same plan it was given it is the only way to finish it.
</p>
{record.report?.message && (
<p className="text-xs text-[var(--text-secondary)] leading-snug select-text">
{record.report.message}
</p>
)}
<p className="text-xs text-[var(--text-secondary)] leading-snug">
{ROLLBACK_SCOPE}
</p>
<div className="flex flex-wrap gap-1.5 pt-0.5">
<Button size="md" variant="primary" disabled={busy} onClick={onResume}>
Resume update
</Button>
{record.rollback_image && (
<Button size="md" variant="danger" disabled={busy} onClick={onRollback}>
Roll back
</Button>
)}
</div>
</div>
);
}
@@ -18,6 +18,7 @@ const FRESH: ContainerStaleness = {
apt_delta: [],
npm_global_delta: [],
verbatim_paths: [],
unpreserved_data: [],
outdated_package_count: 0,
probe_error: null,
};
@@ -40,6 +41,7 @@ function migration(overrides: Partial<ContainerMigration> = {}): ContainerMigrat
return {
staleness: null,
probing: false,
probeSettled: true,
running: false,
recovered: false,
interrupted: null,
@@ -51,7 +53,7 @@ function migration(overrides: Partial<ContainerMigration> = {}): ContainerMigrat
resume: vi.fn(async () => {}),
keep: vi.fn(async () => {}),
rollback: vi.fn(async () => {}),
dismiss: vi.fn(),
dismiss: vi.fn(async () => {}),
refresh: vi.fn(async () => {}),
...overrides,
};
@@ -173,7 +175,7 @@ describe("ContainerMigrationBanner", () => {
});
renderBanner(m);
expect(
screen.getByText(/A container base update was interrupted/i),
screen.getByText(/The container base update did not finish/i),
).toBeInTheDocument();
expect(screen.getByText(/part-way onto the new base/i)).toBeInTheDocument();
// The plain "Update container base…" call to action must not be what is
@@ -207,6 +209,36 @@ describe("ContainerMigrationBanner", () => {
expect(screen.getByRole("button", { name: "Resume update" })).toBeInTheDocument();
});
it("distinguishes an unsettled probe from a running container", () => {
// "Stop the container to update its base" on a container that is already
// stopped — because the probe has not landed — reads as a bug.
renderBanner(
migration({ staleness: STALE, probing: true, probeSettled: false }),
false,
);
expect(
screen.getByText(/Checking what this container has/i),
).toBeInTheDocument();
expect(
screen.queryByText(/Stop the container to update its base/i),
).not.toBeInTheDocument();
});
it("names the /var data that updating would destroy", () => {
renderBanner(
migration({
staleness: {
...STALE,
unpreserved_data: [
{ path: "/var/lib/postgresql", bytes: 41_000_000, file_count: 912 },
],
},
}),
);
expect(screen.getByText("/var/lib/postgresql")).toBeInTheDocument();
expect(screen.getByText(/back this up before updating/i)).toBeInTheDocument();
});
describe("the report", () => {
const CLEAN: MigrationReport = {
phase: "succeeded",
@@ -295,6 +327,39 @@ describe("ContainerMigrationBanner", () => {
expect(screen.getByRole("button", { name: "Dismiss" })).toBeInTheDocument();
});
it("never offers Keep over a container that is still mid-swap", () => {
// The failing-commit path returns a report *and* leaves the record
// interrupted. Keep would untag the rollback image and delete the record
// while `triple-c-snapshot-<id>:latest` still points at the old lineage —
// and the backend's own message on that record says to resume.
const m = migration({
staleness: STALE,
interrupted: {
phase: "interrupted",
from_image_id: "sha256:aaa",
to_base_id: "sha256:bbb",
started_at: "2026-08-09T10:00:00Z",
report: null,
rollback_image: "triple-c-snapshot-p1:pre-migration-20260809-100000",
staging_path: null,
options: { replay_packages: true, copy_paths: true, keep_rollback: true },
plan: null,
},
report: {
...CLEAN,
phase: "failed",
message: "saving it failed. Resume it, or roll back.",
},
});
renderBanner(m);
expect(screen.queryByRole("button", { name: "Keep" })).not.toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Resume update" }),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Roll back" }));
expect(m.rollback).toHaveBeenCalledTimes(1);
});
it("does not describe rollback as a time machine", () => {
renderBanner(migration({ staleness: FRESH, report: CLEAN }));
expect(
@@ -2,7 +2,8 @@ import type { ContainerMigration } from "../../../hooks/useContainerMigration";
import Button from "../../ui/Button";
import StatusIndicator from "../../ui/StatusIndicator";
import MigrationReportCard from "../MigrationReportCard";
import { ROLLBACK_SCOPE, formatSnapshotDate, joinFeatures } from "../migrationCopy";
import MigrationInterruptedCard from "../MigrationInterruptedCard";
import { formatSnapshotDate, joinFeatures } from "../migrationCopy";
interface Props {
migration: ContainerMigration;
@@ -31,8 +32,38 @@ export default function ContainerMigrationBanner({
canMigrate,
onOpen,
}: Props) {
const { staleness, running, recovered, interrupted, report, phaseMessage, busy } =
migration;
const {
staleness,
probing,
probeSettled,
running,
recovered,
interrupted,
report,
phaseMessage,
busy,
} = migration;
// An unfinished migration outranks its own report. The report's action row
// offers Keep, and Keep on a mid-swap container drops the rollback image
// while `:latest` still points at the old lineage — the backend's message on
// the very same record says to resume. Resume is the only honest primary
// action here, so the report card is not rendered at all.
if (interrupted) {
return (
<section
className={`${SHELL} border-[var(--error)]/40 bg-[var(--error-muted)]`}
aria-label="Container base update was interrupted"
>
<MigrationInterruptedCard
record={interrupted}
busy={busy || running}
onResume={() => void migration.resume()}
onRollback={() => void migration.rollback()}
/>
</section>
);
}
// The report outranks staleness: after a run, the outcome is the news.
if (report) {
@@ -50,7 +81,7 @@ export default function ContainerMigrationBanner({
busy={busy}
onKeep={() => void migration.keep()}
onRollback={() => void migration.rollback()}
onDismiss={migration.dismiss}
onDismiss={() => void migration.dismiss()}
/>
</section>
);
@@ -90,53 +121,6 @@ export default function ContainerMigrationBanner({
);
}
// Nothing is driving this one. It outranks staleness because the container is
// sitting mid-swap, and the one thing it must never do is look like a normal
// out-of-date container that the user can take or leave.
if (interrupted) {
return (
<section
className={`${SHELL} border-[var(--error)]/40 bg-[var(--error-muted)]`}
aria-label="Container base update was interrupted"
>
<StatusIndicator
tone="error"
label="A container base update was interrupted"
className="text-[13px] font-semibold"
/>
<p className="text-xs text-[var(--text-secondary)] leading-snug">
It started{" "}
{formatSnapshotDate(interrupted.started_at) ?? "earlier"} and the app
closed before it finished, so this container is part-way onto the new
base. Resuming replays the same plan it was given.
</p>
<p className="text-xs text-[var(--text-secondary)] leading-snug">
{ROLLBACK_SCOPE}
</p>
<div className="flex flex-wrap gap-1.5">
<Button
size="md"
variant="primary"
disabled={busy}
onClick={() => void migration.resume()}
>
Resume update
</Button>
{interrupted.rollback_image && (
<Button
size="md"
variant="danger"
disabled={busy}
onClick={() => void migration.rollback()}
>
Roll back
</Button>
)}
</div>
</section>
);
}
if (!staleness) return null;
// `stale` is deliberately false whenever `known` is false — an unestablished
@@ -210,9 +194,32 @@ export default function ContainerMigrationBanner({
</p>
)}
{/* An out-of-date container that also has data under /var is the one
case where updating can cost something, so it is said here and not
only behind the button. */}
{staleness.unpreserved_data.length > 0 && (
<p className="text-xs text-[var(--text-primary)] leading-snug">
Not carried across:{" "}
<span className="font-mono text-[var(--text-secondary)]">
{staleness.unpreserved_data.map((d) => d.path).join(", ")}
</span>
<span className="text-[var(--text-secondary)]">
{" "}
back this up before updating.
</span>
</p>
)}
{!canMigrate && (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
Stop the container to update its base.
{/* Distinguishing these matters: "stop the container" on a
container that is already stopped, because the probe has not
landed, reads as a bug. */}
{!probeSettled
? probing
? "Checking what this container has that the current base does not…"
: "That check did not complete, so what would be carried across is not known. Updating stays disabled until it does — try again once the container can be inspected."
: "Stop the container to update its base."}
</p>
)}
</div>
@@ -93,11 +93,17 @@ export default function ProjectHome({ projectId, active }: Props) {
// Reset does — with the extra condition that there is a container to migrate.
// An interrupted migration is excluded too: its action is Resume, on the
// Overview banner, not a fresh pre-flight.
//
// `probeSettled` is the fourth condition and it is not cosmetic. The probe
// takes ~6 s, and until it lands every delta the pre-flight renders reads as
// empty — so the dialog would tell the user there was nothing to copy while
// the backend was told not to copy anything.
const canMigrate =
isStopped &&
!actions.busy &&
!migration.running &&
!migration.interrupted &&
migration.probeSettled &&
!!project.container_id;
return (
+28 -1
View File
@@ -24,8 +24,23 @@ export const KEPT_AUTOMATICALLY = [
export const KEPT_WHY =
"/home/claude and ~/.claude are Docker volumes. They detach from the old container and re-attach to the new one unchanged.";
/**
* The honest list of what the writable layer holds, because the modal's own
* sections name more than one thing and copy that says "the only thing" while
* the section below it offers to copy files is copy the user cannot trust.
*/
export const LOST_WITHOUT_REPLAY =
"What a new base does not carry over is the root-level system packages you installed with apt. Those are the only thing this update has to put back.";
"What a new base does not carry over is what lives in the container itself: system packages you installed with apt, global npm packages, and files under /usr/local, /opt, /srv or loose in /workspace. This update puts those back.";
/**
* The exception, and it is not a small one — so it gets its own line wherever
* the update is offered. Reinstalling `postgresql` gets the package back and an
* empty cluster with it; the ordinary Reset-free recreate keeps /var because it
* builds from the project's own saved image, so this is the one way in which
* updating the base is more destructive than leaving it alone.
*/
export const DATA_NOT_CARRIED =
"Data written under /var is not carried across and reinstalling the package does not bring it back — a database in /var/lib, a site in /var/www. Back it up from inside the container before you update.";
/**
* Said plainly everywhere rollback is offered. Rollback is not a time machine:
@@ -45,6 +60,18 @@ export const MID_RUN_SAFETY =
export const REPLAY_COST =
"Needs network access and usually takes 12 minutes.";
/** `41.0 MB`. Sizes here are informational, so the friendlier decimal unit. */
export function formatDataSize(bytes: number): string {
const units = ["B", "KB", "MB", "GB", "TB"];
let value = bytes;
let unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit += 1;
}
return unit === 0 ? `${bytes} B` : `${value.toFixed(1)} ${units[unit]}`;
}
/** `1 Mar` — short enough to sit inline in the banner sentence. */
export function formatSnapshotDate(iso: string | null): string | null {
if (!iso) return null;
@@ -9,6 +9,11 @@ import {
authErrorMessage,
useClaudeTokenAcquisition,
} from "../../hooks/useClaudeAuth";
import {
ANTHROPIC_SIGN_IN_HOSTS,
sanitizeRelayUrl,
urlOrigin,
} from "../../lib/urlRelay";
interface Props {
/** Project whose running container is borrowed to run the CLI. */
@@ -85,11 +90,30 @@ export default function ClaudeAuthModal({
? PHASE_STATUS.finishing
: PHASE_STATUS.waiting;
// Split for display only. `flow.signInUrl` has already passed the host
// allowlist; this decides which half of it an ellipsis is allowed to eat.
const signInOrigin = flow.signInUrl ? (urlOrigin(flow.signInUrl) ?? "") : "";
const signInPath = flow.signInUrl
? flow.signInUrl.slice(signInOrigin.length)
: "";
const handleOpen = async () => {
if (!flow.signInUrl) return;
setLinkError(null);
// Re-validated at the sink. `extractSignInUrl` already applies the host
// allowlist, so a failure here means that invariant broke — which is the
// one moment it matters that the last step before the OS opener checks.
const target = sanitizeRelayUrl(flow.signInUrl, {
allowHosts: ANTHROPIC_SIGN_IN_HOSTS,
});
if (!target) {
setLinkError(
"That link is not an Anthropic sign-in address and was not opened. Start authentication again.",
);
return;
}
try {
await openUrl(flow.signInUrl);
await openUrl(target);
} catch (e) {
setLinkError(
authErrorMessage(
@@ -103,8 +127,19 @@ export default function ClaudeAuthModal({
const handleCopy = async () => {
if (!flow.signInUrl) return;
setLinkError(null);
// Copying is the manual route to the same browser, so it gets the same
// check — a link too dangerous to open is too dangerous to hand over.
const target = sanitizeRelayUrl(flow.signInUrl, {
allowHosts: ANTHROPIC_SIGN_IN_HOSTS,
});
if (!target) {
setLinkError(
"That link is not an Anthropic sign-in address and was not copied. Start authentication again.",
);
return;
}
try {
await navigator.clipboard.writeText(flow.signInUrl);
await navigator.clipboard.writeText(target);
setCopied(true);
} catch (e) {
setLinkError(
@@ -185,16 +220,32 @@ export default function ClaudeAuthModal({
{flow.signInUrl ? (
<div className="mt-1 space-y-1.5">
<div className="flex items-center gap-1.5">
{/* The origin is rendered at full length and the path is the
only part allowed to truncate. A single `truncate` element
showing the whole URL is a spoofing primitive: pad the
front and the ellipsis eats the half that decides where the
user's Anthropic password goes. */}
<a
href={flow.signInUrl}
onClick={(e) => {
e.preventDefault();
void handleOpen();
}}
className="min-w-0 flex-1 truncate px-2.5 py-1.5 font-mono text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] transition-colors"
className="flex min-w-0 flex-1 items-baseline px-2.5 py-1.5 font-mono text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] transition-colors"
title={flow.signInUrl}
>
{flow.signInUrl}
<span
data-testid="claude-auth-url-origin"
className="shrink-0 font-semibold [overflow-wrap:anywhere]"
>
{signInOrigin}
</span>
<span
data-testid="claude-auth-url-path"
className="min-w-0 truncate text-[var(--text-secondary)]"
>
{signInPath}
</span>
</a>
<Button size="md" onClick={() => void handleOpen()}>
Open
@@ -0,0 +1,105 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import GatewaySettings from "./GatewaySettings";
import type { AppSettings, GatewayStatus } from "../../lib/types";
const getGatewayStatus = vi.fn();
const stopGateway = vi.fn();
const startGateway = vi.fn();
const checkGatewayHealth = vi.fn();
const saveSettings = vi.fn();
vi.mock("../../lib/tauri-commands", () => ({
getGatewayStatus: () => getGatewayStatus(),
startGateway: () => startGateway(),
stopGateway: () => stopGateway(),
checkGatewayHealth: () => checkGatewayHealth(),
pullGatewayImage: vi.fn(),
buildGatewayImage: vi.fn(),
setGatewayApiKey: vi.fn(),
clearGatewayApiKey: vi.fn(),
getGatewayAuthToken: vi.fn(),
regenerateGatewayAuthToken: vi.fn(),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => vi.fn()) }));
let appSettings: AppSettings | null = null;
vi.mock("../../hooks/useSettings", () => ({
useSettings: () => ({ appSettings, saveSettings }),
}));
const settingsWithGateway = (enabled: boolean): AppSettings =>
({
gateway: { enabled, port: 4000, provider: "openai", api_base: null, models: [] },
}) as unknown as AppSettings;
const status = (over: Partial<GatewayStatus> = {}): GatewayStatus => ({
container_exists: true,
running: true,
port: 4000,
image_exists: true,
model_count: 0,
has_api_key: false,
base_url: "http://host.docker.internal:4000",
...over,
});
describe("GatewaySettings", () => {
beforeEach(() => {
vi.clearAllMocks();
appSettings = settingsWithGateway(false);
getGatewayStatus.mockResolvedValue(status());
checkGatewayHealth.mockResolvedValue(true);
saveSettings.mockImplementation(async (s: AppSettings) => s);
stopGateway.mockResolvedValue(undefined);
});
it("keeps a working Stop button when the gateway is disabled but its container exists", async () => {
render(<GatewaySettings />);
const stop = await screen.findByRole("button", { name: "Stop" });
// The configuration UI stays hidden — only the container row survives.
expect(screen.queryByLabelText("Provider")).not.toBeInTheDocument();
expect(screen.getByTestId("gateway-leftover-container")).toHaveTextContent(
/gateway container is still present/i,
);
// Status is a word, not just a colour.
expect(screen.getByTestId("gateway-leftover-container")).toHaveTextContent(
/Running on port 4000/,
);
fireEvent.click(stop);
await waitFor(() => expect(stopGateway).toHaveBeenCalledTimes(1));
// Stopping re-reads status: once on mount, once after the action.
await waitFor(() => expect(getGatewayStatus).toHaveBeenCalledTimes(2));
});
it("shows nothing extra when the gateway is disabled and no container exists", async () => {
getGatewayStatus.mockResolvedValue(status({ container_exists: false, running: false }));
render(<GatewaySettings />);
await waitFor(() => expect(getGatewayStatus).toHaveBeenCalled());
expect(screen.queryByTestId("gateway-leftover-container")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
});
it("re-reads container status after toggling the gateway off", async () => {
appSettings = settingsWithGateway(true);
render(<GatewaySettings />);
await waitFor(() => expect(getGatewayStatus).toHaveBeenCalledTimes(1));
// The backend stops the container as part of update_settings, so the UI has
// to re-read rather than trust the status it already has.
getGatewayStatus.mockResolvedValue(status({ running: false }));
fireEvent.click(screen.getByRole("switch", { name: "Model gateway" }));
await waitFor(() =>
expect(saveSettings).toHaveBeenCalledWith(
expect.objectContaining({ gateway: expect.objectContaining({ enabled: false }) }),
),
);
await waitFor(() => expect(getGatewayStatus).toHaveBeenCalledTimes(2));
});
});
@@ -79,9 +79,17 @@ export default function GatewaySettings() {
refreshStatus();
}, [refreshStatus]);
/**
* Persist a gateway settings change, then re-read the container status.
*
* `update_settings` reconciles the container itself it stops the gateway
* when `enabled` goes false and recreates it on a port change so the status
* we are holding is stale the moment the save returns.
*/
const patch = async (changes: Partial<GatewaySettingsType>) => {
if (!appSettings) return;
await saveSettings({ ...appSettings, gateway: { ...gateway, ...changes } });
await refreshStatus();
};
const savePort = async () => {
@@ -190,6 +198,13 @@ export default function GatewaySettings() {
? "Stopped"
: "Image ready";
// Rendered in whichever branch is live — only one of them ever mounts.
const errorLine = error ? (
<p className="text-xs text-[var(--error)]" role="alert">
{error}
</p>
) : null;
return (
<div>
<label className="block text-sm font-medium mb-1">Model Gateway</label>
@@ -213,6 +228,27 @@ export default function GatewaySettings() {
}
/>
{/*
Turning the gateway off hides its configuration, but a container that
already exists must stay reachable otherwise a leftover container
keeps its port bound with no UI left to stop it.
*/}
{!gateway.enabled && status?.container_exists && (
<div className="space-y-2" data-testid="gateway-leftover-container">
<div className="flex items-center gap-3 flex-wrap">
<StatusIndicator tone={tone} label={statusLabel} className="text-xs" />
<Button variant="danger" disabled={loading} onClick={() => run(stopGateway)}>
{loading ? "Working…" : "Stop"}
</Button>
</div>
<p className="text-xs text-[var(--text-secondary)] leading-snug">
The gateway container is still present. Stop it here if it is still running; it
will not be started again while the gateway is off.
</p>
{errorLine}
</div>
)}
{gateway.enabled && (
<>
{/* ── Container ─────────────────────────────────────────────── */}
@@ -247,11 +283,7 @@ export default function GatewaySettings() {
</pre>
)}
{error && (
<p className="text-xs text-[var(--error)]" role="alert">
{error}
</p>
)}
{errorLine}
{/* ── Provider ──────────────────────────────────────────────── */}
<Field
@@ -395,10 +427,10 @@ export default function GatewaySettings() {
</div>
<p className="mt-0.5 text-xs text-[var(--text-secondary)] leading-snug">
Set a project's backend to <strong>OpenAI Compatible</strong> and use these
values. On native Linux Docker, where{" "}
<code className="font-mono">host.docker.internal</code> is not injected into
containers, use <code className="font-mono">http://172.17.0.1:{gateway.port}</code>{" "}
instead.
values. The base URL below is the one your Docker engine actually needs {" "}
<code className="font-mono">host.docker.internal</code> on Docker Desktop, the
bridge gateway address on native Linux, where that name is not injected into
containers.
</p>
</div>
@@ -1,7 +1,8 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import SharedAuthSettings from "./SharedAuthSettings";
import type { Project } from "../../lib/types";
import { useAppState } from "../../store/appState";
import type { ClearTokenOutcome, Project } from "../../lib/types";
const hasClaudeToken = vi.fn();
const clearClaudeToken = vi.fn();
@@ -63,8 +64,29 @@ describe("SharedAuthSettings", () => {
vi.clearAllMocks();
projects = [];
hasClaudeToken.mockResolvedValue(false);
useAppState.setState({ toasts: [] });
});
/** Open the confirmation and go through with it. */
async function revoke(outcome: Partial<ClearTokenOutcome>) {
projects = [running()];
hasClaudeToken.mockResolvedValue(true);
clearClaudeToken.mockResolvedValue({
snapshots_scrubbed: [],
snapshots_failed: [],
snapshots_superseded: [],
docker_unavailable: null,
...outcome,
});
render(<SharedAuthSettings />);
fireEvent.click(await screen.findByRole("button", { name: "Revoke" }));
fireEvent.click(await screen.findByRole("button", { name: "Revoke token" }));
await waitFor(() =>
expect(useAppState.getState().toasts.length).toBeGreaterThan(0),
);
return useAppState.getState().toasts[0];
}
it("disables Authenticate and says why when nothing is running", async () => {
projects = [baseProject];
render(<SharedAuthSettings />);
@@ -123,4 +145,48 @@ describe("SharedAuthSettings", () => {
await screen.findByText("keyring backend unavailable");
expect(screen.queryByRole("button", { name: "Revoke" })).not.toBeInTheDocument();
});
// ── Revoking has to tell the truth ──────────────────────────────────────
// Deleting the keychain entry is only part of it. `docker commit` copies the
// token into each project's snapshot image, and an image outlives every
// container built from it — so a "removed" message while a snapshot still
// holds a live ~1-year credential is the wrong thing to say.
it("says so plainly when snapshot images were cleared too", async () => {
const toast = await revoke({
snapshots_scrubbed: ["triple-c-snapshot-p1:latest"],
});
expect(toast.kind).toBe("success");
expect(toast.message).toMatch(/1 snapshot image/);
});
it("reports an error, not success, when an image still holds the token", async () => {
const toast = await revoke({
snapshots_failed: ["triple-c-snapshot-p1:latest: image has child images"],
});
expect(toast.kind).toBe("error");
expect(toast.message).toMatch(/still in some images/i);
expect(toast.detail).toMatch(/triple-c-snapshot-p1/);
});
it("does not claim the images are clean when Docker could not be reached", async () => {
const toast = await revoke({ docker_unavailable: "Docker is not running" });
expect(toast.kind).toBe("error");
expect(toast.detail).toMatch(/Docker could not be reached/);
});
it("mentions a retained image layer without calling the revoke a failure", async () => {
const toast = await revoke({
snapshots_scrubbed: ["triple-c-snapshot-p1:latest"],
snapshots_superseded: ["triple-c-snapshot-p1:latest"],
});
expect(toast.kind).toBe("success");
expect(toast.detail).toMatch(/still on disk because a container is running/);
});
it("still succeeds plainly when there was nothing to scrub", async () => {
const toast = await revoke({});
expect(toast.kind).toBe("success");
expect(toast.message).toBe("Shared Claude token removed from the keychain.");
});
});
@@ -64,13 +64,52 @@ export default function SharedAuthSettings() {
const handleRevoke = async () => {
setRevoking(true);
try {
await clearClaudeToken();
const outcome = await clearClaudeToken();
setConfirmRevoke(false);
await refresh();
pushToast({
kind: "success",
message: "Shared Claude token removed from the keychain.",
});
// The keychain entry is gone either way. What matters here is the copy of
// the token that `docker commit` baked into each project's snapshot
// image: that one outlives every container, and `docker image inspect`
// will keep printing it until the image is rewritten. If that could not
// be done, the revocation is incomplete and saying "removed" would be a
// lie.
if (outcome.docker_unavailable) {
pushToast({
kind: "error",
message: "Token removed from the keychain, but snapshots were not checked.",
detail:
`Docker could not be reached (${outcome.docker_unavailable}), so any snapshot image ` +
"built before this version may still contain the token in its environment. " +
"Start Docker and revoke again to clear them.",
});
} else if (outcome.snapshots_failed.length > 0) {
pushToast({
kind: "error",
message: "Token removed from the keychain, but it is still in some images.",
detail:
`${outcome.snapshots_failed.length} snapshot image(s) could not be rewritten and ` +
"still contain the token, readable via `docker image inspect`. Reset those " +
`projects to remove the images. Details: ${outcome.snapshots_failed.join("; ")}`,
});
} else if (outcome.snapshots_scrubbed.length > 0) {
pushToast({
kind: "success",
message: `Shared Claude token removed, and cleared from ${outcome.snapshots_scrubbed.length} snapshot image(s).`,
detail:
outcome.snapshots_superseded.length > 0
? "The pre-rewrite image layer for " +
`${outcome.snapshots_superseded.join(", ")} is still on disk because a ` +
"container is running from it. It goes away once that project is restarted " +
"(which recreates the container) and Docker prunes the leftover."
: undefined,
});
} else {
pushToast({
kind: "success",
message: "Shared Claude token removed from the keychain.",
});
}
} catch (e) {
pushToast({
kind: "error",
@@ -220,6 +259,13 @@ export default function SharedAuthSettings() {
container starts. Existing running containers keep working until they are
restarted.
</p>
<p className="mt-2 text-[13px] text-[var(--text-secondary)] leading-snug">
Each project&rsquo;s snapshot image is also rewritten, because{" "}
<code className="font-mono">docker commit</code> copies the token into it
and an image outlives every container built from it. If any image
cannot be rewritten you will be told which, and the token stays readable
in it until that project is Reset.
</p>
</Modal>
)}
</div>
+58 -12
View File
@@ -14,6 +14,7 @@ import {
RelayRateLimiter,
URL_RELAY_OSC,
parseUrlRelayOsc,
sanitizeRelayUrl,
} from "../../lib/urlRelay";
import UrlToast from "./UrlToast";
import { trimSelection } from "./trimSelection";
@@ -45,10 +46,38 @@ export default function TerminalView({ sessionId, active }: Props) {
// One toast slot, two producers: the heuristic long-URL detector and the
// container's explicit "open this in the host browser" relay (OSC 7777).
// Sharing the slot keeps them from stacking on top of each other.
const [urlPrompt, setUrlPrompt] = useState<{ url: string; label: string } | null>(
null,
);
//
// Both producers read the container's PTY output, so both are untrusted, and
// both must go through `sanitizeRelayUrl` before anything is stored here —
// see `promptUrl` below, which is the only writer.
//
// `seq` exists because the slot is shared and long-lived: a second prompt
// replacing a first would otherwise mutate the toast in place, swapping the
// text under a user who is mid-read and mid-click. Keying the toast on it
// remounts the component, so a new URL is unmistakably a new prompt.
const [urlPrompt, setUrlPrompt] = useState<{
url: string;
label: string;
seq: number;
} | null>(null);
const promptSeqRef = useRef(0);
const relayLimiterRef = useRef(new RelayRateLimiter());
/**
* The only writer of the prompt slot. Re-validates whatever the caller
* found: the OSC relay branch has already been through `parseUrlRelayOsc`,
* but the heuristic detector branch has been through nothing at all, and a
* raw regex match is exactly the input `sanitizeRelayUrl` exists to refuse.
*/
const promptUrl = useCallback((raw: string, label: string) => {
const url = sanitizeRelayUrl(raw);
if (!url) {
console.warn("Refusing to prompt for a URL that failed validation");
return;
}
promptSeqRef.current += 1;
setUrlPrompt({ url, label, seq: promptSeqRef.current });
}, []);
const [imagePasteMsg, setImagePasteMsg] = useState<string | null>(null);
const [isAtBottom, setIsAtBottom] = useState(true);
const [isAutoFollow, setIsAutoFollow] = useState(true);
@@ -162,9 +191,19 @@ export default function TerminalView({ sessionId, active }: Props) {
// Web links addon — opens URLs in host browser via Tauri, with a permissive regex
// that matches URLs even if they lack trailing path segments (the default regex
// misses OAuth URLs that end mid-line).
const urlRegex = /https?:\/\/[^\s'"\x07]+/;
// eslint-disable-next-line no-control-regex
const urlRegex = /https?:\/\/[^\s'"`<>\x00-\x20\x7f]+/;
const webLinksAddon = new WebLinksAddon((_event, uri) => {
openUrl(uri).catch((e) => console.error("Failed to open URL:", e));
// Same sink, same rule: what xterm matched came off the container's
// output, so it is validated before it reaches the OS opener. A click
// here is a deliberate act on visible text, but "visible" is exactly
// what a userinfo-spoofed URL subverts.
const safe = sanitizeRelayUrl(uri);
if (!safe) {
console.warn("Refusing to open a link that failed validation");
return;
}
openUrl(safe).catch((e) => console.error("Failed to open URL:", e));
}, { urlRegex });
term.loadAddon(webLinksAddon);
@@ -244,7 +283,7 @@ export default function TerminalView({ sessionId, active }: Props) {
console.warn("URL relay: rate-limited", url);
return true;
}
setUrlPrompt({ url, label: "Container asked to open a URL" });
promptUrl(url, "Container asked to open a URL");
return true;
});
@@ -332,7 +371,7 @@ export default function TerminalView({ sessionId, active }: Props) {
let aborted = false;
const detector = new UrlDetector((url) =>
setUrlPrompt({ url, label: "Long URL detected" }),
promptUrl(url, "Long URL detected"),
);
detectorRef.current = detector;
@@ -477,12 +516,17 @@ export default function TerminalView({ sessionId, active }: Props) {
}, [imagePasteMsg]);
const handleOpenUrl = useCallback(() => {
if (urlPrompt) {
openUrl(urlPrompt.url).catch((e) =>
console.error("Failed to open URL:", e),
);
setUrlPrompt(null);
if (!urlPrompt) return;
// Validated again at the sink. `promptUrl` is the only writer and already
// sanitizes, so this can only fail if that invariant is broken — which is
// precisely when it matters that the last thing before `openUrl` checks.
const safe = sanitizeRelayUrl(urlPrompt.url);
setUrlPrompt(null);
if (!safe) {
console.warn("Refusing to open a URL that failed validation");
return;
}
openUrl(safe).catch((e) => console.error("Failed to open URL:", e));
}, [urlPrompt]);
const handleScrollToBottom = useCallback(() => {
@@ -557,6 +601,8 @@ export default function TerminalView({ sessionId, active }: Props) {
>
{urlPrompt && (
<UrlToast
// A different URL is a different prompt, not an edit of this one.
key={urlPrompt.seq}
url={urlPrompt.url}
label={urlPrompt.label}
onOpen={handleOpenUrl}
@@ -0,0 +1,61 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import UrlToast from "./UrlToast";
/**
* The toast is the *only* thing standing between a container-chosen URL and
* the host's browser, so what it shows has to be what will be opened and the
* part that decides that is the origin.
*/
describe("UrlToast", () => {
const noop = () => {};
it("shows the origin separately from the truncatable remainder", () => {
render(
<UrlToast
url="https://github.com/login/device?code=ABCD-EFGH"
onOpen={noop}
onDismiss={noop}
/>,
);
expect(screen.getByTestId("url-toast-origin")).toHaveTextContent(
"https://github.com",
);
expect(screen.getByTestId("url-toast-rest")).toHaveTextContent(
"/login/device?code=ABCD-EFGH",
);
});
it("keeps the origin intact when the path is long enough to push it out", () => {
const url = `https://evil.tld/${"padding/".repeat(200)}end`;
render(<UrlToast url={url} onOpen={noop} onDismiss={noop} />);
// The registrable domain must be present in its own element, whole. A
// single ellipsised line would render this and show only the padding.
expect(screen.getByTestId("url-toast-origin")).toHaveTextContent(
"https://evil.tld",
);
});
it("exposes the whole URL as a tooltip", () => {
const url = "https://example.com/a/b?c=d";
render(<UrlToast url={url} onOpen={noop} onDismiss={noop} />);
expect(screen.getByTestId("url-toast-url")).toHaveAttribute("title", url);
});
it("announces itself, so a replacement prompt is not silent", () => {
render(
<UrlToast url="https://example.com/" onOpen={noop} onDismiss={noop} />,
);
expect(screen.getByRole("status")).toBeInTheDocument();
});
it("opens only via the button, never on its own", () => {
const onOpen = vi.fn();
render(
<UrlToast url="https://example.com/" onOpen={onOpen} onDismiss={noop} />,
);
expect(onOpen).not.toHaveBeenCalled();
screen.getByRole("button", { name: "Open" }).click();
expect(onOpen).toHaveBeenCalledTimes(1);
});
});
+55 -4
View File
@@ -1,4 +1,7 @@
import { urlOrigin } from "../../lib/urlRelay";
interface Props {
/** Already validated by `sanitizeRelayUrl` — this component never opens it. */
url: string;
/** Heading above the URL. Says why the toast appeared. */
label?: string;
@@ -6,15 +9,36 @@ interface Props {
onDismiss: () => void;
}
/**
* Confirmation prompt for a URL something inside the container wants opened in
* the host browser.
*
* The origin is rendered separately from the rest of the URL and is never
* truncated. A single `nowrap`/`ellipsis` line looks tidy but is a spoofing
* primitive: `https://accounts.example.com/....(600 chars)....@evil.tld/` shows
* the reassuring half and hides the half that decides where the request goes.
* `sanitizeRelayUrl` already rejects the userinfo form; showing the origin in
* full is the belt to that braces, and it also covers the plainer case of a
* long path pushing the host out of view.
*
* Render this with a `key` that changes whenever the URL does. The prompt slot
* is shared and long-lived, so without one React mutates the node in place: the
* text swaps with no animation, and a user reading URL A can click Open on URL
* B that arrived a second later.
*/
export default function UrlToast({
url,
label = "Long URL detected",
onOpen,
onDismiss,
}: Props) {
const origin = urlOrigin(url);
const rest = origin && url.startsWith(origin) ? url.slice(origin.length) : url;
return (
<div
className="animate-slide-down"
role="status"
style={{
position: "absolute",
top: 12,
@@ -43,16 +67,43 @@ export default function UrlToast({
{label}
</div>
<div
data-testid="url-toast-url"
title={url}
style={{
fontSize: 12,
fontFamily: "monospace",
color: "var(--text-primary)",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
display: "flex",
alignItems: "baseline",
minWidth: 0,
}}
>
{url}
{origin && (
<span
data-testid="url-toast-origin"
style={{
fontWeight: 700,
// The part that decides where the credentials go. It wraps
// rather than truncates, whatever else has to give.
flexShrink: 0,
overflowWrap: "anywhere",
}}
>
{origin}
</span>
)}
<span
data-testid="url-toast-rest"
style={{
color: "var(--text-secondary)",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
minWidth: 0,
}}
>
{rest}
</span>
</div>
</div>