@hszrdm/create-commerce 1.24.1 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hszrdm/create-commerce",
3
- "version": "1.24.1",
3
+ "version": "1.26.0",
4
4
  "description": "Create a complete HSZRDM Commerce webshop project.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
package/src/upgrade.mjs CHANGED
@@ -119,6 +119,9 @@ export function generatedRootScripts() {
119
119
  "backup:dev": "node ./scripts/commerce-ops.mjs backup dev",
120
120
  "backup:prod": "node ./scripts/commerce-ops.mjs backup prod",
121
121
  "backup:staging": "node ./scripts/commerce-ops.mjs backup staging",
122
+ "backup:local": "node ./backend/scripts/automated-backup.mjs backup",
123
+ "backup:local:install": "node ./backend/scripts/automated-backup.mjs install",
124
+ "backup:local:verify": "node ./backend/scripts/automated-backup.mjs monthly-check",
122
125
  "restore:dev": "node ./scripts/commerce-ops.mjs restore dev",
123
126
  "restore:prod": "node ./scripts/commerce-ops.mjs restore prod",
124
127
  "restore:staging": "node ./scripts/commerce-ops.mjs restore staging",
@@ -23,7 +23,7 @@
23
23
  "start:prod": "cd .medusa/server && medusa start"
24
24
  },
