@open-mercato/cli 0.11.1-develop.8883.1.78d3645a50 → 0.11.1-develop.8920.1.d3c2cc4681

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 (166) hide show
  1. package/.turbo/turbo-build.log +7 -1
  2. package/dist/agentic/guides/integrations.md +1 -1
  3. package/dist/agentic/guides/module-facts.json +2106 -181
  4. package/dist/agentic/guides/module-facts.v2.json +2106 -181
  5. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  6. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  8. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  9. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  10. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  11. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  12. package/dist/agentic/guides/modules/auth/index.md +1 -1
  13. package/dist/agentic/guides/modules/availability/index.md +1 -1
  14. package/dist/agentic/guides/modules/backups/index.md +1 -1
  15. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  16. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  17. package/dist/agentic/guides/modules/cart/index.md +1 -1
  18. package/dist/agentic/guides/modules/catalog/acl-features.md +3 -1
  19. package/dist/agentic/guides/modules/catalog/backend-pages.md +3 -0
  20. package/dist/agentic/guides/modules/catalog/contribution-resolutions.md +4 -0
  21. package/dist/agentic/guides/modules/catalog/custom-entities.md +1 -0
  22. package/dist/agentic/guides/modules/catalog/domain-commands.md +3 -1
  23. package/dist/agentic/guides/modules/catalog/entities.md +3 -0
  24. package/dist/agentic/guides/modules/catalog/events.md +4 -1
  25. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +5 -0
  26. package/dist/agentic/guides/modules/catalog/host-extension-points.md +1 -1
  27. package/dist/agentic/guides/modules/catalog/index.md +6 -6
  28. package/dist/agentic/guides/modules/catalog/search-entities.md +1 -0
  29. package/dist/agentic/guides/modules/catalog/umes-contributions.md +4 -0
  30. package/dist/agentic/guides/modules/catalog/umes-hosts.md +8 -0
  31. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  33. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  35. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  36. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  37. package/dist/agentic/guides/modules/channel_ms365/acl-features.md +12 -0
  38. package/dist/agentic/guides/modules/channel_ms365/contribution-resolutions.md +12 -0
  39. package/dist/agentic/guides/modules/channel_ms365/di-registrations-rich.md +12 -0
  40. package/dist/agentic/guides/modules/channel_ms365/exact-override-targets.md +17 -0
  41. package/dist/agentic/guides/modules/channel_ms365/index.md +18 -0
  42. package/dist/agentic/guides/modules/channel_ms365/owned-contract-module-metadata.md +11 -0
  43. package/dist/agentic/guides/modules/channel_ms365/setup.md +11 -0
  44. package/dist/agentic/guides/modules/channel_ms365/umes-contributions.md +12 -0
  45. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  46. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  47. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  48. package/dist/agentic/guides/modules/checkout/exact-override-targets.md +1 -1
  49. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  50. package/dist/agentic/guides/modules/checkout/workers.md +1 -1
  51. package/dist/agentic/guides/modules/communication_channels/incoming-installed-contributions.md +1 -0
  52. package/dist/agentic/guides/modules/communication_channels/index.md +2 -2
  53. package/dist/agentic/guides/modules/configs/acl-features.md +3 -1
  54. package/dist/agentic/guides/modules/configs/backend-pages.md +1 -0
  55. package/dist/agentic/guides/modules/configs/exact-override-targets.md +3 -0
  56. package/dist/agentic/guides/modules/configs/index.md +3 -3
  57. package/dist/agentic/guides/modules/configs/owned-contract-module-metadata.md +1 -1
  58. package/dist/agentic/guides/modules/configs/umes-hosts.md +1 -0
  59. package/dist/agentic/guides/modules/content/index.md +1 -1
  60. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  61. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  62. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  63. package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
  64. package/dist/agentic/guides/modules/customers/index.md +1 -1
  65. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  66. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  67. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  68. package/dist/agentic/guides/modules/devices/index.md +1 -1
  69. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  70. package/dist/agentic/guides/modules/directory/index.md +1 -1
  71. package/dist/agentic/guides/modules/documents/index.md +1 -1
  72. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  73. package/dist/agentic/guides/modules/entities/index.md +1 -1
  74. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  75. package/dist/agentic/guides/modules/events/index.md +1 -1
  76. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  77. package/dist/agentic/guides/modules/forms/index.md +1 -1
  78. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  79. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  80. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  81. package/dist/agentic/guides/modules/generators/index.md +1 -1
  82. package/dist/agentic/guides/modules/gus_regon/acl-features.md +11 -0
  83. package/dist/agentic/guides/modules/gus_regon/cli-commands.md +12 -0
  84. package/dist/agentic/guides/modules/gus_regon/contribution-resolutions.md +11 -0
  85. package/dist/agentic/guides/modules/gus_regon/di-registrations-rich.md +11 -0
  86. package/dist/agentic/guides/modules/gus_regon/exact-override-targets.md +17 -0
  87. package/dist/agentic/guides/modules/gus_regon/index.md +19 -0
  88. package/dist/agentic/guides/modules/gus_regon/owned-contract-module-metadata.md +11 -0
  89. package/dist/agentic/guides/modules/gus_regon/setup.md +11 -0
  90. package/dist/agentic/guides/modules/gus_regon/umes-contributions.md +11 -0
  91. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  92. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  93. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  94. package/dist/agentic/guides/modules/maintenance/index.md +1 -1
  95. package/dist/agentic/guides/modules/messages/index.md +1 -1
  96. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  97. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  98. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  99. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  100. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  101. package/dist/agentic/guides/modules/planner/index.md +1 -1
  102. package/dist/agentic/guides/modules/portal/index.md +1 -1
  103. package/dist/agentic/guides/modules/progress/index.md +1 -1
  104. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  105. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  106. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  107. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  108. package/dist/agentic/guides/modules/resources/index.md +1 -1
  109. package/dist/agentic/guides/modules/sales/index.md +1 -1
  110. package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
  111. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  112. package/dist/agentic/guides/modules/search/index.md +1 -1
  113. package/dist/agentic/guides/modules/security/index.md +1 -1
  114. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  115. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  116. package/dist/agentic/guides/modules/sso/index.md +1 -1
  117. package/dist/agentic/guides/modules/staff/index.md +1 -1
  118. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  119. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  120. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  121. package/dist/agentic/guides/modules/sync_shopify/acl-features.md +12 -0
  122. package/dist/agentic/guides/modules/sync_shopify/cli-commands.md +12 -0
  123. package/dist/agentic/guides/modules/sync_shopify/contribution-resolutions.md +11 -0
  124. package/dist/agentic/guides/modules/sync_shopify/di-registrations-rich.md +11 -0
  125. package/dist/agentic/guides/modules/sync_shopify/exact-override-targets.md +17 -0
  126. package/dist/agentic/guides/modules/sync_shopify/index.md +19 -0
  127. package/dist/agentic/guides/modules/sync_shopify/owned-contract-module-metadata.md +11 -0
  128. package/dist/agentic/guides/modules/sync_shopify/setup.md +11 -0
  129. package/dist/agentic/guides/modules/sync_shopify/umes-contributions.md +11 -0
  130. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  131. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  132. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  133. package/dist/agentic/guides/modules/translations/index.md +1 -1
  134. package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
  135. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  136. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  137. package/dist/agentic/guides/modules/wms/index.md +1 -1
  138. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  139. package/dist/agentic/guides/reference-module-facts.json +2 -2
  140. package/dist/agentic/guides/reference-modules/example/index.md +1 -1
  141. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +18 -0
  142. package/dist/agentic/guides/upstream/manifest.json +2 -2
  143. package/dist/agentic/shared/ai/harness/cases.json +4 -3
  144. package/dist/agentic/shared/ai/skills/om-integration-builder/references/provider-families.md +1 -1
  145. package/dist/lib/init-secrets.js +1 -1
  146. package/dist/lib/init-secrets.js.map +2 -2
  147. package/dist/lib/server-start-lock.js +120 -21
  148. package/dist/lib/server-start-lock.js.map +2 -2
  149. package/dist/lib/testing/integration-discovery.js +13 -0
  150. package/dist/lib/testing/integration-discovery.js.map +2 -2
  151. package/dist/lib/testing/integration.js +286 -26
  152. package/dist/lib/testing/integration.js.map +2 -2
  153. package/dist/mercato.js +9 -2
  154. package/dist/mercato.js.map +2 -2
  155. package/package.json +7 -7
  156. package/src/__tests__/mercato.test.ts +68 -0
  157. package/src/lib/__tests__/init-secrets.test.ts +11 -2
  158. package/src/lib/__tests__/server-start-lock.test.ts +400 -0
  159. package/src/lib/generators/__tests__/module-facts.extension-hosts.test.ts +2 -0
  160. package/src/lib/init-secrets.ts +1 -1
  161. package/src/lib/server-start-lock.ts +170 -19
  162. package/src/lib/testing/__tests__/integration-prebuilt-artifacts.test.ts +486 -0
  163. package/src/lib/testing/__tests__/integration.test.ts +27 -0
  164. package/src/lib/testing/integration-discovery.ts +16 -0
  165. package/src/lib/testing/integration.ts +366 -27
  166. package/src/mercato.ts +9 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.11.1-develop.8883.1.78d3645a50",
