@prenta/cli 1.3.3 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +67 -53
  3. package/CHANGELOG.md +48 -0
  4. package/dist/commands/doctor.d.ts.map +1 -1
  5. package/dist/commands/doctor.js +86 -31
  6. package/dist/commands/doctor.js.map +1 -1
  7. package/dist/deployment/diagnostics.d.ts +67 -2
  8. package/dist/deployment/diagnostics.d.ts.map +1 -1
  9. package/dist/deployment/diagnostics.js +500 -90
  10. package/dist/deployment/diagnostics.js.map +1 -1
  11. package/dist/deployment/health-check.d.ts +15 -0
  12. package/dist/deployment/health-check.d.ts.map +1 -0
  13. package/dist/deployment/health-check.js +85 -0
  14. package/dist/deployment/health-check.js.map +1 -0
  15. package/dist/deployment/layout.d.ts +19 -0
  16. package/dist/deployment/layout.d.ts.map +1 -0
  17. package/dist/deployment/layout.js +67 -0
  18. package/dist/deployment/layout.js.map +1 -0
  19. package/dist/vercel/env-matrix.d.ts +11 -1
  20. package/dist/vercel/env-matrix.d.ts.map +1 -1
  21. package/dist/vercel/env-matrix.js +6 -1
  22. package/dist/vercel/env-matrix.js.map +1 -1
  23. package/package.json +3 -3
  24. package/src/__tests__/deployment-diagnostics.test.ts +1 -1
  25. package/src/__tests__/doctor-astro-split.test.ts +376 -0
  26. package/src/__tests__/doctor-env-shape-fallback.test.ts +44 -0
  27. package/src/__tests__/rate-limit-backend.test.ts +259 -0
  28. package/src/__tests__/vercel-cron-plan.test.ts +71 -0
  29. package/src/commands/doctor.ts +104 -29
  30. package/src/deployment/diagnostics.ts +569 -95
  31. package/src/deployment/health-check.ts +114 -0
  32. package/src/deployment/layout.ts +90 -0
  33. package/src/vercel/env-matrix.ts +22 -0
