@prenta/core 7.7.0 → 7.7.2

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 (106) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/route-helpers/auth.d.ts +131 -0
  3. package/dist/api/route-helpers/auth.d.ts.map +1 -0
  4. package/dist/api/route-helpers/auth.js +505 -0
  5. package/dist/api/route-helpers/auth.js.map +1 -0
  6. package/dist/api/route-helpers/authoring.d.ts +32 -0
  7. package/dist/api/route-helpers/authoring.d.ts.map +1 -0
  8. package/dist/api/route-helpers/authoring.js +99 -0
  9. package/dist/api/route-helpers/authoring.js.map +1 -0
  10. package/dist/api/route-helpers/forms.d.ts +46 -0
  11. package/dist/api/route-helpers/forms.d.ts.map +1 -0
  12. package/dist/api/route-helpers/forms.js +435 -0
  13. package/dist/api/route-helpers/forms.js.map +1 -0
  14. package/dist/api/route-helpers/http.d.ts +87 -0
  15. package/dist/api/route-helpers/http.d.ts.map +1 -0
  16. package/dist/api/route-helpers/http.js +286 -0
  17. package/dist/api/route-helpers/http.js.map +1 -0
  18. package/dist/api/route-helpers/media.d.ts +37 -0
  19. package/dist/api/route-helpers/media.d.ts.map +1 -0
  20. package/dist/api/route-helpers/media.js +189 -0
  21. package/dist/api/route-helpers/media.js.map +1 -0
  22. package/dist/api/route-helpers/page-shape.d.ts +31 -0
  23. package/dist/api/route-helpers/page-shape.d.ts.map +1 -0
  24. package/dist/api/route-helpers/page-shape.js +98 -0
  25. package/dist/api/route-helpers/page-shape.js.map +1 -0
  26. package/dist/api/route-helpers.d.ts +8 -358
  27. package/dist/api/route-helpers.d.ts.map +1 -1
  28. package/dist/api/route-helpers.js +7 -1592
  29. package/dist/api/route-helpers.js.map +1 -1
  30. package/dist/api/routes/seo/handlers/analysis.d.ts +4 -0
  31. package/dist/api/routes/seo/handlers/analysis.d.ts.map +1 -0
  32. package/dist/api/routes/seo/handlers/analysis.js +131 -0
  33. package/dist/api/routes/seo/handlers/analysis.js.map +1 -0
  34. package/dist/api/routes/seo/handlers/audits.d.ts +5 -0
  35. package/dist/api/routes/seo/handlers/audits.d.ts.map +1 -0
  36. package/dist/api/routes/seo/handlers/audits.js +121 -0
  37. package/dist/api/routes/seo/handlers/audits.js.map +1 -0
  38. package/dist/api/routes/seo/handlers/content.d.ts +4 -0
  39. package/dist/api/routes/seo/handlers/content.d.ts.map +1 -0
  40. package/dist/api/routes/seo/handlers/content.js +330 -0
  41. package/dist/api/routes/seo/handlers/content.js.map +1 -0
  42. package/dist/api/routes/seo/handlers/issue-helpers.d.ts +37 -0
  43. package/dist/api/routes/seo/handlers/issue-helpers.d.ts.map +1 -0
  44. package/dist/api/routes/seo/handlers/issue-helpers.js +72 -0
  45. package/dist/api/routes/seo/handlers/issue-helpers.js.map +1 -0
  46. package/dist/api/routes/seo/handlers/issues-briefs.d.ts +7 -0
  47. package/dist/api/routes/seo/handlers/issues-briefs.d.ts.map +1 -0
  48. package/dist/api/routes/seo/handlers/issues-briefs.js +341 -0
  49. package/dist/api/routes/seo/handlers/issues-briefs.js.map +1 -0
  50. package/dist/api/routes/seo/handlers/issues-fixes.d.ts +4 -0
  51. package/dist/api/routes/seo/handlers/issues-fixes.d.ts.map +1 -0
  52. package/dist/api/routes/seo/handlers/issues-fixes.js +233 -0
  53. package/dist/api/routes/seo/handlers/issues-fixes.js.map +1 -0
  54. package/dist/api/routes/seo/handlers/issues-list.d.ts +7 -0
  55. package/dist/api/routes/seo/handlers/issues-list.d.ts.map +1 -0
  56. package/dist/api/routes/seo/handlers/issues-list.js +191 -0
  57. package/dist/api/routes/seo/handlers/issues-list.js.map +1 -0
  58. package/dist/api/routes/seo/handlers/links.d.ts +6 -0
  59. package/dist/api/routes/seo/handlers/links.d.ts.map +1 -0
  60. package/dist/api/routes/seo/handlers/links.js +383 -0
  61. package/dist/api/routes/seo/handlers/links.js.map +1 -0
  62. package/dist/api/routes/seo/handlers/overview.d.ts +4 -0
  63. package/dist/api/routes/seo/handlers/overview.d.ts.map +1 -0
  64. package/dist/api/routes/seo/handlers/overview.js +348 -0
  65. package/dist/api/routes/seo/handlers/overview.js.map +1 -0
  66. package/dist/api/routes/seo/handlers/pages.d.ts +2 -0
  67. package/dist/api/routes/seo/handlers/pages.d.ts.map +1 -0
  68. package/dist/api/routes/seo/handlers/pages.js +38 -0
  69. package/dist/api/routes/seo/handlers/pages.js.map +1 -0
  70. package/dist/api/routes/seo/handlers/proposals.d.ts +4 -0
  71. package/dist/api/routes/seo/handlers/proposals.d.ts.map +1 -0
  72. package/dist/api/routes/seo/handlers/proposals.js +93 -0
  73. package/dist/api/routes/seo/handlers/proposals.js.map +1 -0
  74. package/dist/api/routes/seo/handlers/public-files.d.ts +6 -0
  75. package/dist/api/routes/seo/handlers/public-files.d.ts.map +1 -0
  76. package/dist/api/routes/seo/handlers/public-files.js +328 -0
  77. package/dist/api/routes/seo/handlers/public-files.js.map +1 -0
  78. package/dist/api/routes/seo/handlers/shared.d.ts +24 -0
  79. package/dist/api/routes/seo/handlers/shared.d.ts.map +1 -0
  80. package/dist/api/routes/seo/handlers/shared.js +67 -0
  81. package/dist/api/routes/seo/handlers/shared.js.map +1 -0
  82. package/dist/api/routes/seo.d.ts +5 -5
  83. package/dist/api/routes/seo.d.ts.map +1 -1
  84. package/dist/api/routes/seo.js +56 -2610
  85. package/dist/api/routes/seo.js.map +1 -1
  86. package/dist/api/routes/users/handlers/api-keys.d.ts +4 -0
  87. package/dist/api/routes/users/handlers/api-keys.d.ts.map +1 -0
  88. package/dist/api/routes/users/handlers/api-keys.js +164 -0
  89. package/dist/api/routes/users/handlers/api-keys.js.map +1 -0
  90. package/dist/api/routes/users/handlers/invites.d.ts +7 -0
  91. package/dist/api/routes/users/handlers/invites.d.ts.map +1 -0
  92. package/dist/api/routes/users/handlers/invites.js +201 -0
  93. package/dist/api/routes/users/handlers/invites.js.map +1 -0
  94. package/dist/api/routes/users/handlers/users-admin.d.ts +7 -0
  95. package/dist/api/routes/users/handlers/users-admin.d.ts.map +1 -0
  96. package/dist/api/routes/users/handlers/users-admin.js +310 -0
  97. package/dist/api/routes/users/handlers/users-admin.js.map +1 -0
  98. package/dist/api/routes/users/handlers/users-detail.d.ts +16 -0
  99. package/dist/api/routes/users/handlers/users-detail.d.ts.map +1 -0
  100. package/dist/api/routes/users/handlers/users-detail.js +525 -0
  101. package/dist/api/routes/users/handlers/users-detail.js.map +1 -0
  102. package/dist/api/routes/users.d.ts +4 -0
  103. package/dist/api/routes/users.d.ts.map +1 -1
  104. package/dist/api/routes/users.js +38 -1177
  105. package/dist/api/routes/users.js.map +1 -1
  106. package/package.json +1 -1
@@ -1,1598 +1,13 @@
1
- import { assertCollectionAccess, buildRelationLookup } from '../actions.js';
2
- import { populateRelations, parsePopulateParam } from '../fields/relations.js';
3
- import { verifySession } from '../auth/session.js';
4
- import { resolveEmailSender } from '../email/sender.js';
5
- import { workspaceDomainFromUrl } from '../auth/team.js';
6
- import { getDB } from '../db.js';
7
- import { formatBytes } from '../media/optimize.js';
8
- import { calculateMediaSeoScore } from '../media/seo.js';
9
- import { publicReadCacheControl } from '../cache/http.js';
10
- import { verifyCaptcha, getCaptchaConfig, isCaptchaProviderError } from '../security/captcha.js';
11
- import { logEvent } from '../security/audit.js';
12
- import { FormNotFoundError, FormValidationError, FormConflictError, FormHasSubmissionsError, } from '../forms/service.js';
13
- import { processSubmission, SubmissionValidationError, } from '../forms/submission.js';
14
- import { validateSubmissionFiles, FORM_UPLOAD_ALLOWED_MIME_TYPES, DEFAULT_MAX_FILE_BYTES, } from '../forms/files.js';
15
- import { resolveSubmissionFields } from '../forms/submission.js';
16
- import { FormWebhookError } from '../forms/webhooks.js';
17
- import { createRateLimiter } from '../security/rate-limit.js';
18
- import { bindRequestLogUser, createLogger } from '../diagnostics/logger.js';
19
- import { captureServerException } from '../diagnostics/sentry.js';
20
- import { getClientIp, isResolvedIp } from '../security/client-ip.js';
21
- import { safeFetch } from '../security/safe-fetch.js';
22
- import { validateWebhookUrl } from '../security/webhook.js';
23
- import { enforceSessionLimits } from '../security/session-limits.js';
24
- import { verifyReauth } from '../security/reauth.js';
25
- import { getPrentaConfig } from '../config/runtime.js';
26
- import { hashApiKey, looksLikeApiKey, validateApiKeyScope, validateApiKeyGlobalScope, validateApiKeyMediaScope, validateApiKeyIp, } from '../security/api-key-enhanced.js';
27
- import { guardedDb, ModelNotAvailableError } from './guarded-db.js';
28
- import { SECURITY_HEADERS } from './security-headers.js';
29
- // Opaque dynamic import so Turbopack/webpack won't statically analyze the specifier.
30
- // Returns { put, del, ... } from @vercel/blob when available.
31
- export async function importBlobStorage() {
32
- const mod = '@vercel/' + 'blob';
33
- return import(/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ mod);
34
- }
35
1
  export { importAIPlugin } from '../ai/plugin-import.js';
