forked from iazzam-bornan/docker-session
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplates.ts
More file actions
538 lines (494 loc) · 16.9 KB
/
Copy pathtemplates.ts
File metadata and controls
538 lines (494 loc) · 16.9 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
// ─────────────────────────────────────────────────────────────────────────
// command template registry
//
// the template system is the heart of the security model. user-typed text
// never reaches a shell. instead:
//
// 1. the user's command is matched against a template's regex
// 2. captured groups are validated and bound to template parameters
// 3. the template returns a *concrete* argv array which we pass to spawn
//
// every template is responsible for:
// • injecting --label session=<id> on every artifact it creates
// • prefixing names with <id>- so users never collide
// • rewriting -p host:guest mappings into the per-session port slice
//
// adding a new command means: add a new template object below.
// ─────────────────────────────────────────────────────────────────────────
import type { Session } from "./session"
import { releasePort, reservePort } from "./workspace"
export type TemplateMatch = {
/** absolute path of the executable to run */
bin: string
/** argv array (no shell interpolation, ever) */
args: string[]
/** working directory */
cwd?: string
/** soft kill timeout in ms */
timeoutMs?: number
/** optional message we want the user to see *before* the command runs */
preface?: string
/** optional message after the command finishes successfully */
epilogue?: string
}
export type TemplateBuildResult =
| { ok: true; cmd: TemplateMatch }
| { ok: false; reason: string; hint?: string }
/**
* Context handed to a template's `build()` callback. Carries the absolute
* cwd resolved from the run request — docker templates that need a build
* context (build, compose) read this so the user has to actually `cd` into
* the project before the command works, like a real shell.
*/
export type BuildContext = {
/** absolute path the user is currently `cd`'d into */
requestCwd: string
}
export type Template = {
/** human-readable name, used in error messages */
name: string
/** regex applied to the trimmed user input */
match: RegExp
/** build the concrete command for the matched session */
build: (
m: RegExpMatchArray,
session: Session,
ctx: BuildContext
) => TemplateBuildResult
}
// ─── helpers ─────────────────────────────────────────────────────────────
const NAME_RE = /^[a-z][a-z0-9-]{0,30}$/
const PORT_RE = /^\d{1,5}$/
/** prefix any user-supplied container/image name with the session id */
function prefixed(session: Session, name: string): string {
return `${session.id}-${name}`
}
function isValidName(name: string): boolean {
return NAME_RE.test(name)
}
function isValidPort(port: string): boolean {
if (!PORT_RE.test(port)) return false
const n = Number(port)
return n > 0 && n < 65536
}
const SESSION_LABEL = (session: Session) => `session=${session.id}`
// ─── docker images ───────────────────────────────────────────────────────
const dockerImages: Template = {
name: "docker images",
match: /^docker\s+images\s*$/,
build: (_m, session) => ({
ok: true,
cmd: {
bin: "docker",
args: [
"images",
"--filter",
`label=${SESSION_LABEL(session)}`,
"--format",
"table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}}\t{{.Size}}",
],
timeoutMs: 5_000,
},
}),
}
// ─── docker ps (running) and docker ps -a (all) ──────────────────────────
const dockerPs: Template = {
name: "docker ps",
match: /^docker\s+ps(\s+-a)?\s*$/,
build: (m, session) => {
const all = m[1] !== undefined
return {
ok: true,
cmd: {
bin: "docker",
args: [
"ps",
...(all ? ["-a"] : []),
"--filter",
`label=${SESSION_LABEL(session)}`,
"--format",
"table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}",
],
timeoutMs: 5_000,
},
}
},
}
// ─── docker build -t <name> . ────────────────────────────────────────────
//
// build context comes from the request cwd — i.e. wherever the user is
// `cd`'d into in their terminal. the user has to actually be in the
// project (or any folder containing a Dockerfile) for this to work,
// just like a real shell. if there's no Dockerfile, docker fails
// naturally with a clear error.
const dockerBuild: Template = {
name: "docker build",
match: /^docker\s+build\s+-t\s+([a-z][\w-]{0,30})\s+\.\s*$/,
build: (m, session, ctx) => {
const userName = m[1].toLowerCase()
if (!isValidName(userName)) {
return { ok: false, reason: `invalid image name: ${m[1]}` }
}
const fullName = prefixed(session, userName)
return {
ok: true,
cmd: {
bin: "docker",
args: [
"build",
"-t",
`${fullName}:latest`,
"--label",
SESSION_LABEL(session),
// resource caps so a runaway build can't take down the demo
"--memory",
"512m",
ctx.requestCwd,
],
cwd: ctx.requestCwd,
timeoutMs: 10 * 60_000, // 10 minutes — first build pulls the base image
epilogue: `tagged as ${userName}:latest`,
},
}
},
}
// ─── docker run -p host:guest <image> ────────────────────────────────────
//
// we accept either:
// docker run -p 3000:3000 greeter
// docker run -d -p 3000:3000 greeter
//
// host port is rewritten through the per-session pool. user types `3000`,
// container actually binds (e.g.) `30041`. the host port is what we report
// back so the user knows where to point their browser.
const dockerRun: Template = {
name: "docker run",
match:
/^docker\s+run(?:\s+-d)?\s+-p\s+(\d{1,5}):(\d{1,5})\s+([a-z][\w-]{0,30})\s*$/,
build: (m, session) => {
const requestedHost = m[1]
const guestPort = m[2]
const userImage = m[3].toLowerCase()
if (!isValidPort(requestedHost) || !isValidPort(guestPort)) {
return { ok: false, reason: "ports must be between 1 and 65535" }
}
if (!isValidName(userImage)) {
return { ok: false, reason: `invalid image name: ${m[3]}` }
}
const guestPortNum = Number(guestPort)
const allocated = reservePort(session.id, guestPortNum)
if (allocated === null) {
return {
ok: false,
reason: "your port slice is full — `docker rm` something first",
}
}
const fullImage = prefixed(session, userImage)
const containerName = prefixed(session, userImage)
return {
ok: true,
cmd: {
bin: "docker",
args: [
"run",
"-d", // always detached so the websocket isn't blocked
"--rm", // auto-cleanup on stop, simpler lifecycle
"--name",
containerName,
"--label",
SESSION_LABEL(session),
"-p",
`${allocated}:${guestPort}`,
// resource caps
"--memory",
"256m",
"--cpus",
"0.5",
"--pids-limit",
"100",
`${fullImage}:latest`,
],
timeoutMs: 30_000,
// We deliberately echo the user's requested port instead of the
// real allocated host port. The browser app translates localhost
// URLs through `lookup_port` so the user never has to think about
// the per-session port pool.
epilogue: `→ http://localhost:${requestedHost}`,
},
}
},
}
// ─── docker stop <name> ──────────────────────────────────────────────────
const dockerStop: Template = {
name: "docker stop",
match: /^docker\s+stop\s+([a-z][\w-]{0,30})\s*$/,
build: (m, session) => {
const userName = m[1].toLowerCase()
if (!isValidName(userName)) {
return { ok: false, reason: `invalid container name: ${m[1]}` }
}
return {
ok: true,
cmd: {
bin: "docker",
args: ["stop", prefixed(session, userName)],
timeoutMs: 30_000,
epilogue: "stopped",
},
}
},
}
// ─── docker rm <name> ────────────────────────────────────────────────────
//
// because run uses --rm, this is mostly a no-op for running containers.
// but stopped containers (-a) still hang around if they crashed, so we
// keep this for cleanup.
const dockerRm: Template = {
name: "docker rm",
match: /^docker\s+rm\s+(-f\s+)?([a-z][\w-]{0,30})\s*$/,
build: (m, session) => {
const force = m[1] !== undefined
const userName = m[2].toLowerCase()
if (!isValidName(userName)) {
return { ok: false, reason: `invalid container name: ${m[2]}` }
}
return {
ok: true,
cmd: {
bin: "docker",
args: [
"rm",
...(force ? ["-f"] : []),
prefixed(session, userName),
],
timeoutMs: 30_000,
},
}
},
}
// ─── docker rmi <name> ───────────────────────────────────────────────────
const dockerRmi: Template = {
name: "docker rmi",
match: /^docker\s+rmi\s+([a-z][\w-]{0,30})\s*$/,
build: (m, session) => {
const userName = m[1].toLowerCase()
if (!isValidName(userName)) {
return { ok: false, reason: `invalid image name: ${m[1]}` }
}
return {
ok: true,
cmd: {
bin: "docker",
args: ["rmi", `${prefixed(session, userName)}:latest`],
timeoutMs: 15_000,
},
}
},
}
// ─── docker logs [-f] <name> ─────────────────────────────────────────────
//
// `-f` (follow) is a long-running command that streams forever. the
// frontend's cancel button issues a `cancel` message which the executor
// translates into proc.kill() — see index.ts activeProcs map.
const dockerLogs: Template = {
name: "docker logs",
match: /^docker\s+logs(\s+-f)?\s+([a-z][\w-]{0,30})\s*$/,
build: (m, session) => {
const follow = m[1] !== undefined
const userName = m[2].toLowerCase()
if (!isValidName(userName)) {
return { ok: false, reason: `invalid container name: ${m[2]}` }
}
return {
ok: true,
cmd: {
bin: "docker",
args: [
"logs",
"--tail",
"200",
...(follow ? ["-f"] : []),
prefixed(session, userName),
],
// follow mode has no timeout; the user cancels with the cancel button
timeoutMs: follow ? undefined : 5_000,
},
}
},
}
// ─── docker inspect <name> ───────────────────────────────────────────────
const dockerInspect: Template = {
name: "docker inspect",
match: /^docker\s+inspect\s+([a-z][\w-]{0,30})\s*$/,
build: (m, session) => {
const userName = m[1].toLowerCase()
if (!isValidName(userName)) {
return { ok: false, reason: `invalid name: ${m[1]}` }
}
return {
ok: true,
cmd: {
bin: "docker",
args: [
"inspect",
prefixed(session, userName),
],
timeoutMs: 10_000,
},
}
},
}
// ─── docker compose ──────────────────────────────────────────────────────
//
// every compose call is namespaced with `-p <sessionId>` so multiple
// users running the same compose file get distinct project stacks. the
// project directory is wherever the user is `cd`'d into when they run
// the command — they have to be in a folder with a docker-compose.yml,
// just like a real shell.
function composeBaseArgs(session: Session, requestCwd: string): string[] {
return [
"compose",
"-p",
session.id,
"--project-directory",
requestCwd,
"-f",
`${requestCwd}/docker-compose.yml`,
]
}
const dockerComposeUp: Template = {
name: "docker compose up",
match: /^docker\s+compose\s+up(\s+-d|\s+--build)*\s*$/,
build: (m, session, ctx) => {
const flags = m[0].replace(/^docker\s+compose\s+up\s*/, "").trim()
const extras: string[] = []
if (flags.includes("--build")) extras.push("--build")
return {
ok: true,
cmd: {
bin: "docker",
args: [
...composeBaseArgs(session, ctx.requestCwd),
"up",
"-d", // always detached so the websocket isn't blocked
...extras,
],
cwd: ctx.requestCwd,
timeoutMs: 10 * 60_000,
epilogue: "stack up — try `docker compose ps`",
},
}
},
}
const dockerComposeDown: Template = {
name: "docker compose down",
match: /^docker\s+compose\s+down(\s+-v)?\s*$/,
build: (m, session, ctx) => {
const wipeVolumes = m[1] !== undefined
return {
ok: true,
cmd: {
bin: "docker",
args: [
...composeBaseArgs(session, ctx.requestCwd),
"down",
...(wipeVolumes ? ["-v"] : []),
],
cwd: ctx.requestCwd,
timeoutMs: 60_000,
},
}
},
}
const dockerComposePs: Template = {
name: "docker compose ps",
match: /^docker\s+compose\s+ps\s*$/,
build: (_m, session, ctx) => ({
ok: true,
cmd: {
bin: "docker",
args: [...composeBaseArgs(session, ctx.requestCwd), "ps"],
cwd: ctx.requestCwd,
timeoutMs: 10_000,
},
}),
}
const dockerComposeBuild: Template = {
name: "docker compose build",
match: /^docker\s+compose\s+build\s*$/,
build: (_m, session, ctx) => ({
ok: true,
cmd: {
bin: "docker",
args: [...composeBaseArgs(session, ctx.requestCwd), "build"],
cwd: ctx.requestCwd,
timeoutMs: 10 * 60_000,
},
}),
}
const dockerComposeLogs: Template = {
name: "docker compose logs",
match: /^docker\s+compose\s+logs(\s+--tail=\d{1,4})?\s*$/,
build: (m, session, ctx) => {
const tailMatch = m[0].match(/--tail=(\d{1,4})/)
const tail = tailMatch ? tailMatch[1] : "200"
return {
ok: true,
cmd: {
bin: "docker",
args: [...composeBaseArgs(session, ctx.requestCwd), "logs", "--tail", tail],
cwd: ctx.requestCwd,
timeoutMs: 10_000,
},
}
},
}
// ─── registry ────────────────────────────────────────────────────────────
//
// order matters: we try templates top-to-bottom and return the first match.
// keep more-specific patterns before more-general ones if they ever overlap.
// order matters: more specific patterns (compose) come before more general
// ones (`docker run` etc) — though they don't actually overlap, having
// compose first makes the registry easier to scan.
export const TEMPLATES: Template[] = [
dockerImages,
dockerPs,
dockerBuild,
dockerRun,
dockerStop,
dockerRm,
dockerRmi,
dockerLogs,
dockerInspect,
dockerComposeUp,
dockerComposeDown,
dockerComposePs,
dockerComposeBuild,
dockerComposeLogs,
]
export function matchTemplate(
input: string
): { template: Template; match: RegExpMatchArray } | null {
const trimmed = input.trim()
for (const template of TEMPLATES) {
const m = trimmed.match(template.match)
if (m) return { template, match: m }
}
return null
}
// ─── port release on rm ──────────────────────────────────────────────────
//
// when a user removes a container, we need to release its port reservation
// so they can run another. but our templates only know names, not ports.
// the dispatcher in index.ts calls this *after* a successful rm/stop to
// keep the slice tidy. for now we just clear all reservations on a rm
// targeting a known container — good enough for the demo.
export function releasePortsForName(session: Session, name: string): void {
// we don't track which guest port belongs to which container, so the
// simplest correct behaviour is: when a user removes a container, free
// the port they most likely meant. since the demo only uses 3000, this
// is fine. a richer implementation would parse `docker inspect` output.
releasePort(session.id, 3000)
// silence linter when name is unused
void name
}