@hszrdm/create-commerce 1.10.1 → 1.11.1

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 (37) hide show
  1. package/README.md +70 -46
  2. package/package.json +1 -1
  3. package/src/cli.mjs +23 -4
  4. package/src/upgrade.mjs +248 -22
  5. package/templates/backend/.env.example +8 -0
  6. package/templates/backend/package.json +1 -1
  7. package/templates/backend/scripts/commerce-instance-status.mjs +135 -0
  8. package/templates/backend/scripts/commerce-ops.mjs +58 -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/storefront/package.json +5 -1
  16. package/templates/storefront/src/app/checkout/success/page.tsx +2 -0
  17. package/templates/storefront/src/app/globals.css +32 -0
  18. package/templates/storefront/src/app/layout.tsx +7 -1
  19. package/templates/storefront/src/app/legal/page.tsx +3 -3
  20. package/templates/storefront/src/components/analytics.tsx +10 -8
  21. package/templates/storefront/src/components/checkout-flow.tsx +539 -75
  22. package/templates/storefront/src/components/fogyasztobarat-embed.tsx +6 -2
  23. package/templates/storefront/src/components/google-analytics-purchase.tsx +33 -0
  24. package/templates/storefront/src/components/stripe-payment.tsx +186 -62
  25. package/templates/storefront/src/lib/core/checkout-addresses.ts +166 -0
  26. package/templates/storefront/src/lib/core/checkout.ts +12 -0
  27. package/templates/storefront/src/lib/core/commerce.ts +12 -2
  28. package/templates/storefront/src/lib/core/company-tax.ts +132 -0
  29. package/templates/storefront/src/lib/core/ga4-bootstrap.ts +35 -0
  30. package/templates/storefront/src/lib/core/legal.ts +1 -0
  31. package/templates/storefront/src/lib/core/public-error.ts +1 -0
  32. package/templates/storefront/src/lib/core/stripe-checkout-phase.ts +23 -0
  33. package/templates/storefront/src/lib/core/tracking.ts +11 -2
  34. package/templates/storefront/tests/checkout-addresses.test.mjs +148 -0
  35. package/templates/storefront/tests/company-tax.test.mjs +68 -0
  36. package/templates/storefront/tests/ga4-bootstrap.test.mjs +74 -0
  37. package/templates/storefront/tests/stripe-checkout-phase.test.mjs +92 -0
@@ -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.1",
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
  }
@@ -1,56 +1,11 @@
1
1
  #!/usr/bin/env bash
2
+ # Compatibility entry point. Backups must use the encrypted-data-aware Core
3
+ # bundle format; never archive raw backend/.env production secrets.
2
4
  set -Eeuo pipefail
3
-
4
5
  ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
5
6
  cd "$ROOT"
