@marcusrbrown/infra 0.13.0 → 0.13.2

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.
Files changed (108) hide show
  1. package/dist/cli.js +4977 -0
  2. package/package.json +7 -3
  3. package/src/__snapshots__/cli.test.ts.snap +0 -219
  4. package/src/__test__/mcp-ctx-fixture.test.ts +0 -108
  5. package/src/__test__/mcp-ctx-fixture.ts +0 -104
  6. package/src/cli.test.ts +0 -66
  7. package/src/cli.ts +0 -43
  8. package/src/commands/cliproxy/config.test.ts +0 -475
  9. package/src/commands/cliproxy/config.ts +0 -238
  10. package/src/commands/cliproxy/deploy.test.ts +0 -181
  11. package/src/commands/cliproxy/deploy.ts +0 -157
  12. package/src/commands/cliproxy/host.test.ts +0 -73
  13. package/src/commands/cliproxy/host.ts +0 -31
  14. package/src/commands/cliproxy/index.ts +0 -21
  15. package/src/commands/cliproxy/keys.test.ts +0 -326
  16. package/src/commands/cliproxy/keys.ts +0 -201
  17. package/src/commands/cliproxy/login.test.ts +0 -415
  18. package/src/commands/cliproxy/login.ts +0 -131
  19. package/src/commands/cliproxy/models.test.ts +0 -592
  20. package/src/commands/cliproxy/models.ts +0 -237
  21. package/src/commands/cliproxy/open.test.ts +0 -132
  22. package/src/commands/cliproxy/open.ts +0 -78
  23. package/src/commands/cliproxy/setup/gh.test.ts +0 -218
  24. package/src/commands/cliproxy/setup/gh.ts +0 -250
  25. package/src/commands/cliproxy/setup/preview.test.ts +0 -159
  26. package/src/commands/cliproxy/setup/preview.ts +0 -41
  27. package/src/commands/cliproxy/setup/prompts.test.ts +0 -58
  28. package/src/commands/cliproxy/setup/prompts.ts +0 -99
  29. package/src/commands/cliproxy/setup/providers.test.ts +0 -245
  30. package/src/commands/cliproxy/setup/providers.ts +0 -136
  31. package/src/commands/cliproxy/setup/smoke-test.test.ts +0 -821
  32. package/src/commands/cliproxy/setup/smoke-test.ts +0 -223
  33. package/src/commands/cliproxy/setup/templates.test.ts +0 -357
  34. package/src/commands/cliproxy/setup/templates.ts +0 -145
  35. package/src/commands/cliproxy/setup/validation.test.ts +0 -567
  36. package/src/commands/cliproxy/setup/validation.ts +0 -209
  37. package/src/commands/cliproxy/setup/workflow-analyzer.test.ts +0 -363
  38. package/src/commands/cliproxy/setup/workflow-analyzer.ts +0 -136
  39. package/src/commands/cliproxy/setup.test.ts +0 -2366
  40. package/src/commands/cliproxy/setup.ts +0 -809
  41. package/src/commands/cliproxy/shared.test.ts +0 -118
  42. package/src/commands/cliproxy/shared.ts +0 -84
  43. package/src/commands/cliproxy/status.test.ts +0 -1157
  44. package/src/commands/cliproxy/status.ts +0 -597
  45. package/src/commands/dashboard/deploy.test.ts +0 -215
  46. package/src/commands/dashboard/deploy.ts +0 -135
  47. package/src/commands/dashboard/host.test.ts +0 -79
  48. package/src/commands/dashboard/host.ts +0 -33
  49. package/src/commands/dashboard/index.ts +0 -13
  50. package/src/commands/dashboard/logs.test.ts +0 -317
  51. package/src/commands/dashboard/logs.ts +0 -180
  52. package/src/commands/dashboard/status.test.ts +0 -708
  53. package/src/commands/dashboard/status.ts +0 -293
  54. package/src/commands/gateway/backup.test.ts +0 -426
  55. package/src/commands/gateway/backup.ts +0 -205
  56. package/src/commands/gateway/deploy.test.ts +0 -491
  57. package/src/commands/gateway/deploy.ts +0 -173
  58. package/src/commands/gateway/host.test.ts +0 -89
  59. package/src/commands/gateway/host.ts +0 -33
  60. package/src/commands/gateway/index.ts +0 -17
  61. package/src/commands/gateway/logs.test.ts +0 -263
  62. package/src/commands/gateway/logs.ts +0 -160
  63. package/src/commands/gateway/restore.test.ts +0 -650
  64. package/src/commands/gateway/restore.ts +0 -308
  65. package/src/commands/gateway/status.test.ts +0 -755
  66. package/src/commands/gateway/status.ts +0 -255
  67. package/src/commands/keeweb/deploy.test.ts +0 -177
  68. package/src/commands/keeweb/deploy.ts +0 -191
  69. package/src/commands/keeweb/index.ts +0 -11
  70. package/src/commands/keeweb/open.test.ts +0 -54
  71. package/src/commands/keeweb/open.ts +0 -30
  72. package/src/commands/keeweb/status.test.ts +0 -509
  73. package/src/commands/keeweb/status.ts +0 -359
  74. package/src/commands/mcp.test.ts +0 -260
  75. package/src/commands/mcp.ts +0 -58
  76. package/src/commands/status.test.ts +0 -222
  77. package/src/commands/status.ts +0 -161
  78. package/src/commands/umami/deploy.test.ts +0 -202
  79. package/src/commands/umami/deploy.ts +0 -132
  80. package/src/commands/umami/host.test.ts +0 -79
  81. package/src/commands/umami/host.ts +0 -33
  82. package/src/commands/umami/index.ts +0 -13
  83. package/src/commands/umami/logs.test.ts +0 -191
  84. package/src/commands/umami/logs.ts +0 -163
  85. package/src/commands/umami/status.test.ts +0 -633
  86. package/src/commands/umami/status.ts +0 -285
  87. package/src/commands/vpn/client.test.ts +0 -949
  88. package/src/commands/vpn/client.ts +0 -467
  89. package/src/commands/vpn/deploy.test.ts +0 -208
  90. package/src/commands/vpn/deploy.ts +0 -143
  91. package/src/commands/vpn/host.test.ts +0 -89
  92. package/src/commands/vpn/host.ts +0 -36
  93. package/src/commands/vpn/index.ts +0 -15
  94. package/src/commands/vpn/logs.test.ts +0 -234
  95. package/src/commands/vpn/logs.ts +0 -136
  96. package/src/commands/vpn/peers.test.ts +0 -478
  97. package/src/commands/vpn/shared.test.ts +0 -454
  98. package/src/commands/vpn/shared.ts +0 -170
  99. package/src/commands/vpn/status.test.ts +0 -142
  100. package/src/commands/vpn/status.ts +0 -78
  101. package/src/conventions.test.ts +0 -1180
  102. package/src/lib/action-ctx.ts +0 -25
  103. package/src/lib/known-hosts.test.ts +0 -192
  104. package/src/lib/known-hosts.ts +0 -76
  105. package/src/lib/redact.ts +0 -21
  106. package/src/lib/ssh-identity.test.ts +0 -134
  107. package/src/lib/ssh-identity.ts +0 -76
  108. /package/{src/resources/known_hosts → dist/known_hosts-tk724cp0.} +0 -0
