@hszrdm/create-commerce 1.10.0 → 1.11.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 (38) hide show
  1. package/README.md +6 -0
  2. package/package.json +1 -1
  3. package/src/cli.mjs +20 -4
  4. package/src/upgrade.mjs +79 -4
  5. package/templates/backend/.env.example +8 -0
  6. package/templates/backend/package.json +2 -1
  7. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  8. package/templates/backend/scripts/commerce-ops.mjs +61 -2
  9. package/templates/backend/scripts/core-restore.mjs +40 -5
  10. package/templates/backend/scripts/lib/core-backup-common.mjs +91 -11
  11. package/templates/backend/scripts/production-assets/backup.sh +6 -51
  12. package/templates/backend/scripts/production-assets/deploy.sh +10 -62
  13. package/templates/backend/scripts/production-assets/install.sh +23 -195
  14. package/templates/backend/scripts/production-assets/restore.sh +17 -66
  15. package/templates/backend/src/scripts/sync-integration-runtime.ts +1 -0
  16. package/templates/storefront/package.json +5 -1
  17. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  18. package/templates/storefront/src/app/globals.css +32 -0
  19. package/templates/storefront/src/app/layout.tsx +7 -1
  20. package/templates/storefront/src/app/legal/page.tsx +3 -3
  21. package/templates/storefront/src/components/analytics.tsx +10 -8
  22. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  23. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  24. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  25. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  26. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  27. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  28. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  29. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  30. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  31. package/templates/storefront/src/lib/core/legal.ts +1 -0
  32. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  33. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  34. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  35. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  36. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  37. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  38. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
package/README.md CHANGED
@@ -73,6 +73,12 @@ reproducible production change requests.
73
73
  The updater synchronizes the canonical backend and storefront dependencies,
74
74
  their scripts and shared template files, generated deployment utilities, PM2
75
75
  configuration, and regenerates the **full transitive** `package-lock.json`.
76
+ It also synchronizes the Core's **root npm `overrides`** (Lodash, GraphQL
77
+ Tools and Nodemailer security pins), because npm uses overrides only from the
78
+ customer project's root manifest. Customer-only overrides are preserved; a
79
+ modified Core-managed override reports a conflict rather than being overwritten.
80
+ Use `npm audit --omit=dev --audit-level=high` after the lockfile refresh and
81
+ review any remaining Medusa transitive vulnerabilities before production.
76
82
  It preserves customer-only package dependencies, routes, application code,
77
83
  customized files, and secret-bearing `.env*` files. Nothing modifies the
