@zabaca/zbc 0.12.0 → 0.14.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/package.json +6 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/init.ts +1 -0
  5. package/src/engine/apply.ts +60 -21
  6. package/src/engine/destroy.ts +183 -14
  7. package/src/engine/discover.ts +1 -1
  8. package/src/engine/resolve.ts +56 -11
  9. package/src/utils/copy-template.ts +10 -0
  10. package/templates/apps/inbox/package.json +4 -2
  11. package/templates/apps/inbox/tsconfig.json +3 -1
  12. package/templates/apps/inbox/worker/api.ts +197 -0
  13. package/templates/apps/inbox/worker/commands.ts +299 -0
  14. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  15. package/templates/apps/inbox/worker/index.ts +15 -202
  16. package/templates/apps/inbox/worker/mcp.ts +49 -100
  17. package/templates/apps/walgit/CONTEXT.md +135 -0
  18. package/templates/apps/walgit/Dockerfile +40 -18
  19. package/templates/apps/walgit/README.md +518 -55
  20. package/templates/apps/walgit/e2e/README.md +100 -6
  21. package/templates/apps/walgit/e2e/harness.ts +262 -1
  22. package/templates/apps/walgit/e2e/live.ts +588 -0
  23. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  24. package/templates/apps/walgit/e2e/suite.ts +5 -5
  25. package/templates/apps/walgit/examples/watch.ts +209 -0
  26. package/templates/apps/walgit/package.json +12 -3
  27. package/templates/apps/walgit/registry.json +6 -11
  28. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  29. package/templates/apps/walgit/shared/container-env.ts +114 -0
  30. package/templates/apps/walgit/shared/credentials.ts +81 -0
  31. package/templates/apps/walgit/shared/events.ts +277 -0
  32. package/templates/apps/walgit/shared/landing.ts +1241 -0
  33. package/templates/apps/walgit/shared/llms.ts +463 -0
  34. package/templates/apps/walgit/shared/outbox.ts +266 -0
  35. package/templates/apps/walgit/shared/policy.ts +59 -0
  36. package/templates/apps/walgit/shared/protocol.ts +197 -0
  37. package/templates/apps/walgit/shared/provenance.ts +154 -0
  38. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  39. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  40. package/templates/apps/walgit/src/announce-main.ts +37 -0
  41. package/templates/apps/walgit/src/announce.ts +98 -0
  42. package/templates/apps/walgit/src/append-only.ts +112 -0
  43. package/templates/apps/walgit/src/cache.ts +172 -0
  44. package/templates/apps/walgit/src/cli.ts +493 -0
  45. package/templates/apps/walgit/src/compact.ts +25 -23
  46. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  47. package/templates/apps/walgit/src/expire.ts +248 -0
  48. package/templates/apps/walgit/src/gc.ts +8 -16
  49. package/templates/apps/walgit/src/git-backend.ts +29 -0
  50. package/templates/apps/walgit/src/git.ts +78 -0
  51. package/templates/apps/walgit/src/hook-main.ts +259 -17
  52. package/templates/apps/walgit/src/hooks.ts +4 -3
  53. package/templates/apps/walgit/src/http.ts +237 -45
  54. package/templates/apps/walgit/src/instructions.ts +240 -0
  55. package/templates/apps/walgit/src/keys.ts +126 -0
  56. package/templates/apps/walgit/src/limits.ts +158 -0
  57. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  58. package/templates/apps/walgit/src/materialize.ts +48 -40
  59. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  60. package/templates/apps/walgit/src/orphans.ts +2 -5
  61. package/templates/apps/walgit/src/pending.ts +201 -0
  62. package/templates/apps/walgit/src/push-cert.ts +254 -0
  63. package/templates/apps/walgit/src/push.ts +233 -46
  64. package/templates/apps/walgit/src/reconcile.ts +5 -8
  65. package/templates/apps/walgit/src/repo.ts +22 -77
  66. package/templates/apps/walgit/src/server.ts +148 -26
  67. package/templates/apps/walgit/src/signers.ts +577 -0
  68. package/templates/apps/walgit/src/store-env.ts +5 -4
  69. package/templates/apps/walgit/src/store.ts +47 -24
  70. package/templates/apps/walgit/src/usage.ts +404 -0
  71. package/templates/apps/walgit/src/verify.ts +171 -0
  72. package/templates/apps/walgit/src/wal-index.ts +189 -11
  73. package/templates/apps/walgit/tsconfig.json +8 -2
  74. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  75. package/templates/apps/walgit/worker/events-do.ts +259 -0
  76. package/templates/apps/walgit/worker/index.ts +572 -0
  77. package/templates/apps/walgit/wrangler.jsonc +95 -0
  78. package/templates/apps/warehouse/package.json +1 -1
  79. package/templates/infra/modules/cloudflare/index.ts +93 -67
  80. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  81. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  82. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  83. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  84. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  85. package/templates/infra/modules/cloudflare-token/index.ts +10 -30
  86. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  87. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  88. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  89. package/templates/infra/modules/fly/index.ts +158 -35
  90. package/templates/infra/modules/host-file/index.ts +6 -7
  91. package/templates/infra/modules/provision-core/index.ts +21 -15
  92. package/templates/infra/modules/r2/index.ts +38 -55
  93. package/templates/infra/modules/r2/registry.json +1 -1
  94. package/templates/infra/modules/remote-provision/index.ts +1 -3
  95. package/templates/infra/modules/turso/index.ts +45 -7
  96. package/templates/infra/modules/vm-provision/index.ts +10 -3
  97. package/templates/infra/package.json +1 -1
  98. package/templates/infra/src/context.ts +115 -0
  99. package/templates/infra/src/define-module.ts +8 -2
  100. package/templates/infra/src/index.ts +11 -1
  101. package/templates/infra/src/types.ts +72 -3
  102. package/src/commands/add-registry.test.ts +0 -92
  103. package/src/commands/secret.test.ts +0 -717
  104. package/src/commands/vendor-mode.test.ts +0 -183
  105. package/src/infra-types.ts +0 -38
  106. package/src/utils/subtree.test.ts +0 -127
  107. package/templates/apps/inbox/worker/send-op.ts +0 -174
  108. package/templates/apps/walgit/entrypoint.sh +0 -59
  109. package/templates/apps/walgit/fly.toml +0 -52
  110. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  111. package/templates/apps/walgit/sshd_config +0 -38
