From a382dfe60bfa8d6f4d638884502e752a0a271223 Mon Sep 17 00:00:00 2001 From: Brendan Date: Fri, 18 Sep 2026 18:53:01 +0000 Subject: [PATCH] Enforce versioned API boundaries --- AGENTS.md | 8 ++ packages/app/package.json | 3 +- packages/app/scripts/check-api-boundaries.mjs | 15 ++ packages/app/src/access-tokens.ts | 3 +- packages/app/src/api-contract.ts | 26 ++++ packages/app/src/flow-service.ts | 37 +++++ packages/app/src/index.ts | 129 +----------------- packages/app/src/protected-api.ts | 33 +++++ packages/app/src/types.ts | 1 + packages/app/src/ui.ts | 38 +++--- packages/app/src/worker.ts | 4 +- packages/app/test/api-contract.test.ts | 16 +++ packages/app/test/api-keys.browser.test.ts | 16 +-- packages/app/test/ui.test.ts | 8 +- packages/docs/api/reference.mdx | 22 ++- packages/docs/openapi.yaml | 28 +++- 16 files changed, 222 insertions(+), 165 deletions(-) create mode 100644 packages/app/scripts/check-api-boundaries.mjs create mode 100644 packages/app/src/api-contract.ts create mode 100644 packages/app/test/api-contract.test.ts diff --git a/AGENTS.md b/AGENTS.md index d5c64b6e..cecfd0e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,11 @@ ## Linear This project in Linear is "Factorize" + +## API architecture + +- Every JSON application endpoint must live under `/api/v1` and be documented in `packages/docs/openapi.yaml`. +- Frontend code must call the same `/api/v1` endpoints as external clients. Never add a frontend-only `/api/*` route. +- Register API operations only in `packages/app/src/protected-api.ts`; page, auth callback, webhook, health, and internal routes belong in their existing non-API namespaces. +- A new API operation must include authorization, validation, OpenAPI documentation, and contract or boundary tests in the same change. +- `/auth`, `/oauth`, `/webhooks`, `/internal`, `/mcp`, and `/healthz` are explicit non-API namespaces and must not be used to hide frontend application endpoints. diff --git a/packages/app/package.json b/packages/app/package.json index b1b91b54..bd6a2dd4 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -6,7 +6,8 @@ "scripts": { "dev": "npm run build:css && wrangler dev", "build:css": "tailwindcss -i ./src/tailwind.css -o ./public/styles.css --minify", - "check": "tsc --noEmit && vitest run && wrangler deploy --dry-run", + "check": "npm run check:api-boundaries && tsc --noEmit && vitest run && wrangler deploy --dry-run", + "check:api-boundaries": "node scripts/check-api-boundaries.mjs", "test": "vitest run", "deploy": "wrangler deploy", "db:migrate": "node scripts/migrate.mjs", diff --git a/packages/app/scripts/check-api-boundaries.mjs b/packages/app/scripts/check-api-boundaries.mjs new file mode 100644 index 00000000..1c41b6f5 --- /dev/null +++ b/packages/app/scripts/check-api-boundaries.mjs @@ -0,0 +1,15 @@ +import { readFileSync } from "node:fs"; +import { globSync } from "node:fs"; + +const files = globSync("{src,test}/**/*.{ts,tsx,js,mjs}", { cwd: new URL("..", import.meta.url) }); +const failures = []; +for (const file of files) { + const source = readFileSync(new URL(`../${file}`, import.meta.url), "utf8"); + for (const match of source.matchAll(/["'`]\/api\/(?!v1(?:\/|["'`]))[^"'`]*/g)) failures.push(`${file}: unversioned API reference ${match[0]}`); + if (file !== "src/protected-api.ts" && /app\.(?:get|post|put|patch|delete|all)\(["'`]\/api\//.test(source)) failures.push(`${file}: API routes may only be registered in src/protected-api.ts`); +} +const contract = readFileSync(new URL("../src/api-contract.ts", import.meta.url), "utf8"); +const openapi = readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"); +for (const [, path] of contract.matchAll(/\["(?:GET|POST|PUT|PATCH|DELETE)", "([^"]+)"\]/g)) if (!openapi.includes(` ${path}:`)) failures.push(`OpenAPI is missing ${path}`); +if (failures.length) { console.error(failures.join("\n")); process.exit(1); } +console.log(`API boundaries verified across ${files.length} source and test files.`); diff --git a/packages/app/src/access-tokens.ts b/packages/app/src/access-tokens.ts index e5327c15..94f5117c 100644 --- a/packages/app/src/access-tokens.ts +++ b/packages/app/src/access-tokens.ts @@ -32,5 +32,6 @@ export async function authenticateAccessToken(request: Request, env: Env): Promi if (!authorization?.startsWith("Bearer fzt_")) return null; const token = authorization.slice(7), tenantId = accessTokenTenant(token); if (!tenantId) return null; - return new AccessTokenRepository(databaseFor(env), tenantId).authenticate(await accessTokenDigest(token)); + const auth = await new AccessTokenRepository(databaseFor(env), tenantId).authenticate(await accessTokenDigest(token)); + return auth ? { ...auth, authMethod: "access_token" } : null; } diff --git a/packages/app/src/api-contract.ts b/packages/app/src/api-contract.ts new file mode 100644 index 00000000..6c99c0ba --- /dev/null +++ b/packages/app/src/api-contract.ts @@ -0,0 +1,26 @@ +export const API_OPERATIONS = [ + ["GET", "/api/v1/exe-connections"], ["GET", "/api/v1/github-installations"], + ["GET", "/api/v1/execution-targets"], ["GET", "/api/v1/job-trigger-availability"], + ["POST", "/api/v1/schedules/preview"], ["GET", "/api/v1/integrations"], + ["GET", "/api/v1/integrations/cloudflare-tail"], ["POST", "/api/v1/integrations/cloudflare-tail"], + ["PUT", "/api/v1/integrations/cloudflare-tail/{integrationId}"], ["DELETE", "/api/v1/integrations/cloudflare-tail/{integrationId}"], + ["POST", "/api/v1/integrations/cloudflare-tail/{integrationId}/test"], + ["PUT", "/api/v1/integrations/exe"], ["POST", "/api/v1/integrations/exe/test"], ["DELETE", "/api/v1/integrations/exe/{connectionId}"], + ["POST", "/api/v1/integrations/exe/{connectionId}/diagnostics"], + ["PUT", "/api/v1/integrations/amp"], ["POST", "/api/v1/integrations/amp/test"], ["DELETE", "/api/v1/integrations/amp/{connectionId}"], + ["GET", "/api/v1/providers/linear/projects"], ["GET", "/api/v1/providers/linear/options"], + ["GET", "/api/v1/providers/clickup/lists"], ["GET", "/api/v1/providers/clickup/options"], + ["GET", "/api/v1/providers/github/installations"], ["DELETE", "/api/v1/providers/github/installations/{installationId}"], + ["GET", "/api/v1/providers/github/installations/{installationId}/repositories"], + ["GET", "/api/v1/providers/github/installations/{installationId}/repositories/{repositoryId}/issue-options"], + ["GET", "/api/v1/access/authorized-clients"], ["DELETE", "/api/v1/access/authorized-clients/{clientId}"], + ["GET", "/api/v1/access-tokens"], ["POST", "/api/v1/access-tokens"], ["DELETE", "/api/v1/access-tokens/{tokenId}"], + ["GET", "/api/v1/jobs"], ["POST", "/api/v1/jobs"], ["GET", "/api/v1/jobs/{jobId}"], ["PUT", "/api/v1/jobs/{jobId}"], ["DELETE", "/api/v1/jobs/{jobId}"], + ["POST", "/api/v1/jobs/{jobId}/enable"], ["POST", "/api/v1/jobs/{jobId}/disable"], ["POST", "/api/v1/jobs/{jobId}/invocations"], ["GET", "/api/v1/jobs/{jobId}/events"], + ["POST", "/api/v1/job-handlers/test"], ["GET", "/api/v1/runs"], ["GET", "/api/v1/runs/{runId}"], ["GET", "/api/v1/runs/{runId}/trace"], + ["GET", "/api/v1/runs/{runId}/diagnostics"], ["POST", "/api/v1/runs/{runId}/stop"], ["POST", "/api/v1/runs/{runId}/kill"], ["GET", "/api/v1/search"], + ["GET", "/api/v1/webhooks/deliveries"], ["GET", "/api/v1/webhooks/deliveries/{deliveryId}"], +] as const; + +const matchers = API_OPERATIONS.map(([method, template]) => [method, new RegExp(`^${template.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{[^/]+\\\}/g, "[^/]+")}$`)] as const); +export function isDeclaredApiOperation(method: string, path: string): boolean { return matchers.some(([candidate, pattern]) => candidate === method && pattern.test(path)); } diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 3cbcd365..217dd401 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -16,6 +16,8 @@ import { OperationsRepository } from "./postgres/operations-repository"; import { installedTriggerAvailability } from "./trigger-availability"; import { invokeCustomHandler } from "./custom-handler"; import { validateWebhookHandler } from "./webhook-trigger"; +import { ProviderCatalog } from "./postgres/provider-catalog"; +import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; export class ServiceError extends Error { constructor(public status: number, public code: string, message: string) { super(message); } @@ -65,6 +67,7 @@ export class ApiService { const tokenActive = !this.auth.accessTokenId || await new AccessTokenRepository(database, this.auth.tenantId).active(this.auth.accessTokenId); if (member?.role !== "owner" || member.sessionVersion !== this.auth.sessionVersion || !tokenActive) throw new ServiceError(401, "invalid_token", "The request is not authorized."); } + private async authorizeOwnerSession(scope: Scope): Promise { await this.authorize(scope); if (this.auth.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); } private publicJob(value: any) { for (const trigger of value?.triggers ?? []) { @@ -128,4 +131,38 @@ export class ApiService { throw new ServiceError(400, "invalid_request", error instanceof Error ? error.message : "Invalid schedule"); } } + + private integrations() { return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } + private providers() { return new ProviderCatalog(databaseFor(this.env), this.env, this.auth.tenantId); } + + async integrationStatus() { await this.authorize("flows:read"); return this.integrations().status(); } + async saveExeIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().saveExe(input); } + async testExeIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().testExe(input); } + async removeIntegration(kind: "exe" | "amp", id: string) { await this.authorize("flows:write"); const result = await this.integrations().remove(kind, id); if (result.conflict) throw new ServiceError(409, "conflict", "This integration is used by a job."); if (!result.deleted) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } + async saveAmpIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().saveAmp(input); } + async testAmpIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().testAmp(input); } + async saveTailIntegration(input: any) { await this.authorize("flows:write"); return this.integrations().saveTail(input); } + async testTailIntegration(id: string) { await this.authorize("flows:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; } + async removeTailIntegration(id: string) { await this.authorize("flows:write"); if (!await this.connections().delete(`cloudflare-tail:${id}`)) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } + async linearProjects() { await this.authorize("flows:read"); return this.providers().linearProjects(); } + async linearOptions() { await this.authorize("flows:read"); return this.providers().linearOptions(); } + async clickUpLists() { await this.authorize("flows:read"); return this.providers().clickUpLists(); } + async clickUpOptions(listId: string) { await this.authorize("flows:read"); return this.providers().clickUpOptions(listId); } + async githubRepositories(installationId: number) { await this.authorize("flows:read"); return this.providers().githubRepositories(installationId); } + async githubIssueOptions(installationId: number, repositoryId: number) { await this.authorize("flows:read"); return this.providers().githubIssueOptions(installationId, repositoryId); } + async removeGitHubInstallation(id: number) { await this.authorize("flows:write"); if (!await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).delete(id)) throw new ServiceError(404, "not_found", "Installation not found"); return { id, deleted: true }; } + + async listAuthorizedClients() { + await this.authorizeOwnerSession("flows:read"); + if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); + const grants: any[] = []; let cursor: string | undefined; + do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => !grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000))); cursor = page.cursor; } while (cursor); + const clients = await Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await this.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const)); + const byId = new Map(clients); + return grants.map(grant => ({ grantId: grant.id, clientId: grant.clientId, clientName: byId.get(grant.clientId)?.clientName ?? grant.clientId, scopes: grant.scope, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null })); + } + async revokeAuthorizedClient(clientId: string) { await this.authorizeOwnerSession("flows:write"); if (!this.env.OAUTH_PROVIDER) throw new ServiceError(503, "operation_failed", "OAuth management unavailable"); const grants: any[] = []; let cursor: string | undefined; do { const page = await this.env.OAUTH_PROVIDER.listUserGrants(this.auth.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => grant.clientId === clientId)); cursor = page.cursor; } while (cursor); await Promise.all(grants.map(grant => this.env.OAUTH_PROVIDER!.revokeGrant(grant.id, this.auth.userId))); return { revoked: grants.length }; } + async listAccessTokens() { await this.authorizeOwnerSession("flows:read"); return new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).list(); } + async createAccessToken(input: any) { await this.authorizeOwnerSession("flows:write"); const name = typeof input?.name === "string" ? input.name.trim() : "", requested: string[] = Array.isArray(input?.scopes) ? [...new Set(input.scopes.filter((scope: unknown): scope is string => typeof scope === "string"))] : [], expiryDays = Number(input?.expiryDays); if (!name || name.length > 100 || !requested.length || requested.some(scope => !ACCESS_SCOPES.includes(scope as any)) || ![7, 30, 90].includes(expiryDays)) throw new ServiceError(400, "invalid_request", "A name, supported scopes, and expiryDays of 7, 30, or 90 are required."); const token = issueAccessToken(this.auth.tenantId), expiresAt = new Date(Date.now() + expiryDays * 86_400_000).toISOString(); const metadata = await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).create({ name, scopes: requested, expiresAt, digest: await accessTokenDigest(token), userId: this.auth.userId, sessionVersion: this.auth.sessionVersion }); if (!metadata) throw new ServiceError(401, "invalid_token", "The owner session is no longer active."); return { ...metadata, token }; } + async revokeAccessToken(id: string) { await this.authorizeOwnerSession("flows:write"); if (!await new AccessTokenRepository(databaseFor(this.env), this.auth.tenantId).revoke(id)) throw new ServiceError(404, "not_found", "Access token not found"); return { revoked: true }; } } diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index cc039ed1..3a146ae4 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -5,15 +5,11 @@ import { equalHmac, hmac } from "./crypto"; import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github"; import { apiKeysSettingsPage, authPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, loginPage, settingsPage } from "./ui"; import type { Env } from "./types"; -import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens"; import { databaseFor } from "./postgres/database"; import { AuthRepository } from "./postgres/auth-repository"; import { IdentityRepository } from "./postgres/identity-repository"; -import { AccessTokenRepository } from "./postgres/access-token-repository"; -import { IntegrationService } from "./postgres/integration-service"; import { ConnectionRepository } from "./postgres/connection-repository"; import { GitHubRepository } from "./postgres/github-repository"; -import { ProviderCatalog } from "./postgres/provider-catalog"; import { WebhookService } from "./postgres/webhook-service"; const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>(); @@ -32,7 +28,7 @@ app.use("*", async (c, next) => { app.onError((error, c) => { console.error(JSON.stringify({ event: "factorize_unexpected_failure", path: c.req.path, message: error.message, factorizeTailSuppressed: c.req.path.startsWith("/webhooks/cloudflare/") })); - if (c.req.path.startsWith("/api/")) return c.json({ error: "Factorize could not complete this request. Try again shortly." }, 502); + if (c.req.path.startsWith("/api/v1/")) return c.json({ error: { code: "internal_error", message: "Factorize could not complete this request. Try again shortly." } }, 502); return c.text("Internal Server Error", 500); }); @@ -72,49 +68,8 @@ async function owner(c: any): Promise { return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? session : null; } -app.get("/api/health", (c) => c.json({ ok: true })); app.get("/styles.css", (c) => c.env.ASSETS.fetch(c.req.raw)); - -app.get("/api/access/authorized-clients", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - if (!c.env.OAUTH_PROVIDER) return c.json({ error: "OAuth management unavailable" }, 503); - const grants: any[] = []; let cursor: string | undefined; - do { const page = await c.env.OAUTH_PROVIDER.listUserGrants(session.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => !grant.expiresAt || grant.expiresAt > Math.floor(Date.now() / 1000))); cursor = page.cursor; } while (cursor); - const clients = await Promise.all([...new Set(grants.map(grant => grant.clientId))].map(async clientId => [clientId, await c.env.OAUTH_PROVIDER!.lookupClient(clientId)] as const)); - const byId = new Map(clients); - return c.json(grants.map(grant => ({ grantId: grant.id, clientId: grant.clientId, clientName: byId.get(grant.clientId)?.clientName ?? grant.clientId, scopes: grant.scope, authorizationDate: new Date(grant.createdAt * 1000).toISOString(), expiresAt: grant.expiresAt ? new Date(grant.expiresAt * 1000).toISOString() : null, lastUsedAt: null }))); -}); - -app.delete("/api/access/authorized-clients/:clientId", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - if (!c.env.OAUTH_PROVIDER) return c.json({ error: "OAuth management unavailable" }, 503); - const clientId = c.req.param("clientId"), grants: any[] = []; let cursor: string | undefined; - do { const page = await c.env.OAUTH_PROVIDER.listUserGrants(session.userId, { limit: 100, cursor }); grants.push(...page.items.filter(grant => grant.clientId === clientId)); cursor = page.cursor; } while (cursor); - await Promise.all(grants.map(grant => c.env.OAUTH_PROVIDER!.revokeGrant(grant.id, session.userId))); - return c.json({ revoked: grants.length }); -}); - -app.get("/api/access-tokens", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new AccessTokenRepository(databaseFor(c.env), session.tenantId).list()); -}); - -app.post("/api/access-tokens", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const input = await c.req.json().catch(() => null) as any, name = typeof input?.name === "string" ? input.name.trim() : ""; - const requested: string[] = Array.isArray(input?.scopes) ? [...new Set(input.scopes.filter((scope: unknown): scope is string => typeof scope === "string"))] : [], expiryDays = Number(input?.expiryDays); - if (!name || name.length > 100 || !requested.length || requested.some(scope => !ACCESS_SCOPES.includes(scope as any)) || ![7, 30, 90].includes(expiryDays)) return c.json({ error: "A name, supported scopes, and expiryDays of 7, 30, or 90 are required." }, 400); - const token = issueAccessToken(session.tenantId), expiresAt = new Date(Date.now() + expiryDays * 86_400_000).toISOString(); - const metadata = await new AccessTokenRepository(databaseFor(c.env), session.tenantId).create({ name, scopes: requested, expiresAt, digest: await accessTokenDigest(token), userId: session.userId, sessionVersion: session.sessionVersion }); - if (!metadata) return c.json({ error: "The owner session is no longer active." }, 401); - return c.json({ ...metadata, token }, 201); -}); - -app.delete("/api/access-tokens/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const revoked = await new AccessTokenRepository(databaseFor(c.env), session.tenantId).revoke(c.req.param("id")); - return revoked ? c.json({ revoked: true }) : c.json({ error: "Access token not found" }, 404); -}); +app.get("/healthz", (c) => c.json({ ok: true })); app.get("/auth/linear", async (c) => { const state = crypto.randomUUID(); @@ -188,62 +143,6 @@ app.get("/auth/clickup/callback", async (c) => { return c.redirect("/settings/integrations"); }); -app.get("/api/connections/status", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).status()); -}); -app.get("/api/connections/cloudflare-tail", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).tails()); -}); -app.post("/api/connections/cloudflare-tail", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveTail(await c.req.json()), 201); -}); -app.put("/api/connections/cloudflare-tail/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveTail({ ...await c.req.json() as any, integrationId: c.req.param("id") })); -}); -app.post("/api/connections/cloudflare-tail/:id/test", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const result = await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).testTail(c.req.param("id")); return result ? c.json(result) : c.json({ error: "Not found" }, 404); -}); -app.delete("/api/connections/cloudflare-tail/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const deleted = await new ConnectionRepository(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).delete(`cloudflare-tail:${c.req.param("id")}`); return deleted ? c.body(null, 204) : c.json({ error: "Not found" }, 404); -}); -app.get("/api/linear/projects", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).linearProjects()); -}); -app.get("/api/linear/options", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).linearOptions()); -}); -app.get("/api/clickup/lists", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).clickUpLists()); -}); -app.get("/api/clickup/options", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).clickUpOptions(c.req.query("listId") ?? "")); -}); -app.get("/api/github/installations", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new GitHubRepository(databaseFor(c.env), session.tenantId).installations()); -}); -app.get("/api/github/installations/:id/repositories", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).githubRepositories(Number(c.req.param("id")))); -}); -app.get("/api/github/installations/:installationId/repositories/:repositoryId/issue-options", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new ProviderCatalog(databaseFor(c.env), c.env, session.tenantId).githubIssueOptions(Number(c.req.param("installationId")), Number(c.req.param("repositoryId")))); -}); -app.delete("/api/github/installations/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return await new GitHubRepository(databaseFor(c.env), session.tenantId).delete(Number(c.req.param("id"))) ? c.json({ ok: true }) : c.json({ error: "Not found" }, 404); -}); app.get("/auth/github/install", async (c) => { const session = await owner(c); if (!session) return c.redirect("/auth/linear"); if (!c.env.GITHUB_APP_SLUG) return c.text("GitHub App is not configured", 503); @@ -267,30 +166,6 @@ app.get("/auth/github/setup", async (c) => { catch (error) { if (error instanceof Error && error.message === "installation_conflict") return c.text("This GitHub installation is already connected to another tenant", 409); throw error; } return c.redirect("/settings"); }); -app.put("/api/connections/exe", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveExe(await c.req.json())); -}); -app.post("/api/connections/exe/test", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).testExe(await c.req.json())); -}); -app.delete("/api/connections/exe/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const result = await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).remove("exe", c.req.param("id")); return result.conflict ? c.json({ error: "This integration is used by a job." }, 409) : result.deleted ? c.body(null, 204) : c.json({ error: "Not found" }, 404); -}); -app.put("/api/connections/amp", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).saveAmp(await c.req.json())); -}); -app.post("/api/connections/amp/test", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - return c.json(await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).testAmp(await c.req.json())); -}); -app.delete("/api/connections/amp/:id", async (c) => { - const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - const result = await new IntegrationService(databaseFor(c.env), session.tenantId, c.env.CREDENTIAL_ENCRYPTION_KEY).remove("amp", c.req.param("id")); return result.conflict ? c.json({ error: "This integration is used by a job." }, 409) : result.deleted ? c.body(null, 204) : c.json({ error: "Not found" }, 404); -}); app.post("/webhooks/cloudflare/:tenantId/:jobId", async (c) => { const raw = await c.req.text(); if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 01d16409..24dbb9c6 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import { ApiService, ServiceError } from "./flow-service"; import { jobHandlerTestSchema, jobIdSchema, jobInputSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; import type { Env, OAuthProps } from "./types"; +import { isDeclaredApiOperation } from "./api-contract"; function errorResponse(error: unknown): Response { if (error instanceof z.ZodError) return Response.json({ error: { code: "invalid_request", message: "Request validation failed", details: error.issues } }, { status: 400 }); @@ -38,12 +39,44 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP const url = new URL(request.url), path = url.pathname, service = new ApiService(env, auth); if (path === "/mcp") return mcp(request, service, env, ctx); if (!path.startsWith("/api/v1")) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); + if (!isDeclaredApiOperation(request.method, path)) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); if (request.method === "GET" && path === "/api/v1/exe-connections") return Response.json(await service.listExeConnections()); if (request.method === "GET" && path === "/api/v1/github-installations") return Response.json(await service.listGitHubInstallations()); if (request.method === "GET" && path === "/api/v1/execution-targets") return Response.json(await service.listExecutionTargets()); if (request.method === "GET" && path === "/api/v1/job-trigger-availability") return Response.json(await service.listJobTriggerAvailability()); if (request.method === "POST" && path === "/api/v1/schedules/preview") return Response.json(await service.previewSchedule(await request.json())); if (request.method === "GET" && path === "/api/v1/integrations/cloudflare-tail") return Response.json(await service.listTailIntegrations()); + if (request.method === "GET" && path === "/api/v1/integrations") return Response.json(await service.integrationStatus()); + if (request.method === "PUT" && path === "/api/v1/integrations/exe") return Response.json(await service.saveExeIntegration(await request.json())); + if (request.method === "POST" && path === "/api/v1/integrations/exe/test") return Response.json(await service.testExeIntegration(await request.json())); + if (request.method === "PUT" && path === "/api/v1/integrations/amp") return Response.json(await service.saveAmpIntegration(await request.json())); + if (request.method === "POST" && path === "/api/v1/integrations/amp/test") return Response.json(await service.testAmpIntegration(await request.json())); + if (request.method === "POST" && path === "/api/v1/integrations/cloudflare-tail") return Response.json(await service.saveTailIntegration(await request.json()), { status: 201 }); + if (request.method === "GET" && path === "/api/v1/providers/linear/projects") return Response.json(await service.linearProjects()); + if (request.method === "GET" && path === "/api/v1/providers/linear/options") return Response.json(await service.linearOptions()); + if (request.method === "GET" && path === "/api/v1/providers/clickup/lists") return Response.json(await service.clickUpLists()); + if (request.method === "GET" && path === "/api/v1/providers/clickup/options") return Response.json(await service.clickUpOptions(url.searchParams.get("listId") ?? "")); + if (request.method === "GET" && path === "/api/v1/providers/github/installations") return Response.json(await service.listGitHubInstallations()); + if (request.method === "GET" && path === "/api/v1/access/authorized-clients") return Response.json(await service.listAuthorizedClients()); + if (request.method === "GET" && path === "/api/v1/access-tokens") return Response.json(await service.listAccessTokens()); + if (request.method === "POST" && path === "/api/v1/access-tokens") return Response.json(await service.createAccessToken(await request.json()), { status: 201 }); + const accessTokenMatch = path.match(/^\/api\/v1\/access-tokens\/([^/]+)$/); + if (accessTokenMatch && request.method === "DELETE") return Response.json(await service.revokeAccessToken(decodeURIComponent(accessTokenMatch[1]))); + const authorizedClientMatch = path.match(/^\/api\/v1\/access\/authorized-clients\/([^/]+)$/); + if (authorizedClientMatch && request.method === "DELETE") return Response.json(await service.revokeAuthorizedClient(decodeURIComponent(authorizedClientMatch[1]))); + const integrationMatch = path.match(/^\/api\/v1\/integrations\/(exe|amp)\/([^/]+)$/); + if (integrationMatch && request.method === "DELETE") return Response.json(await service.removeIntegration(integrationMatch[1] as "exe" | "amp", decodeURIComponent(integrationMatch[2]))); + const tailMatch = path.match(/^\/api\/v1\/integrations\/cloudflare-tail\/([^/]+)$/); + if (tailMatch && request.method === "PUT") return Response.json(await service.saveTailIntegration({ ...await request.json() as any, integrationId: decodeURIComponent(tailMatch[1]) })); + if (tailMatch && request.method === "DELETE") return Response.json(await service.removeTailIntegration(decodeURIComponent(tailMatch[1]))); + const tailTestMatch = path.match(/^\/api\/v1\/integrations\/cloudflare-tail\/([^/]+)\/test$/); + if (tailTestMatch && request.method === "POST") return Response.json(await service.testTailIntegration(decodeURIComponent(tailTestMatch[1]))); + const githubRepositoriesMatch = path.match(/^\/api\/v1\/providers\/github\/installations\/(\d+)\/repositories$/); + if (githubRepositoriesMatch && request.method === "GET") return Response.json(await service.githubRepositories(Number(githubRepositoriesMatch[1]))); + const githubOptionsMatch = path.match(/^\/api\/v1\/providers\/github\/installations\/(\d+)\/repositories\/(\d+)\/issue-options$/); + if (githubOptionsMatch && request.method === "GET") return Response.json(await service.githubIssueOptions(Number(githubOptionsMatch[1]), Number(githubOptionsMatch[2]))); + const githubInstallationMatch = path.match(/^\/api\/v1\/providers\/github\/installations\/(\d+)$/); + if (githubInstallationMatch && request.method === "DELETE") return Response.json(await service.removeGitHubInstallation(Number(githubInstallationMatch[1]))); const exeDiagnosticMatch = path.match(/^\/api\/v1\/integrations\/exe\/([^/]+)\/diagnostics$/); if (exeDiagnosticMatch && request.method === "POST") return Response.json(await service.diagnoseExeIntegration(decodeURIComponent(exeDiagnosticMatch[1]))); if (request.method === "GET" && path === "/api/v1/jobs") return Response.json(await service.listJobs()); diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index 0582ccca..d0e4d7ea 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -37,6 +37,7 @@ export type OAuthProps = { sessionVersion: number; scopes: string[]; accessTokenId?: string; + authMethod?: "session" | "oauth" | "access_token"; }; export interface WorkItem { diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index c9fa3008..735bb131 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -134,7 +134,7 @@ function insertHint(path){const start=promptEditor.selectionStart,end=promptEdit promptEditor.addEventListener('input',()=>{activeSuggestion=0;updateSuggestions()});promptEditor.addEventListener('click',updateSuggestions);promptEditor.addEventListener('keyup',e=>{if(!['ArrowDown','ArrowUp','Escape','Tab'].includes(e.key))updateSuggestions()});promptEditor.addEventListener('keydown',e=>{if(suggestionMenu.classList.contains('hidden'))return;if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();activeSuggestion=(activeSuggestion+(e.key==='ArrowDown'?1:-1)+matches.length)%matches.length;updateSuggestions()}else if(e.key==='Tab'||e.key==='Enter'){e.preventDefault();selectSuggestion()}else if(e.key==='Escape'){e.preventDefault();closeSuggestions()}});suggestionMenu.addEventListener('mousedown',e=>e.preventDefault());suggestionMenu.addEventListener('click',e=>{const option=e.target.closest('[data-suggestion]');if(option)selectSuggestion(Number(option.dataset.suggestion))});promptEditor.addEventListener('blur',()=>setTimeout(closeSuggestions,100)); $('#context-paths').addEventListener('click',e=>{const hint=e.target.closest('[data-context-hint]');if(hint)insertHint(hint.dataset.contextHint)}); function nextSlug(){let n=1;while(reservedSlugs.has('trigger-'+n))n++;const slug='trigger-'+n;reservedSlugs.add(slug);return slug} -async function repositories(installationId){const key=String(installationId);if(resources.repositories.has(key))return resources.repositories.get(key);const response=await fetch('/api/github/installations/'+encodeURIComponent(key)+'/repositories');const items=response.ok?await response.json():[];resources.repositories.set(key,items);return items} +async function repositories(installationId){const key=String(installationId);if(resources.repositories.has(key))return resources.repositories.get(key);const response=await fetch('/api/v1/providers/github/installations/'+encodeURIComponent(key)+'/repositories');const items=response.ok?await response.json():[];resources.repositories.set(key,items);return items} function options(select,items,label,value='id'){select.replaceChildren(...items.map(x=>new Option(x[label]||x.name,String(x[value]))))} function syncModels(selected=form.model.value,selectedEffort=form.effort.value){const target=resources.targets.find(x=>String(x.id)===form.executionTargetId.value),amp=target?.kind==='amp',models=target?.models||[],efforts=target?.efforts||[];form.model.replaceChildren(new Option('Harness default',''),...models.map(value=>new Option(value,value)));form.model.disabled=amp;form.model.value=amp?'':selected;if(selected&&!form.model.value){form.model.append(new Option(selected+' (unavailable)',selected));form.model.value=selected}form.effort.replaceChildren(new Option('Harness default',''),...efforts.map(value=>new Option(value,value)));form.effort.disabled=amp||!efforts.length;form.effort.value=form.effort.disabled?'':selectedEffort;$('#model-help').textContent=amp?'This target manages its model in Amp.':models.length?'Models loaded when this VM integration was added.':'No models were returned by this VM integration.';$('#effort-help').textContent=efforts.length?'Select the harness reasoning effort.':'This harness does not expose effort selection.'} // Select the connected environment and model that will run this job. syncModels(current?.model||'') @@ -146,11 +146,11 @@ function readLinearRules(){return linearRuleRows().map(row=>{const [type,target] function clickupRuleRows(){return [...$('#clickup-rules').querySelectorAll('[data-clickup-rule]')]} function addClickupRule(rule={type:'status',targetId:''}){const row=document.createElement('div');row.dataset.clickupRule='';row.className='grid gap-3 rounded-xl border border-stone-200 bg-stone-50 p-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto] sm:items-end dark:border-slate-700 dark:bg-slate-950';const typeLabel=document.createElement('label'),type=document.createElement('select'),valueLabel=document.createElement('label'),value=document.createElement('select'),remove=document.createElement('button');typeLabel.className=valueLabel.className='label';typeLabel.textContent='Match on';valueLabel.textContent='Value';type.className=value.className='field';type.innerHTML=Object.entries(ruleLabels).filter(([key])=>key!=='owner').map(([key,label])=>'').join('');type.value=rule.type;const fill=()=>{const items=type.value==='status'?resources.clickupOptions.statuses:type.value==='label'?resources.clickupOptions.labels:resources.clickupOptions.users;value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...items.map(item=>new Option(item.name,item.id)));value.value=type.value===rule.type?rule.targetId:''};type.onchange=fill;fill();typeLabel.append(type);valueLabel.append(value);remove.type='button';remove.className='rounded-lg border border-red-200 px-3 py-2 text-sm font-semibold text-red-700';remove.textContent='Remove';remove.onclick=()=>row.remove();row.append(typeLabel,valueLabel,remove);$('#clickup-rules').append(row)} function readClickupRules(){return clickupRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} -async function syncClickupOptions(rules=[{type:'status',targetId:''}]){const listId=triggerForm.elements.clickupListId.value;resources.clickupOptions=listId?await request('/api/clickup/options?listId='+encodeURIComponent(listId)):{statuses:[],users:[],labels:[]};$('#clickup-rules').replaceChildren();rules.forEach(addClickupRule)} +async function syncClickupOptions(rules=[{type:'status',targetId:''}]){const listId=triggerForm.elements.clickupListId.value;resources.clickupOptions=listId?await request('/api/v1/providers/clickup/options?listId='+encodeURIComponent(listId)):{statuses:[],users:[],labels:[]};$('#clickup-rules').replaceChildren();rules.forEach(addClickupRule)} function githubRuleRows(){return [...$('#github-rules').querySelectorAll('[data-github-rule]')]} function addGithubRule(rule={type:'status',targetId:''}){const row=document.createElement('div');row.dataset.githubRule='';row.className='grid gap-3 rounded-xl border border-stone-200 bg-stone-50 p-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)_auto] sm:items-end';const type=document.createElement('select'),value=document.createElement('select'),remove=document.createElement('button');type.className=value.className='field';type.innerHTML=['status','label','assignee','creator'].map(x=>'').join('');type.value=rule.type==='owner'?'assignee':rule.type;const fill=()=>{value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...githubRuleOptions(type.value).map(x=>new Option(x.name,x.id)));value.value=rule.targetId};type.onchange=fill;fill();remove.type='button';remove.textContent='Remove';remove.onclick=()=>row.remove();row.append(type,value,remove);$('#github-rules').append(row)} function readGithubRules(){return githubRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} -async function syncGithubIssueOptions(){const installationId=triggerForm.elements.installationId.value,repositoryId=triggerForm.elements.repositoryId.value;resources.githubOptions=installationId&&repositoryId?await request('/api/github/installations/'+encodeURIComponent(installationId)+'/repositories/'+encodeURIComponent(repositoryId)+'/issue-options'):{statuses:[],users:[],labels:[]};githubRuleRows().forEach(row=>{const [type,value]=row.querySelectorAll('select'),selected=value.value;value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...githubRuleOptions(type.value).map(x=>new Option(x.name,x.id)));value.value=selected})} +async function syncGithubIssueOptions(){const installationId=triggerForm.elements.installationId.value,repositoryId=triggerForm.elements.repositoryId.value;resources.githubOptions=installationId&&repositoryId?await request('/api/v1/providers/github/installations/'+encodeURIComponent(installationId)+'/repositories/'+encodeURIComponent(repositoryId)+'/issue-options'):{statuses:[],users:[],labels:[]};githubRuleRows().forEach(row=>{const [type,value]=row.querySelectorAll('select'),selected=value.value;value.replaceChildren(new Option('Choose '+ruleLabels[type.value].toLowerCase(),''),...githubRuleOptions(type.value).map(x=>new Option(x.name,x.id)));value.value=selected})} async function openEditor(kind,index=-1){const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind;if(!kinds[k])throw new Error('This trigger type is no longer supported.');editing=index;const c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='clickup'?'clickup':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='clickup'){options(triggerForm.elements.clickupListId,resources.clickupLists,'name');triggerForm.elements.clickupListId.value=c.listId||resources.clickupLists[0]?.id||'';await syncClickupOptions(c.matchRules)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);$('#github-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addGithubRule);await syncGithubIssueOptions()}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','clickup','github','cloudflareTail'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} async function previewSchedule(){const body={cron:triggerForm.elements.cron.value,timezone:triggerForm.elements.timezone.value};try{const x=await request('/api/v1/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});$('#schedule-preview').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()}catch(e){$('#schedule-preview').textContent=e.message}} function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='clickup')return {kind:'webhook',config:{provider:'clickup',listId:triggerForm.elements.clickupListId.value,matchRules:readClickupRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),matchRules:readGithubRules(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,integrationId:triggerForm.elements.tailIntegrationId.value}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} @@ -160,7 +160,7 @@ $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;tr triggerForm.querySelectorAll('[name=scheduleMode]').forEach(input=>input.onchange=syncScheduleEditor);triggerForm.elements.intervalUnit.onchange=syncScheduleEditor;triggerForm.elements.intervalValue.oninput=syncScheduleEditor; triggerForm.onsubmit=e=>{e.preventDefault();try{const value=configFromForm();validate(value);if(editing>=0)triggers[editing]={...triggers[editing],...value};else triggers.push({...value,id:undefined,slug:nextSlug(),enabled:true,_clientId:++clientId});dialog.close();render()}catch(error){$('#dialog-error').textContent=error.message;$('#dialog-error').classList.remove('hidden')}}; $('#test-handler').onclick=async()=>{const output=$('#handler-result');try{const handlerCode=triggerForm.elements.handlerCode.value;if(!handlerCode)throw new Error('Enter handler code first.');const payload=JSON.parse(triggerForm.elements.testPayload.value);const result=await request('/api/v1/job-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({handlerCode,payload})});output.textContent=result.ok?'Accepted: '+JSON.stringify(result.decision):'Rejected: '+result.category}catch(e){output.textContent=e.message}}; -async function loadProviderResources(){const pending=[];if(availability.linear)pending.push(Promise.all([request('/api/linear/projects'),request('/api/linear/options')]).then(([projects,linearOptions])=>{resources.projects=projects;resources.options=linearOptions}).catch(()=>{}));if(availability.clickup)pending.push(request('/api/clickup/lists').then(lists=>{resources.clickupLists=lists}).catch(()=>{}));if(availability.github)pending.push(fetch('/api/github/installations').then(response=>response.ok?response.json():[]).then(installations=>{resources.installations=installations.filter(x=>x.state==='active')}).catch(()=>{}));if(availability.cloudflareTail)pending.push(request('/api/connections/cloudflare-tail').then(tails=>{resources.tailInstallations=tails;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId')}).catch(()=>{}));await Promise.all(pending)} +async function loadProviderResources(){const pending=[];if(availability.linear)pending.push(Promise.all([request('/api/v1/providers/linear/projects'),request('/api/v1/providers/linear/options')]).then(([projects,linearOptions])=>{resources.projects=projects;resources.options=linearOptions}).catch(()=>{}));if(availability.clickup)pending.push(request('/api/v1/providers/clickup/lists').then(lists=>{resources.clickupLists=lists}).catch(()=>{}));if(availability.github)pending.push(fetch('/api/v1/providers/github/installations').then(response=>response.ok?response.json():[]).then(installations=>{resources.installations=installations.filter(x=>x.state==='active')}).catch(()=>{}));if(availability.cloudflareTail)pending.push(request('/api/v1/integrations/cloudflare-tail').then(tails=>{resources.tailInstallations=tails;options(triggerForm.elements.tailIntegrationId,tails,'name','integrationId')}).catch(()=>{}));await Promise.all(pending)} async function init(){const [targets,jobs,current]=await Promise.all([request('/api/v1/execution-targets'),request('/api/v1/jobs'),jobId?request('/api/v1/jobs/'+encodeURIComponent(jobId)):null]);resources.targets=targets;resources.jobs=jobs;options(form.executionTargetId,targets,'name');if(current){form.name.value=current.name;form.slug.value=current.slug;form.promptTemplate.value=current.promptTemplate;form.concurrencyLimit.value=current.concurrencyLimit;form.executionTargetId.value=current.executionTargetId;triggers=current.triggers.map(t=>({...t,config:{...t.config}}))}else triggers=[{kind:'manual',slug:'trigger-1',enabled:true,config:{}}];syncModels(current?.model||'',current?.effort||'');highlightPrompt();reservedSlugs=new Set(triggers.map(t=>t.slug));render();await refreshAvailability();loadProviderResources()} form.executionTargetId.addEventListener('change',()=>syncModels('','')); window.addEventListener('focus',()=>refreshAvailability().catch(()=>{}));window.addEventListener('pageshow',()=>refreshAvailability().catch(()=>{})); @@ -220,20 +220,20 @@ const badge=(id,label,tone)=>{const el=$(id);el.textContent=label;el.className=' const integrationIcons=${JSON.stringify(integrationIcons)}; const testButton=(kind,id)=>''; const installedRow=(name,description,status,tone,actions)=>'
'+integrationIcons[name==='Cloudflare Tail'?'tail':name==='Exe.dev'?'exe':name.toLowerCase()]+'

