-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathcodespace-store.ts
More file actions
674 lines (587 loc) · 23.1 KB
/
Copy pathcodespace-store.ts
File metadata and controls
674 lines (587 loc) · 23.1 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
import { DurableObject } from "cloudflare:workers";
interface CodespaceCredentials {
githubToken: string;
githubUser: string;
codespaceName: string;
githubRepository?: string;
githubOrg?: string;
githubRepo?: string;
createdAt: number;
updatedAt: number;
status?: "available" | "unavailable";
lastHealthCheck?: number;
lastError?: string;
}
interface StoredCodespaceCredentials {
keyId: number | null;
salt: string | null;
iv: string | null;
encryptedData: string | null;
createdAt: number;
updatedAt: number;
}
export class CodespaceStore extends DurableObject<Record<string, any>> {
private sql: SqlStorage;
private keys: Map<number, CryptoKey> = new Map();
private currentKeyId: number = 0;
private initialized = false;
constructor(ctx: DurableObjectState, env: Record<string, any>) {
super(ctx, env);
this.sql = ctx.storage.sql;
// Initialize database schema
this.sql.exec(`
CREATE TABLE IF NOT EXISTS codespace_credentials (
codespace_name TEXT PRIMARY KEY,
github_user TEXT NOT NULL,
key_id INTEGER,
salt TEXT,
iv TEXT,
encrypted_data TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_github_user ON codespace_credentials(github_user);
CREATE INDEX IF NOT EXISTS idx_created_at ON codespace_credentials(created_at);
CREATE INDEX IF NOT EXISTS idx_updated_at ON codespace_credentials(updated_at);
`);
// Migration: Add github_repository column if it doesn't exist
try {
// Try to add the column - will fail silently if it already exists
this.sql.exec(`
ALTER TABLE codespace_credentials ADD COLUMN github_repository TEXT;
`);
} catch (_error) {
// Column already exists or other error - safe to ignore
// SQLite will throw if column already exists
}
// Migration: Add status tracking columns if they don't exist
try {
this.sql.exec(`
ALTER TABLE codespace_credentials ADD COLUMN status TEXT DEFAULT 'available';
ALTER TABLE codespace_credentials ADD COLUMN last_health_check INTEGER;
ALTER TABLE codespace_credentials ADD COLUMN last_error TEXT;
`);
} catch (_error) {
// Columns already exist or other error - safe to ignore
}
}
private async initKeys() {
if (this.initialized) return;
// Import encryption keys from environment - reuse the same key system as sessions
const keyConfigs = [
{ id: 2, env: "CATNIP_ENCRYPTION_KEY_V2" },
{ id: 1, env: "CATNIP_ENCRYPTION_KEY_V1" },
];
for (const config of keyConfigs) {
const keyString = this.env[config.env] || this.env.CATNIP_ENCRYPTION_KEY;
if (keyString) {
const key = await this.importKey(keyString);
this.keys.set(config.id, key);
this.currentKeyId = Math.max(this.currentKeyId, config.id);
}
}
// Fallback to single key if no versioned keys
if (this.keys.size === 0 && this.env.CATNIP_ENCRYPTION_KEY) {
const key = await this.importKey(this.env.CATNIP_ENCRYPTION_KEY);
this.keys.set(1, key);
this.currentKeyId = 1;
}
this.initialized = true;
}
private async importKey(keyString: string): Promise<CryptoKey> {
// Handle base64url encoded keys (convert to standard base64)
const base64 = keyString
.replace(/-/g, "+")
.replace(/_/g, "/")
.padEnd(keyString.length + ((4 - (keyString.length % 4)) % 4), "=");
const keyData = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
return await crypto.subtle.importKey(
"raw",
keyData,
{ name: "AES-GCM" },
false,
["encrypt", "decrypt"],
);
}
private async encrypt(
data: CodespaceCredentials,
keyId: number,
): Promise<{ salt: string; iv: string; encrypted: string }> {
const key = this.keys.get(keyId);
if (!key) throw new Error(`Key ${keyId} not found`);
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoder = new TextEncoder();
const encrypted = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv,
additionalData: salt,
},
key,
encoder.encode(JSON.stringify(data)),
);
return {
salt: btoa(String.fromCharCode(...salt)),
iv: btoa(String.fromCharCode(...iv)),
encrypted: btoa(String.fromCharCode(...new Uint8Array(encrypted))),
};
}
private async decrypt(
stored: StoredCodespaceCredentials,
): Promise<CodespaceCredentials> {
if (
stored.keyId === null ||
stored.salt === null ||
stored.iv === null ||
stored.encryptedData === null
) {
throw new Error("Invalid stored credentials: missing encryption data");
}
const key = this.keys.get(stored.keyId);
if (!key) throw new Error(`Key ${stored.keyId} not found`);
const salt = Uint8Array.from(atob(stored.salt), (c) => c.charCodeAt(0));
const iv = Uint8Array.from(atob(stored.iv), (c) => c.charCodeAt(0));
const encrypted = Uint8Array.from(atob(stored.encryptedData), (c) =>
c.charCodeAt(0),
);
const decrypted = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv,
additionalData: salt,
},
key,
encrypted,
);
const decoder = new TextDecoder();
return JSON.parse(decoder.decode(decrypted));
}
async fetch(request: Request): Promise<Response> {
await this.initKeys();
const url = new URL(request.url);
const pathParts = url.pathname.split("/");
// Handle verification cache routes: /verification-cache/{username}
if (url.pathname.match(/^\/verification-cache\/(.+)$/)) {
const username = url.pathname.split("/")[2];
const cacheKey = `verification-cache:${username}`;
// GET /verification-cache/{username}
if (request.method === "GET") {
const cache = await this.ctx.storage.get<{
username: string;
lastVerified: number;
lastRefreshRequest: number;
verifiedCodespaces: any[];
}>(cacheKey);
if (!cache) {
return new Response("Not found", { status: 404 });
}
return new Response(JSON.stringify(cache), {
headers: { "Content-Type": "application/json" },
});
}
// PATCH /verification-cache/{username}
else if (request.method === "PATCH") {
let update;
try {
update = await request.json<{
username?: string;
lastVerified?: number;
lastRefreshRequest?: number;
verifiedCodespaces?: any[];
}>();
} catch (_error) {
return new Response("Invalid JSON", { status: 400 });
}
// Get existing cache or create new one
let cache = await this.ctx.storage.get<{
username: string;
lastVerified: number;
lastRefreshRequest: number;
verifiedCodespaces: any[];
}>(cacheKey);
if (!cache) {
cache = {
username,
lastVerified: 0,
lastRefreshRequest: 0,
verifiedCodespaces: [],
};
}
// Apply update
cache = { ...cache, ...update };
// Save
await this.ctx.storage.put(cacheKey, cache);
return new Response("OK", { status: 200 });
}
// Unsupported methods
else {
return new Response("Method not allowed", { status: 405 });
}
}
// Handle specific codespace lookup: /internal/codespace/{username}/{codespaceName}
if (pathParts.length >= 4 && request.method === "GET") {
const codespaceName = pathParts.pop();
const githubUser = pathParts.pop();
if (githubUser && codespaceName) {
const rows = this.sql
.exec(
"SELECT * FROM codespace_credentials WHERE github_user = ? AND codespace_name = ? ORDER BY updated_at DESC LIMIT 1",
githubUser,
codespaceName,
)
.toArray();
if (rows.length === 0) {
return new Response("Codespace not found", { status: 404 });
}
const row = rows[0];
const result = {
keyId: row.key_id as number | null,
salt: row.salt as string | null,
iv: row.iv as string | null,
encryptedData: row.encrypted_data as string | null,
createdAt: row.created_at as number,
updatedAt: row.updated_at as number,
} as StoredCodespaceCredentials;
// Extract status fields
const status = row.status as string | null;
const lastHealthCheck = row.last_health_check as number | null;
const lastError = row.last_error as string | null;
// Check if credentials are already nullified (expired)
if (
!result.encryptedData ||
!result.salt ||
!result.iv ||
!result.keyId
) {
// Return basic codespace info without credentials
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: row.codespace_name as string,
githubRepository: row.github_repository as string | undefined,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
status: status as "available" | "unavailable" | undefined,
lastHealthCheck: lastHealthCheck ?? undefined,
lastError: lastError ?? undefined,
};
return Response.json(basicCodespace);
}
try {
const credentials = await this.decrypt(result);
// Check if credentials are expired (24 hours)
const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;
if (credentials.updatedAt < twentyFourHoursAgo) {
// Null out expired credentials but keep codespace record
this.sql.exec(
"UPDATE codespace_credentials SET key_id = NULL, salt = NULL, iv = NULL, encrypted_data = NULL WHERE codespace_name = ?",
credentials.codespaceName,
);
// Return basic codespace info without credentials
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: credentials.codespaceName,
githubRepository: credentials.githubRepository,
createdAt: credentials.createdAt,
updatedAt: credentials.updatedAt,
status: status as "available" | "unavailable" | undefined,
lastHealthCheck: lastHealthCheck ?? undefined,
lastError: lastError ?? undefined,
};
return Response.json(basicCodespace);
}
// Add status fields to decrypted credentials
credentials.status = status as
| "available"
| "unavailable"
| undefined;
credentials.lastHealthCheck = lastHealthCheck ?? undefined;
credentials.lastError = lastError ?? undefined;
return Response.json(credentials);
} catch (error) {
console.error("Decryption error:", error);
// Return basic codespace info without credentials on decryption error
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: row.codespace_name as string,
githubRepository: row.github_repository as string | undefined,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
status: status as "available" | "unavailable" | undefined,
lastHealthCheck: lastHealthCheck ?? undefined,
lastError: lastError ?? undefined,
};
return Response.json(basicCodespace);
}
}
}
// Handle specific codespace deletion: /internal/codespace/{username}/{codespaceName}
if (pathParts.length >= 4 && request.method === "DELETE") {
const codespaceName = pathParts.pop();
const githubUser = pathParts.pop();
if (githubUser && codespaceName) {
const result = this.sql.exec(
"DELETE FROM codespace_credentials WHERE codespace_name = ? AND github_user = ?",
codespaceName,
githubUser,
);
if (result.rowsWritten !== 1) {
return new Response("Codespace not found in store", { status: 404 });
}
return new Response("OK");
}
}
const githubUser = pathParts.pop();
// Handle status update: PATCH /internal/codespace/{username}/{codespaceName}/status
if (request.method === "PATCH" && url.pathname.endsWith("/status")) {
// Path format: /internal/codespace/{username}/{codespaceName}/status
const statusUpdate: {
status?: "available" | "unavailable";
lastError?: string;
} = await request.json();
const pathSegments = url.pathname.split("/");
const codespaceName = pathSegments[pathSegments.length - 2]; // Second to last segment (before "status")
const username = pathSegments[pathSegments.length - 3]; // Third to last
if (!username || !codespaceName) {
return new Response("Invalid path", { status: 400 });
}
const now = Date.now();
// Build UPDATE statement dynamically based on what fields are provided
const updates: string[] = ["last_health_check = ?"];
const params: any[] = [now];
if (statusUpdate.status !== undefined) {
updates.push("status = ?");
params.push(statusUpdate.status);
}
if (statusUpdate.lastError !== undefined) {
updates.push("last_error = ?");
params.push(statusUpdate.lastError);
}
params.push(username, codespaceName);
const result = this.sql.exec(
`UPDATE codespace_credentials
SET ${updates.join(", ")}
WHERE github_user = ? AND codespace_name = ?`,
...params,
);
if (result.rowsWritten === 0) {
return new Response("Codespace not found", { status: 404 });
}
return new Response("OK");
}
if (request.method === "GET" && githubUser) {
// Check if requesting all codespaces
const getAllParam = url.searchParams.get("all");
if (getAllParam === "true") {
// Get all codespaces by GitHub user (including those without credentials)
const rows = this.sql
.exec(
"SELECT * FROM codespace_credentials WHERE github_user = ? ORDER BY updated_at DESC",
githubUser,
)
.toArray();
if (rows.length === 0) {
return new Response("Not found", { status: 404 });
}
const availableCodespaces: CodespaceCredentials[] = [];
const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;
for (const row of rows) {
const result = {
keyId: row.key_id as number | null,
salt: row.salt as string | null,
iv: row.iv as string | null,
encryptedData: row.encrypted_data as string | null,
createdAt: row.created_at as number,
updatedAt: row.updated_at as number,
} as StoredCodespaceCredentials;
// If credentials are nullified (expired), create a basic codespace entry
if (
!result.encryptedData ||
!result.salt ||
!result.iv ||
!result.keyId
) {
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: row.codespace_name as string,
githubRepository: row.github_repository as string | undefined,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
};
availableCodespaces.push(basicCodespace);
continue;
}
try {
const credentials = await this.decrypt(result);
// Check if credentials are expired (24 hours)
if (credentials.updatedAt < twentyFourHoursAgo) {
// Null out expired credentials but keep codespace record
this.sql.exec(
"UPDATE codespace_credentials SET key_id = NULL, salt = NULL, iv = NULL, encrypted_data = NULL WHERE codespace_name = ?",
credentials.codespaceName,
);
// Still add as available codespace without credentials
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: credentials.codespaceName,
githubRepository: credentials.githubRepository,
createdAt: credentials.createdAt,
updatedAt: credentials.updatedAt,
};
availableCodespaces.push(basicCodespace);
continue;
}
availableCodespaces.push(credentials);
} catch (error) {
console.error("Decryption error for codespace:", error);
// Still add as available codespace without credentials
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: row.codespace_name as string,
githubRepository: row.github_repository as string | undefined,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
};
availableCodespaces.push(basicCodespace);
continue;
}
}
if (availableCodespaces.length === 0) {
return new Response("No codespaces found", { status: 404 });
}
return Response.json(availableCodespaces);
} else {
// Get most recent codespace by GitHub user (including those without credentials)
const rows = this.sql
.exec(
"SELECT * FROM codespace_credentials WHERE github_user = ? ORDER BY updated_at DESC LIMIT 1",
githubUser,
)
.toArray();
if (rows.length === 0) {
return new Response("Not found", { status: 404 });
}
const row = rows[0];
const result = {
keyId: row.key_id as number | null,
salt: row.salt as string | null,
iv: row.iv as string | null,
encryptedData: row.encrypted_data as string | null,
createdAt: row.created_at as number,
updatedAt: row.updated_at as number,
} as StoredCodespaceCredentials;
// Check if credentials are already nullified (expired)
if (
!result.encryptedData ||
!result.salt ||
!result.iv ||
!result.keyId
) {
// Return basic codespace info without credentials
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: row.codespace_name as string,
githubRepository: row.github_repository as string | undefined,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
};
return Response.json(basicCodespace);
}
try {
const credentials = await this.decrypt(result);
// Check if credentials are expired (24 hours)
const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;
if (credentials.updatedAt < twentyFourHoursAgo) {
// Null out expired credentials but keep codespace record
this.sql.exec(
"UPDATE codespace_credentials SET key_id = NULL, salt = NULL, iv = NULL, encrypted_data = NULL WHERE codespace_name = ?",
credentials.codespaceName,
);
// Return basic codespace info without credentials
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: credentials.codespaceName,
githubRepository: credentials.githubRepository,
createdAt: credentials.createdAt,
updatedAt: credentials.updatedAt,
};
return Response.json(basicCodespace);
}
return Response.json(credentials);
} catch (error) {
console.error("Decryption error:", error);
// Return basic codespace info without credentials on decryption error
const basicCodespace: CodespaceCredentials = {
githubToken: "", // Empty token - will need to be refreshed
githubUser: githubUser,
codespaceName: row.codespace_name as string,
githubRepository: row.github_repository as string | undefined,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
};
return Response.json(basicCodespace);
}
}
}
if (request.method === "PUT" && githubUser) {
// Store new credentials
const credentials: CodespaceCredentials = await request.json();
const { salt, iv, encrypted } = await this.encrypt(
credentials,
this.currentKeyId,
);
const now = Date.now();
// Check if credentials already exist for this codespace
const existingRows = this.sql
.exec(
"SELECT created_at FROM codespace_credentials WHERE codespace_name = ? LIMIT 1",
credentials.codespaceName,
)
.toArray();
const createdAt =
existingRows.length > 0 ? (existingRows[0].created_at as number) : now;
// Insert or replace credentials for this specific codespace
this.sql.exec(
`INSERT OR REPLACE INTO codespace_credentials
(codespace_name, github_user, github_repository, key_id, salt, iv, encrypted_data, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
credentials.codespaceName,
credentials.githubUser,
credentials.githubRepository || null,
this.currentKeyId,
salt,
iv,
encrypted,
createdAt,
now,
);
return new Response("OK");
}
if (request.method === "DELETE" && githubUser) {
// Delete all credentials for this user
this.sql.exec(
"DELETE FROM codespace_credentials WHERE github_user = ?",
githubUser,
);
return new Response("OK");
}
// Cleanup old credentials (older than 24 hours) - null out encrypted data but keep records
if (request.method === "POST" && url.pathname.endsWith("/cleanup")) {
const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;
this.sql.exec(
"UPDATE codespace_credentials SET key_id = NULL, salt = NULL, iv = NULL, encrypted_data = NULL WHERE updated_at < ? AND encrypted_data IS NOT NULL",
twentyFourHoursAgo,
);
return new Response("OK");
}
return new Response("Method not allowed", { status: 405 });
}
}