@@ -1,132 +0,0 @@
1
- import type {goke} from 'goke'
2
-
3
- import {z} from 'zod'
4
-
5
- declare const process: {
6
- env: Record<string, string | undefined>
7
- exitCode?: number
8
- }
9
-
10
- const REPO = 'marcusrbrown/infra'
11
- const WORKFLOW_NAME = 'Deploy Umami'
12
- const WORKFLOW_URL = 'https://github.com/marcusrbrown/infra/actions/workflows/deploy-umami.yaml'
13
-
14
- type CliInstance = ReturnType<typeof goke>
15
-
16
- // ─── Env helpers ─────────────────────────────────────────────────────────────
17
-
18
- export function getUmamiDeployEnv(): Record<string, string> {
19
- const path = process.env.PATH
20
- const home = process.env.HOME
21
- const sshAuthSock = process.env.SSH_AUTH_SOCK
22
- const sshKey = process.env.UMAMI_SSH_KEY
23
-
24
- if (!path) {
25
- throw new Error('PATH is required for local deploy')
26
- }
27
-
28
- if (!home) {
29
- throw new Error('HOME is required for local deploy')
30
- }
31
-
32
- if (!sshAuthSock && !sshKey) {
33
- throw new Error('Local deploy needs an SSH context: set SSH_AUTH_SOCK (ssh-agent) or UMAMI_SSH_KEY (key from env).')
34
- }
35
-
36
- return {
37
- PATH: path,
38
- HOME: home,
39
- ...(sshAuthSock ? {SSH_AUTH_SOCK: sshAuthSock} : {}),
40
- UMAMI_DOMAIN: process.env.UMAMI_DOMAIN ?? '',
41
- UMAMI_APP_SECRET: process.env.UMAMI_APP_SECRET ?? '',
42
- UMAMI_DB_PASSWORD: process.env.UMAMI_DB_PASSWORD ?? '',
43
- UMAMI_ADMIN_PASSWORD: process.env.UMAMI_ADMIN_PASSWORD ?? '',
44
- ...(sshKey ? {UMAMI_SSH_KEY: sshKey} : {}),
45
- }
46
- }
47
-
48
- export function validateUmamiRemotePreconditions(): void {
49
- if (!Bun.which('gh')) {
50
- throw new Error('gh CLI is required for remote deploy. Install gh and run `gh auth login`.')
51
- }
52
- }
53
-
54
- // ─── Command registration ─────────────────────────────────────────────────────
55
-
56
- export function registerUmamiDeploy(cli: CliInstance): void {
57
- cli
58
- .command(
59
- 'umami deploy',
60
- 'Deploy Umami analytics. Default mode triggers the GitHub Deploy Umami workflow, while --local runs apps/umami deploy directly with Bun.',
61
- )
62
- .option(
63
- '--local',
64
- z
65
- .boolean()
66
- .default(false)
67
- .describe('Run local deployment with Bun using apps/umami instead of triggering GitHub Actions.'),
68
- )
69
- .option(
70
- '--dry-run',
71
- z
72
- .boolean()
73
- .default(false)
74
- .describe(
75
- 'Validate deploy prerequisites and print planned actions without executing local deploy or dispatching workflow.',
76
- ),
77
- )
78
- .example('# Trigger remote GitHub Actions deploy (default mode)')
79
- .example('infra umami deploy')
80
- .example('# Validate local deploy preconditions and planned command')
81
- .example('infra umami deploy --local --dry-run')
82
- .example('# Run local deploy with explicit SSH agent context')
83
- .example('infra umami deploy --local')
84
- .action(async options => {
85
- if (options.local) {
86
- const command = ['bun', 'run', '--cwd', 'apps/umami', 'deploy']
87
-
88
- if (options.dryRun) {
89
- console.log('Dry run: local umami deploy')
90
- console.log(`- command: ${command.join(' ')}`)
91
- return
92
- }
93
-
94
- const env = getUmamiDeployEnv()
95
-
96
- const child = Bun.spawn(command, {
97
- env,
98
- stdout: 'inherit',
99
- stderr: 'inherit',
100
- })
101
-
102
- const exitCode = await child.exited
103
- if (exitCode !== 0) {
104
- throw new Error(`Local deploy failed with exit code ${exitCode}`)
105
- }
106
-
107
- return
108
- }
109
-
110
- validateUmamiRemotePreconditions()
111
-
112
- if (options.dryRun) {
113
- console.log('Dry run: remote umami deploy')
114
- console.log(`- command: gh workflow run "${WORKFLOW_NAME}" --repo ${REPO}`)
115
- console.log(`- workflow URL: ${WORKFLOW_URL}`)
116
- return
117
- }
118
-
119
- const child = Bun.spawn(['gh', 'workflow', 'run', WORKFLOW_NAME, '--repo', REPO], {
120
- stdout: 'inherit',
121
- stderr: 'inherit',
122
- })
123
-
124
- const exitCode = await child.exited
125
- if (exitCode !== 0) {
126
- throw new Error(`Failed to trigger "${WORKFLOW_NAME}" workflow (exit code ${exitCode})`)
127
- }
128
-
129
- console.log(`Workflow triggered: ${WORKFLOW_URL}`)
130
- console.log('Approve the umami environment deployment in GitHub Actions to continue.')
131
- })
132
- }
@@ -1,79 +0,0 @@
1
- import {describe, expect, it} from 'bun:test'
2
-
3
- import {validateUmamiHost} from './host'
4
-
5
- describe('validateUmamiHost', () => {
6
- it('accepts a standard FQDN', () => {
7
- expect(() => validateUmamiHost('metrics.fro.bot')).not.toThrow()
8
- expect(validateUmamiHost('metrics.fro.bot')).toBe('metrics.fro.bot')
9
- })
10
-
11
- it('accepts localhost', () => {
12
- expect(() => validateUmamiHost('localhost')).not.toThrow()
13
- })
14
-
15
- it('accepts an IPv4 address', () => {
16
- expect(() => validateUmamiHost('147.182.133.210')).not.toThrow()
17
- })
18
-
19
- it('accepts a single-character hostname', () => {
20
- expect(() => validateUmamiHost('a')).not.toThrow()
21
- })
22
-
23
- it('accepts a hostname with hyphens', () => {
24
- expect(() => validateUmamiHost('my-metrics.prod.example.com')).not.toThrow()
25
- })
26
-
27
- it('rejects a leading-hyphen value (ProxyCommand injection vector)', () => {
28
- expect(() => validateUmamiHost('-oProxyCommand=evil')).toThrow('Invalid UMAMI_DOMAIN')
29
- })
30
-
31
- it('rejects a value with shell metacharacters (semicolon)', () => {
32
- expect(() => validateUmamiHost('metrics.fro.bot;rm -rf')).toThrow('Invalid UMAMI_DOMAIN')
33
- })
34
-
35
- it('rejects a value with shell metacharacters (backtick)', () => {
36
- expect(() => validateUmamiHost('metrics.fro.bot`id`')).toThrow('Invalid UMAMI_DOMAIN')
37
- })
38
-
39
- it('rejects a value with spaces', () => {
40
- expect(() => validateUmamiHost('metrics fro.bot')).toThrow('Invalid UMAMI_DOMAIN')
41
- })
42
-
43
- it('rejects a value with an at-sign', () => {
44
- expect(() => validateUmamiHost('user@metrics.fro.bot')).toThrow('Invalid UMAMI_DOMAIN')
45
- })
46
-
47
- it('rejects an empty string', () => {
48
- expect(() => validateUmamiHost('')).toThrow('Invalid UMAMI_DOMAIN')
49
- })
50
-
51
- it('omits the rejected value entirely from the error message', () => {
52
- const longMalicious = `-oProxyCommand=${'A'.repeat(100)}`
53
- let message = ''
54
- try {
55
- validateUmamiHost(longMalicious)
56
- } catch (error) {
57
- message = error instanceof Error ? error.message : String(error)
58
- }
59
- // The value is never echoed (it may be a misdirected secret) — only the constraint is shown.
60
- expect(message).toContain('Invalid UMAMI_DOMAIN')
61
- expect(message).not.toContain('ProxyCommand')
62
- expect(message).not.toContain('AAAA')
63
- })
64
-
65
- // ── Secret value redaction ───────────────────────────────────────────────────
66
-
67
- it('does not echo the rejected value in the error message', () => {
68
- const secretValue = 'AWS_SECRET_KEY=AKIA1234567890EXAMPLE'
69
- let message = ''
70
- try {
71
- validateUmamiHost(secretValue)
72
- } catch (error) {
73
- message = error instanceof Error ? error.message : String(error)
74
- }
75
- expect(message).toContain('Invalid UMAMI_DOMAIN')
76
- expect(message).not.toContain('AKIA1234567890EXAMPLE')
77
- expect(message).not.toContain('AWS_SECRET_KEY')
78
- })
79
- })
@@ -1,33 +0,0 @@
1
- // ─── Umami host validation ────────────────────────────────────────────────────
2
- //
3
- // Validates UMAMI_DOMAIN values before they are passed as ssh argv arguments.
4
- // A value starting with `-` would be interpreted by ssh as an option flag,
5
- // enabling ProxyCommand injection and local code execution.
6
-
7
- const VALID_HOST_RE = /^[a-z\d][a-z\d.\-]*$/i
8
-
9
- /**
10
- * Validates a candidate UMAMI_DOMAIN value against a strict hostname allowlist.
11
- *
12
- * Accepts: hostnames, FQDNs, IPv4 addresses, `localhost`.
13
- * Rejects: empty strings, values starting with `-`, and anything containing
14
- * characters outside `[A-Za-z0-9.-]`.
15
- *
16
- * @throws {Error} when empty or not a valid hostname. The rejected value is
17
- * never included in the message (it may be a misdirected secret).
18
- * @returns The validated host string (unchanged).
19
- */
20
- export function validateUmamiHost(host: string): string {
21
- if (!host) {
22
- throw new Error('Invalid UMAMI_DOMAIN: value is empty')
23
- }
24
-
25
- if (!VALID_HOST_RE.test(host)) {
26
- // Do NOT echo the value — it may be a secret that was redirected via --key
27
- throw new Error(
28
- `Invalid UMAMI_DOMAIN: value is not a valid hostname (must match ${String.raw`[A-Za-z0-9][A-Za-z0-9.\-]*`})`,
29
- )
30
- }
31
-
32
- return host
33
- }
@@ -1,13 +0,0 @@
1
- import type {goke} from 'goke'
2
-
3
- import {registerUmamiDeploy} from './deploy'
4
- import {registerUmamiLogs} from './logs'
5
- import {registerUmamiStatus} from './status'
6
-
7
- export {getUmamiStatusSummary} from './status'
8
-
9
- export function registerUmamiCommands(cli: ReturnType<typeof goke>): void {
10
- registerUmamiStatus(cli)
11
- registerUmamiDeploy(cli)
12
- registerUmamiLogs(cli)
13
- }
@@ -1,191 +0,0 @@
1
- import {afterEach, beforeEach, describe, expect, it} from 'bun:test'
2
-
3
- import {streamUmamiLogs, type LogsSpawnFn, type StreamLogsOpts} from './logs'
4
-
5
- // ─── streamUmamiLogs ─────────────────────────────────────────────────────────
6
-
7
- function makeLogsSpawn(exitCode = 0): LogsSpawnFn {
8
- return (_cmd, _opts) => ({exited: Promise.resolve(exitCode)})
9
- }
10
-
11
- describe('logs command', () => {
12
- let originalCI: string | undefined
13
- let originalUmamiDomain: string | undefined
14
-
15
- beforeEach(() => {
16
- originalCI = process.env.CI
17
- originalUmamiDomain = process.env.UMAMI_DOMAIN
18
- })
19
-
20
- afterEach(() => {
21
- if (originalCI === undefined) {
22
- delete process.env.CI
23
- } else {
24
- process.env.CI = originalCI
25
- }
26
-
27
- if (originalUmamiDomain === undefined) {
28
- delete process.env.UMAMI_DOMAIN
29
- } else {
30
- process.env.UMAMI_DOMAIN = originalUmamiDomain
31
- }
32
- })
33
-
34
- it('refuses to stream logs in CI without --allow-ci', async () => {
35
- process.env.CI = 'true'
36
-
37
- const opts: StreamLogsOpts = {
38
- host: 'metrics.fro.bot',
39
- service: 'umami',
40
- tail: 100,
41
- allowCi: false,
42
- }
43
-
44
- const messages: string[] = []
45
- const result = await streamUmamiLogs(opts, makeLogsSpawn(), msg => messages.push(msg))
46
-
47
- expect(result.refused).toBe(true)
48
- expect(messages.join('')).toContain('Refusing to stream logs in CI')
49
- })
50
-
51
- it('proceeds in CI when --allow-ci is set', async () => {
52
- process.env.CI = 'true'
53
-
54
- const opts: StreamLogsOpts = {
55
- host: 'metrics.fro.bot',
56
- service: 'umami',
57
- tail: 100,
58
- allowCi: true,
59
- }
60
-
61
- const warnings: string[] = []
62
- const result = await streamUmamiLogs(opts, makeLogsSpawn(), undefined, msg => warnings.push(msg))
63
-
64
- expect(result.refused).toBe(false)
65
- expect(result.exitCode).toBe(0)
66
- })
67
-
68
- it('always emits a sensitive-data warning to stderr', async () => {
69
- delete process.env.CI
70
-
71
- const opts: StreamLogsOpts = {
72
- host: 'metrics.fro.bot',
73
- service: 'umami',
74
- tail: 100,
75
- allowCi: false,
76
- }
77
-
78
- const warnings: string[] = []
79
- await streamUmamiLogs(opts, makeLogsSpawn(), undefined, msg => warnings.push(msg))
80
-
81
- expect(warnings.join('')).toContain('sensitive')
82
- })
83
-
84
- it('rejects invalid host before spawning SSH', async () => {
85
- delete process.env.CI
86
-
87
- const opts: StreamLogsOpts = {
88
- host: '-oProxyCommand=evil',
89
- service: 'umami',
90
- tail: 100,
91
- allowCi: false,
92
- }
93
-
94
- let spawnCalled = false
95
- const spy: LogsSpawnFn = (_cmd, _opts) => {
96
- spawnCalled = true
97
- return {exited: Promise.resolve(0)}
98
- }
99
-
100
- await expect(streamUmamiLogs(opts, spy)).rejects.toThrow('Invalid UMAMI_DOMAIN')
101
- expect(spawnCalled).toBe(false)
102
- })
103
-
104
- it('returns exitCode from the SSH subprocess', async () => {
105
- delete process.env.CI
106
-
107
- const opts: StreamLogsOpts = {
108
- host: 'metrics.fro.bot',
109
- service: 'umami',
110
- tail: 50,
111
- allowCi: false,
112
- }
113
-
114
- const result = await streamUmamiLogs(opts, makeLogsSpawn(42))
115
-
116
- expect(result.refused).toBe(false)
117
- expect(result.exitCode).toBe(42)
118
- })
119
-
120
- it('accepts caddy as a valid service', async () => {
121
- delete process.env.CI
122
-
123
- const opts: StreamLogsOpts = {
124
- host: 'metrics.fro.bot',
125
- service: 'caddy',
126
- tail: 100,
127
- allowCi: false,
128
- }
129
-
130
- const result = await streamUmamiLogs(opts, makeLogsSpawn(0))
131
- expect(result.refused).toBe(false)
132
- expect(result.exitCode).toBe(0)
133
- })
134
-
135
- it('rejects an unknown service when called directly (bypassing the CLI action)', async () => {
136
- delete process.env.CI
137
-
138
- const opts: StreamLogsOpts = {
139
- host: 'metrics.fro.bot',
140
- service: 'notaservice',
141
- tail: 100,
142
- allowCi: false,
143
- }
144
-
145
- let spawnCalled = false
146
- const spy: LogsSpawnFn = (_cmd, _opts) => {
147
- spawnCalled = true
148
- return {exited: Promise.resolve(0)}
149
- }
150
-
151
- await expect(streamUmamiLogs(opts, spy)).rejects.toThrow(/Invalid service/)
152
- expect(spawnCalled).toBe(false)
153
- })
154
- })
155
-
156
- // ─── SSH command includes repo-pinned UserKnownHostsFile ─────────────────────
157
-
158
- describe('streamUmamiLogs — SSH command includes UserKnownHostsFile', () => {
159
- it('passes -o UserKnownHostsFile=<repo>/.github/known_hosts to ssh', async () => {
160
- delete process.env.CI
161
-
162
- let capturedCmd: string[] = []
163
- const spawnCapture: LogsSpawnFn = (cmd, _opts) => {
164
- capturedCmd = cmd
165
- return {exited: Promise.resolve(0)}
166
- }
167
-
168
- await streamUmamiLogs({host: 'metrics.fro.bot', service: 'umami', tail: 100, allowCi: false}, spawnCapture)
169
-
170
- const knownHostsIdx = capturedCmd.findIndex(arg => arg.startsWith('UserKnownHostsFile='))
171
- expect(knownHostsIdx).toBeGreaterThan(-1)
172
- expect(capturedCmd[knownHostsIdx - 1]).toBe('-o')
173
- expect(capturedCmd[knownHostsIdx]).toMatch(/\.github[/\\]known_hosts$/)
174
- })
175
-
176
- it('does not weaken StrictHostKeyChecking when UserKnownHostsFile is added', async () => {
177
- delete process.env.CI
178
-
179
- let capturedCmd: string[] = []
180
- const spawnCapture: LogsSpawnFn = (cmd, _opts) => {
181
- capturedCmd = cmd
182
- return {exited: Promise.resolve(0)}
183
- }
184
-
185
- await streamUmamiLogs({host: 'metrics.fro.bot', service: 'umami', tail: 100, allowCi: false}, spawnCapture)
186
-
187
- const strictIdx = capturedCmd.findIndex(arg => arg.startsWith('StrictHostKeyChecking='))
188
- expect(strictIdx).toBeGreaterThan(-1)
189
- expect(capturedCmd[strictIdx]).toBe('StrictHostKeyChecking=yes')
190
- })
191
- })
@@ -1,163 +0,0 @@
1
- import type {goke} from 'goke'
2
-
3
- import {z} from 'zod'
4
-
5
- import {buildKnownHostsArgs} from '../../lib/known-hosts'
6
- import {validateUmamiHost} from './host'
7
-
8
- declare const process: {
9
- env: Record<string, string | undefined>
10
- exitCode?: number
11
- stderr: {write: (msg: string) => void}
12
- }
13
-
14
- const COMPOSE_PROJECT_DIR = '/opt/umami'
15
- const SENSITIVE_WARNING =
16
- 'Warning: Logs may contain database passwords, app secrets, or user data. Treat output as sensitive; do not capture in shared logs or chat.'
17
-
18
- export const VALID_SERVICES = ['umami', 'db', 'caddy'] as const
19
-
20
- export type ValidService = (typeof VALID_SERVICES)[number]
21
-
22
- // ─── Pure helpers ─────────────────────────────────────────────────────────────
23
-
24
- export function validateService(service: string): asserts service is ValidService {
25
- if (!VALID_SERVICES.includes(service as ValidService)) {
26
- throw new Error(`Invalid service "${service}". Valid services: ${VALID_SERVICES.join(', ')}`)
27
- }
28
- }
29
-
30
- // ─── Injectable spawn type ────────────────────────────────────────────────────
31
-
32
- export type LogsSpawnFn = (
33
- cmd: string[],
34
- opts: {env: Record<string, string>; stdout: 'inherit'; stderr: 'inherit'},
35
- ) => {
36
- exited: Promise<number>
37
- }
38
-
39
- export interface StreamLogsOpts {
40
- host: string
41
- service: string
42
- tail: number
43
- allowCi: boolean
44
- }
45
-
46
- export interface StreamLogsResult {
47
- refused: boolean
48
- exitCode?: number
49
- }
50
-
51
- function defaultLogsSpawn(
52
- cmd: string[],
53
- opts: {env: Record<string, string>; stdout: 'inherit'; stderr: 'inherit'},
54
- ): {exited: Promise<number>} {
55
- return Bun.spawn(cmd, opts)
56
- }
57
-
58
- export async function streamUmamiLogs(
59
- opts: StreamLogsOpts,
60
- spawn: LogsSpawnFn = defaultLogsSpawn,
61
- printOut?: (msg: string) => void,
62
- printErr?: (msg: string) => void,
63
- ): Promise<StreamLogsResult> {
64
- // Validate service at the top so direct callers cannot bypass the guard.
65
- validateService(opts.service)
66
-
67
- const isCI = process.env.CI === 'true'
68
-
69
- if (isCI && !opts.allowCi) {
70
- const msg = 'Refusing to stream logs in CI without --allow-ci. Logs may contain sensitive credentials or user data.'
71
- if (printOut) {
72
- printOut(msg)
73
- } else {
74
- console.log(msg)
75
- }
76
-
77
- return {refused: true}
78
- }
79
-
80
- // Warn on every run — logs are sensitive regardless of context
81
- if (printErr) {
82
- printErr(SENSITIVE_WARNING)
83
- } else {
84
- console.error(SENSITIVE_WARNING)
85
- }
86
-
87
- validateUmamiHost(opts.host)
88
-
89
- const sshCmd = [
90
- 'ssh',
91
- '-o',
92
- 'BatchMode=yes',
93
- '-o',
94
- 'StrictHostKeyChecking=yes',
95
- ...buildKnownHostsArgs(),
96
- `root@${opts.host}`,
97
- `docker compose --project-directory ${COMPOSE_PROJECT_DIR} logs --no-color --tail=${opts.tail} ${opts.service}`,
98
- ]
99
-
100
- const env: Record<string, string> = {
101
- PATH: process.env.PATH ?? '/usr/bin:/bin',
102
- HOME: process.env.HOME ?? '/tmp',
103
- ...(process.env.SSH_AUTH_SOCK ? {SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK} : {}),
104
- }
105
-
106
- const child = spawn(sshCmd, {env, stdout: 'inherit', stderr: 'inherit'})
107
- const exitCode = await child.exited
108
-
109
- return {refused: false, exitCode}
110
- }
111
-
112
- // ─── Command registration ─────────────────────────────────────────────────────
113
-
114
- export function registerUmamiLogs(cli: ReturnType<typeof goke>): void {
115
- cli
116
- .command('umami logs [service]', 'Stream logs from an Umami service via SSH and docker compose.')
117
- .option('--tail [n]', z.number().default(100).describe('Number of log lines to tail from each service.'))
118
- .option(
119
- '--allow-ci',
120
- z
121
- .boolean()
122
- .default(false)
123
- .describe('Allow log streaming in CI environments. Logs may contain sensitive credentials.'),
124
- )
125
- .option(
126
- '--key [key]',
127
- z.string().describe('Environment variable name holding the SSH host. Falls back to UMAMI_DOMAIN when omitted.'),
128
- )
129
- .action(async (service, options) => {
130
- const targetService = (service as string | undefined) ?? 'umami'
131
-
132
- try {
133
- validateService(targetService)
134
- } catch (error) {
135
- console.error(error instanceof Error ? error.message : String(error))
136
- process.exitCode = 1
137
- return
138
- }
139
-
140
- const hostEnvKey = options.key ?? 'UMAMI_DOMAIN'
141
- const host = process.env[hostEnvKey]
142
-
143
- if (!host) {
144
- console.error('Umami host not set. Export UMAMI_DOMAIN or pass --key <env-name> pointing to a set variable.')
145
- process.exitCode = 1
146
- return
147
- }
148
-
149
- const tail = typeof options.tail === 'number' ? options.tail : 100
150
- const allowCi = options.allowCi === true
151
-
152
- const result = await streamUmamiLogs({host, service: targetService, tail, allowCi})
153
-
154
- if (result.refused) {
155
- process.exitCode = 1
156
- return
157
- }
158
-
159
- if (result.exitCode !== 0) {
160
- process.exitCode = result.exitCode ?? 1
161
- }
162
- })
163
- }