36
- /**
37
- * Build the system/user prompt for an inline co-author action. Kept
38
- * deterministic and small so the governed runtime can route it to any
39
- * configured provider/model.
40
- */
41
- export function buildCoauthorPrompt(action, body) {
42
- const text = body.text ?? '';
43
- switch (action) {
44
- case 'expand': {
45
- const hint = body.instructions ? ` Follow this guidance: ${body.instructions}.` : '';
46
- return {
47
- system: 'You are an expert writer. Expand the user\u2019s text with more detail and depth ' +
48
- 'while preserving its meaning and voice.' +
49
- hint +
50
- ' Return only the expanded text, with no preamble.',
51
- user: text,
52
- maxTokens: 2048,
53
- };
54
- }
55
- case 'compress': {
56
- const hint = typeof body.targetLength === 'number' && body.targetLength > 0
57
- ? ` Aim for about ${body.targetLength} words.`
58
- : '';
59
- return {
60
- system: 'You are an expert editor. Tighten the user\u2019s text, removing redundancy while ' +
61
- 'preserving the key information and voice.' +
62
- hint +
63
- ' Return only the edited text, with no preamble.',
64
- user: text,
65
- maxTokens: 1024,
66
- };
67
- }
68
- case 'proofread':
69
- return {
70
- system: 'You are a meticulous proofreader. Correct grammar, spelling, and punctuation in the ' +
71
- 'user\u2019s text. Preserve its meaning and voice. Return only the corrected text, ' +
72
- 'with no preamble.',
73
- user: text,
74
- maxTokens: 2048,
75
- };
76
- case 'rewrite':
77
- default: {
78
- const style = body.style ? ` Write in a ${body.style} style.` : '';
79
- const tone = body.tone ? ` Use a ${body.tone} tone.` : '';
80
- return {
81
- system: 'You are an expert editor. Rewrite the user\u2019s text to improve clarity and flow ' +
82
- 'while preserving its meaning.' +
83
- style +
84
- tone +
85
- ' Return only the rewritten text, with no preamble.',
86
- user: text,
87
- maxTokens: 2048,
88
- };
89
- }
90
- }
91
- }
92
- /**
93
- * Common helper for the read endpoints. Reads the `?populate=` query param,
94
- * fetches the target collection's field schema, and expands every relation
95
- * reference into a {@link RelationSummary}. When the caller didn't ask for
96
- * population (or the doc has no `data` field) we short-circuit and return
97
- * the doc untouched.
98
- *
99
- * Lives here (not in `actions.ts`) because the rest of the actions API
100
- * stays purely DB-shaped — population is an HTTP concern.
101
- */
102
- export async function maybePopulate(request, collection, doc, dbInstance, viewer) {
103
- if (!doc)
104
- return doc;
105
- const url = new URL(request.url);
106
- const opts = parsePopulateParam(url.searchParams.get('populate'));
107
- if (!opts)
108
- return doc;
109
- const cfg = getPrentaConfig();
110
- const fields = cfg?.collections?.[collection]?.fields;
111
- if (!fields)
112
- return doc;
113
- const data = doc.data && typeof doc.data === 'object' ? doc.data : null;
114
- if (!data)
115
- return doc;
116
- try {
117
- const populated = await populateRelations(fields, data, buildRelationLookup(dbInstance, { viewer }), opts);
118
- return { ...doc, data: populated };
119
- }
120
- catch (err) {
121
- // Never let a populate failure mask the underlying document — log and
122
- // return the unpopulated doc.
123
- logger.error('populate failed', {
124
- collection,
125
- error: err instanceof Error ? err.message : String(err),
126
- });
127
- return doc;
128
- }
129
- }
130
- export { SECURITY_HEADERS };
131
- const logger = createLogger('api');
132
- export function json(data, status = 200) {
133
- return new Response(JSON.stringify(data), {
134
- status,
135
- headers: { ...SECURITY_HEADERS },
136
- });
137
- }
138
- /**
139
- * Variant of `json()` that emits the Phase-5.5 public-read
140
- * `Cache-Control` header when the active CMS config opts in.
141
- *
142
- * - Session-cookie requests always get `private, no-store`.
143
- * - API-key / unauthenticated requests get
144
- * `public, s-maxage=N, stale-while-revalidate=M` when
145
- * `cache.publicReads.enabled` is true.
146
- * - Otherwise no `Cache-Control` header is set (i.e. the response is
147
- * uncacheable downstream, matching the pre-5.5 behaviour).
148
- *
149
- * Use this for the public read endpoints (`/collections/:slug`,
150
- * `/collections/:slug/:id`, `/globals/:slug`, `/resolve`). Mutating
151
- * endpoints stay on the plain `json()` so the CDN never caches a write
152
- * response by accident.
153
- */
154
- export function jsonWithCache(data, request, status = 200) {
155
- const cacheControl = publicReadCacheControl(request, getPrentaConfig()?.cache);
156
- const headers = { ...SECURITY_HEADERS };
157
- if (cacheControl)
158
- headers['Cache-Control'] = cacheControl;
159
- return new Response(JSON.stringify(data), { status, headers });
160
- }
161
- export function errorResponse(message, status) {
162
- return json({ error: message }, status);
163
- }
164
- export function internalError(err, context) {
165
- if (err instanceof ModelNotAvailableError) {
166
- return modelNotAvailable(err.model);
167
- }
168
- const msg = err instanceof Error ? err.message : String(err);
169
- logger.error(msg, context ? { context } : undefined);
170
- // Fire-and-forget: capture lazily imports the optional @sentry/node and never
171
- // throws, so we don't await it before returning the error response.
172
- void captureServerException(err, { scope: 'api', extra: context ? { context } : undefined });
173
- if (process.env.PRENTA_DEBUG_ERRORS === '1') {
174
- return errorResponse(msg, 500);
175
- }
176
- return errorResponse('Internal server error', 500);
177
- }
178
- /**
179
- * Map a thrown action-layer error to the right HTTP status. The data layer
180
- * throws plain `Error`s with stable, human-readable prefixes for client-fixable
181
- * problems (publish validation, access/permission, not-found); those are 4xx
182
- * and the message is safe to return verbatim. Anything else falls through to
183
- * {@link internalError} (500, generic message, logged).
184
- */
185
- export function actionError(err, context) {
186
- if (err instanceof ModelNotAvailableError)
187
- return modelNotAvailable(err.model);
188
- const conflict = uniqueConstraintConflict(err);
189
- if (conflict)
190
- return errorResponse(conflict, 409);
191
- const msg = err instanceof Error ? err.message : String(err);
192
- if (/^Cannot publish —/.test(msg))
193
- return errorResponse(msg, 422);
194
- if (/^Invalid media field/i.test(msg))
195
- return errorResponse(msg, 400);
196
- if (/insufficient permissions/i.test(msg) ||
197
- /^Access denied/i.test(msg) ||
198
- /submit for review before publishing/i.test(msg)) {
199
- return errorResponse(msg, 403);
200
- }
201
- if (/not found/i.test(msg))
202
- return errorResponse(msg, 404);
203
- return internalError(err, context);
204
- }
205
- /**
206
- * Detect a Prisma unique-constraint violation (P2002) via its stable `code`,
207
- * without importing the heavy Prisma error class. Returns a client-safe 409
208
- * message, or null when `err` is not a unique-constraint error. The usual
209
- * trigger is a duplicate (collection, slug) on create/rename/publish — which
210
- * previously fell through to a 500 (#560); a genuine live-slug clash is a
211
- * client-fixable conflict, so it belongs at 409.
212
- */
213
- function uniqueConstraintConflict(err) {
214
- if (!err || typeof err !== 'object' || err.code !== 'P2002') {
215
- return null;
216
- }
217
- const target = err.meta?.target;
218
- const fields = Array.isArray(target)
219
- ? target.map(String)
220
- : typeof target === 'string'
221
- ? [target]
222
- : [];
223
- if (fields.some((f) => f.toLowerCase().includes('slug'))) {
224
- return 'A document with this slug already exists in this collection.';
225
- }
226
- return 'That value is already in use.';
227
- }
228
- export function clampPageSize(raw, max = 100, fallback = 20) {
229
- const n = Number(raw) || fallback;
230
- return Math.min(Math.max(1, n), max);
231
- }
232
- /**
233
- * Clamp a 1-based list `page` query param. Negative / zero / NaN values must
234
- * never reach Prisma `skip` (negative OFFSET → validation error → opaque 500).
235
- * Mirrors forms/users/redirects (`Math.max(1, …)`).
236
- */
237
- export function clampPage(raw, fallback = 1) {
238
- const n = Number(raw);
239
- if (!Number.isFinite(n) || n < 1)
240
- return fallback;
241
- return Math.min(Math.floor(n), 100_000);
242
- }
243
- /** Parse a JSON object body; invalid JSON or a non-object yields a 400. */
244
- export async function readJsonBody(request) {
245
- try {
246
- const parsed = await request.json();
247
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
248
- return { ok: false, error: errorResponse('Invalid JSON body', 400) };
249
- }
250
- return { ok: true, data: parsed };
251
- }
252
- catch {
253
- return { ok: false, error: errorResponse('Invalid JSON body', 400) };
254
- }
255
- }
256
- export function mediaUrl(storageKey) {
257
- const value = String(storageKey ?? '');
258
- if (!value)
259
- return '';
260
- return value.startsWith('http://') || value.startsWith('https://') || value.startsWith('/')
261
- ? value
262
- : '';
263
- }
264
- export function normalizeMediaItem(media) {
265
- const width = typeof media.width === 'number' ? media.width : null;
266
- const height = typeof media.height === 'number' ? media.height : null;
267
- const sizeBytes = Number(media.fileSize ?? media.sizeBytes ?? 0);
268
- const isDecorative = media.isDecorative === true;
269
- const usedOnTitles = Array.isArray(media.mediaUsages)
270
- ? media.mediaUsages
271
- .map((usage) => usage?.document?.title)
272
- .filter((title) => typeof title === 'string' && title.trim().length > 0)
273
- : [];
274
- // Derived on every read (never persisted) so the score can't drift from the
275
- // metadata — see `media/seo.ts` for the weight contract.
276
- const seo = calculateMediaSeoScore({
277
- fileName: media.filename ?? media.name ?? null,
278
- mimeType: media.mimeType ?? media.type ?? null,
279
- altText: media.altText ?? media.altTag ?? null,
280
- title: media.title ?? null,
281
- caption: media.caption ?? null,
282
- description: media.description ?? null,
283
- focusKeyword: media.focusKeyword ?? null,
284
- sizeBytes,
285
- width,
286
- height,
287
- isDecorative,
288
- usedOnTitles,
289
- });
290
- return {
291
- ...media,
292
- name: media.filename ?? media.name ?? '',
293
- type: media.mimeType ?? media.type ?? '',
294
- size: formatBytes(sizeBytes),
295
- sizeBytes,
296
- date: media.createdAt ?? media.updatedAt ?? null,
297
- url: mediaUrl(media.storageKey ?? media.url),
298
- dimensions: width && height ? `${width}x${height}` : undefined,
299
- format: typeof media.mimeType === 'string' ? media.mimeType.split('/')[1] : undefined,
300
- altTag: media.altText ?? media.altTag ?? '',
301
- isDecorative,
302
- ...(media.aiAltText != null ? { aiAltSuggestion: media.aiAltText } : {}),
303
- title: media.title ?? '',
304
- seoScore: seo.score,
305
- seoGrade: seo.grade,
306
- seoIssues: seo.issues,
307
- };
308
- }
309
- /**
310
- * Build the admin editor route for a document that references a media asset.
311
- * Pages own the `/pages/*` namespace; post-type collections use
312
- * `/posts/:type/:id/edit`; everything else falls back to the generic
313
- * collection editor. Kept in sync with the route table in `AdminRoot.tsx`.
314
- */
315
- function mediaUsageEditPath(collection, id) {
316
- if (collection === 'pages')
317
- return `/pages/${id}/edit`;
318
- const def = getPrentaConfig()?.collections?.[collection];
319
- if (def?.type === 'post')
320
- return `/posts/${collection}/${id}/edit`;
321
- return `/collections/${collection}/${id}`;
322
- }
323
- /**
324
- * Map the `MediaUsage` join rows (with their related document) into the
325
- * `{ page, path }[]` shape the admin drawer renders. Soft-deleted documents
326
- * are excluded so trashed pages don't keep an asset looking "in use".
327
- */
328
- export function buildMediaUsedOn(mediaUsages) {
329
- if (!Array.isArray(mediaUsages))
330
- return [];
331
- const seen = new Set();
332
- const out = [];
333
- for (const usage of mediaUsages) {
334
- const doc = usage?.document;
335
- if (!doc || doc.deletedAt || seen.has(doc.id))
336
- continue;
337
- seen.add(doc.id);
338
- out.push({
339
- page: doc.title || '(untitled)',
340
- path: mediaUsageEditPath(doc.collection, doc.id),
341
- });
342
- }
343
- return out;
344
- }
345
- const MEDIA_TITLE_STOPWORDS = new Set([
346
- 'a',
347
- 'an',
348
- 'the',
349
- 'of',
350
- 'and',
351
- 'or',
352
- 'to',
353
- 'in',
354
- 'on',
355
- 'for',
356
- 'with',
357
- 'at',
358
- 'by',
359
- 'from',
360
- 'is',
361
- 'are',
362
- 'as',
363
- ]);
364
- /**
365
- * Derive a concise, Title-Cased title from AI-generated alt text. The alt
366
- * text is already a model output describing the image, so the title stays
367
- * grounded in real content rather than the filename.
368
- */
369
- export function deriveMediaTitleFromAlt(alt) {
370
- if (!alt)
371
- return '';
372
- const firstClause = (alt.split(/[.;:\n]/)[0] ?? '').trim();
373
- const titled = firstClause
374
- .split(/\s+/)
375
- .slice(0, 9)
376
- .map((word, i) => {
377
- const lower = word.toLowerCase();
378
- if (i > 0 && MEDIA_TITLE_STOPWORDS.has(lower))
379
- return lower;
380
- return word.charAt(0).toUpperCase() + word.slice(1);
381
- })
382
- .join(' ');
383
- return titled.slice(0, 80).replace(/[\s,]+$/, '');
384
- }
385
- export function asRecord(value) {
386
- return value && typeof value === 'object' && !Array.isArray(value)
387
- ? value
388
- : {};
389
- }
390
- export function normalizeSubmission(submission) {
391
- const data = asRecord(submission.data);
392
- const attribution = asRecord(submission.attribution);
393
- return {
394
- ...submission,
395
- name: String(data.name ?? submission.name ?? ''),
396
- email: String(data.email ?? submission.email ?? ''),
397
- phone: data.phone ?? submission.phone,
398
- message: String(data.message ?? submission.message ?? ''),
399
- status: submission.status ?? 'new',
400
- attribution: {
401
- source: String(attribution.source ?? '(direct)'),
402
- medium: String(attribution.medium ?? '(none)'),
403
- campaign: String(attribution.campaign ?? ''),
404
- term: String(attribution.term ?? ''),
405
- content: String(attribution.content ?? ''),
406
- landingPage: String(attribution.landingPage ?? ''),
407
- referrer: String(attribution.referrer ?? ''),
408
- deviceType: attribution.deviceType ?? 'Desktop',
409
- clickIds: asRecord(attribution.clickIds),
410
- capturedAt: attribution.capturedAt ?? submission.submittedAt ?? submission.createdAt ?? null,
411
- },
412
- };
413
- }
414
- /**
415
- * Map a forms-service domain error to an HTTP response. Returns `null` for
416
- * unrecognised errors so the caller can fall through to `internalError`.
417
- */
418
- export function mapFormError(err) {
419
- if (err instanceof FormNotFoundError)
420
- return errorResponse(err.message, 404);
421
- if (err instanceof FormValidationError) {
422
- return json({ error: err.message, code: 'INVALID_SCHEMA', details: err.errors }, 400);
423
- }
424
- if (err instanceof FormConflictError)
425
- return errorResponse(err.message, 409);
426
- if (err instanceof FormHasSubmissionsError) {
427
- return json({ error: err.message, code: 'FORM_HAS_SUBMISSIONS', submissionCount: err.submissionCount }, 409);
428
- }
429
- if (err instanceof FormWebhookError)
430
- return errorResponse(err.message, err.status);
431
- return null;
432
- }
433
- export function parseFormsQuery(url) {
434
- const sp = url.searchParams;
435
- const status = sp.get('status');
436
- const notify = sp.get('notifyEnabled');
437
- return {
438
- search: sp.get('search') ?? undefined,
439
- status: status === 'active' || status === 'draft' || status === 'archived' ? status : undefined,
440
- notifyEnabled: notify == null ? undefined : notify === 'true',
441
- sortBy: sp.get('sortBy') ?? undefined,
442
- sortDirection: sp.get('sortDirection') === 'asc'
443
- ? 'asc'
444
- : sp.get('sortDirection') === 'desc'
445
- ? 'desc'
446
- : undefined,
447
- page: sp.get('page') ? clampPage(sp.get('page')) : undefined,
448
- pageSize: sp.get('pageSize') ? clampPageSize(sp.get('pageSize')) : undefined,
449
- };
450
- }
451
- export function parseEntriesQuery(url) {
452
- const sp = url.searchParams;
453
- const spam = sp.get('spamStatus');
454
- const boolParam = (key) => {
455
- const v = sp.get(key);
456
- return v == null ? undefined : v === 'true';
457
- };
458
- return {
459
- search: sp.get('search') ?? undefined,
460
- formId: sp.get('formId') ?? sp.get('form') ?? undefined,
461
- unread: boolParam('unread'),
462
- starred: boolParam('starred'),
463
- archived: boolParam('archived'),
464
- spamStatus: spam === 'clean' || spam === 'suspected' || spam === 'spam'
465
- ? spam
466
- : undefined,
467
- dateFrom: sp.get('dateFrom') ?? undefined,
468
- dateTo: sp.get('dateTo') ?? undefined,
469
- thisWeek: boolParam('thisWeek'),
470
- sortBy: sp.get('sortBy') ?? undefined,
471
- sortDirection: sp.get('sortDirection') === 'asc' ? 'asc' : undefined,
472
- page: sp.get('page') ? clampPage(sp.get('page')) : undefined,
473
- pageSize: sp.get('pageSize') ? clampPageSize(sp.get('pageSize')) : undefined,
474
- };
475
- }
476
- // ─── Public form submission helpers ─────────────────────────────────────────
477
- /**
478
- * Build CORS headers for the public form endpoints. When the form has no
479
- * embed allowlist we reflect the requesting origin (open embedding). When an
480
- * allowlist is set we only echo the origin if it matches, so a disallowed site
481
- * cannot read the response. Browser-level CORS is complemented by a hard
482
- * server-side origin check in the submit handler.
483
- */
484
- export function formCorsHeaders(request, allowedDomains) {
485
- const origin = request.headers.get('origin');
486
- const headers = {
487
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
488
- 'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
489
- 'Access-Control-Max-Age': '600',
490
- Vary: 'Origin',
491
- };
492
- if (!allowedDomains || allowedDomains.length === 0) {
493
- headers['Access-Control-Allow-Origin'] = origin || '*';
494
- }
495
- else if (origin && isOriginAllowed(origin, allowedDomains)) {
496
- headers['Access-Control-Allow-Origin'] = origin;
497
- }
498
- return headers;
499
- }
500
- function normalizeAllowedHost(domain) {
501
- return domain
502
- .trim()
503
- .toLowerCase()
504
- .replace(/^https?:\/\//, '')
505
- .replace(/\/.*$/, '')
506
- .replace(/^\*\./, '');
507
- }
508
- function isOriginAllowed(origin, allowedDomains) {
509
- let host;
510
- try {
511
- host = new URL(origin).hostname.toLowerCase();
512
- }
513
- catch {
514
- return false;
515
- }
516
- return allowedDomains
517
- .map(normalizeAllowedHost)
518
- .some((a) => a !== '' && (host === a || host.endsWith(`.${a}`)));
519
- }
520
- export function jsonWithHeaders(data, status, extra) {
521
- return new Response(JSON.stringify(data), {
522
- status,
523
- headers: { ...SECURITY_HEADERS, ...extra },
524
- });
525
- }
526
- /**
527
- * Parse a public submission request into field values, files, and metadata.
528
- * Supports both `application/json` (no files) and `multipart/form-data`
529
- * (files + fields). Unknown/oversized bodies are rejected by the caller's
530
- * Content-Length gate before this runs.
531
- */
532
- export async function parseSubmissionRequest(request) {
533
- const contentType = request.headers.get('content-type') ?? '';
534
- if (contentType.includes('multipart/form-data')) {
535
- const form = await request.formData();
536
- return parseFlatSubmissionEntries(form.entries());
537
- }
538
- if (contentType.includes('application/x-www-form-urlencoded')) {
539
- const text = await request.text();
540
- return parseFlatSubmissionEntries(new URLSearchParams(text).entries());
541
- }
542
- // JSON body.
543
- const body = (await request.json().catch(() => null));
544
- if (!body)
545
- return null;
546
- const values = body.fields && typeof body.fields === 'object' && !Array.isArray(body.fields)
547
- ? body.fields
548
- : null;
549
- if (!values)
550
- return null;
551
- return {
552
- values,
553
- files: [],
554
- meta: {
555
- attribution: safeJsonObject(body.attribution),
556
- elapsedMs: typeof body.elapsedMs === 'number' && Number.isFinite(body.elapsedMs)
557
- ? body.elapsedMs
558
- : null,
559
- pageUrl: typeof body.pageUrl === 'string' ? body.pageUrl : null,
560
- captchaToken: typeof body.captchaToken === 'string' ? body.captchaToken : '',
561
- },
562
- };
563
- }
564
- async function readSubmissionFile(value) {
565
- if (typeof value !== 'object' || value === null || !('arrayBuffer' in value))
566
- return null;
567
- const file = value;
568
- if (file.size === 0 && !file.name)
569
- return null;
570
- const buffer = Buffer.from(await file.arrayBuffer());
571
- return {
572
- fieldKey: '',
573
- fileName: file.name || 'file',
574
- mimeType: file.type || 'application/octet-stream',
575
- size: buffer.byteLength,
576
- buffer,
577
- };
578
- }
579
- function parseFlatSubmissionEntries(entries) {
580
- return (async () => {
581
- const values = {};
582
- const files = [];
583
- let attribution = null;
584
- let elapsedMs = null;
585
- let pageUrl = null;
586
- let captchaToken = '';
587
- let renderStartedAt = null;
588
- for (const [key, rawValue] of entries) {
589
- if (typeof rawValue === 'object' && rawValue !== null && 'arrayBuffer' in rawValue) {
590
- const file = await readSubmissionFile(rawValue);
591
- if (file) {
592
- file.fieldKey = key;
593
- files.push(file);
594
- }
595
- continue;
596
- }
597
- const str = String(rawValue);
598
- if (key === '__attribution') {
599
- attribution = safeJsonObject(str);
600
- }
601
- else if (key === '__elapsedMs') {
602
- const n = Number(str);
603
- elapsedMs = Number.isFinite(n) ? n : null;
604
- }
605
- else if (key === '__renderStartedAt') {
606
- const n = Number(str);
607
- renderStartedAt = Number.isFinite(n) ? n : null;
608
- }
609
- else if (key === '__pageUrl') {
610
- pageUrl = str || null;
611
- }
612
- else if (key === '__captchaToken' || key === 'captchaToken') {
613
- captchaToken = str;
614
- }
615
- else if (Object.prototype.hasOwnProperty.call(values, key)) {
616
- const existing = values[key];
617
- values[key] = Array.isArray(existing) ? [...existing, str] : [existing, str];
618
- }
619
- else {
620
- values[key] = str;
621
- }
622
- }
623
- if (elapsedMs === null && renderStartedAt !== null) {
624
- elapsedMs = Math.max(0, Date.now() - renderStartedAt);
625
- }
626
- return { values, files, meta: { attribution, elapsedMs, pageUrl, captchaToken } };
627
- })();
628
- }
629
- function safeJsonObject(value) {
630
- if (value && typeof value === 'object' && !Array.isArray(value)) {
631
- return value;
632
- }
633
- if (typeof value === 'string' && value.trim()) {
634
- try {
635
- const parsed = JSON.parse(value);
636
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
637
- return parsed;
638
- }
639
- }
640
- catch {
641
- /* ignore malformed attribution blob */
642
- }
643
- }
644
- return null;
645
- }
646
- /**
647
- * Shared public-submission handler used by both the slug-based public route and
648
- * the legacy by-id route. Enforces per-IP+form rate limiting, embed-origin
649
- * allowlisting, optional CAPTCHA, file validation, then runs the core
650
- * submission pipeline. Always responds with CORS headers so embedded forms can
651
- * read the result.
652
- */
653
- export async function submitToForm(request, form) {
654
- const allowedDomains = form.embedSettings?.allowedDomains;
655
- const cors = formCorsHeaders(request, allowedDomains);
656
- const ip = getClientIp(request);
657
- const rlKey = isResolvedIp(ip) ? `formsubmit:${ip}:${form.id}` : `formsubmit:_unknown:${form.id}`;
658
- if (!(await checkRateLimitAsync(formLimiterGlobal, rlKey))) {
659
- return jsonWithHeaders({ error: 'Too many submissions. Please try again later.' }, 429, cors);
660
- }
661
- // Hard server-side origin check when an embed allowlist is configured —
662
- // browser CORS alone does not prevent a non-browser client from posting.
663
- if (allowedDomains && allowedDomains.length > 0) {
664
- const origin = request.headers.get('origin');
665
- if (origin && !isOriginAllowed(origin, allowedDomains)) {
666
- return jsonWithHeaders({ error: 'This form cannot be submitted from this origin.' }, 403, cors);
667
- }
668
- }
669
- const parsed = await parseSubmissionRequest(request);
670
- if (!parsed) {
671
- return jsonWithHeaders({ error: 'Invalid or missing submission body.' }, 400, cors);
672
- }
673
- const captchaConfig = getCaptchaConfig();
674
- if (captchaConfig.provider !== 'none' && captchaConfig.enforce) {
675
- const result = await verifyCaptcha(parsed.meta.captchaToken, captchaConfig, isResolvedIp(ip) ? ip : undefined);
676
- if (!result.success) {
677
- const providerError = isCaptchaProviderError(result);
678
- if (providerError && captchaConfig.onProviderError === 'fail-open') {
679
- void logEvent({
680
- event: 'captcha.provider_error',
681
- details: {
682
- formId: form.id,
683
- formSlug: form.slug,
684
- provider: captchaConfig.provider,
685
- policy: 'fail-open',
686
- errorCodes: result.errorCodes ?? [],
687
- },
688
- }).catch(() => { });
689
- }
690
- else {
691
- void logEvent({
692
- event: providerError ? 'captcha.provider_error' : 'captcha.verify_failed',
693
- details: {
694
- formId: form.id,
695
- formSlug: form.slug,
696
- provider: captchaConfig.provider,
697
- policy: providerError ? captchaConfig.onProviderError : 'reject',
698
- errorCodes: result.errorCodes ?? [],
699
- score: result.score ?? null,
700
- },
701
- }).catch(() => { });
702
- return jsonWithHeaders({
703
- error: providerError
704
- ? 'CAPTCHA provider unavailable. Please try again shortly.'
705
- : 'CAPTCHA verification failed. Please try again.',
706
- code: providerError ? 'CAPTCHA_PROVIDER_ERROR' : 'CAPTCHA_FAILED',
707
- }, 403, cors);
708
- }
709
- }
710
- }
711
- if (parsed.files.length > 0) {
712
- const fileCfg = getPrentaConfig()?.forms?.fileUpload;
713
- if (fileCfg?.enabled === false) {
714
- return jsonWithHeaders({ error: 'File uploads are not enabled for this site.' }, 400, cors);
715
- }
716
- const { fields } = await resolveSubmissionFields(form);
717
- const fileCheck = validateSubmissionFiles(fields, parsed.files, {
718
- maxSizeBytes: fileCfg?.maxSizeMB ? fileCfg.maxSizeMB * 1024 * 1024 : DEFAULT_MAX_FILE_BYTES,
719
- allowedMimeTypes: fileCfg?.allowedMimeTypes ?? FORM_UPLOAD_ALLOWED_MIME_TYPES,
720
- });
721
- if (!fileCheck.ok) {
722
- return jsonWithHeaders({ error: 'File validation failed.', code: 'INVALID_FILES', details: fileCheck.errors }, 422, cors);
723
- }
724
- }
725
- const ctx = {
726
- values: parsed.values,
727
- files: parsed.files,
728
- ip,
729
- userAgent: request.headers.get('user-agent'),
730
- referrer: request.headers.get('referer'),
731
- origin: request.headers.get('origin'),
732
- pageUrl: parsed.meta.pageUrl,
733
- attribution: parsed.meta.attribution,
734
- elapsedMs: parsed.meta.elapsedMs,
735
- };
736
- try {
737
- const result = await processSubmission(form, ctx);
738
- const confirmation = result.confirmation;
739
- if (requestPrefersHtmlResponse(request)) {
740
- if (confirmation.type === 'redirect' && confirmation.redirectUrl) {
741
- return Response.redirect(confirmation.redirectUrl, 303);
742
- }
743
- const message = confirmation.message ??
744
- form.successMessage ??
745
- 'Thank you! Your submission has been received.';
746
- return htmlWithHeaders(renderSubmissionResultHtml(message, false), 201, cors);
747
- }
748
- return jsonWithHeaders({
749
- data: {
750
- success: true,
751
- submissionId: result.submissionId,
752
- entryNumber: result.entryNumber,
753
- confirmation: result.confirmation,
754
- },
755
- }, 201, cors);
756
- }
757
- catch (err) {
758
- if (err instanceof SubmissionValidationError) {
759
- if (requestPrefersHtmlResponse(request)) {
760
- return htmlWithHeaders(renderSubmissionResultHtml('Please check the form and try again.', true), 422, cors);
761
- }
762
- return jsonWithHeaders({ error: 'Validation failed.', code: 'VALIDATION_ERROR', details: err.fieldErrors }, 422, cors);
763
- }
764
- return internalError(err);
765
- }
766
- }
767
- /** Native HTML form posts typically prefer HTML; fetch/XHR clients send Accept: application/json. */
768
- export function requestPrefersHtmlResponse(request) {
769
- const accept = request.headers.get('accept') ?? '';
770
- if (accept.includes('application/json') && !accept.includes('text/html'))
771
- return false;
772
- const contentType = request.headers.get('content-type') ?? '';
773
- if (contentType.includes('application/x-www-form-urlencoded') ||
774
- contentType.includes('multipart/form-data')) {
775
- return !accept.includes('application/json') || accept.includes('text/html');
776
- }
777
- return accept.includes('text/html') && !accept.includes('application/json');
778
- }
779
- function escapeHtmlText(value) {
780
- return value
781
- .replace(/&/g, '&amp;')
782
- .replace(/</g, '&lt;')
783
- .replace(/>/g, '&gt;')
784
- .replace(/"/g, '&quot;');
785
- }
786
- function renderSubmissionResultHtml(message, isError) {
787
- const title = isError ? 'Submission error' : 'Thank you';
788
- const role = isError ? 'alert' : 'status';
789
- return `<!DOCTYPE html>
790
- <html lang="en">
791
- <head>
792
- <meta charset="utf-8" />
793
- <meta name="viewport" content="width=device-width, initial-scale=1" />
794
- <title>${escapeHtmlText(title)}</title>
795
- </head>
796
- <body>
797
- <main><p role="${role}">${escapeHtmlText(message)}</p></main>
798
- </body>
799
- </html>`;
800
- }
801
- function htmlWithHeaders(body, status, extra) {
802
- return new Response(body, {
803
- status,
804
- headers: {
805
- ...SECURITY_HEADERS,
806
- 'Content-Type': 'text/html; charset=utf-8',
807
- ...extra,
808
- },
809
- });
810
- }
811
- export function normalizeRedirect(redirect) {
812
- return {
813
- ...redirect,
814
- from: redirect.from ?? redirect.source ?? '',
815
- to: redirect.to ?? redirect.destination ?? '',
816
- type: String(redirect.type ?? redirect.statusCode ?? 301),
817
- hits: Number(redirect.hits ?? 0),
818
- active: redirect.active ?? true,
819
- };
820
- }
821
- export function normalizeSeoPage(page) {
822
- const data = asRecord(page.data);
823
- const structuredData = asRecord(page.structuredData);
824
- const issueValue = structuredData.issues ?? data.issues;
825
- const issueCount = Array.isArray(issueValue) ? issueValue.length : Number(issueValue ?? 0);
826
- const slug = String(data.slug ?? page.slug ?? page.id ?? '');
827
- const schemaType = data.schemaType ?? data.structuredDataType ?? structuredData.schemaType ?? '';
828
- // Return ONLY the derived summary fields — never the raw `data` /
829
- // `structuredData` JSONB blobs. This endpoint powers a summary table; for
830
- // section-built pages those blobs are large, so spreading them made the
831
- // response grow linearly with page content (megabytes for a table that only
832
- // needs a dozen scalar fields).
833
- return {
834
- id: page.id,
835
- collection: page.collection,
836
- updatedAt: page.updatedAt,
837
- url: data.url ?? (slug === 'home' ? '/' : `/${slug}`),
838
- title: data.title ?? page.title ?? 'Untitled',
839
- score: Number(structuredData.score ?? data.score ?? 0),
840
- issues: issueCount,
841
- metaTitle: data.metaTitle ?? '',
842
- metaDescription: data.metaDescription ?? '',
843
- canonical: data.canonical ?? data.canonicalUrl ?? '',
844
- schemaType,
845
- };
846
- }
847
- export function hasModel(d, name) {
848
- try {
849
- return d[name] && typeof d[name].findMany === 'function';
850
- }
851
- catch {
852
- return false;
853
- }
854
- }
855
- /** Format a number compactly, e.g. 8400 -> "8.4K", 1_200_000 -> "1.2M". */
856
- export function formatCompactNumber(n) {
857
- if (!Number.isFinite(n))
858
- return '0';
859
- if (Math.abs(n) >= 1_000_000)
860
- return `${(n / 1_000_000).toFixed(1)}M`;
861
- if (Math.abs(n) >= 1_000)
862
- return `${(n / 1_000).toFixed(1)}K`;
863
- return String(Math.round(n));
864
- }
865
- /** Minimal CSV line parser supporting double-quoted fields with escaped quotes. */
866
- export function parseCsvLine(line) {
867
- const out = [];
868
- let cur = '';
869
- let inQuotes = false;
870
- for (let i = 0; i < line.length; i++) {
871
- const ch = line[i];
872
- if (inQuotes) {
873
- if (ch === '"') {
874
- if (line[i + 1] === '"') {
875
- cur += '"';
876
- i++;
877
- }
878
- else {
879
- inQuotes = false;
880
- }
881
- }
882
- else {
883
- cur += ch;
884
- }
885
- }
886
- else if (ch === '"') {
887
- inQuotes = true;
888
- }
889
- else if (ch === ',') {
890
- out.push(cur);
891
- cur = '';
892
- }
893
- else {
894
- cur += ch;
895
- }
896
- }
897
- out.push(cur);
898
- return out;
899
- }
900
- export function modelNotAvailable(name) {
901
- return errorResponse(`The "${name}" model is not available in your Prisma schema. ` +
902
- 'Run `prenta db:init` for new schemas, or carefully update the existing Prenta block, create/apply a Prisma migration, then regenerate Prisma Client. ' +
903
- 'See https://prentacms.dev/docs/database-setup for required models.', 501);
904
- }
905
- /**
906
- * XML-escape a value for safe inclusion in sitemap content. Sitemaps reject
907
- * unescaped ampersands and angle brackets; URLs frequently contain `&` query
908
- * separators, so this is non-optional.
909
- */
910
- export function escapeXml(value) {
911
- return value
912
- .replace(/&/g, '&amp;')
913
- .replace(/</g, '&lt;')
914
- .replace(/>/g, '&gt;')
915
- .replace(/"/g, '&quot;')
916
- .replace(/'/g, '&apos;');
917
- }
918
- /**
919
- * URLs per sitemap file. The sitemaps protocol caps a single file at 50,000
920
- * URLs, but the child-sitemap route must load each row's full `data` JSON blob
921
- * (for path/noindex/images) into memory to build the XML — at 45k rows that is
922
- * hundreds of MB per request on an unauthenticated, crawler-hit endpoint. We
923
- * cap well below the protocol limit to bound per-request memory; collections
924
- * larger than this are split across multiple `?page=N` files referenced from
925
- * the sitemap index, so no URLs are lost.
926
- */
927
- export const SITEMAP_PAGE_SIZE = 10000;
928
- /**
929
- * Renders a 1200x630 SVG suitable for og:image. We don't pull in Satori/resvg
930
- * because most integrators don't need PNG — major crawlers (Facebook, Twitter,
931
- * LinkedIn, Slack, Discord) handle image/svg+xml correctly. Sites that
932
- * specifically need PNG can override with their own /og endpoint via
933
- * @vercel/og and point `seo.defaultOgImage` at it.
934
- */
935
- export function renderOgSvg(opts) {
936
- const { title, description, siteName, bg, fg, muted } = opts;
937
- // Naive line wrapping at ~22 chars (large font). Good enough for an OG card;
938
- // anything longer than ~3 lines gets truncated with an ellipsis.
939
- const wrap = (text, maxChars, maxLines) => {
940
- const words = text.split(/\s+/);
941
- const lines = [];
942
- let current = '';
943
- for (const w of words) {
944
- if (lines.length >= maxLines)
945
- break;
946
- const next = current ? `${current} ${w}` : w;
947
- if (next.length > maxChars) {
948
- if (current)
949
- lines.push(current);
950
- current = w;
951
- if (lines.length === maxLines - 1 && words.indexOf(w) < words.length - 1) {
952
- lines.push(current.length > maxChars ? current.slice(0, maxChars - 1) + '…' : current + '…');
953
- current = '';
954
- break;
955
- }
956
- }
957
- else {
958
- current = next;
959
- }
960
- }
961
- if (current && lines.length < maxLines)
962
- lines.push(current);
963
- return lines;
964
- };
965
- const escapeSvg = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
966
- const titleLines = wrap(title, 28, 3);
967
- const descLines = description ? wrap(description, 60, 2) : [];
968
- const titleEls = titleLines
969
- .map((line, i) => `<tspan x="60" dy="${i === 0 ? 0 : 78}">${escapeSvg(line)}</tspan>`)
970
- .join('');
971
- const descEls = descLines
972
- .map((line, i) => `<tspan x="60" dy="${i === 0 ? 0 : 36}">${escapeSvg(line)}</tspan>`)
973
- .join('');
974
- // Layout: site name top-left, title bottom-left, description below title.
975
- // Coordinates are roughly aligned to the 1200x630 spec used by every major
976
- // social platform.
977
- const titleY = descLines.length > 0 ? 360 : 420;
978
- const descY = titleY + 80 * titleLines.length;
979
- return `<?xml version="1.0" encoding="UTF-8"?>
980
- <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">
981
- <rect width="1200" height="630" fill="${bg}"/>
982
- ${siteName ? `<text x="60" y="100" font-family="system-ui, -apple-system, Segoe UI, Arial, sans-serif" font-size="28" font-weight="500" fill="${muted}">${escapeSvg(siteName)}</text>` : ''}
983
- <text x="60" y="${titleY}" font-family="system-ui, -apple-system, Segoe UI, Arial, sans-serif" font-size="68" font-weight="700" fill="${fg}">${titleEls}</text>
984
- ${descLines.length > 0 ? `<text x="60" y="${descY}" font-family="system-ui, -apple-system, Segoe UI, Arial, sans-serif" font-size="30" fill="${muted}">${descEls}</text>` : ''}
985
- <rect x="60" y="560" width="60" height="6" fill="${fg}" rx="3"/>
986
- </svg>`;
987
- }
988
- /**
989
- * Log unexpected query failures from the `safe*` wrappers.
990
- *
991
- * The wrappers exist so an optional Prisma model (e.g. a delegate
992
- * that older schemas don't define) doesn't blow up the route — they
993
- * return the empty value (`0` / `[]`) when the model isn't available.
994
- * That defensive contract historically swallowed *every* error,
995
- * including Prisma's "Unknown argument" rejections that flag a real
996
- * application bug (see the `relationLoadStrategy` regression
997
- * discovered while landing Phase 5.5 #5). Logging the underlying
998
- * error preserves the defensive return semantics while making the
999
- * actual class of bug visible in Vercel + Sentry logs.
1000
- *
1001
- * Kept private to this module — it's a logging contract, not a
1002
- * public API.
1003
- */
1004
- export function logSafeQueryFailure(scope, err) {
1005
- // Defensive: never throw from a logger that wraps `safe*` queries
1006
- // — the whole point of those wrappers is to keep the request hot
1007
- // path alive.
1008
- try {
1009
- const message = err instanceof Error ? err.message : String(err);
1010
- logger.warn(`${scope} query failed`, { error: message });
1011
- }
1012
- catch {
1013
- /* swallow */
1014
- }
1015
- }
1016
- export async function safeCount(model, where) {
1017
- if (!model || typeof model !== 'object')
1018
- return 0;
1019
- let countFn;
1020
- try {
1021
- countFn = model.count;
1022
- }
1023
- catch {
1024
- return 0;
1025
- }
1026
- if (typeof countFn !== 'function')
1027
- return 0;
1028
- try {
1029
- return await countFn.call(model, where ? { where } : undefined);
1030
- }
1031
- catch (err) {
1032
- logSafeQueryFailure('safeCount', err);
1033
- return 0;
1034
- }
1035
- }
1036
- export async function safeFindMany(model, args) {
1037
- if (!model || typeof model !== 'object')
1038
- return [];
1039
- let findManyFn;
1040
- try {
1041
- findManyFn = model.findMany;
1042
- }
1043
- catch {
1044
- return [];
1045
- }
1046
- if (typeof findManyFn !== 'function')
1047
- return [];
1048
- try {
1049
- return await findManyFn.call(model, args);
1050
- }
1051
- catch (err) {
1052
- logSafeQueryFailure('safeFindMany', err);
1053
- return [];
1054
- }
1055
- }
1056
- /**
1057
- * String-level gate before fetching a media `storageKey`. Delegates to
1058
- * {@link validateWebhookUrl} (IP canonicalization for decimal/octal/hex,
1059
- * CGNAT, metadata, etc.) so this allowlist cannot drift from the SSRF policy
1060
- * used by `safeFetch`. Also rejects `*.local` (mDNS) which webhook validation
1061
- * does not cover.
1062
- */
1063
- export function isAllowedStorageUrl(url) {
1064
- if (!validateWebhookUrl(url).valid)
1065
- return false;
1066
- try {
1067
- const h = new URL(url).hostname.toLowerCase();
1068
- if (h.endsWith('.local'))
1069
- return false;
1070
- return true;
1071
- }
1072
- catch {
1073
- return false;
1074
- }
1075
- }
1076
- /** Max image size (bytes) we'll pull into memory for vision analysis. */
1077
- const MAX_VISION_IMAGE_BYTES = 8 * 1024 * 1024;
1078
- /**
1079
- * Fetch image bytes for multimodal (vision) analysis through {@link safeFetch}
1080
- * (SSRF-safe: re-validates the host, DNS-resolves to defeat rebinding, no
1081
- * redirects). Returns `null` on any failure (non-image, oversize, blocked,
1082
- * network) so the caller transparently falls back to a context-only heuristic.
1083
- */
1084
- export async function fetchImageForVision(url, knownMimeType) {
1085
- try {
1086
- const resp = await safeFetch(url, { method: 'GET', timeoutMs: 5000 });
1087
- if (!resp.ok)
1088
- return null;
1089
- const contentType = ((resp.headers.get('content-type') ?? knownMimeType ?? '').split(';')[0] ?? '').trim();
1090
- if (!contentType.startsWith('image/'))
1091
- return null;
1092
- const declaredLength = Number(resp.headers.get('content-length') ?? '0');
1093
- if (declaredLength > MAX_VISION_IMAGE_BYTES)
1094
- return null;
1095
- const buffer = Buffer.from(await resp.arrayBuffer());
1096
- if (buffer.byteLength === 0 || buffer.byteLength > MAX_VISION_IMAGE_BYTES)
1097
- return null;
1098
- return { base64: buffer.toString('base64'), mimeType: contentType };
1099
- }
1100
- catch {
1101
- return null;
1102
- }
1103
- }
1104
- let _secretMissing = false;
1105
- let _secretWarningLogged = false;
1106
- export function getSessionSecret() {
1107
- const secret = process.env.CMS_SECRET ?? process.env.CMS_SESSION_SECRET ?? getPrentaConfig()?.secret;
1108
- if (!secret) {
1109
- _secretMissing = true;
1110
- if (!_secretWarningLogged) {
1111
- _secretWarningLogged = true;
1112
- logger.error('Missing CMS secret. Set CMS_SECRET (min 32 characters) or pass secret in prenta.config.ts. Authenticated routes return 503 until it is set.');
1113
- }
1114
- throw new Error('CMS secret not configured');
1115
- }
1116
- if (secret.length < 32) {
1117
- throw new Error('[Prenta CMS] CMS secret must be at least 32 characters (got ' +
1118
- secret.length +
1119
- '). ' +
1120
- "Generate a secure value with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"");
1121
- }
1122
- _secretMissing = false;
1123
- return secret;
1124
- }
1125
- export function isSecretMissing() {
1126
- if (_secretMissing)
1127
- return true;
1128
- try {
1129
- getSessionSecret();
1130
- return false;
1131
- }
1132
- catch {
1133
- return true;
1134
- }
1135
- }
1136
- export async function extractSession(request) {
1137
- if (isSecretMissing())
1138
- return null;
1139
- let token;
1140
- const authHeader = request.headers.get('Authorization');
1141
- if (authHeader?.startsWith('Bearer ')) {
1142
- token = authHeader.slice(7);
1143
- }
1144
- if (!token) {
1145
- const cookieHeader = request.headers.get('cookie') ?? '';
1146
- const cookies = parseCookieHeader(cookieHeader);
1147
- token = cookies['prenta_session'];
1148
- }
1149
- if (!token)
1150
- return null;
1151
- // API key path. Keys are recognized by the `act_sk_` prefix and looked up
1152
- // by SHA-256 hash. We never JWT-verify these tokens — they are opaque
1153
- // random secrets stored as hashes in `prenta_api_keys`.
1154
- if (looksLikeApiKey(token)) {
1155
- try {
1156
- const d = getDB();
1157
- if (!hasModel(d, 'apiKey'))
1158
- return null;
1159
- const hash = await hashApiKey(token);
1160
- const apiKey = await d.apiKey.findUnique({ where: { keyHash: hash } });
1161
- if (!apiKey)
1162
- return null;
1163
- if (apiKey.revokedAt)
1164
- return null;
1165
- if (apiKey.expiresAt && new Date(apiKey.expiresAt).getTime() < Date.now())
1166
- return null;
1167
- const ipRestrictions = Array.isArray(apiKey.ipRestrictions)
1168
- ? apiKey.ipRestrictions
1169
- : apiKey.ipRestrictions
1170
- ? (apiKey.ipRestrictions.allow ?? null)
1171
- : null;
1172
- if (ipRestrictions && ipRestrictions.length > 0) {
1173
- const ip = getClientIp(request);
1174
- if (!validateApiKeyIp(ipRestrictions, ip))
1175
- return null;
1176
- }
1177
- // Keys inherit the owner's current lifecycle + role. Suspension, lock,
1178
- // deactivation, or a demotion must take effect immediately — the key
1179
- // cannot outrank the user who minted it (CRIT-1).
1180
- if (!hasModel(d, 'user'))
1181
- return null;
1182
- const owner = await d.user.findUnique({
1183
- where: { id: apiKey.userId },
1184
- select: { id: true, role: true, isActive: true, suspendedAt: true, lockedAt: true },
1185
- });
1186
- if (!owner)
1187
- return null;
1188
- if (owner.isActive === false || owner.suspendedAt || owner.lockedAt)
1189
- return null;
1190
- const scopes = apiKey.scopes ?? {};
1191
- // Fire-and-forget lastUsedAt update; never block the request on it.
1192
- void d.apiKey
1193
- .update({ where: { id: apiKey.id }, data: { lastUsedAt: new Date() } })
1194
- .catch(() => { });
1195
- bindRequestLogUser(apiKey.userId);
1196
- return {
1197
- userId: apiKey.userId,
1198
- role: scopes.admin ? String(owner.role || 'ADMIN') : 'API_KEY',
1199
- sessionId: apiKey.id,
1200
- apiKey: { id: apiKey.id, scopes },
1201
- };
1202
- }
1203
- catch {
1204
- return null;
1205
- }
1206
- }
1207
- // Session JWT path.
1208
- try {
1209
- const payload = await verifySession(token, { secret: getSessionSecret() });
1210
- const d = getDB();
1211
- if (hasModel(d, 'session')) {
1212
- const dbSession = await d.session.findUnique({
1213
- where: { id: payload.sessionId },
1214
- select: { revokedAt: true },
1215
- });
1216
- if (!dbSession || dbSession.revokedAt)
1217
- return null;
1218
- }
1219
- if (payload.userId)
1220
- bindRequestLogUser(payload.userId);
1221
- return payload;
1222
- }
1223
- catch {
1224
- return null;
1225
- }
1226
- }
1227
- export function parseCookieHeader(cookieHeader) {
1228
- const cookies = {};
1229
- for (const pair of cookieHeader.split(';')) {
1230
- const [key, ...rest] = pair.split('=');
1231
- if (key) {
1232
- cookies[key.trim()] = rest.join('=').trim();
1233
- }
1234
- }
1235
- return cookies;
1236
- }
1237
- /**
1238
- * Verify a password (or "current password") posted in the X-Reauth-Password
1239
- * header against the authenticated user. Returns an error Response when the
1240
- * header is missing or the password is wrong; returns null on success.
1241
- *
1242
- * Use this for high-impact account changes (TOTP enable/disable, role change,
1243
- * delete user, etc.) so a stolen session alone cannot perform them.
1244
- */
1245
- export async function requirePasswordReauth(request, userId) {
1246
- const password = request.headers.get('x-reauth-password');
1247
- if (!password) {
1248
- return new Response(JSON.stringify({
1249
- error: 'Re-authentication required for this action.',
1250
- code: 'REAUTH_REQUIRED',
1251
- method: 'password',
1252
- }), { status: 401, headers: { ...SECURITY_HEADERS } });
1253
- }
1254
- try {
1255
- const { getDB } = await import('../db.js');
1256
- const ok = await verifyReauth(userId, password, 'password', getDB());
1257
- if (!ok) {
1258
- return errorResponse('Re-authentication failed.', 401);
1259
- }
1260
- return null;
1261
- }
1262
- catch (err) {
1263
- logger.error('reauth verify failed', {
1264
- error: err instanceof Error ? err.message : String(err),
1265
- });
1266
- return errorResponse('Re-authentication failed.', 401);
1267
- }
1268
- }
1269
- export async function requireAuth(request) {
1270
- if (isSecretMissing()) {
1271
- return {
1272
- error: json({
1273
- error: 'CMS secret not configured. Set CMS_SECRET or CMS_SESSION_SECRET environment variable (min 32 characters).',
1274
- code: 'MISSING_SECRET',
1275
- }, 503),
1276
- };
1277
- }
1278
- const session = await extractSession(request);
1279
- if (!session) {
1280
- return { error: errorResponse('Unauthorized', 401) };
1281
- }
1282
- return { session };
1283
- }
1284
- /**
1285
- * API-key collection-scope check as a plain denial reason (`null` = allowed).
1286
- * JWT sessions are never denied here — role checks are the route's job. Use
1287
- * this where the collection is only known deep inside a service (e.g. an SEO
1288
- * fix that writes a document) and a `Response` cannot be returned directly.
1289
- */
1290
- export function apiKeyCollectionScopeDenial(session, collection, action) {
1291
- if (!session.apiKey)
1292
- return null;
1293
- return validateApiKeyScope(session.apiKey.scopes, collection, action)
1294
- ? null
1295
- : `API key does not have permission to ${action} on collection "${collection}"`;
1296
- }
1297
- /**
1298
- * Check that the request's auth context permits `action` on `collection`.
1299
- * - Session-authenticated requests fall through to `requireRole` semantics:
1300
- * write actions require WRITE_ROLES.
1301
- * - API-key-authenticated requests must have an explicit scope match.
1302
- */
1303
- export function requireCollectionScope(session, collection, action) {
1304
- if (session.apiKey) {
1305
- const denial = apiKeyCollectionScopeDenial(session, collection, action);
1306
- return denial ? errorResponse(denial, 403) : null;
1307
- }
1308
- if (action === 'read')
1309
- return null;
1310
- return requireRole(session.role, WRITE_ROLES);
1311
- }
1312
- export function requireGlobalScope(session, slug) {
1313
- if (session.apiKey) {
1314
- if (!validateApiKeyGlobalScope(session.apiKey.scopes, slug)) {
1315
- return errorResponse(`API key does not have permission for global "${slug}"`, 403);
1316
- }
1317
- }
1318
- return null;
1319
- }
1320
- export function requireMediaScope(session) {
1321
- if (session.apiKey) {
1322
- if (!validateApiKeyMediaScope(session.apiKey.scopes)) {
1323
- return errorResponse('API key does not have media scope', 403);
1324
- }
1325
- }
1326
- return null;
1327
- }
1328
- export function requireAdminScope(session) {
1329
- if (session.apiKey) {
1330
- if (!session.apiKey.scopes.admin) {
1331
- return errorResponse('API key does not have admin scope', 403);
1332
- }
1333
- return null;
1334
- }
1335
- return requireRole(session.role, ADMIN_ROLES);
1336
- }
1337
- export function buildActionContext(session, db, locale) {
1338
- return {
1339
- userId: session.userId,
1340
- role: session.role,
1341
- locale,
1342
- db,
1343
- };
1344
- }
1345
- export const WRITE_ROLES = new Set(['OWNER', 'ADMIN', 'EDITOR', 'AUTHOR']);
1346
- export const ADMIN_ROLES = new Set(['OWNER', 'ADMIN']);
1347
- export function requireRole(role, allowedRoles) {
1348
- if (!allowedRoles.has(role)) {
1349
- return errorResponse('Insufficient permissions', 403);
1350
- }
1351
- return null;
1352
- }
1353
- /**
1354
- * Build the shared {@link TeamOptions} for the Users endpoints from config +
1355
- * session: the workspace domain (for external-domain detection) and the seat
1356
- * cap (config-provided; null = unlimited until billing exists).
1357
- */
1358
- export function teamOptionsFor(session) {
1359
- const cfg = getPrentaConfig();
1360
- const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ??
1361
- cfg?.seo?.siteUrl ??
1362
- null;
1363
- const seatLimit = cfg?.users?.seatLimit ??
1364
- cfg?.admin?.seatLimit ??
1365
- null;
1366
- return {
1367
- workspaceDomain: workspaceDomainFromUrl(siteUrl),
1368
- seatLimit,
1369
- currentUserId: session.userId,
1370
- };
1371
- }
1372
- /** Whether the configured email provider can actually send mail. */
1373
- function isEmailConfigured() {
1374
- const cfg = getPrentaConfig();
1375
- if (cfg?.platform?.email)
1376
- return true;
1377
- return !!resolveEmailSender();
1378
- }
1379
- /**
1380
- * DB-aware variant of {@link isEmailConfigured} — also true when a provider
1381
- * is configured through Settings > Email.
1382
- */
1383
- export async function isEmailConfiguredAsync(db) {
1384
- if (isEmailConfigured())
1385
- return true;
1386
- const { resolveEmailSenderAsync } = await import('../email/resolve.js');
1387
- return Boolean(await resolveEmailSenderAsync(db));
1388
- }
1389
- export const loginLimiter = createRateLimiter({
1390
- maxRequests: 5,
1391
- windowMs: 15 * 60 * 1000,
1392
- failClosed: true,
1393
- });
1394
- // Fallback limiter for auth requests whose client IP can't be resolved (no
1395
- // trusted proxy header) — those all share ONE bucket. The strict 5/15min
1396
- // `loginLimiter` there would let a handful of anonymous requests lock every
1397
- // user out of login (see #536), so the shared "unknown" bucket gets a much
1398
- // higher ceiling. The real fix is resolving IPs (PRENTA_TRUST_PROXY); this
1399
- // just bounds abuse without turning a mis-config into a global outage.
1400
- export const loginUnknownLimiter = createRateLimiter({
1401
- maxRequests: 100,
1402
- windowMs: 15 * 60 * 1000,
1403
- failClosed: true,
1404
- });
1405
- /** Per-email-hash login limiter so account protection does not depend on IP. */
1406
- export const loginEmailLimiter = createRateLimiter({
1407
- maxRequests: 5,
1408
- windowMs: 15 * 60 * 1000,
1409
- failClosed: true,
1410
- });
1411
- // Admin-gated, but bounds invitation-email volume (and accidental loops) per
1412
- // admin: enough to onboard a team, low enough to deter abuse.
1413
- export const inviteLimiter = createRateLimiter({ maxRequests: 20, windowMs: 60 * 60 * 1000 });
1414
- export const totpLimiter = createRateLimiter({
1415
- maxRequests: 10,
1416
- windowMs: 15 * 60 * 1000,
1417
- failClosed: true,
1418
- });
1419
- // Admin-gated test sends from Settings > Email — enough to debug a provider
1420
- // setup, low enough that a compromised admin session can't spray mail.
1421
- export const emailTestLimiter = createRateLimiter({ maxRequests: 10, windowMs: 60 * 60 * 1000 });
1422
- const formLimiterGlobal = createRateLimiter({ maxRequests: 10, windowMs: 60_000 });
1423
- export const aiGenerateLimiter = createRateLimiter({
1424
- maxRequests: 20,
1425
- windowMs: 60 * 60 * 1000,
1426
- failClosed: true,
1427
- });
1428
- // Strict per-user upload cap (security rule: uploads strict at 20/hour) — guards
1429
- // storage cost and optimization abuse beyond the global per-IP API bucket.
1430
- export const uploadLimiter = createRateLimiter({
1431
- maxRequests: 20,
1432
- windowMs: 60 * 60 * 1000,
1433
- failClosed: true,
1434
- });
1435
- // Deterministic (no provider) AI-adjacent routes that scan/iterate documents.
1436
- // Cheaper than the generation budget but still bounded against cost/DoS.
1437
- export const aiAnalysisLimiter = createRateLimiter({
1438
- maxRequests: 60,
1439
- windowMs: 60 * 60 * 1000,
1440
- failClosed: true,
1441
- });
1442
- // Upper bound on free-text inputs to the deterministic analysis routes
1443
- // (document body / link-candidate content) — caps memory + scan work.
1444
- export const AI_ANALYSIS_MAX_CHARS = 50_000;
1445
- export const linkHealthLimiter = createRateLimiter({ maxRequests: 4, windowMs: 60 * 60 * 1000 });
1446
- export const seoAuditLimiter = createRateLimiter({ maxRequests: 10, windowMs: 60 * 60 * 1000 });
1447
- // Admin-gated live checks against the Google Search Console API ("Test
1448
- // connection") — enough to debug a setup, bounded against key-guessing.
1449
- export const searchConsoleTestLimiter = createRateLimiter({
1450
- maxRequests: 10,
1451
- windowMs: 60 * 60 * 1000,
1452
- failClosed: true,
1453
- });
1454
- // Manual search-data syncs hit Google quotas and write big row sets; the
1455
- // nightly cron is the normal path, so the manual button is strictly bounded.
1456
- export const searchSyncLimiter = createRateLimiter({
1457
- maxRequests: 5,
1458
- windowMs: 60 * 60 * 1000,
1459
- failClosed: true,
1460
- });
1461
- // Digest test-sends dispatch real email to the caller — strictly bounded.
1462
- export const digestTestSendLimiter = createRateLimiter({
1463
- maxRequests: 5,
1464
- windowMs: 60 * 60 * 1000,
1465
- failClosed: true,
1466
- });
1467
- export async function checkRateLimitAsync(limiter, key) {
1468
- // Explicit, environment-gated bypass for test harnesses. Production never
1469
- // sets this — Vercel + the deploy guide both omit it. We deliberately do
1470
- // NOT key off `NODE_ENV === 'test'` because Next.js builds run with
1471
- // NODE_ENV=test in some CI configurations and we want rate limiting
1472
- // exercised by unit tests that explicitly opt in.
1473
- if (process.env.PRENTA_DISABLE_RATE_LIMIT === '1') {
1474
- return true;
1475
- }
1476
- const result = await limiter.check(key);
1477
- return result.allowed;
1478
- }
1479
- /**
1480
- * Resolve the client IP from trusted-proxy headers (Vercel first, then x-real-ip,
1481
- * then x-forwarded-for only when PRENTA_TRUST_PROXY=1). Returns 'unknown' when
1482
- * no trustworthy source is available — callers MUST treat that case as a hard
1483
- * failure for security-sensitive decisions like rate-limit keys and IP allowlists.
1484
- */
1485
- export function clientIp(request) {
1486
- return getClientIp(request);
1487
- }
1488
- /**
1489
- * Compute a before/after diff of top-level scalar (string/number/boolean) keys
1490
- * between a stored record and an incoming patch. Used to audit settings changes
1491
- * without ever logging nested objects (which may hold secret blobs).
1492
- */
1493
- export function diffScalarKeys(previous, next) {
1494
- const isScalar = (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null;
1495
- const changes = [];
1496
- for (const key of Object.keys(next)) {
1497
- const to = next[key];
1498
- if (!isScalar(to))
1499
- continue;
1500
- const from = previous[key];
1501
- if (isScalar(from) && from === to)
1502
- continue;
1503
- if (!isScalar(from) && from !== undefined)
1504
- continue;
1505
- changes.push({ key, from: isScalar(from) ? from : undefined, to });
1506
- }
1507
- return changes;
1508
- }
1509
- const MAX_CONCURRENT_SESSIONS = 5;
1510
- /**
1511
- * After a successful primary-credential check, prune the user's active sessions
1512
- * down to the configured concurrent maximum (default 5; configurable via
1513
- * `auth.maxConcurrentSessions`). Strategy is "revoke oldest" so a user can
1514
- * always sign in.
1515
- */
1516
- export async function enforceSessionLimitsForUser(d, userId) {
1517
- if (!hasModel(d, 'session'))
1518
- return;
1519
- // Precedence: explicitly-saved Security setting (database) ▸ auth config ▸
1520
- // default. We read the stored value directly (rather than the parsed
1521
- // defaults) so an unsaved policy doesn't shadow a config-provided override.
1522
- let storedMax;
1523
- try {
1524
- if (hasModel(d, 'document')) {
1525
- const row = await d.document.findFirst({
1526
- where: { collection: 'settings', deletedAt: null },
1527
- select: { data: true },
1528
- });
1529
- const stored = row?.data?.security;
1530
- const v = stored?.session?.maxConcurrentSessions;
1531
- if (typeof v === 'number' && Number.isInteger(v) && v >= 0)
1532
- storedMax = v;
1533
- }
1534
- }
1535
- catch {
1536
- /* fall back to config/default below */
1537
- }
1538
- const auth = getPrentaConfig()?.auth;
1539
- const max = storedMax !== undefined
1540
- ? storedMax
1541
- : typeof auth?.maxConcurrentSessions === 'number' && auth.maxConcurrentSessions > 0
1542
- ? auth.maxConcurrentSessions
1543
- : MAX_CONCURRENT_SESSIONS;
1544
- // 0 ⇒ unlimited: skip pruning entirely.
1545
- if (max <= 0)
1546
- return;
1547
- const active = await d.session.findMany({
1548
- where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
1549
- select: { id: true, createdAt: true },
1550
- });
1551
- const decision = enforceSessionLimits(active.map((s) => ({ sessionId: s.id, userId, createdAt: s.createdAt })), { maxConcurrentSessions: max, strategy: 'revoke_oldest' });
1552
- if (decision.sessionsToRevoke.length > 0) {
1553
- await d.session.updateMany({
1554
- where: { id: { in: decision.sessionsToRevoke } },
1555
- data: { revokedAt: new Date() },
1556
- });
1557
- }
1558
- }
1559
- /** Revoke every live API key for a user. Called with session revocation. */
1560
- export async function revokeUserApiKeys(d, userId) {
1561
- if (!hasModel(d, 'apiKey'))
1562
- return 0;
1563
- const result = await d.apiKey.updateMany({
1564
- where: { userId, revokedAt: null },
1565
- data: { revokedAt: new Date() },
1566
- });
1567
- return typeof result?.count === 'number' ? result.count : 0;
1568
- }
1569
- export function getAdminPath() {
1570
- return process.env.PRENTA_ADMIN_PATH ?? getPrentaConfig()?.admin?.path ?? '/admin';
1571
- }
2
+ export { SECURITY_HEADERS } from './security-headers.js';
1572
3
  // Collection lookups live in the config layer so pure domain modules (SEO
1573
4
  // scanner, section helpers) can use them without depending on `api/`.
1574
5
  // Re-exported here for existing route callers.
1575
6
  export { findCollectionDef, collectionSupportsSections } from '../config/collection-lookup.js';
1576
- /**
1577
- * Gate a per-document read for endpoints (e.g. SEO analysis) that fetch a
1578
- * document directly rather than through the collection CRUD routes. Enforces
1579
- * both the API-key collection scope and the collection's `access.read` rule
1580
- * so an AUTHOR scoped to one collection cannot read another's content.
1581
- * Returns a `Response` to short-circuit with, or `null` when allowed.
1582
- */
1583
- export async function enforceDocumentReadAccess(session, collection) {
1584
- const scopeErr = requireCollectionScope(session, collection, 'read');
1585
- if (scopeErr)
1586
- return scopeErr;
1587
- try {
1588
- await assertCollectionAccess(collection, 'read', buildActionContext(session, guardedDb()));
1589
- }
1590
- catch (err) {
1591
- if (err instanceof Error && err.message.includes('Access denied')) {
1592
- return errorResponse('Insufficient permissions', 403);
1593
- }
1594
- throw err;
1595
- }
1596
- return null;
1597
- }
7
+ export { importBlobStorage, mediaUrl, normalizeMediaItem, buildMediaUsedOn, deriveMediaTitleFromAlt, isAllowedStorageUrl, fetchImageForVision, } from './route-helpers/media.js';
8
+ export { buildCoauthorPrompt, maybePopulate } from './route-helpers/authoring.js';
9
+ export { json, jsonWithCache, errorResponse, internalError, actionError, clampPageSize, clampPage, readJsonBody, asRecord, hasModel, formatCompactNumber, parseCsvLine, modelNotAvailable, escapeXml, SITEMAP_PAGE_SIZE, logSafeQueryFailure, safeCount, safeFindMany, } from './route-helpers/http.js';
10
+ export { normalizeSubmission, mapFormError, parseFormsQuery, parseEntriesQuery, formCorsHeaders, jsonWithHeaders, parseSubmissionRequest, submitToForm, requestPrefersHtmlResponse, } from './route-helpers/forms.js';
11
+ export { normalizeRedirect, normalizeSeoPage, renderOgSvg } from './route-helpers/page-shape.js';
12
+ export { getSessionSecret, isSecretMissing, extractSession, parseCookieHeader, requirePasswordReauth, requireAuth, apiKeyCollectionScopeDenial, requireCollectionScope, requireGlobalScope, requireMediaScope, requireAdminScope, buildActionContext, WRITE_ROLES, ADMIN_ROLES, requireRole, teamOptionsFor, isEmailConfiguredAsync, loginLimiter, loginUnknownLimiter, loginEmailLimiter, inviteLimiter, totpLimiter, emailTestLimiter, aiGenerateLimiter, uploadLimiter, aiAnalysisLimiter, AI_ANALYSIS_MAX_CHARS, linkHealthLimiter, seoAuditLimiter, searchConsoleTestLimiter, searchSyncLimiter, digestTestSendLimiter, checkRateLimitAsync, clientIp, diffScalarKeys, enforceSessionLimitsForUser, revokeUserApiKeys, getAdminPath, enforceDocumentReadAccess, } from './route-helpers/auth.js';
1598
13
  //# sourceMappingURL=route-helpers.js.map