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
211 changes: 211 additions & 0 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,70 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/fly/connection": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Read Fly account connection status
* @description Owner browser session only. Returns organization metadata and never returns the provisioning token.
*
* Requires the integrations:read scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
get: operations["get_api_v1_fly_connection"];
/**
* Save a Fly account connection
* @description Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org <slug>`. A read-only org token is insufficient for provisioning. The server validates the connection and encrypts the token with its credential key; the token is never returned.
*
* Requires the integrations:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
put: operations["put_api_v1_fly_connection"];
post?: never;
/**
* Remove the Fly account connection
* @description Owner browser session only. Deletes the tenant's encrypted provisioning token.
*
* Requires the integrations:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
delete: operations["delete_api_v1_fly_connection"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/fly/connection/test": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Validate a Fly organization token
* @description Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org <slug>`. A read-only org token is insufficient for later provisioning. Validation calls Fly's documented read-only current-token endpoint and launches no resources.
*
* Requires the integrations:write scope.
*
* An interactive owner session is required; bearer tokens cannot call this operation.
*/
post: operations["post_api_v1_fly_connection_test"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/integrations/exe": {
parameters: {
query?: never;
Expand Down Expand Up @@ -3823,6 +3887,153 @@ export interface operations {
503: components["responses"]["Error503"];
};
};
get_api_v1_fly_connection: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Connection status */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
connection: {
organizationSlug: string;
organizationName: string;
} | null;
};
};
};
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"];
};
};
put_api_v1_fly_connection: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
token: string;
organizationSlug: string;
};
};
};
responses: {
/** @description Saved connection metadata */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
connection: {
organizationSlug: string;
organizationName: string;
};
};
};
};
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_fly_connection: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Deletion result */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
deleted: boolean;
};
};
};
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_fly_connection_test: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
token: string;
organizationSlug: string;
};
};
};
responses: {
/** @description Validated organization */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @constant */
valid: true;
connection: {
organizationSlug: string;
organizationName: string;
};
};
};
};
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_exe: {
parameters: {
query?: never;
Expand Down
8 changes: 8 additions & 0 deletions packages/api/migrations/0034_fly_connections.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE app.fly_connections (
tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE,
organization_slug text NOT NULL CHECK (organization_slug ~ '^[a-z0-9-]{1,63}$'),
organization_name text NOT NULL CHECK (length(organization_name) BETWEEN 1 AND 120),
encrypted_token text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
21 changes: 21 additions & 0 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { traceReplaySchema } from "./trace-replay-schemas";
import document from "./api-document.json";
import { authInputs, authSuccess, continuationSuccess, connectionStartInput, connectionStartSuccess, connectionResumeInput, loginSuccess, sessionResponse, type AuthAction } from "./auth-api";
import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput } from "./skills";
import { flyConnectionInput, flyConnectionMetadata } from "./fly-account-client";

type JsonSchema = Record<string, any>;
export interface RouteContract {
Expand Down Expand Up @@ -358,6 +359,26 @@ export const API_ROUTES: RouteContract[] = [
},
(service) => service.integrationStatus(),
),
route("GET", "/api/v1/fly/connection", "integrations:read", {
summary: "Read Fly account connection status",
description: "Owner browser session only. Returns organization metadata and never returns the provisioning token.",
responses: { "200": { description: "Connection status", content: { "application/json": { schema: jsonSchema(z.object({ connection: flyConnectionMetadata.nullable() }), "output") } } } },
}, service => service.getFlyConnection(), { ownerSession: true }),
route("POST", "/api/v1/fly/connection/test", "integrations:write", {
summary: "Validate a Fly organization token",
description: "Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org <slug>`. A read-only org token is insufficient for later provisioning. Validation calls Fly's documented read-only current-token endpoint and launches no resources.",
responses: { "200": { description: "Validated organization", content: { "application/json": { schema: jsonSchema(z.object({ valid: z.literal(true), connection: flyConnectionMetadata }), "output") } } } },
}, (service, { body }) => service.validateFlyConnection(body), { body: flyConnectionInput, ownerSession: true }),
route("PUT", "/api/v1/fly/connection", "integrations:write", {
summary: "Save a Fly account connection",
description: "Owner browser session only. Supply an org-scoped Fly deploy token with permission to manage Machines in the selected organization, created with `fly tokens create org --org <slug>`. A read-only org token is insufficient for provisioning. The server validates the connection and encrypts the token with its credential key; the token is never returned.",
responses: { "200": { description: "Saved connection metadata", content: { "application/json": { schema: jsonSchema(z.object({ connection: flyConnectionMetadata }), "output") } } } },
}, (service, { body }) => service.saveFlyConnection(body), { body: flyConnectionInput, ownerSession: true }),
route("DELETE", "/api/v1/fly/connection", "integrations:write", {
summary: "Remove the Fly account connection",
description: "Owner browser session only. Deletes the tenant's encrypted provisioning token.",
responses: { "200": { description: "Deletion result", content: { "application/json": { schema: jsonSchema(z.object({ deleted: z.boolean() }), "output") } } } },
}, service => service.removeFlyConnection(), { ownerSession: true }),
route(
"PUT",
"/api/v1/integrations/exe",
Expand Down
23 changes: 23 additions & 0 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import { SkillRepository, SkillConflict, SkillReferenced } from "./postgres/skil
import { RunRepository } from "./postgres/run-repository";
import { safeDiagnosticText } from "./harness-diagnostics";
import { skillInput, skillUpdateInput, skillPage, skillResponse, skillJobsResponse, previewSkillInput, composePrompt } from "./skills";
import { createFlyAccountClient, FlyAccountError, flyConnectionInput } from "./fly-account-client";
import { FlyConnectionRepository } from "./postgres/fly-connection-repository";

const PROJECT_GRAPH_LABEL_MAX_CHARS = 24;

Expand All @@ -65,6 +67,7 @@ export class ApiService {

private jobs() { return new PostgresJobRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); }
private connections() { return new ConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); }
private flyConnections() { return new FlyConnectionRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); }
private projects() { return new ProjectRepository(databaseFor(this.env), this.auth.tenantId); }
private skills() { return new SkillRepository(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); }
private async executionConfig(id: string) {
Expand Down Expand Up @@ -168,6 +171,26 @@ export class ApiService {


async listExeConnections() { await this.authorize("integrations:read"); return publicValue(z.array(exeConnection), (await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).status()).exeConnections); }
async getFlyConnection() { await this.authorizeOwnerSession("integrations:read"); return { connection: await this.flyConnections().get() }; }
async validateFlyConnection(input: unknown) {
await this.authorizeOwnerSession("integrations:write");
const parsed = flyConnectionInput.parse(input);
try { return { valid: true, connection: await createFlyAccountClient().validate(parsed.token, parsed.organizationSlug) }; }
catch (error) { this.throwFlyAccountError(error); }
}
async saveFlyConnection(input: unknown) {
await this.authorizeOwnerSession("integrations:write");
const parsed = flyConnectionInput.parse(input);
try {
const metadata = await createFlyAccountClient().validate(parsed.token, parsed.organizationSlug);
return { connection: await this.flyConnections().save(metadata, parsed.token) };
} catch (error) { this.throwFlyAccountError(error); }
}
async removeFlyConnection() { await this.authorizeOwnerSession("integrations:write"); return { deleted: await this.flyConnections().remove() }; }
private throwFlyAccountError(error: unknown): never {
if (error instanceof FlyAccountError) throw new ServiceError(error.kind === "auth" ? 401 : error.kind === "organization" ? 400 : 502, error.kind === "auth" ? "fly_auth_failed" : error.kind === "organization" ? "fly_organization_unavailable" : "fly_validation_failed", error.message);
throw error;
}
async listGitHubInstallations() { await this.authorize("integrations:read"); return publicValue(z.array(githubInstallation), JSON.parse(JSON.stringify(await new GitHubRepository(databaseFor(this.env), this.auth.tenantId).installations()))); }
async listTailIntegrations() { await this.authorize("integrations:read"); return publicValue(z.array(tailIntegration), await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails()); }
async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return publicValue(runPageResponse, JSON.parse(JSON.stringify(await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query)))); }
Expand Down
55 changes: 55 additions & 0 deletions packages/api/src/fly-account-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { z } from "zod";