6
-
7
- log() { printf '\n==> %s\n' "$*"; }
8
- fail() { printf '\nERROR: %s\n' "$*" >&2; exit 1; }
9
- need() { command -v "$1" >/dev/null 2>&1 || fail "Missing required command: $1"; }
10
- env_value() {
11
- local file="$1" key="$2"
12
- sed -n "s/^${key}=//p" "$file" | head -n 1
7
+ [[ -f backend/.env.production ]] || {
8
+ echo "ERROR: backend/.env.production is required for production backup." >&2
9
+ exit 2
13
10
  }
14
-
15
- need pg_dump
16
- need tar
17
-
18
- [[ -f backend/.env ]] || fail "backend/.env is missing"
19
- DATABASE_URL="$(env_value backend/.env DATABASE_URL)"
20
- [[ -n "$DATABASE_URL" ]] || fail "DATABASE_URL is missing from backend/.env"
21
-
22
- STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
23
- BACKUP_DIR="${HSZRDM_BACKUP_DIR:-$ROOT/backups}"
24
- RETENTION="${HSZRDM_BACKUP_RETENTION:-5}"
25
- mkdir -p "$BACKUP_DIR"
26
- chmod 700 "$BACKUP_DIR" || true
27
- TMP="$(mktemp -d)"
28
- trap 'rm -rf "$TMP"' EXIT
29
- mkdir -p "$TMP/config" "$TMP/runtime"
30
-
31
- log "Database backup"
32
- pg_dump --format=custom --no-owner --file "$TMP/database.dump" "$DATABASE_URL"
33
-
34
- cp backend/.env "$TMP/config/backend.env"
35
- [[ -f storefront/.env.local ]] && cp storefront/.env.local "$TMP/config/storefront.env.local"
36
- [[ -f .env.docker ]] && cp .env.docker "$TMP/config/env.docker"
37
- [[ -f hszrdm-commerce.json ]] && cp hszrdm-commerce.json "$TMP/config/hszrdm-commerce.json"
38
- [[ -d backend/.core ]] && cp -R backend/.core "$TMP/runtime/core"
39
-
40
- FILE_UPLOAD_DIR="$(env_value backend/.env FILE_UPLOAD_DIR)"
41
- if [[ -n "$FILE_UPLOAD_DIR" && -d "$FILE_UPLOAD_DIR" ]]; then
42
- cp -R "$FILE_UPLOAD_DIR" "$TMP/runtime/uploads"
43
- elif [[ -d backend/uploads ]]; then
44
- cp -R backend/uploads "$TMP/runtime/uploads"
45
- fi
46
-
47
- ARCHIVE="$BACKUP_DIR/hszrdm-commerce-$STAMP.tar.gz"
48
- tar -C "$TMP" -czf "$ARCHIVE" .
49
- chmod 600 "$ARCHIVE" || true
50
-
51
- if [[ "$RETENTION" =~ ^[0-9]+$ ]] && (( RETENTION > 0 )); then
52
- ls -1t "$BACKUP_DIR"/hszrdm-commerce-*.tar.gz 2>/dev/null | tail -n +$((RETENTION + 1)) | xargs -r rm -f
53
- fi
54
-
55
- log "Backup created: $ARCHIVE"
56
- printf 'WARNING: this archive contains production secrets and customer data. Store it securely.\n'
11
+ exec npm run backup:prod
@@ -1,68 +1,16 @@
1
1
  #!/usr/bin/env bash
2
+ # Compatibility entry point. The environment-aware commerce-ops workflow is
3
+ # the only supported production deploy implementation.
2
4
  set -Eeuo pipefail
3
-
4
5
  ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
5
6
  cd "$ROOT"
6
-
7
- log() { printf '\n==> %s\n' "$*"; }
8
- fail() { printf '\nERROR: %s\n' "$*" >&2; exit 1; }
9
- need() { command -v "$1" >/dev/null 2>&1 || fail "Missing required command: $1"; }
10
- pm2_run() {
11
- if command -v pm2 >/dev/null 2>&1; then
12
- pm2 "$@"
13
- else
14
- npx --yes pm2@6.0.13 "$@"
15
- fi
7
+ [[ -f backend/.env.production ]] || {
8
+ echo "ERROR: backend/.env.production is required. Refusing to deploy using backend/.env (development)." >&2
9
+ exit 2
16
10
  }
17
- env_value() {
18
- local file="$1" key="$2"
19
- sed -n "s/^${key}=//p" "$file" | head -n 1
11
+ [[ -f storefront/.env.local ]] || {
12
+ echo "ERROR: storefront/.env.local is missing." >&2
13
+ exit 2
20
14
  }
21
-
22
- log "HSZRDM Commerce deploy"
23
- need git
24
- need npm
25
- need curl
26
-
27
- [[ -f backend/.env ]] || fail "backend/.env is missing"
28
- [[ -f storefront/.env.local ]] || fail "storefront/.env.local is missing"
29
-
30
- if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
31
- fail "Tracked production files contain local changes. Commit/revert them before deploy."
32
- fi
33
-
34
- log "Backup before deploy"
35
- bash deploy/backup.sh
36
-
37
- OLD_SHA="$(git rev-parse HEAD)"
38
- log "Pull latest code (fast-forward only)"
39
- git pull --ff-only
40
- NEW_SHA="$(git rev-parse HEAD)"
41
- printf 'Deploying %s -> %s\n' "$OLD_SHA" "$NEW_SHA"
42
-
43
- log "Clean dependency tree and install exact dependencies"
44
- rm -rf node_modules
45
- npm ci
46
- npm --workspace backend run env:verify
47
-
48
- log "Run database migrations"
49
- npm run db:migrate
50
- npm run core:init -- --yes
51
-
52
- log "Build"
53
- npm run build
54
-
55
- log "Reload PM2"
56
- pm2_run startOrReload ecosystem.config.cjs --env production
57
- pm2_run save
58
-
59
- BACKEND_URL="$(env_value backend/.env MEDUSA_BACKEND_URL)"
60
- STOREFRONT_URL="$(env_value backend/.env STOREFRONT_URL)"
61
- if [[ -n "$BACKEND_URL" ]]; then
62
- curl --fail --silent --show-error --max-time 15 "${BACKEND_URL%/}/health" >/dev/null || fail "Backend healthcheck failed after deploy"
63
- fi
64
- if [[ -n "$STOREFRONT_URL" ]]; then
65
- curl --fail --silent --show-error --max-time 15 "$STOREFRONT_URL" >/dev/null || fail "Storefront healthcheck failed after deploy"
66
- fi
67
-
68
- log "Deploy completed"
15
+ echo "HSZRDM production deploy via canonical deploy:prod (no implicit git pull)."
16
+ exec npm run deploy:prod