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
243 changes: 243 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,69 @@
// Generated from packages/docs/openapi.yaml. Do not edit.
export interface paths {
"/api/v1/integrations/bearer": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List encrypted bearer integrations
* @description Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed.
*
* Requires the integrations:read scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
get: operations["get_api_v1_integrations_bearer"];
put?: never;
/**
* Create an encrypted bearer integration
* @description Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential.
*
* Requires the integrations:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
post: operations["post_api_v1_integrations_bearer"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/integrations/bearer/{integrationId}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
/**
* Update an encrypted bearer integration
* @description Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext.
*
* Requires the integrations:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
put: operations["put_api_v1_integrations_bearer_integrationId"];
post?: never;
/**
* Delete an encrypted bearer integration
* @description Requires an interactive owner browser session and the current collection revision.
*
* Requires the integrations:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
delete: operations["delete_api_v1_integrations_bearer_integrationId"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/auth/connections": {
parameters: {
query?: never;
Expand Down Expand Up @@ -2451,6 +2515,185 @@ export interface components {
}
export type $defs = Record<string, never>;
export interface operations {
get_api_v1_integrations_bearer: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Encrypted bearer integration records */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
revision: number;
integrations: {
/** Format: uuid */
id: string;
name: string;
origin: string;
description: string | null;
revision: number;
encryptedPayload: string;
}[];
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
post_api_v1_integrations_bearer: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** Format: uuid */
id: string;
expectedRevision: number;
/** Format: uuid */
idempotencyKey: string;
name: string;
/** Format: uri */
origin: string;
description: string | null;
encryptedPayload: string;
};
};
};
responses: {
/** @description Created integration */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
revision: number;
duplicate: boolean;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
415: components["responses"]["Error415"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
put_api_v1_integrations_bearer_integrationId: {
parameters: {
query?: never;
header?: never;
path: {
integrationId: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
expectedRevision: number;
/** Format: uuid */
idempotencyKey: string;
name: string;
/** Format: uri */
origin: string;
description: string | null;
encryptedPayload: string;
};
};
};
responses: {
/** @description Updated integration */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
revision: number;
duplicate: boolean;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
415: components["responses"]["Error415"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
delete_api_v1_integrations_bearer_integrationId: {
parameters: {
query?: never;
header?: never;
path: {
integrationId: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
expectedRevision: number;
/** Format: uuid */
idempotencyKey: string;
};
};
};
responses: {
/** @description Deleted integration */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** Format: uuid */
id: string;
/** @constant */
deleted: true;
revision: number;
duplicate: boolean;
};
};
};
400: components["responses"]["Error400"];
401: components["responses"]["Error401"];
403: components["responses"]["Error403"];
404: components["responses"]["Error404"];
409: components["responses"]["Error409"];
415: components["responses"]["Error415"];
429: components["responses"]["Error429"];
500: components["responses"]["Error500"];
503: components["responses"]["Error503"];
};
};
post_api_v1_auth_connections: {
parameters: {
query?: never;
Expand Down
34 changes: 34 additions & 0 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,20 @@ const accessTokenBody = z.object({
scopes: z.array(z.union([scopeSchema, z.enum(["flows:read", "flows:write"])] )).min(1),
expiryDays: z.union([z.literal(7), z.literal(30), z.literal(90)]),
});
const bearerIntegrationMetadata = z.object({
id: z.uuid(), name: z.string(), origin: z.string(), description: z.string().nullable(),
revision: z.number().int().nonnegative(), encryptedPayload: z.string(),
});
const bearerIntegrationCreate = z.object({
id: z.uuid(), expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid(),
name: z.string().trim().min(1).max(120), origin: z.string().url().max(2048),
description: z.string().max(500).nullable(), encryptedPayload: z.string().min(1).max(65_536),
}).strict();
const bearerIntegrationUpdate = bearerIntegrationCreate.omit({ id: true });
const bearerIntegrationDelete = z.object({ expectedRevision: z.number().int().nonnegative(), idempotencyKey: z.uuid() }).strict();
const bearerIntegrationList = z.object({ revision: z.number().int().nonnegative(), integrations: z.array(bearerIntegrationMetadata) });
const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonnegative(), duplicate: z.boolean() });
const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() });

function route(
method: string,
Expand Down Expand Up @@ -195,6 +209,26 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st
}

