opencode-tethergate 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/setup.js ADDED
@@ -0,0 +1,605 @@
1
+ import { execFile } from "node:child_process"
2
+ import { promisify } from "node:util"
3
+
4
+ import {
5
+ approvalFor,
6
+ assertNoAdminShell,
7
+ commandFromInput,
8
+ } from "./guard.js"
9
+
10
+ const execFileAsync = promisify(execFile)
11
+ export const DEFAULT_COMMAND = ["docker", "exec", "-i", "tethergate", "tethergate"]
12
+
13
+ export function makeRunner(ctx) {
14
+ const configured =
15
+ ctx.options && Array.isArray(ctx.options.command) && ctx.options.command.length
16
+ ? ctx.options.command
17
+ : DEFAULT_COMMAND
18
+ const command = configured.map(String)
19
+ return async (args) => {
20
+ const [binary, ...prefix] = command
21
+ try {
22
+ const result = await execFileAsync(binary, [...prefix, ...args], {
23
+ timeout: 20_000,
24
+ maxBuffer: 2 * 1024 * 1024,
25
+ encoding: "utf8",
26
+ })
27
+ return result.stdout
28
+ } catch (error) {
29
+ const stderr =
30
+ error && typeof error === "object" && "stderr" in error
31
+ ? String(error.stderr).trim()
32
+ : ""
33
+ throw new Error(stderr || `tethergate command failed: ${binary}`)
34
+ }
35
+ }
36
+ }
37
+
38
+ async function requireApproval(ctx, request) {
39
+ await ctx.permission.assert(request)
40
+ }
41
+
42
+ const SESSION_RE = /^ses_[A-Za-z0-9_-]{4,128}$/
43
+ const NODE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
44
+
45
+ function validSession(sessionID) {
46
+ if (typeof sessionID !== "string" || !SESSION_RE.test(sessionID)) {
47
+ throw new Error("invalid OpenCode session id")
48
+ }
49
+ return sessionID
50
+ }
51
+
52
+ function validNode(name) {
53
+ if (typeof name !== "string" || !NODE_RE.test(name)) {
54
+ throw new Error("invalid node name")
55
+ }
56
+ return name
57
+ }
58
+
59
+ export function formatError(error) {
60
+ if (typeof error === "string") return error
61
+ if (error instanceof Error) return error.message
62
+ if (error && typeof error === "object") {
63
+ if (typeof error.message === "string" && error.message) return error.message
64
+ if (typeof error.data === "string" && error.data) return error.data
65
+ if (
66
+ error.data &&
67
+ typeof error.data === "object" &&
68
+ typeof error.data.message === "string" &&
69
+ error.data.message
70
+ ) {
71
+ return error.data.message
72
+ }
73
+ try {
74
+ const serialized = JSON.stringify(error)
75
+ if (serialized && serialized !== "{}") return serialized
76
+ } catch {
77
+ // Fall through to the generic string form below.
78
+ }
79
+ }
80
+ return String(error)
81
+ }
82
+
83
+ function nodeSummary(nodes) {
84
+ if (!Array.isArray(nodes) || nodes.length === 0) return "No nodes enrolled."
85
+ return nodes
86
+ .map(
87
+ (node) =>
88
+ `${node.name}: ${node.online ? "online" : "offline"} (${node.status})` +
89
+ (node.connected_ip ? ` · ${node.connected_ip}` : ""),
90
+ )
91
+ .join("\n")
92
+ }
93
+
94
+ export const COMMAND_HELP = `Tethergate commands:
95
+ /tethergate Show this help
96
+ /tethergate help Show this help
97
+ /tethergate status Show this session's access and nodes
98
+ /tethergate grant all Grant this session every enrolled node
99
+ /tethergate grant NODE[,NODE] Grant this session specific nodes
100
+ /tethergate revoke Revoke this session's node access
101
+ /tethergate default deny New sessions get no node access
102
+ /tethergate default all --yes New sessions get every node
103
+ /tethergate node list List enrolled nodes
104
+ /tethergate node add NAME Create a one-command enrollment token
105
+ /tethergate node revoke NAME Revoke a node
106
+ /tethergate node reset NAME Clear quarantine and re-enable a node
107
+ /tethergate node rename OLD NEW Rename a node
108
+ /tethergate node retire NAME Retire a node and free its name
109
+ /tethergate node update NAME Update a node agent to this server version
110
+ /tethergate node rollback NAME Roll back a node agent
111
+ /tethergate node uninstall NAME Remove the agent from a node
112
+ /tethergate auto status Show automatic agent update state
113
+ /tethergate auto pause [REASON] Stop future automatic agent updates
114
+ /tethergate auto resume Resume automatic agent updates
115
+ /tethergate auto run Skip the delay and start the rollout now
116
+ /tethergate fleet add [LABEL] Create a reusable fleet installer
117
+ /tethergate fleet list List fleet installers
118
+ /tethergate fleet revoke ID Revoke a fleet installer`
119
+
120
+ export async function runCommand(rpc, service, sessionID, text) {
121
+ const parts = String(text || "")
122
+ .trim()
123
+ .split(/\s+/)
124
+ .filter(Boolean)
125
+ if (parts.length === 0) {
126
+ return COMMAND_HELP
127
+ }
128
+ const action = parts[0].toLowerCase()
129
+ if (action === "help") {
130
+ return COMMAND_HELP
131
+ }
132
+ if (action === "status") {
133
+ const data = await rpc.snapshot({ sessionID })
134
+ return `${service.describe(data)}\n\n${nodeSummary(data.nodes)}`
135
+ }
136
+ if (action === "grant" && parts[1]?.toLowerCase() === "all") {
137
+ const data = await rpc.grantAll({ sessionID })
138
+ return service.describe(data)
139
+ }
140
+ if (action === "grant") {
141
+ const names = parts
142
+ .slice(1)
143
+ .join(" ")
144
+ .split(",")
145
+ .map((name) => name.trim())
146
+ .filter(Boolean)
147
+ if (names.length === 0) {
148
+ return COMMAND_HELP
149
+ }
150
+ const data = await rpc.grantNodes({ sessionID, nodes: names })
151
+ return service.describe(data)
152
+ }
153
+ if (action === "revoke") {
154
+ const current = await rpc.snapshot({ sessionID })
155
+ if (current.defaultAccess === "all") {
156
+ return "default-all is active; set /tethergate default deny before revoking individual sessions"
157
+ }
158
+ const data = await rpc.revoke({ sessionID })
159
+ return service.describe(data)
160
+ }
161
+ if (action === "default") {
162
+ const mode = (parts[1] || "").toLowerCase()
163
+ if (mode !== "deny" && mode !== "all") {
164
+ return COMMAND_HELP
165
+ }
166
+ if (mode === "all" && !parts.includes("--yes")) {
167
+ return `refusing default-all without --yes; run /tethergate default all --yes\n\n${COMMAND_HELP}`
168
+ }
169
+ const result = await rpc.setDefault({
170
+ mode,
171
+ confirm: mode === "all",
172
+ sessionID,
173
+ })
174
+ return `default access for new sessions: ${result.default}`
175
+ }
176
+ if (action === "auto") {
177
+ const sub = (parts[1] || "").toLowerCase()
178
+ if (sub === "status") {
179
+ const data = await rpc.autoStatus({})
180
+ return data.output || "Automatic agent updates: no status available."
181
+ }
182
+ if (sub === "pause") {
183
+ const data = await rpc.autoPause({
184
+ sessionID,
185
+ reason: parts.slice(2).join(" "),
186
+ })
187
+ return data.output || "Automatic agent updates paused."
188
+ }
189
+ if (sub === "resume") {
190
+ const data = await rpc.autoResume({ sessionID })
191
+ return data.output || "Automatic agent updates resumed."
192
+ }
193
+ if (sub === "run") {
194
+ const data = await rpc.autoRun({ sessionID })
195
+ return data.output || "Automatic agent rollout started."
196
+ }
197
+ return COMMAND_HELP
198
+ }
199
+ if (action === "fleet") {
200
+ const sub = (parts[1] || "").toLowerCase()
201
+ if (sub === "list") {
202
+ const data = await rpc.fleetList({})
203
+ if (data.tokens.length === 0) return "No fleet installers."
204
+ return data.tokens
205
+ .map(
206
+ (token) =>
207
+ `${token.id}: ${token.label || "(no label)"} — ${
208
+ token.valid ? "active" : "revoked"
209
+ }, ${token.uses}/${token.maxUses} uses`,
210
+ )
211
+ .join("\n")
212
+ }
213
+ if (sub === "revoke") {
214
+ const id = parts[2]
215
+ if (!id) return COMMAND_HELP
216
+ await rpc.fleetRevoke({ sessionID, id })
217
+ return `Revoked fleet installer ${id}.`
218
+ }
219
+ if (sub !== "add") {
220
+ return COMMAND_HELP
221
+ }
222
+ const data = await rpc.fleetAdd({
223
+ sessionID,
224
+ label: parts.slice(2).join(" "),
225
+ ttlSeconds: 3600,
226
+ maxUses: 50,
227
+ })
228
+ return data.command
229
+ }
230
+ if (action === "node") {
231
+ const sub = (parts[1] || "").toLowerCase()
232
+ if (sub === "list") {
233
+ const data = await rpc.nodeList({})
234
+ return nodeSummary(data.nodes)
235
+ }
236
+ if (sub === "add") {
237
+ const name = parts[2]
238
+ if (!name) return COMMAND_HELP
239
+ const data = await rpc.nodeAdd({ name, sessionID })
240
+ return data.command
241
+ }
242
+ if (sub === "revoke") {
243
+ const node = parts[2]
244
+ if (!node) return COMMAND_HELP
245
+ await rpc.nodeRevoke({ node, sessionID })
246
+ return `Revoked node ${node}.`
247
+ }
248
+ if (sub === "reset") {
249
+ const node = parts[2]
250
+ if (!node) return COMMAND_HELP
251
+ await rpc.nodeReactivate({ node, sessionID })
252
+ return `Re-enabled node ${node}.`
253
+ }
254
+ if (sub === "rename") {
255
+ const node = parts[2]
256
+ const name = parts[3]
257
+ if (!node || !name) return COMMAND_HELP
258
+ await rpc.nodeRename({ node, name, sessionID })
259
+ return `Renamed node ${node} to ${name}.`
260
+ }
261
+ if (sub === "retire") {
262
+ const node = parts[2]
263
+ if (!node) return COMMAND_HELP
264
+ await rpc.nodeRetire({ node, sessionID })
265
+ return `Retired node ${node}; its original name is free for a replacement.`
266
+ }
267
+ if (sub === "update" || sub === "rollback") {
268
+ const node = parts[2]
269
+ if (!node) return COMMAND_HELP
270
+ const result = await rpc.nodeUpdate({
271
+ node,
272
+ rollback: sub === "rollback",
273
+ sessionID,
274
+ })
275
+ return (
276
+ String(result.output || "").trim() ||
277
+ `${sub === "rollback" ? "Rolled back" : "Updated"} node ${node}.`
278
+ )
279
+ }
280
+ if (sub === "uninstall") {
281
+ const node = parts[2]
282
+ if (!node) return COMMAND_HELP
283
+ const result = await rpc.nodeUninstall({ node, sessionID })
284
+ return String(result.output || "").trim() || `Uninstalled the agent on ${node}.`
285
+ }
286
+ return COMMAND_HELP
287
+ }
288
+ return `Unknown command: ${parts[0]}\n\n${COMMAND_HELP}`
289
+ }
290
+
291
+ export async function setupTethergate(ctx, service, rpcDefinition) {
292
+ // Access changes are user decisions. Force every Tethergate authorization
293
+ // action through OpenCode's native permission prompt, even when the user's
294
+ // agent rules would otherwise auto-allow it. An explicit deny still wins.
295
+ const disposers = []
296
+ disposers.push(
297
+ await ctx.permission.hook("evaluate", (event) => {
298
+ if (event.action.startsWith("tethergate.") && event.effect !== "deny") {
299
+ event.effect = "ask"
300
+ const scoped = event.metadata && event.metadata.message
301
+ event.message = scoped
302
+ ? `${scoped} (Tethergate access changes require explicit approval.)`
303
+ : "Tethergate access changes require explicit approval in OpenCode."
304
+ }
305
+ }),
306
+ )
307
+
308
+ // A model with a shell tool must not be able to bypass the UI by running
309
+ // the admin CLI or `docker exec` itself.
310
+ disposers.push(
311
+ await ctx.tool.hook("execute.before", (event) => {
312
+ // File-edit tools are data, not process launches. Inspect every other
313
+ // tool so custom/renamed shell tools cannot bypass the guard.
314
+ if (/^(edit|write|read|patch|apply_patch|multiedit|compress|todowrite|todoread|question|search)$/i.test(String(event.tool || ""))) {
315
+ return
316
+ }
317
+ assertNoAdminShell(commandFromInput(event.input))
318
+ }),
319
+ )
320
+ disposers.push(
321
+ await ctx.shell.hook("create.before", (event) => {
322
+ assertNoAdminShell(event.command)
323
+ }),
324
+ )
325
+
326
+ const registration = await ctx.rpc.register(rpcDefinition, {
327
+ snapshot: async (input) => service.snapshot(validSession(input.sessionID)),
328
+ grantAll: async (input) => {
329
+ validSession(input.sessionID)
330
+ await requireApproval(
331
+ ctx,
332
+ approvalFor(
333
+ input.sessionID,
334
+ "grant",
335
+ ["scope:all"],
336
+ "Grant this OpenCode session access to every enrolled node?",
337
+ ),
338
+ )
339
+ return service.grantAll(input.sessionID)
340
+ },
341
+ grantNodes: async (input) => {
342
+ validSession(input.sessionID)
343
+ if (!Array.isArray(input.nodes) || input.nodes.length === 0) {
344
+ throw new Error("at least one node is required")
345
+ }
346
+ input.nodes.forEach(validNode)
347
+ const current = await service.snapshot(input.sessionID)
348
+ if (current.defaultAccess === "all") {
349
+ throw new Error("default-all is active; set default deny before choosing nodes")
350
+ }
351
+ await requireApproval(
352
+ ctx,
353
+ approvalFor(
354
+ input.sessionID,
355
+ "grant",
356
+ input.nodes.map((node) => `node:${node}`),
357
+ `Grant this OpenCode session access to ${input.nodes.join(", ")}?`,
358
+ ),
359
+ )
360
+ return service.grantNodes(input.sessionID, input.nodes)
361
+ },
362
+ revoke: async (input) => {
363
+ validSession(input.sessionID)
364
+ await requireApproval(
365
+ ctx,
366
+ approvalFor(
367
+ input.sessionID,
368
+ "revoke",
369
+ ["scope:this-session"],
370
+ "Revoke this OpenCode session's Tethergate access?",
371
+ ),
372
+ )
373
+ return service.revoke(input.sessionID)
374
+ },
375
+ nodeList: async () => ({ nodes: await service.nodeList() }),
376
+ nodeAdd: async (input) => {
377
+ validSession(input.sessionID)
378
+ validNode(input.name)
379
+ await requireApproval(
380
+ ctx,
381
+ approvalFor(
382
+ input.sessionID,
383
+ "node",
384
+ [`node:${input.name}`, "action:enroll"],
385
+ `Create an enrollment token for node ${input.name}?`,
386
+ ),
387
+ )
388
+ return service.nodeAdd(input.name)
389
+ },
390
+ nodeRevoke: async (input) => {
391
+ validSession(input.sessionID)
392
+ validNode(input.node)
393
+ await requireApproval(
394
+ ctx,
395
+ approvalFor(
396
+ input.sessionID,
397
+ "node",
398
+ [`node:${input.node}`, "action:revoke"],
399
+ `Revoke node ${input.node} and close its agent connection?`,
400
+ ),
401
+ )
402
+ return service.nodeRevoke(input.node)
403
+ },
404
+ nodeReactivate: async (input) => {
405
+ validSession(input.sessionID)
406
+ validNode(input.node)
407
+ await requireApproval(
408
+ ctx,
409
+ approvalFor(
410
+ input.sessionID,
411
+ "node",
412
+ [`node:${input.node}`, "action:reactivate"],
413
+ `Re-enable quarantined node ${input.node}?`,
414
+ ),
415
+ )
416
+ return service.nodeReactivate(input.node)
417
+ },
418
+ nodeRename: async (input) => {
419
+ validSession(input.sessionID)
420
+ validNode(input.node)
421
+ validNode(input.name)
422
+ await requireApproval(
423
+ ctx,
424
+ approvalFor(
425
+ input.sessionID,
426
+ "node",
427
+ [`node:${input.node}`, `rename:${input.name}`],
428
+ `Rename node ${input.node} to ${input.name}?`,
429
+ ),
430
+ )
431
+ return service.nodeRename(input.node, input.name)
432
+ },
433
+ nodeRetire: async (input) => {
434
+ validSession(input.sessionID)
435
+ validNode(input.node)
436
+ await requireApproval(
437
+ ctx,
438
+ approvalFor(
439
+ input.sessionID,
440
+ "node",
441
+ [`node:${input.node}`, "action:retire"],
442
+ `Retire node ${input.node} and free its name for a replacement?`,
443
+ ),
444
+ )
445
+ return service.nodeRetire(input.node)
446
+ },
447
+ nodeUpdate: async (input) => {
448
+ validSession(input.sessionID)
449
+ validNode(input.node)
450
+ await requireApproval(
451
+ ctx,
452
+ approvalFor(
453
+ input.sessionID,
454
+ "node",
455
+ [
456
+ `node:${input.node}`,
457
+ input.rollback ? "action:rollback" : "action:update",
458
+ ],
459
+ input.rollback
460
+ ? `Roll back the agent on ${input.node} to the previous release?`
461
+ : `Install the current agent release on ${input.node}?`,
462
+ ),
463
+ )
464
+ return service.nodeUpdate(input.node, Boolean(input.rollback))
465
+ },
466
+ nodeUninstall: async (input) => {
467
+ validSession(input.sessionID)
468
+ validNode(input.node)
469
+ await requireApproval(
470
+ ctx,
471
+ approvalFor(
472
+ input.sessionID,
473
+ "node",
474
+ [`node:${input.node}`, "action:uninstall"],
475
+ `Remove the tethergate agent from ${input.node}? The server record will remain.`,
476
+ ),
477
+ )
478
+ return service.nodeUninstall(input.node)
479
+ },
480
+ autoStatus: async () => service.autoStatus(),
481
+ autoPause: async (input) => {
482
+ validSession(input.sessionID)
483
+ await requireApproval(
484
+ ctx,
485
+ approvalFor(
486
+ input.sessionID,
487
+ "node",
488
+ ["auto-update:pause"],
489
+ `Pause automatic agent updates${input.reason ? ` (${input.reason})` : ""}?`,
490
+ ),
491
+ )
492
+ return service.autoPause(input.reason || "")
493
+ },
494
+ autoResume: async (input) => {
495
+ validSession(input.sessionID)
496
+ await requireApproval(
497
+ ctx,
498
+ approvalFor(
499
+ input.sessionID,
500
+ "node",
501
+ ["auto-update:resume"],
502
+ "Resume automatic agent updates?",
503
+ ),
504
+ )
505
+ return service.autoResume()
506
+ },
507
+ autoRun: async (input) => {
508
+ validSession(input.sessionID)
509
+ await requireApproval(
510
+ ctx,
511
+ approvalFor(
512
+ input.sessionID,
513
+ "node",
514
+ ["auto-update:run"],
515
+ "Start the automatic agent rollout now, skipping the safety delay?",
516
+ ),
517
+ )
518
+ return service.autoRun()
519
+ },
520
+ fleetList: async () => ({ tokens: await service.fleetList() }),
521
+ fleetRevoke: async (input) => {
522
+ validSession(input.sessionID)
523
+ if (typeof input.id !== "string" || !/^flt_[A-Za-z0-9_-]{4,128}$/.test(input.id)) {
524
+ throw new Error("invalid fleet installer id")
525
+ }
526
+ await requireApproval(
527
+ ctx,
528
+ approvalFor(
529
+ input.sessionID,
530
+ "node",
531
+ [`fleet:${input.id}`, "action:revoke"],
532
+ `Revoke reusable fleet installer ${input.id}?`,
533
+ ),
534
+ )
535
+ return service.fleetRevoke(input.id)
536
+ },
537
+ fleetAdd: async (input) => {
538
+ validSession(input.sessionID)
539
+ await requireApproval(
540
+ ctx,
541
+ approvalFor(
542
+ input.sessionID,
543
+ "node",
544
+ ["fleet:new", `max-uses:${input.maxUses || 50}`],
545
+ "Create a reusable fleet installer one-liner?",
546
+ ),
547
+ )
548
+ return service.fleetAdd(
549
+ input.label || "",
550
+ input.ttlSeconds || 3600,
551
+ input.maxUses || 50,
552
+ )
553
+ },
554
+ setDefault: async (input) => {
555
+ validSession(input.sessionID)
556
+ await requireApproval(
557
+ ctx,
558
+ approvalFor(
559
+ input.sessionID,
560
+ "default",
561
+ [`default:${input.mode}`],
562
+ input.mode === "all"
563
+ ? "Allow every new OpenCode session to access every enrolled node?"
564
+ : "Deny access by default for every new OpenCode session?",
565
+ ),
566
+ )
567
+ return service.setDefault(input.mode, Boolean(input.confirm))
568
+ },
569
+ })
570
+ const rpc = ctx.rpc(rpcDefinition)
571
+
572
+ // This command runs in the server plugin, not through the model. It is
573
+ // available in the TUI, web, and desktop clients.
574
+ disposers.push(
575
+ await ctx.command.transform((editor) => {
576
+ editor.add({
577
+ name: "tethergate",
578
+ description: "Manage tethergate access for the current session",
579
+ execute: async ({ sessionID, prompt }) => {
580
+ let message
581
+ try {
582
+ message = await runCommand(rpc, service, sessionID, prompt?.text)
583
+ } catch (error) {
584
+ message = `tethergate error: ${formatError(error)}`
585
+ }
586
+ await ctx.session.synthetic({ sessionID, text: message })
587
+ },
588
+ })
589
+ }),
590
+ )
591
+
592
+ return async () => {
593
+ for (const dispose of disposers.reverse()) {
594
+ try {
595
+ if (typeof dispose === "function") await dispose()
596
+ else if (dispose && typeof dispose.dispose === "function") {
597
+ await dispose.dispose()
598
+ }
599
+ } catch {
600
+ // best-effort cleanup during plugin reload
601
+ }
602
+ }
603
+ await registration.dispose()
604
+ }
605
+ }