3
+ "version": "0.11.1-develop.8920.1.d3c2cc4681",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -60,10 +60,10 @@
60
60
  "@mikro-orm/decorators": "^7.1.14",
61
61
  "@mikro-orm/migrations": "^7.1.14",
62
62
  "@mikro-orm/postgresql": "^7.1.14",
63
- "@open-mercato/events": "0.11.1-develop.8883.1.78d3645a50",
64
- "@open-mercato/queue": "0.11.1-develop.8883.1.78d3645a50",
65
- "@open-mercato/shared": "0.11.1-develop.8883.1.78d3645a50",
66
- "@open-mercato/telemetry": "0.11.1-develop.8883.1.78d3645a50",
63
+ "@open-mercato/events": "0.11.1-develop.8920.1.d3c2cc4681",
64
+ "@open-mercato/queue": "0.11.1-develop.8920.1.d3c2cc4681",
65
+ "@open-mercato/shared": "0.11.1-develop.8920.1.d3c2cc4681",
66
+ "@open-mercato/telemetry": "0.11.1-develop.8920.1.d3c2cc4681",
67
67
  "cross-spawn": "^7.0.6",
68
68
  "minisearch": "7.2.0",
69
69
  "pg": "8.23.0",
@@ -75,10 +75,10 @@
75
75
  "typescript-js": "npm:typescript@6.0.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.11.1-develop.8883.1.78d3645a50"
