Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/api/src/auth-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export function safeReturnTo(value: string | undefined): string {
try {
const url = new URL(value, "https://local.invalid");
if (url.origin !== "https://local.invalid") return "/settings/integrations";
if (!/^\/(?:authorize|device|jobs(?:\/[^/]+(?:\/edit)?)?|job-runs\/[^/]+|settings(?:\/(?:integrations|api-keys|password))?)$/.test(url.pathname)) return "/settings/integrations";
if (!/^\/(?:authorize|device|jobs(?:\/[^/]+(?:\/(?:edit|settings))?)?|job-runs\/[^/]+|settings(?:\/(?:integrations|api-keys|password))?)$/.test(url.pathname)) return "/settings/integrations";
return url.pathname + url.search + url.hash;
} catch { return "/settings/integrations"; }
}
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/static-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Env } from "./types";
export const STATIC_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'";
const pages = new Set(["/", "/jobs", "/jobs/new", "/settings", "/settings/integrations", "/settings/api-keys", "/settings/authorized-clients", "/settings/password", "/auth/login", "/auth/signup", "/auth/password-reset", "/auth/verify", "/auth/verify/request", "/authorize", "/device"]);
export function isStaticPage(path: string) {
return pages.has(path) || /^\/jobs\/[^/]+(?:\/edit)?$/.test(path) || /^\/job-runs\/[^/]+$/.test(path);
return pages.has(path) || /^\/jobs\/[^/]+(?:\/(?:edit|settings))?$/.test(path) || /^\/job-runs\/[^/]+$/.test(path);
}
export function isStaticAsset(path: string) {
return /^\/assets\/[A-Za-z0-9_.-]+$/.test(path) || path === "/styles.css";
Expand Down
4 changes: 2 additions & 2 deletions packages/api/test/auth-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,8 @@ describe("public auth API and cookie security", () => {
});

describe("safe interrupted-flow navigation", () => {
it.each(["//evil.test", "https://evil.test", "/\\evil.test", "/device-evil", "/auth/logout", "/jobs\nLocation:evil", "/%2f%2fevil.test"])("rejects %s", value => expect(safeReturnTo(value)).toBe("/settings/integrations"));
it.each(["/authorize?client_id=a&state=b", "/device?user_code=ABCD-EFGH", "/jobs/job-a/edit", "/job-runs/run-a"])("preserves %s", value => expect(safeReturnTo(value)).toBe(value));
it.each(["//evil.test", "https://evil.test", "/\\evil.test", "/device-evil", "/jobs/job-a/settings/extra", "/auth/logout", "/jobs\nLocation:evil", "/%2f%2fevil.test"])("rejects %s", value => expect(safeReturnTo(value)).toBe("/settings/integrations"));
it.each(["/authorize?client_id=a&state=b", "/device?user_code=ABCD-EFGH", "/jobs/job-a/edit", "/jobs/job-a/settings?tab=prompt", "/job-runs/run-a"])("preserves %s", value => expect(safeReturnTo(value)).toBe(value));
});

describe("cookie-only consent and device API boundaries", () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/api/test/static-routing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ describe("same-origin static ownership", () => {
it("serves explicit deep links with an external-bundle policy and revalidated entry HTML", async () => {
const fetch = vi.fn(async (request: Request) => new Response(request.method === "HEAD" ? null : "entry", { headers: { "Content-Type": "text/html" } }));
const env = { ASSETS: { fetch } } as unknown as Env;
for (const path of ["/", "/jobs", "/jobs/new", "/jobs/id/edit", "/job-runs/id", "/settings/authorized-clients", "/auth/verify?token=one-time", "/authorize?client_id=test", "/device?user_code=ABCD-2345"]) {
for (const path of ["/", "/jobs", "/jobs/new", "/jobs/id/edit", "/jobs/id/settings", "/job-runs/id", "/settings/authorized-clients", "/auth/verify?token=one-time", "/authorize?client_id=test", "/device?user_code=ABCD-2345"]) {
const response = await staticApp(new Request(`https://app.factorize.sh${path}`), env);
expect(response?.status).toBe(200);
expect(response?.headers.get("content-security-policy")).toBe(STATIC_CSP);
Expand All @@ -21,7 +21,7 @@ describe("same-origin static ownership", () => {
});
it("never forwards backend namespaces, unknown routes or mutations to static hosting", async () => {
const fetch = vi.fn(); const env = { ASSETS: { fetch } } as unknown as Env;
for (const path of ["/api/v1", "/api/v1/unknown", "/api/v1/jobs", "/oauth/token", "/auth/linear", "/auth/github/setup", "/webhooks/github", "/internal/missing", "/mcp", "/healthz", "/.well-known/oauth-authorization-server", "/unknown", "/assets/subdir/file.js", "/index.html", "/jobs/id/edit/extra"]) {
for (const path of ["/api/v1", "/api/v1/unknown", "/api/v1/jobs", "/oauth/token", "/auth/linear", "/auth/github/setup", "/webhooks/github", "/internal/missing", "/mcp", "/healthz", "/.well-known/oauth-authorization-server", "/unknown", "/assets/subdir/file.js", "/index.html", "/jobs/id/edit/extra", "/jobs/id/settings/extra", "/jobs/id/unknown"]) {
expect(await staticApp(new Request(`https://app.factorize.sh${path}`), env)).toBeNull();
}
for (const method of ["POST", "PUT", "DELETE", "OPTIONS"]) for (const path of ["/jobs", "/authorize", "/device", "/assets/index-hash.js", "/auth/login"]) expect(await staticApp(new Request(`https://app.factorize.sh${path}`, { method }), env)).toBeNull();
Expand Down
9 changes: 8 additions & 1 deletion packages/api/test/static-slice.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,21 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => {
});
const page = await context.newPage(); page.setDefaultTimeout(10000);
await page.goto(`https://factorize.test/jobs/${job.id}/edit`);
await page.waitForURL(`**/jobs/${job.id}/settings`);
await page.getByLabel("Prompt template", { exact: true }).fill("My edited prompt");
await service.updateJob(job.id, { name: "Concurrent name", slug: job.slug, promptTemplate: job.promptTemplate, executionTargetId: job.executionTargetId, concurrencyLimit: 1, triggers: [{ id: job.triggers[0].id, slug: job.triggers[0].slug, kind: "manual", enabled: true, config: {} }], expectedUpdatedAt: job.updatedAt });
await page.getByRole("button", { name: "Save job", exact: true }).click();
await page.getByRole("button", { name: "Reconcile my changes" }).click();
expect(await page.getByLabel("Name", { exact: true }).inputValue()).toBe("Concurrent name");
await page.getByRole("button", { name: "Save job", exact: true }).click(); await page.waitForURL(`**/jobs/${job.id}`);
await page.getByRole("button", { name: "Save job", exact: true }).click();
await page.getByRole("status").filter({ hasText: "Job settings saved." }).waitFor();
expect(new URL(page.url()).pathname).toBe(`/jobs/${job.id}/settings`);
const saved = await service.getJob(job.id); expect(saved.name).toBe("Concurrent name"); expect(saved.promptTemplate).toBe("My edited prompt"); expect(saved.triggers[0].id).toBe(job.triggers[0].id);
const row = (await f.db.pool.query("SELECT encrypted_prompt_template FROM app.jobs WHERE tenant_id=$1 AND id=$2", [f.tenantId, job.id])).rows[0]; expect(await decrypt(row.encrypted_prompt_template, f.env.CREDENTIAL_ENCRYPTION_KEY)).toBe("My edited prompt");
await page.reload();
await page.getByLabel("Prompt template", { exact: true }).waitFor();
expect(await page.getByLabel("Name", { exact: true }).inputValue()).toBe("Concurrent name");
expect(await page.getByLabel("Prompt template", { exact: true }).inputValue()).toBe("My edited prompt");
await page.goto("https://factorize.test/settings/api-keys"); await page.getByLabel("Key name").fill("Real key"); await page.getByRole("button", { name: "Create key" }).click(); await page.getByText("Copy this key now. It will only be displayed once.", { exact: true }).waitFor();
await page.getByRole("button", { name: "Dismiss key" }).click(); await page.reload(); await page.getByText("Real key", { exact: true }).waitFor();
page.once("dialog", dialog => dialog.accept()); await page.getByRole("button", { name: "Revoke key" }).click(); await page.getByText("Revoked", { exact: true }).waitFor();
Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/features/jobs/delete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { useNavigate } from "@tanstack/react-router";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "factorize-api-client";
import { messageOf } from "../auth/session";
export function DeleteJob({ jobId, name }: { jobId: string; name: string }) {
export function DeleteJob({ jobId, name, disabled = false, onDeleted }: { jobId: string; name: string; disabled?: boolean; onDeleted?: () => void }) {
const cache = useQueryClient(), navigate = useNavigate();
const remove = useMutation({ retry: false, mutationFn: async () => { const { error } = await api.DELETE("/api/v1/jobs/{jobId}", { params: { path: { jobId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: async () => { await cache.invalidateQueries({ queryKey: ["jobs"] }); await cache.invalidateQueries({ queryKey: ["runs"] }); void navigate({ to: "/jobs", search: { q: "" } }); } });
return <Card className="my-6"><h2 className="text-base">Delete this job</h2><p className="mb-4 text-sm text-slate-600 dark:text-slate-400">Permanently remove this job, its execution history, and artifacts.</p><Button variant="destructive" disabled={remove.isPending} onClick={() => { if (window.confirm(`Delete ${name} and its execution history and artifacts? This cannot be undone.`)) remove.mutate(); }}>Delete job</Button>{remove.error && <p role="alert">{remove.error.message}</p>}</Card>;
const remove = useMutation({ retry: false, mutationFn: async () => { const { error } = await api.DELETE("/api/v1/jobs/{jobId}", { params: { path: { jobId } } }); if (error) throw new Error(messageOf(error)); }, onSuccess: async () => { onDeleted?.(); await cache.invalidateQueries({ queryKey: ["jobs"] }); await cache.invalidateQueries({ queryKey: ["runs"] }); void navigate({ to: "/jobs", search: { q: "" } }); } });
return <Card className="my-6"><h2 className="text-base">Delete this job</h2><p className="mb-4 text-sm text-slate-600 dark:text-slate-400">Permanently remove this job, its execution history, and artifacts.</p><Button variant="destructive" disabled={disabled || remove.isPending} onClick={() => { if (window.confirm(`Delete ${name} and its execution history and artifacts? This cannot be undone.`)) remove.mutate(); }}>Delete job</Button>{remove.error && <p role="alert">{remove.error.message}</p>}</Card>;
}
11 changes: 4 additions & 7 deletions packages/app/src/features/jobs/detail.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Disclosure, Summary, Badge, Button, Page, Card } from "../../shared/ui";
import { DeleteJob } from "./delete";
import { Badge, Button, Page } from "../../shared/ui";
import { JobTabs } from "./tabs";
import { RunHistory } from "../runs/history";
import { useParams, Link } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
Expand All @@ -17,13 +17,10 @@ export function JobDetail() {
const job = query.data;
return <Page className="max-w-6xl"><Link to="/jobs" search={{ q: "" }}>Jobs</Link>
{query.isPending && <p role="status">Loading job…</p>}{query.error && <p role="alert">{query.error.message}</p>}
{job && <><h1 className="mt-5 text-3xl font-semibold">{job.name}</h1><div className="mb-6 flex flex-wrap items-center gap-3"><Badge active={job.enabled}>{job.enabled ? "Enabled" : "Disabled"}</Badge><p className="text-sm text-slate-600 dark:text-slate-400">{job.agentKind} · {job.model || "Default model"} · {job.runningCount}/{job.concurrencyLimit} running</p></div><div className="mb-6 flex flex-wrap items-center gap-3"><InvokeJob jobId={job.id} enabled={job.enabled} />
<Link to="/jobs/$jobId/edit" params={{ jobId: job.id }} className="rounded-lg border border-stone-300 px-3 py-2 text-sm font-semibold dark:border-slate-700">Edit job</Link>
{job && <><h1 className="mt-5 break-words text-3xl font-semibold">{job.name}</h1><JobTabs jobId={job.id} /><div className="mb-6 flex flex-wrap items-center gap-3"><Badge active={job.enabled}>{job.enabled ? "Enabled" : "Disabled"}</Badge><p className="text-sm text-slate-600 dark:text-slate-400">{job.agentKind} · {job.model || "Default model"} · {job.runningCount}/{job.concurrencyLimit} running</p></div><div className="mb-6 flex flex-wrap items-center gap-3"><InvokeJob jobId={job.id} enabled={job.enabled} />
<Button disabled={enabled.isPending} onClick={() => enabled.mutate(!job.enabled)}>{job.enabled ? "Disable job" : "Enable job"}</Button>
</div>{enabled.error && <p role="alert">{enabled.error.message}</p>}
<Disclosure><Summary>Prompt template</Summary><pre className="whitespace-pre-wrap break-words">{job.promptTemplate}</pre></Disclosure>
<Card><h2>Triggers</h2><ul>{job.triggers.map(trigger => <li key={trigger.id}>{trigger.slug} · {trigger.kind} · {trigger.enabled ? "Enabled" : "Disabled"}{trigger.kind === "webhook" && <span> · {trigger.config.conditions ? "Conditions configured" : "No additional conditions"}</span>}{trigger.kind === "webhook" && trigger.config.provider === "cloudflareTail" && trigger.config.destination && <><p>Tail webhook destination</p><code className="break-all">{trigger.config.destination}</code></>}</li>)}</ul></Card>
<RunHistory jobId={job.id} /><DeleteJob jobId={job.id} name={job.name} />
<RunHistory jobId={job.id} />
</>}
</Page>;
}
13 changes: 8 additions & 5 deletions packages/app/src/features/jobs/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Disclosure, Summary, Button, Input, Select, Label, Page, Card } from "../../shared/ui";
import { JobTabs } from "./tabs";
import { DeleteJob } from "./delete";
import { validationMessage } from "./validation-message";
import { useEffect, useState, useRef } from "react";
import { Link, useNavigate, useParams, useBlocker } from "@tanstack/react-router";
Expand All @@ -24,12 +26,12 @@ function EditorForm({ initial }: { initial?: Job }) {
const [remote, setRemote] = useState<Job>(), [conflicts, setConflicts] = useState<(keyof JobInput)[]>([]);
const [reconciling, setReconciling] = useState(false), [saved, setSaved] = useState(false);
const savingNavigation = useRef(false);
const dirty = !saved && JSON.stringify(base) !== JSON.stringify(draft);
const dirty = JSON.stringify(base) !== JSON.stringify(draft);
useBlocker({ shouldBlockFn: () => dirty && !savingNavigation.current && !window.confirm("Discard unsaved job changes?"), enableBeforeUnload: dirty });
useEffect(() => { const handler = (event: BeforeUnloadEvent) => { if (dirty) { event.preventDefault(); event.returnValue = ""; } }; window.addEventListener("beforeunload", handler); return () => window.removeEventListener("beforeunload", handler); }, [dirty]);
const targets = useQuery(targetsQuery), metadata = useQuery(metadataQuery);
const target = targets.data?.find(t => t.id === draft.executionTargetId);
const update = <K extends keyof JobInput>(key: K, value: JobInput[K]) => setDraft(previous => ({ ...previous, [key]: value }));
const update = <K extends keyof JobInput>(key: K, value: JobInput[K]) => { setSaved(false); setDraft(previous => ({ ...previous, [key]: value })); };
const refreshConflict = useMutation({ retry: false, mutationFn: async () => {
if (!initial) throw new Error("No job selected");
const { data, error } = await api.GET("/api/v1/jobs/{jobId}", { params: { path: { jobId: initial.id } } });
Expand All @@ -43,7 +45,7 @@ function EditorForm({ initial }: { initial?: Job }) {
throw new Error(validationMessage(result.error));
}
return result.data;
}, onSuccess: async value => { savingNavigation.current = true; setSaved(true); setBase(editableJob(value)); cache.setQueryData(jobQuery(value.id).queryKey, value); await cache.invalidateQueries({ queryKey: ["jobs"] }); void navigate({ to: "/jobs/$jobId", params: { jobId: value.id } }); } });
}, onSuccess: async value => { savingNavigation.current = true; setSaved(true); setBase(editableJob(value)); setDraft(editableJob(value)); setRevision(value.updatedAt); cache.setQueryData(jobQuery(value.id).queryKey, value); await cache.invalidateQueries({ queryKey: ["jobs"] }); if (!initial) void navigate({ to: "/jobs/$jobId", params: { jobId: value.id } }); else savingNavigation.current = false; } });
const acceptRemote = () => { if (!remote) return; const value = editableJob(remote); setDraft(value); setBase(value); setRevision(remote.updatedAt); setRemote(undefined); setConflicts([]); save.reset(); };
const merge = () => { if (!remote) return; const value = editableJob(remote), result = reconcile(base, draft, value); setDraft(result.merged); setConflicts(result.conflicts); setBase(value); setRevision(remote.updatedAt); if (!result.conflicts.length) setRemote(undefined); save.reset(); };
const resolve = (field: keyof JobInput, local: boolean) => {
Expand All @@ -52,7 +54,7 @@ function EditorForm({ initial }: { initial?: Job }) {
if (conflicts.length === 1) setRemote(undefined);
};
const [localConflictDraft, setLocalConflictDraft] = useState(draft);
return <Page className="max-w-6xl"><Link to="/jobs" search={{ q: "" }}>Jobs</Link><h1 className="text-3xl font-semibold">{initial ? "Edit job" : "Create job"}</h1>
return <Page className="max-w-6xl"><Link to="/jobs" search={{ q: "" }}>Jobs</Link><h1 className="mt-5 break-words text-3xl font-semibold">{initial ? initial.name : "Create job"}</h1>{initial && <JobTabs jobId={initial.id} />}
{(remote || reconciling || refreshConflict.error) && <Card role="alert" className="my-4 border p-4"><h2>This job changed while you were editing</h2><p>Your unsaved draft is retained. Review the latest configuration before retrying.</p>
{refreshConflict.isPending && <p>Loading latest configuration…</p>}{refreshConflict.error && <><p>{refreshConflict.error.message}</p><Button onClick={() => refreshConflict.mutate()}>Retry loading latest</Button></>}
{remote && !conflicts.length && <><pre className="max-h-64 overflow-auto whitespace-pre-wrap">{JSON.stringify(editableJob(remote), null, 2)}</pre><Button onClick={acceptRemote}>Reload latest and discard my changes</Button><Button onClick={() => { setLocalConflictDraft(draft); merge(); }}>Reconcile my changes</Button></>}
Expand All @@ -70,8 +72,9 @@ function EditorForm({ initial }: { initial?: Job }) {
<TemplateField label="Run name template" value={draft.runNameTemplate ?? ""} onChange={value => update("runNameTemplate", value)} triggers={draft.triggers} />
<Disclosure><Summary>Template variables</Summary>{metadata.error && <p role="alert">{metadata.error.message}</p>}{Object.entries(metadata.data ?? {}).map(([kind, fields]) => <Card key={kind}><h3>{kind}</h3><ul>{fields.map(field => <li key={field.path}><code>{field.path}</code> — {field.description}</li>)}</ul></Card>)}</Disclosure>
</Card><Card><h2>Triggers</h2><p className="mb-5 text-sm text-slate-600 dark:text-slate-400">Choose the events that start this job.</p><TriggerEditor triggers={draft.triggers} onChange={value => update("triggers", value)} />
{initial?.triggers.map(trigger => trigger.kind === "webhook" && trigger.config.provider === "cloudflareTail" && trigger.config.destination ? <div key={trigger.id} className="mt-4 text-sm"><p>{trigger.slug} · Tail webhook destination</p><code className="break-all">{trigger.config.destination}</code></div> : null)}
</Card>{save.error && <p role="alert">{save.error.message}</p>}
<Button variant="primary" disabled={save.isPending || !!remote || reconciling || !!conflicts.length || targets.isPending || !!targets.error}>{save.isPending ? "Saving…" : "Save job"}</Button>
</form>
</form>{saved && <p role="status">Job settings saved.</p>}{initial && <DeleteJob jobId={initial.id} name={initial.name} disabled={save.isPending} onDeleted={() => { savingNavigation.current = true; }} />}
</Page>;
}
Loading
Loading