-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathroute.ts
More file actions
299 lines (268 loc) · 9.72 KB
/
route.ts
File metadata and controls
299 lines (268 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import { type NextRequest, NextResponse } from "next/server";
import crypto from "node:crypto";
import { execSync } from "node:child_process";
import { writeFileSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { authenticateRequest } from "@/lib/auth";
import { getPool } from "@/lib/db";
import { flyctlSync } from "@/lib/flyctl";
import { createMachine, type CreateMachineConfig } from "@/lib/fly";
/**
* Generate an Ed25519 SSH keypair using Node.js crypto.
* Returns the public key in OpenSSH authorized_keys format
* and the private key in OpenSSH format (BEGIN OPENSSH PRIVATE KEY).
*
* PKCS8 PEM (BEGIN PRIVATE KEY) is NOT used because macOS's SSH client
* doesn't support it for Ed25519 keys.
*/
function generateSSHKeypair(): { publicKey: string; privateKey: string } {
const keypair = crypto.generateKeyPairSync("ed25519");
// Extract raw 32-byte keys from DER encoding
const spkiDer = keypair.publicKey.export({ type: "spki", format: "der" }) as Buffer;
const rawPub = spkiDer.subarray(12); // Ed25519 SPKI DER: 12-byte header + 32-byte key
const pkcs8Der = keypair.privateKey.export({ type: "pkcs8", format: "der" }) as Buffer;
const rawSeed = pkcs8Der.subarray(16); // Ed25519 PKCS8 DER: 16-byte header + 32-byte seed
// Helper: write an SSH wire-format string (uint32 length prefix + data)
const sshString = (data: Buffer): Buffer => {
const buf = Buffer.alloc(4 + data.length);
buf.writeUInt32BE(data.length, 0);
data.copy(buf, 4);
return buf;
};
const sshUint32 = (n: number): Buffer => {
const buf = Buffer.alloc(4);
buf.writeUInt32BE(n, 0);
return buf;
};
const keyTypeStr = Buffer.from("ssh-ed25519");
// Public key in OpenSSH wire format
const pubWire = Buffer.concat([sshString(keyTypeStr), sshString(rawPub)]);
const publicKey = `ssh-ed25519 ${pubWire.toString("base64")}`;
// Private key in OpenSSH format
const checkInt = crypto.randomBytes(4);
const privSection = Buffer.concat([
checkInt, // checkint1
checkInt, // checkint2 (must match)
sshString(keyTypeStr), // key type
sshString(rawPub), // public key (32 bytes)
sshString(Buffer.concat([rawSeed, rawPub])), // private key (64 bytes: seed + pub)
sshString(Buffer.alloc(0)), // comment (empty)
]);
// Pad to cipher block size (8 for "none")
const padLen = (8 - (privSection.length % 8)) % 8;
const padding = Buffer.from(Array.from({ length: padLen }, (_, i) => i + 1));
const none = Buffer.from("none");
const fullKey = Buffer.concat([
Buffer.from("openssh-key-v1\0"), // magic
sshString(none), // ciphername
sshString(none), // kdfname
sshString(Buffer.alloc(0)), // kdfoptions
sshUint32(1), // number of keys
sshString(pubWire), // public key
sshString(Buffer.concat([privSection, padding])), // private section
]);
// Wrap base64 to 70-char lines
const b64Lines = fullKey.toString("base64").match(/.{1,70}/g) ?? [];
const privateKey = [
"-----BEGIN OPENSSH PRIVATE KEY-----",
...b64Lines,
"-----END OPENSSH PRIVATE KEY-----",
"",
].join("\n");
return { publicKey, privateKey };
}
const FLY_ORG = process.env.FLY_ORG ?? "tiger-data";
const FLY_REGION = process.env.FLY_REGION ?? "iad";
const CLOUD_DEV_IMAGE =
process.env.CLOUD_DEV_IMAGE ?? "registry.fly.io/opflow-cloud-dev-image:latest";
/**
* POST /api/cloud-dev/create
* Create a cloud dev machine for the authenticated user.
*/
export async function POST(req: NextRequest) {
const auth = await authenticateRequest(req);
if (auth instanceof NextResponse) return auth;
const { userId } = auth;
try {
const body = (await req.json()) as {
appName?: string;
envVars?: Record<string, string>;
};
if (!body.appName) {
return NextResponse.json(
{ error: "appName is required" },
{ status: 400 },
);
}
const { appName, envVars = {} } = body;
const db = await getPool();
// Check for existing machine with this app name
const existing = await db.query(
`SELECT dm.fly_app_name, dm.app_url
FROM dev_machines dm
JOIN dev_machine_members dmm ON dm.id = dmm.machine_id
WHERE dmm.user_id = $1 AND dm.app_name = $2`,
[userId, appName],
);
if (existing.rows.length > 0) {
return NextResponse.json({
data: {
appUrl: existing.rows[0].app_url as string,
},
});
}
// Generate unpredictable Fly app name
const hexId = crypto.randomBytes(4).toString("hex");
const flyAppName = `opflow-dev-${hexId}`;
const appUrl = `https://${flyAppName}.fly.dev`;
const linuxUser = `user-${userId.replace(/[^a-zA-Z0-9]/g, "").slice(0, 16)}`;
// Generate SSH keypair for remote access
const sshKeypair = generateSSHKeypair();
console.log(`[cloud-dev/create] Creating Fly app: ${flyAppName}`);
// 1. Create Fly app
flyctlSync(["apps", "create", flyAppName, "--org", FLY_ORG]);
// 2. Create Fly volume
let volumeId: string;
try {
const volOutput = flyctlSync([
"volumes",
"create",
"app_data",
"-s",
"10",
"-r",
FLY_REGION,
"-a",
flyAppName,
"-y",
"-j",
]);
const volData = JSON.parse(volOutput) as { id?: string };
volumeId = volData.id ?? "";
if (!volumeId) {
throw new Error(`No volume ID in response: ${volOutput}`);
}
} catch (err) {
// Clean up Fly app on volume creation failure
try {
flyctlSync(["apps", "destroy", flyAppName, "-y"]);
} catch { /* ignore cleanup errors */ }
throw err;
}
// 3. Allocate dedicated IPv4 (required for raw TCP services like SSH;
// shared IPv4 only supports HTTP/TLS via Fly's Anycast proxy)
try {
flyctlSync(["ips", "allocate-v4", "-a", flyAppName, "-y"]);
} catch (err) {
// Clean up Fly app — without an IP the machine is unreachable
console.error(
`[cloud-dev/create] IPv4 allocation failed: ${err instanceof Error ? err.message : String(err)}`,
);
try {
flyctlSync(["apps", "destroy", flyAppName, "-y"]);
} catch { /* ignore cleanup errors */ }
throw new Error(`IPv4 allocation failed — machine would be unreachable`);
}
// 4. Insert into dev_machines + dev_machine_members (before secrets so we can include WORKSPACE_ID)
const insertResult = await db.query(
`INSERT INTO dev_machines (app_name, fly_app_name, app_url, created_by, ssh_private_key)
VALUES ($1, $2, $3, $4, $5)
RETURNING id`,
[appName, flyAppName, appUrl, userId, sshKeypair.privateKey],
);
const machineDbId = insertResult.rows[0].id as number;
await db.query(
`INSERT INTO dev_machine_members (machine_id, user_id, role, linux_user)
VALUES ($1, $2, 'owner', $3)`,
[machineDbId, userId, linuxUser],
);
// 5. Set secrets (env vars) — staged so they apply when machine starts
const secrets: Record<string, string> = {
...envVars,
APP_NAME: appName,
DEV_USER: linuxUser,
SSH_PUBLIC_KEY: sshKeypair.publicKey,
WORKSPACE_ID: String(machineDbId),
};
// Inject auth-server's public URL so the cloud machine calls back to us
if (process.env.PUBLIC_URL) {
secrets.OPFLOW_SERVER_URL = process.env.PUBLIC_URL;
}
const secretsFile = join(tmpdir(), `secrets-${flyAppName}.env`);
const secretsContent = Object.entries(secrets)
.map(([k, v]) => `${k}=${v}`)
.join("\n");
writeFileSync(secretsFile, secretsContent);
try {
execSync(
`flyctl secrets import -a ${flyAppName} --stage < ${secretsFile}`,
{
env: { ...process.env, FLY_API_TOKEN: process.env.FLY_API_TOKEN },
stdio: "pipe",
timeout: 15000,
shell: "/bin/bash",
},
);
} catch (err) {
console.log(
`[cloud-dev/create] Secrets import warning: ${err instanceof Error ? err.message : String(err)}`,
);
} finally {
try { unlinkSync(secretsFile); } catch { /* ignore */ }
}
// 6. Create machine via Fly Machines API
const machineConfig: CreateMachineConfig = {
image: CLOUD_DEV_IMAGE,
services: [
{
ports: [
{ port: 443, handlers: ["tls", "http"] },
{ port: 80, handlers: ["http"] },
],
protocol: "tcp",
internal_port: 4173,
autostop: "stop",
autostart: true,
min_machines_running: 0,
},
{
ports: [{ port: 2222, handlers: [] }],
protocol: "tcp",
internal_port: 2222,
autostop: "stop",
autostart: true,
min_machines_running: 0,
},
],
guest: {
cpu_kind: "shared",
cpus: 2,
memory_mb: 2048,
},
mounts: [
{
volume: volumeId,
path: "/data",
},
],
};
const machine = await createMachine(flyAppName, machineConfig);
console.log(
`[cloud-dev/create] Machine created: ${machine.id} for ${flyAppName}`,
);
return NextResponse.json({
data: { appUrl, flyAppName, sshPrivateKey: sshKeypair.privateKey },
});
} catch (err) {
console.error(
`[cloud-dev/create] Error: ${err instanceof Error ? err.message : String(err)}`,
);
return NextResponse.json(
{
error: `Create failed: ${err instanceof Error ? err.message : String(err)}`,
},
{ status: 500 },
);
}
}