25
25
  "dependencies": {
26
- "@hszrdm/core": "1.24.1",
26
+ "@hszrdm/core": "1.26.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,496 @@
1
+ #!/usr/bin/env node
2
+ // HSZRDM Commerce: opt-in, local-only production Docker backups.
3
+ // No daemon, cloud credentials, destructive database operations or automatic activation.
4
+ import { createHash, randomBytes } from "node:crypto"
5
+ import { spawn, spawnSync } from "node:child_process"
6
+ import {
7
+ closeSync, copyFileSync, createReadStream, createWriteStream, existsSync, lstatSync,
8
+ mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync,
9
+ statSync, writeFileSync,
10
+ } from "node:fs"
11
+ import { hostname } from "node:os"
12
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
13
+ import { pipeline } from "node:stream/promises"
14
+ import { fileURLToPath } from "node:url"
15
+
16
+ const STAMP = /^backup-(\d{8})T(\d{6})Z-[a-f0-9]{8}$/
17
+ const DEFAULT_RETENTION = 30
18
+
19
+ export function parseOptions(argv) {
20
+ const [action, ...rest] = argv
21
+ if (!["backup", "monthly-check", "install", "status"].includes(action)) {
22
+ throw new Error("Usage: automated-backup.mjs <backup|monthly-check|install|status> [--project-dir PATH] [--backup-dir PATH] [--compose-file PATH] [--env-file PATH] [--alert-email ADDRESS] [--apply]")
23
+ }
24
+ const flags = {}
25
+ for (let i = 0; i < rest.length; i++) {
26
+ const part = rest[i]
27
+ if (part === "--apply") { flags.apply = true; continue }
28
+ if (!part.startsWith("--") || !rest[i + 1] || rest[i + 1].startsWith("--")) {
29
+ throw new Error("Invalid or missing argument: " + part)
30
+ }
31
+ flags[part.slice(2)] = rest[++i]
32
+ }
33
+ const projectDir = resolve(flags["project-dir"] || process.cwd())
34
+ const composeFile = resolve(projectDir, flags["compose-file"] ||
35
+ (existsSync(join(projectDir, "compose.production.yml")) ? "compose.production.yml" : "docker-compose.yml"))
36
+ const envFile = resolve(projectDir, flags["env-file"] ||
37
+ (existsSync(join(projectDir, ".env.production.docker")) ? ".env.production.docker" : ".env.docker"))
38
+ const slug = basename(projectDir).replace(/[^a-zA-Z0-9_-]/g, "-").toLowerCase()
39
+ const backupDir = resolve(flags["backup-dir"] || join("/var/backups/hszrdm", slug))
40
+ const retentionDays = Number(flags["retention-days"] || DEFAULT_RETENTION)
41
+ if (!Number.isInteger(retentionDays) || retentionDays < 1 || retentionDays > 3650) throw new Error("Invalid retention-days")
42
+ const postgresService = flags["postgres-service"] || "postgres"
43
+ const redisService = flags["redis-service"] || "redis"
44
+ for (const value of [postgresService, redisService]) {
45
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(value)) throw new Error("Invalid service name")
46
+ }
47
+ const alertEmail = flags["alert-email"] || process.env.BACKUP_ALERT_EMAIL || ""
48
+ if (alertEmail && !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(alertEmail)) throw new Error("Invalid alert email")
49
+ const options = { action, projectDir, composeFile, envFile, backupDir,
50
+ retentionDays, postgresService, redisService, alertEmail, apply: !!flags.apply }
51
+ if (["backup", "monthly-check", "install"].includes(action)) {
52
+ for (const path of [projectDir, composeFile, envFile]) {
53
+ if (!existsSync(path)) throw new Error("Missing required production path: " + path)
54
+ if (lstatSync(path).isSymbolicLink()) throw new Error("Symlink production path not supported: " + path)
55
+ }
56
+ if (backupDir === "/" || backupDir === projectDir || backupDir.startsWith(projectDir + sep)) {
57
+ throw new Error("Backups must be outside the application tree")
58
+ }
59
+ }
60
+ return options
61
+ }
62
+
63
+ function invoke(cmd, args, { cwd, input, maxBuffer = 8 * 1024 * 1024 } = {}) {
64
+ const r = spawnSync(cmd, args, { cwd, input, encoding: "utf8", maxBuffer })
65
+ if (r.error || r.status !== 0) {
66
+ throw new Error(cmd + " failed (" + (r.status ?? r.error?.code) + "): " + String(r.stderr || "").slice(-800))
67
+ }
68
+ return String(r.stdout || "").trim()
69
+ }
70
+
71
+ function compose(o, extra) {
72
+ return invoke("docker", ["compose", "--env-file", o.envFile, "-f", o.composeFile, ...extra], { cwd: o.projectDir })
73
+ }
74
+
75
+ function composeArgs(o, extra) {
76
+ return ["compose", "--env-file", o.envFile, "-f", o.composeFile, ...extra]
77
+ }
78
+
79
+ async function toFile(cmd, args, path, cwd) {
80
+ const child = spawn(cmd, args, { cwd, stdio: ["ignore", "pipe", "pipe"] })
81
+ const output = createWriteStream(path, { flags: "wx", mode: 0o600 })
82
+ let stderr = ""
83
+ child.stderr.on("data", chunk => { stderr = (stderr + chunk.toString()).slice(-1500) })
84
+ const exit = new Promise((yes, no) => {
85
+ child.on("error", no)
86
+ child.on("close", code => code === 0 ? yes() : no(new Error(cmd + " failed (" + code + "): " + stderr)))
87
+ })
88
+ try {
89
+ await Promise.all([pipeline(child.stdout, output), exit])
90
+ } catch (error) {
91
+ child.kill("SIGTERM")
92
+ rmSync(path, { force: true })
93
+ throw error
94
+ }
95
+ if (!statSync(path).size) throw new Error("Empty backup artifact: " + basename(path))
96
+ }
97
+
98
+ async function validatePgDump(o, path) {
99
+ const child = spawn("docker", composeArgs(o, ["exec", "-T", o.postgresService,
100
+ "pg_restore", "--list"]), { cwd: o.projectDir, stdio: ["pipe", "pipe", "pipe"] })
101
+ let stderr = ""
102
+ child.stdout.resume()
103
+ child.stderr.on("data", chunk => { stderr = (stderr + chunk.toString()).slice(-1000) })
104
+ const exit = new Promise((yes, no) => {
105
+ child.on("error", no)
106
+ child.on("close", code => code === 0 ? yes() :
107
+ no(new Error("pg_restore --list validation failed (" + code + "): " + stderr)))
108
+ })
109
+ try {
110
+ await Promise.all([pipeline(createReadStream(path), child.stdin), exit])
111
+ } catch (error) {
112
+ child.kill("SIGTERM")
113
+ throw error
114
+ }
115
+ }
116
+
117
+ function sha256(path) {
118
+ const hash = createHash("sha256")
119
+ const fd = openSync(path, "r")
120
+ const chunk = Buffer.allocUnsafe(1024 * 1024)
121
+ try {
122
+ let count
123
+ while ((count = readSync(fd, chunk, 0, chunk.length, null)) > 0) {
124
+ hash.update(chunk.subarray(0, count))
125
+ }
126
+ } finally {
127
+ closeSync(fd)
128
+ }
129
+ return hash.digest("hex")
130
+ }
131
+ function atomicJson(path, data) {
132
+ const temp = path + "." + process.pid + ".tmp"
133
+ writeFileSync(temp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600, flag: "wx" })
134
+ renameSync(temp, path)
135
+ }
136
+ function safeArchiveName(name) {
137
+ const prefix = name.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 70)
138
+ const suffix = createHash("sha256").update(name).digest("hex").slice(0, 12)
139
+ return prefix + "-" + suffix
140
+ }
141
+ function composeContainer(o, service) {
142
+ const id = compose(o, ["ps", "-q", service])
143
+ if (!/^[a-f0-9]{12,64}$/.test(id)) throw new Error("Compose service is not running: " + service)
144
+ return id
145
+ }
146
+ function mounts(id) {
147
+ const containers = JSON.parse(invoke("docker", ["inspect", id]))
148
+ return containers[0]?.Mounts || []
149
+ }
150
+ function safeNamedVolume(mount) {
151
+ return mount.Type === "volume" && /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(mount.Name || "") &&
152
+ isAbsolute(mount.Source) && existsSync(mount.Source) && !lstatSync(mount.Source).isSymbolicLink()
153
+ }
154
+ function sendFailureAlert(o, message) {
155
+ if (!o.alertEmail) return
156
+ const path = ["/usr/sbin/sendmail", "/usr/lib/sendmail"].find(existsSync)
157
+ if (!path) { console.error("CRITICAL: sendmail not installed; backup alert not delivered"); return }
158
+ const subject = "[HSZRDM] Backup failed on " + hostname()
159
+ const body = "From: backup@" + hostname().replace(/[^a-zA-Z0-9.-]/g, "") +
160
+ "\nTo: " + o.alertEmail + "\nSubject: " + subject +
161
+ "\nContent-Type: text/plain; charset=UTF-8\n\n" +
162
+ "Project: " + o.projectDir + "\nOperation: " + o.action + "\n" +
163
+ "Failure: " + message.slice(0, 1500) + "\n"
164
+ const r = spawnSync(path, ["-t", "-oi"], { input: body, encoding: "utf8" })
165
+ if (r.status !== 0) console.error("CRITICAL: sendmail failed; backup alert not delivered")
166
+ }
167
+
168
+ function tarDirectory(source, destination) {
169
+ if (!isAbsolute(source) || !existsSync(source) || !lstatSync(source).isDirectory()) {
170
+ throw new Error("Invalid volume source")
171
+ }
172
+ invoke("tar", ["-C", source, "-czf", destination, "."])
173
+ invoke("tar", ["-tzf", destination])
174
+ }
175
+ function collectConfig(o, targetDir) {
176
+ const configDir = join(targetDir, "configuration")
177
+ mkdirSync(configDir, { mode: 0o700 })
178
+ const candidates = [
179
+ o.composeFile, o.envFile,
180
+ ...["backend/.env.production", "backend/.env.production.docker",
181
+ "storefront/.env.production", "storefront/.env.local", ".env.production",
182
+ ".env.production.docker", ".env.docker", "docker-compose.yml", "compose.production.yml"]
183
+ .map(p => join(o.projectDir, p)),
184
+ ]
185
+ const seen = new Set()
186
+ for (const source of candidates) {
187
+ const absolute = resolve(source)
188
+ if (seen.has(absolute) || !existsSync(absolute)) continue
189
+ seen.add(absolute)
190
+ if (!lstatSync(absolute).isFile()) throw new Error("Invalid configuration file: " + absolute)
191
+ const rel = absolute.startsWith(o.projectDir + sep) ?
192
+ relative(o.projectDir, absolute) : "deployment/" + basename(absolute)
193
+ const target = join(configDir, rel)
194
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 })
195
+ copyFileSync(absolute, target)
196
+ // Configurations contain production credentials: never allow group/other read.
197
+ invoke("chmod", ["600", target])
198
+ }
199
+ try {
200
+ writeFileSync(join(targetDir, "git-commit.txt"),
201
+ invoke("git", ["-C", o.projectDir, "rev-parse", "HEAD"]) + "\n", { mode: 0o600 })
202
+ } catch { /* Source checkout can be detached or distributed without Git. */ }
203
+ }
204
+
205
+ async function redisSnapshot(o) {
206
+ const redisId = composeContainer(o, o.redisService)
207
+ const reply = compose(o, ["exec", "-T", o.redisService, "redis-cli", "--raw", "BGSAVE"])
208
+ if (!/Background saving (started|scheduled)|Background save already in progress/.test(reply)) {
209
+ throw new Error("Redis BGSAVE rejected")
210
+ }
211
+ let ok = false
212
+ for (let i = 0; i < 120; i++) {
213
+ const state = compose(o, ["exec", "-T", o.redisService, "redis-cli", "--raw", "INFO", "persistence"])
214
+ if (/rdb_bgsave_in_progress:0\b/.test(state) && /rdb_last_bgsave_status:ok\b/.test(state) &&
215
+ !/rdb_bgsave_scheduled:1\b/.test(state)) { ok = true; break }
216
+ await new Promise(resolve => setTimeout(resolve, 1000))
217
+ }
218
+ if (!ok) throw new Error("Redis snapshot failed or timed out")
219
+ const dataMount = mounts(redisId).find(m => m.Destination === "/data" && safeNamedVolume(m))
220
+ if (!dataMount || !existsSync(join(dataMount.Source, "dump.rdb")) ||
221
+ !statSync(join(dataMount.Source, "dump.rdb")).size) throw new Error("Redis dump.rdb is missing")
222
+ return dataMount
223
+ }
224
+
225
+ function reportArtifactTree(dir) {
226
+ const files = []
227
+ function walk(root, name) {
228
+ for (const entry of readdirSync(join(root, name), { withFileTypes: true })) {
229
+ const rel = join(name, entry.name)
230
+ const file = join(root, rel)
231
+ if (entry.isSymbolicLink()) throw new Error("Backup artifact symlink forbidden: " + rel)
232
+ if (entry.isDirectory()) walk(root, rel)
233
+ else if (entry.isFile()) files.push({ path: rel, size: statSync(file).size, sha256: sha256(file) })
234
+ else throw new Error("Unsupported artifact type: " + rel)
235
+ }
236
+ }
237
+ walk(dir, "")
238
+ return files.sort((a, b) => a.path.localeCompare(b.path))
239
+ }
240
+
241
+ export function backupDirectories(output) {
242
+ if (!existsSync(output)) return []
243
+ return readdirSync(output, { withFileTypes: true })
244
+ .filter(item => item.isDirectory() && STAMP.test(item.name))
245
+ .map(item => ({ name: item.name, path: join(output, item.name) }))
246
+ }
247
+
248
+ export function expiredSuccessfulBackups(output, days, now = Date.now()) {
249
+ const threshold = now - days * 86400000
250
+ const result = []
251
+ for (const item of backupDirectories(output)) {
252
+ const match = STAMP.exec(item.name)
253
+ const iso = match[1].slice(0,4) + "-" + match[1].slice(4,6) + "-" +
254
+ match[1].slice(6,8) + "T" + match[2].slice(0,2) + ":" +
255
+ match[2].slice(2,4) + ":" + match[2].slice(4,6) + "Z"
256
+ if (Date.parse(iso) >= threshold) continue
257
+ const manifestPath = join(item.path, "manifest.json")
258
+ if (!existsSync(manifestPath)) continue
259
+ try {
260
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"))
261
+ if (manifest.status === "success" && manifest.schema_version === 1) result.push(item)
262
+ } catch { /* Never prune uncertain or incomplete backups. */ }
263
+ }
264
+ return result
265
+ }
266
+
267
+ function newestSuccess(o) {
268
+ const candidates = backupDirectories(o.backupDir).sort((a,b) => b.name.localeCompare(a.name))
269
+ for (const item of candidates) {
270
+ const file = join(item.path, "manifest.json")
271
+ if (!existsSync(file)) continue
272
+ try {
273
+ if (JSON.parse(readFileSync(file, "utf8")).status === "success") return item.path
274
+ } catch { /* Skip invalid bundles. */ }
275
+ }
276
+ throw new Error("No successful backups found")
277
+ }
278
+ function verifyBundle(bundle) {
279
+ const manifest = JSON.parse(readFileSync(join(bundle, "manifest.json"), "utf8"))
280
+ if (manifest.schema_version !== 1 || manifest.status !== "success" || !Array.isArray(manifest.artifacts)) {
281
+ throw new Error("Invalid manifest")
282
+ }
283
+ for (const item of manifest.artifacts) {
284
+ if (!item || !/^[a-zA-Z0-9_./-]+$/.test(item.path) ||
285
+ item.path.split("/").some(part => part === ".." || part === ".") ||
286
+ !/^[a-f0-9]{64}$/.test(item.sha256)) throw new Error("Invalid artifact path/checksum")
287
+ const full = resolve(bundle, item.path)
288
+ if (!full.startsWith(bundle + sep) || !existsSync(full) || !lstatSync(full).isFile() ||
289
+ sha256(full) !== item.sha256) throw new Error("Corrupted artifact: " + item.path)
290
+ if (item.path.endsWith(".tar.gz")) invoke("tar", ["-tzf", full])
291
+ }
292
+ if (!manifest.artifacts.some(x => x.path === "database.dump")) throw new Error("Missing database.dump")
293
+ return manifest
294
+ }
295
+
296
+ async function backup(o) {
297
+ if (process.getuid?.() !== 0) throw new Error("Docker volume backup requires root. Use sudo.")
298
+ mkdirSync(o.backupDir, { recursive: true, mode: 0o700 })
299
+ if (lstatSync(o.backupDir).isSymbolicLink()) throw new Error("Symlink backup directory forbidden")
300
+ const lock = join(o.backupDir, ".backup.lock")
301
+ mkdirSync(lock, { mode: 0o700 })
302
+ let stage
303
+ try {
304
+ const name = "backup-" + new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z") +
305
+ "-" + randomBytes(4).toString("hex")
306
+ stage = join(o.backupDir, "." + name + ".tmp")
307
+ const final = join(o.backupDir, name)
308
+ mkdirSync(stage, { mode: 0o700 })
309
+ const pgId = composeContainer(o, o.postgresService)
310
+ const pgMounts = mounts(pgId)
311
+ const pgDataVolumes = new Set(pgMounts.filter(m =>
312
+ m.Destination === "/var/lib/postgresql/data" || m.Destination.startsWith("/var/lib/postgresql/data/"))
313
+ .map(m => m.Name))
314
+ console.log("Backing up PostgreSQL...")
315
+ await toFile("docker", composeArgs(o, ["exec", "-T", o.postgresService, "sh", "-c",
316
+ 'exec pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc --no-owner --no-acl']),
317
+ join(stage, "database.dump"), o.projectDir)
318
+ await validatePgDump(o, join(stage, "database.dump"))
319
+ await toFile("docker", composeArgs(o, ["exec", "-T", o.postgresService, "sh", "-c",
320
+ 'exec pg_dumpall -U "$POSTGRES_USER" --globals-only']),
321
+ join(stage, "postgres-globals.sql"), o.projectDir)
322
+
323
+ const redisMount = await redisSnapshot(o)
324
+ const ids = compose(o, ["ps", "-q"]).split(/\s+/).filter(Boolean)
325
+ const volumes = new Map()
326
+ const skippedBinds = []
327
+ for (const id of ids) {
328
+ for (const mount of mounts(id)) {
329
+ if (mount.Type === "bind") { skippedBinds.push(mount.Destination); continue }
330
+ if (!safeNamedVolume(mount) || pgDataVolumes.has(mount.Name)) continue
331
+ volumes.set(mount.Name, mount.Source)
332
+ }
333
+ }
334
+ if (!volumes.has(redisMount.Name)) throw new Error("Redis volume not discovered")
335
+ const volumeDir = join(stage, "volumes")
336
+ mkdirSync(volumeDir, { mode: 0o700 })
337
+ for (const [name, source] of volumes) {
338
+ console.log("Archiving volume " + name)
339
+ tarDirectory(source, join(volumeDir, safeArchiveName(name) + ".tar.gz"))
340
+ }
341
+ copyFileSync(join(redisMount.Source, "dump.rdb"), join(stage, "redis-dump.rdb"))
342
+ invoke("chmod", ["600", join(stage, "redis-dump.rdb")])
343
+ collectConfig(o, stage)
344
+ writeFileSync(join(stage, "docker-images.txt"),
345
+ compose(o, ["images"]) + "\n", { mode: 0o600 })
346
+ const manifest = { schema_version: 1, status: "success", created_at: new Date().toISOString(),
347
+ postgres_service: o.postgresService, redis_service: o.redisService,
348
+ docker_volumes: [...volumes.keys()], excluded_raw_pgdata: [...pgDataVolumes],
349
+ skipped_bind_mount_destinations: [...new Set(skippedBinds)],
350
+ artifacts: reportArtifactTree(stage) }
351
+ atomicJson(join(stage, "manifest.json"), manifest)
352
+ verifyBundle(stage)
353
+ renameSync(stage, final)
354
+ stage = null
355
+ // Only successful, checksum-verified backups permit cleanup.
356
+ const expired = expiredSuccessfulBackups(o.backupDir, o.retentionDays)
357
+ for (const item of expired) {
358
+ if (item.path !== final) rmSync(item.path, { recursive: true, force: true })
359
+ }
360
+ atomicJson(join(o.backupDir, "backup-status.json"),
361
+ { status: "success", at: new Date().toISOString(), last_backup: final })
362
+ console.log("Backup complete: " + final)
363
+ } finally {
364
+ if (stage && existsSync(stage)) {
365
+ // Preserve failed partial artifacts for diagnosis, not for restore.
366
+ renameSync(stage, join(o.backupDir, "failed-" + Date.now()))
367
+ }
368
+ rmSync(lock, { recursive: true, force: true })
369
+ }
370
+ }
371
+
372
+ function monthlyCheck(o) {
373
+ if (process.getuid?.() !== 0) throw new Error("Monthly restore probe requires root")
374
+ const bundle = newestSuccess(o)
375
+ const manifest = verifyBundle(bundle)
376
+ console.log("Verified " + manifest.artifacts.length + " artifacts")
377
+ // Use the running PostgreSQL server's exact local image, but NEVER its
378
+ // database/container/volume/network. The disposable instance has no network.
379
+ const image = invoke("docker", ["inspect", "--format", "{{.Image}}", composeContainer(o, o.postgresService)])
380
+ if (!/^sha256:[a-f0-9]{64}$/.test(image)) throw new Error("Invalid local PostgreSQL image")
381
+ const name = "hszrdm-restore-" + process.pid + "-" + randomBytes(3).toString("hex")
382
+ let started = false
383
+ try {
384
+ invoke("docker", ["run", "--detach", "--rm", "--pull", "never", "--network", "none",
385
+ "--name", name, "--tmpfs", "/var/lib/postgresql/data:rw,mode=0700",
386
+ "-e", "POSTGRES_HOST_AUTH_METHOD=trust", "-e", "POSTGRES_DB=restore_probe", image])
387
+ started = true
388
+ let ready = false
389
+ for (let i = 0; i < 40; i++) {
390
+ const r = spawnSync("docker", ["exec", name, "pg_isready", "-U", "postgres", "-d", "restore_probe"],
391
+ { encoding: "utf8" })
392
+ if (r.status === 0) { ready = true; break }
393
+ invoke("sleep", ["1"])
394
+ }
395
+ if (!ready) throw new Error("Disposable PostgreSQL did not start")
396
+ invoke("docker", ["cp", join(bundle, "database.dump"), name + ":/tmp/restore.dump"])
397
+ invoke("docker", ["exec", "-u", "root", name, "chown", "postgres:postgres", "/tmp/restore.dump"])
398
+ invoke("docker", ["exec", "-u", "postgres", name, "pg_restore", "--exit-on-error",
399
+ "--no-owner", "--no-acl", "-U", "postgres", "-d", "restore_probe", "/tmp/restore.dump"])
400
+ const count = Number(invoke("docker", ["exec", "-u", "postgres", name, "psql",
401
+ "-U", "postgres", "-d", "restore_probe", "-tAc",
402
+ "select count(*) from information_schema.tables where table_schema = 'public'"]))
403
+ if (!Number.isInteger(count) || count < 1) throw new Error("Restore contained no public tables")
404
+ atomicJson(join(o.backupDir, "restore-check-status.json"),
405
+ { status: "success", at: new Date().toISOString(), bundle, table_count: count })
406
+ console.log("Isolated restore successful (" + count + " public tables)")
407
+ } finally {
408
+ if (started) spawnSync("docker", ["rm", "--force", name], { encoding: "utf8" })
409
+ }
410
+ }
411
+
412
+ export function systemdUnits(o, script = fileURLToPath(import.meta.url), node = process.execPath) {
413
+ const unitName = "hszrdm-backup-" + basename(o.projectDir).replace(/[^a-zA-Z0-9_-]/g, "-").toLowerCase()
414
+ const quote = v => '"' + v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]/g, "") + '"'
415
+ const args = ["--project-dir", o.projectDir, "--backup-dir", o.backupDir,
416
+ "--compose-file", o.composeFile, "--env-file", o.envFile,
417
+ "--postgres-service", o.postgresService, "--redis-service", o.redisService,
418
+ "--retention-days", String(o.retentionDays), ...(o.alertEmail ? ["--alert-email", o.alertEmail] : [])]
419
+ const cmd = action => [node, script, action, ...args].map(quote).join(" ")
420
+ const service = action => "[Unit]\nDescription=HSZRDM local " + action +
421
+ " for " + unitName + "\nAfter=docker.service\nRequires=docker.service\n\n" +
422
+ "[Service]\nType=oneshot\nUser=root\nGroup=root\nUMask=0077\n" +
423
+ "WorkingDirectory=" + quote(o.projectDir) + "\nExecStart=" + cmd(action) +
424
+ "\nTimeoutStartSec=3600\nNoNewPrivileges=true\nPrivateTmp=true\n"
425
+ const timer = calendar => "[Unit]\nDescription=Schedule " + unitName +
426
+ "\n\n[Timer]\nOnCalendar=" + calendar +
427
+ "\nPersistent=true\nUnit=REPLACE_ME.service\n\n[Install]\nWantedBy=timers.target\n"
428
+ const daily = unitName + ".service"
429
+ const monthly = unitName + "-monthly.service"
430
+ return {
431
+ [daily]: service("backup"),
432
+ [unitName + ".timer"]: timer("*-*-* 02:00:00 Europe/Budapest").replace("REPLACE_ME.service", daily),
433
+ [monthly]: service("monthly-check"),
434
+ [unitName + "-monthly.timer"]: timer("*-*-01 03:00:00 Europe/Budapest").replace("REPLACE_ME.service", monthly),
435
+ }
436
+ }
437
+
438
+ function install(o) {
439
+ const units = systemdUnits(o)
440
+ if (!o.apply) {
441
+ console.log("Dry-run only; use install --apply after checking prerequisites:")
442
+ for (const [name, content] of Object.entries(units)) console.log("\n" + name + ":\n" + content)
443
+ return
444
+ }
445
+ if (process.getuid?.() !== 0) throw new Error("Installation requires root")
446
+ if (!o.alertEmail) throw new Error("--alert-email is required for automated installation")
447
+ if (!["/usr/sbin/sendmail", "/usr/lib/sendmail"].some(existsSync)) {
448
+ throw new Error("sendmail MTA is required for failure email; configure it before installation")
449
+ }
450
+ invoke("docker", ["compose", "--env-file", o.envFile, "-f", o.composeFile, "ps", "-q", o.postgresService])
451
+ mkdirSync(o.backupDir, { recursive: true, mode: 0o700 })
452
+ for (const [name, content] of Object.entries(units)) {
453
+ const path = join("/etc/systemd/system", name)
454
+ if (existsSync(path) && readFileSync(path, "utf8") !== content) {
455
+ throw new Error("Existing unit differs: " + path + " (review manually)")
456
+ }
457
+ }
458
+ for (const [name, content] of Object.entries(units)) {
459
+ const path = join("/etc/systemd/system", name)
460
+ if (!existsSync(path)) writeFileSync(path, content, { mode: 0o644, flag: "wx" })
461
+ }
462
+ invoke("systemctl", ["daemon-reload"])
463
+ for (const name of Object.keys(units).filter(n => n.endsWith(".timer"))) {
464
+ invoke("systemctl", ["enable", "--now", name])
465
+ }
466
+ console.log("Local backup timers enabled. No cloud destination configured.")
467
+ }
468
+
469
+ async function main() {
470
+ let options
471
+ try {
472
+ options = parseOptions(process.argv.slice(2))
473
+ if (options.action === "backup") await backup(options)
474
+ else if (options.action === "monthly-check") monthlyCheck(options)
475
+ else if (options.action === "install") install(options)
476
+ else {
477
+ for (const name of ["backup-status.json", "restore-check-status.json"]) {
478
+ const path = join(options.backupDir, name)
479
+ console.log(name + ": " + (existsSync(path) ? readFileSync(path, "utf8") : "not recorded"))
480
+ }
481
+ }
482
+ } catch (error) {
483
+ const message = error instanceof Error ? error.message : String(error)
484
+ console.error("Backup automation failed: " + message)
485
+ if (options && ["backup", "monthly-check"].includes(options.action)) {
486
+ try {
487
+ mkdirSync(options.backupDir, { recursive: true, mode: 0o700 })
488
+ atomicJson(join(options.backupDir, options.action + "-failure.json"),
489
+ { status: "failed", at: new Date().toISOString(), error: message })
490
+ } catch {}
491
+ sendFailureAlert(options, message)
492
+ }
493
+ process.exitCode = 1
494
+ }
495
+ }
496
+ if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) await main()
@@ -5,7 +5,6 @@ NEXT_PUBLIC_MEDUSA_BACKEND_URL=http://localhost:9000
5
5
  NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=