78
+ "@open-mercato/shared": "0.11.1-develop.8920.1.d3c2cc4681"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.11.1-develop.8883.1.78d3645a50",
81
+ "@open-mercato/shared": "0.11.1-develop.8920.1.d3c2cc4681",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -1426,6 +1426,74 @@ describe('init command failure output', () => {
1426
1426
  }
1427
1427
  })
1428
1428
 
1429
+ it('keeps development demo defaults out of explicit password overrides', async () => {
1430
+ const previousEnv = { ...process.env }
1431
+ jest.spyOn(console, 'error').mockImplementation()
1432
+ jest.spyOn(console, 'log').mockImplementation()
1433
+ process.env.NODE_ENV = 'development'
1434
+ delete process.env.OM_INIT_ADMIN_PASSWORD
1435
+ delete process.env.OM_INIT_EMPLOYEE_PASSWORD
1436
+ const authSetup = jest.fn().mockImplementation(async () => {
1437
+ expect(process.env.OM_INIT_ADMIN_PASSWORD).toBeUndefined()
1438
+ expect(process.env.OM_INIT_EMPLOYEE_PASSWORD).toBeUndefined()
1439
+ })
1440
+ mockInitDependencies({ authSetup })
1441
+ try {
1442
+ const mercato = await import('../mercato')
1443
+ expect(await mercato.run(['node', 'mercato', 'init'])).toBe(0)
1444
+ expect(authSetup).toHaveBeenCalledWith(expect.arrayContaining(['--include-demo-users', '--skip-password-policy']))
1445
+ } finally {
1446
+ process.env = previousEnv
1447
+ }
1448
+ })
1449
+
1450
+ it('preserves explicitly configured development derived passwords', async () => {
1451
+ const previousEnv = { ...process.env }
1452
+ jest.spyOn(console, 'error').mockImplementation()
1453
+ jest.spyOn(console, 'log').mockImplementation()
1454
+ process.env.NODE_ENV = 'development'
1455
+ process.env.OM_INIT_ADMIN_PASSWORD = 'Custom-Admin-937!'
1456
+ process.env.OM_INIT_EMPLOYEE_PASSWORD = 'Custom-Employee-937!'
1457
+ const authSetup = jest.fn().mockImplementation(async () => {
1458
+ expect(process.env.OM_INIT_ADMIN_PASSWORD).toBe('Custom-Admin-937!')
1459
+ expect(process.env.OM_INIT_EMPLOYEE_PASSWORD).toBe('Custom-Employee-937!')
1460
+ })
1461
+ mockInitDependencies({ authSetup })
1462
+ try {
1463
+ const mercato = await import('../mercato')
1464
+ expect(await mercato.run(['node', 'mercato', 'init'])).toBe(0)
1465
+ expect(authSetup).toHaveBeenCalled()
1466
+ } finally {
1467
+ process.env = previousEnv
1468
+ }
1469
+ })
1470
+
1471
+ it.each(['production', 'PRODUCTION', ' production '])('forwards policy-compliant derived passwords with NODE_ENV=%s', async (nodeEnvironment) => {
1472
+ const previousEnv = { ...process.env }
1473
+ jest.spyOn(console, 'error').mockImplementation()
1474
+ jest.spyOn(console, 'log').mockImplementation()
1475
+ process.env.NODE_ENV = nodeEnvironment
1476
+ process.env.OM_PASSWORD_MIN_LENGTH = '32'
1477
+ process.env.OM_INIT_SUPERADMIN_PASSWORD = 'Unique-Owner-937!'.repeat(3)
1478
+ delete process.env.OM_INIT_ADMIN_PASSWORD
1479
+ delete process.env.OM_INIT_EMPLOYEE_PASSWORD
1480
+ const authSetup = jest.fn().mockImplementation(async () => {
1481
+ const { buildPasswordSchema } = await import('@open-mercato/shared/lib/auth/passwordPolicy')
1482
+ for (const password of [process.env.OM_INIT_ADMIN_PASSWORD, process.env.OM_INIT_EMPLOYEE_PASSWORD]) {
1483
+ expect(buildPasswordSchema().safeParse(password).success).toBe(true)
1484
+ }
1485
+ })
1486
+ mockInitDependencies({ authSetup })
1487
+ try {
1488
+ const mercato = await import('../mercato')
1489
+ expect(await mercato.run(['node', 'mercato', 'init'])).toBe(0)
1490
+ expect(authSetup).toHaveBeenCalledWith(expect.arrayContaining(['--include-demo-users']))
1491
+ expect(authSetup.mock.calls[0][0]).not.toContain('--skip-password-policy')
1492
+ } finally {
1493
+ process.env = previousEnv
1494
+ }
1495
+ })
1496
+
1429
1497
  it('passes --include-demo-users to auth setup by default', async () => {
1430
1498
  const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation()
1431
1499
  const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation()
@@ -1,3 +1,4 @@
1
+ import { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'
1
2
  import { readFileSync } from 'node:fs'
2
3
  import path from 'node:path'
3
4
  import { resolveInitDerivedSecrets, resolveInitSuperadminCredentials } from '../init-secrets'
@@ -30,6 +31,14 @@ describe('resolveInitDerivedSecrets', () => {
30
31
  expect(result.adminPassword).not.toBe(result.employeePassword)
31
32
  })
32
33
 
34
+ it.each(['production', 'PRODUCTION', ' production '])('generates policy-compliant derived credentials for NODE_ENV=%s', (nodeEnvironment) => {
35
+ const env = { NODE_ENV: nodeEnvironment, OM_PASSWORD_MIN_LENGTH: '32' }
36
+ const result = resolveInitDerivedSecrets({ email: 'owner@acme.com', env, randomSource: (size) => Buffer.alloc(size, 255) })
37
+ for (const password of [result.adminPassword, result.employeePassword]) {
38
+ expect(validatePassword(password!, getPasswordPolicy(env)).ok).toBe(true)
39
+ }
40
+ })
41
+
33
42
  it('respects explicit derived overrides', () => {
34
43
  const env: NodeJS.ProcessEnv = {
35
44
  OM_INIT_ADMIN_EMAIL: 'admin@acme.com',
@@ -44,11 +53,11 @@ describe('resolveInitDerivedSecrets', () => {
44
53
  expect(result.employeePassword).toBe('EmployeeSecret')
45
54
  })
46
55
 
47
- it('uses the provided randomSource (base64url-encoded 12 bytes) in production', () => {
56
+ it('uses the provided randomSource with a policy-compliant prefix in production', () => {
48
57
  const env: NodeJS.ProcessEnv = { NODE_ENV: 'production' }
49
58
  const randomBuffer = Buffer.from('abcdefghijkl')
50
59
  const randomSource = () => randomBuffer
51
- const expected = randomBuffer.toString('base64url')
60
+ const expected = `Aa1!${randomBuffer.toString('base64url')}`
52
61
  const result = resolveInitDerivedSecrets({ email: 'boss@acme.com', env, randomSource })
53
62
  expect(result.adminPassword).toBe(expected)
54
63
  expect(result.employeePassword).toBe(expected)
@@ -1,3 +1,5 @@
1
+ import { spawn, type ChildProcess } from 'node:child_process'
2
+ import { createHash } from 'node:crypto'
1
3
  import fs from 'node:fs'
2
4
  import os from 'node:os'
3
5
  import path from 'node:path'
@@ -5,8 +7,105 @@ import path from 'node:path'
5
7
  import {
6
8
  acquireServerStartLock,
7
9
  getServerStartLockPath,
10
+ readProcessStartTime,
8
11
  } from '../server-start-lock'
9
12
 
13
+ const BOOT_ID_PATH = '/proc/sys/kernel/random/boot_id'
14
+ const CURRENT_BOOT_ID = '6f1c2a7e-0b3d-4c58-9a51-2f7e8d4b1c90'
15
+ const hasProcFs = fs.existsSync(`/proc/${process.pid}/stat`)
16
+
17
+ function buildStatLine(pid: number, startTime: string, command = 'node'): string {
18
+ const fieldsBeforeStartTime = ['S', ...Array.from({ length: 18 }, () => '0')]
19
+ return `${pid} (${command}) ${[...fieldsBeforeStartTime, startTime, '1024', '256'].join(' ')}\n`
20
+ }
21
+
22
+ function mockProcFs(entries: Record<string, string>) {
23
+ const realReadFileSync = fs.readFileSync
24
+ return jest.spyOn(fs, 'readFileSync').mockImplementation(((
25
+ file: fs.PathOrFileDescriptor,
26
+ options?: Parameters<typeof fs.readFileSync>[1],
27
+ ) => {
28
+ if (typeof file === 'string' && file.startsWith('/proc/')) {
29
+ const content = entries[file]
30
+ if (content === undefined) {
31
+ const missing = new Error(`ENOENT: no such file or directory, open '${file}'`) as NodeJS.ErrnoException
32
+ missing.code = 'ENOENT'
33
+ throw missing
34
+ }
35
+ return content
36
+ }
37
+ return realReadFileSync(file, options)
38
+ }) as typeof fs.readFileSync)
39
+ }
40
+
41
+ function writeLock(lockPath: string, record: Record<string, unknown>) {
42
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true })
43
+ fs.writeFileSync(lockPath, JSON.stringify(record))
44
+ }
45
+
46
+ const LOCK_MODULE_PATH = path.resolve(__dirname, '../server-start-lock.ts')
47
+
48
+ // Runs acquireServerStartLock in a separate Node process. The "late" contender
49
+ // pauses right after it has inspected the stale lock, at the first step that
50
+ // could remove it (claiming the takeover guard, or deleting the lock file), and
51
+ // waits for the `late-resume` marker. Each contender reports `acquired` or
52
+ // `refused` and stays alive, holding what it got, until the `exit` marker.
53
+ const CONTENDER_SCRIPT = `
54
+ import fs from 'node:fs'
55
+ import path from 'node:path'
56
+
57
+ const [modulePath, appDir, role, syncDir] = process.argv.slice(2)
58
+ const lockPath = path.join(appDir, '.mercato', 'server-start.lock')
59
+ const marker = (name) => path.join(syncDir, name)
60
+ const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
61
+ const waitFor = (name) => { while (!fs.existsSync(marker(name))) sleep(5) }
62
+
63
+ if (role === 'late') {
64
+ const realLinkSync = fs.linkSync
65
+ const realRmSync = fs.rmSync
66
+ let paused = false
67
+ const pause = () => {
68
+ if (paused) return
69
+ paused = true
70
+ fs.writeFileSync(marker('late-paused'), '')
71
+ waitFor('late-resume')
72
+ }
73
+ fs.linkSync = (source, target) => {
74
+ if (String(target).endsWith('.takeover')) pause()
75
+ return realLinkSync(source, target)
76
+ }
77
+ fs.rmSync = (target, options) => {
78
+ if (String(target) === lockPath) pause()
79
+ return realRmSync(target, options)
80
+ }
81
+ }
82
+
83
+ const { acquireServerStartLock } = await import(modulePath)
84
+ let result
85
+ try {
86
+ acquireServerStartLock(appDir, { port: role })
87
+ result = 'acquired'
88
+ } catch (error) {
89
+ result = 'refused: ' + error.message
90
+ }
91
+ fs.writeFileSync(marker(role + '-result'), result)
92
+ waitFor('exit')
93
+ `
94
+
95
+ async function waitForFile(filePath: string, timeoutMs = 15000): Promise<string> {
96
+ const deadline = Date.now() + timeoutMs
97
+ while (!fs.existsSync(filePath)) {
98
+ if (Date.now() > deadline) throw new Error(`Timed out waiting for ${filePath}`)
99
+ await new Promise((resolve) => setTimeout(resolve, 5))
100
+ }
101
+ return fs.readFileSync(filePath, 'utf8')
102
+ }
103
+
104
+ function waitForExit(child: ChildProcess): Promise<void> {
105
+ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve()
106
+ return new Promise((resolve) => child.once('exit', () => resolve()))
107
+ }
108
+
10
109
  describe('server start lock', () => {
11
110
  let tempDir: string
12
111
 
@@ -15,6 +114,7 @@ describe('server start lock', () => {
15
114
  })
16
115
 
17
116
  afterEach(() => {
117
+ jest.restoreAllMocks()
18
118
  fs.rmSync(tempDir, { recursive: true, force: true })
19
119
  })
20
120
 
@@ -63,4 +163,304 @@ describe('server start lock', () => {
63
163
  `Another Open Mercato production server is already running for ${tempDir}`,
64
164
  )
65
165
  })
166
+
167
+ it('takes over a lock whose pid now belongs to an unrelated process', () => {
168
+ mockProcFs({
169
+ [BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
170
+ [`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
171
+ [`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '4321', 'sh'),
172
+ })
173
+ const lockPath = getServerStartLockPath(tempDir)
174
+ writeLock(lockPath, {
175
+ pid: process.ppid,
176
+ port: '3000',
177
+ startedAt: new Date().toISOString(),
178
+ processStartTime: '1234',
179
+ bootId: CURRENT_BOOT_ID,
180
+ })
181
+
182
+ const handle = acquireServerStartLock(tempDir, { port: '3000' })
183
+
184
+ const written = JSON.parse(fs.readFileSync(lockPath, 'utf8'))
185
+ expect(written).toMatchObject({
186
+ pid: process.pid,
187
+ port: '3000',
188
+ processStartTime: '90210',
189
+ bootId: CURRENT_BOOT_ID,
190
+ })
191
+
192
+ handle.release()
193
+ })
194
+
195
+ it('refuses a lock whose owner is still the same running process', () => {
196
+ mockProcFs({
197
+ [BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
198
+ [`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
199
+ [`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '1234'),
200
+ })
201
+ const lockPath = getServerStartLockPath(tempDir)
202
+ writeLock(lockPath, {
203
+ pid: process.ppid,
204
+ port: '3000',
205
+ startedAt: new Date().toISOString(),
206
+ processStartTime: '1234',
207
+ bootId: CURRENT_BOOT_ID,
208
+ })
209
+
210
+ expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
211
+ `Another Open Mercato production server is already running for ${tempDir} (pid ${process.ppid} on port 3000)`,
212
+ )
213
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid).toBe(process.ppid)
214
+ })
215
+
216
+ it('takes over a lock written before a reboot', () => {
217
+ mockProcFs({
218
+ [BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
219
+ [`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
220
+ [`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '1234'),
221
+ })
222
+ const lockPath = getServerStartLockPath(tempDir)
223
+ writeLock(lockPath, {
224
+ pid: process.ppid,
225
+ port: '3000',
226
+ startedAt: new Date().toISOString(),
227
+ processStartTime: '1234',
228
+ bootId: 'a-previous-boot',
229
+ })
230
+
231
+ const handle = acquireServerStartLock(tempDir, { port: '3000' })
232
+
233
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid).toBe(process.pid)
234
+ handle.release()
235
+ })
236
+
237
+ it('keeps refusing a live pid from a lock written by an older version', () => {
238
+ mockProcFs({
239
+ [BOOT_ID_PATH]: `${CURRENT_BOOT_ID}\n`,
240
+ [`/proc/${process.pid}/stat`]: buildStatLine(process.pid, '90210'),
241
+ [`/proc/${process.ppid}/stat`]: buildStatLine(process.ppid, '4321'),
242
+ })
243
+ const lockPath = getServerStartLockPath(tempDir)
244
+ writeLock(lockPath, {
245
+ pid: process.ppid,
246
+ port: '3000',
247
+ startedAt: new Date().toISOString(),
248
+ })
249
+
250
+ expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
251
+ `Another Open Mercato production server is already running for ${tempDir}`,
252
+ )
253
+ })
254
+
255
+ it('falls back to the pid check where /proc is unavailable', () => {
256
+ mockProcFs({})
257
+ const lockPath = getServerStartLockPath(tempDir)
258
+ writeLock(lockPath, {
259
+ pid: process.ppid,
260
+ port: '3000',
261
+ startedAt: new Date().toISOString(),
262
+ processStartTime: '1234',
263
+ bootId: CURRENT_BOOT_ID,
264
+ })
265
+
266
+ expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
267
+ `Another Open Mercato production server is already running for ${tempDir}`,
268
+ )
269
+
270
+ fs.rmSync(lockPath)
271
+ const handle = acquireServerStartLock(tempDir, { port: '3000' })
272
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toMatchObject({
273
+ pid: process.pid,
274
+ processStartTime: null,
275
+ bootId: null,
276
+ })
277
+ handle.release()
278
+ })
279
+
280
+ it('reads the start time when the command name contains spaces and parentheses', () => {
281
+ mockProcFs({
282
+ '/proc/4242/stat': buildStatLine(4242, '777001', 'node (server) 9 S'),
283
+ '/proc/4243/stat': '4243 (broken',
284
+ })
285
+
286
+ expect(readProcessStartTime(4242)).toBe('777001')
287
+ expect(readProcessStartTime(4243)).toBeNull()
288
+ expect(readProcessStartTime(4244)).toBeNull()
289
+ })
290
+
291
+ ;(hasProcFs ? it : it.skip)('identifies the real lock owner through /proc', () => {
292
+ const parentStartTime = readProcessStartTime(process.ppid)
293
+ expect(parentStartTime).toMatch(/^\d+$/)
294
+ const lockPath = getServerStartLockPath(tempDir)
295
+ writeLock(lockPath, {
296
+ pid: process.ppid,
297
+ port: '3000',
298
+ startedAt: new Date().toISOString(),
299
+ processStartTime: parentStartTime,
300
+ })
301
+
302
+ expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
303
+ `Another Open Mercato production server is already running for ${tempDir}`,
304
+ )
305
+
306
+ writeLock(lockPath, {
307
+ pid: process.ppid,
308
+ port: '3000',
309
+ startedAt: new Date().toISOString(),
310
+ processStartTime: `${parentStartTime}1`,
311
+ })
312
+ const handle = acquireServerStartLock(tempDir, { port: '3000' })
313
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).processStartTime).toBe(readProcessStartTime(process.pid))
314
+ handle.release()
315
+ })
316
+
317
+ it('does not let an old owner release a lock that has been taken over', () => {
318
+ const handle = acquireServerStartLock(tempDir, { port: '3000' })
319
+ const lockPath = handle.lockPath
320
+ const winner = {
321
+ pid: process.pid,
322
+ port: '3001',
323
+ startedAt: new Date().toISOString(),
324
+ token: 'winner-token',
325
+ }
326
+ writeLock(lockPath, winner)
327
+
328
+ handle.release()
329
+
330
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toMatchObject(winner)
331
+ })
332
+
333
+ it('waits for a live takeover in progress and then refuses the new owner', () => {
334
+ const lockPath = getServerStartLockPath(tempDir)
335
+ const staleRaw = JSON.stringify({ pid: 999999, port: '3000', startedAt: new Date(0).toISOString() })
336
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true })
337
+ fs.writeFileSync(lockPath, staleRaw)
338
+
339
+ // Another live process holds the takeover guard of this generation. While it
340
+ // holds it, this process must neither remove the stale lock nor claim a guard
341
+ // slot of its own. Once the holder has written its lock, this process refuses.
342
+ const realLinkSync = fs.linkSync
343
+ let guardAttempts = 0
344
+ jest.spyOn(fs, 'linkSync').mockImplementation(((source: fs.PathLike, target: fs.PathLike) => {
345
+ if (String(target).endsWith('.takeover')) {
346
+ guardAttempts += 1
347
+ if (guardAttempts === 1) {
348
+ realLinkSync(source, target)
349
+ fs.writeFileSync(String(target), JSON.stringify({ pid: process.ppid, port: '3001', startedAt: '' }))
350
+ const busy = new Error('EEXIST') as NodeJS.ErrnoException
351
+ busy.code = 'EEXIST'
352
+ throw busy
353
+ }
354
+ }
355
+ return realLinkSync(source, target)
356
+ }) as typeof fs.linkSync)
357
+ const realRmSync = fs.rmSync
358
+ let finishedForeignTakeover = false
359
+ jest.spyOn(global.Atomics, 'wait').mockImplementation(() => {
360
+ if (!finishedForeignTakeover) {
361
+ finishedForeignTakeover = true
362
+ expect(fs.readFileSync(lockPath, 'utf8')).toBe(staleRaw)
363
+ realRmSync(lockPath)
364
+ fs.writeFileSync(lockPath, JSON.stringify({ pid: process.ppid, port: '3001', startedAt: '' }))
365
+ for (const entry of fs.readdirSync(path.dirname(lockPath))) {
366
+ if (entry.endsWith('.takeover')) realRmSync(path.join(path.dirname(lockPath), entry))
367
+ }
368
+ }
369
+ return 'timed-out'
370
+ })
371
+
372
+ expect(() => acquireServerStartLock(tempDir, { port: '3000' })).toThrow(
373
+ `Another Open Mercato production server is already running for ${tempDir} (pid ${process.ppid} on port 3001)`,
374
+ )
375
+ expect(guardAttempts).toBe(1)
376
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).port).toBe('3001')
377
+ })
378
+
379
+ it('skips a takeover guard left behind by a process that died mid-takeover', () => {
380
+ const lockPath = getServerStartLockPath(tempDir)
381
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true })
382
+ fs.writeFileSync(lockPath, JSON.stringify({ pid: 999999, port: '3000', startedAt: new Date(0).toISOString() }))
383
+ const realLinkSync = fs.linkSync
384
+ let plantedDeadGuard = false
385
+ jest.spyOn(fs, 'linkSync').mockImplementation(((source: fs.PathLike, target: fs.PathLike) => {
386
+ if (!plantedDeadGuard && String(target).endsWith('.0.takeover')) {
387
+ plantedDeadGuard = true
388
+ fs.writeFileSync(String(target), JSON.stringify({ pid: 999998, port: null, startedAt: '' }))
389
+ }
390
+ return realLinkSync(source, target)
391
+ }) as typeof fs.linkSync)
392
+
393
+ const handle = acquireServerStartLock(tempDir, { port: '3000' })
394
+
395
+ expect(plantedDeadGuard).toBe(true)
396
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8')).pid).toBe(process.pid)
397
+ handle.release()
398
+ expect(fs.readdirSync(path.dirname(lockPath))).toEqual([])
399
+ })
400
+
401
+ it('preserves a live takeover guard when reading it fails', () => {
402
+ const lockPath = getServerStartLockPath(tempDir)
403
+ const staleLock = { pid: 999999, port: '3000', startedAt: new Date(0).toISOString() }
404
+ writeLock(lockPath, staleLock)
405
+
406
+ const generation = createHash('sha256').update(JSON.stringify(staleLock)).digest('hex').slice(0, 16)
407
+ const guardPath = `${lockPath}.${generation}.0.takeover`
408
+ const liveGuard = { pid: process.ppid, port: null, startedAt: '' }
409
+ writeLock(guardPath, liveGuard)
410
+
411
+ const readError = Object.assign(new Error('takeover guard read failed'), { code: 'EIO' })
412
+ const realReadFileSync = fs.readFileSync
413
+ const readSpy = jest.spyOn(fs, 'readFileSync').mockImplementation(((
414
+ filePath: fs.PathOrFileDescriptor,
415
+ options?: Parameters<typeof fs.readFileSync>[1],
416
+ ) => {
417
+ if (filePath === guardPath) throw readError
418
+ return realReadFileSync(filePath, options)
419
+ }) as typeof fs.readFileSync)
420
+
421
+ expect(() => acquireServerStartLock(tempDir)).toThrow(readError)
422
+ readSpy.mockRestore()
423
+ expect(JSON.parse(fs.readFileSync(guardPath, 'utf8'))).toEqual(liveGuard)
424
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toEqual(staleLock)
425
+ })
426
+
427
+ it('lets exactly one of two processes recover the same stale lock', async () => {
428
+ const scriptPath = path.join(tempDir, 'contender.mjs')
429
+ fs.writeFileSync(scriptPath, CONTENDER_SCRIPT)
430
+ const env = { ...process.env }
431
+ delete env.NODE_OPTIONS
432
+
433
+ for (let trial = 0; trial < 10; trial += 1) {
434
+ const appDir = path.join(tempDir, `app-${trial}`)
435
+ const syncDir = path.join(tempDir, `sync-${trial}`)
436
+ fs.mkdirSync(syncDir, { recursive: true })
437
+ const lockPath = getServerStartLockPath(appDir)
438
+ writeLock(lockPath, { pid: 999999, port: '3000', startedAt: new Date(0).toISOString() })
439
+
440
+ const startContender = (role: 'early' | 'late') =>
441
+ spawn(process.execPath, [scriptPath, LOCK_MODULE_PATH, appDir, role, syncDir], {
442
+ env,
443
+ stdio: ['ignore', 'ignore', 'inherit'],
444
+ })
445
+
446
+ const late = startContender('late')
447
+ let early: ChildProcess | null = null
448
+ try {
449
+ await waitForFile(path.join(syncDir, 'late-paused'))
450
+ early = startContender('early')
451
+ expect(await waitForFile(path.join(syncDir, 'early-result'))).toBe('acquired')
452
+
453
+ fs.writeFileSync(path.join(syncDir, 'late-resume'), '')
454
+ expect(await waitForFile(path.join(syncDir, 'late-result'))).toContain(
455
+ `refused: [server] Another Open Mercato production server is already running for ${appDir} (pid ${early.pid} on port early)`,
456
+ )
457
+ expect(JSON.parse(fs.readFileSync(lockPath, 'utf8'))).toMatchObject({ pid: early.pid, port: 'early' })
458
+ } finally {
459
+ fs.writeFileSync(path.join(syncDir, 'exit'), '')
460
+ await Promise.all([waitForExit(late), early ? waitForExit(early) : Promise.resolve()])
461
+ }
462
+
463
+ expect(fs.readdirSync(path.dirname(lockPath))).toEqual([])
464
+ }
465
+ }, 120000)
66
466
  })
