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
4,276 changes: 2,708 additions & 1,568 deletions package-lock.json

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions packages/app/drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineConfig } from "drizzle-kit";

export default defineConfig({
dialect: "postgresql",
schema: "./src/postgres/schema.ts",
// Existing SQL migrations remain the immutable deployment history. New
// migrations are reviewed into that same directory.
out: "./migrations",
schemaFilter: ["app"],
dbCredentials: { url: process.env.DATABASE_URL ?? "postgresql://localhost/factorize" },
strict: true,
verbose: true,
});
9 changes: 9 additions & 0 deletions packages/app/migrations/0004_trigger_lifecycle.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- Disabled triggers remain editable. Removed triggers disappear from the job
-- definition but retain their stable identity while history references them.
ALTER TABLE app.triggers ADD COLUMN IF NOT EXISTS removed_at timestamptz;

ALTER TABLE app.triggers DROP CONSTRAINT IF EXISTS triggers_tenant_id_job_id_slug_key;
CREATE UNIQUE INDEX IF NOT EXISTS triggers_active_slug
ON app.triggers (tenant_id,job_id,slug) WHERE removed_at IS NULL;

INSERT INTO app.schema_migrations(version) VALUES ('0004_trigger_lifecycle') ON CONFLICT DO NOTHING;
11 changes: 11 additions & 0 deletions packages/app/migrations/0005_oauth_device_authorizations.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS app.oauth_device_authorizations (
device_code text PRIMARY KEY,
user_code text NOT NULL UNIQUE,
record jsonb NOT NULL,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS oauth_device_authorizations_expires ON app.oauth_device_authorizations(expires_at);

INSERT INTO app.schema_migrations(version) VALUES ('0005_oauth_device_authorizations') ON CONFLICT DO NOTHING;
10 changes: 10 additions & 0 deletions packages/app/migrations/0006_job_delete_cascade.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- The original composite SET NULL action also tried to null tenant_id, which
-- is NOT NULL. Job deletion is intentionally destructive, so these associated
-- delivery events belong to the job cascade.
ALTER TABLE app.webhook_delivery_events
DROP CONSTRAINT IF EXISTS webhook_delivery_events_tenant_id_job_id_fkey;
ALTER TABLE app.webhook_delivery_events
ADD CONSTRAINT webhook_delivery_events_tenant_id_job_id_fkey
FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE;

INSERT INTO app.schema_migrations(version) VALUES ('0006_job_delete_cascade') ON CONFLICT DO NOTHING;
5 changes: 5 additions & 0 deletions packages/app/migrations/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# PostgreSQL migrations

`../src/postgres/schema.ts` is the canonical Drizzle representation of the
deployed `app` schema. These SQL files remain the immutable deployment history;
schema changes must update both the Drizzle model and a forward-only migration.
The application migration runner, rather than `drizzle-kit push`, applies them.

These reviewed SQL migrations run outside Worker request handling. Apply them
with a schema-owner connection:

Expand Down
5 changes: 4 additions & 1 deletion packages/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
"test": "vitest run",
"deploy": "wrangler deploy",
"db:migrate": "node scripts/migrate.mjs",
"db:verify": "node scripts/verify-schema.mjs"
"db:verify": "node scripts/verify-schema.mjs",
"db:studio": "drizzle-kit studio --config drizzle.config.ts"
},
"dependencies": {
"@cloudflare/workers-oauth-provider": "^0.10.3",
"@modelcontextprotocol/hono": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"cron-parser": "^5.10.1",
"drizzle-orm": "^0.45.2",
"hono": "^4.11.4",
"mustache": "^4.2.0",
"pg": "8.16.3",
Expand All @@ -30,6 +32,7 @@
"@types/mustache": "^4.2.6",
"@types/node": "^26.5.1",
"@types/pg": "^8.15.5",
"drizzle-kit": "^0.31.10",
"happy-dom": "^20.14.5",
"tailwindcss": "^4.1.14",
"typescript": "^5.9.3",
Expand Down
44 changes: 31 additions & 13 deletions packages/app/src/device-oauth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { AuthRequest } from "@cloudflare/workers-oauth-provider";
import { hmac } from "./crypto";
import type { Env, OAuthProps } from "./types";
import { and, eq, gt } from "drizzle-orm";
import { databaseFor } from "./postgres/database";
import { oauthDeviceAuthorizations } from "./postgres/schema";

export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
const DEVICE_TTL = 600;
Expand Down Expand Up @@ -84,12 +87,30 @@ async function authenticateDeviceClient(request: Request, env: Env, form: FormDa
return Boolean(stored?.clientSecret && safeEqual(await sha256Hex(clientSecret), stored.clientSecret));
}
async function readDevice(env: Env, code: string): Promise<DeviceRecord | null> {
return env.OAUTH_KV?.get<DeviceRecord>(deviceKey(code), "json") ?? null;
if (!env.DATABASE && !env.HYPERDRIVE) return env.OAUTH_KV?.get<DeviceRecord>(deviceKey(code), "json") ?? null;
const [row] = await databaseFor(env).orm.select({ record: oauthDeviceAuthorizations.record }).from(oauthDeviceAuthorizations).where(and(eq(oauthDeviceAuthorizations.deviceCode, code), gt(oauthDeviceAuthorizations.expiresAt, new Date()))).limit(1);
return row?.record as DeviceRecord | undefined ?? null;
}
async function deviceCodeForUser(env: Env, userCode: string): Promise<string | null> {
if (!env.DATABASE && !env.HYPERDRIVE) return env.OAUTH_KV?.get(userKey(userCode)) ?? null;
const [row] = await databaseFor(env).orm.select({ deviceCode: oauthDeviceAuthorizations.deviceCode }).from(oauthDeviceAuthorizations).where(and(eq(oauthDeviceAuthorizations.userCode, normalizeUserCode(userCode)), gt(oauthDeviceAuthorizations.expiresAt, new Date()))).limit(1);
return row?.deviceCode ?? null;
}
async function writeDevice(env: Env, deviceCode: string, userCode: string, record: DeviceRecord): Promise<void> {
if (!env.DATABASE && !env.HYPERDRIVE) {
await Promise.all([env.OAUTH_KV!.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - Math.floor(Date.now() / 1000)) }), env.OAUTH_KV!.put(userKey(userCode), deviceCode, { expirationTtl: Math.max(1, record.expiresAt - Math.floor(Date.now() / 1000)) })]);
return;
}
await databaseFor(env).orm.insert(oauthDeviceAuthorizations).values({ deviceCode, userCode: normalizeUserCode(userCode), record, expiresAt: new Date(record.expiresAt * 1000) }).onConflictDoUpdate({ target: oauthDeviceAuthorizations.deviceCode, set: { record, expiresAt: new Date(record.expiresAt * 1000), updatedAt: new Date() } });
}
async function deleteDevice(env: Env, deviceCode: string, userCode?: string): Promise<void> {
if (!env.DATABASE && !env.HYPERDRIVE) { await Promise.all([env.OAUTH_KV!.delete(deviceKey(deviceCode)), ...(userCode ? [env.OAUTH_KV!.delete(userKey(userCode))] : [])]); return; }
await databaseFor(env).orm.delete(oauthDeviceAuthorizations).where(eq(oauthDeviceAuthorizations.deviceCode, deviceCode));
}