6
6
 
7
7
  # Public widget key from Packeta Client (never use Packeta API password here).
8
- NEXT_PUBLIC_PACKETA_WIDGET_API_KEY=
9
8
 
10
9
  # Browser-restricted Google Maps API key for the MPL PostaPont legacy map.
11
10
  NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=
@@ -7,7 +7,7 @@
7
7
  "build": "next build",
8
8
  "start": "next start",
9
9
  "typecheck": "tsc --noEmit",
10
- "test:pickup": "node --experimental-strip-types --test tests/carrier-pickup-adapter.test.mjs",
10
+ "test:pickup": "node --experimental-strip-types --test tests/carrier-pickup-adapter.test.mjs tests/packeta-widget-config.test.mjs",
11
11
  "test:validation": "node --experimental-strip-types --test tests/shipping-input-validation.test.mjs",
12
12
  "test:errors": "node --experimental-strip-types --test tests/public-error.test.mjs",
13
13
  "test:addresses": "node --experimental-strip-types --test tests/checkout-addresses.test.mjs",
@@ -8,6 +8,7 @@ type Props = {
8
8
  carrier: CarrierPickupKind
9
9
  selected: CarrierPickupPoint | null
10
10
  postalCode: string
11
+ packetaWidgetKey?: string | null
11
12
  locale: "hu" | "en"
12
13
  onSelect: (point: CarrierPickupPoint) => void
13
14
  onClose: () => void
@@ -21,7 +22,7 @@ const carrierLabels: Record<CarrierPickupKind, string> = {
21
22
  mpl: "MPL / PostaPont",
22
23
  }
23
24
 
24
- export function CarrierPickupDialog({ carrier, selected, postalCode, locale, onSelect, onClose }: Props) {
25
+ export function CarrierPickupDialog({ carrier, selected, postalCode, packetaWidgetKey, locale, onSelect, onClose }: Props) {
25
26
  const titleId = useId()
26
27
  const closeRef = useRef<HTMLButtonElement>(null)
27
28
  const previousFocus = useRef<HTMLElement | null>(null)
@@ -108,7 +109,7 @@ export function CarrierPickupDialog({ carrier, selected, postalCode, locale, onS
108
109
  onClick={onClose} aria-label={locale === "en" ? "Close map" : "Térkép bezárása"}>×</button>
109
110
  </div>
110
111
  <div className="hszrdm-pickup-body">
111
- <CarrierPickupMap carrier={carrier} locale={locale} postalCode={postalCode}
112
+ <CarrierPickupMap carrier={carrier} locale={locale} postalCode={postalCode} packetaWidgetKey={packetaWidgetKey}
112
113
  selected={selected} onSelect={choose} autoOpen />
113
114
  </div>
114
115
  </section>
@@ -58,7 +58,7 @@ function loadWidgetScript(url: string, module = false): Promise<void> {
58
58
  }
59
59
 
60
60
  export function CarrierPickupMap({
61
- carrier, onSelect, selected, locale = "hu", postalCode = "", autoOpen = false,
61
+ carrier, onSelect, selected, locale = "hu", postalCode = "", autoOpen = false, packetaWidgetKey = null,
62
62
  }: {
63
63
  carrier: CarrierPickupKind
64
64
  onSelect: (point: CarrierPickupPoint | null) => void
@@ -66,6 +66,8 @@ export function CarrierPickupMap({
66
66
  locale?: "hu" | "en"
67
67
  postalCode?: string
68
68
  autoOpen?: boolean
69
+ /** Public Packeta widget identifier from Core /store/core-config (never API_PASSWORD). */
70
+ packetaWidgetKey?: string | null
69
71
  }) {
70
72
  const rawId = useId().replace(/[^a-zA-Z0-9_-]/g, "")
71
73
  const containerId = `hszrdm-pickup-${rawId}`
@@ -121,8 +123,8 @@ export function CarrierPickupMap({
121
123
  return
122
124
  }
123
125
  if (carrier === "packeta") {
124
- if (!process.env.NEXT_PUBLIC_PACKETA_WIDGET_API_KEY?.trim()) {
125
- throw new Error("Hiányzik a NEXT_PUBLIC_PACKETA_WIDGET_API_KEY. A Packeta térképhez nyilvános widget-kulcs szükséges.")
126
+ if (!packetaWidgetKey?.trim()) {
127
+ throw new Error("A Packeta térképhez nincs nyilvános API-kulcs beállítva. Ellenőrizd a Packeta integrációt az Adminban.")
126
128
  }
127
129
  await loadWidgetScript(PACKETA_SCRIPT)
128
130
  if (!alive) return
@@ -157,10 +159,10 @@ export function CarrierPickupMap({
157
159
  if (carrier === "packeta") globals.Packeta?.Widget?.close?.()
158
160
  if (carrier === "mpl" && globals.ppapi) globals.ppapi.onSelect = undefined
159
161
  }
160
- }, [carrier, containerId, locale, zipId])
162
+ }, [carrier, containerId, locale, zipId, packetaWidgetKey])
161
163
 
162
164
  const openPacketa = useCallback(() => {
163
- const key = process.env.NEXT_PUBLIC_PACKETA_WIDGET_API_KEY?.trim()
165
+ const key = packetaWidgetKey?.trim()
164
166
  if (!key) { setError("Nincs Packeta widget-kulcs."); return }
165
167
  const widget = (window as WidgetGlobals).Packeta?.Widget
166
168
  if (!widget?.pick) { setError("A Packeta térkép még nem töltődött be."); return }
@@ -169,7 +171,7 @@ export function CarrierPickupMap({
169
171
  if (point) { setError(""); onSelectRef.current(point) }
170
172
  else setError("A Packeta nem adott vissza érvényes pontazonosítót.")
171
173
  } }, { country: "hu", language: locale })
172
- }, [locale])
174
+ }, [locale, packetaWidgetKey])
173
175
 
174
176
  useEffect(() => {
175
177
  if (autoOpen && ready && carrier === "packeta") openPacketa()
@@ -999,6 +999,7 @@ export function CheckoutFlow({ config }: { config: CoreConfig }) {
999
999
  carrier={pickup}
1000
1000
  selected={selectedPickupPoint}
1001
1001
  postalCode={address.postal_code}
1002
+ packetaWidgetKey={config.shipping.packeta?.widget_api_key}
1002
1003
  locale={locale}
1003
1004
  onSelect={setSelectedPickupPoint}
1004
1005
  onClose={() => setPickupDialogOpen(false)}
@@ -44,7 +44,7 @@ export type CoreConfig = {
44
44
  marker: "shipping_method.data.cod"
45
45
  }
46
46
  }
47
- shipping: Record<string, { enabled: boolean }>
47
+ shipping: Record<string, { enabled: boolean; widget_api_key?: string | null }>
48
48
  after_sales: {
49
49
  enabled: boolean
50
50
  returns: boolean
@@ -0,0 +1,20 @@
1
+ import assert from "node:assert/strict"
2
+ import { readFileSync } from "node:fs"
3
+ import { test } from "node:test"
4
+
5
+ const source = (path) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8")
6
+
7
+ test("Packeta widget uses the Admin-sourced Core config, not a build-time NEXT_PUBLIC secret", () => {
8
+ const map = source("components/carrier-pickup-map.tsx")
9
+ const dialog = source("components/carrier-pickup-dialog.tsx")
10
+ const checkout = source("components/checkout-flow.tsx")
11
+ const contract = source("lib/core/types.ts")
12
+
13
+ assert.ok(map.includes("packetaWidgetKey?.trim()"))
14
+ assert.ok(map.includes("widget.pick(key,"))
15
+ assert.ok(map.includes("https://widget.packeta.com/v6/www/js/library.js"))
16
+ assert.ok(!map.includes("NEXT_PUBLIC_PACKETA_WIDGET_API_KEY"))
17
+ assert.ok(dialog.includes("packetaWidgetKey={packetaWidgetKey}"))
18
+ assert.ok(checkout.includes("packetaWidgetKey={config.shipping.packeta?.widget_api_key}"))
19
+ assert.ok(contract.includes("widget_api_key?: string | null"))
20
+ })