storyshelf 0.3.2 → 0.5.3

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,462 @@
1
+ #!/usr/bin/env node
2
+ import "node:path";
3
+ import "node:url";
4
+ import.meta.url;
5
+ import { TERRAFORM_REQUIRED_VERSION } from "./terraform-aws.js";
6
+ //#region src/commands/server/terraform-azure.ts
7
+ function header() {
8
+ return `# Generated by \`storyshelf server init --target azure\`. Do not edit by hand;\n# re-run the scaffold or edit the generator in @storyshelf/cli.\n\n`;
9
+ }
10
+ function generateAzureVersions() {
11
+ return `${header()}terraform {
12
+ required_version = "${TERRAFORM_REQUIRED_VERSION}"
13
+
14
+ required_providers {
15
+ azurerm = {
16
+ source = "hashicorp/azurerm"
17
+ version = ">= 4.0"
18
+ }
19
+ azuread = {
20
+ source = "hashicorp/azuread"
21
+ version = ">= 3.0"
22
+ }
23
+ random = {
24
+ source = "hashicorp/random"
25
+ version = ">= 3.0"
26
+ }
27
+ }
28
+ }
29
+
30
+ provider "azurerm" {
31
+ features {}
32
+ }
33
+ `;
34
+ }
35
+ function generateAzureVariables() {
36
+ return `${header()}variable "project" {
37
+ description = "Project slug, used as a name prefix for all resources."
38
+ type = string
39
+ }
40
+
41
+ variable "location" {
42
+ description = "Azure region for all resources."
43
+ type = string
44
+ default = "eastus"
45
+ }
46
+
47
+ variable "queue_backend" {
48
+ description = "Capture queue backend: Storage Queues or Service Bus."
49
+ type = string
50
+ default = "storage-queues"
51
+
52
+ validation {
53
+ condition = contains(["storage-queues", "service-bus"], var.queue_backend)
54
+ error_message = "queue_backend must be storage-queues or service-bus."
55
+ }
56
+ }
57
+
58
+ variable "domain_name" {
59
+ description = "Public domain for the app (DNS zone + records). Empty skips DNS."
60
+ type = string
61
+ default = ""
62
+ }
63
+
64
+ variable "entra_tenant_id" {
65
+ description = "Entra tenant ID for the app registration. Empty skips identity."
66
+ type = string
67
+ default = ""
68
+ }
69
+ `;
70
+ }
71
+ function generateAzureMain() {
72
+ return `${header()}# One resource group per project. Storage account names allow only
73
+ # lowercase alphanumerics, so alphanum is the sanitized prefix.
74
+ resource "azurerm_resource_group" "main" {
75
+ name = "\${local.slug}-rg"
76
+ location = var.location
77
+ }
78
+
79
+ locals {
80
+ slug = lower(var.project)
81
+ alphanum = substr(replace(local.slug, "/[^a-z0-9]/", ""), 0, 16)
82
+ }
83
+ `;
84
+ }
85
+ function generateAzureMonitoring() {
86
+ return `${header()}resource "azurerm_log_analytics_workspace" "main" {
87
+ name = "\${local.slug}-law"
88
+ location = azurerm_resource_group.main.location
89
+ resource_group_name = azurerm_resource_group.main.name
90
+ sku = "PerGB2018"
91
+ retention_in_days = 30
92
+ }
93
+
94
+ resource "azurerm_container_app_environment" "main" {
95
+ name = "\${local.slug}-cae"
96
+ location = azurerm_resource_group.main.location
97
+ resource_group_name = azurerm_resource_group.main.name
98
+ log_analytics_workspace_id = azurerm_log_analytics_workspace.main.id
99
+ }
100
+ `;
101
+ }
102
+ function generateAzureApp() {
103
+ return `${header()}# App with external ingress. Image is a placeholder: push the
104
+ # scaffolded Dockerfile to ACR and update it before applying.
105
+ resource "azurerm_container_app" "app" {
106
+ name = "\${local.slug}-app"
107
+ container_app_environment_id = azurerm_container_app_environment.main.id
108
+ resource_group_name = azurerm_resource_group.main.name
109
+ revision_mode = "Single"
110
+
111
+ template {
112
+ container {
113
+ name = "app"
114
+ image = "storyshelf:latest"
115
+ cpu = 1
116
+ memory = "2Gi"
117
+ }
118
+ }
119
+
120
+ ingress {
121
+ external = true
122
+ target_port = 3000
123
+
124
+ traffic_weight {
125
+ latest_revision = true
126
+ percentage = 100
127
+ }
128
+ }
129
+ }
130
+ `;
131
+ }
132
+ function generateAzureWorker() {
133
+ return `${header()}# Worker polls the capture queue and renders with Playwright.
134
+ # No ingress: it only makes outbound calls (queue, database, storage).
135
+ resource "azurerm_container_app" "worker" {
136
+ name = "\${local.slug}-worker"
137
+ container_app_environment_id = azurerm_container_app_environment.main.id
138
+ resource_group_name = azurerm_resource_group.main.name
139
+ revision_mode = "Single"
140
+
141
+ template {
142
+ min_replicas = 1
143
+
144
+ container {
145
+ name = "worker"
146
+ image = "storyshelf-worker:latest"
147
+ cpu = 2
148
+ memory = "4Gi"
149
+ }
150
+ }
151
+ }
152
+ `;
153
+ }
154
+ function generateAzureDatabase() {
155
+ return `${header()}# Postgres Flexible Server, smallest burstable SKU (test-profile
156
+ # default — raise sku_name for production). The server connects with
157
+ # createPostgresDatabase({ url: <db_endpoint output> }).
158
+ resource "random_password" "db" {
159
+ length = 32
160
+ special = true
161
+ }
162
+
163
+ resource "azurerm_postgresql_flexible_server" "main" {
164
+ name = "\${local.slug}-db"
165
+ resource_group_name = azurerm_resource_group.main.name
166
+ location = azurerm_resource_group.main.location
167
+ version = "16"
168
+ administrator_login = "shelfadmin"
169
+ administrator_password = random_password.db.result
170
+ storage_mb = 32768
171
+ sku_name = "B_Standard_B1ms"
172
+ backup_retention_days = 7
173
+ }
174
+
175
+ resource "azurerm_postgresql_flexible_server_firewall_rule" "azure_services" {
176
+ name = "allow-azure-services"
177
+ server_id = azurerm_postgresql_flexible_server.main.id
178
+ start_ip_address = "0.0.0.0"
179
+ end_ip_address = "0.0.0.0"
180
+ }
181
+
182
+ resource "azurerm_postgresql_flexible_server_database" "shelf" {
183
+ name = "shelf"
184
+ server_id = azurerm_postgresql_flexible_server.main.id
185
+ charset = "UTF8"
186
+ collation = "en_US.utf8"
187
+ }
188
+ `;
189
+ }
190
+ function generateAzureStorage() {
191
+ return `${header()}# Blob container for storybook bundles + the Storage Queues
192
+ # backend (created only when var.queue_backend selects it). The queue
193
+ # name matches the scaffolded server default ("capture-jobs").
194
+ resource "azurerm_storage_account" "main" {
195
+ name = "\${local.alphanum}shlf"
196
+ resource_group_name = azurerm_resource_group.main.name
197
+ location = azurerm_resource_group.main.location
198
+ account_tier = "Standard"
199
+ account_replication_type = "LRS"
200
+ min_tls_version = "TLS1_2"
201
+ }
202
+
203
+ resource "azurerm_storage_container" "storybook" {
204
+ name = "storybook"
205
+ storage_account_id = azurerm_storage_account.main.id
206
+ }
207
+
208
+ resource "azurerm_storage_queue" "capture" {
209
+ count = var.queue_backend == "storage-queues" ? 1 : 0
210
+ name = "capture-jobs"
211
+ storage_account_id = azurerm_storage_account.main.id
212
+ }
213
+ `;
214
+ }
215
+ function generateAzureQueue() {
216
+ return `${header()}# Service Bus backend (created only when var.queue_backend
217
+ # selects it). max_delivery_count dead-letters poison messages to the
218
+ # built-in DLQ sub-queue — the Azure analog of the SQS + DLQ pattern.
219
+ resource "azurerm_servicebus_namespace" "main" {
220
+ count = var.queue_backend == "service-bus" ? 1 : 0
221
+ name = "\${local.slug}-sb"
222
+ location = azurerm_resource_group.main.location
223
+ resource_group_name = azurerm_resource_group.main.name
224
+ sku = "Standard"
225
+ }
226
+
227
+ resource "azurerm_servicebus_queue" "capture" {
228
+ count = var.queue_backend == "service-bus" ? 1 : 0
229
+ name = "capture-jobs"
230
+ namespace_id = azurerm_servicebus_namespace.main[0].id
231
+ max_delivery_count = 3
232
+ dead_lettering_on_message_expiration = true
233
+ }
234
+ `;
235
+ }
236
+ function generateAzureIdentity() {
237
+ return `${header()}# Microsoft Entra app registration for OIDC. Skipped entirely
238
+ # when var.entra_tenant_id is empty (use any OIDC provider instead).
239
+ data "azurerm_client_config" "current" {}
240
+
241
+ resource "azuread_application" "shelf" {
242
+ count = var.entra_tenant_id == "" ? 0 : 1
243
+ display_name = "\${var.project}-shelf"
244
+ }
245
+
246
+ resource "azuread_service_principal" "shelf" {
247
+ count = var.entra_tenant_id == "" ? 0 : 1
248
+ client_id = azuread_application.shelf[0].client_id
249
+ }
250
+ `;
251
+ }
252
+ function generateAzureSecrets() {
253
+ return `${header()}# Key Vault: session secret, OIDC secret, break-glass admin
254
+ # token, and the Postgres password. Never check these into env files.
255
+ resource "azurerm_key_vault" "main" {
256
+ name = "\${local.slug}-kv"
257
+ location = azurerm_resource_group.main.location
258
+ resource_group_name = azurerm_resource_group.main.name
259
+ tenant_id = data.azurerm_client_config.current.tenant_id
260
+ sku_name = "standard"
261
+ enable_rbac_authorization = true
262
+ soft_delete_retention_days = 7
263
+ }
264
+
265
+ resource "azurerm_key_vault_secret" "shelf_secret" {
266
+ name = "SECRET"
267
+ value = "change-me"
268
+ key_vault_id = azurerm_key_vault.main.id
269
+ }
270
+
271
+ resource "azurerm_key_vault_secret" "oidc_client_secret" {
272
+ name = "OIDC_CLIENT_SECRET"
273
+ value = "change-me"
274
+ key_vault_id = azurerm_key_vault.main.id
275
+ }
276
+
277
+ resource "azurerm_key_vault_secret" "admin_token" {
278
+ name = "ADMIN_TOKEN"
279
+ value = "change-me"
280
+ key_vault_id = azurerm_key_vault.main.id
281
+ }
282
+
283
+ resource "azurerm_key_vault_secret" "db_password" {
284
+ name = "DB_PASSWORD"
285
+ value = random_password.db.result
286
+ key_vault_id = azurerm_key_vault.main.id
287
+ }
288
+ `;
289
+ }
290
+ function generateAzureDns() {
291
+ return `${header()}# DNS zone + verification TXT + app CNAME. Skipped entirely when
292
+ # var.domain_name is empty. Hostname binding + managed TLS is a
293
+ # post-apply step (see README): the records below are its prerequisite.
294
+ resource "azurerm_dns_zone" "main" {
295
+ count = var.domain_name == "" ? 0 : 1
296
+ name = var.domain_name
297
+ resource_group_name = azurerm_resource_group.main.name
298
+ }
299
+
300
+ resource "azurerm_dns_txt_record" "verify" {
301
+ count = var.domain_name == "" ? 0 : 1
302
+ name = "asuid.app"
303
+ zone_name = azurerm_dns_zone.main[0].name
304
+ resource_group_name = azurerm_resource_group.main.name
305
+ ttl = 300
306
+
307
+ record {
308
+ value = azurerm_container_app_environment.main.custom_domain_verification_id
309
+ }
310
+ }
311
+
312
+ resource "azurerm_dns_cname_record" "app" {
313
+ count = var.domain_name == "" ? 0 : 1
314
+ name = "app"
315
+ zone_name = azurerm_dns_zone.main[0].name
316
+ resource_group_name = azurerm_resource_group.main.name
317
+ ttl = 300
318
+ record = azurerm_container_app.app.latest_revision_fqdn
319
+ }
320
+ `;
321
+ }
322
+ function generateAzureOutputs() {
323
+ return `${header()}# Outputs feed directly into the scaffolded server's env. Keys are
324
+ # a stable contract parsed by CI — do not rename (tests pin the set).
325
+ # Values are "" when the resource is not provisioned for this backend.
326
+ output "app_fqdn" {
327
+ value = azurerm_container_app.app.latest_revision_fqdn
328
+ }
329
+
330
+ output "storage_connection_string" {
331
+ value = azurerm_storage_account.main.primary_connection_string
332
+ sensitive = true
333
+ }
334
+
335
+ output "servicebus_connection_string" {
336
+ value = var.queue_backend == "service-bus" ? azurerm_servicebus_namespace.main[0].default_primary_connection_string : ""
337
+ sensitive = true
338
+ }
339
+
340
+ output "queue_name" {
341
+ value = "capture-jobs"
342
+ }
343
+
344
+ output "database_url" {
345
+ value = "postgresql://shelfadmin:\${random_password.db.result}@\${azurerm_postgresql_flexible_server.main.fqdn}:5432/shelf?sslmode=require"
346
+ sensitive = true
347
+ }
348
+
349
+ output "entra_application_id" {
350
+ value = var.entra_tenant_id == "" ? "" : azuread_application.shelf[0].client_id
351
+ }
352
+
353
+ output "entra_tenant_id" {
354
+ value = var.entra_tenant_id
355
+ }
356
+ `;
357
+ }
358
+ function generateAzureTfvarsExample() {
359
+ return `# Copy to terraform.tfvars and fill in per environment.
360
+ # CI test profile: pass a unique project per run instead —
361
+ # terraform plan -var "project=shelf-ci-$GITHUB_RUN_ID"
362
+ project = "my-storyshelf"
363
+ location = "eastus"
364
+ queue_backend = "storage-queues" # or "service-bus"
365
+ domain_name = ""
366
+ entra_tenant_id = ""
367
+ `;
368
+ }
369
+ function generateAzureEnvTable(queueBackend) {
370
+ return `| Output | Env var | Adapter |
371
+ |---|---|---|
372
+ | \`storage_connection_string\` | \`AZURE_STORAGE_CONNECTION\` | \`storage-azure\` (Blob container) |
373
+ ${queueBackend === "service-bus" ? "| `servicebus_connection_string` | `AZURE_SERVICE_BUS_CONNECTION` | `queue-azure` (service-bus) |" : "| `storage_connection_string` | `AZURE_STORAGE_CONNECTION` | `queue-azure` (storage-queues) + `storage-azure` |"}
374
+ | \`queue_name\` | (baked into scaffold as \`"capture-jobs"\`) | \`queue-azure\` |
375
+ | \`database_url\` | \`DATABASE_URL\` | \`db-postgres\` |
376
+ | \`entra_application_id\` / \`entra_tenant_id\` | \`OIDC_CLIENT_ID\` / \`OIDC_ISSUER\` (\`https://login.microsoftonline.com/{tenant}/v2.0\`) | \`auth\` (keycloak recipe) |
377
+ | Key Vault | \`SECRET\` / \`OIDC_CLIENT_SECRET\` / \`ADMIN_TOKEN\` | sessions / OIDC / bootstrap |
378
+ `;
379
+ }
380
+ function generateAzureCiProfile() {
381
+ return `## CI test profile
382
+
383
+ Smallest footprint, unique resources per run, documented destroy:
384
+
385
+ \`\`\`sh
386
+ export PROJECT="shelf-ci-$GITHUB_RUN_ID" # unique prefix per run (all names derive from it)
387
+ terraform init
388
+ terraform plan -var "project=$PROJECT" -out=tfplan
389
+ terraform apply tfplan
390
+ terraform output -json # or: npm run infra:outputs
391
+ # ... run live tests against the outputs ...
392
+ terraform destroy -var "project=$PROJECT" -auto-approve
393
+ \`\`\`
394
+
395
+ Cost notes: Postgres Flexible is the B1ms burstable SKU, Container Apps
396
+ run on consumption, and the worker scales to a single replica. Key Vault
397
+ uses 7-day soft-delete so re-running with the same project name within a
398
+ week reuses the vault (prefer a fresh unique prefix per run).
399
+ `;
400
+ }
401
+ function generateAzureReadme(project, queueBackend) {
402
+ return `# ${project} on Azure
403
+
404
+ Scaffolded by \`storyshelf server init --target azure\`.
405
+
406
+ ## Next steps
407
+
408
+ \`\`\`sh
409
+ az login
410
+ cd terraform
411
+ terraform init
412
+ terraform plan -out=tfplan # review before applying
413
+ terraform apply tfplan
414
+ \`\`\`
415
+
416
+ ## Wire outputs into env
417
+
418
+ \`\`\`sh
419
+ terraform output -json # or: npm run infra:outputs
420
+ \`\`\`
421
+
422
+ ${generateAzureEnvTable(queueBackend)}
423
+ \`\`\`sh
424
+ npm install
425
+ npm start
426
+ \`\`\`
427
+
428
+ Authenticate with \`az login\` (or a service principal / managed identity) —
429
+ never check connection strings into env files.
430
+
431
+ ## Custom domain
432
+
433
+ The scaffold creates the DNS zone plus verification records. After
434
+ applying, bind the hostname and let Container Apps issue the managed
435
+ certificate (portal, or \`az containerapp hostname add\` once the CNAME
436
+ resolves).
437
+
438
+ ${generateAzureCiProfile()}`;
439
+ }
440
+ const AZURE_FILES = [
441
+ ["terraform/versions.tf", () => generateAzureVersions()],
442
+ ["terraform/variables.tf", () => generateAzureVariables()],
443
+ ["terraform/main.tf", () => generateAzureMain()],
444
+ ["terraform/compute.tf", () => `${generateAzureMonitoring()}${generateAzureApp()}${generateAzureWorker()}`],
445
+ ["terraform/database.tf", () => generateAzureDatabase()],
446
+ ["terraform/storage.tf", () => generateAzureStorage()],
447
+ ["terraform/queue.tf", () => generateAzureQueue()],
448
+ ["terraform/identity.tf", () => generateAzureIdentity()],
449
+ ["terraform/secrets.tf", () => generateAzureSecrets()],
450
+ ["terraform/dns.tf", () => generateAzureDns()],
451
+ ["terraform/outputs.tf", () => generateAzureOutputs()],
452
+ ["terraform/terraform.tfvars.example", () => generateAzureTfvarsExample()]
453
+ ];
454
+ /** Generate every Terraform file for the Azure reference stack. */
455
+ function generateAzureTerraformFiles(options) {
456
+ const files = {};
457
+ for (const [path, generate] of AZURE_FILES) files[path] = generate(options);
458
+ files["terraform/README.md"] = generateAzureReadme(options.project, options.queueBackend);
459
+ return files;
460
+ }
461
+ //#endregion
462
+ export { generateAzureApp, generateAzureDatabase, generateAzureDns, generateAzureIdentity, generateAzureMain, generateAzureMonitoring, generateAzureOutputs, generateAzureQueue, generateAzureReadme, generateAzureSecrets, generateAzureStorage, generateAzureTerraformFiles, generateAzureTfvarsExample, generateAzureVariables, generateAzureVersions, generateAzureWorker };