@zabaca/zbc 0.1.0 → 0.2.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/bin/zbc.js CHANGED
@@ -1,2 +1,5 @@
1
1
  #!/usr/bin/env bun
2
- import('../src/index.ts')
2
+ import('../src/index.ts').catch((e) => {
3
+ console.error(e)
4
+ process.exit(1)
5
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabaca/zbc",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Zabaca stack CLI — scaffold and deploy infrastructure",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,6 +12,9 @@
12
12
  "src",
13
13
  "templates"
14
14
  ],
15
+ "scripts": {
16
+ "publish:npm": "bun publish --access public"
17
+ },
15
18
  "publishConfig": {
16
19
  "access": "public"
17
20
  },
@@ -0,0 +1,267 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { z } from 'zod'
3
+ import { defineModule } from '../../src/define-module'
4
+
5
+ const FLY_API = 'https://api.machines.dev'
6
+ const FLY_GRAPHQL = 'https://api.fly.io/graphql'
7
+ const NATS_USER = 'app'
8
+ const MACHINE_TAG = { 'managed-by': 'zbc', instance: 'nats' } as const
9
+
10
+ interface FlyApp {
11
+ id: string
12
+ name: string
13
+ organization: { slug: string }
14
+ }
15
+
16
+ interface FlyMachine {
17
+ id: string
18
+ name: string
19
+ state: string
20
+ config?: {
21
+ metadata?: Record<string, string>
22
+ }
23
+ }
24
+
25
+ async function flyFetch<T = unknown>(
26
+ path: string,
27
+ token: string,
28
+ options?: RequestInit,
29
+ ): Promise<T | null> {
30
+ const res = await fetch(`${FLY_API}${path}`, {
31
+ ...options,
32
+ headers: {
33
+ Authorization: `Bearer ${token}`,
34
+ 'Content-Type': 'application/json',
35
+ ...options?.headers,
36
+ },
37
+ })
38
+
39
+ if (res.status === 404) return null
40
+ if (!res.ok) {
41
+ const body = await res.text()
42
+ throw new Error(`Fly API ${path} failed (${res.status}): ${body}`)
43
+ }
44
+ if (res.status === 204) return null
45
+ return (await res.json()) as T
46
+ }
47
+
48
+ async function flyGraphQL<T>(
49
+ token: string,
50
+ query: string,
51
+ variables: Record<string, unknown>,
52
+ ): Promise<T> {
53
+ const res = await fetch(FLY_GRAPHQL, {
54
+ method: 'POST',
55
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
56
+ body: JSON.stringify({ query, variables }),
57
+ })
58
+ const body = (await res.json()) as { data?: T; errors?: Array<{ message: string }> }
59
+ if (body.errors?.length) {
60
+ throw new Error(`Fly GraphQL: ${body.errors.map((e) => e.message).join('; ')}`)
61
+ }
62
+ if (!body.data) throw new Error('Fly GraphQL: empty response')
63
+ return body.data
64
+ }
65
+
66
+ /**
67
+ * Fly's Machines REST API does not auto-allocate public IPs. Without this,
68
+ * <app>.fly.dev never resolves. IP allocation isn't on the Machines API yet
69
+ * — we go through GraphQL. shared_v4 is org-wide and not listed per-app,
70
+ * so we always (re-)issue the mutation; it's idempotent. v6 is per-app, so
71
+ * we only allocate if not present.
72
+ */
73
+ async function ensureIPs(appName: string, token: string): Promise<void> {
74
+ const list = await flyGraphQL<{ app: { ipAddresses: { nodes: Array<{ type: string }> } } }>(
75
+ token,
76
+ `query($name: String!) { app(name: $name) { ipAddresses { nodes { type } } } }`,
77
+ { name: appName },
78
+ )
79
+ const hasV6 = list.app.ipAddresses.nodes.some((n) => n.type === 'v6')
80
+
81
+ await flyGraphQL(
82
+ token,
83
+ `mutation($appId: ID!) { allocateIpAddress(input: {appId: $appId, type: shared_v4}) { ipAddress { address } } }`,
84
+ { appId: appName },
85
+ )
86
+ if (!hasV6) {
87
+ await flyGraphQL(
88
+ token,
89
+ `mutation($appId: ID!) { allocateIpAddress(input: {appId: $appId, type: v6}) { ipAddress { address } } }`,
90
+ { appId: appName },
91
+ )
92
+ console.log(` Allocated IPv6 for "${appName}"`)
93
+ }
94
+ }
95
+
96
+ function renderConf(): string {
97
+ return `# Managed by zbc — do not edit by hand.
98
+
99
+ http_port: 8222
100
+
101
+ websocket {
102
+ port: 8080
103
+ no_tls: true
104
+ }
105
+
106
+ authorization {
107
+ user: ${NATS_USER}
108
+ password: $NATS_PASSWORD
109
+ }
110
+
111
+ max_payload: 1MB
112
+ write_deadline: "10s"
113
+ `
114
+ }
115
+
116
+ function isManaged(machine: FlyMachine): boolean {
117
+ const md = machine.config?.metadata ?? {}
118
+ return md['managed-by'] === MACHINE_TAG['managed-by'] && md.instance === MACHINE_TAG.instance
119
+ }
120
+
121
+ export const natsServerModule = defineModule({
122
+ name: 'nats-server',
123
+ configSchema: z.object({
124
+ appName: z.string(),
125
+ flyOrg: z.string().default('personal'),
126
+ region: z.string().default('iad'),
127
+ memoryMB: z.number().default(256),
128
+ cpuKind: z.enum(['shared', 'performance']).default('shared'),
129
+ cpus: z.number().default(1),
130
+ }),
131
+ outputs: z.object({
132
+ url: z.string(),
133
+ user: z.string(),
134
+ password: z.string(),
135
+ }),
136
+ async apply(config, ctx) {
137
+ const flyToken = ctx.secrets['FLY_API_TOKEN']
138
+ if (!flyToken) throw new Error('Missing secret: FLY_API_TOKEN')
139
+
140
+ const password = ctx.secrets['NATS_PASSWORD']
141
+ if (!password) {
142
+ const generated = randomBytes(32).toString('hex')
143
+ throw new Error(
144
+ `Missing secret: NATS_PASSWORD\n` +
145
+ ` Generated one for you — add to your environment's secrets.yaml and re-run:\n\n` +
146
+ ` NATS_PASSWORD: ${generated}\n`,
147
+ )
148
+ }
149
+
150
+ let app = await flyFetch<FlyApp>(`/v1/apps/${config.appName}`, flyToken)
151
+ if (app) {
152
+ console.log(` Fly app "${config.appName}" already exists`)
153
+ } else {
154
+ app = await flyFetch<FlyApp>('/v1/apps', flyToken, {
155
+ method: 'POST',
156
+ body: JSON.stringify({ app_name: config.appName, org_slug: config.flyOrg }),
157
+ })
158
+ console.log(` Created Fly app "${config.appName}" in org "${config.flyOrg}"`)
159
+ }
160
+
161
+ await ensureIPs(config.appName, flyToken)
162
+
163
+ const machineConfig = {
164
+ image: 'nats:latest',
165
+ env: { NATS_PASSWORD: password },
166
+ files: [
167
+ {
168
+ guest_path: '/etc/nats/nats-server.conf',
169
+ raw_value: Buffer.from(renderConf(), 'utf8').toString('base64'),
170
+ },
171
+ ],
172
+ init: { cmd: ['-c', '/etc/nats/nats-server.conf'] },
173
+ services: [
174
+ {
175
+ protocol: 'tcp',
176
+ internal_port: 8080,
177
+ ports: [{ port: 443, handlers: ['tls', 'http'] }],
178
+ },
179
+ ],
180
+ checks: {
181
+ healthz: {
182
+ type: 'http',
183
+ port: 8222,
184
+ path: '/healthz',
185
+ interval: '15s',
186
+ timeout: '5s',
187
+ grace_period: '10s',
188
+ },
189
+ },
190
+ metadata: { ...MACHINE_TAG },
191
+ guest: {
192
+ cpu_kind: config.cpuKind,
193
+ cpus: config.cpus,
194
+ memory_mb: config.memoryMB,
195
+ },
196
+ }
197
+
198
+ const machines =
199
+ (await flyFetch<FlyMachine[]>(`/v1/apps/${config.appName}/machines`, flyToken)) ?? []
200
+ const managed = machines.filter(isManaged)
201
+
202
+ let machineId: string
203
+ if (managed.length === 0) {
204
+ const created = await flyFetch<FlyMachine>(`/v1/apps/${config.appName}/machines`, flyToken, {
205
+ method: 'POST',
206
+ body: JSON.stringify({
207
+ name: 'nats',
208
+ region: config.region,
209
+ config: machineConfig,
210
+ }),
211
+ })
212
+ if (!created) throw new Error('Fly machine create returned no body')
213
+ machineId = created.id
214
+ console.log(` Created machine "${created.id}" in ${config.region}`)
215
+ } else {
216
+ machineId = managed[0].id
217
+ await flyFetch<FlyMachine>(`/v1/apps/${config.appName}/machines/${machineId}`, flyToken, {
218
+ method: 'POST',
219
+ body: JSON.stringify({ config: machineConfig, region: config.region }),
220
+ })
221
+ console.log(` Updated machine "${machineId}"`)
222
+ if (managed.length > 1) {
223
+ console.warn(
224
+ ` ⚠ Found ${managed.length} machines tagged managed-by=zbc; updated first, ignored the rest`,
225
+ )
226
+ }
227
+ }
228
+
229
+ // Fly's update cycle (stop → swap config → start) auto-starts the
230
+ // machine, but the full cycle can take 60–90s. Don't call /start
231
+ // ourselves — it races the auto-start and 412s with "getting replaced".
232
+ // /wait caps at 60s server-side; poll up to ~4 minutes.
233
+ const waitURL = `/v1/apps/${config.appName}/machines/${machineId}/wait?state=started&timeout=60`
234
+ let started = false
235
+ for (let attempt = 0; attempt < 4; attempt++) {
236
+ try {
237
+ await flyFetch(waitURL, flyToken)
238
+ started = true
239
+ break
240
+ } catch (err) {
241
+ const msg = err instanceof Error ? err.message : String(err)
242
+ if (!msg.includes('(408)')) throw err
243
+ }
244
+ }
245
+ if (!started) throw new Error(`Machine "${machineId}" did not reach started state in 4m`)
246
+ console.log(` Machine "${machineId}" started`)
247
+
248
+ return {
249
+ url: `wss://${config.appName}.fly.dev`,
250
+ user: NATS_USER,
251
+ password,
252
+ }
253
+ },
254
+ async destroy(config, ctx) {
255
+ const flyToken = ctx.secrets['FLY_API_TOKEN']
256
+ if (!flyToken) throw new Error('Missing secret: FLY_API_TOKEN')
257
+
258
+ const result = await flyFetch(`/v1/apps/${config.appName}?force=true`, flyToken, {
259
+ method: 'DELETE',
260
+ })
261
+ if (result === null) {
262
+ console.log(` Fly app "${config.appName}" deleted (or did not exist)`)
263
+ } else {
264
+ console.log(` Fly app "${config.appName}" deleted`)
265
+ }
266
+ },
267
+ })
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "nats-server",
3
+ "description": "Self-hosted NATS pub/sub server on Fly.io (WebSocket, single shared cred)",
4
+ "files": [{ "path": "index.ts" }],
5
+ "dependencies": {
6
+ "zod": "^3.24.0"
7
+ },
8
+ "secrets": ["FLY_API_TOKEN", "NATS_PASSWORD"],
9
+ "signupUrl": "https://fly.io/app/sign-up",
10
+ "tokenUrl": "https://fly.io/user/personal_access_tokens",
11
+ "instructions": "Add FLY_API_TOKEN and NATS_PASSWORD to packages/infra/environments/<env>/secrets.yaml. If you don't have a NATS_PASSWORD yet, run apply once and the module will print a generated value to paste in. The module creates a single Fly Machine running nats:latest with WebSocket on wss://<appName>.fly.dev."
12
+ }