'+esc(name)+'

Actions
'+actions+'

'+description+'

'+esc(status)+'
'; -async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await request('/api/github/installations/'+encodeURIComponent(id),{method:'DELETE'});await load()} -async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/connections/status'),fetch('/api/github/installations'),request('/api/connections/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.agentKind)+(c.models?.length?' · '+c.models.length+' models':'')+(c.tags?.length?' · tags: '+esc(c.tags.join(', ')):' · no VM tags'),'Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} +async function disconnectGitHub(id){if(!confirm('Disconnect this GitHub installation from Factorize?'))return;await request('/api/v1/providers/github/installations/'+encodeURIComponent(id),{method:'DELETE'});await load()} +async function load(){const loading=$('#installed-loading'),list=$('#installed-integrations'),table=$('#installed-table'),empty=$('#installed-empty');loading.classList.remove('hidden');table.classList.add('hidden');empty.classList.add('hidden');$('#integration-error').classList.add('hidden');try{const [s,gh,tails]=await Promise.all([request('/api/v1/integrations'),fetch('/api/v1/providers/github/installations'),request('/api/v1/integrations/cloudflare-tail')]),rows=[];const exe=s.exeConnections||[],amps=s.ampConnections||[];badge('#linear-available-status',(s.linear?1:0)+' installed','neutral');badge('#clickup-available-status',(s.clickup?1:0)+' installed','neutral');badge('#exe-available-status',exe.length+' installed','neutral');badge('#amp-available-status',amps.length+' installed','neutral');badge('#tail-available-status',tails.length+' installed','neutral');$('#linear-action').textContent=s.linear?'Reconnect Linear':'Continue to Linear';if(s.linear)rows.push(installedRow('Linear',esc(s.linear.organizationName||'Linear workspace')+(s.linear.viewerEmail?' · '+esc(s.linear.viewerEmail):''),'Connected','ok',''));if(s.clickup)rows.push(installedRow('ClickUp',esc(s.clickup.teamName||'ClickUp workspace'),'Connected','ok',''));exe.forEach(c=>rows.push(installedRow('Exe.dev',esc(c.agentKind)+(c.models?.length?' · '+c.models.length+' models':'')+(c.tags?.length?' · tags: '+esc(c.tags.join(', ')):' · no VM tags'),'Connected','ok',testButton('exe',c.connectionId)+'')));amps.forEach(c=>rows.push(installedRow('Amp',esc(c.project),'Connected','ok',testButton('amp',c.connectionId)+'')));tails.forEach(c=>rows.push(installedRow('Cloudflare Tail',esc(c.name)+(c.referencedJobCount?' · '+c.referencedJobCount+' jobs':''),'Connected','ok','')));if(gh.status===404){badge('#github-available-status','Unavailable','neutral');$('#github-install').classList.add('hidden')}else if(!gh.ok){badge('#github-available-status','Action required','warn');rows.push(installedRow('GitHub','Installation status could not be loaded.','Action required','warn',''))}else{const installs=await gh.json(),active=installs.filter(x=>x.state==='active');badge('#github-available-status',active.length+' installed',installs.length&&!active.length?'warn':'neutral');$('#github-install').textContent=active.length?'Add another installation':'Continue to GitHub';installs.forEach(x=>rows.push(installedRow('GitHub',esc(x.accountLogin||'Installation '+x.installationId)+' · '+esc(x.accountType||'GitHub'),x.state==='active'?'Connected':x.state,'active'===x.state?'ok':'warn','Configure ↗')))}list.innerHTML=rows.join('');loading.classList.add('hidden');table.classList.toggle('hidden',!rows.length);empty.classList.toggle('hidden',rows.length>0);bindActions()}catch(e){loading.classList.add('hidden');empty.classList.remove('hidden');const error=$('#integration-error');error.textContent=e.message||'Could not load integration status. Try again.';error.classList.remove('hidden');['linear','clickup','github','exe','amp','tail'].forEach(id=>badge('#'+id+'-available-status','Unavailable','neutral'))}} function openSetup(kind){const dialog=$('#'+kind+'-setup');if(!dialog.open)dialog.showModal()} function closeSetup(kind){const dialog=$('#'+kind+'-setup');if(dialog.open)dialog.close()} -async function tailAction(id,method){await request('/api/connections/cloudflare-tail/'+encodeURIComponent(id),{method});await load()} -function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>{if(button.dataset.openSetup==='tail'){delete $('#tail-connection').dataset.id;$('#tail-connection').reset()}openSetup(button.dataset.openSetup)});document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>closeSetup(button.dataset.closeSetup));document.querySelectorAll('dialog').forEach(dialog=>dialog.onclick=e=>{if(e.target===dialog)dialog.close()});document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(showError));document.querySelectorAll('[data-disconnect-tail]').forEach(button=>button.onclick=()=>{if(confirm('Disconnect this Tail installation? Jobs using it will need another installation.'))tailAction(button.dataset.disconnectTail,'DELETE').catch(showError)});document.querySelectorAll('[data-test-tail]').forEach(button=>button.onclick=async()=>{button.disabled=true;try{await request('/api/connections/cloudflare-tail/'+encodeURIComponent(button.dataset.testTail)+'/test',{method:'POST'});button.textContent='Connected'}catch(e){button.textContent='Action required'}finally{button.disabled=false}});document.querySelectorAll('[data-configure-tail]').forEach(button=>button.onclick=()=>{const form=$('#tail-connection');form.dataset.id=button.dataset.configureTail;form.elements.name.value=button.dataset.name;openSetup('tail')})} +async function tailAction(id,method){await request('/api/v1/integrations/cloudflare-tail/'+encodeURIComponent(id),{method});await load()} +function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>{if(button.dataset.openSetup==='tail'){delete $('#tail-connection').dataset.id;$('#tail-connection').reset()}openSetup(button.dataset.openSetup)});document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>closeSetup(button.dataset.closeSetup));document.querySelectorAll('dialog').forEach(dialog=>dialog.onclick=e=>{if(e.target===dialog)dialog.close()});document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(showError));document.querySelectorAll('[data-disconnect-tail]').forEach(button=>button.onclick=()=>{if(confirm('Disconnect this Tail installation? Jobs using it will need another installation.'))tailAction(button.dataset.disconnectTail,'DELETE').catch(showError)});document.querySelectorAll('[data-test-tail]').forEach(button=>button.onclick=async()=>{button.disabled=true;try{await request('/api/v1/integrations/cloudflare-tail/'+encodeURIComponent(button.dataset.testTail)+'/test',{method:'POST'});button.textContent='Connected'}catch(e){button.textContent='Action required'}finally{button.disabled=false}});document.querySelectorAll('[data-configure-tail]').forEach(button=>button.onclick=()=>{const form=$('#tail-connection');form.dataset.id=button.dataset.configureTail;form.elements.name.value=button.dataset.name;openSetup('tail')})} function showError(e){const error=$('#integration-error');error.textContent=e.message||'The integration action failed.';error.classList.remove('hidden')} -function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} -document.addEventListener('click',async event=>{const button=event.target.closest('[data-remove-integration]');if(!button||!confirm('Remove this integration?'))return;button.disabled=true;try{await request('/api/connections/'+button.dataset.removeIntegration+'/'+encodeURIComponent(button.dataset.id),{method:'DELETE'});await load()}catch(error){button.disabled=false;showError(error)}}); +function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/v1/integrations/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} +document.addEventListener('click',async event=>{const button=event.target.closest('[data-remove-integration]');if(!button||!confirm('Remove this integration?'))return;button.disabled=true;try{await request('/api/v1/integrations/'+button.dataset.removeIntegration+'/'+encodeURIComponent(button.dataset.id),{method:'DELETE'});await load()}catch(error){button.disabled=false;showError(error)}}); const exePayload=()=>{const form=$('#connection');return {apiToken:form.elements.apiToken.value,agentKind:form.elements.agentKind.value,tags:[...form.elements.tags.selectedOptions].map(option=>option.value)}}; -let exeTokenTimer=0,exeTokenRequest=0,verifiedExeToken='';async function testExeToken(){const form=$('#connection'),m=$('#settings-message'),status=$('#exe-token-status'),valid=$('#exe-token-valid'),button=$('#test-exe-token'),token=form.elements.apiToken.value.trim(),requestId=++exeTokenRequest;if(!token)return;button.disabled=true;status.textContent='Testing token and loading tags…';try{const result=await request('/api/connections/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:token})});if(requestId!==exeTokenRequest||token!==form.elements.apiToken.value.trim())return;if(!result.ok){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=result.missingPermissions.length?'Missing required permissions: '+result.missingPermissions.join(', '):'The token could not be verified. Check that it is valid and try again.';return}verifiedExeToken=token;valid.classList.remove('hidden');valid.classList.add('flex');form.elements.tags.replaceChildren(...result.tags.map(tag=>new Option(tag,tag)));form.elements.tags.disabled=false;status.textContent=result.tags.length?'Token verified. Select the VM tags to attach.':'Token verified. No integration tags were found.';m.textContent=''}catch(error){if(requestId===exeTokenRequest){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=error.message}}finally{if(requestId===exeTokenRequest)button.disabled=false}}$('#test-exe-token').onclick=testExeToken;$('#connection').elements.apiToken.addEventListener('input',event=>{clearTimeout(exeTokenTimer);exeTokenRequest++;verifiedExeToken='';const form=$('#connection'),valid=$('#exe-token-valid'),status=$('#exe-token-status'),token=event.target.value.trim();valid.classList.add('hidden');valid.classList.remove('flex');form.elements.tags.disabled=true;status.textContent=token?'Waiting for you to finish typing…':'Token testing starts automatically after you finish typing.';if(token.length>=16)exeTokenTimer=setTimeout(testExeToken,500)}); -$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#settings-message');try{m.textContent='Creating a temporary VM to validate the agent and load models…';await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();verifiedExeToken='';$('#exe-token-valid').classList.add('hidden');$('#exe-token-valid').classList.remove('flex');$('#exe-token-status').textContent='Token testing starts automatically after you finish typing.';form.elements.tags.disabled=true;m.textContent='VM connection saved.';await load()}catch(x){m.textContent=x.message}}; -const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; -$('#tail-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/connections/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`); +let exeTokenTimer=0,exeTokenRequest=0,verifiedExeToken='';async function testExeToken(){const form=$('#connection'),m=$('#settings-message'),status=$('#exe-token-status'),valid=$('#exe-token-valid'),button=$('#test-exe-token'),token=form.elements.apiToken.value.trim(),requestId=++exeTokenRequest;if(!token)return;button.disabled=true;status.textContent='Testing token and loading tags…';try{const result=await request('/api/v1/integrations/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({apiToken:token})});if(requestId!==exeTokenRequest||token!==form.elements.apiToken.value.trim())return;if(!result.ok){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=result.missingPermissions.length?'Missing required permissions: '+result.missingPermissions.join(', '):'The token could not be verified. Check that it is valid and try again.';return}verifiedExeToken=token;valid.classList.remove('hidden');valid.classList.add('flex');form.elements.tags.replaceChildren(...result.tags.map(tag=>new Option(tag,tag)));form.elements.tags.disabled=false;status.textContent=result.tags.length?'Token verified. Select the VM tags to attach.':'Token verified. No integration tags were found.';m.textContent=''}catch(error){if(requestId===exeTokenRequest){verifiedExeToken='';valid.classList.add('hidden');valid.classList.remove('flex');status.textContent=error.message}}finally{if(requestId===exeTokenRequest)button.disabled=false}}$('#test-exe-token').onclick=testExeToken;$('#connection').elements.apiToken.addEventListener('input',event=>{clearTimeout(exeTokenTimer);exeTokenRequest++;verifiedExeToken='';const form=$('#connection'),valid=$('#exe-token-valid'),status=$('#exe-token-status'),token=event.target.value.trim();valid.classList.add('hidden');valid.classList.remove('flex');form.elements.tags.disabled=true;status.textContent=token?'Waiting for you to finish typing…':'Token testing starts automatically after you finish typing.';if(token.length>=16)exeTokenTimer=setTimeout(testExeToken,500)}); +$('#connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#settings-message');try{m.textContent='Creating a temporary VM to validate the agent and load models…';await request('/api/v1/integrations/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(exePayload())});form.reset();verifiedExeToken='';$('#exe-token-valid').classList.add('hidden');$('#exe-token-valid').classList.remove('flex');$('#exe-token-status').textContent='Token testing starts automatically after you finish typing.';form.elements.tags.disabled=true;m.textContent='VM connection saved.';await load()}catch(x){m.textContent=x.message}}; +const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/v1/integrations/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,m=$('#amp-message');try{await request('/api/v1/integrations/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});form.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; +$('#tail-connection').onsubmit=async e=>{e.preventDefault();const form=e.currentTarget,d=new FormData(form),m=$('#tail-message'),id=form.dataset.id,url='/api/v1/integrations/cloudflare-tail'+(id?'/'+encodeURIComponent(id):'');try{const x=await request(url,{method:id?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}form.reset();delete form.dataset.id;m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`); export const apiKeysSettingsPage = (viewer: { email: string }) => shell("API Keys — Factorize", viewer, settingsLayout("api-keys", `${dashboardHead("API Keys", "Manage API keys for programmatic access to Factorize.")} @@ -248,12 +248,12 @@ const scopes=value=>(value||[]).map(scope=>'

'+esc(client.clientName)+'

Client '+esc(client.clientId)+'

'+scopes(client.scopes)+'
Authorized
'+date(client.authorizationDate)+'
Last used
'+date(client.lastUsedAt)+'
Authorization expires
'+date(client.expiresAt)+'
'; const tokenRow=token=>'

'+esc(token.name)+'

'+scopes(token.scopes)+'
Expires
'+date(token.expires_at)+'
Created
'+date(token.created_at)+'
Last used
'+date(token.last_used_at)+'
'; -async function loadClients(){const loading=$('#clients-loading'),root=$('#authorized-clients'),empty=$('#clients-empty');loading.classList.remove('hidden');try{const clients=await request('/api/access/authorized-clients');root.innerHTML=clients.map(clientRow).join('');root.classList.toggle('hidden',!clients.length);empty.classList.toggle('hidden',clients.length>0);bindClientActions()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}} -async function loadTokens(){const loading=$('#tokens-loading'),root=$('#access-tokens'),empty=$('#tokens-empty');loading.classList.remove('hidden');try{const tokens=(await request('/api/access-tokens')).filter(token=>!token.revoked_at);root.innerHTML=tokens.map(tokenRow).join('');root.classList.toggle('hidden',!tokens.length);empty.classList.toggle('hidden',tokens.length>0);bindTokenActions()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}} -function bindClientActions(){document.querySelectorAll('[data-disconnect-client]').forEach(button=>button.onclick=async()=>{if(!confirm('Disconnect '+button.dataset.clientName+'? All of its tokens will stop working immediately.'))return;button.disabled=true;try{await request('/api/access/authorized-clients/'+encodeURIComponent(button.dataset.disconnectClient),{method:'DELETE'});await loadClients()}catch(error){button.disabled=false;accessError(error.message)}})} -function bindTokenActions(){document.querySelectorAll('[data-revoke-token]').forEach(button=>button.onclick=async()=>{if(!confirm('Revoke the access token “'+button.dataset.tokenName+'”? It will stop working immediately.'))return;button.disabled=true;try{await request('/api/access-tokens/'+encodeURIComponent(button.dataset.revokeToken),{method:'DELETE'});await loadTokens()}catch(error){button.disabled=false;accessError(error.message)}})} +async function loadClients(){const loading=$('#clients-loading'),root=$('#authorized-clients'),empty=$('#clients-empty');loading.classList.remove('hidden');try{const clients=await request('/api/v1/access/authorized-clients');root.innerHTML=clients.map(clientRow).join('');root.classList.toggle('hidden',!clients.length);empty.classList.toggle('hidden',clients.length>0);bindClientActions()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}} +async function loadTokens(){const loading=$('#tokens-loading'),root=$('#access-tokens'),empty=$('#tokens-empty');loading.classList.remove('hidden');try{const tokens=(await request('/api/v1/access-tokens')).filter(token=>!token.revoked_at);root.innerHTML=tokens.map(tokenRow).join('');root.classList.toggle('hidden',!tokens.length);empty.classList.toggle('hidden',tokens.length>0);bindTokenActions()}catch(error){empty.classList.remove('hidden');accessError(error.message)}finally{loading.classList.add('hidden')}} +function bindClientActions(){document.querySelectorAll('[data-disconnect-client]').forEach(button=>button.onclick=async()=>{if(!confirm('Disconnect '+button.dataset.clientName+'? All of its tokens will stop working immediately.'))return;button.disabled=true;try{await request('/api/v1/access/authorized-clients/'+encodeURIComponent(button.dataset.disconnectClient),{method:'DELETE'});await loadClients()}catch(error){button.disabled=false;accessError(error.message)}})} +function bindTokenActions(){document.querySelectorAll('[data-revoke-token]').forEach(button=>button.onclick=async()=>{if(!confirm('Revoke the access token “'+button.dataset.tokenName+'”? It will stop working immediately.'))return;button.disabled=true;try{await request('/api/v1/access-tokens/'+encodeURIComponent(button.dataset.revokeToken),{method:'DELETE'});await loadTokens()}catch(error){button.disabled=false;accessError(error.message)}})} const form=$('#token-form');$('#open-token-form').onclick=()=>{form.classList.remove('hidden');$('#open-token-form').classList.add('hidden');form.elements.name.focus()};$('#cancel-token-form').onclick=()=>{form.reset();form.classList.add('hidden');$('#open-token-form').classList.remove('hidden');$('#token-form-error').classList.add('hidden')}; document.querySelectorAll('[data-scope-preset]').forEach(button=>button.onclick=()=>{const read=button.dataset.scopePreset==='read';form.querySelectorAll('[name=scope]').forEach(input=>input.checked=!read||input.value.endsWith(':read'))}); -form.onsubmit=async event=>{event.preventDefault();const error=$('#token-form-error'),submit=form.querySelector('button[type="submit"]');error.classList.add('hidden');if(!submit){error.textContent='The create-token action is unavailable. Refresh and try again.';error.classList.remove('hidden');return}const selected=[...form.querySelectorAll('[name=scope]:checked')].map(input=>input.value);if(!selected.length){error.textContent='Select at least one scope.';error.classList.remove('hidden');return}submit.disabled=true;try{const result=await request('/api/access-tokens',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:form.elements.name.value,expiryDays:Number(form.elements.expiryDays.value),scopes:selected})});$('#new-token-value').textContent=result.token;const reveal=$('#new-token');reveal.classList.remove('hidden');reveal.focus();form.reset();form.classList.add('hidden');$('#open-token-form').classList.remove('hidden');await loadTokens()}catch(x){error.textContent=x.message||'Could not create the access token. Try again.';error.classList.remove('hidden')}finally{submit.disabled=false}}; +form.onsubmit=async event=>{event.preventDefault();const error=$('#token-form-error'),submit=form.querySelector('button[type="submit"]');error.classList.add('hidden');if(!submit){error.textContent='The create-token action is unavailable. Refresh and try again.';error.classList.remove('hidden');return}const selected=[...form.querySelectorAll('[name=scope]:checked')].map(input=>input.value);if(!selected.length){error.textContent='Select at least one scope.';error.classList.remove('hidden');return}submit.disabled=true;try{const result=await request('/api/v1/access-tokens',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:form.elements.name.value,expiryDays:Number(form.elements.expiryDays.value),scopes:selected})});$('#new-token-value').textContent=result.token;const reveal=$('#new-token');reveal.classList.remove('hidden');reveal.focus();form.reset();form.classList.add('hidden');$('#open-token-form').classList.remove('hidden');await loadTokens()}catch(x){error.textContent=x.message||'Could not create the access token. Try again.';error.classList.remove('hidden')}finally{submit.disabled=false}}; $('#copy-token').onclick=async()=>{const button=$('#copy-token');try{await navigator.clipboard.writeText($('#new-token-value').textContent);button.textContent='Copied'}catch{button.textContent='Select and copy the token'}setTimeout(()=>button.textContent='Copy',2000)}; Promise.all([loadClients(),loadTokens()]);`); diff --git a/packages/app/src/worker.ts b/packages/app/src/worker.ts index 08cbf26e..9e3561f6 100644 --- a/packages/app/src/worker.ts +++ b/packages/app/src/worker.ts @@ -56,7 +56,7 @@ const defaultHandler: ExportedHandler = { return Response.redirect(redirect, 302); } const granted = form.getAll("scope").map(String).filter(scope => parsed.scope.includes(scope) && scopes.includes(scope)); - const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: granted }; + const props: OAuthProps = { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes: granted, authMethod: "oauth" }; const { redirectTo } = await env.OAUTH_PROVIDER!.completeAuthorization({ request: parsed, userId: session.userId, metadata: { tenantId: session.tenantId }, scope: granted, props }); return Response.redirect(redirectTo, 302); } catch (error) { if (error instanceof AuthorizationError) return oauthError(error); throw error; } @@ -82,7 +82,7 @@ export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) if (url.pathname.startsWith("/api/v1") && !request.headers.has("Authorization")) { const session = await currentOwner(request, env); if (!session) return Response.json({ error: { code: "invalid_token", message: "Unauthorized" } }, { status: 401 }); - return protectedApiFetch(request, env, { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes }, ctx); + return protectedApiFetch(request, env, { tenantId: session.tenantId, userId: session.userId, sessionVersion: session.sessionVersion, scopes, authMethod: "session" }, ctx); } if ((url.pathname === "/mcp" || url.pathname.startsWith("/api/v1")) && request.headers.get("Authorization")?.startsWith("Bearer fzt_")) { const auth = await authenticateAccessToken(request, env); diff --git a/packages/app/test/api-contract.test.ts b/packages/app/test/api-contract.test.ts new file mode 100644 index 00000000..13cba510 --- /dev/null +++ b/packages/app/test/api-contract.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { API_OPERATIONS, isDeclaredApiOperation } from "../src/api-contract"; + +describe("versioned API contract", () => { + it("declares only versioned application endpoints", () => { + expect(API_OPERATIONS.length).toBeGreaterThan(40); + expect(API_OPERATIONS.every(([, path]) => path.startsWith("/api/v1/"))).toBe(true); + }); + + it("matches declared parameterized routes and rejects legacy routes", () => { + expect(isDeclaredApiOperation("GET", "/api/v1/providers/github/installations/42/repositories")).toBe(true); + expect(isDeclaredApiOperation("POST", "/api/v1/integrations/cloudflare-tail/tail-1/test")).toBe(true); + expect(isDeclaredApiOperation("GET", "/api" + "/connections/status")).toBe(false); + expect(isDeclaredApiOperation("GET", "/api/v1/not-declared")).toBe(false); + }); +}); diff --git a/packages/app/test/api-keys.browser.test.ts b/packages/app/test/api-keys.browser.test.ts index 974e0f2a..df9a3618 100644 --- a/packages/app/test/api-keys.browser.test.ts +++ b/packages/app/test/api-keys.browser.test.ts @@ -37,9 +37,9 @@ describe("rendered access token form", () => { const pendingCreate = new Promise((resolve) => { finishCreate = resolve; }); const fetchMock = vi.fn((input: unknown, init?: RequestInit) => { const path = String(input); - if (path === "/api/access/authorized-clients") return Promise.resolve(json([])); - if (path === "/api/access-tokens" && init?.method === "POST") return pendingCreate; - if (path === "/api/access-tokens") return Promise.resolve(json([])); + if (path === "/api/v1/access/authorized-clients") return Promise.resolve(json([])); + if (path === "/api/v1/access-tokens" && init?.method === "POST") return pendingCreate; + if (path === "/api/v1/access-tokens") return Promise.resolve(json([])); throw new Error(`Unexpected request: ${path}`); }); const form = renderPage(fetchMock); @@ -48,7 +48,7 @@ describe("rendered access token form", () => { form.dispatchEvent(new SubmitEvent("submit", { bubbles: true, cancelable: true, submitter: submit })); expect(submit.disabled).toBe(true); - expect(fetchMock.mock.calls.filter(([url, init]) => url === "/api/access-tokens" && init?.method === "POST")).toHaveLength(1); + expect(fetchMock.mock.calls.filter(([url, init]) => url === "/api/v1/access-tokens" && init?.method === "POST")).toHaveLength(1); finishCreate(json({ token: "fact_once_only" }, 201)); await flush(); @@ -56,16 +56,16 @@ describe("rendered access token form", () => { expect(document.querySelector("#new-token-value")?.textContent).toBe("fact_once_only"); expect(document.querySelector("#new-token")?.classList.contains("hidden")).toBe(false); - expect(fetchMock.mock.calls.filter(([url, init]) => url === "/api/access-tokens" && !init?.method)).toHaveLength(2); + expect(fetchMock.mock.calls.filter(([url, init]) => url === "/api/v1/access-tokens" && !init?.method)).toHaveLength(2); expect(submit.disabled).toBe(false); }); it("shows API errors in the form and restores the button", async () => { const fetchMock = vi.fn((input: unknown, init?: RequestInit) => { const path = String(input); - if (path === "/api/access/authorized-clients") return Promise.resolve(json([])); - if (path === "/api/access-tokens" && init?.method === "POST") return Promise.resolve(json({ error: "Token name already exists" }, 422)); - if (path === "/api/access-tokens") return Promise.resolve(json([])); + if (path === "/api/v1/access/authorized-clients") return Promise.resolve(json([])); + if (path === "/api/v1/access-tokens" && init?.method === "POST") return Promise.resolve(json({ error: "Token name already exists" }, 422)); + if (path === "/api/v1/access-tokens") return Promise.resolve(json([])); throw new Error(`Unexpected request: ${path}`); }); const form = renderPage(fetchMock); diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index 3d0fc3de..a121a843 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -127,8 +127,8 @@ describe("pages", () => { expect(html).toContain("reservedSlugs=new Set(triggers.map(t=>t.slug));render();await refreshAvailability();loadProviderResources()"); expect(html).toContain("if(availability.linear)"); expect(html).toContain("if(availability.clickup)"); - expect(html).not.toContain("request('/api/clickup/lists').catch(()=>[])"); - expect(html).not.toContain("request('/api/linear/options').catch"); + expect(html).toContain("request('/api/v1/providers/clickup/lists')"); + expect(html).toContain("request('/api/v1/providers/linear/options')"); expectInlineScriptsToParse(html); }); @@ -294,7 +294,7 @@ describe("pages", () => { expect(apiKeys).toContain("cannot be retrieved again"); expect(apiKeys).toContain("Authorization: Bearer <token>"); expect(apiKeys).toContain("All of its tokens will stop working immediately"); - expect(apiKeys).toContain("/api/access-tokens"); + expect(apiKeys).toContain("/api/v1/access-tokens"); expectInlineScriptsToParse(apiKeys); }); @@ -320,7 +320,7 @@ describe("pages", () => { expect(settings).toContain('