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
162 changes: 162 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.

Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ export class HetznerConnectionRepository {
}

private async clearSshCredentials(client: DatabaseClient) {
await client.query("DELETE FROM app.connections WHERE tenant_id=$1 AND (kind LIKE 'hetzner-ssh:%' OR kind LIKE 'hetzner-client-key:%')", [this.tenantId]);
await client.query("DELETE FROM app.connections WHERE tenant_id=$1 AND (kind LIKE 'hetzner-ssh:%' OR kind LIKE 'hetzner-client-key:%' OR kind LIKE 'hetzner-command-ssh:%')", [this.tenantId]);
}
}
19 changes: 15 additions & 4 deletions packages/api/src/ssh/api/contracts.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import { z } from "zod";
import { isPublicAddress } from "../../proxy/transport/public-address";

const target = {
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 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}$/),
...target,
});
export const hetznerSshPinInput = z.strictObject(target);
export const hetznerSshServerId = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
export const hetznerSshPin = hetznerSshPinInput.extend({ serverId: hetznerSshServerId, revision: z.uuid(), projectRevision: z.uuid(), needsVerification: z.boolean().default(false) });
export const publicHetznerSshPin = hetznerSshPin.omit({ revision: true, projectRevision: true }).strip();
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")) });
const execFields = z.strictObject({ targetId: z.uuid().optional(), hetznerServerId: hetznerSshServerId.optional(), command: z.string().min(1).max(4096).refine(command => !command.includes("\0")) });
const oneSelector = (value: { targetId?: string; hetznerServerId?: number }) =>
(value.targetId !== undefined) !== (value.hetznerServerId !== undefined);
export const sshExecInput = execFields.refine(oneSelector, "Supply either targetId or hetznerServerId.");
export const sshRoutingTarget = (value: z.infer<typeof sshExecInput>) => value.targetId ?? "hetzner:" + value.hetznerServerId;
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(),
Expand All @@ -19,5 +30,5 @@ export const sshClientAuthority = z.strictObject({
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 const sshBrokerRequest = execFields.extend({ authority: sshClientAuthority }).refine(oneSelector);
export type SshClientAuthority = z.infer<typeof sshClientAuthority>;
2 changes: 1 addition & 1 deletion packages/api/src/ssh/api/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ 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.",
mcpTool<z.infer<typeof sshExecInput>>(null, "ssh_exec", "Run one non-interactive SSH command. Supply a saved targetId or a hetznerServerId from the native Hetzner server list. The Hetzner server must have a verified host fingerprint. 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)),
];
14 changes: 13 additions & 1 deletion packages/api/src/ssh/api/rest.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import { z } from "zod";
import { jsonSchema, route } from "../../transport/rest/route-contract";
import { sshTarget, sshTargetInput } from "./contracts";
import { hetznerSshPinInput, hetznerSshServerId, publicHetznerSshPin, sshTarget, sshTargetInput } from "./contracts";

const ok = (description: string, schema: z.ZodType) => ({
"200": { description, content: { "application/json": { schema: jsonSchema(schema, "output") } } },
});
const serverParameters = z.object({ serverId: z.string().regex(/^[1-9][0-9]*$/).refine(value => hetznerSshServerId.safeParse(Number(value)).success) });
export const sshTargetRoutes = [
route("GET", "/api/v1/ssh/hetzner-targets", "integrations:read", {
summary: "List verified SSH identities for the connected Hetzner project", responses: ok("Targets", z.object({ targets: z.array(publicHetznerSshPin) })),
}, service => service.ssh.listHetznerPins(), { ownerSession: true }),
route("PUT", "/api/v1/ssh/hetzner-targets/{serverId}", "integrations:write", {
summary: "Save an independently verified Hetzner SSH fingerprint", responses: ok("Target", publicHetznerSshPin),
}, (service, { params, body }) => service.ssh.saveHetznerPin(Number(params.serverId), body),
{ ownerSession: true, parameters: serverParameters, body: hetznerSshPinInput, maxBodyBytes: 4096 }),
route("DELETE", "/api/v1/ssh/hetzner-targets/{serverId}", "integrations:write", {
summary: "Remove a saved Hetzner SSH fingerprint", responses: ok("Removal", z.object({ deleted: z.boolean() })),
}, (service, { params }) => service.ssh.removeHetznerPin(Number(params.serverId)),
{ ownerSession: true, parameters: serverParameters }),
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 }),
Expand Down
56 changes: 56 additions & 0 deletions packages/api/src/ssh/application/hetzner-target.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { signingConfig } from "../../config/runtime";
import { HetznerConnectionRepository } from "../../credentials/storage/hetzner-connection-repository";
import { activeHetznerScope } from "../../integrations/application/hetzner-access";
import { HetznerInventoryService } from "../../integrations/application/hetzner-inventory";
import { lockIntegrationTopology } from "../../integrations/storage/integration-removal-topology";
import { databaseFor, type DatabaseClient } from "../../postgres/database";
import { isPublicAddress } from "../../proxy/transport/public-address";
import { ServiceError } from "../../service-contract";
import type { Env } from "../../types";
import type { SshClientAuthority } from "../api/contracts";
import { HetznerSshPinRepository } from "../storage/hetzner-pin-repository";

export function hetznerSshContext(env: Env, identity: { tenantId: string; userId: string }, sql?: DatabaseClient) {
const database = databaseFor(env), key = signingConfig(env).credentialKey;
const connections = new HetznerConnectionRepository(database, identity.tenantId, key);
return {
connections,
inventory: new HetznerInventoryService(connections),
pins: new HetznerSshPinRepository(sql ?? database.pool, identity.tenantId, identity.userId, key),
};
}

export function hetznerSshAllowed(db: DatabaseClient, caller: SshClientAuthority) {
return activeHetznerScope(db, { tenantId: caller.tenantId, userId: caller.userId, sessionVersion: caller.sessionVersion,
installationId: caller.oauthInstallationId, grantId: caller.oauthGrantId, expiresAt: caller.oauthExpiresAt });
}

export async function resolveHetznerSshTarget(env: Env, caller: SshClientAuthority, serverId: number) {
const db = databaseFor(env).pool, { connections, inventory, pins } = hetznerSshContext(env, caller, db);
if (!await hetznerSshAllowed(db, caller)) throw new ServiceError(403, "hetzner_ssh_access_denied", "This client does not have access to the connected Hetzner project.");
const pin = await pins.get(serverId);
const project = await connections.get();
if (!pin || pin.needsVerification || pin.projectRevision !== project?.revision) throw new ServiceError(412, "ssh_host_unverified", "Verify this server's SSH host fingerprint in Factorize before connecting.");
const server = await inventory.targetForServer(serverId);
if (!isPublicAddress(server.ipv4) || server.connectionRevision !== pin.projectRevision) {
throw new ServiceError(412, "ssh_host_unverified", "Recheck this server's SSH host identity before connecting.");
}
return {
target: { id: pin.revision, name: "Hetzner " + serverId, address: server.ipv4, username: pin.username, hostFingerprint: pin.hostFingerprint },
markMismatch: async () => {
const database = databaseFor(env);
await database.transaction(async sql => {
await lockIntegrationTopology(sql, caller.tenantId);
const scoped = hetznerSshContext(env, caller, sql).pins;
const latest = await scoped.get(serverId);
if (latest?.revision === pin.revision && !latest.needsVerification) {
await scoped.save({ ...latest, needsVerification: true });
}
});
},
current: async () => {
const [scope, latest, active] = await Promise.all([hetznerSshAllowed(db, caller), pins.get(serverId), connections.get()]);
return Boolean(scope && latest?.revision === pin.revision && !latest.needsVerification && active?.revision === pin.projectRevision);
},
};
}
Loading
Loading