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
5 changes: 1 addition & 4 deletions packages/api-client/src/schema.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export class AccessControlService {
const globallyAvailable = [...AGENT_SCOPES, ...integrations.filter(row => row.available && row.policy !== "disabled").map(row => row.requiredScope)];
const liveScopes = new Set(integrations.filter(row => row.kind === "hetzner" && row.available && row.policy !== "disabled").map(row => row.requiredScope));
const scopeLabels = Object.fromEntries(integrations.map(row => [row.requiredScope,
row.kind === "hetzner" ? "Hetzner Cloud (native API and enrolled SSH)" : `${row.name} integration access`]));
row.kind === "hetzner" ? "Hetzner Cloud (native API and enrolled SSH; a Read & Write token allows changes, deletions, and charges)" : `${row.name} integration access`]));
return publicValue(z.array(authorizedClient), rows.map(row => {
const appName = byId.get(row.client_id)?.clientName ?? row.client_id;
const inactive = (row.active_expires_at !== null && row.active_expires_at.getTime() <= Date.now()) || row.active_session_version !== this.auth.sessionVersion;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { FlyConnectionRepository } from "../storage/fly-connection-repository";
import { isPublicHttpsOrigin } from "../../proxy/transport/public-address";

/** Only call after shared identity/grant authorization. No caller origin or secret. */
export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string, method: string): Promise<OutboundCredential | null> {
export async function resolveAgentCredential(env: Env, tenantId: string, kind: string, credentialId: string, relativePath: string): Promise<OutboundCredential | null> {
if (kind === "cloudflare") return cloudflareCredential(env, tenantId, credentialId, relativePath);
const database = databaseFor(env);
if (kind === "hetzner") {
Expand All @@ -29,9 +29,6 @@ export async function resolveAgentCredential(env: Env, tenantId: string, kind: s
}
const project = await new HetznerConnectionRepository(database, tenantId, signingConfig(env).credentialKey).get();
if (!project) return null;
if (method !== "GET" && method !== "HEAD" && project.nativeWritesEnabled !== true) {
throw new AgentApiError(403, "hetzner_native_writes_disabled", "The owner has not enabled native Hetzner Cloud API writes.");
}
return { origin, path: target.pathname + target.search, credential: project.token,
requestHeaders: ["accept", "content-type", "if-match", "if-none-match"] };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { decrypt, encrypt } from "../../crypto";
import { lockIntegrationTopology } from "../../integrations/storage/integration-removal-topology";
import type { Database, DatabaseClient } from "../../postgres/database";

export type HetznerProject = { name: string; token: string; revision: string; nativeWritesEnabled?: boolean };
export type HetznerProject = { name: string; token: string; revision: string };

export class HetznerConnectionRepository {
constructor(private database: Database, private tenantId: string, private encryptionKey: string) {
Expand All @@ -16,8 +16,8 @@ export class HetznerConnectionRepository {
return rows[0] ? JSON.parse(await decrypt(rows[0].encrypted_value, this.encryptionKey)) as HetznerProject : null;
}

async save(name: string, token: string, nativeWritesEnabled = false) {
const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID(), nativeWritesEnabled }), this.encryptionKey);
async save(name: string, token: string) {
const value = await encrypt(JSON.stringify({ name, token, revision: crypto.randomUUID() }), this.encryptionKey);
await this.database.transaction(async client => {
await lockIntegrationTopology(client, this.tenantId);
const hadProject = Boolean(await this.get(client));
Expand All @@ -26,7 +26,7 @@ export class HetznerConnectionRepository {
`INSERT INTO app.connections (tenant_id,kind,encrypted_value) VALUES ($1,'hetzner',$2)
ON CONFLICT (tenant_id,kind) DO UPDATE SET encrypted_value=excluded.encrypted_value,updated_at=now()`,
[this.tenantId, value]);
// Existing grants never cross a project/token replacement or gain new provisioning power.
// Existing grants never cross a project/token replacement.
if (hadProject) await client.query(
"UPDATE app.agent_integrations SET epoch=epoch+1,revision=revision+1 WHERE tenant_id=$1 AND kind='hetzner' AND credential_id='hetzner'",
[this.tenantId]);
Expand Down
3 changes: 1 addition & 2 deletions packages/api/src/integrations/api/hetzner-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import { z } from "zod";

export const hetznerConnectionInput = z.strictObject({
name: z.string().trim().min(1).max(120),
nativeWritesEnabled: z.boolean().optional(),
token: z.string().trim().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/).meta({ writeOnly: true }),
});
export const hetznerConnectionMetadata = z.object({ name: z.string(), nativeWritesEnabled: z.boolean().optional() });
export const hetznerConnectionMetadata = z.object({ name: z.string() });
export const hetznerServer = z.object({
id: z.number().int().positive(),
name: z.string().min(1).max(255),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/integrations/api/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export const integrationRoutes = [
}, service => service.integrations.getHetznerConnection(), { ownerSession: true }),
route("PUT", "/api/v1/hetzner/connection", "integrations:write", {
summary: "Save a Hetzner Cloud project connection",
description: "Owner browser session only. Supply a project API token with Read permission, or Read & Write only when explicitly enabling native API writes through the proxy. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources.",
description: "Owner browser session only. Choose Read to limit checked clients to reads or Read & Write to allow native changes, deletions, and billable resources. Factorize verifies that it can list servers and stores it encrypted; saving does not change provider resources.",
responses: { "200": { description: "Saved connection metadata", content: { "application/json": { schema: jsonSchema(z.object({ connection: hetznerConnectionMetadata }), "output") } } } },
}, (service, { body }) => service.integrations.saveHetznerConnection(body), { body: hetznerConnectionInput, ownerSession: true, maxBodyBytes: 4096 }),
route("DELETE", "/api/v1/hetzner/connection", "integrations:write", {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ export class HetznerInventoryService {

async connection() {
const project = await this.connections.get();
return { connection: project ? { name: project.name, ...(project.nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } : null };
return { connection: project ? { name: project.name } : null };
}

async connectionRevision() { return (await this.connections.get())?.revision ?? null; }

async save(input: unknown) {
const { name, token, nativeWritesEnabled = false } = hetznerConnectionInput.parse(input);
const { name, token } = hetznerConnectionInput.parse(input);
await this.withProviderError("validate_token", () => createHetznerCloudClient().validate(token));
await this.connections.save(name, token, nativeWritesEnabled);
return { connection: { name, ...(nativeWritesEnabled ? { nativeWritesEnabled: true } : {}) } };
await this.connections.save(name, token);
return { connection: { name } };
}

async delete() { return { deleted: await this.connections.delete() }; }
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/proxy/application/agent-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import type { z } from "zod";
const STORAGE_BLOCK_BYTES = proxyLimits.artifactBlockBytes;
const forbidden = () => new AgentApiError(403, "forbidden", "This integration is not authorized.");
const invalidIdentity = () => new AgentApiError(401, "invalid_token", "The agent authorization is no longer active.");
const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.kind === "hetzner" ? "Native Hetzner Cloud project API, with owner-controlled write access." : row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) });
const publicIntegration = (row: AgentIntegration) => ({ id: row.id, kind: row.kind, credentialId: row.credential_id, name: row.name, description: row.kind === "hetzner" ? "Native Hetzner Cloud project API, bounded by the project token’s permissions." : row.description, available: row.available, policy: row.policy, revision: row.revision, requiredScope: requiredIntegrationScope(row) });

/** These are structural checks only: reflection never refreshes/decrypts secrets. */
export async function integrationConsentLabels(env: Env, tenantId: string, scopes: string[]) {
Expand Down Expand Up @@ -110,7 +110,7 @@ export class AgentApiService {
const path = row.kind === "linear" ? "/graphql" : row.kind === "x" ? "/2/users/me" : row.kind === "cloudflare" ? "/zones" : row.kind === "fly" ? "/v1/apps" : row.kind === "hetzner" ? "/v1/servers" : row.kind === "exe" ? "/exec" : "/";
const method = row.kind === "linear" || row.kind === "exe" ? "POST" : "GET";
const requestExample = {integration:row.id,method,path,...(row.kind === "linear" ? {headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"query { viewer { id name } }"})} : row.kind === "exe" ? {headers:{"Content-Type":"text/plain"},body:"help"} : {})};
result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use paths relative to the Cloudflare v4 REST API. Cloudflare enforces the accounts and permissions authorized on its consent screen." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "hetzner" ? "Use native Hetzner Cloud /v1 paths, methods, query and body. Reads require the owner’s Hetzner grant. Mutating methods also require explicit native writes enablement and a Read & Write project token." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")});
result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use paths relative to the Cloudflare v4 REST API. Cloudflare enforces the accounts and permissions authorized on its consent screen." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "hetzner" ? "Use native Hetzner Cloud /v1 paths, methods, query and body. The owner’s Hetzner checkbox grants access to the project API. Hetzner enforces the token’s permissions; a Read & Write token permits changes, deletions, and billable resources." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")});
}
return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(identity.scopes).filter(scope => !identity.policy.disabled_scopes.includes(scope)), proxy: {
requestUrl: appConfig(this.env).origin + "/api/v1/agent/requests",
Expand All @@ -126,8 +126,8 @@ export class AgentApiService {
forward(integration: string, path: string, request: Request, expectedOperationEpoch?: number) {
return this.egress().forward(integration, path, request, expectedOperationEpoch);
}
assertRequest(integration: AgentIntegration, path: string, method: string) {
return this.egress().assertRequest(integration, path, method);
assertRequest(integration: AgentIntegration, path: string) {
return this.egress().assertRequest(integration, path);
}
forwardX(connectionId: string, path: string, request: Request) {
return this.egress().forwardX(connectionId, path, request);
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/proxy/application/proxy-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class ProxyOperations {
const parsed=requestApiInput.parse(input),api=this.api();
if(this.auth.authMethod==="oauth"&&!this.auth.scopes.includes("proxy:use"))throw new AgentApiError(403,"insufficient_scope","Renew consent with proxy:use before requesting integrations.","proxy:use");
const {identity,integration}=await api.authorize(parsed.integration);
await api.assertRequest(integration, parsed.path, parsed.method);
await api.assertRequest(integration, parsed.path);
if(!this.env.PROXY_ARTIFACTS || !this.env.SCHEDULER)throw new AgentApiError(503,"proxy_unavailable","Durable proxy storage/scheduling is unavailable.");
const size=parsed.body===undefined?0:Buffer.byteLength(parsed.body,parsed.encoding==="base64"?"base64":"utf8");
if(size>proxyLimits.requestBytes)throw new AgentApiError(413,"request_too_large","Request exceeds the fixed 32 MiB limit.");
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/proxy/transport/credential-backed-egress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,17 @@ export class CredentialBackedEgress {
) {}

/** Deny a locally prohibited Hetzner request before it creates an async receipt. */
async assertRequest(integration: AgentIntegration, path: string, method: string) {
async assertRequest(integration: AgentIntegration, path: string) {
if (integration.kind === "hetzner" && !await resolveAgentCredential(this.env, this.tenantId,
integration.kind, integration.credential_id, path, method)) throw forbidden();
integration.kind, integration.credential_id, path)) throw forbidden();
}

async forward(integration: string, path: string, request: Request, expectedOperationEpoch?: number) {
const grant = await this.authorize(integration);
if (expectedOperationEpoch !== undefined && grant.integration.operation_epoch !== expectedOperationEpoch) throw forbidden();
if (grant.integration.kind === "x") return this.forwardX(grant.integration.credential_id, path, request, expectedOperationEpoch);
let credential;
try { credential = await resolveAgentCredential(this.env, this.tenantId, grant.integration.kind, grant.integration.credential_id, path, request.method); }
try { credential = await resolveAgentCredential(this.env, this.tenantId, grant.integration.kind, grant.integration.credential_id, path); }
catch (error) {
if (error instanceof AgentApiError) throw error;
throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved.");
Expand Down
Loading
Loading