78
84
  database, running PM2 processes, or the live deployment during this operation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -4,6 +4,8 @@ import {
4
4
  cpSync,
5
5
  existsSync,
6
6
  mkdirSync,
7
+ lstatSync,
8
+ readdirSync,
7
9
  readFileSync,
8
10
  rmSync,
9
11
  writeFileSync,
@@ -12,7 +14,7 @@ import { dirname, join, resolve } from "node:path"
12
14
  import { fileURLToPath } from "node:url"
13
15
  import { createInterface } from "node:readline/promises"
14
16
  import { stdin as input, stdout as output } from "node:process"
15
- import { generatedRootScripts, writeGeneratedManifest, upgradeFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
17
+ import { generatedRootScripts, generatedRootOverrides, writeGeneratedManifest, upgradeFromArgs, renderEcosystemConfig } from "./upgrade.mjs"
16
18
 
17
19
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..")
18
20
  const packageVersion = clean(
@@ -35,9 +37,20 @@ export async function main(argv = process.argv.slice(2)) {
35
37
 
36
38
  const destination = resolve(parsed.flags.dir || projectName)
37
39
  const force = bool(parsed.flags.force)
38
- if (existsSync(destination)) {
39
- if (!force) throw new Error(`A célkönyvtár már létezik: ${destination}. Tudatos felülíráshoz: --force`)
40
- rmSync(destination, { recursive: true, force: true })
40
+ const targetStat = lstatSync(destination, { throwIfNoEntry: false })
41
+ if (targetStat) {
42
+ if (!targetStat.isDirectory() || targetStat.isSymbolicLink()) {
43
+ throw new Error(`A cél nem egy valódi könyvtár (vagy szimbolikus link): ${destination}`)
44
+ }
45
+ // --force must NEVER destroy a customer checkout, data or secrets.
46
+ // Existing projects are updated by the non-destructive upgrade command.
47
+ if (readdirSync(destination).length > 0) {
48
+ throw new Error(
49
+ `A célkönyvtár nem üres, ezért nem írható felül: ${destination}. ` +
50
+ "Meglévő webshophoz használd a create-commerce upgrade parancsot."
51
+ )
52
+ }
53
+ if (!force) throw new Error(`A célkönyvtár már létezik: ${destination}. Üres célhoz add meg a --force kapcsolót.`)
41
54
  }
42
55
 
43
56
  const settings = await collectSettings(projectName, parsed.flags)
@@ -230,11 +243,14 @@ function configureProject(root, settings) {
230
243
  engines: { node: "22.x" },
231
244
  workspaces: ["backend", "storefront"],
232
245
  scripts: generatedRootScripts(),
246
+ overrides: generatedRootOverrides(),
233
247
  }
234
248
  writeJson(join(root, "package.json"), rootPackage)
235
249
  mkdirSync(join(root, "scripts"), { recursive: true })
236
250
  cpSync(join(root, "backend", "scripts", "commerce-ops.mjs"),
237
251
  join(root, "scripts", "commerce-ops.mjs"))
252
+ cpSync(join(root, "backend", "scripts", "commerce-instance-status.mjs"),
253
+ join(root, "scripts", "commerce-instance-status.mjs"))
238
254
  // Materialize generated operational assets before recording their baseline.
239
255
  // Future Core upgrades can then replace only unchanged, Core-owned files.
240
256
  mkdirSync(join(root, "deploy"), { recursive: true })
package/src/upgrade.mjs CHANGED
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url"
7
7
 
8
8
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..")
9
9
  const MANIFEST = "hszrdm-managed.json"
10
- const MANAGED_EXTRA_FILES = ["ecosystem.config.cjs", "scripts/commerce-ops.mjs", ...["install.sh", "deploy.sh", "backup.sh", "restore.sh"].map(name => "deploy/" + name)]
10
+ const MANAGED_EXTRA_FILES = ["ecosystem.config.cjs", "scripts/commerce-ops.mjs", "scripts/commerce-instance-status.mjs", ...["install.sh", "deploy.sh", "backup.sh", "restore.sh"].map(name => "deploy/" + name)]
11
11
  const SKIP_SEGMENTS = new Set(["node_modules", ".next", ".medusa", ".cache", ".git", "out", "static"])
12
12
  const SKIP_FILES = new Set(["package.json", "package-lock.json", ".env", ".env.production", ".env.staging", ".env.local", ".env.docker"])
13
13
 
@@ -67,13 +67,24 @@ export function renderEcosystemConfig(settings) {
67
67
  `
68
68
  }
69
69
 
70
+ // Root-level npm overrides are required to secure the full transitive dependency
71
+ // graph. npm does not inherit overrides from @hszrdm/core's package.json.
72
+ export function generatedRootOverrides() {
73
+ return {
74
+ "lodash": "4.18.1",
75
+ "@graphql-tools/utils": "12.1.0",
76
+ "nodemailer": "10.3.1",
77
+ }
78
+ }
79
+
70
80
  export function generatedRootScripts() {
71
81
  return {
72
82
  "dev:backend": "npm --workspace backend run dev",
73
83
  "dev:storefront": "npm --workspace storefront run dev",
74
84
  "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
75
- "test": "npm --workspace backend run test",
85
+ "test": "npm --workspace backend run test && npm --workspace storefront run test:addresses && npm --workspace storefront run test:stripe && npm --workspace storefront run test:company-tax",
76
86
  "build": "npm --workspace backend run verify:build && npm --workspace storefront run build",
87
+ "build:deploy": "npm --workspace backend run build && npm --workspace storefront run build",
77
88
  "verify": "npm run typecheck && npm run test && npm run build",
78
89
  "db:migrate": "npm --workspace backend run db:migrate",
79
90
  "core:init": "npm --workspace backend run core:init --",
@@ -86,6 +97,7 @@ export function generatedRootScripts() {
86
97
  "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
87
98
  "deploy:staging": "node ./scripts/commerce-ops.mjs deploy staging",
88
99
  "deploy:production": "npm run deploy:prod",
100
+ "commerce:status": "node ./scripts/commerce-instance-status.mjs",
89
101
  "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
90
102
  "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
91
103
  "backup:staging": "node ./scripts/commerce-ops.mjs backup staging",
@@ -98,12 +110,33 @@ export function generatedRootScripts() {
98
110
  }
99
111
  }
100
112
 
113
+ // A generated-project upgrade may update customer files, but must never
114
+ // traverse a symlink into an unrelated checkout, secret store or upload root.
115
+ function assertManagedTarget(root, relativePath) {
116
+ if (!relativePath || relativePath.startsWith("/") ||
117
+ relativePath.split("/").some(part => !part || part === "." || part === "..")) {
118
+ throw new Error("Invalid managed target: " + relativePath)
119
+ }
120
+ const resolvedRoot = resolve(root)
121
+ if (lstatSync(resolvedRoot, { throwIfNoEntry: false })?.isSymbolicLink()) {
122
+ throw new Error("Symlink project root is not supported for Core upgrades.")
123
+ }
124
+ let current = resolvedRoot
125
+ for (const part of relativePath.split("/")) {
126
+ current = join(current, part)
127
+ const info = lstatSync(current, { throwIfNoEntry: false })
128
+ if (info?.isSymbolicLink()) {
129
+ throw new Error("Symlink in managed upgrade path: " + relativePath)
130
+ }
131
+ }
132
+ }
133
+
101
134
  function readJson(path) { return JSON.parse(readFileSync(path, "utf8")) }
102
135
  function json(value) { return JSON.stringify(value, null, 2) + "\n" }
103
136
  function sha(data) { return createHash("sha256").update(data).digest("hex") }
104
137
  function hashFile(path) { return sha(readFileSync(path)) }
105
138
  function canonicalSource(path) {
106
- if (path === "scripts/commerce-ops.mjs") return join(PACKAGE_ROOT, "templates", "backend", "scripts", "commerce-ops.mjs")
139
+ if (path === "scripts/commerce-ops.mjs" || path === "scripts/commerce-instance-status.mjs") return join(PACKAGE_ROOT, "templates", "backend", "scripts", path.slice("scripts/".length))
107
140
  if (path.startsWith("deploy/")) return join(PACKAGE_ROOT, "templates", "backend", "scripts", "production-assets", path.slice("deploy/".length))
108
141
  return join(PACKAGE_ROOT, "templates", path)
109
142
  }
@@ -139,6 +172,13 @@ function managedPackageState(root) {
139
172
  result[path] = {
140
173
  scripts: { ...(p.scripts || {}) },
141
174
  deps: packageDeps(p),
175
+ ...(path === "package.json" ? {
176
+ // Only Core-owned pins are part of the managed baseline. Customer-only
177
+ // overrides are never owned by this generator.
178
+ overrides: Object.fromEntries(Object.keys(generatedRootOverrides())
179
+ .filter((key) => Object.prototype.hasOwnProperty.call(p.overrides || {}, key))
180
+ .map((key) => [key, p.overrides[key]])),
181
+ } : {}),
142
182
  }
143
183
  }
144
184
  return result
@@ -158,7 +198,7 @@ export function writeGeneratedManifest(root, version) {
158
198
  }
159
199
 
160
200
  function expectedPackage(path, version) {
161
- if (path === "package.json") return { scripts: generatedRootScripts() }
201
+ if (path === "package.json") return { scripts: generatedRootScripts(), overrides: generatedRootOverrides() }
162
202
  const packagePath = join(PACKAGE_ROOT, "templates", path)
163
203
  const pkg = readJson(packagePath)
164
204
  if (path === "backend/package.json") {
@@ -187,6 +227,10 @@ export function planUpgrade(root, version) {
187
227
  const canonicalPaths = managedPaths()
188
228
  const canonicalSet = new Set(canonicalPaths)
189
229
  for (const path of canonicalPaths) {
230
+ try { assertManagedTarget(root, path) } catch (error) {
231
+ conflicts.push(path + " (" + error.message + ")")
232
+ continue
233
+ }
190
234
  const source = path === "ecosystem.config.cjs" ? null : canonicalSource(path)
191
235
  const target = join(root, path)
192
236
  const metadata = path === "ecosystem.config.cjs" ? readJson(metadataPath) : null
@@ -217,6 +261,10 @@ export function planUpgrade(root, version) {
217
261
  // content is unchanged; never remove customer-modified files.
218
262
  for (const [path, previousHash] of Object.entries(previous?.files || {})) {
219
263
  if (canonicalSet.has(path)) continue
264
+ try { assertManagedTarget(root, path) } catch (error) {
265
+ conflicts.push(path + " (" + error.message + ")")
266
+ continue
267
+ }
220
268
  const target = join(root, path)
221
269
  const stat = lstatSync(target, { throwIfNoEntry: false })
222
270
  if (!stat) continue
@@ -230,6 +278,7 @@ export function planUpgrade(root, version) {
230
278
 
231
279
  const packages = {}
232
280
  for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
281
+ assertManagedTarget(root, path)
233
282
  const current = readJson(join(root, path))
234
283
  const desired = expectedPackage(path, version)
235
284
  const base = previous?.packages?.[path]
@@ -260,6 +309,25 @@ export function planUpgrade(root, version) {
260
309
  else conflicts.push(path + ":obsolete " + group + "." + key)
261
310
  }
262
311
  }
312
+ // Root npm overrides are the only reliable way to pin deeply nested
313
+ // vulnerable dependencies in generated customer shops.
314
+ if (path === "package.json") {
315
+ merged.overrides ||= {}
316
+ for (const [key, nextValue] of Object.entries(desired.overrides || {})) {
317
+ const currentValue = current.overrides?.[key]
318
+ const oldValue = base?.overrides?.[key]
319
+ // A pre-existing override with no Core-owned baseline is a customer
320
+ // choice, not a safe value to silently replace. If Core previously
321
+ // owned the key, update only when its value is still unchanged.
322
+ if (currentValue !== undefined && currentValue !== nextValue &&
323
+ (oldValue === undefined || currentValue !== oldValue)) {
324
+ conflicts.push(path + ":overrides." + key)
325
+ } else merged.overrides[key] = nextValue
326
+ }
327
+ // Do not auto-remove a key merely because it appeared in an older
328
+ // manifest: historical manifests may include unrelated customer pins.
329
+ // Unknown/custom overrides must always survive Core upgrades.
330
+ }
263
331
  const oldContent = readFileSync(join(root, path), "utf8")
264
332
  if (json(merged) !== oldContent) changes.push({ kind: "json", path, content: json(merged) })
265
333
  packages[path] = {
@@ -267,6 +335,9 @@ export function planUpgrade(root, version) {
267
335
  deps: Object.fromEntries(["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"].map(k => [
268
336
  k, Object.fromEntries(Object.keys(desired[k] || {}).map(dep => [dep, merged[k][dep]])),
269
337
  ])),
338
+ ...(path === "package.json" ? {
339
+ overrides: Object.fromEntries(Object.keys(desired.overrides || {}).map(key => [key, merged.overrides[key]])),
340
+ } : {}),
270
341
  }
271
342
  }
272
343
 
@@ -285,6 +356,10 @@ export function applyUpgrade(plan, { execute = true } = {}) {
285
356
  if (plan.conflicts.length) throw new Error("Upgrade blocked by customer changes:\n- " + plan.conflicts.join("\n- "))
286
357
  if (!execute) return plan
287
358
  const staged = [...plan.changes, { kind: "json", path: MANIFEST, content: json(plan.nextManifest) }]
359
+ // Preflight every file that can be modified, before the first write.
360
+ for (const change of staged) assertManagedTarget(plan.root, change.path)
361
+ assertManagedTarget(plan.root, "hszrdm-commerce.json")
362
+ assertManagedTarget(plan.root, "package-lock.json")
288
363
  const metadataPath = join(plan.root, "hszrdm-commerce.json")
289
364
  const metadata = readJson(metadataPath)
290
365
  metadata.core_version = plan.version
@@ -38,6 +38,8 @@ AUTH_CORS=http://localhost:3000,http://localhost:9000,http://localhost:7001
38
38
  INTEGRATION_SETTINGS_ENCRYPTION_KEY=replace-with-at-least-32-random-characters
39
39
  INTEGRATION_SETTINGS_FILE=
40
40
  # Shared inbound shipping callback secret. Required only for enabled callback-based providers.
41
+ # Security PR #53 requires 32-256 random characters; weaker configuration disables callbacks.
42
+ # Generate a unique secret per deployment: openssl rand -hex 32
41
43
  SHIPPING_WEBHOOK_SECRET=
42
44
 
43
45
  # -----------------------------------------------------------------------------
@@ -119,6 +121,8 @@ EMAIL_LOGO_URL=
119
121
  EMAIL_TRACKING_ENABLED=true
120
122
  EMAIL_TRACKING_BASE_URL=
121
123
  EMAIL_TRACKING_SECRET=
124
+ # Must contain 32-256 random characters or email callbacks are rejected (401).
125
+ # Rotate and update the sender/provider webhook configuration before deploying.
122
126
  EMAIL_WEBHOOK_SECRET=
123
127
 
124
128
  # -----------------------------------------------------------------------------
@@ -317,6 +321,8 @@ PACKETA_TIMEOUT_MS=15000
317
321
  PACKETA_DEFAULT_WEIGHT_KG=1
318
322
  PACKETA_LABEL_FORMAT=A6 on A6
319
323
  PACKETA_LANGUAGE=hu
324
+ # Signing key for signed Packeta callbacks. Confirm provider compatibility;
325
+ # raw body and timestamp are mandatory. Rotate separately from other webhook secrets.
320
326
  PACKETA_WEBHOOK_SIGNING_KEY=
321
327
 
322
328
  DPD_ENABLED=false
@@ -426,6 +432,8 @@ ARUKERESO_DEFAULT_DELIVERY_TIME=
426
432
  ARUKERESO_DEFAULT_DELIVERY_COST=
427
433
 
428
434
  FOGYASZTOBARAT_ENABLED=false
435
+ # Admin integration: paste full provider <script> snippet (legacy ID still supported)
436
+ FOGYASZTOBARAT_EMBED_CODE=
429
437
  FOGYASZTOBARAT_DATA_ID=
430
438
 
431
439
  # -----------------------------------------------------------------------------
@@ -12,6 +12,7 @@
12
12
  "start": "medusa start",
13
13
  "typecheck": "npm run env:verify && npm run prepare:project && tsc --noEmit",
14
14
  "core:init": "npm run prepare:project && medusa exec ./src/scripts/core-init.ts",
15
+ "integrations:sync": "npm run prepare:project && medusa exec ./src/scripts/sync-integration-runtime.ts",
15
16
  "core:backup": "node ./scripts/core-backup.mjs --project-dir .",
16
17
  "core:restore": "node ./scripts/core-restore.mjs --project-dir .",
17
18
  "storefront:key": "npm run prepare:project && medusa exec ./src/scripts/create-storefront-key.ts",
@@ -22,7 +23,7 @@
22
23
  "start:prod": "cd .medusa/server && medusa start"
23
24
  },
24
25
  "dependencies": {
25
- "@hszrdm/core": "1.10.0",
26
+ "@hszrdm/core": "1.11.0",
26
27
  "@medusajs/admin-sdk": "2.22.2",
27
28
  "@medusajs/cli": "2.22.2",
28
29
  "@medusajs/draft-order": "2.22.2",
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ // Read-only, credential-free inventory report for a generated HSZRDM webshop.
3
+ // Intended as a local data source for a future Commerce Manager agent.
4
+ import { existsSync, readFileSync } from "node:fs"
5
+ import { join, resolve } from "node:path"
6
+ import { pathToFileURL } from "node:url"
7
+
8
+ function readJson(path) {
9
+ return JSON.parse(readFileSync(path, "utf8"))
10
+ }
11
+
12
+ function optionalText(value) {
13
+ return typeof value === "string" && value.trim() ? value.trim() : null
14
+ }
15
+
16
+ function readRelease(path) {
17
+ if (!existsSync(path)) return {}
18
+ const allowed = new Set(["CORE_INSTANCE_ID", "CORE_RELEASE_CHANNEL", "RELEASE_SHA", "RELEASE_BUILT_AT"])
19
+ const values = {}
20
+ for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
21
+ const match = /^([A-Z_]+)=(.*)$/.exec(line)
22
+ if (match && allowed.has(match[1])) values[match[1]] = match[2]
23
+ }
24
+ return values
25
+ }
26
+
27
+ function parseOptions(argv) {
28
+ const options = { projectDir: process.cwd(), environment: null, readinessUrl: null }
29
+ for (let index = 0; index < argv.length; index++) {
30
+ const flag = argv[index]
31
+ if (flag === "--help" || flag === "-h") return { help: true }
32
+ if (!["--project-dir", "--environment", "--readiness-url"].includes(flag)) {
33
+ throw new Error("Unknown argument: " + flag)
34
+ }
35
+ const value = argv[++index]
36
+ if (!value || value.startsWith("--")) throw new Error("Missing value for " + flag)
37
+ if (flag === "--project-dir") options.projectDir = value
38
+ if (flag === "--environment") options.environment = value
39
+ if (flag === "--readiness-url") options.readinessUrl = value
40
+ }
41
+ if (options.environment && !["development", "staging", "production"].includes(options.environment)) {
42
+ throw new Error("Environment must be development, staging or production")
43
+ }
44
+ return options
45
+ }
46
+
47
+ function validatedReadinessUrl(value) {
48
+ const url = new URL(value)
49
+ if (!["http:", "https:"].includes(url.protocol) ||
50
+ !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) ||
51
+ url.username || url.password || url.search || url.hash ||
52
+ url.pathname !== "/health/ready") {
53
+ throw new Error("Readiness URL must be a credential-free loopback /health/ready endpoint")
54
+ }
55
+ return url
56
+ }
57
+
58
+ async function checkReadiness(value) {
59
+ if (!value) return { state: "not_checked", http_status: null }
60
+ const url = validatedReadinessUrl(value)
61
+ try {
62
+ const response = await fetch(url, {
63
+ method: "GET",
64
+ redirect: "error",
65
+ signal: AbortSignal.timeout(3000),
66
+ headers: { accept: "application/json" },
67
+ })
68
+ return { state: response.status === 200 ? "ready" : "unready", http_status: response.status }
69
+ } catch {
70
+ return { state: "unreachable", http_status: null }
71
+ }
72
+ }
73
+
74
+ export async function collectInstanceStatus(options = {}) {
75
+ const root = resolve(options.projectDir || process.cwd())
76
+ const metadataPath = join(root, "hszrdm-commerce.json")
77
+ const backendPath = join(root, "backend", "package.json")
78
+ if (!existsSync(metadataPath) || !existsSync(backendPath)) {
79
+ throw new Error("Not a generated HSZRDM Commerce webshop (metadata or backend package missing)")
80
+ }
81
+ const metadata = readJson(metadataPath)
82
+ const backend = readJson(backendPath)
83
+ const app = readJson(join(root, "package.json"))
84
+ if (metadata.schema_version !== 1 || metadata.generator !== "@hszrdm/create-commerce") {
85
+ throw new Error("Unsupported HSZRDM Commerce metadata")
86
+ }
87
+ const releasePath = join(root, ".commerce-release.env")
88
+ const release = readRelease(releasePath)
89
+ const pm2Marker = join(root, ".core", "deployment-environment")
90
+ const marker = existsSync(pm2Marker) ? readFileSync(pm2Marker, "utf8").trim() : null
91
+ const environment = options.environment || (
92
+ marker === "prod" ? "production" : marker === "staging" ? "staging" : null
93
+ )
94
+ const sha = optionalText(release.RELEASE_SHA)
95
+ // The dependency is a declared version, not proof of what a running process loaded.
96
+ const declaredCore = optionalText(backend.dependencies?.["@hszrdm/core"])
97
+ const readiness = await checkReadiness(options.readinessUrl)
98
+ return {
99
+ schema_version: 1,
100
+ kind: "hszrdm-commerce-instance",
101
+ observed_at: new Date().toISOString(),
102
+ instance: {
103
+ id: optionalText(release.CORE_INSTANCE_ID) || optionalText(metadata.project?.slug),
104
+ name: optionalText(metadata.project?.store_name),
105
+ app_version: optionalText(app.version),
106
+ declared_core_version: declaredCore,
107
+ environment,
108
+ deployment_method: existsSync(releasePath) ? "systemd-immutable" :
109
+ marker ? "pm2-in-place" : "unknown",
110
+ },
111
+ release: {
112
+ git_sha: sha && /^[a-f0-9]{40}$/i.test(sha) ? sha : null,
113
+ channel: optionalText(release.CORE_RELEASE_CHANNEL),
114
+ built_at: optionalText(release.RELEASE_BUILT_AT),
115
+ },
116
+ readiness,
117
+ }
118
+ }
119
+
120
+ async function main() {
121
+ const options = parseOptions(process.argv.slice(2))
122
+ if (options.help) {
123
+ console.log("Usage: node scripts/commerce-instance-status.mjs [--project-dir PATH] [--environment development|staging|production] [--readiness-url http://127.0.0.1:9000/health/ready]")
124
+ return
125
+ }
126
+ const status = await collectInstanceStatus(options)
127
+ process.stdout.write(JSON.stringify(status) + "\n")
128
+ }
129
+
130
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
131
+ main().catch((error) => {
132
+ console.error("Commerce instance status failed: " + (error instanceof Error ? error.message : String(error)))
133
+ process.exitCode = 1
134
+ })
135
+ }
@@ -35,6 +35,23 @@ for (const [otherTarget, name] of [["dev", ".env"], ["staging", ".env.staging"],
35
35
  }
36
36
  }
37
37
  const env = { ...process.env, ...envFile, APP_ENV: expectedApp, NODE_ENV: expectedNode }
38
+ // A fresh production bootstrap is explicit, and never part of a routine deploy.
39
+ if (rest.includes("--bootstrap") && (action !== "deploy" || target !== "prod")) {
40
+ throw new Error("--bootstrap is allowed only with deploy prod.")
41
+ }
42
+ // Bootstrap cannot silently create a storefront with no Admin account. Require
43
+ // explicitly supplied production credentials, and keep them out of PM2's env.
44
+ const initialAdminEmail = rest.includes("--bootstrap")
45
+ ? String(env.HSZRDM_INSTALL_ADMIN_EMAIL || "").trim() : ""
46
+ const initialAdminPassword = rest.includes("--bootstrap")
47
+ ? String(env.HSZRDM_INSTALL_ADMIN_PASSWORD || "") : ""
48
+ delete env.HSZRDM_INSTALL_ADMIN_EMAIL
49
+ delete env.HSZRDM_INSTALL_ADMIN_PASSWORD
50
+ if (rest.includes("--bootstrap") &&
51
+ (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(initialAdminEmail) ||
52
+ initialAdminPassword.length < 12)) {
53
+ throw new Error("Fresh production bootstrap requires HSZRDM_INSTALL_ADMIN_EMAIL and a 12+ character HSZRDM_INSTALL_ADMIN_PASSWORD.")
54
+ }
38
55
  const shopName = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name
39
56
  if (!shopName || !/^[a-z0-9][a-z0-9._-]*$/.test(shopName)) throw new Error("Invalid webshop package name.")
40
57
  const pm2Names = target === "staging"
@@ -101,10 +118,17 @@ if (action === "restore") {
101
118
  const from = rest[fromIndex + 1]
102
119
  if (!from || from.startsWith("--")) throw new Error("Restore --from path missing.")
103
120
  // Explicit --yes is still required by core-restore for destructive restore.
121
+ const databaseFlag = rest.find(item => item.startsWith("--confirm-database="))
122
+ const databaseIndex = rest.indexOf("--confirm-database")
123
+ const databaseConfirmation = databaseFlag
124
+ ? databaseFlag.slice("--confirm-database=".length)
125
+ : databaseIndex >= 0 ? rest[databaseIndex + 1] : ""
104
126
  run(process.execPath, [restoreScript(), "--project-dir", root,
105
127
  "--database-url", envFile.DATABASE_URL, "--from", resolve(from),
106
128
  ...(rest.includes("--yes") ? ["--yes"] : []),
107
- ...(rest.includes("--overwrite-files") ? ["--overwrite-files"] : [])])
129
+ ...(databaseConfirmation ? ["--confirm-database", databaseConfirmation] : []),
130
+ ...(rest.includes("--overwrite-files") ? ["--overwrite-files"] : []),
131
+ ...(rest.includes("--migrate") ? ["--migrate"] : [])])
108
132
  }
109
133
  // A deployment build writes into one shared workspace. Lock a checkout to a
110
134
  // single deployed runtime so staging cannot overwrite production artifacts.
@@ -128,10 +152,45 @@ if (action === "deploy") {
128
152
  npm(["ci"])
129
153
  backup()
130
154
  npm(["run", "db:migrate"])
155
+ if (rest.includes("--bootstrap")) {
156
+ // Fresh production database only: initialise the store and create a
157
+ // publishable key in THAT database, rather than reusing the dev key.
158
+ npm(["run", "core:init", "--", "--yes"])
159
+ // Only the explicit one-time install path creates a Medusa Admin account.
160
+ // Do not log credentials or persist the password in a project file.
161
+ const medusaUser = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm",
162
+ ["exec", "--workspace", "backend", "--", "medusa", "user",
163
+ "-e", initialAdminEmail, "-p", initialAdminPassword],
164
+ { cwd: root, env, stdio: "inherit" })
165
+ if (medusaUser.error) throw medusaUser.error
166
+ if (medusaUser.status !== 0) throw new Error("Initial production Medusa Admin user creation failed.")
167
+ const key = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm",
168
+ ["run", "storefront:key", "--", "--title", (envFile.STORE_NAME || shopName) + " Storefront"],
169
+ { cwd: root, env, encoding: "utf8" })
170
+ if (key.error) throw key.error
171
+ if (key.status !== 0) throw new Error("Production storefront API key creation failed.")
172
+ const token = key.stdout.match(/^HSZRDM_PUBLISHABLE_KEY=(.+)$/m)?.[1]?.trim()
173
+ if (!token) throw new Error("Production storefront API key could not be verified.")
174
+ const storefrontEnvPath = join(root, "storefront", ".env.local")
175
+ if (!existsSync(storefrontEnvPath)) {
176
+ throw new Error("Missing storefront/.env.local; configure it before first production install.")
177
+ }
178
+ const existing = readFileSync(storefrontEnvPath, "utf8")
179
+ const updated = /^NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=/m.test(existing)
180
+ ? existing.replace(/^NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=.*$/m, "NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=" + token)
181
+ : existing.replace(/\s*$/, "") + "\nNEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=" + token + "\n"
182
+ writeFileSync(storefrontEnvPath, updated, { mode: 0o600 })
183
+ console.log("✅ Production storefront publishable API key configured (not printed).")
184
+ }
185
+ // Runtime credentials originate from this deployment\x27s Admin DB, never .env.
186
+ // Regenerate the scoped encrypted cache before PM2 starts the new version.
187
+ npm(["--prefix", backendDir, "run", "integrations:sync"])
131
188
  if (target === "dev") {
132
189
  devServer()
133
190
  } else {
134
- npm(["run", "build"])
191
+ // Test verification builds run with APP_ENV=test; deploy must build with
192
+ // the selected staging/production configuration and credentials.
193
+ npm(["run", "build:deploy"])
135
194
  if (!existsSync(join(root, "ecosystem.config.cjs"))) {
136
195
  throw new Error("Missing ecosystem.config.cjs: cannot safely reload production PM2.")
137
196
  }
@@ -54,9 +54,18 @@ console.log("- Integration Settings encryption key: jelen van (érték nincs ki
54
54
 
55
55
  if (!args.yes) {
56
56
  console.log("\nDRY RUN: adatbázist és fájlt nem módosítottam.")
57
- console.log("A tényleges, destruktív restore-hoz futtasd újra --yes kapcsolóval.")
57
+ console.log("A tényleges, destruktív restore-hoz --yes ÉS --confirm-database=<cél DB> szükséges.")
58
58
  process.exit(0)
59
59
  }
60
+ // --yes on its own is not enough: require the operator to independently name
61
+ // the target database. Never allow restoring into PostgreSQL system databases.
62
+ if (["postgres", "template0", "template1"].includes(pg.database.toLowerCase()) ||
63
+ String(args["confirm-database"] || "").trim() !== pg.database) {
64
+ throw new Error(
65
+ "Destruktív restore megtagadva. Add meg a pontos céladatbázist: --confirm-database=" + pg.database,
66
+ )
67
+ }
68
+ assertRestoreTargets({ projectDir, bundleDir, env, overwrite: Boolean(args["overwrite-files"]) })
60
69
 
61
70
  const dumpPath = join(bundleDir, "database.dump")
62
71
  console.log("\n- PostgreSQL visszaállítása (--clean --if-exists)...")
@@ -65,6 +74,8 @@ run(
65
74
  [
66
75
  "--clean",
67
76
  "--if-exists",
77
+ "--exit-on-error",
78
+ "--single-transaction",
68
79
  "--no-owner",
69
80
  "--no-acl",
70
81
  `--dbname=${pg.database}`,
@@ -97,6 +108,30 @@ console.log("2. Ellenőrizd, hogy az eredeti INTEGRATION_SETTINGS_ENCRYPTION_KEY
97
108
  console.log("3. Indítsd a backendet, majd futtasd a Production readiness ellenőrzést.")
98
109
  console.log("4. Futtasd az E2E/smoke tesztet egy staging restore-on production indítás előtt.")
99
110
 
111
+ // Check every potentially overwritten file/directory BEFORE running the DB
112
+ // restore, so an existing upload directory cannot fail halfway through.
113
+ function assertRestoreTargets({ projectDir, bundleDir, env, overwrite }) {
114
+ const checks = [
115
+ [join(bundleDir, "files", "integration-settings.enc"), integrationSnapshotPath(projectDir, env)],
116
+ [join(bundleDir, "files", "local-static"), join(backendProjectDir(projectDir), "static")],
117
+ ]
118
+ const uploadSource = join(bundleDir, "files", "file-upload-dir")
119
+ if (existsSync(uploadSource)) {
120
+ const uploadTarget = String(env.FILE_UPLOAD_DIR || "").trim()
121
+ if (!uploadTarget || !isAbsolute(uploadTarget) || uploadTarget === "/" ||
122
+ uploadTarget === projectDir) {
123
+ throw new Error("Biztonságos abszolút FILE_UPLOAD_DIR szükséges a fájlok visszaállításához.")
124
+ }
125
+ checks.push([uploadSource, uploadTarget])
126
+ }
127
+ for (const [source, target] of checks) {
128
+ if (existsSync(source) && existsSync(target) && !overwrite) {
129
+ throw new Error("A restore felülírna egy meglévő útvonalat: " + target +
130
+ ". Tudatos jóváhagyáshoz: --overwrite-files.")
131
+ }
132
+ }
133
+ }
134
+
100
135
  function restoreFiles({ projectDir, bundleDir, env, overwrite }) {
101
136
  const snapshotSource = join(bundleDir, "files", "integration-settings.enc")
102
137
  if (existsSync(snapshotSource)) {
@@ -135,8 +170,8 @@ function copyWithGuard(source, target, overwrite) {
135
170
  cpSync(source, target, { recursive: true, force: overwrite, errorOnExist: !overwrite })
136
171
  }
137
172
 
138
- function run(command, commandArgs, commandEnv) {
139
- const result = spawnSync(command, commandArgs, { env: commandEnv, stdio: "inherit" })
173
+ function run(command, commandArgs, commandEnv, cwd) {
174
+ const result = spawnSync(command, commandArgs, { env: commandEnv, cwd, stdio: "inherit" })
140
175
  if (result.error?.code === "ENOENT") {
141
176
  throw new Error(`${command} nem található. Telepítsd a PostgreSQL klienseszközöket.`)
142
177
  }
@@ -145,7 +180,7 @@ function run(command, commandArgs, commandEnv) {
145
180
  }
146
181
 
147
182
  function runNpm(cwd, commandArgs, commandEnv) {
148
- run(process.platform === "win32" ? "npm.cmd" : "npm", commandArgs, commandEnv)
183
+ run(process.platform === "win32" ? "npm.cmd" : "npm", commandArgs, commandEnv, cwd)
149
184
  }
150
185
 
151
186
  function required(value, flag) {
@@ -175,5 +210,5 @@ function parseArgs(tokens) {
175
210
  }
176
211
 
177
212
  function printHelp() {
178
- console.log(`MEDUSA WEBSHOP CORE restore\n\nEllenőrzés / dry run:\n npm run core:restore -- --from backups/<bundle>\n\nTényleges restore:\n npm run core:restore -- --from backups/<bundle> --yes --overwrite-files [--migrate]\n\nA restore destruktív PostgreSQL --clean műveletet használ, ezért --yes nélkül soha nem módosít adatot.\n`)
213
+ console.log(`MEDUSA WEBSHOP CORE restore\n\nEllenőrzés / dry run:\n npm run core:restore -- --from backups/<bundle>\n\nTényleges restore:\n npm run core:restore -- --from backups/<bundle> --yes --confirm-database=<cél DB> [--overwrite-files] [--migrate]\n\nA restore destruktív PostgreSQL --clean műveletet használ, ezért --yes nélkül soha nem módosít adatot.\n`)
179
214
  }