@marcusrbrown/infra 0.11.4 → 0.12.1

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.
@@ -0,0 +1,317 @@
1
+ import {afterEach, beforeEach, describe, expect, it} from 'bun:test'
2
+
3
+ import {streamDashboardLogs, type LogsSpawnFn, type StreamLogsOpts} from './logs'
4
+
5
+ // ─── Capturing spawn helper ───────────────────────────────────────────────────
6
+
7
+ function makeCapturingLogsSpawn(exitCode = 0): {spawn: LogsSpawnFn; capturedCmd: () => string[]} {
8
+ let captured: string[] = []
9
+ const spawn: LogsSpawnFn = (cmd, _opts) => {
10
+ captured = [...cmd]
11
+ return {exited: Promise.resolve(exitCode)}
12
+ }
13
+ return {spawn, capturedCmd: () => captured}
14
+ }
15
+
16
+ // NOTE: dashboard logs is intentionally CLI-only and NOT in the MCP allowlist.
17
+ // Logs may contain sensitive data (DB passwords, app secrets, user data).
18
+
19
+ // ─── streamDashboardLogs ─────────────────────────────────────────────────────
20
+
21
+ function makeLogsSpawn(exitCode = 0): LogsSpawnFn {
22
+ return (_cmd, _opts) => ({exited: Promise.resolve(exitCode)})
23
+ }
24
+
25
+ describe('logs command', () => {
26
+ let originalCI: string | undefined
27
+ let originalDashboardDomain: string | undefined
28
+
29
+ beforeEach(() => {
30
+ originalCI = process.env.CI
31
+ originalDashboardDomain = process.env.DASHBOARD_DOMAIN
32
+ })
33
+
34
+ afterEach(() => {
35
+ if (originalCI === undefined) {
36
+ delete process.env.CI
37
+ } else {
38
+ process.env.CI = originalCI
39
+ }
40
+
41
+ if (originalDashboardDomain === undefined) {
42
+ delete process.env.DASHBOARD_DOMAIN
43
+ } else {
44
+ process.env.DASHBOARD_DOMAIN = originalDashboardDomain
45
+ }
46
+ })
47
+
48
+ it('refuses to stream logs in CI without --allow-ci', async () => {
49
+ process.env.CI = 'true'
50
+
51
+ const opts: StreamLogsOpts = {
52
+ host: 'dashboard.fro.bot',
53
+ service: 'dashboard',
54
+ tail: 100,
55
+ allowCi: false,
56
+ }
57
+
58
+ const messages: string[] = []
59
+ const result = await streamDashboardLogs(opts, makeLogsSpawn(), msg => messages.push(msg))
60
+
61
+ expect(result.refused).toBe(true)
62
+ expect(messages.join('')).toContain('Refusing to stream logs in CI')
63
+ })
64
+
65
+ it('proceeds in CI when --allow-ci is set', async () => {
66
+ process.env.CI = 'true'
67
+
68
+ const opts: StreamLogsOpts = {
69
+ host: 'dashboard.fro.bot',
70
+ service: 'dashboard',
71
+ tail: 100,
72
+ allowCi: true,
73
+ }
74
+
75
+ const warnings: string[] = []
76
+ const result = await streamDashboardLogs(opts, makeLogsSpawn(), undefined, msg => warnings.push(msg))
77
+
78
+ expect(result.refused).toBe(false)
79
+ expect(result.exitCode).toBe(0)
80
+ })
81
+
82
+ it('always emits a sensitive-data warning to stderr', async () => {
83
+ delete process.env.CI
84
+
85
+ const opts: StreamLogsOpts = {
86
+ host: 'dashboard.fro.bot',
87
+ service: 'dashboard',
88
+ tail: 100,
89
+ allowCi: false,
90
+ }
91
+
92
+ const warnings: string[] = []
93
+ await streamDashboardLogs(opts, makeLogsSpawn(), undefined, msg => warnings.push(msg))
94
+
95
+ expect(warnings.join('')).toContain('sensitive')
96
+ })
97
+
98
+ it('rejects invalid host before spawning SSH', async () => {
99
+ delete process.env.CI
100
+
101
+ const opts: StreamLogsOpts = {
102
+ host: '-oProxyCommand=evil',
103
+ service: 'dashboard',
104
+ tail: 100,
105
+ allowCi: false,
106
+ }
107
+
108
+ let spawnCalled = false
109
+ const spy: LogsSpawnFn = (_cmd, _opts) => {
110
+ spawnCalled = true
111
+ return {exited: Promise.resolve(0)}
112
+ }
113
+
114
+ await expect(streamDashboardLogs(opts, spy)).rejects.toThrow('Invalid DASHBOARD_DOMAIN')
115
+ expect(spawnCalled).toBe(false)
116
+ })
117
+
118
+ it('returns exitCode from the SSH subprocess', async () => {
119
+ delete process.env.CI
120
+
121
+ const opts: StreamLogsOpts = {
122
+ host: 'dashboard.fro.bot',
123
+ service: 'dashboard',
124
+ tail: 50,
125
+ allowCi: false,
126
+ }
127
+
128
+ const result = await streamDashboardLogs(opts, makeLogsSpawn(42))
129
+
130
+ expect(result.refused).toBe(false)
131
+ expect(result.exitCode).toBe(42)
132
+ })
133
+
134
+ it('accepts caddy as a valid service', async () => {
135
+ delete process.env.CI
136
+
137
+ const opts: StreamLogsOpts = {
138
+ host: 'dashboard.fro.bot',
139
+ service: 'caddy',
140
+ tail: 100,
141
+ allowCi: false,
142
+ }
143
+
144
+ const result = await streamDashboardLogs(opts, makeLogsSpawn(0))
145
+ expect(result.refused).toBe(false)
146
+ expect(result.exitCode).toBe(0)
147
+ })
148
+
149
+ it('rejects an unknown service when called directly (bypassing the CLI action)', async () => {
150
+ delete process.env.CI
151
+
152
+ const opts: StreamLogsOpts = {
153
+ host: 'dashboard.fro.bot',
154
+ service: 'notaservice',
155
+ tail: 100,
156
+ allowCi: false,
157
+ }
158
+
159
+ let spawnCalled = false
160
+ const spy: LogsSpawnFn = (_cmd, _opts) => {
161
+ spawnCalled = true
162
+ return {exited: Promise.resolve(0)}
163
+ }
164
+
165
+ await expect(streamDashboardLogs(opts, spy)).rejects.toThrow(/Invalid service/)
166
+ expect(spawnCalled).toBe(false)
167
+ })
168
+ })
169
+
170
+ // ─── SSH command includes ConnectTimeout ─────────────────────────────────────
171
+
172
+ describe('streamDashboardLogs — SSH command includes ConnectTimeout', () => {
173
+ it('passes -o ConnectTimeout=10 to ssh', async () => {
174
+ delete process.env.CI
175
+
176
+ let capturedCmd: string[] = []
177
+ const spawnCapture: LogsSpawnFn = (cmd, _opts) => {
178
+ capturedCmd = cmd
179
+ return {exited: Promise.resolve(0)}
180
+ }
181
+
182
+ await streamDashboardLogs(
183
+ {host: 'dashboard.fro.bot', service: 'dashboard', tail: 100, allowCi: false},
184
+ spawnCapture,
185
+ )
186
+
187
+ const connectTimeoutIdx = capturedCmd.findIndex(arg => arg.startsWith('ConnectTimeout='))
188
+ expect(connectTimeoutIdx).toBeGreaterThan(-1)
189
+ expect(capturedCmd[connectTimeoutIdx - 1]).toBe('-o')
190
+ expect(capturedCmd[connectTimeoutIdx]).toBe('ConnectTimeout=10')
191
+ })
192
+ })
193
+
194
+ // ─── SSH command includes repo-pinned UserKnownHostsFile ─────────────────────
195
+
196
+ describe('streamDashboardLogs — SSH command includes UserKnownHostsFile', () => {
197
+ it('passes -o UserKnownHostsFile=<repo>/.github/known_hosts to ssh', async () => {
198
+ delete process.env.CI
199
+
200
+ let capturedCmd: string[] = []
201
+ const spawnCapture: LogsSpawnFn = (cmd, _opts) => {
202
+ capturedCmd = cmd
203
+ return {exited: Promise.resolve(0)}
204
+ }
205
+
206
+ await streamDashboardLogs(
207
+ {host: 'dashboard.fro.bot', service: 'dashboard', tail: 100, allowCi: false},
208
+ spawnCapture,
209
+ )
210
+
211
+ const knownHostsIdx = capturedCmd.findIndex(arg => arg.startsWith('UserKnownHostsFile='))
212
+ expect(knownHostsIdx).toBeGreaterThan(-1)
213
+ expect(capturedCmd[knownHostsIdx - 1]).toBe('-o')
214
+ expect(capturedCmd[knownHostsIdx]).toMatch(/\.github[/\\]known_hosts$/)
215
+ })
216
+
217
+ it('does not weaken StrictHostKeyChecking when UserKnownHostsFile is added', async () => {
218
+ delete process.env.CI
219
+
220
+ let capturedCmd: string[] = []
221
+ const spawnCapture: LogsSpawnFn = (cmd, _opts) => {
222
+ capturedCmd = cmd
223
+ return {exited: Promise.resolve(0)}
224
+ }
225
+
226
+ await streamDashboardLogs(
227
+ {host: 'dashboard.fro.bot', service: 'dashboard', tail: 100, allowCi: false},
228
+ spawnCapture,
229
+ )
230
+
231
+ const strictIdx = capturedCmd.findIndex(arg => arg.startsWith('StrictHostKeyChecking='))
232
+ expect(strictIdx).toBeGreaterThan(-1)
233
+ expect(capturedCmd[strictIdx]).toBe('StrictHostKeyChecking=yes')
234
+ })
235
+ })
236
+
237
+ // ─── SSH identity injection (DASHBOARD_SSH_KEY) ───────────────────────────────
238
+
239
+ describe('streamDashboardLogs — SSH identity injection', () => {
240
+ let originalEnv: Record<string, string | undefined>
241
+
242
+ beforeEach(() => {
243
+ originalEnv = {
244
+ CI: process.env.CI,
245
+ DASHBOARD_SSH_KEY: process.env.DASHBOARD_SSH_KEY,
246
+ }
247
+ delete process.env.CI
248
+ })
249
+
250
+ afterEach(() => {
251
+ if (originalEnv.CI === undefined) {
252
+ delete process.env.CI
253
+ } else {
254
+ process.env.CI = originalEnv.CI
255
+ }
256
+
257
+ if (originalEnv.DASHBOARD_SSH_KEY === undefined) {
258
+ delete process.env.DASHBOARD_SSH_KEY
259
+ } else {
260
+ process.env.DASHBOARD_SSH_KEY = originalEnv.DASHBOARD_SSH_KEY
261
+ }
262
+ })
263
+
264
+ it('includes -i <path> and IdentitiesOnly=yes in ssh argv when DASHBOARD_SSH_KEY is set', async () => {
265
+ process.env.DASHBOARD_SSH_KEY = '-----BEGIN OPENSSH PRIVATE KEY-----\nfakekey\n-----END OPENSSH PRIVATE KEY-----\n'
266
+
267
+ const {spawn, capturedCmd} = makeCapturingLogsSpawn(0)
268
+
269
+ await streamDashboardLogs({host: 'dashboard.fro.bot', service: 'dashboard', tail: 100, allowCi: false}, spawn)
270
+
271
+ const cmd = capturedCmd()
272
+ const iIdx = cmd.indexOf('-i')
273
+ expect(iIdx).toBeGreaterThan(-1)
274
+ expect(cmd[iIdx + 1]).toBeTruthy()
275
+
276
+ const identitiesOnlyIdx = cmd.indexOf('IdentitiesOnly=yes')
277
+ expect(identitiesOnlyIdx).toBeGreaterThan(-1)
278
+
279
+ const destination = cmd.find(arg => arg.includes('@'))
280
+ expect(destination).toBe('root@dashboard.fro.bot')
281
+ })
282
+
283
+ it('does not include -i or IdentitiesOnly=yes when DASHBOARD_SSH_KEY is absent', async () => {
284
+ delete process.env.DASHBOARD_SSH_KEY
285
+
286
+ const {spawn, capturedCmd} = makeCapturingLogsSpawn(0)
287
+
288
+ await streamDashboardLogs({host: 'dashboard.fro.bot', service: 'dashboard', tail: 100, allowCi: false}, spawn)
289
+
290
+ const cmd = capturedCmd()
291
+ expect(cmd.indexOf('-i')).toBe(-1)
292
+ expect(cmd.indexOf('IdentitiesOnly=yes')).toBe(-1)
293
+ })
294
+
295
+ it('cleans up the temp key file after the SSH command completes', async () => {
296
+ const {statSync} = await import('node:fs')
297
+ process.env.DASHBOARD_SSH_KEY = '-----BEGIN OPENSSH PRIVATE KEY-----\nfakekey\n-----END OPENSSH PRIVATE KEY-----\n'
298
+
299
+ let capturedKeyPath: string | undefined
300
+ const capturingSpawn: LogsSpawnFn = (cmd, _opts) => {
301
+ const iIdx = cmd.indexOf('-i')
302
+ if (iIdx !== -1) capturedKeyPath = cmd[iIdx + 1]
303
+ return {exited: Promise.resolve(0)}
304
+ }
305
+
306
+ await streamDashboardLogs(
307
+ {host: 'dashboard.fro.bot', service: 'dashboard', tail: 100, allowCi: false},
308
+ capturingSpawn,
309
+ )
310
+
311
+ expect(capturedKeyPath).toBeTruthy()
312
+ const keyPath = capturedKeyPath
313
+ if (keyPath) {
314
+ expect(() => statSync(keyPath)).toThrow()
315
+ }
316
+ })
317
+ })
@@ -0,0 +1,180 @@
1
+ import type {goke} from 'goke'
2
+
3
+ import {z} from 'zod'
4
+
5
+ import {buildKnownHostsArgs} from '../../lib/known-hosts'
6
+ import {buildIdentityArgs} from '../../lib/ssh-identity'
7
+ import {validateDashboardHost} from './host'
8
+
9
+ declare const process: {
10
+ env: Record<string, string | undefined>
11
+ exitCode?: number
12
+ stderr: {write: (msg: string) => void}
13
+ }
14
+
15
+ const COMPOSE_PROJECT_DIR = '/opt/dashboard'
16
+ const SENSITIVE_WARNING =
17
+ 'Warning: Logs may contain database passwords, app secrets, or user data. Treat output as sensitive; do not capture in shared logs or chat.'
18
+
19
+ export const VALID_SERVICES = ['dashboard', 'caddy'] as const
20
+
21
+ export type ValidService = (typeof VALID_SERVICES)[number]
22
+
23
+ // ─── Pure helpers ─────────────────────────────────────────────────────────────
24
+
25
+ export function validateService(service: string): asserts service is ValidService {
26
+ if (!VALID_SERVICES.includes(service as ValidService)) {
27
+ throw new Error(`Invalid service "${service}". Valid services: ${VALID_SERVICES.join(', ')}`)
28
+ }
29
+ }
30
+
31
+ // ─── Injectable spawn type ────────────────────────────────────────────────────
32
+
33
+ export type LogsSpawnFn = (
34
+ cmd: string[],
35
+ opts: {env: Record<string, string>; stdout: 'inherit'; stderr: 'inherit'},
36
+ ) => {
37
+ exited: Promise<number>
38
+ }
39
+
40
+ export interface StreamLogsOpts {
41
+ host: string
42
+ service: string
43
+ tail: number
44
+ allowCi: boolean
45
+ }
46
+
47
+ export interface StreamLogsResult {
48
+ refused: boolean
49
+ exitCode?: number
50
+ }
51
+
52
+ function defaultLogsSpawn(
53
+ cmd: string[],
54
+ opts: {env: Record<string, string>; stdout: 'inherit'; stderr: 'inherit'},
55
+ ): {exited: Promise<number>} {
56
+ return Bun.spawn(cmd, opts)
57
+ }
58
+
59
+ // NOTE: dashboard logs is intentionally CLI-only and NOT in the MCP allowlist.
60
+ // Logs may contain sensitive data (DB passwords, app secrets, user data).
61
+ export async function streamDashboardLogs(
62
+ opts: StreamLogsOpts,
63
+ spawn: LogsSpawnFn = defaultLogsSpawn,
64
+ printOut?: (msg: string) => void,
65
+ printErr?: (msg: string) => void,
66
+ ): Promise<StreamLogsResult> {
67
+ // Validate service at the top so direct callers cannot bypass the guard.
68
+ validateService(opts.service)
69
+
70
+ const isCI = process.env.CI === 'true'
71
+
72
+ if (isCI && !opts.allowCi) {
73
+ const msg = 'Refusing to stream logs in CI without --allow-ci. Logs may contain sensitive credentials or user data.'
74
+ if (printOut) {
75
+ printOut(msg)
76
+ } else {
77
+ console.log(msg)
78
+ }
79
+
80
+ return {refused: true}
81
+ }
82
+
83
+ // Warn on every run — logs are sensitive regardless of context
84
+ if (printErr) {
85
+ printErr(SENSITIVE_WARNING)
86
+ } else {
87
+ console.error(SENSITIVE_WARNING)
88
+ }
89
+
90
+ validateDashboardHost(opts.host)
91
+
92
+ const {args: identityArgs, cleanup} = buildIdentityArgs(process.env.DASHBOARD_SSH_KEY)
93
+
94
+ const sshCmd = [
95
+ 'ssh',
96
+ '-o',
97
+ 'BatchMode=yes',
98
+ '-o',
99
+ 'ConnectTimeout=10',
100
+ '-o',
101
+ 'StrictHostKeyChecking=yes',
102
+ ...buildKnownHostsArgs(),
103
+ ...identityArgs,
104
+ `root@${opts.host}`,
105
+ `docker compose --project-directory ${COMPOSE_PROJECT_DIR} logs --no-color --tail=${opts.tail} ${opts.service}`,
106
+ ]
107
+
108
+ const env: Record<string, string> = {
109
+ PATH: process.env.PATH ?? '/usr/bin:/bin',
110
+ HOME: process.env.HOME ?? '/tmp',
111
+ ...(process.env.SSH_AUTH_SOCK ? {SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK} : {}),
112
+ }
113
+
114
+ let exitCode: number
115
+ try {
116
+ const child = spawn(sshCmd, {env, stdout: 'inherit', stderr: 'inherit'})
117
+ exitCode = await child.exited
118
+ } finally {
119
+ cleanup()
120
+ }
121
+
122
+ return {refused: false, exitCode}
123
+ }
124
+
125
+ // ─── Command registration ─────────────────────────────────────────────────────
126
+
127
+ export function registerDashboardLogs(cli: ReturnType<typeof goke>): void {
128
+ cli
129
+ .command('dashboard logs [service]', 'Stream logs from a dashboard service via SSH and docker compose.')
130
+ .option('--tail [n]', z.number().default(100).describe('Number of log lines to tail from each service.'))
131
+ .option(
132
+ '--allow-ci',
133
+ z
134
+ .boolean()
135
+ .default(false)
136
+ .describe('Allow log streaming in CI environments. Logs may contain sensitive credentials.'),
137
+ )
138
+ .option(
139
+ '--key [key]',
140
+ z
141
+ .string()
142
+ .describe('Environment variable name holding the SSH host. Falls back to DASHBOARD_DOMAIN when omitted.'),
143
+ )
144
+ .action(async (service, options) => {
145
+ const targetService = (service as string | undefined) ?? 'dashboard'
146
+
147
+ try {
148
+ validateService(targetService)
149
+ } catch (error) {
150
+ console.error(error instanceof Error ? error.message : String(error))
151
+ process.exitCode = 1
152
+ return
153
+ }
154
+
155
+ const hostEnvKey = options.key ?? 'DASHBOARD_DOMAIN'
156
+ const host = process.env[hostEnvKey]
157
+
158
+ if (!host) {
159
+ console.error(
160
+ 'Dashboard host not set. Export DASHBOARD_DOMAIN or pass --key <env-name> pointing to a set variable.',
161
+ )
162
+ process.exitCode = 1
163
+ return
164
+ }
165
+
166
+ const tail = typeof options.tail === 'number' ? options.tail : 100
167
+ const allowCi = options.allowCi === true
168
+
169
+ const result = await streamDashboardLogs({host, service: targetService, tail, allowCi})
170
+
171
+ if (result.refused) {
172
+ process.exitCode = 1
173
+ return
174
+ }
175
+
176
+ if (result.exitCode !== 0) {
177
+ process.exitCode = result.exitCode ?? 1
178
+ }
179
+ })
180
+ }