@@ -1,183 +0,0 @@
1
- import { afterEach, describe, expect, test } from 'bun:test'
2
- import { execSync, spawnSync } from 'node:child_process'
3
- import * as fs from 'node:fs'
4
- import * as os from 'node:os'
5
- import * as path from 'node:path'
6
-
7
- /**
8
- * End-to-end tests for subtree (vendor) mode, spawning the real CLI against a
9
- * throwaway consumer repo + a local stand-in for Zabaca/zbc-core. No network:
10
- * the core "URL" is a local path and the fake module declares no dependencies.
11
- */
12
-
13
- const CLI = path.resolve(import.meta.dir, '../index.ts')
14
-
15
- const roots: string[] = []
16
- afterEach(() => {
17
- for (const r of roots.splice(0)) fs.rmSync(r, { recursive: true, force: true })
18
- })
19
-
20
- function sh(cwd: string, cmd: string): string {
21
- return execSync(cmd, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
22
- }
23
-
24
- function tmpdir(prefix: string): string {
25
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
26
- roots.push(dir)
27
- return dir
28
- }
29
-
30
- function makeRepo(dir: string): void {
31
- sh(dir, 'git init -q -b main')
32
- sh(dir, 'git config user.email t@t && git config user.name t')
33
- fs.writeFileSync(path.join(dir, '.keep'), '')
34
- sh(dir, 'git add . && git commit -qm init')
35
- }
36
-
37
- function makeCore(): string {
38
- const dir = tmpdir('zbc-core-')
39
- makeRepo(dir)
40
- fs.mkdirSync(path.join(dir, 'src'), { recursive: true })
41
- fs.writeFileSync(path.join(dir, 'src/define-module.ts'), 'export const defineModule = 1\n')
42
- fs.mkdirSync(path.join(dir, 'modules/faketool'), { recursive: true })
43
- fs.writeFileSync(path.join(dir, 'modules/faketool/index.ts'), 'export const faketool = 1\n')
44
- fs.writeFileSync(
45
- path.join(dir, 'modules/faketool/registry.json'),
46
- JSON.stringify({
47
- name: 'faketool',
48
- description: 'test module',
49
- files: [{ path: 'index.ts' }],
50
- secrets: ['FAKETOOL_TOKEN'],
51
- instructions: 'faketool post-install text',
52
- }),
53
- )
54
- sh(dir, 'git add . && git commit -qm core-content')
55
- return dir
56
- }
57
-
58
- function zbc(cwd: string, args: string[]): { status: number; out: string } {
59
- const res = spawnSync('bun', [CLI, ...args], { cwd, encoding: 'utf8' })
60
- return { status: res.status ?? -1, out: `${res.stdout}\n${res.stderr}` }
61
- }
62
-
63
- function initSubtree(core: string): string {
64
- const consumer = tmpdir('consumer-')
65
- makeRepo(consumer)
66
- const res = zbc(consumer, [
67
- 'init',
68
- 'testproj',
69
- '--subtree',
70
- '--core-url',
71
- core,
72
- '--core-ref',
73
- 'main',
74
- ])
75
- expect(res.status).toBe(0)
76
- return consumer
77
- }
78
-
79
- describe('zbc init --subtree', () => {
80
- test('vendors core at vendor/zbc and skips copying the engine into packages/infra', () => {
81
- const consumer = initSubtree(makeCore())
82
- expect(fs.existsSync(path.join(consumer, 'vendor/zbc/src/define-module.ts'))).toBe(true)
83
- expect(fs.existsSync(path.join(consumer, 'vendor/zbc/modules/faketool/index.ts'))).toBe(true)
84
- // Engine comes from the vendor tree — no copied src/, no split-repo README.
85
- expect(fs.existsSync(path.join(consumer, 'packages/infra/src'))).toBe(false)
86
- expect(fs.existsSync(path.join(consumer, 'packages/infra/README.md'))).toBe(false)
87
- // Rest of the scaffold still lands.
88
- expect(fs.existsSync(path.join(consumer, 'zbc.config.ts'))).toBe(true)
89
- expect(fs.existsSync(path.join(consumer, 'packages/infra/package.json'))).toBe(true)
90
- // zbc.config.ts must import the engine from the vendor tree — the copied
91
- // '@<project>/infra' package points at a src/ that subtree mode skips.
92
- const config = fs.readFileSync(path.join(consumer, 'zbc.config.ts'), 'utf8')
93
- expect(config).toContain("from './vendor/zbc/src/index'")
94
- expect(config).not.toContain('@testproj/infra')
95
- // Subtree bookkeeping recorded.
96
- expect(sh(consumer, 'git log --format=%B')).toContain('git-subtree-dir: vendor/zbc')
97
- })
98
-
99
- test('fresh subtree init leaves no dangling engine exports in packages/infra', () => {
100
- const consumer = initSubtree(makeCore())
101
- const pkg = JSON.parse(
102
- fs.readFileSync(path.join(consumer, 'packages/infra/package.json'), 'utf8'),
103
- ) as Record<string, unknown>
104
- // exports "." → ./src/index.ts would be unresolvable — src/ isn't copied.
105
- expect(pkg.exports).toBeUndefined()
106
- })
107
-
108
- test('brownfield repo with an existing copy-mode zbc.config.ts gets its import rewritten', () => {
109
- const core = makeCore()
110
- const consumer = tmpdir('consumer-')
111
- makeRepo(consumer)
112
- fs.writeFileSync(
113
- path.join(consumer, 'zbc.config.ts'),
114
- "import { defineConfig } from '@oldname/infra'\nexport default defineConfig({ project: 'oldname', environments: ['production'] })\n",
115
- )
116
- sh(consumer, 'git add . && git commit -qm existing-config')
117
- const res = zbc(consumer, ['init', '--subtree', '--core-url', core, '--core-ref', 'main'])
118
- expect(res.status).toBe(0)
119
- const config = fs.readFileSync(path.join(consumer, 'zbc.config.ts'), 'utf8')
120
- expect(config).toContain("from './vendor/zbc/src/index'")
121
- expect(config).not.toContain('/infra')
122
- })
123
-
124
- test('dirty tree → nonzero exit naming uncommitted changes, no vendor dir', () => {
125
- const core = makeCore()
126
- const consumer = tmpdir('consumer-')
127
- makeRepo(consumer)
128
- fs.writeFileSync(path.join(consumer, 'wip.txt'), 'x')
129
- const res = zbc(consumer, ['init', '--subtree', '--core-url', core, '--core-ref', 'main'])
130
- expect(res.status).not.toBe(0)
131
- expect(res.out).toMatch(/uncommitted/i)
132
- expect(fs.existsSync(path.join(consumer, 'vendor/zbc'))).toBe(false)
133
- })
134
- })
135
-
136
- describe('zbc add in vendor mode', () => {
137
- test('resolves the module from vendor/zbc, copies nothing, prints vendor import path', () => {
138
- const consumer = initSubtree(makeCore())
139
- const res = zbc(consumer, ['add', 'faketool', '--no-prompt'])
140
- expect(res.status).toBe(0)
141
- // Nothing vendored into packages/infra/modules — the module lives in vendor/zbc.
142
- expect(fs.existsSync(path.join(consumer, 'packages/infra/modules/faketool'))).toBe(false)
143
- expect(res.out).toContain('faketool post-install text')
144
- // Full relative path from packages/infra/environments/<env>/ — four .. to
145
- // the repo root. (A bare substring match would be satisfied by the
146
- // "already vendored at vendor/zbc/..." log line and miss an off-by-one.)
147
- expect(res.out).toContain('../../../../vendor/zbc/modules/faketool')
148
- })
149
-
150
- test('unknown module still errors clearly', () => {
151
- const consumer = initSubtree(makeCore())
152
- const res = zbc(consumer, ['add', 'no-such-module', '--no-prompt'])
153
- expect(res.status).not.toBe(0)
154
- expect(res.out).toContain('no-such-module')
155
- })
156
- })
157
-
158
- describe('zbc update', () => {
159
- test('pulls newer core commits into vendor/zbc', () => {
160
- const core = makeCore()
161
- const consumer = initSubtree(core)
162
- // Commit the init scaffold so the tree is clean for the pull.
163
- sh(consumer, 'git add . && git commit -qm scaffold')
164
-
165
- fs.mkdirSync(path.join(core, 'modules/newmod'), { recursive: true })
166
- fs.writeFileSync(path.join(core, 'modules/newmod/index.ts'), 'export const n = 1\n')
167
- sh(core, 'git add . && git commit -qm add-newmod')
168
-
169
- const res = zbc(consumer, ['update', '--core-url', core, '--core-ref', 'main'])
170
- expect(res.status).toBe(0)
171
- expect(fs.existsSync(path.join(consumer, 'vendor/zbc/modules/newmod/index.ts'))).toBe(true)
172
- })
173
-
174
- test('outside vendor mode (copy-mode project) → clear error', () => {
175
- const consumer = tmpdir('consumer-')
176
- makeRepo(consumer)
177
- // A copy-mode zbc project: config present, no vendor/zbc.
178
- fs.writeFileSync(path.join(consumer, 'zbc.config.ts'), 'export default {}\n')
179
- const res = zbc(consumer, ['update', '--core-url', makeCore(), '--core-ref', 'main'])
180
- expect(res.status).not.toBe(0)
181
- expect(res.out).toMatch(/vendor|subtree/i)
182
- })
183
- })
@@ -1,38 +0,0 @@
1
- // Mirror of packages/infra/src/types.ts. Inlined here so the published CLI
2
- // has no runtime/workspace dependency on @zbc/infra. Keep in sync.
3
- import type { z } from 'zod'
4
-
5
- export type ApplyFn<TConfig, TOutputs> = (config: TConfig, ctx: ApplyContext) => Promise<TOutputs>
6
-
7
- export type DestroyFn<TConfig> = (config: TConfig, ctx: ApplyContext) => Promise<void>
8
-
9
- export interface ApplyContext {
10
- secrets: Record<string, string>
11
- imports: Record<string, unknown>
12
- projectRoot: string
13
- }
14
-
15
- export interface ModuleDefinition<TConfig extends z.ZodType, TOutputs extends z.ZodType> {
16
- name: string
17
- configSchema: TConfig
18
- outputsSchema: TOutputs
19
- apply: ApplyFn<z.infer<TConfig>, z.infer<TOutputs>>
20
- destroy?: DestroyFn<z.infer<TConfig>>
21
- instance: (opts: InstanceOptions<TConfig>) => ModuleInstance<TOutputs>
22
- }
23
-
24
- export interface InstanceOptions<TConfig extends z.ZodType> {
25
- name: string
26
- config: z.input<TConfig>
27
- imports?: ModuleInstance[]
28
- }
29
-
30
- export interface ModuleInstance<TOutputs extends z.ZodType = z.ZodType> {
31
- name: string
32
- moduleName: string
33
- config: unknown
34
- imports: ModuleInstance[]
35
- _outputsSchema: TOutputs
36
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
- _definition: ModuleDefinition<any, TOutputs>
38
- }
@@ -1,127 +0,0 @@
1
- import { afterEach, describe, expect, test } from 'bun:test'
2
- import { execSync } from 'node:child_process'
3
- import * as fs from 'node:fs'
4
- import * as os from 'node:os'
5
- import * as path from 'node:path'
6
- import {
7
- coreRefForVersion,
8
- ensureCleanGitTree,
9
- isVendorMode,
10
- subtreeAdd,
11
- subtreePull,
12
- VENDOR_PREFIX,
13
- } from './subtree'
14
-
15
- /**
16
- * Real-git tests: a throwaway "core" repo stands in for Zabaca/zbc-core (local
17
- * path in place of the URL — git subtree accepts any repository), and a
18
- * throwaway consumer repo vendors it. No network.
19
- */
20
-
21
- const roots: string[] = []
22
- afterEach(() => {
23
- for (const r of roots.splice(0)) fs.rmSync(r, { recursive: true, force: true })
24
- })
25
-
26
- function sh(cwd: string, cmd: string): string {
27
- return execSync(cmd, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
28
- }
29
-
30
- function tmpdir(prefix: string): string {
31
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
32
- roots.push(dir)
33
- return dir
34
- }
35
-
36
- /** Init a git repo with identity + one commit so subtree has a base. */
37
- function makeRepo(dir: string): void {
38
- sh(dir, 'git init -q -b main')
39
- sh(dir, 'git config user.email t@t && git config user.name t')
40
- fs.writeFileSync(path.join(dir, '.keep'), '')
41
- sh(dir, 'git add . && git commit -qm init')
42
- }
43
-
44
- /** A fake zbc-core: src/define-module.ts + one dep-free module. */
45
- function makeCore(): string {
46
- const dir = tmpdir('zbc-core-')
47
- makeRepo(dir)
48
- fs.mkdirSync(path.join(dir, 'src'), { recursive: true })
49
- fs.writeFileSync(path.join(dir, 'src/define-module.ts'), 'export const defineModule = 1\n')
50
- fs.mkdirSync(path.join(dir, 'modules/faketool'), { recursive: true })
51
- fs.writeFileSync(path.join(dir, 'modules/faketool/index.ts'), 'export const faketool = 1\n')
52
- fs.writeFileSync(
53
- path.join(dir, 'modules/faketool/registry.json'),
54
- JSON.stringify({ name: 'faketool', description: 'test module', files: [{ path: 'index.ts' }] }),
55
- )
56
- sh(dir, 'git add . && git commit -qm core-content')
57
- return dir
58
- }
59
-
60
- describe('coreRefForVersion', () => {
61
- test('maps a CLI version to its core tag', () => {
62
- expect(coreRefForVersion('0.9.0')).toBe('zbc-core-v0.9.0')
63
- })
64
- })
65
-
66
- describe('ensureCleanGitTree', () => {
67
- test('passes on a clean tree', () => {
68
- const dir = tmpdir('clean-')
69
- makeRepo(dir)
70
- expect(() => ensureCleanGitTree(dir)).not.toThrow()
71
- })
72
-
73
- test('throws on a dirty tree, naming the offending state', () => {
74
- const dir = tmpdir('dirty-')
75
- makeRepo(dir)
76
- fs.writeFileSync(path.join(dir, 'uncommitted.txt'), 'x')
77
- expect(() => ensureCleanGitTree(dir)).toThrow(/uncommitted/i)
78
- })
79
-
80
- test('throws outside a git repository', () => {
81
- const dir = tmpdir('nogit-')
82
- expect(() => ensureCleanGitTree(dir)).toThrow(/git/i)
83
- })
84
- })
85
-
86
- describe('subtreeAdd / isVendorMode / subtreePull', () => {
87
- test('vendors core under vendor/zbc with a squash commit; isVendorMode flips', async () => {
88
- const core = makeCore()
89
- const consumer = tmpdir('consumer-')
90
- makeRepo(consumer)
91
-
92
- expect(await isVendorMode(consumer)).toBe(false)
93
- subtreeAdd(consumer, { url: core, ref: 'main' })
94
-
95
- expect(fs.existsSync(path.join(consumer, VENDOR_PREFIX, 'src/define-module.ts'))).toBe(true)
96
- expect(
97
- fs.existsSync(path.join(consumer, VENDOR_PREFIX, 'modules/faketool/registry.json')),
98
- ).toBe(true)
99
- expect(await isVendorMode(consumer)).toBe(true)
100
- // --squash bookkeeping present (subtree pull depends on it)
101
- const log = sh(consumer, 'git log --format=%B')
102
- expect(log).toContain(`git-subtree-dir: ${VENDOR_PREFIX}`)
103
- })
104
-
105
- test('subtreePull brings later core commits into the vendored copy', () => {
106
- const core = makeCore()
107
- const consumer = tmpdir('consumer-')
108
- makeRepo(consumer)
109
- subtreeAdd(consumer, { url: core, ref: 'main' })
110
-
111
- fs.mkdirSync(path.join(core, 'modules/newmod'), { recursive: true })
112
- fs.writeFileSync(path.join(core, 'modules/newmod/index.ts'), 'export const n = 1\n')
113
- sh(core, 'git add . && git commit -qm add-newmod')
114
-
115
- subtreePull(consumer, { url: core, ref: 'main' })
116
- expect(fs.existsSync(path.join(consumer, VENDOR_PREFIX, 'modules/newmod/index.ts'))).toBe(true)
117
- })
118
-
119
- test('subtreeAdd on a dirty tree throws before touching anything', () => {
120
- const core = makeCore()
121
- const consumer = tmpdir('consumer-')
122
- makeRepo(consumer)
123
- fs.writeFileSync(path.join(consumer, 'wip.txt'), 'x')
124
- expect(() => subtreeAdd(consumer, { url: core, ref: 'main' })).toThrow(/uncommitted/i)
125
- expect(fs.existsSync(path.join(consumer, VENDOR_PREFIX))).toBe(false)
126
- })
127
- })
@@ -1,174 +0,0 @@
1
- import type { Inbox } from './inbox-do'
2
- import { type MailEnv, emitWebhook, makeSnippet, newId, normalizeMsgId, sendMail } from './shared'
3
-
4
- /**
5
- * The one send operation, shared by POST /api/send and the MCP send_email
6
- * tool (a Worker cannot fetch its own routes, so this is a function, not a
7
- * self-request). Validates, dispatches now or queues for the DO alarm
8
- * (sendAt), records the outbound row, and emits the message.sent webhook.
9
- */
10
-
11
- export interface SendBody {
12
- to: string
13
- subject: string
14
- text?: string
15
- html?: string
16
- from?: string
17
- /** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
18
- inReplyTo?: string
19
- /**
20
- * ISO timestamp: instead of sending now, queue the message for the DO
21
- * alarm to dispatch at (or shortly after) this time.
22
- */
23
- sendAt?: string
24
- }
25
-
26
- export interface SendEnv extends MailEnv {
27
- DEFAULT_FROM?: string
28
- }
29
-
30
- export interface SendOutcome {
31
- status: number
32
- body: Record<string, unknown>
33
- }
34
-
35
- export async function performSend(
36
- env: SendEnv,
37
- stub: DurableObjectStub<Inbox>,
38
- body: SendBody,
39
- ): Promise<SendOutcome> {
40
- if (!body.to || !body.subject || (!body.text && !body.html)) {
41
- return { status: 400, body: { error: 'required: to, subject, and text or html' } }
42
- }
43
- const from = body.from ?? env.DEFAULT_FROM
44
- if (!from) {
45
- return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or pass from)' } }
46
- }
47
-
48
- // Email Sending only accepts whitelisted custom headers (a Message-ID of
49
- // our own is rejected), so the wire Message-ID is provider-chosen and
50
- // unknown to us. We store a synthetic one for OUR send chain; recipient
51
- // replies thread via the subject+participant fallback.
52
- const id = newId()
53
- const messageId = `${id}@${from.split('@')[1] ?? 'localhost'}`
54
- const inReplyTo = normalizeMsgId(body.inReplyTo)
55
- const text = body.text ?? ''
56
- const snippet = makeSnippet(text, body.html ?? '')
57
-
58
- // sendAt → queue for the DO alarm instead of dispatching now.
59
- if (body.sendAt !== undefined) {
60
- const at = new Date(body.sendAt)
61
- if (Number.isNaN(at.getTime())) {
62
- return { status: 400, body: { error: 'sendAt is not a valid date' } }
63
- }
64
- await stub.insert({
65
- id,
66
- status: 'scheduled',
67
- scheduled_at: at.toISOString(),
68
- direction: 'outbound',
69
- in_reply_to: inReplyTo,
70
- message_id: messageId,
71
- from_addr: from,
72
- to_addr: body.to,
73
- subject: body.subject,
74
- date: at.toISOString(),
75
- snippet,
76
- text_body: text,
77
- html_body: body.html ?? '',
78
- r2_key: '',
79
- attachments_json: '[]',
80
- size: text.length + (body.html?.length ?? 0),
81
- })
82
- return { status: 202, body: { ok: true, id, status: 'scheduled', sendAt: at.toISOString() } }
83
- }
84
-
85
- try {
86
- await sendMail(env, {
87
- from,
88
- to: body.to,
89
- subject: body.subject,
90
- text: body.text,
91
- html: body.html,
92
- inReplyTo,
93
- })
94
- } catch (err) {
95
- return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
96
- }
97
-
98
- // Record the outbound message so the inbox shows both sides of a
99
- // conversation. No raw MIME (we never see the provider's final wire form),
100
- // so r2_key stays empty and /raw 404s for these.
101
- const { threadId } = await stub.insert({
102
- id,
103
- direction: 'outbound',
104
- in_reply_to: inReplyTo,
105
- message_id: messageId,
106
- from_addr: from,
107
- to_addr: body.to,
108
- subject: body.subject,
109
- date: new Date().toISOString(),
110
- snippet,
111
- text_body: text,
112
- html_body: body.html ?? '',
113
- r2_key: '',
114
- attachments_json: '[]',
115
- size: text.length + (body.html?.length ?? 0),
116
- })
117
- await emitWebhook(env, 'message.sent', {
118
- id,
119
- threadId,
120
- from,
121
- to: body.to,
122
- subject: body.subject,
123
- snippet,
124
- direction: 'outbound',
125
- })
126
- return { status: 200, body: { ok: true, id, from, to: body.to, messageId, threadId } }
127
- }
128
-
129
- /** Send an existing draft: validate completeness, dispatch, flip to sent. */
130
- export async function performDraftSend(
131
- env: SendEnv,
132
- stub: DurableObjectStub<Inbox>,
133
- draftId: string,
134
- ): Promise<SendOutcome> {
135
- const draft = await stub.get(draftId)
136
- if (!draft || draft.status !== 'draft') return { status: 404, body: { error: 'not a draft' } }
137
- const from = draft.from_addr || env.DEFAULT_FROM
138
- if (!from) {
139
- return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or the draft from)' } }
140
- }
141
- if (!draft.to_addr || !draft.subject || (!draft.text_body && !draft.html_body)) {
142
- return { status: 400, body: { error: 'draft incomplete: needs to, subject, and text or html' } }
143
- }
144
- try {
145
- await sendMail(env, {
146
- from,
147
- to: draft.to_addr,
148
- subject: draft.subject,
149
- text: draft.text_body || undefined,
150
- html: draft.html_body || undefined,
151
- inReplyTo: draft.in_reply_to,
152
- })
153
- } catch (err) {
154
- return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
155
- }
156
- // Persist the from that was actually used (may have come from
157
- // DEFAULT_FROM), then flip the row to sent — thread resolves NOW.
158
- if (from !== draft.from_addr) await stub.updateDraft(draftId, { from_addr: from })
159
- const sent = await stub.markDraftSent(draftId, new Date().toISOString())
160
- if (!sent) return { status: 500, body: { error: 'draft vanished during send' } }
161
- await emitWebhook(env, 'message.sent', {
162
- id: draftId,
163
- threadId: sent.threadId,
164
- from,
165
- to: draft.to_addr,
166
- subject: draft.subject,
167
- snippet: draft.snippet,
168
- direction: 'outbound',
169
- })
170
- return {
171
- status: 200,
172
- body: { ok: true, id: draftId, from, to: draft.to_addr, threadId: sent.threadId },
173
- }
174
- }
@@ -1,59 +0,0 @@
1
- #!/bin/sh
2
- # walgit boot: materialize SSH identity from secrets, then supervise sshd and
3
- # the smart-HTTP server as one unit.
4
- set -eu
5
-
6
- REPOS_DIR="${WALGIT_REPOS_DIR:-/srv/walgit/repos}"
7
- mkdir -p "$REPOS_DIR"
8
- chown git:git "$REPOS_DIR"
9
-
10
- # The host key comes from a secret because the container filesystem does not
11
- # survive a machine stop. A generated-on-boot key would change on every
12
- # autostart and every client would see the SSH man-in-the-middle warning — on a
13
- # host designed to stop whenever it is idle, that is every day.
14
- if [ -n "${WALGIT_SSH_HOST_KEY:-}" ]; then
15
- printf '%s\n' "$WALGIT_SSH_HOST_KEY" > /etc/ssh/ssh_host_ed25519_key
16
- chmod 600 /etc/ssh/ssh_host_ed25519_key
17
- ssh-keygen -y -f /etc/ssh/ssh_host_ed25519_key > /etc/ssh/ssh_host_ed25519_key.pub
18
- else
19
- echo "walgit: WALGIT_SSH_HOST_KEY is unset — generating an EPHEMERAL host key." >&2
20
- echo "walgit: clients will see a changed host key after every machine stop." >&2
21
- ssh-keygen -q -t ed25519 -N '' -f /etc/ssh/ssh_host_ed25519_key
22
- fi
23
-
24
- # Every authorized key is pinned to the forced command. The client's own command
25
- # line is then never executed — it arrives as SSH_ORIGINAL_COMMAND and is parsed
26
- # by src/repo.ts, which allows exactly two git verbs and one repository name.
27
- AUTH_KEYS=/srv/walgit/.ssh/authorized_keys
28
- : > "$AUTH_KEYS"
29
- if [ -n "${WALGIT_SSH_AUTHORIZED_KEYS:-}" ]; then
30
- printf '%s\n' "$WALGIT_SSH_AUTHORIZED_KEYS" | while IFS= read -r key; do
31
- case "$key" in
32
- ''|\#*) continue ;;
33
- esac
34
- printf 'command="bun /app/src/ssh-shell.ts",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty %s\n' "$key" >> "$AUTH_KEYS"
35
- done
36
- fi
37
- chown git:git "$AUTH_KEYS"
38
- chmod 600 "$AUTH_KEYS"
39
- if [ ! -s "$AUTH_KEYS" ]; then
40
- echo "walgit: no authorized keys — SSH will refuse every client (set WALGIT_SSH_AUTHORIZED_KEYS)." >&2
41
- fi
42
-
43
- # Two processes, one machine lifetime: if either half dies the machine should
44
- # stop rather than keep serving half a git host, so each kills the other.
45
- /usr/sbin/sshd -D -e &
46
- SSHD=$!
47
- bun /app/src/server.ts &
48
- HTTP=$!
49
-
50
- term() { kill "$SSHD" "$HTTP" 2>/dev/null || true; }
51
- trap term TERM INT
52
-
53
- # Polled rather than `wait -n`, which busybox ash does not reliably provide.
54
- while kill -0 "$SSHD" 2>/dev/null && kill -0 "$HTTP" 2>/dev/null; do
55
- sleep 5
56
- done
57
- echo "walgit: a server process exited — stopping the machine." >&2
58
- term
59
- exit 1
@@ -1,52 +0,0 @@
1
- # walgit on Fly. The topology lives here, not in the zbc `fly` module — the
2
- # module only runs `fly deploy` against this file.
3
- #
4
- # The app name is a per-project identity, so an instance in a consumer's
5
- # environment overrides it with `appName`. This default is what `fly deploy`
6
- # uses if nothing does.
7
- app = "walgit"
8
- primary_region = "sjc"
9
-
10
- [build]
11
-
12
- # SSH: RAW TCP PASS-THROUGH. The absence of `handlers` is what makes it raw —
13
- # adding one would make Fly Proxy try to speak HTTP or TLS to a git client and
14
- # every connection would fail. Verified against real Fly in the walgit M0 spike
15
- # (docs/research/walgit-m0-spike/ in the zbc repository).
16
- #
17
- # A dedicated IPv4 is REQUIRED for this to be reachable at all: shared IPv4
18
- # covers ports 80/443 only, and nothing reports the difference. The instance
19
- # sets `ipv4: "dedicated"`.
20
- [[services]]
21
- protocol = "tcp"
22
- internal_port = 22
23
- auto_stop_machines = "stop"
24
- auto_start_machines = true
25
- min_machines_running = 0
26
-
27
- [[services.ports]]
28
- port = 22
29
-
30
- # smart-HTTP. Same autostop policy, so both front doors wake the same machine;
31
- # the M0 spike measured a raw-TCP cold start at ~1.35 s, which a git client
32
- # spends waiting and never notices.
33
- [[services]]
34
- protocol = "tcp"
35
- internal_port = 8080
36
- auto_stop_machines = "stop"
37
- auto_start_machines = true
38
- min_machines_running = 0
39
-
40
- [[services.ports]]
41
- port = 80
42
- handlers = ["http"]
43
- force_https = true
44
-
45
- [[services.ports]]
46
- port = 443
47
- handlers = ["tls", "http"]
48
-
49
- # No [[mounts]]. Deliberate: see the Dockerfile — the repo on disk is a cache.
50
- [[vm]]
51
- size = "shared-cpu-1x"
52
- memory = "512mb"
@@ -1,36 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * The SSH forced command.
4
- *
5
- * Every authorized key is pinned to this script (`command="..."` in
6
- * authorized_keys), so an SSH session can do exactly one thing: run one git
7
- * transport verb against one repository. The client's own command line arrives
8
- * in SSH_ORIGINAL_COMMAND and is parsed, never executed.
9
- *
10
- * git's transport is stdio: upload-pack/receive-pack speak the pack protocol
11
- * over the same stdin/stdout the SSH channel provides, which is why this
12
- * process replaces itself with git rather than proxying bytes.
13
- */
14
-
15
- import { spawnSync } from 'node:child_process'
16
- import { ensureBareRepo, parseSshCommand, resolveRepo } from './repo'
17
- import { storeFromEnv } from './store-env'
18
- import { syncRepo } from './sync'
19
-
20
- const reposDir = process.env.WALGIT_REPOS_DIR ?? '/srv/walgit/repos'
21
-
22
- try {
23
- const { service, requested } = parseSshCommand(process.env.SSH_ORIGINAL_COMMAND)
24
- const repo = ensureBareRepo(resolveRepo(reposDir, requested))
25
- // Before a byte of the pack protocol is exchanged: an upload-pack that
26
- // advertises stale refs sends the client a repository that no longer exists,
27
- // and a receive-pack negotiating against them computes its ref updates from
28
- // a state the log has already moved past.
29
- await syncRepo(storeFromEnv(), repo)
30
- const res = spawnSync(service, [repo.dir], { stdio: 'inherit' })
31
- process.exit(res.status ?? 1)
32
- } catch (err) {
33
- // Goes back over the SSH channel to the client, which prints it verbatim.
34
- process.stderr.write(`walgit: ${(err as Error).message}\n`)
35
- process.exit(1)
36
- }