@@ -28,6 +28,7 @@ describe('module-facts extension host extraction', () => {
28
28
  'catalog:catalog_product',
29
29
  'catalog:catalog_product_variant',
30
30
  'catalog:catalog_product_price',
31
+ 'catalog:catalog_service',
31
32
  ],
32
33
  sales: [
33
34
  'sales:sales_order',
@@ -111,6 +112,7 @@ describe('module-facts extension host extraction', () => {
111
112
  'catalog.categories.list',
112
113
  'catalog.prices.list',
113
114
  'catalog.products.list',
115
+ 'catalog.services.list',
114
116
  ])
115
117
 
116
118
  const sales = extractModuleFacts({ moduleId: 'sales', coreSrcRoot })
@@ -64,7 +64,7 @@ export function resolveInitDerivedSecrets(options: {
64
64
  }
65
65
  const isProduction = (env.NODE_ENV ?? '').trim().toLowerCase() === 'production'
66
66
  const randomize = options.randomSource ?? randomBytes
67
- const randomSecret = () => randomize(12).toString('base64url')
67
+ const randomSecret = () => `Aa1!${randomize(Math.max(12, getPasswordPolicy(env).minLength)).toString('base64url')}`
68
68
  const resolvePassword = (key: string, emailValue: string | null) => {
69
69
  if (!emailValue) return null
70
70
  const envValue = envRead(key)