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
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
15 changes: 15 additions & 0 deletions packages/app/scripts/check-api-boundaries.mjs
Original file line number Diff line number Diff line change
@@ -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.`);
3 changes: 2 additions & 1 deletion packages/app/src/access-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
26 changes: 26 additions & 0 deletions packages/app/src/api-contract.ts
Original file line number Diff line number Diff line change
@@ -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)); }
37 changes: 37 additions & 0 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand Down Expand Up @@ -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<void> { 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 ?? []) {
Expand Down Expand Up @@ -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<string>(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 }; }
}
Loading
Loading