@@ -0,0 +1,376 @@
1
+ /**
2
+ * #1263: `prenta doctor` looked for the Astro site in `site/` (astro-split
3
+ * writes `apps/site`), passed detectors whose source file did not exist,
4
+ * accepted a localhost site URL, checked env presence only, and had no
5
+ * checks for CRON_SECRET, a registered Blob adapter, email, the
6
+ * CMS_HOST_ORIGIN placeholder or the Astro project's env.
7
+ *
8
+ * The fixtures mirror the audit's `fake/` and `split/` repro folders.
9
+ */
10
+ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
11
+ import { tmpdir } from 'node:os'
12
+ import path from 'node:path'
13
+ import { Command } from 'commander'
14
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
15
+
16
+ import { registerDeployCheckCommand, registerDoctorCommand } from '../commands/doctor.js'
17
+ import {
18
+ createDiagnosticReport,
19
+ productionOriginProblem,
20
+ type DiagnosticCheck,
21
+ type DiagnosticInput,
22
+ } from '../deployment/diagnostics.js'
23
+ import { resolveProjectLayout } from '../deployment/layout.js'
24
+
25
+ const VALID_ENV = [
26
+ 'DATABASE_URL="postgresql://u:p@db.example.com:5432/prenta"',
27
+ `CMS_SECRET="${'a1'.repeat(24)}"`,
28
+ `CMS_ENCRYPTION_KEY="${'ab'.repeat(32)}"`,
29
+ ].join('\n')
30
+
31
+ async function write(root: string, files: Record<string, string>) {
32
+ for (const [rel, content] of Object.entries(files)) {
33
+ const full = path.join(root, rel)
34
+ await mkdir(path.dirname(full), { recursive: true })
35
+ await writeFile(full, content)
36
+ }
37
+ }
38
+
39
+ let root: string
40
+ const originalCwd = process.cwd()
41
+ // Keep the developer's or CI's own env out of the fixtures.
42
+ const SCRUB = [
43
+ 'DATABASE_URL',
44
+ 'CMS_SECRET',
45
+ 'CMS_ENCRYPTION_KEY',
46
+ 'NEXT_PUBLIC_SITE_URL',
47
+ 'CRON_SECRET',
48
+ 'NODE_ENV',
49
+ 'VERCEL_ENV',
50
+ 'RESEND_API_KEY',
51
+ 'SMTP_HOST',
52
+ 'EMAIL_PROVIDER',
53
+ 'BLOB_READ_WRITE_TOKEN',
54
+ 'BLOB_STORE_ID',
55
+ ]
56
+ const saved: Record<string, string | undefined> = {}
57
+
58
+ beforeEach(async () => {
59
+ root = await mkdtemp(path.join(tmpdir(), 'prenta-doctor-1263-'))
60
+ for (const key of SCRUB) {
61
+ saved[key] = process.env[key]
62
+ delete process.env[key]
63
+ }
64
+ })
65
+
66
+ afterEach(async () => {
67
+ process.chdir(originalCwd)
68
+ for (const key of SCRUB) {
69
+ if (saved[key] === undefined) delete process.env[key]
70
+ else process.env[key] = saved[key]
71
+ }
72
+ vi.restoreAllMocks()
73
+ process.exitCode = undefined
74
+ await rm(root, { recursive: true, force: true })
75
+ })
76
+
77
+ async function runJson(
78
+ command: 'doctor' | 'deploy:check',
79
+ cwd: string,
80
+ ): Promise<{ status: string; checks: DiagnosticCheck[] }> {
81
+ const out: string[] = []
82
+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
83
+ out.push(args.join(' '))
84
+ })
85
+ process.chdir(cwd)
86
+ const program = new Command()
87
+ program.exitOverride()
88
+ registerDoctorCommand(program)
89
+ registerDeployCheckCommand(program)
90
+ await program.parseAsync(['node', 'prenta', command, '--json'])
91
+ vi.restoreAllMocks()
92
+ return JSON.parse(out.join('\n'))
93
+ }
94
+
95
+ const byId = (checks: DiagnosticCheck[], id: string) => checks.find((c) => c.id === id)
96
+
97
+ describe('the fake/ fixture: no app files', () => {
98
+ beforeEach(async () => {
99
+ await write(root, {
100
+ '.env': `${VALID_ENV}\nNEXT_PUBLIC_SITE_URL="http://localhost:3000"`,
101
+ 'package.json': '{}',
102
+ 'prenta.config.ts': 'export default { seo: { siteUrl: "https://x.com" } }',
103
+ })
104
+ })
105
+
106
+ it('skips the Next detectors instead of passing on files that do not exist', async () => {
107
+ const { checks } = await runJson('doctor', root)
108
+ for (const id of [
109
+ 'cached-resolve',
110
+ 'public-sections-ssr',
111
+ 'structured-data-html',
112
+ 'api-cache-invalidation',
113
+ ]) {
114
+ expect(byId(checks, id)?.status, id).toBe('skip')
115
+ }
116
+ })
117
+
118
+ it('fails deploy:check on a localhost site URL, and only warns in doctor', async () => {
119
+ const deploy = await runJson('deploy:check', root)
120
+ expect(byId(deploy.checks, 'seo-site-url')).toMatchObject({ status: 'fail' })
121
+ expect(byId(deploy.checks, 'seo-site-url')?.message).toContain('local address')
122
+ const doctor = await runJson('doctor', root)
123
+ expect(byId(doctor.checks, 'seo-site-url')?.status).toBe('warn')
124
+ })
125
+
126
+ it('fails deploy:check without CRON_SECRET', async () => {
127
+ const { checks } = await runJson('deploy:check', root)
128
+ expect(byId(checks, 'cron-secret')).toMatchObject({ status: 'fail' })
129
+ })
130
+
131
+ it('checks env values with the rules /health uses, not just presence', async () => {
132
+ await write(root, { '.env': `${VALID_ENV}\nCMS_SECRET="too-short"` })
133
+ const { checks } = await runJson('deploy:check', root)
134
+ const shape = byId(checks, 'env-shape')
135
+ expect(shape?.status).toBe('fail')
136
+ expect(shape?.message).toContain('CMS_SECRET')
137
+ // Values are never echoed back.
138
+ expect(shape?.message).not.toContain('too-short')
139
+ })
140
+ })
141
+
142
+ describe('the split/ fixture: an astro-split workspace', () => {
143
+ beforeEach(async () => {
144
+ await write(root, {
145
+ 'package.json': '{}',
146
+ 'apps/cms/.env': `${VALID_ENV}\nNEXT_PUBLIC_SITE_URL="https://example.com"`,
147
+ 'apps/cms/package.json': '{}',
148
+ 'apps/cms/prenta.config.ts': 'export default { seo: { siteUrl: "https://example.com" } }',
149
+ 'apps/cms/app/api/cms/[[...cms]]/route.ts':
150
+ "import { createBlobAdapter } from '@prenta/platform-vercel'\ncreateBlobAdapter()\n",
151
+ 'apps/site/astro.config.mjs': 'export default {}',
152
+ 'apps/site/src/lib/cms.ts':
153
+ "import { createAstroSiteHelpers } from '@prenta/core/astro/site'",
154
+ 'apps/site/vercel.json': JSON.stringify({
155
+ rewrites: [
156
+ { source: '/api/cms/:path*', destination: 'https://CMS_HOST_ORIGIN/api/cms/:path*' },
157
+ ],
158
+ }),
159
+ })
160
+ })
161
+
162
+ it('finds the CMS and site from the repo root and from apps/cms', async () => {
163
+ expect(await resolveProjectLayout(root)).toMatchObject({
164
+ cmsRoot: path.join(root, 'apps/cms'),
165
+ siteRoot: path.join(root, 'apps/site'),
166
+ siteLabel: 'apps/site',
167
+ })
168
+ expect(await resolveProjectLayout(path.join(root, 'apps/cms'))).toMatchObject({
169
+ cmsRoot: path.join(root, 'apps/cms'),
170
+ siteRoot: path.join(root, 'apps/site'),
171
+ siteLabel: '../site',
172
+ })
173
+ })
174
+
175
+ it.each([
176
+ ['repo root', ''],
177
+ ['apps/cms', 'apps/cms'],
178
+ ])('from the %s, reports the Astro site and no Next SEO-route advice', async (_label, rel) => {
179
+ const { checks } = await runJson('doctor', path.join(root, rel))
180
+ expect(byId(checks, 'astro-split-site')?.status).toBe('pass')
181
+ expect(byId(checks, 'astro-cms-helpers')?.status).toBe('pass')
182
+ expect(byId(checks, 'seo-public-routes')?.status).toBe('pass')
183
+ expect(byId(checks, 'seo-public-routes')?.fix).toBeUndefined()
184
+ // The CMS env was read from apps/cms even from the root.
185
+ expect(byId(checks, 'environment')?.status).toBe('pass')
186
+ })
187
+
188
+ it('fails deploy:check on the CMS_HOST_ORIGIN placeholder in the site rewrites', async () => {
189
+ const { checks } = await runJson('deploy:check', root)
190
+ expect(byId(checks, 'astro-cms-host-origin')).toMatchObject({ status: 'fail' })
191
+ expect(byId(checks, 'astro-cms-host-origin')?.message).toContain('apps/site/vercel.json')
192
+ })
193
+
194
+ it('fails deploy:check when the route registers a Blob adapter but no store is linked', async () => {
195
+ const { checks } = await runJson('deploy:check', root)
196
+ expect(byId(checks, 'blob-storage')).toMatchObject({ status: 'fail' })
197
+ })
198
+
199
+ it('skips the site env check when the site has no .env, naming what to set', async () => {
200
+ const { checks } = await runJson('doctor', root)
201
+ const env = byId(checks, 'astro-site-env')
202
+ expect(env?.status).toBe('skip')
203
+ expect(env?.message).toContain('PRENTA_WEBHOOK_SECRET')
204
+ })
205
+
206
+ it('names the missing Astro env and a SITE that differs from NEXT_PUBLIC_SITE_URL', async () => {
207
+ await write(root, {
208
+ 'apps/site/.env': 'SITE="https://www.other.com"\nPRENTA_CMS_URL="https://cms.example.com"',
209
+ })
210
+ const { checks } = await runJson('doctor', root)
211
+ const env = byId(checks, 'astro-site-env')
212
+ expect(env?.status).toBe('warn')
213
+ expect(env?.message).toContain('PRENTA_WEBHOOK_SECRET')
214
+ expect(env?.message).toContain('CLOUDFLARE_ZONE_ID')
215
+ expect(byId(checks, 'astro-site-url-match')).toMatchObject({ status: 'warn' })
216
+ })
217
+
218
+ it('from apps/site, reads the CMS from its sibling apps/cms', async () => {
219
+ expect(await resolveProjectLayout(path.join(root, 'apps/site'))).toMatchObject({
220
+ cmsRoot: path.join(root, 'apps/cms'),
221
+ siteRoot: path.join(root, 'apps/site'),
222
+ })
223
+ const { checks } = await runJson('doctor', path.join(root, 'apps/site'))
224
+ expect(byId(checks, 'environment')?.status).toBe('pass')
225
+ })
226
+
227
+ it('takes an explicit --schema relative to the folder it runs in when that file exists', async () => {
228
+ await write(root, { 'apps/cms/prisma/schema.prisma': 'model User {\n id String @id\n}\n' })
229
+ const out: string[] = []
230
+ vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => void out.push(a.join(' ')))
231
+ process.chdir(root)
232
+ const program = new Command()
233
+ program.exitOverride()
234
+ registerDoctorCommand(program)
235
+ await program.parseAsync([
236
+ 'node',
237
+ 'prenta',
238
+ 'doctor',
239
+ '--json',
240
+ '--schema',
241
+ 'apps/cms/prisma/schema.prisma',
242
+ ])
243
+ vi.restoreAllMocks()
244
+ const models = byId(JSON.parse(out.join('\n')).checks, 'schema-models')
245
+ // It read the file: User is no longer reported missing.
246
+ expect(models?.message).not.toMatch(/Missing[^.]*\bUser\b/)
247
+ })
248
+ })
249
+
250
+ describe('the layout does not borrow a neighbouring project', () => {
251
+ it('ignores a sibling site/ next to a monolith', async () => {
252
+ await write(root, {
253
+ 'proj/prenta.config.ts': 'export default {}',
254
+ 'site/astro.config.mjs': 'export default {}',
255
+ })
256
+ expect((await resolveProjectLayout(path.join(root, 'proj'))).siteRoot).toBeUndefined()
257
+ })
258
+
259
+ it('ignores apps/site two levels up from a monolith', async () => {
260
+ await write(root, {
261
+ 'ws/x/mono/prenta.config.ts': 'export default {}',
262
+ 'ws/apps/site/astro.config.mjs': 'export default {}',
263
+ })
264
+ expect((await resolveProjectLayout(path.join(root, 'ws/x/mono'))).siteRoot).toBeUndefined()
265
+ })
266
+ })
267
+
268
+ describe('env-shape', () => {
269
+ const summary = (checks: Array<{ name: string; status: string; message: string }>) => ({
270
+ errorCount: checks.filter((c) => c.status === 'error').length,
271
+ checks: checks.map((c) => ({ ...c, required: true })),
272
+ })
273
+ const input = (overrides: Partial<DiagnosticInput>): DiagnosticInput => ({
274
+ schemaModels: new Set(),
275
+ env: {},
276
+ packageManager: 'pnpm',
277
+ schemaPath: 'prisma/schema.prisma',
278
+ ...overrides,
279
+ })
280
+
281
+ it('does not fail a Marketplace Blob (OIDC) project for having no read-write token', () => {
282
+ const { checks } = createDiagnosticReport(
283
+ input({
284
+ mode: 'deploy',
285
+ env: { BLOB_STORE_ID: 'store_1' },
286
+ envShape: summary([
287
+ { name: 'BLOB_READ_WRITE_TOKEN', status: 'error', message: 'upload auth is missing' },
288
+ ]),
289
+ }),
290
+ )
291
+ expect(byId(checks, 'env-shape')?.status).toBe('pass')
292
+ expect(byId(checks, 'blob-storage')?.status).toBe('pass')
293
+ })
294
+
295
+ it('fails deploy:check on a malformed value but only warns in doctor', () => {
296
+ const shape = summary([
297
+ { name: 'CMS_SECRET', status: 'error', message: 'Should be ≥ 32 chars' },
298
+ ])
299
+ expect(
300
+ byId(createDiagnosticReport(input({ mode: 'deploy', envShape: shape })).checks, 'env-shape')
301
+ ?.status,
302
+ ).toBe('fail')
303
+ expect(
304
+ byId(createDiagnosticReport(input({ mode: 'doctor', envShape: shape })).checks, 'env-shape')
305
+ ?.status,
306
+ ).toBe('warn')
307
+ })
308
+
309
+ it('leaves a missing variable to the environment check instead of reporting it twice', () => {
310
+ const { checks } = createDiagnosticReport(
311
+ input({
312
+ mode: 'deploy',
313
+ envShape: summary([{ name: 'CMS_SECRET', status: 'missing', message: 'Not set' }]),
314
+ }),
315
+ )
316
+ expect(byId(checks, 'env-shape')?.status).toBe('pass')
317
+ })
318
+
319
+ it('reports a placeholder CRON_SECRET under the cron check, with core wording', () => {
320
+ const { checks } = createDiagnosticReport(
321
+ input({
322
+ mode: 'deploy',
323
+ env: { CRON_SECRET: 'your-secret-here-please-change' },
324
+ envShape: summary([
325
+ { name: 'CRON_SECRET', status: 'error', message: 'Looks like a placeholder string.' },
326
+ ]),
327
+ }),
328
+ )
329
+ expect(byId(checks, 'cron-secret')).toMatchObject({ status: 'fail' })
330
+ expect(byId(checks, 'cron-secret')?.message).toContain('placeholder')
331
+ expect(byId(checks, 'env-shape')?.status).toBe('pass')
332
+ })
333
+ })
334
+
335
+ describe('email provider', () => {
336
+ const base: DiagnosticInput = {
337
+ schemaModels: new Set(),
338
+ env: {},
339
+ packageManager: 'pnpm',
340
+ schemaPath: 'prisma/schema.prisma',
341
+ configContent: 'export default { plugins: [emailPlugin()] }',
342
+ }
343
+
344
+ it('warns when emailPlugin() is registered with no provider', () => {
345
+ const check = byId(createDiagnosticReport(base).checks, 'email-provider')
346
+ expect(check?.status).toBe('warn')
347
+ expect(check?.message).toContain('password-reset')
348
+ })
349
+
350
+ it('passes with RESEND_API_KEY, and says nothing without the plugin', () => {
351
+ expect(
352
+ byId(
353
+ createDiagnosticReport({ ...base, env: { RESEND_API_KEY: 're_x' } }).checks,
354
+ 'email-provider',
355
+ )?.status,
356
+ ).toBe('pass')
357
+ expect(
358
+ byId(createDiagnosticReport({ ...base, configContent: '' }).checks, 'email-provider'),
359
+ ).toBeUndefined()
360
+ })
361
+ })
362
+
363
+ describe('productionOriginProblem', () => {
364
+ it.each([
365
+ ['http://localhost:3000', 'local address'],
366
+ ['https://127.0.0.1', 'local address'],
367
+ ['http://example.com', 'not https'],
368
+ ['example.com', 'not a valid URL'],
369
+ ])('rejects %s', (value, reason) => {
370
+ expect(productionOriginProblem(value)).toContain(reason)
371
+ })
372
+
373
+ it('accepts an https origin', () => {
374
+ expect(productionOriginProblem('https://example.com')).toBeNull()
375
+ })
376
+ })
@@ -0,0 +1,44 @@
1
+ /**
2
+ * #1263: the CLI peers @prenta/core >=8.10, and only newer cores ship
3
+ * `@prenta/core/diagnostics`. With an older core, doctor must still run and
4
+ * report the value check as skipped, not crash.
5
+ */
6
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
7
+ import { tmpdir } from 'node:os'
8
+ import path from 'node:path'
9
+ import { Command } from 'commander'
10
+ import { afterEach, expect, it, vi } from 'vitest'
11
+
12
+ vi.mock('@prenta/core/diagnostics', () => {
13
+ throw new Error('Package subpath "./diagnostics" is not defined by "exports"')
14
+ })
15
+
16
+ const { registerDoctorCommand } = await import('../commands/doctor.js')
17
+
18
+ const originalCwd = process.cwd()
19
+ let root: string | undefined
20
+
21
+ afterEach(async () => {
22
+ process.chdir(originalCwd)
23
+ vi.restoreAllMocks()
24
+ process.exitCode = undefined
25
+ if (root) await rm(root, { recursive: true, force: true })
26
+ })
27
+
28
+ it('skips the env value check when the installed core has no diagnostics entry', async () => {
29
+ root = await mkdtemp(path.join(tmpdir(), 'prenta-doctor-oldcore-'))
30
+ await writeFile(path.join(root, 'prenta.config.ts'), 'export default {}')
31
+ const out: string[] = []
32
+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
33
+ out.push(args.join(' '))
34
+ })
35
+ process.chdir(root)
36
+ const program = new Command()
37
+ program.exitOverride()
38
+ registerDoctorCommand(program)
39
+ await program.parseAsync(['node', 'prenta', 'doctor', '--json'])
40
+ vi.restoreAllMocks()
41
+
42
+ const report = JSON.parse(out.join('\n')) as { checks: Array<{ id: string; status: string }> }
43
+ expect(report.checks.find((c) => c.id === 'env-shape')).toMatchObject({ status: 'skip' })
44
+ })
@@ -0,0 +1,259 @@
1
+ /**
2
+ * #1261: a production deploy without a rate-limit store refuses sign-in,
3
+ * setup and saves. `prenta doctor` / `deploy:check` must say so before the
4
+ * deploy, and `prenta verify` must not pass a deploy whose /health says
5
+ * "unhealthy".
6
+ */
7
+ import { Command } from 'commander'
8
+ import { afterEach, describe, expect, it, vi } from 'vitest'
9
+
10
+ import { registerVerifyCommand } from '../commands/doctor.js'
11
+ import {
12
+ createDiagnosticReport,
13
+ detectRateLimitBackend,
14
+ VERCEL_MATRIX_OPTIONAL,
15
+ VERCEL_MATRIX_REQUIRED,
16
+ VERCEL_MATRIX_REQUIRED_ONE_OF,
17
+ } from '../deployment/diagnostics.js'
18
+ import { checkHealthResponse } from '../deployment/health-check.js'
19
+ import type { VercelEnvVar } from '../vercel/client.js'
20
+ import { buildEnvMatrix } from '../vercel/env-matrix.js'
21
+
22
+ const BASE_ENV = {
23
+ DATABASE_URL: 'postgresql://example',
24
+ DIRECT_DATABASE_URL: 'postgresql://example',
25
+ CMS_SECRET: 'x'.repeat(40),
26
+ CMS_ENCRYPTION_KEY: 'ab'.repeat(32),
27
+ NEXT_PUBLIC_SITE_URL: 'https://example.com',
28
+ }
29
+
30
+ function rateLimitCheck(env: Record<string, string | undefined>, mode?: 'doctor' | 'deploy') {
31
+ const report = createDiagnosticReport({
32
+ schemaModels: new Set(),
33
+ env,
34
+ packageManager: 'pnpm',
35
+ schemaPath: 'prisma/schema.prisma',
36
+ mode,
37
+ })
38
+ return { report, check: report.checks.find((c) => c.id === 'rate-limit-backend') }
39
+ }
40
+
41
+ describe('rate-limit store check (doctor / deploy:check)', () => {
42
+ it('fails deploy:check when neither name pair is set, and names both', () => {
43
+ const { report, check } = rateLimitCheck(BASE_ENV, 'deploy')
44
+ expect(check?.status).toBe('fail')
45
+ expect(report.status).toBe('fail')
46
+ expect(check?.message).toContain('UPSTASH_REDIS_REST_URL')
47
+ expect(check?.message).toContain('KV_REST_API_URL')
48
+ expect(check?.message).toContain('503')
49
+ expect(check?.fix).toContain('Vercel Marketplace')
50
+ })
51
+
52
+ it('fails doctor when the environment is production', () => {
53
+ expect(rateLimitCheck({ ...BASE_ENV, NODE_ENV: 'production' }, 'doctor').check?.status).toBe(
54
+ 'fail',
55
+ )
56
+ expect(rateLimitCheck({ ...BASE_ENV, VERCEL_ENV: 'production' }, 'doctor').check?.status).toBe(
57
+ 'fail',
58
+ )
59
+ })
60
+
61
+ it('only warns in local doctor runs, where an in-memory limiter is used', () => {
62
+ expect(rateLimitCheck(BASE_ENV, 'doctor').check?.status).toBe('warn')
63
+ })
64
+
65
+ it('passes with the Vercel Marketplace KV_REST_API_* names', () => {
66
+ const { check } = rateLimitCheck(
67
+ { ...BASE_ENV, KV_REST_API_URL: 'https://kv.example.com', KV_REST_API_TOKEN: 't' },
68
+ 'deploy',
69
+ )
70
+ expect(check?.status).toBe('pass')
71
+ expect(check?.message).toContain('KV_REST_API_URL')
72
+ })
73
+
74
+ it('passes with the Upstash console names', () => {
75
+ const { check } = rateLimitCheck(
76
+ {
77
+ ...BASE_ENV,
78
+ UPSTASH_REDIS_REST_URL: 'https://u.example.com',
79
+ UPSTASH_REDIS_REST_TOKEN: 't',
80
+ },
81
+ 'deploy',
82
+ )
83
+ expect(check?.status).toBe('pass')
84
+ })
85
+
86
+ it('names the missing half of a half-set pair', () => {
87
+ const { check } = rateLimitCheck({ ...BASE_ENV, KV_REST_API_URL: 'https://kv' }, 'deploy')
88
+ expect(check?.status).toBe('fail')
89
+ expect(check?.message).toContain('UPSTASH_REDIS_REST_TOKEN (or KV_REST_API_TOKEN)')
90
+ })
91
+
92
+ it('mixes names per variable, like the core does', () => {
93
+ expect(
94
+ detectRateLimitBackend({ UPSTASH_REDIS_REST_URL: 'https://u', KV_REST_API_TOKEN: 't' }).state,
95
+ ).toBe('ok')
96
+ })
97
+ })
98
+
99
+ describe('deploy:check --vercel matrix', () => {
100
+ const env = (key: string, target: VercelEnvVar['target']): VercelEnvVar => ({ key, target })
101
+ const required = VERCEL_MATRIX_REQUIRED.map((key) =>
102
+ env(key, ['production', 'preview', 'development']),
103
+ )
104
+ const matrix = (vars: VercelEnvVar[]) =>
105
+ buildEnvMatrix(
106
+ [...required, ...vars],
107
+ VERCEL_MATRIX_REQUIRED,
108
+ VERCEL_MATRIX_OPTIONAL,
109
+ VERCEL_MATRIX_REQUIRED_ONE_OF,
110
+ )
111
+
112
+ it('blocks a project with no rate-limit store on production or preview', () => {
113
+ expect(matrix([]).missingCritical).toEqual([
114
+ {
115
+ key: expect.stringContaining('KV_REST_API_URL'),
116
+ targets: ['production', 'preview'],
117
+ },
118
+ ])
119
+ })
120
+
121
+ it('accepts the Marketplace KV names', () => {
122
+ const all: VercelEnvVar['target'] = ['production', 'preview']
123
+ expect(
124
+ matrix([env('KV_REST_API_URL', all), env('KV_REST_API_TOKEN', all)]).missingCritical,
125
+ ).toEqual([])
126
+ })
127
+
128
+ it('does not accept a pair split across targets', () => {
129
+ const result = matrix([
130
+ env('KV_REST_API_URL', ['production', 'preview']),
131
+ env('KV_REST_API_TOKEN', ['production']),
132
+ ])
133
+ expect(result.missingCritical).toEqual([
134
+ { key: expect.stringContaining('rate-limit'), targets: ['preview'] },
135
+ ])
136
+ })
137
+
138
+ it('shows both name pairs in the matrix', () => {
139
+ const keys = matrix([]).rows.map((r) => r.key)
140
+ expect(keys).toEqual(
141
+ expect.arrayContaining([
142
+ 'UPSTASH_REDIS_REST_URL',
143
+ 'UPSTASH_REDIS_REST_TOKEN',
144
+ 'KV_REST_API_URL',
145
+ 'KV_REST_API_TOKEN',
146
+ ]),
147
+ )
148
+ })
149
+ })
150
+
151
+ function healthResponse(data: unknown, status: number): Response {
152
+ return new Response(JSON.stringify({ data }), {
153
+ status,
154
+ headers: { 'Content-Type': 'application/json' },
155
+ })
156
+ }
157
+
158
+ const URL_ = 'https://example.com/api/cms/health'
159
+
160
+ describe('checkHealthResponse', () => {
161
+ it('fails an unhealthy deploy that answers 200 (cores before #1261)', async () => {
162
+ const result = await checkHealthResponse(
163
+ healthResponse({ status: 'unhealthy', rateLimitBackendReady: false }, 200),
164
+ URL_,
165
+ )
166
+ expect(result.verdict).toBe('fail')
167
+ expect(result.lines.join('\n')).toContain('KV_REST_API_URL')
168
+ })
169
+
170
+ it('fails an unhealthy deploy that answers 503 and says why', async () => {
171
+ const result = await checkHealthResponse(
172
+ healthResponse(
173
+ {
174
+ status: 'unhealthy',
175
+ rateLimitBackendReady: true,
176
+ trustedIpSource: false,
177
+ trustProxyHint: 'Set PRENTA_TRUST_PROXY=1 behind a trusted reverse proxy.',
178
+ env: { checks: [{ name: 'CMS_SECRET', status: 'error', message: 'too short' }] },
179
+ },
180
+ 503,
181
+ ),
182
+ URL_,
183
+ )
184
+ expect(result.verdict).toBe('fail')
185
+ expect(result.lines).toEqual(
186
+ expect.arrayContaining([
187
+ expect.stringContaining('PRENTA_TRUST_PROXY'),
188
+ 'CMS_SECRET: too short',
189
+ ]),
190
+ )
191
+ })
192
+
193
+ it('passes a healthy deploy', async () => {
194
+ expect(
195
+ (await checkHealthResponse(healthResponse({ status: 'healthy' }, 200), URL_)).verdict,
196
+ ).toBe('pass')
197
+ })
198
+
199
+ it('warns on degraded', async () => {
200
+ const result = await checkHealthResponse(
201
+ healthResponse({ status: 'degraded', databaseConnected: false }, 200),
202
+ URL_,
203
+ )
204
+ expect(result.verdict).toBe('warn')
205
+ })
206
+
207
+ it('warns, not passes, when Deployment Protection hides the report', async () => {
208
+ expect((await checkHealthResponse(new Response('', { status: 401 }), URL_)).verdict).toBe(
209
+ 'warn',
210
+ )
211
+ })
212
+
213
+ it('fails a 5xx without a report', async () => {
214
+ expect((await checkHealthResponse(new Response('oops', { status: 500 }), URL_)).verdict).toBe(
215
+ 'fail',
216
+ )
217
+ })
218
+ })
219
+
220
+ describe('prenta verify --url', () => {
221
+ afterEach(() => {
222
+ vi.unstubAllGlobals()
223
+ vi.restoreAllMocks()
224
+ process.exitCode = undefined
225
+ })
226
+
227
+ async function verify(health: () => Response): Promise<{ exitCode: unknown; out: string }> {
228
+ vi.stubGlobal(
229
+ 'fetch',
230
+ vi.fn(async (url: string) =>
231
+ url.endsWith('/api/cms/health') ? health() : new Response('', { status: 302 }),
232
+ ),
233
+ )
234
+ const lines: string[] = []
235
+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
236
+ lines.push(args.join(' '))
237
+ })
238
+ const program = new Command()
239
+ program.exitOverride()
240
+ registerVerifyCommand(program)
241
+ await program.parseAsync(['node', 'prenta', 'verify', '--full', '--url', 'https://example.com'])
242
+ return { exitCode: process.exitCode, out: lines.join('\n') }
243
+ }
244
+
245
+ it('fails when /health reports unhealthy, even with HTTP 200', async () => {
246
+ const { exitCode, out } = await verify(() =>
247
+ healthResponse({ status: 'unhealthy', rateLimitBackendReady: false }, 200),
248
+ )
249
+ expect(exitCode).toBe(1)
250
+ expect(out).toContain('FAIL')
251
+ expect(out).toContain('unhealthy')
252
+ })
253
+
254
+ it('passes when /health reports healthy', async () => {
255
+ const { exitCode, out } = await verify(() => healthResponse({ status: 'healthy' }, 200))
256
+ expect(exitCode).toBeUndefined()
257
+ expect(out).toContain('PASS Health route')
258
+ })
259
+ })