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
12 changes: 7 additions & 5 deletions packages/api/src/postgres/integration-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { ConnectionRepository } from "./connection-repository";

const timestamp = () => new Date().toISOString();
const tailSecret = () => `fztail_${Array.from(crypto.getRandomValues(new Uint8Array(24)), byte => byte.toString(16).padStart(2, "0")).join("")}`;
const text = (value: unknown) => typeof value === "string" ? value : undefined;
const tags = (value: unknown) => Array.isArray(value) ? value.filter((tag): tag is string => typeof tag === "string") : [];

export class IntegrationService {
readonly connections: ConnectionRepository;
Expand Down Expand Up @@ -76,17 +78,17 @@ export class IntegrationService {
]);
const byId = new Map(counts.rows.map(row => [row.integration_id, Number(row.count)]));
return [...connections].filter(([kind]) => kind.startsWith("cloudflare-tail:")).map(([kind, value]) => {
const { signingSecret: _, ...safe } = value, integrationId = kind.slice(16);
return { ...safe, integrationId, status: "connected", secretConfigured: true, referencedJobCount: byId.get(integrationId) ?? 0 };
const integrationId = kind.slice(16);
return { integrationId, name: text(value?.name) ?? "Unnamed Tail integration", status: "connected" as const, secretConfigured: true as const, ...(text(value?.createdAt) ? { createdAt: text(value.createdAt) } : {}), ...(text(value?.updatedAt) ? { updatedAt: text(value.updatedAt) } : {}), referencedJobCount: byId.get(integrationId) ?? 0 };
});
}
async testTail(id: string) { const value = await this.connections.get<any>(`cloudflare-tail:${id}`); if (!value) return null; const now = String(Date.now()), delivery = `test-${crypto.randomUUID()}`, body = "{}", signature = await signTailDelivery(value.signingSecret, now, delivery, body); return { ok: await verifyTailDelivery(value.signingSecret, now, delivery, body, signature) === "valid" }; }
async status() {
const connectionsPromise = this.connections.all(["linear", "clickup", "exe:", "amp:", "cloudflare-tail:"]);
const [connections, tails] = await Promise.all([connectionsPromise, this.tails(connectionsPromise)]);
const linear = connections.get("linear"), clickup = connections.get("clickup");
const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => { const { apiToken: _, ...safe } = value; return { ...safe, connectionId: kind.slice(4) }; });
const ampConnections = [...connections].filter(([kind]) => kind.startsWith("amp:")).map(([kind, value]) => { const { accessToken: _, ...safe } = value; return { ...safe, connectionId: kind.slice(4) }; });
return { linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, clickup: clickup ? { teamName: clickup.teamName ?? null } : null, exe: exeConnections[0] ?? null, exeConnections, ampConnections, cloudflareTail: { count: tails.length, installations: tails } };
const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => ({ connectionId: kind.slice(4), credentialStatus: "connected" as const, accountTags: tags(value?.accountTags) }));
const ampConnections = [...connections].filter(([kind]) => kind.startsWith("amp:")).map(([kind, value]) => ({ connectionId: kind.slice(4), project: text(value?.project) ?? "Unnamed Amp project", ...(text(value?.apiBaseUrl) ? { apiBaseUrl: text(value.apiBaseUrl) } : {}) }));
return { linear: linear ? { organizationName: text(linear.organizationName) ?? null, viewerEmail: text(linear.viewerEmail) ?? null } : null, clickup: clickup ? { teamName: text(clickup.teamName) ?? null } : null, exe: exeConnections[0] ?? null, exeConnections, ampConnections, cloudflareTail: { count: tails.length, installations: tails } };
}
}
18 changes: 18 additions & 0 deletions packages/api/test/loading.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { loadingFixture } from "./helpers/loading-fixture";
import { Database } from "../src/postgres/database";
import { IdentityRepository } from "../src/postgres/identity-repository";
import { PostgresJobRepository } from "../src/postgres/job-repository";
import { ConnectionRepository } from "../src/postgres/connection-repository";
import { ApiService } from "../src/flow-service";
import worker from "../src/worker";
import { signSession } from "../src/index";
Expand Down Expand Up @@ -58,6 +59,23 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => {
expect(query).toHaveBeenCalledTimes(3); // membership + connections + reference counts
} finally { query.mockRestore(); }
});
it("keeps the integration status available when legacy connection metadata is malformed", async () => {
const connections = new ConnectionRepository(db, tenantId, env.CREDENTIAL_ENCRYPTION_KEY), originalLinear = await connections.get("linear");
try {
await connections.put("linear", { organizationName: 42, viewerEmail: false });
await connections.put("exe:legacy", { apiToken: "private-token", accountTags: "not-an-array" });
await connections.put("amp:legacy", { accessToken: "private-token", project: 42, apiBaseUrl: false });
await connections.put("cloudflare-tail:legacy", { signingSecret: "private-secret" });
const status = await new ApiService(env, auth).integrationStatus();
expect(status.linear).toEqual({ organizationName: null, viewerEmail: null });
expect(status.exeConnections).toContainEqual({ connectionId: "legacy", credentialStatus: "connected", accountTags: [] });
expect(status.ampConnections).toContainEqual({ connectionId: "legacy", project: "Unnamed Amp project" });
expect(status.cloudflareTail.installations).toContainEqual({ integrationId: "legacy", name: "Unnamed Tail integration", status: "connected", secretConfigured: true, referencedJobCount: 0 });
expect(JSON.stringify(status)).not.toContain("private-");
} finally {
await Promise.all([originalLinear ? connections.put("linear", originalLinear) : connections.delete("linear"), connections.delete("exe:legacy"), connections.delete("amp:legacy"), connections.delete("cloudflare-tail:legacy")]);
}
});

it("creates a job with a deterministic migrated execution target UUID", async () => {
const target = (await db.pool.query(`INSERT INTO app.execution_targets(tenant_id,id,name,integration_kind,integration_id,agent_kind)
Expand Down
Loading