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
23 changes: 23 additions & 0 deletions package-lock.json

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

164 changes: 164 additions & 0 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.

5 changes: 5 additions & 0 deletions packages/api/migrations/0121_ssh_client_identity.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- Keep keys attached to saved clients, independent of provider connection lifecycle.
INSERT INTO app.connections (tenant_id, kind, encrypted_value)
SELECT tenant_id, replace(kind, 'hetzner-client-key:', 'ssh-client-key:'), encrypted_value
FROM app.connections WHERE kind LIKE 'hetzner-client-key:%'
ON CONFLICT (tenant_id, kind) DO NOTHING;
1 change: 1 addition & 0 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"aws4fetch": "1.0.20",
"cron-parser": "^5.10.1",
"drizzle-orm": "^0.45.2",
"edgeport": "1.0.6",
"fast-xml-parser": "5.12.1",
"hono": "^4.11.4",
"json-rules-engine": "^7.3.1",
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/api-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { SshService } from "./ssh/application/ssh-service";
import { HetznerClientKeyService } from "./integrations/application/hetzner-client-key";
import { AwsIntegrationService } from "./integrations/application/aws-service";
import { HetznerSshService } from "./integrations/application/hetzner-ssh";
Expand Down Expand Up @@ -47,6 +48,7 @@ export class ApiService {
get integrations() {
return new IntegrationsService(this.env, this.auth, scope => this.authorize(scope), scope => this.authorizeOwnerSession(scope));
}
get ssh() { return new SshService(this.env, this.auth, scope => this.authorizeOwnerSession(scope)); }
get hetznerKeys() { return new HetznerClientKeyService(this.env, this.auth); }
get hetznerSsh() {
return new HetznerSshService(this.env, this.auth, scope => this.authorizeOwnerSession(scope));
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/cloudflare-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { WorkflowEntrypoint } from "cloudflare:workers";
import type { Env } from "./types";

export { default, AlarmCoordinator } from "./worker";
export { SshExecBroker } from "./ssh/transport/exec-broker";
export { HetznerSshBroker } from "./integrations/providers/hetzner-ssh-broker";

// Preserve the deployed workflow binding while the retirement runs through release.
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/config/bindings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export interface Env {
CLIENT_SSH?: DurableObjectNamespace;
HETZNER_SSH?: DurableObjectNamespace;
SCHEDULER?: DurableObjectNamespace;
ASSETS: Fetcher;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1 @@
import { z } from "zod";
import { decrypt, encrypt } from "../../crypto";
import type { DatabaseClient } from "../../postgres/database";

const keyPair = z.strictObject({ privateKey: z.string().min(1), publicKey: z.string().regex(/^ssh-ed25519 [A-Za-z0-9+/]+=*$/) });
type KeyPair = z.infer<typeof keyPair>;

export class HetznerClientKeyRepository {
constructor(private tenantId: string, private key: string) {}

/** Call while holding the integration topology transaction lock. */
async getOrCreate(sql: DatabaseClient, installationId: string, create: () => KeyPair) {
const kind = "hetzner-client-key:" + installationId;
const { rows } = await sql.query<{encrypted_value: string}>("SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, kind]);
if (rows[0]) return keyPair.parse(JSON.parse(await decrypt(rows[0].encrypted_value, this.key)));
const pair = keyPair.parse(create());
await sql.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,$2,$3)", [this.tenantId, kind, await encrypt(JSON.stringify(pair), this.key)]);
return pair;
}
}
export { SshClientKeyRepository as HetznerClientKeyRepository } from "./ssh-client-key-repository";
28 changes: 28 additions & 0 deletions packages/api/src/credentials/storage/ssh-client-key-repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { z } from "zod";
import { decrypt, encrypt } from "../../crypto";
import type { DatabaseClient } from "../../postgres/database";

const keyPair = z.strictObject({ privateKey: z.string().min(1), publicKey: z.string().regex(/^ssh-ed25519 [A-Za-z0-9+/]+=*$/) });
type KeyPair = z.infer<typeof keyPair>;

export class SshClientKeyRepository {
constructor(private tenantId: string, private key: string) {}

async get(sql: DatabaseClient, installationId: string) {
const kind = "ssh-client-key:" + installationId;
const { rows } = await sql.query<{encrypted_value: string}>(
"SELECT encrypted_value FROM app.connections WHERE tenant_id=$1 AND kind=$2", [this.tenantId, kind],
);
return rows[0] ? keyPair.parse(JSON.parse(await decrypt(rows[0].encrypted_value, this.key))) : null;
}

/** Call while holding the integration topology transaction lock. */
async getOrCreate(sql: DatabaseClient, installationId: string, create: () => KeyPair) {
const kind = "ssh-client-key:" + installationId;
const existing = await this.get(sql, installationId);
if (existing) return existing;
const pair = keyPair.parse(create());
await sql.query("INSERT INTO app.connections(tenant_id,kind,encrypted_value) VALUES($1,$2,$3)", [this.tenantId, kind, await encrypt(JSON.stringify(pair), this.key)]);
return pair;
}
}
2 changes: 2 additions & 0 deletions packages/api/src/integrations/api/rest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { awsRoutes } from "./aws-rest";
import { sshTargetRoutes } from "../../ssh/api/rest";
import { hetznerSshRoutes } from "./hetzner-ssh-rest";
import { hetznerConnectionInput, hetznerConnectionMetadata, hetznerInventory } from "./hetzner-contracts";
import { integrationRemovalConfirmation, integrationRemovalPreview, integrationRemovalTarget } from "../../integrations/api/integration-removal-contracts";
Expand Down Expand Up @@ -59,6 +60,7 @@ const bearerIntegrationWriteResult = z.object({ revision: z.number().int().nonne
const bearerIntegrationDeleteResult = z.object({ id: z.uuid(), deleted: z.literal(true), revision: z.number().int().nonnegative(), duplicate: z.boolean() });
export const integrationRoutes = [
...hetznerSshRoutes,
...sshTargetRoutes,
...awsRoutes,
route("POST", "/api/v1/integrations/removal/preview", "integrations:write", {
summary: "Preview what deleting one installed integration affects",
Expand Down
23 changes: 23 additions & 0 deletions packages/api/src/ssh/api/contracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { z } from "zod";
import { isPublicAddress } from "../../proxy/transport/public-address";

export const sshTargetInput = z.strictObject({
name: z.string().trim().min(1).max(96),
address: z.string().max(45).refine(address => !address.includes("%") && isPublicAddress(address), "Use a public IP address."),
username: z.string().regex(/^[a-z_][a-z0-9_-]{0,31}$/).refine(username => username !== "root", "Use a non-root account."),
hostFingerprint: z.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
});
export const sshTarget = sshTargetInput.extend({ id: z.uuid() });
export const sshExecInput = z.strictObject({ targetId: z.uuid(), command: z.string().min(1).max(4096).refine(command => !command.includes("\0")) });
export const sshExecResult = z.strictObject({
stdout: z.string(), stderr: z.string(), exitCode: z.number().int().nullable(),
signal: z.string().nullable(), reusedConnection: z.boolean(), truncated: z.boolean(),
});
export type SshTarget = z.infer<typeof sshTarget>;
export const sshClientAuthority = z.strictObject({
tenantId: z.uuid(), userId: z.uuid(), sessionVersion: z.number().int().positive(),
oauthInstallationId: z.string().min(1).max(512), oauthClientId: z.string().min(1).max(512).optional(),
oauthGrantId: z.string().min(1).max(512), oauthExpiresAt: z.number().finite().positive(),
});
export const sshBrokerRequest = sshExecInput.extend({ authority: sshClientAuthority });
export type SshClientAuthority = z.infer<typeof sshClientAuthority>;
10 changes: 10 additions & 0 deletions packages/api/src/ssh/api/mcp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { z } from "zod";
import { mcpTool } from "../../transport/mcp/tool";
import { sshExecInput } from "./contracts";

export const sshTools = [
mcpTool(null, "get_ssh_public_key", "Get the public SSH key of this saved Factorize client. Install it on a server account to grant that key access. The private key is never returned.",
z.strictObject({}), service => () => service.ssh.publicKey()),
mcpTool<z.infer<typeof sshExecInput>>(null, "ssh_exec", "Run one non-interactive SSH command on a saved target. The server decides if this client's key is authorized. Each call opens a fresh command channel, possibly on a warm connection. Do not retry a timed-out command blindly.",
sshExecInput, service => input => service.ssh.exec(input)),
];
20 changes: 20 additions & 0 deletions packages/api/src/ssh/api/rest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { z } from "zod";
import { jsonSchema, route } from "../../transport/rest/route-contract";
import { sshTarget, sshTargetInput } from "./contracts";

const ok = (description: string, schema: z.ZodType) => ({
"200": { description, content: { "application/json": { schema: jsonSchema(schema, "output") } } },
});
export const sshTargetRoutes = [
route("GET", "/api/v1/ssh/targets", "integrations:read", {
summary: "List saved SSH target identities", responses: ok("Targets", z.object({ targets: z.array(sshTarget) })),
}, service => service.ssh.listTargets(), { ownerSession: true }),
route("POST", "/api/v1/ssh/targets", "integrations:write", {
summary: "Save an independently verified SSH target identity", responses: ok("Target", sshTarget),
}, (service, { body }) => service.ssh.addTarget(body), { ownerSession: true, body: sshTargetInput, maxBodyBytes: 4096 }),
route("DELETE", "/api/v1/ssh/targets/{targetId}", "integrations:write", {
summary: "Remove a saved SSH target", responses: ok("Removal", z.object({ deleted: z.boolean() })),
}, (service, { params }) => service.ssh.removeTarget(params.targetId), { ownerSession: true,
parameters: z.object({ targetId: z.uuid() }),
}),
];
Loading
Loading