@hszrdm/create-commerce 1.10.1 → 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 (36) hide show
  1. package/package.json +1 -1
  2. package/src/cli.mjs +18 -3
  3. package/src/upgrade.mjs +39 -3
  4. package/templates/backend/.env.example +8 -0
  5. package/templates/backend/package.json +1 -1
  6. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  7. package/templates/backend/scripts/commerce-ops.mjs +58 -2
  8. package/templates/backend/scripts/core-restore.mjs +40 -5
  9. package/templates/backend/scripts/lib/core-backup-common.mjs +91 -11
  10. package/templates/backend/scripts/production-assets/backup.sh +6 -51
  11. package/templates/backend/scripts/production-assets/deploy.sh +10 -62
  12. package/templates/backend/scripts/production-assets/install.sh +23 -195
  13. package/templates/backend/scripts/production-assets/restore.sh +17 -66
  14. package/templates/storefront/package.json +5 -1
  15. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  16. package/templates/storefront/src/app/globals.css +32 -0
  17. package/templates/storefront/src/app/layout.tsx +7 -1
  18. package/templates/storefront/src/app/legal/page.tsx +3 -3
  19. package/templates/storefront/src/components/analytics.tsx +10 -8
  20. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  21. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  22. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  23. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  24. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  25. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  26. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  27. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  28. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  29. package/templates/storefront/src/lib/core/legal.ts +1 -0
  30. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  31. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  32. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  33. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  34. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  35. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  36. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.10.1",
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,
@@ -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)
@@ -236,6 +249,8 @@ function configureProject(root, settings) {
236
249
  mkdirSync(join(root, "scripts"), { recursive: true })
237
250
  cpSync(join(root, "backend", "scripts", "commerce-ops.mjs"),
238
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"))
239
254
  // Materialize generated operational assets before recording their baseline.
240
255
  // Future Core upgrades can then replace only unchanged, Core-owned files.
241
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
 
@@ -82,8 +82,9 @@ export function generatedRootScripts() {
82
82
  "dev:backend": "npm --workspace backend run dev",
83
83
  "dev:storefront": "npm --workspace storefront run dev",
84
84
  "typecheck": "npm --workspace backend run typecheck && npm --workspace storefront run typecheck",
85
- "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",
86
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",
87
88
  "verify": "npm run typecheck && npm run test && npm run build",
88
89
  "db:migrate": "npm --workspace backend run db:migrate",
89
90
  "core:init": "npm --workspace backend run core:init --",
@@ -96,6 +97,7 @@ export function generatedRootScripts() {
96
97
  "deploy:prod": "node ./scripts/commerce-ops.mjs deploy prod",
97
98
  "deploy:staging": "node ./scripts/commerce-ops.mjs deploy staging",
98
99
  "deploy:production": "npm run deploy:prod",
100
+ "commerce:status": "node ./scripts/commerce-instance-status.mjs",
99
101
  "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
100
102
  "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
101
103
  "backup:staging": "node ./scripts/commerce-ops.mjs backup staging",
@@ -108,12 +110,33 @@ export function generatedRootScripts() {
108
110
  }
109
111
  }
110
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
+
111
134
  function readJson(path) { return JSON.parse(readFileSync(path, "utf8")) }
112
135
  function json(value) { return JSON.stringify(value, null, 2) + "\n" }
113
136
  function sha(data) { return createHash("sha256").update(data).digest("hex") }
114
137
  function hashFile(path) { return sha(readFileSync(path)) }
115
138
  function canonicalSource(path) {
116
- 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))
117
140
  if (path.startsWith("deploy/")) return join(PACKAGE_ROOT, "templates", "backend", "scripts", "production-assets", path.slice("deploy/".length))
118
141
  return join(PACKAGE_ROOT, "templates", path)
119
142
  }
@@ -204,6 +227,10 @@ export function planUpgrade(root, version) {
204
227
  const canonicalPaths = managedPaths()
205
228
  const canonicalSet = new Set(canonicalPaths)
206
229
  for (const path of canonicalPaths) {
230
+ try { assertManagedTarget(root, path) } catch (error) {
231
+ conflicts.push(path + " (" + error.message + ")")
232
+ continue
233
+ }
207
234
  const source = path === "ecosystem.config.cjs" ? null : canonicalSource(path)
208
235
  const target = join(root, path)
209
236
  const metadata = path === "ecosystem.config.cjs" ? readJson(metadataPath) : null
@@ -234,6 +261,10 @@ export function planUpgrade(root, version) {
234
261
  // content is unchanged; never remove customer-modified files.
235
262
  for (const [path, previousHash] of Object.entries(previous?.files || {})) {
236
263
  if (canonicalSet.has(path)) continue
264
+ try { assertManagedTarget(root, path) } catch (error) {
265
+ conflicts.push(path + " (" + error.message + ")")
266
+ continue
267
+ }
237
268
  const target = join(root, path)
238
269
  const stat = lstatSync(target, { throwIfNoEntry: false })
239
270
  if (!stat) continue
@@ -247,6 +278,7 @@ export function planUpgrade(root, version) {
247
278
 
248
279
  const packages = {}
249
280
  for (const path of ["package.json", "backend/package.json", "storefront/package.json"]) {
281
+ assertManagedTarget(root, path)
250
282
  const current = readJson(join(root, path))
251
283
  const desired = expectedPackage(path, version)
252
284
  const base = previous?.packages?.[path]
@@ -324,6 +356,10 @@ export function applyUpgrade(plan, { execute = true } = {}) {
324
356
  if (plan.conflicts.length) throw new Error("Upgrade blocked by customer changes:\n- " + plan.conflicts.join("\n- "))
325
357
  if (!execute) return plan
326
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")
327
363
  const metadataPath = join(plan.root, "hszrdm-commerce.json")
328
364
  const metadata = readJson(metadataPath)
329
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
  # -----------------------------------------------------------------------------
@@ -23,7 +23,7 @@
23
23
  "start:prod": "cd .medusa/server && medusa start"
24
24
  },
25
25
  "dependencies": {
26
- "@hszrdm/core": "1.10.1",
26
+ "@hszrdm/core": "1.11.0",
27
27
  "@medusajs/admin-sdk": "2.22.2",
28
28
  "@medusajs/cli": "2.22.2",
29
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,13 +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
+ }
131
185
  // Runtime credentials originate from this deployment\x27s Admin DB, never .env.
132
186
  // Regenerate the scoped encrypted cache before PM2 starts the new version.
133
187
  npm(["--prefix", backendDir, "run", "integrations:sync"])
134
188
  if (target === "dev") {
135
189
  devServer()
136
190
  } else {
137
- 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"])
138
194
  if (!existsSync(join(root, "ecosystem.config.cjs"))) {
139
195
  throw new Error("Missing ecosystem.config.cjs: cannot safely reload production PM2.")
140
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
  }
@@ -3,11 +3,11 @@ import {
3
3
  cpSync,
4
4
  existsSync,
5
5
  mkdirSync,
6
+ lstatSync,
6
7
  readFileSync,
7
8
  readdirSync,
8
- statSync,
9
9
  } from "node:fs"
10
- import { dirname, isAbsolute, join, resolve } from "node:path"
10
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path"
11
11
 
12
12
  export const PORTABLE_ENV_KEYS = [
13
13
  "MEDUSA_BACKEND_URL",
@@ -64,7 +64,16 @@ export function backendProjectDir(projectDir) {
64
64
  }
65
65
 
66
66
  export function loadRuntimeEnv(projectDir, overrides = process.env) {
67
- const file = join(backendProjectDir(projectDir), ".env")
67
+ const appEnv = String(overrides.APP_ENV || "").trim() ||
68
+ (overrides.NODE_ENV === "production" ? "production" : "development")
69
+ const envName = appEnv === "production" ? ".env.production" :
70
+ appEnv === "staging" ? ".env.staging" : ".env"
71
+ const file = join(backendProjectDir(projectDir), envName)
72
+ // In deployed environments NEVER silently load development credentials,
73
+ // upload paths or encryption settings from backend/.env.
74
+ if (["production", "staging"].includes(appEnv) && !existsSync(file)) {
75
+ throw new Error("Hiányzik a környezet saját konfigurációja: " + file)
76
+ }
68
77
  const fromFile = existsSync(file) ? parseEnv(readFileSync(file, "utf8")) : {}
69
78
  const explicitOverrides = Object.fromEntries(
70
79
  Object.entries(overrides).filter(([, value]) => value != null && String(value).trim() !== ""),
@@ -160,6 +169,12 @@ export function backupFileSources(projectDir, env) {
160
169
  }
161
170
 
162
171
  export function copyBackupSource(bundleDir, item) {
172
+ const sourceStat = lstatSync(item.source)
173
+ if (sourceStat.isSymbolicLink()) {
174
+ throw new Error("Symlink backup source not permitted: " + item.key)
175
+ }
176
+ if (sourceStat.isDirectory()) sha256Tree(item.source) // refuses nested symlinks
177
+ else if (!sourceStat.isFile()) throw new Error("Unsupported backup source: " + item.key)
163
178
  const target = join(bundleDir, item.relative)
164
179
  mkdirSync(dirname(target), { recursive: true })
165
180
  cpSync(item.source, target, { recursive: true, force: true })
@@ -178,19 +193,79 @@ export function sha256Tree(path) {
178
193
  return hash.digest("hex")
179
194
  }
180
195
 
196
+ // Backup manifests are integrity metadata, not arbitrary read instructions.
197
+ // Restrict them to the known bundle schema and reject symlinks even within a
198
+ // checksum-covered directory; this guards dry-runs as well as real restores.
199
+ const ARTIFACT_KINDS = new Map([
200
+ ["database.dump", "file"],
201
+ ["portable-config.json", "file"],
202
+ ["portable-config.env", "file"],
203
+ ["webshop-bootstrap.json", "file"],
204
+ ["files/integration-settings.enc", "file"],
205
+ ["files/local-static", "directory"],
206
+ ["files/file-upload-dir", "directory"],
207
+ ])
208
+ const REQUIRED_ARTIFACTS = ["database.dump", "portable-config.json", "portable-config.env"]
209
+
181
210
  export function verifyManifest(bundleDir, manifest) {
211
+ if (!manifest || !Array.isArray(manifest.artifacts) ||
212
+ manifest.database_format !== "postgres-custom") {
213
+ throw new Error("Érvénytelen Core backup manifest vagy adatbázis-formátum.")
214
+ }
182
215
  const failures = []
183
- for (const artifact of manifest.artifacts || []) {
184
- const path = join(bundleDir, artifact.path)
185
- if (!existsSync(path)) {
186
- failures.push(`${artifact.path}: hiányzik`)
216
+ const seen = new Set()
217
+ const root = resolve(bundleDir)
218
+ for (const artifact of manifest.artifacts) {
219
+ const name = artifact?.path
220
+ const expectedKind = ARTIFACT_KINDS.get(name)
221
+ if (typeof name !== "string" || !expectedKind ||
222
+ artifact.kind !== expectedKind ||
223
+ typeof artifact.sha256 !== "string" ||
224
+ !/^[0-9a-f]{64}$/.test(artifact.sha256) ||
225
+ seen.has(name)) {
226
+ failures.push("Érvénytelen/duplikált backup artifact: " + String(name))
227
+ continue
228
+ }
229
+ seen.add(name)
230
+ const target = resolve(root, name)
231
+ if (!target.startsWith(root + sep)) {
232
+ failures.push(name + ": érvénytelen célútvonal")
187
233
  continue
188
234
  }
189
- const actual = artifact.kind === "directory" ? sha256Tree(path) : sha256File(path)
190
- if (actual !== artifact.sha256) failures.push(`${artifact.path}: checksum eltérés`)
235
+ // Reject symlinks in every path segment, including the leaf.
236
+ let unsafe = false
237
+ let current = root
238
+ for (const segment of name.split("/")) {
239
+ current = join(current, segment)
240
+ if (!existsSync(current)) {
241
+ failures.push(name + ": hiányzik")
242
+ unsafe = true
243
+ break
244
+ }
245
+ if (lstatSync(current).isSymbolicLink()) {
246
+ failures.push(name + ": szimbolikus link nem engedélyezett")
247
+ unsafe = true
248
+ break
249
+ }
250
+ }
251
+ if (unsafe) continue
252
+ if ((expectedKind === "file" && !lstatSync(target).isFile()) ||
253
+ (expectedKind === "directory" && !lstatSync(target).isDirectory())) {
254
+ failures.push(name + ": hibás fájltípus")
255
+ continue
256
+ }
257
+ try {
258
+ const actual = expectedKind === "directory" ? sha256Tree(target) : sha256File(target)
259
+ if (actual !== artifact.sha256) failures.push(name + ": checksum eltérés")
260
+ } catch (error) {
261
+ failures.push(name + ": " + (error instanceof Error ? error.message : String(error)))
262
+ }
263
+ }
264
+ for (const required of REQUIRED_ARTIFACTS) {
265
+ if (!seen.has(required)) failures.push(required + ": kötelező artifact hiányzik")
191
266
  }
192
267
  if (failures.length) {
193
- throw new Error(`A backup integritásellenőrzése sikertelen:\n- ${failures.join("\n- ")}`)
268
+ throw new Error("A backup integritásellenőrzése sikertelen:\n- " + failures.join("\n- "))
194
269
  }
195
270
  }
196
271
 
@@ -213,13 +288,18 @@ function hashDirectory(hash, root, current) {
213
288
  for (const name of entries) {
214
289
  const full = join(current, name)
215
290
  const relative = full.slice(root.length + 1)
216
- const stat = statSync(full)
291
+ const stat = lstatSync(full)
292
+ if (stat.isSymbolicLink()) {
293
+ throw new Error("Symlink not permitted in Core backup: " + relative)
294
+ }
217
295
  if (stat.isDirectory()) {
218
296
  hash.update(`D:${relative}\n`)
219
297
  hashDirectory(hash, root, full)
220
298
  } else if (stat.isFile()) {
221
299
  hash.update(`F:${relative}:${stat.size}\n`)
222
300
  hash.update(readFileSync(full))
301
+ } else {
302
+ throw new Error("Unsupported file type in Core backup: " + relative)
223
303
  }
224
304
  }
225
305
  }