export const flyConnectionInput = z.object({
token: z.string().trim().min(1).max(4096).meta({ writeOnly: true }),
organizationSlug: z.string().trim().min(1).max(63).regex(/^[a-z0-9-]+$/),
}).strict();

export const flyConnectionMetadata = z.object({
organizationSlug: z.string(),
organizationName: z.string(),
});

export class FlyAccountError extends Error {
constructor(readonly kind: "auth" | "organization" | "unavailable" | "invalid_response") {
super(kind === "auth" ? "Fly authentication failed" : kind === "organization" ? "Fly organization is unavailable to this token" : kind === "unavailable" ? "Fly could not validate the account right now" : "Fly returned an invalid account response");
this.name = "FlyAccountError";
}
}

type FlyAccountOptions = { apiOrigin?: string; timeoutMs?: number; fetch?: typeof fetch };

/** Validates an org-scoped Fly token using the documented read-only current-token endpoint. */
export function createFlyAccountClient(options: FlyAccountOptions = {}) {
const origin = (options.apiOrigin ?? "https://api.machines.dev").replace(/\/$/, "");
const timeoutMs = options.timeoutMs ?? 5_000;
const fetchImpl = options.fetch ?? fetch;
return {
async validate(token: string, organizationSlug: string): Promise<{ organizationSlug: string; organizationName: string }> {
let response: Response;
try {
response = await fetchImpl(`${origin}/v1/tokens/current`, {
headers: { authorization: `Bearer ${token}`, accept: "application/json" },
signal: AbortSignal.timeout(timeoutMs),
});
} catch {
throw new FlyAccountError("unavailable");
}
if (response.status === 401 || response.status === 403) {
await response.body?.cancel().catch(() => undefined);
throw new FlyAccountError("auth");
}
if (!response.ok) {
await response.body?.cancel().catch(() => undefined);
throw new FlyAccountError("unavailable");
}
let body: unknown;
try { body = await response.json(); } catch { throw new FlyAccountError("invalid_response"); }
const parsed = z.object({ tokens: z.array(z.object({ org_slug: z.string(), organization: z.string().optional() }).passthrough()) }).safeParse(body);
if (!parsed.success) throw new FlyAccountError("invalid_response");
const organization = parsed.data.tokens.find(item => item.org_slug.toLowerCase() === organizationSlug.toLowerCase());
if (!organization) throw new FlyAccountError("organization");
return { organizationSlug: organization.org_slug, organizationName: organization.organization?.trim() || organization.org_slug };
},
};
}
Loading
Loading