export const API_ROUTES: RouteContract[] = [
route("GET", "/api/v1/integrations/bearer", "flows:read", {
summary: "List encrypted bearer integrations",
description: "Requires an interactive owner browser session. Returns safe metadata and user-encrypted ciphertext; credentials are never decrypted or revealed.",
responses: { "200": { description: "Encrypted bearer integration records", content: { "application/json": { schema: jsonSchema(bearerIntegrationList, "output") } } } },
}, service => service.listBearerIntegrations(), { ownerSession: true }),
route("POST", "/api/v1/integrations/bearer", "flows:write", {
summary: "Create an encrypted bearer integration",
description: "Requires an interactive owner browser session. Accepts only user-encrypted ciphertext, never an unlock key or plaintext credential.",
responses: { "201": { description: "Created integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } },
}, (service, { body }) => service.createBearerIntegration(body), { body: bearerIntegrationCreate, maxBodyBytes: 70_000, ownerSession: true }),
route("PUT", "/api/v1/integrations/bearer/{integrationId}", "flows:write", {
summary: "Update an encrypted bearer integration",
description: "Requires an interactive owner browser session and the current collection revision. Accepts only user-encrypted ciphertext.",
responses: { "200": { description: "Updated integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } },
}, (service, { params, body }) => service.updateBearerIntegration(params.integrationId, body), { body: bearerIntegrationUpdate, maxBodyBytes: 70_000, ownerSession: true }),
route("DELETE", "/api/v1/integrations/bearer/{integrationId}", "flows:write", {
summary: "Delete an encrypted bearer integration",
description: "Requires an interactive owner browser session and the current collection revision.",
responses: { "200": { description: "Deleted integration", content: { "application/json": { schema: jsonSchema(bearerIntegrationDeleteResult, "output") } } } },
}, (service, { params, body }) => service.deleteBearerIntegration(params.integrationId, body), { body: bearerIntegrationDelete, maxBodyBytes: 4096, ownerSession: true }),
authRoute("POST", "/api/v1/auth/connections", "connection-start", "Persist an individual validated MCP connection; sets a per-attempt browser cookie", connectionStartSuccess, connectionStartInput),
authRoute("POST", "/api/v1/auth/connections/resume", "connection-resume", "Resume verified onboarding in the initiating browser; never grants OAuth access", continuationSuccess, connectionResumeInput),
authRoute("GET", "/api/v1/session", "session", "Get current browser session", sessionResponse),
Expand Down
39 changes: 39 additions & 0 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { jobResponse } from "./job-contracts";
import type { JobPageQuery } from "./job-contracts";
import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository";
import { ConnectionRepository } from "./postgres/connection-repository";
import { EncryptedIntegrationRepository, IntegrationIdempotencyConflictError, IntegrationValidationError, StaleIntegrationRevisionError } from "./postgres/encrypted-integration-repository";
import { decrypt, encrypt } from "./crypto";
import { InvocationService, type Job, type Trigger } from "./job-domain";
import { RunQueryRepository } from "./postgres/run-query-repository";
Expand Down Expand Up @@ -456,6 +457,44 @@ export class ApiService {
async testAmpIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().testAmp(input); }
async saveTailIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveTail(input); }
async testTailIntegration(id: string) { await this.authorize("integrations:write"); const result = await this.integrations().testTail(id); if (!result) throw new ServiceError(404, "not_found", "Integration not found"); return result; }
private encryptedIntegrations() { return new EncryptedIntegrationRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); }
private async bearerWrite(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload?: string; operation: "upsert" | "delete" }) {
try { return await this.encryptedIntegrations().write({ ...input, kind: "bearer" }); }
catch (error) {
if (error instanceof StaleIntegrationRevisionError) throw new ServiceError(409, "stale_revision", `The integration collection changed. Current revision is ${error.currentRevision}.`);
if (error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409, "conflict", "The idempotency key was already used for a different integration change.");
if (error instanceof IntegrationValidationError) throw new ServiceError(400, "invalid_request", error.message);
throw error;
}
}
private validateBearerOrigin(origin: string) {
let parsed: URL;
try { parsed = new URL(origin); } catch { throw new ServiceError(400, "invalid_request", "Integration origin must be an HTTPS origin."); }
if (parsed.protocol !== "https:" || parsed.origin !== origin || parsed.username || parsed.password) throw new ServiceError(400, "invalid_request", "Integration origin must be an HTTPS origin without credentials, path, query, or fragment.");
}
async listBearerIntegrations() {
await this.authorizeOwnerSession("integrations:read");
const [revision, records] = await Promise.all([this.encryptedIntegrations().revision(), this.encryptedIntegrations().records("bearer")]);
return { revision, integrations: records };
}
async createBearerIntegration(input: { id: string; expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload: string }) {
await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin);
if ((await this.encryptedIntegrations().records("bearer")).some(record => record.id === input.id)) throw new ServiceError(409, "conflict", "Integration already exists.");
return this.bearerWrite({ ...input, operation: "upsert" });
}
async updateBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string; name: string; origin: string; description: string | null; encryptedPayload: string }) {
await this.authorizeOwnerSession("integrations:write"); this.validateBearerOrigin(input.origin);
const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id);
if (!existing) throw new ServiceError(404, "not_found", "Integration not found.");
return this.bearerWrite({ ...input, id, operation: "upsert" });
}
async deleteBearerIntegration(id: string, input: { expectedRevision: number; idempotencyKey: string }) {
await this.authorizeOwnerSession("integrations:write");
const existing = (await this.encryptedIntegrations().records("bearer")).find(record => record.id === id && record.origin !== null);
if (!existing) throw new ServiceError(404, "not_found", "Integration not found.");
const result = await this.bearerWrite({ id, name: existing.name, origin: existing.origin!, description: existing.description, ...input, operation: "delete" });
return { id, deleted: true as const, ...result };
}
async removeTailIntegration(id: string) { await this.authorize("integrations: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("integrations:read"); return publicValue(z.array(namedOption), await this.providers().linearProjects()); }
async linearOptions() { await this.authorize("integrations:read"); return publicValue(providerOptions, await this.providers().linearOptions()); }
Expand Down
Loading
Loading