export async function deviceAuthorization(request: Request, env: Env, oauth: OAuthHelpers, supportedScopes: string[]): Promise<Response> {
if (request.method !== "POST") return new Response("Method not allowed", { status: 405, headers: { Allow: "POST" } });
if (!env.OAUTH_KV) return oauthError("server_error", "OAuth storage is unavailable.", 500);
if (!env.OAUTH_KV && !env.DATABASE && !env.HYPERDRIVE) return oauthError("server_error", "OAuth storage is unavailable.", 500);
const form = await request.formData();
const basic = basicCredentials(request);
const clientId = basic?.clientId ?? String(form.get("client_id") ?? "");
Expand All @@ -109,7 +130,7 @@ export async function deviceAuthorization(request: Request, env: Env, oauth: OAu
let compactUserCode = "";
for (let attempt = 0; attempt < 8; attempt++) {
compactUserCode = Array.from(crypto.getRandomValues(new Uint8Array(8)), value => alphabet[value % alphabet.length]).join("");
if (!await env.OAUTH_KV.get(userKey(compactUserCode))) break;
if (!await deviceCodeForUser(env, compactUserCode)) break;
compactUserCode = "";
}
if (!compactUserCode) return oauthError("server_error", "Could not allocate a user code.", 500);
Expand All @@ -119,10 +140,7 @@ export async function deviceAuthorization(request: Request, env: Env, oauth: OAu
redirectUri: client.redirectUris[0], codeChallenge: await challenge(codeVerifier),
createdAt: now, expiresAt: now + DEVICE_TTL, interval: DEFAULT_INTERVAL, status: "pending",
};
await Promise.all([
env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: DEVICE_TTL }),
env.OAUTH_KV.put(userKey(compactUserCode), deviceCode, { expirationTtl: DEVICE_TTL }),
]);
await writeDevice(env, deviceCode, compactUserCode, record);
const verificationUri = `${env.APP_ORIGIN}/device`;
const userCode = displayUserCode(compactUserCode);
return json({
Expand All @@ -136,7 +154,7 @@ export async function deviceAuthorization(request: Request, env: Env, oauth: OAu
}

export async function deviceToken(request: Request, env: Env, oauthProvider: { fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> }, ctx: ExecutionContext): Promise<Response> {
if (!env.OAUTH_KV) return oauthError("server_error", "OAuth storage is unavailable.", 500);
if (!env.OAUTH_KV && !env.DATABASE && !env.HYPERDRIVE) return oauthError("server_error", "OAuth storage is unavailable.", 500);
const form = await request.formData();
const deviceCode = String(form.get("device_code") ?? "");
const basic = basicCredentials(request);
Expand Down Expand Up @@ -164,17 +182,17 @@ export async function deviceToken(request: Request, env: Env, oauthProvider: { f
const authorization = request.headers.get("Authorization");
if (authorization) headers.set("Authorization", authorization);
const response = await oauthProvider.fetch(new Request(`${env.APP_ORIGIN}/oauth/token`, { method: "POST", headers, body: exchange }), env, ctx);
if (response.ok) await env.OAUTH_KV.delete(deviceKey(deviceCode));
if (response.ok) await deleteDevice(env, deviceCode);
return response;
}

export async function deviceVerification(request: Request, env: Env, oauth: OAuthHelpers, session: { tenantId: string; userId: string; email: string; sessionVersion: number }): Promise<Response> {
if (!env.OAUTH_KV) return new Response("OAuth storage is unavailable", { status: 500 });
if (!env.OAUTH_KV && !env.DATABASE && !env.HYPERDRIVE) return new Response("OAuth storage is unavailable", { status: 500 });
const url = new URL(request.url);
const form = request.method === "POST" ? await request.formData() : null;
const suppliedCode = String(form?.get("user_code") ?? url.searchParams.get("user_code") ?? "");
const normalized = normalizeUserCode(suppliedCode);
const deviceCode = normalized.length === 8 ? await env.OAUTH_KV.get(userKey(normalized)) : null;
const deviceCode = normalized.length === 8 ? await deviceCodeForUser(env, normalized) : null;
const record = deviceCode ? await readDevice(env, deviceCode) : null;
const valid = record && record.status === "pending" && record.expiresAt > Math.floor(Date.now() / 1000);
if (request.method === "GET") {
Expand All @@ -185,7 +203,7 @@ export async function deviceVerification(request: Request, env: Env, oauth: OAut
if (!valid || !deviceCode || !record) return new Response("Invalid or expired device code", { status: 400 });
if (form?.get("decision") === "deny") {
record.status = "denied";
await Promise.all([env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - Math.floor(Date.now() / 1000)) }), env.OAUTH_KV.delete(userKey(normalized))]);
await writeDevice(env, deviceCode, normalized, record);
return confirmation("Authorization denied", "You can close this window.");
}
if (form?.get("decision") !== "allow") return Response.redirect(`${env.APP_ORIGIN}/device?user_code=${encodeURIComponent(displayUserCode(normalized))}`, 303);
Expand All @@ -195,7 +213,7 @@ export async function deviceVerification(request: Request, env: Env, oauth: OAut
record.status = "approved";
record.authorizationCode = new URL(result.redirectTo).searchParams.get("code") ?? undefined;
if (!record.authorizationCode) return new Response("Could not complete device authorization", { status: 500 });
await Promise.all([env.OAUTH_KV.put(deviceKey(deviceCode), JSON.stringify(record), { expirationTtl: Math.max(1, record.expiresAt - Math.floor(Date.now() / 1000)) }), env.OAUTH_KV.delete(userKey(normalized))]);
await writeDevice(env, deviceCode, normalized, record);
return confirmation("Device connected", "Authorization is complete. You can close this window.");
}

Expand Down
28 changes: 22 additions & 6 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { installedTriggerAvailability } from "./trigger-availability";
import { invokeCustomHandler } from "./custom-handler";
import { validateWebhookHandler } from "./webhook-trigger";
import { ProviderCatalog } from "./postgres/provider-catalog";
import { ArtifactRepository } from "./postgres/artifact-repository";
import { ACCESS_SCOPES, accessTokenDigest, issueAccessToken } from "./access-tokens";

export class ServiceError extends Error {
Expand Down Expand Up @@ -47,10 +48,13 @@ export class ApiService {
const prior = new Map(existing.map(trigger => [trigger.id, trigger])), used = new Set(existing.map(trigger => trigger.slug));
let next = 1, timestamp = new Date().toISOString();
return source.map(trigger => {
const old = trigger.id ? prior.get(trigger.id) : undefined;
// A trigger's kind is part of its identity. Changing kind is a removal
// plus an insertion, never an in-place mutation of historical identity.
const candidate = trigger.id ? prior.get(trigger.id) : undefined;
const old = candidate?.kind === trigger.kind ? candidate : undefined;
while (used.has(`trigger-${next}`)) next++;
const slug = old?.slug ?? trigger.slug ?? `trigger-${next++}`; used.add(slug);
return { id: old?.id ?? trigger.id ?? crypto.randomUUID(), jobId: old?.jobId ?? "", kind: trigger.kind, slug, enabled: trigger.enabled !== false, config: trigger.config, createdAt: old?.createdAt ?? timestamp, updatedAt: timestamp };
return { id: old?.id ?? crypto.randomUUID(), jobId: old?.jobId ?? "", kind: trigger.kind, slug, enabled: trigger.enabled !== false, config: trigger.config, createdAt: old?.createdAt ?? timestamp, updatedAt: timestamp };
});
}

Expand Down Expand Up @@ -97,15 +101,27 @@ export class ApiService {
await this.authorize("flows:write"); const timestamp = new Date().toISOString(), id = crypto.randomUUID();
const triggers = this.normalizedTriggers(input.triggers).map(trigger => ({ ...trigger, jobId: id }));
const job: Job = { id, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", ...(input.effort ? { effort: input.effort } : {}), executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, enabled: true, triggers, createdAt: timestamp, updatedAt: timestamp };
try { return this.presentJob(await this.jobs().save(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; }
try { return this.presentJob(await this.jobs().create(job)); } catch (error: any) { if (error?.code === "23505") throw new ServiceError(409, "conflict", "Job slug is already in use"); throw error; }
}
async updateJob(jobId: string, input: JobInput) {
await this.authorize("flows:write"); const repository = this.jobs(), current = await repository.getJob(jobId); if (!current) throw new ServiceError(404, "not_found", "Job not found");
const triggers = this.normalizedTriggers(input.triggers, current.triggers).map(trigger => ({ ...trigger, jobId }));
return this.presentJob(await repository.save({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }));
return this.presentJob(await repository.update({ ...current, name: input.name, slug: input.slug, promptTemplate: input.promptTemplate, runNameTemplate: input.runNameTemplate ?? "", model: input.model ?? "", effort: input.effort, executionTarget: await this.executionTarget(input.executionTargetId), concurrencyLimit: input.concurrencyLimit, triggers, updatedAt: new Date().toISOString() }));
}
async deleteJob(jobId: string) { await this.authorize("flows:write"); if (!await this.jobs().delete(jobId)) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, deleted: true }; }
async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); await repository.save({ ...job, enabled, updatedAt: new Date().toISOString() }); return { id: jobId, enabled }; }
async deleteJob(jobId: string) {
await this.authorize("flows:write");
const database = databaseFor(this.env), repository = this.jobs();
if (!await repository.getJob(jobId)) throw new ServiceError(404, "not_found", "Job not found");
const objectKeys = await new ArtifactRepository(database, this.auth.tenantId).keysForJob(jobId);
if (objectKeys.length && !this.env.RUN_ARTIFACTS) throw new ServiceError(503, "operation_failed", "Artifact storage is unavailable");
// R2 is outside the PostgreSQL transaction. Delete the objects first and
// retain the database aggregate if object deletion fails so the operation
// can be retried without losing the authoritative object-key inventory.
for (let offset = 0; offset < objectKeys.length; offset += 1_000) await this.env.RUN_ARTIFACTS!.delete(objectKeys.slice(offset, offset + 1_000));
if (!await repository.delete(jobId)) throw new ServiceError(404, "not_found", "Job not found");
return { id: jobId, deleted: true };
}
async setJobEnabled(jobId: string, enabled: boolean) { await this.authorize("flows:write"); const repository = this.jobs(); if (!await repository.setEnabled(jobId, enabled, new Date().toISOString())) throw new ServiceError(404, "not_found", "Job not found"); return { id: jobId, enabled }; }
async invokeJob(jobId: string, input: ManualInvocationInput) {
await this.authorize("runs:write"); const repository = this.jobs(), job = await repository.getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found");
const trigger = job.triggers.find(value => value.kind === "manual" && value.enabled); if (!trigger) throw new ServiceError(409, "operation_failed", "The manual trigger is disabled");
Expand Down
Loading
Loading