@actuate-media/cms-core 0.57.0 → 0.58.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/api/stats-seo-cache.test.js +1 -1
- package/dist/__tests__/api/stats-seo-cache.test.js.map +1 -1
- package/dist/__tests__/auth/oauth.test.js +3 -1
- package/dist/__tests__/auth/oauth.test.js.map +1 -1
- package/dist/__tests__/auth/reset.test.js +1 -0
- package/dist/__tests__/auth/reset.test.js.map +1 -1
- package/dist/__tests__/auth/user-admin.test.js +14 -12
- package/dist/__tests__/auth/user-admin.test.js.map +1 -1
- package/dist/__tests__/db/model-types-freshness.test.d.ts +2 -0
- package/dist/__tests__/db/model-types-freshness.test.d.ts.map +1 -0
- package/dist/__tests__/db/model-types-freshness.test.js +46 -0
- package/dist/__tests__/db/model-types-freshness.test.js.map +1 -0
- package/dist/__tests__/scheduling/scheduling.test.js +8 -6
- package/dist/__tests__/scheduling/scheduling.test.js.map +1 -1
- package/dist/__tests__/server-site.test.js +3 -1
- package/dist/__tests__/server-site.test.js.map +1 -1
- package/dist/__tests__/setup/index.test.js +21 -10
- package/dist/__tests__/setup/index.test.js.map +1 -1
- package/dist/actions.d.ts +2 -1
- package/dist/actions.d.ts.map +1 -1
- package/dist/actions.js +15 -8
- package/dist/actions.js.map +1 -1
- package/dist/api/guarded-db.d.ts +14 -0
- package/dist/api/guarded-db.d.ts.map +1 -0
- package/dist/api/guarded-db.js +58 -0
- package/dist/api/guarded-db.js.map +1 -0
- package/dist/api/handler-factory.d.ts.map +1 -1
- package/dist/api/handler-factory.js +2 -1
- package/dist/api/handler-factory.js.map +1 -1
- package/dist/api/handlers.d.ts +5 -3
- package/dist/api/handlers.d.ts.map +1 -1
- package/dist/api/handlers.js +54 -13068
- package/dist/api/handlers.js.map +1 -1
- package/dist/api/route-helpers.d.ts +321 -0
- package/dist/api/route-helpers.d.ts.map +1 -0
- package/dist/api/route-helpers.js +1307 -0
- package/dist/api/route-helpers.js.map +1 -0
- package/dist/api/routes/ai-seo.d.ts +3 -0
- package/dist/api/routes/ai-seo.d.ts.map +1 -0
- package/dist/api/routes/ai-seo.js +377 -0
- package/dist/api/routes/ai-seo.js.map +1 -0
- package/dist/api/routes/ai-settings.d.ts +3 -0
- package/dist/api/routes/ai-settings.d.ts.map +1 -0
- package/dist/api/routes/ai-settings.js +764 -0
- package/dist/api/routes/ai-settings.js.map +1 -0
- package/dist/api/routes/auth.d.ts +3 -0
- package/dist/api/routes/auth.d.ts.map +1 -0
- package/dist/api/routes/auth.js +787 -0
- package/dist/api/routes/auth.js.map +1 -0
- package/dist/api/routes/collab.d.ts +3 -0
- package/dist/api/routes/collab.d.ts.map +1 -0
- package/dist/api/routes/collab.js +426 -0
- package/dist/api/routes/collab.js.map +1 -0
- package/dist/api/routes/dashboard.d.ts +7 -0
- package/dist/api/routes/dashboard.d.ts.map +1 -0
- package/dist/api/routes/dashboard.js +540 -0
- package/dist/api/routes/dashboard.js.map +1 -0
- package/dist/api/routes/documents.d.ts +3 -0
- package/dist/api/routes/documents.d.ts.map +1 -0
- package/dist/api/routes/documents.js +180 -0
- package/dist/api/routes/documents.js.map +1 -0
- package/dist/api/routes/folders.d.ts +3 -0
- package/dist/api/routes/folders.d.ts.map +1 -0
- package/dist/api/routes/folders.js +195 -0
- package/dist/api/routes/folders.js.map +1 -0
- package/dist/api/routes/forms.d.ts +3 -0
- package/dist/api/routes/forms.d.ts.map +1 -0
- package/dist/api/routes/forms.js +661 -0
- package/dist/api/routes/forms.js.map +1 -0
- package/dist/api/routes/globals.d.ts +3 -0
- package/dist/api/routes/globals.d.ts.map +1 -0
- package/dist/api/routes/globals.js +133 -0
- package/dist/api/routes/globals.js.map +1 -0
- package/dist/api/routes/media.d.ts +3 -0
- package/dist/api/routes/media.d.ts.map +1 -0
- package/dist/api/routes/media.js +521 -0
- package/dist/api/routes/media.js.map +1 -0
- package/dist/api/routes/meta.d.ts +3 -0
- package/dist/api/routes/meta.d.ts.map +1 -0
- package/dist/api/routes/meta.js +96 -0
- package/dist/api/routes/meta.js.map +1 -0
- package/dist/api/routes/page-templates.d.ts +3 -0
- package/dist/api/routes/page-templates.d.ts.map +1 -0
- package/dist/api/routes/page-templates.js +265 -0
- package/dist/api/routes/page-templates.js.map +1 -0
- package/dist/api/routes/presence.d.ts +3 -0
- package/dist/api/routes/presence.d.ts.map +1 -0
- package/dist/api/routes/presence.js +35 -0
- package/dist/api/routes/presence.js.map +1 -0
- package/dist/api/routes/preview.d.ts +3 -0
- package/dist/api/routes/preview.d.ts.map +1 -0
- package/dist/api/routes/preview.js +111 -0
- package/dist/api/routes/preview.js.map +1 -0
- package/dist/api/routes/redirects.d.ts +3 -0
- package/dist/api/routes/redirects.d.ts.map +1 -0
- package/dist/api/routes/redirects.js +790 -0
- package/dist/api/routes/redirects.js.map +1 -0
- package/dist/api/routes/saved-sections.d.ts +3 -0
- package/dist/api/routes/saved-sections.d.ts.map +1 -0
- package/dist/api/routes/saved-sections.js +1036 -0
- package/dist/api/routes/saved-sections.js.map +1 -0
- package/dist/api/routes/scheduling.d.ts +3 -0
- package/dist/api/routes/scheduling.d.ts.map +1 -0
- package/dist/api/routes/scheduling.js +373 -0
- package/dist/api/routes/scheduling.js.map +1 -0
- package/dist/api/routes/sections.d.ts +3 -0
- package/dist/api/routes/sections.d.ts.map +1 -0
- package/dist/api/routes/sections.js +500 -0
- package/dist/api/routes/sections.js.map +1 -0
- package/dist/api/routes/security-center.d.ts +3 -0
- package/dist/api/routes/security-center.d.ts.map +1 -0
- package/dist/api/routes/security-center.js +71 -0
- package/dist/api/routes/security-center.js.map +1 -0
- package/dist/api/routes/seo-public.d.ts +14 -0
- package/dist/api/routes/seo-public.d.ts.map +1 -0
- package/dist/api/routes/seo-public.js +930 -0
- package/dist/api/routes/seo-public.js.map +1 -0
- package/dist/api/routes/seo.d.ts +8 -0
- package/dist/api/routes/seo.d.ts.map +1 -0
- package/dist/api/routes/seo.js +848 -0
- package/dist/api/routes/seo.js.map +1 -0
- package/dist/api/routes/system.d.ts +3 -0
- package/dist/api/routes/system.d.ts.map +1 -0
- package/dist/api/routes/system.js +340 -0
- package/dist/api/routes/system.js.map +1 -0
- package/dist/api/routes/url-resolution.d.ts +3 -0
- package/dist/api/routes/url-resolution.d.ts.map +1 -0
- package/dist/api/routes/url-resolution.js +457 -0
- package/dist/api/routes/url-resolution.js.map +1 -0
- package/dist/api/routes/users.d.ts +3 -0
- package/dist/api/routes/users.d.ts.map +1 -0
- package/dist/api/routes/users.js +1162 -0
- package/dist/api/routes/users.js.map +1 -0
- package/dist/api/routes/webhooks.d.ts +3 -0
- package/dist/api/routes/webhooks.d.ts.map +1 -0
- package/dist/api/routes/webhooks.js +338 -0
- package/dist/api/routes/webhooks.js.map +1 -0
- package/dist/auth/invites.d.ts +9 -8
- package/dist/auth/invites.d.ts.map +1 -1
- package/dist/auth/invites.js.map +1 -1
- package/dist/auth/oauth.d.ts +2 -1
- package/dist/auth/oauth.d.ts.map +1 -1
- package/dist/auth/oauth.js.map +1 -1
- package/dist/auth/reset.d.ts +3 -2
- package/dist/auth/reset.d.ts.map +1 -1
- package/dist/auth/reset.js +5 -2
- package/dist/auth/reset.js.map +1 -1
- package/dist/auth/session.d.ts +3 -2
- package/dist/auth/session.d.ts.map +1 -1
- package/dist/auth/session.js.map +1 -1
- package/dist/auth/team.d.ts +4 -3
- package/dist/auth/team.d.ts.map +1 -1
- package/dist/auth/team.js.map +1 -1
- package/dist/auth/user-admin.d.ts +6 -5
- package/dist/auth/user-admin.d.ts.map +1 -1
- package/dist/auth/user-admin.js.map +1 -1
- package/dist/content-health/cron.d.ts +2 -1
- package/dist/content-health/cron.d.ts.map +1 -1
- package/dist/content-health/cron.js.map +1 -1
- package/dist/cron/index.d.ts +2 -1
- package/dist/cron/index.d.ts.map +1 -1
- package/dist/cron/index.js +2 -0
- package/dist/cron/index.js.map +1 -1
- package/dist/db/client-types.d.ts +75 -0
- package/dist/db/client-types.d.ts.map +1 -0
- package/dist/db/client-types.js +2 -0
- package/dist/db/client-types.js.map +1 -0
- package/dist/db/model-types.d.ts +564 -0
- package/dist/db/model-types.d.ts.map +1 -0
- package/dist/db/model-types.js +14 -0
- package/dist/db/model-types.js.map +1 -0
- package/dist/diagnostics/api-metrics.d.ts.map +1 -1
- package/dist/diagnostics/api-metrics.js.map +1 -1
- package/dist/forms/entries.d.ts.map +1 -1
- package/dist/forms/entries.js.map +1 -1
- package/dist/forms/files.d.ts.map +1 -1
- package/dist/forms/files.js.map +1 -1
- package/dist/forms/service.d.ts.map +1 -1
- package/dist/forms/service.js.map +1 -1
- package/dist/forms/submission.d.ts.map +1 -1
- package/dist/forms/submission.js.map +1 -1
- package/dist/forms/webhooks.d.ts.map +1 -1
- package/dist/forms/webhooks.js.map +1 -1
- package/dist/graphql/index.d.ts.map +1 -1
- package/dist/graphql/index.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/scheduling/index.d.ts +2 -1
- package/dist/scheduling/index.d.ts.map +1 -1
- package/dist/scheduling/index.js.map +1 -1
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js.map +1 -1
- package/dist/security/audit.d.ts.map +1 -1
- package/dist/security/audit.js.map +1 -1
- package/dist/security/reauth.d.ts +2 -1
- package/dist/security/reauth.d.ts.map +1 -1
- package/dist/security/reauth.js.map +1 -1
- package/dist/seo/audit-runner.d.ts +3 -2
- package/dist/seo/audit-runner.d.ts.map +1 -1
- package/dist/seo/audit-runner.js.map +1 -1
- package/dist/server-site.d.ts +2 -1
- package/dist/server-site.d.ts.map +1 -1
- package/dist/server-site.js.map +1 -1
- package/dist/setup/index.d.ts +4 -3
- package/dist/setup/index.d.ts.map +1 -1
- package/dist/setup/index.js.map +1 -1
- package/dist/webhooks/index.d.ts +5 -5
- package/dist/webhooks/index.d.ts.map +1 -1
- package/dist/webhooks/index.js +8 -1
- package/dist/webhooks/index.js.map +1 -1
- package/dist/workflow/index.d.ts.map +1 -1
- package/dist/workflow/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,1307 @@
|
|
|
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 { publicReadCacheControl } from '../cache/http.js';
|
|
9
|
+
import { verifyCaptcha, getCaptchaConfig } from '../security/captcha.js';
|
|
10
|
+
import { FormNotFoundError, FormValidationError, FormConflictError, FormHasSubmissionsError, } from '../forms/service.js';
|
|
11
|
+
import { processSubmission, SubmissionValidationError, } from '../forms/submission.js';
|
|
12
|
+
import { validateSubmissionFiles, FORM_UPLOAD_ALLOWED_MIME_TYPES, DEFAULT_MAX_FILE_BYTES, } from '../forms/files.js';
|
|
13
|
+
import { resolveSubmissionFields } from '../forms/submission.js';
|
|
14
|
+
import { FormWebhookError } from '../forms/webhooks.js';
|
|
15
|
+
import { createRateLimiter } from '../security/rate-limit.js';
|
|
16
|
+
import { getClientIp, isResolvedIp } from '../security/client-ip.js';
|
|
17
|
+
import { safeFetch } from '../security/safe-fetch.js';
|
|
18
|
+
import { enforceSessionLimits } from '../security/session-limits.js';
|
|
19
|
+
import { verifyReauth } from '../security/reauth.js';
|
|
20
|
+
import { getActuateConfig } from '../config/runtime.js';
|
|
21
|
+
import { hashApiKey, looksLikeApiKey, validateApiKeyScope, validateApiKeyGlobalScope, validateApiKeyMediaScope, validateApiKeyPageBuilderScope, validateApiKeyIp, } from '../security/api-key-enhanced.js';
|
|
22
|
+
import { guardedDb, ModelNotAvailableError } from './guarded-db.js';
|
|
23
|
+
// Opaque dynamic import so Turbopack/webpack won't statically analyze the specifier.
|
|
24
|
+
// Returns { put, del, ... } from @vercel/blob when available.
|
|
25
|
+
export async function importBlobStorage() {
|
|
26
|
+
const mod = '@vercel/' + 'blob';
|
|
27
|
+
return import(/* webpackIgnore: true */ mod);
|
|
28
|
+
}
|
|
29
|
+
export async function importAIPlugin() {
|
|
30
|
+
const mod = '@actuate-media/' + 'plugin-ai';
|
|
31
|
+
return import(/* webpackIgnore: true */ mod);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Build the system/user prompt for an inline co-author action. Kept
|
|
35
|
+
* deterministic and small so the governed runtime can route it to any
|
|
36
|
+
* configured provider/model.
|
|
37
|
+
*/
|
|
38
|
+
export function buildCoauthorPrompt(action, body) {
|
|
39
|
+
const text = body.text ?? '';
|
|
40
|
+
switch (action) {
|
|
41
|
+
case 'expand': {
|
|
42
|
+
const hint = body.instructions ? ` Follow this guidance: ${body.instructions}.` : '';
|
|
43
|
+
return {
|
|
44
|
+
system: 'You are an expert writer. Expand the user\u2019s text with more detail and depth ' +
|
|
45
|
+
'while preserving its meaning and voice.' +
|
|
46
|
+
hint +
|
|
47
|
+
' Return only the expanded text, with no preamble.',
|
|
48
|
+
user: text,
|
|
49
|
+
maxTokens: 2048,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
case 'compress': {
|
|
53
|
+
const hint = typeof body.targetLength === 'number' && body.targetLength > 0
|
|
54
|
+
? ` Aim for about ${body.targetLength} words.`
|
|
55
|
+
: '';
|
|
56
|
+
return {
|
|
57
|
+
system: 'You are an expert editor. Tighten the user\u2019s text, removing redundancy while ' +
|
|
58
|
+
'preserving the key information and voice.' +
|
|
59
|
+
hint +
|
|
60
|
+
' Return only the edited text, with no preamble.',
|
|
61
|
+
user: text,
|
|
62
|
+
maxTokens: 1024,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
case 'proofread':
|
|
66
|
+
return {
|
|
67
|
+
system: 'You are a meticulous proofreader. Correct grammar, spelling, and punctuation in the ' +
|
|
68
|
+
'user\u2019s text. Preserve its meaning and voice. Return only the corrected text, ' +
|
|
69
|
+
'with no preamble.',
|
|
70
|
+
user: text,
|
|
71
|
+
maxTokens: 2048,
|
|
72
|
+
};
|
|
73
|
+
case 'rewrite':
|
|
74
|
+
default: {
|
|
75
|
+
const style = body.style ? ` Write in a ${body.style} style.` : '';
|
|
76
|
+
const tone = body.tone ? ` Use a ${body.tone} tone.` : '';
|
|
77
|
+
return {
|
|
78
|
+
system: 'You are an expert editor. Rewrite the user\u2019s text to improve clarity and flow ' +
|
|
79
|
+
'while preserving its meaning.' +
|
|
80
|
+
style +
|
|
81
|
+
tone +
|
|
82
|
+
' Return only the rewritten text, with no preamble.',
|
|
83
|
+
user: text,
|
|
84
|
+
maxTokens: 2048,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Common helper for the read endpoints. Reads the `?populate=` query param,
|
|
91
|
+
* fetches the target collection's field schema, and expands every relation
|
|
92
|
+
* reference into a {@link RelationSummary}. When the caller didn't ask for
|
|
93
|
+
* population (or the doc has no `data` field) we short-circuit and return
|
|
94
|
+
* the doc untouched.
|
|
95
|
+
*
|
|
96
|
+
* Lives here (not in `actions.ts`) because the rest of the actions API
|
|
97
|
+
* stays purely DB-shaped — population is an HTTP concern.
|
|
98
|
+
*/
|
|
99
|
+
export async function maybePopulate(request, collection, doc, dbInstance) {
|
|
100
|
+
if (!doc)
|
|
101
|
+
return doc;
|
|
102
|
+
const url = new URL(request.url);
|
|
103
|
+
const opts = parsePopulateParam(url.searchParams.get('populate'));
|
|
104
|
+
if (!opts)
|
|
105
|
+
return doc;
|
|
106
|
+
const cfg = getActuateConfig();
|
|
107
|
+
const fields = cfg?.collections?.[collection]?.fields;
|
|
108
|
+
if (!fields)
|
|
109
|
+
return doc;
|
|
110
|
+
const data = doc.data && typeof doc.data === 'object' ? doc.data : null;
|
|
111
|
+
if (!data)
|
|
112
|
+
return doc;
|
|
113
|
+
try {
|
|
114
|
+
const populated = await populateRelations(fields, data, buildRelationLookup(dbInstance), opts);
|
|
115
|
+
return { ...doc, data: populated };
|
|
116
|
+
}
|
|
117
|
+
catch (err) {
|
|
118
|
+
// Never let a populate failure mask the underlying document — log and
|
|
119
|
+
// return the unpopulated doc.
|
|
120
|
+
console.error('[actuate][api] populate failed for', collection, err);
|
|
121
|
+
return doc;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export const SECURITY_HEADERS = {
|
|
125
|
+
'Content-Type': 'application/json',
|
|
126
|
+
'X-Content-Type-Options': 'nosniff',
|
|
127
|
+
'X-Frame-Options': 'DENY',
|
|
128
|
+
'Referrer-Policy': 'strict-origin-when-cross-origin',
|
|
129
|
+
};
|
|
130
|
+
export function json(data, status = 200) {
|
|
131
|
+
return new Response(JSON.stringify(data), {
|
|
132
|
+
status,
|
|
133
|
+
headers: { ...SECURITY_HEADERS },
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Variant of `json()` that emits the Phase-5.5 public-read
|
|
138
|
+
* `Cache-Control` header when the active CMS config opts in.
|
|
139
|
+
*
|
|
140
|
+
* - Session-cookie requests always get `private, no-store`.
|
|
141
|
+
* - API-key / unauthenticated requests get
|
|
142
|
+
* `public, s-maxage=N, stale-while-revalidate=M` when
|
|
143
|
+
* `cache.publicReads.enabled` is true.
|
|
144
|
+
* - Otherwise no `Cache-Control` header is set (i.e. the response is
|
|
145
|
+
* uncacheable downstream, matching the pre-5.5 behaviour).
|
|
146
|
+
*
|
|
147
|
+
* Use this for the public read endpoints (`/collections/:slug`,
|
|
148
|
+
* `/collections/:slug/:id`, `/globals/:slug`, `/resolve`). Mutating
|
|
149
|
+
* endpoints stay on the plain `json()` so the CDN never caches a write
|
|
150
|
+
* response by accident.
|
|
151
|
+
*/
|
|
152
|
+
export function jsonWithCache(data, request, status = 200) {
|
|
153
|
+
const cacheControl = publicReadCacheControl(request, getActuateConfig()?.cache);
|
|
154
|
+
const headers = { ...SECURITY_HEADERS };
|
|
155
|
+
if (cacheControl)
|
|
156
|
+
headers['Cache-Control'] = cacheControl;
|
|
157
|
+
return new Response(JSON.stringify(data), { status, headers });
|
|
158
|
+
}
|
|
159
|
+
export function errorResponse(message, status) {
|
|
160
|
+
return json({ error: message }, status);
|
|
161
|
+
}
|
|
162
|
+
export function internalError(err, context) {
|
|
163
|
+
if (err instanceof ModelNotAvailableError) {
|
|
164
|
+
return modelNotAvailable(err.model);
|
|
165
|
+
}
|
|
166
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
167
|
+
console.error(`[actuate][api]${context ? ` ${context}:` : ''} ${msg}`);
|
|
168
|
+
return errorResponse('Internal server error', 500);
|
|
169
|
+
}
|
|
170
|
+
export function clampPageSize(raw, max = 100, fallback = 20) {
|
|
171
|
+
const n = Number(raw) || fallback;
|
|
172
|
+
return Math.min(Math.max(1, n), max);
|
|
173
|
+
}
|
|
174
|
+
export function mediaUrl(storageKey) {
|
|
175
|
+
const value = String(storageKey ?? '');
|
|
176
|
+
if (!value)
|
|
177
|
+
return '';
|
|
178
|
+
return value.startsWith('http://') || value.startsWith('https://') || value.startsWith('/')
|
|
179
|
+
? value
|
|
180
|
+
: '';
|
|
181
|
+
}
|
|
182
|
+
export function normalizeMediaItem(media) {
|
|
183
|
+
const width = typeof media.width === 'number' ? media.width : null;
|
|
184
|
+
const height = typeof media.height === 'number' ? media.height : null;
|
|
185
|
+
return {
|
|
186
|
+
...media,
|
|
187
|
+
name: media.filename ?? media.name ?? '',
|
|
188
|
+
type: media.mimeType ?? media.type ?? '',
|
|
189
|
+
size: formatBytes(Number(media.fileSize ?? media.sizeBytes ?? 0)),
|
|
190
|
+
sizeBytes: Number(media.fileSize ?? media.sizeBytes ?? 0),
|
|
191
|
+
date: media.createdAt ?? media.updatedAt ?? null,
|
|
192
|
+
url: mediaUrl(media.storageKey ?? media.url),
|
|
193
|
+
dimensions: width && height ? `${width}x${height}` : undefined,
|
|
194
|
+
format: typeof media.mimeType === 'string' ? media.mimeType.split('/')[1] : undefined,
|
|
195
|
+
altTag: media.altText ?? media.altTag ?? '',
|
|
196
|
+
title: media.title ?? '',
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Build the admin editor route for a document that references a media asset.
|
|
201
|
+
* Pages own the `/pages/*` namespace; post-type collections use
|
|
202
|
+
* `/posts/:type/:id/edit`; everything else falls back to the generic
|
|
203
|
+
* collection editor. Kept in sync with the route table in `AdminRoot.tsx`.
|
|
204
|
+
*/
|
|
205
|
+
export function mediaUsageEditPath(collection, id) {
|
|
206
|
+
if (collection === 'pages')
|
|
207
|
+
return `/pages/${id}/edit`;
|
|
208
|
+
const def = getActuateConfig()?.collections?.[collection];
|
|
209
|
+
if (def?.type === 'post')
|
|
210
|
+
return `/posts/${collection}/${id}/edit`;
|
|
211
|
+
return `/collections/${collection}/${id}`;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Map the `MediaUsage` join rows (with their related document) into the
|
|
215
|
+
* `{ page, path }[]` shape the admin drawer renders. Soft-deleted documents
|
|
216
|
+
* are excluded so trashed pages don't keep an asset looking "in use".
|
|
217
|
+
*/
|
|
218
|
+
export function buildMediaUsedOn(mediaUsages) {
|
|
219
|
+
if (!Array.isArray(mediaUsages))
|
|
220
|
+
return [];
|
|
221
|
+
const seen = new Set();
|
|
222
|
+
const out = [];
|
|
223
|
+
for (const usage of mediaUsages) {
|
|
224
|
+
const doc = usage?.document;
|
|
225
|
+
if (!doc || doc.deletedAt || seen.has(doc.id))
|
|
226
|
+
continue;
|
|
227
|
+
seen.add(doc.id);
|
|
228
|
+
out.push({
|
|
229
|
+
page: doc.title || '(untitled)',
|
|
230
|
+
path: mediaUsageEditPath(doc.collection, doc.id),
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
export const MEDIA_TITLE_STOPWORDS = new Set([
|
|
236
|
+
'a',
|
|
237
|
+
'an',
|
|
238
|
+
'the',
|
|
239
|
+
'of',
|
|
240
|
+
'and',
|
|
241
|
+
'or',
|
|
242
|
+
'to',
|
|
243
|
+
'in',
|
|
244
|
+
'on',
|
|
245
|
+
'for',
|
|
246
|
+
'with',
|
|
247
|
+
'at',
|
|
248
|
+
'by',
|
|
249
|
+
'from',
|
|
250
|
+
'is',
|
|
251
|
+
'are',
|
|
252
|
+
'as',
|
|
253
|
+
]);
|
|
254
|
+
/**
|
|
255
|
+
* Derive a concise, Title-Cased title from AI-generated alt text. The alt
|
|
256
|
+
* text is already a model output describing the image, so the title stays
|
|
257
|
+
* grounded in real content rather than the filename.
|
|
258
|
+
*/
|
|
259
|
+
export function deriveMediaTitleFromAlt(alt) {
|
|
260
|
+
if (!alt)
|
|
261
|
+
return '';
|
|
262
|
+
const firstClause = (alt.split(/[.;:\n]/)[0] ?? '').trim();
|
|
263
|
+
const titled = firstClause
|
|
264
|
+
.split(/\s+/)
|
|
265
|
+
.slice(0, 9)
|
|
266
|
+
.map((word, i) => {
|
|
267
|
+
const lower = word.toLowerCase();
|
|
268
|
+
if (i > 0 && MEDIA_TITLE_STOPWORDS.has(lower))
|
|
269
|
+
return lower;
|
|
270
|
+
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
271
|
+
})
|
|
272
|
+
.join(' ');
|
|
273
|
+
return titled.slice(0, 80).replace(/[\s,]+$/, '');
|
|
274
|
+
}
|
|
275
|
+
export function asRecord(value) {
|
|
276
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
277
|
+
? value
|
|
278
|
+
: {};
|
|
279
|
+
}
|
|
280
|
+
export function normalizeSubmission(submission) {
|
|
281
|
+
const data = asRecord(submission.data);
|
|
282
|
+
const attribution = asRecord(submission.attribution);
|
|
283
|
+
return {
|
|
284
|
+
...submission,
|
|
285
|
+
name: String(data.name ?? submission.name ?? ''),
|
|
286
|
+
email: String(data.email ?? submission.email ?? ''),
|
|
287
|
+
phone: data.phone ?? submission.phone,
|
|
288
|
+
message: String(data.message ?? submission.message ?? ''),
|
|
289
|
+
status: submission.status ?? 'new',
|
|
290
|
+
attribution: {
|
|
291
|
+
source: String(attribution.source ?? '(direct)'),
|
|
292
|
+
medium: String(attribution.medium ?? '(none)'),
|
|
293
|
+
campaign: String(attribution.campaign ?? ''),
|
|
294
|
+
term: String(attribution.term ?? ''),
|
|
295
|
+
content: String(attribution.content ?? ''),
|
|
296
|
+
landingPage: String(attribution.landingPage ?? ''),
|
|
297
|
+
referrer: String(attribution.referrer ?? ''),
|
|
298
|
+
deviceType: attribution.deviceType ?? 'Desktop',
|
|
299
|
+
clickIds: asRecord(attribution.clickIds),
|
|
300
|
+
capturedAt: attribution.capturedAt ?? submission.submittedAt ?? submission.createdAt ?? null,
|
|
301
|
+
},
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Map a forms-service domain error to an HTTP response. Returns `null` for
|
|
306
|
+
* unrecognised errors so the caller can fall through to `internalError`.
|
|
307
|
+
*/
|
|
308
|
+
export function mapFormError(err) {
|
|
309
|
+
if (err instanceof FormNotFoundError)
|
|
310
|
+
return errorResponse(err.message, 404);
|
|
311
|
+
if (err instanceof FormValidationError) {
|
|
312
|
+
return json({ error: err.message, code: 'INVALID_SCHEMA', details: err.errors }, 400);
|
|
313
|
+
}
|
|
314
|
+
if (err instanceof FormConflictError)
|
|
315
|
+
return errorResponse(err.message, 409);
|
|
316
|
+
if (err instanceof FormHasSubmissionsError) {
|
|
317
|
+
return json({ error: err.message, code: 'FORM_HAS_SUBMISSIONS', submissionCount: err.submissionCount }, 409);
|
|
318
|
+
}
|
|
319
|
+
if (err instanceof FormWebhookError)
|
|
320
|
+
return errorResponse(err.message, err.status);
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
export function parseFormsQuery(url) {
|
|
324
|
+
const sp = url.searchParams;
|
|
325
|
+
const status = sp.get('status');
|
|
326
|
+
const notify = sp.get('notifyEnabled');
|
|
327
|
+
return {
|
|
328
|
+
search: sp.get('search') ?? undefined,
|
|
329
|
+
status: status === 'active' || status === 'draft' || status === 'archived' ? status : undefined,
|
|
330
|
+
notifyEnabled: notify == null ? undefined : notify === 'true',
|
|
331
|
+
sortBy: sp.get('sortBy') ?? undefined,
|
|
332
|
+
sortDirection: sp.get('sortDirection') === 'asc'
|
|
333
|
+
? 'asc'
|
|
334
|
+
: sp.get('sortDirection') === 'desc'
|
|
335
|
+
? 'desc'
|
|
336
|
+
: undefined,
|
|
337
|
+
page: sp.get('page') ? Number(sp.get('page')) : undefined,
|
|
338
|
+
pageSize: sp.get('pageSize') ? Number(sp.get('pageSize')) : undefined,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
export function parseEntriesQuery(url) {
|
|
342
|
+
const sp = url.searchParams;
|
|
343
|
+
const spam = sp.get('spamStatus');
|
|
344
|
+
const boolParam = (key) => {
|
|
345
|
+
const v = sp.get(key);
|
|
346
|
+
return v == null ? undefined : v === 'true';
|
|
347
|
+
};
|
|
348
|
+
return {
|
|
349
|
+
search: sp.get('search') ?? undefined,
|
|
350
|
+
formId: sp.get('formId') ?? sp.get('form') ?? undefined,
|
|
351
|
+
unread: boolParam('unread'),
|
|
352
|
+
starred: boolParam('starred'),
|
|
353
|
+
archived: boolParam('archived'),
|
|
354
|
+
spamStatus: spam === 'clean' || spam === 'suspected' || spam === 'spam'
|
|
355
|
+
? spam
|
|
356
|
+
: undefined,
|
|
357
|
+
dateFrom: sp.get('dateFrom') ?? undefined,
|
|
358
|
+
dateTo: sp.get('dateTo') ?? undefined,
|
|
359
|
+
thisWeek: boolParam('thisWeek'),
|
|
360
|
+
sortBy: sp.get('sortBy') ?? undefined,
|
|
361
|
+
sortDirection: sp.get('sortDirection') === 'asc' ? 'asc' : undefined,
|
|
362
|
+
page: sp.get('page') ? Number(sp.get('page')) : undefined,
|
|
363
|
+
pageSize: sp.get('pageSize') ? Number(sp.get('pageSize')) : undefined,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
// ─── Public form submission helpers ─────────────────────────────────────────
|
|
367
|
+
/**
|
|
368
|
+
* Build CORS headers for the public form endpoints. When the form has no
|
|
369
|
+
* embed allowlist we reflect the requesting origin (open embedding). When an
|
|
370
|
+
* allowlist is set we only echo the origin if it matches, so a disallowed site
|
|
371
|
+
* cannot read the response. Browser-level CORS is complemented by a hard
|
|
372
|
+
* server-side origin check in the submit handler.
|
|
373
|
+
*/
|
|
374
|
+
export function formCorsHeaders(request, allowedDomains) {
|
|
375
|
+
const origin = request.headers.get('origin');
|
|
376
|
+
const headers = {
|
|
377
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
378
|
+
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With',
|
|
379
|
+
'Access-Control-Max-Age': '600',
|
|
380
|
+
Vary: 'Origin',
|
|
381
|
+
};
|
|
382
|
+
if (!allowedDomains || allowedDomains.length === 0) {
|
|
383
|
+
headers['Access-Control-Allow-Origin'] = origin || '*';
|
|
384
|
+
}
|
|
385
|
+
else if (origin && isOriginAllowed(origin, allowedDomains)) {
|
|
386
|
+
headers['Access-Control-Allow-Origin'] = origin;
|
|
387
|
+
}
|
|
388
|
+
return headers;
|
|
389
|
+
}
|
|
390
|
+
export function normalizeAllowedHost(domain) {
|
|
391
|
+
return domain
|
|
392
|
+
.trim()
|
|
393
|
+
.toLowerCase()
|
|
394
|
+
.replace(/^https?:\/\//, '')
|
|
395
|
+
.replace(/\/.*$/, '')
|
|
396
|
+
.replace(/^\*\./, '');
|
|
397
|
+
}
|
|
398
|
+
export function isOriginAllowed(origin, allowedDomains) {
|
|
399
|
+
let host;
|
|
400
|
+
try {
|
|
401
|
+
host = new URL(origin).hostname.toLowerCase();
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
return allowedDomains
|
|
407
|
+
.map(normalizeAllowedHost)
|
|
408
|
+
.some((a) => a !== '' && (host === a || host.endsWith(`.${a}`)));
|
|
409
|
+
}
|
|
410
|
+
export function jsonWithHeaders(data, status, extra) {
|
|
411
|
+
return new Response(JSON.stringify(data), {
|
|
412
|
+
status,
|
|
413
|
+
headers: { ...SECURITY_HEADERS, ...extra },
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Parse a public submission request into field values, files, and metadata.
|
|
418
|
+
* Supports both `application/json` (no files) and `multipart/form-data`
|
|
419
|
+
* (files + fields). Unknown/oversized bodies are rejected by the caller's
|
|
420
|
+
* Content-Length gate before this runs.
|
|
421
|
+
*/
|
|
422
|
+
export async function parseSubmissionRequest(request) {
|
|
423
|
+
const contentType = request.headers.get('content-type') ?? '';
|
|
424
|
+
if (contentType.includes('multipart/form-data')) {
|
|
425
|
+
const form = await request.formData();
|
|
426
|
+
const values = {};
|
|
427
|
+
const files = [];
|
|
428
|
+
let attribution = null;
|
|
429
|
+
let elapsedMs = null;
|
|
430
|
+
let pageUrl = null;
|
|
431
|
+
let captchaToken = '';
|
|
432
|
+
for (const [key, value] of form.entries()) {
|
|
433
|
+
if (typeof value === 'object' && value !== null && 'arrayBuffer' in value) {
|
|
434
|
+
const file = value;
|
|
435
|
+
if (file.size === 0 && !file.name)
|
|
436
|
+
continue;
|
|
437
|
+
const buffer = Buffer.from(await file.arrayBuffer());
|
|
438
|
+
files.push({
|
|
439
|
+
fieldKey: key,
|
|
440
|
+
fileName: file.name || 'file',
|
|
441
|
+
mimeType: file.type || 'application/octet-stream',
|
|
442
|
+
size: buffer.byteLength,
|
|
443
|
+
buffer,
|
|
444
|
+
});
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
const str = String(value);
|
|
448
|
+
if (key === '__attribution') {
|
|
449
|
+
attribution = safeJsonObject(str);
|
|
450
|
+
}
|
|
451
|
+
else if (key === '__elapsedMs') {
|
|
452
|
+
const n = Number(str);
|
|
453
|
+
elapsedMs = Number.isFinite(n) ? n : null;
|
|
454
|
+
}
|
|
455
|
+
else if (key === '__pageUrl') {
|
|
456
|
+
pageUrl = str || null;
|
|
457
|
+
}
|
|
458
|
+
else if (key === '__captchaToken' || key === 'captchaToken') {
|
|
459
|
+
captchaToken = str;
|
|
460
|
+
}
|
|
461
|
+
else if (Object.prototype.hasOwnProperty.call(values, key)) {
|
|
462
|
+
// Repeated keys (e.g. multi-checkbox) collapse into an array.
|
|
463
|
+
const existing = values[key];
|
|
464
|
+
values[key] = Array.isArray(existing) ? [...existing, str] : [existing, str];
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
values[key] = str;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return { values, files, meta: { attribution, elapsedMs, pageUrl, captchaToken } };
|
|
471
|
+
}
|
|
472
|
+
// JSON body.
|
|
473
|
+
const body = (await request.json().catch(() => null));
|
|
474
|
+
if (!body)
|
|
475
|
+
return null;
|
|
476
|
+
const values = body.fields && typeof body.fields === 'object' && !Array.isArray(body.fields)
|
|
477
|
+
? body.fields
|
|
478
|
+
: null;
|
|
479
|
+
if (!values)
|
|
480
|
+
return null;
|
|
481
|
+
return {
|
|
482
|
+
values,
|
|
483
|
+
files: [],
|
|
484
|
+
meta: {
|
|
485
|
+
attribution: safeJsonObject(body.attribution),
|
|
486
|
+
elapsedMs: typeof body.elapsedMs === 'number' && Number.isFinite(body.elapsedMs)
|
|
487
|
+
? body.elapsedMs
|
|
488
|
+
: null,
|
|
489
|
+
pageUrl: typeof body.pageUrl === 'string' ? body.pageUrl : null,
|
|
490
|
+
captchaToken: typeof body.captchaToken === 'string' ? body.captchaToken : '',
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
export function safeJsonObject(value) {
|
|
495
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
496
|
+
return value;
|
|
497
|
+
}
|
|
498
|
+
if (typeof value === 'string' && value.trim()) {
|
|
499
|
+
try {
|
|
500
|
+
const parsed = JSON.parse(value);
|
|
501
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
502
|
+
return parsed;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
catch {
|
|
506
|
+
/* ignore malformed attribution blob */
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Shared public-submission handler used by both the slug-based public route and
|
|
513
|
+
* the legacy by-id route. Enforces per-IP+form rate limiting, embed-origin
|
|
514
|
+
* allowlisting, optional CAPTCHA, file validation, then runs the core
|
|
515
|
+
* submission pipeline. Always responds with CORS headers so embedded forms can
|
|
516
|
+
* read the result.
|
|
517
|
+
*/
|
|
518
|
+
export async function submitToForm(request, form) {
|
|
519
|
+
const allowedDomains = form.embedSettings?.allowedDomains;
|
|
520
|
+
const cors = formCorsHeaders(request, allowedDomains);
|
|
521
|
+
const ip = getClientIp(request);
|
|
522
|
+
const rlKey = isResolvedIp(ip) ? `formsubmit:${ip}:${form.id}` : `formsubmit:_unknown:${form.id}`;
|
|
523
|
+
if (!(await checkRateLimitAsync(formLimiterGlobal, rlKey))) {
|
|
524
|
+
return jsonWithHeaders({ error: 'Too many submissions. Please try again later.' }, 429, cors);
|
|
525
|
+
}
|
|
526
|
+
// Hard server-side origin check when an embed allowlist is configured —
|
|
527
|
+
// browser CORS alone does not prevent a non-browser client from posting.
|
|
528
|
+
if (allowedDomains && allowedDomains.length > 0) {
|
|
529
|
+
const origin = request.headers.get('origin');
|
|
530
|
+
if (origin && !isOriginAllowed(origin, allowedDomains)) {
|
|
531
|
+
return jsonWithHeaders({ error: 'This form cannot be submitted from this origin.' }, 403, cors);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const parsed = await parseSubmissionRequest(request);
|
|
535
|
+
if (!parsed) {
|
|
536
|
+
return jsonWithHeaders({ error: 'Invalid or missing submission body.' }, 400, cors);
|
|
537
|
+
}
|
|
538
|
+
const captchaConfig = getCaptchaConfig();
|
|
539
|
+
if (captchaConfig.provider !== 'none') {
|
|
540
|
+
const result = await verifyCaptcha(parsed.meta.captchaToken, captchaConfig, isResolvedIp(ip) ? ip : undefined);
|
|
541
|
+
if (!result.success) {
|
|
542
|
+
return jsonWithHeaders({ error: 'CAPTCHA verification failed. Please try again.' }, 403, cors);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if (parsed.files.length > 0) {
|
|
546
|
+
const fileCfg = getActuateConfig()?.forms?.fileUpload;
|
|
547
|
+
if (fileCfg?.enabled === false) {
|
|
548
|
+
return jsonWithHeaders({ error: 'File uploads are not enabled for this site.' }, 400, cors);
|
|
549
|
+
}
|
|
550
|
+
const { fields } = await resolveSubmissionFields(form);
|
|
551
|
+
const fileCheck = validateSubmissionFiles(fields, parsed.files, {
|
|
552
|
+
maxSizeBytes: fileCfg?.maxSizeMB ? fileCfg.maxSizeMB * 1024 * 1024 : DEFAULT_MAX_FILE_BYTES,
|
|
553
|
+
allowedMimeTypes: fileCfg?.allowedMimeTypes ?? FORM_UPLOAD_ALLOWED_MIME_TYPES,
|
|
554
|
+
});
|
|
555
|
+
if (!fileCheck.ok) {
|
|
556
|
+
return jsonWithHeaders({ error: 'File validation failed.', code: 'INVALID_FILES', details: fileCheck.errors }, 422, cors);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
const ctx = {
|
|
560
|
+
values: parsed.values,
|
|
561
|
+
files: parsed.files,
|
|
562
|
+
ip,
|
|
563
|
+
userAgent: request.headers.get('user-agent'),
|
|
564
|
+
referrer: request.headers.get('referer'),
|
|
565
|
+
origin: request.headers.get('origin'),
|
|
566
|
+
pageUrl: parsed.meta.pageUrl,
|
|
567
|
+
attribution: parsed.meta.attribution,
|
|
568
|
+
elapsedMs: parsed.meta.elapsedMs,
|
|
569
|
+
};
|
|
570
|
+
try {
|
|
571
|
+
const result = await processSubmission(form, ctx);
|
|
572
|
+
return jsonWithHeaders({
|
|
573
|
+
data: {
|
|
574
|
+
success: true,
|
|
575
|
+
submissionId: result.submissionId,
|
|
576
|
+
entryNumber: result.entryNumber,
|
|
577
|
+
confirmation: result.confirmation,
|
|
578
|
+
},
|
|
579
|
+
}, 201, cors);
|
|
580
|
+
}
|
|
581
|
+
catch (err) {
|
|
582
|
+
if (err instanceof SubmissionValidationError) {
|
|
583
|
+
return jsonWithHeaders({ error: 'Validation failed.', code: 'VALIDATION_ERROR', details: err.fieldErrors }, 422, cors);
|
|
584
|
+
}
|
|
585
|
+
return internalError(err);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
export function normalizeRedirect(redirect) {
|
|
589
|
+
return {
|
|
590
|
+
...redirect,
|
|
591
|
+
from: redirect.from ?? redirect.source ?? '',
|
|
592
|
+
to: redirect.to ?? redirect.destination ?? '',
|
|
593
|
+
type: String(redirect.type ?? redirect.statusCode ?? 301),
|
|
594
|
+
hits: Number(redirect.hits ?? 0),
|
|
595
|
+
active: redirect.active ?? true,
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
export function normalizeSeoPage(page) {
|
|
599
|
+
const data = asRecord(page.data);
|
|
600
|
+
const structuredData = asRecord(page.structuredData);
|
|
601
|
+
const issueValue = structuredData.issues ?? data.issues;
|
|
602
|
+
const issueCount = Array.isArray(issueValue) ? issueValue.length : Number(issueValue ?? 0);
|
|
603
|
+
const slug = String(data.slug ?? page.slug ?? page.id ?? '');
|
|
604
|
+
return {
|
|
605
|
+
...page,
|
|
606
|
+
url: data.url ?? (slug === 'home' ? '/' : `/${slug}`),
|
|
607
|
+
title: data.title ?? page.title ?? 'Untitled',
|
|
608
|
+
score: Number(structuredData.score ?? data.score ?? 0),
|
|
609
|
+
issues: issueCount,
|
|
610
|
+
metaTitle: data.metaTitle ?? '',
|
|
611
|
+
metaDescription: data.metaDescription ?? '',
|
|
612
|
+
canonical: data.canonical ?? '',
|
|
613
|
+
schemaType: data.schemaType ?? structuredData.schemaType ?? '',
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
export function hasModel(d, name) {
|
|
617
|
+
try {
|
|
618
|
+
return d[name] && typeof d[name].findMany === 'function';
|
|
619
|
+
}
|
|
620
|
+
catch {
|
|
621
|
+
return false;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
/** Format a number compactly, e.g. 8400 -> "8.4K", 1_200_000 -> "1.2M". */
|
|
625
|
+
export function formatCompactNumber(n) {
|
|
626
|
+
if (!Number.isFinite(n))
|
|
627
|
+
return '0';
|
|
628
|
+
if (Math.abs(n) >= 1_000_000)
|
|
629
|
+
return `${(n / 1_000_000).toFixed(1)}M`;
|
|
630
|
+
if (Math.abs(n) >= 1_000)
|
|
631
|
+
return `${(n / 1_000).toFixed(1)}K`;
|
|
632
|
+
return String(Math.round(n));
|
|
633
|
+
}
|
|
634
|
+
/** Minimal CSV line parser supporting double-quoted fields with escaped quotes. */
|
|
635
|
+
export function parseCsvLine(line) {
|
|
636
|
+
const out = [];
|
|
637
|
+
let cur = '';
|
|
638
|
+
let inQuotes = false;
|
|
639
|
+
for (let i = 0; i < line.length; i++) {
|
|
640
|
+
const ch = line[i];
|
|
641
|
+
if (inQuotes) {
|
|
642
|
+
if (ch === '"') {
|
|
643
|
+
if (line[i + 1] === '"') {
|
|
644
|
+
cur += '"';
|
|
645
|
+
i++;
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
inQuotes = false;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
else {
|
|
652
|
+
cur += ch;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
else if (ch === '"') {
|
|
656
|
+
inQuotes = true;
|
|
657
|
+
}
|
|
658
|
+
else if (ch === ',') {
|
|
659
|
+
out.push(cur);
|
|
660
|
+
cur = '';
|
|
661
|
+
}
|
|
662
|
+
else {
|
|
663
|
+
cur += ch;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
out.push(cur);
|
|
667
|
+
return out;
|
|
668
|
+
}
|
|
669
|
+
export function modelNotAvailable(name) {
|
|
670
|
+
return errorResponse(`The "${name}" model is not available in your Prisma schema. ` +
|
|
671
|
+
'Run `actuate db:init` for new schemas, or carefully update the existing Actuate block, create/apply a Prisma migration, then regenerate Prisma Client. ' +
|
|
672
|
+
'See https://actuatecms.dev/docs/database-setup for required models.', 501);
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* XML-escape a value for safe inclusion in sitemap content. Sitemaps reject
|
|
676
|
+
* unescaped ampersands and angle brackets; URLs frequently contain `&` query
|
|
677
|
+
* separators, so this is non-optional.
|
|
678
|
+
*/
|
|
679
|
+
export function escapeXml(value) {
|
|
680
|
+
return value
|
|
681
|
+
.replace(/&/g, '&')
|
|
682
|
+
.replace(/</g, '<')
|
|
683
|
+
.replace(/>/g, '>')
|
|
684
|
+
.replace(/"/g, '"')
|
|
685
|
+
.replace(/'/g, ''');
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* URLs per sitemap file. The sitemaps protocol caps a single file at 50,000
|
|
689
|
+
* URLs; we use a margin below that so the optional archive URL on page 0 can
|
|
690
|
+
* never push a file over the limit. Collections larger than this are split
|
|
691
|
+
* across multiple `?page=N` files referenced from the sitemap index.
|
|
692
|
+
*/
|
|
693
|
+
export const SITEMAP_PAGE_SIZE = 45000;
|
|
694
|
+
/**
|
|
695
|
+
* Renders a 1200x630 SVG suitable for og:image. We don't pull in Satori/resvg
|
|
696
|
+
* because most integrators don't need PNG — major crawlers (Facebook, Twitter,
|
|
697
|
+
* LinkedIn, Slack, Discord) handle image/svg+xml correctly. Sites that
|
|
698
|
+
* specifically need PNG can override with their own /og endpoint via
|
|
699
|
+
* @vercel/og and point `seo.defaultOgImage` at it.
|
|
700
|
+
*/
|
|
701
|
+
export function renderOgSvg(opts) {
|
|
702
|
+
const { title, description, siteName, bg, fg, muted } = opts;
|
|
703
|
+
// Naive line wrapping at ~22 chars (large font). Good enough for an OG card;
|
|
704
|
+
// anything longer than ~3 lines gets truncated with an ellipsis.
|
|
705
|
+
const wrap = (text, maxChars, maxLines) => {
|
|
706
|
+
const words = text.split(/\s+/);
|
|
707
|
+
const lines = [];
|
|
708
|
+
let current = '';
|
|
709
|
+
for (const w of words) {
|
|
710
|
+
if (lines.length >= maxLines)
|
|
711
|
+
break;
|
|
712
|
+
const next = current ? `${current} ${w}` : w;
|
|
713
|
+
if (next.length > maxChars) {
|
|
714
|
+
if (current)
|
|
715
|
+
lines.push(current);
|
|
716
|
+
current = w;
|
|
717
|
+
if (lines.length === maxLines - 1 && words.indexOf(w) < words.length - 1) {
|
|
718
|
+
lines.push(current.length > maxChars ? current.slice(0, maxChars - 1) + '…' : current + '…');
|
|
719
|
+
current = '';
|
|
720
|
+
break;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
current = next;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (current && lines.length < maxLines)
|
|
728
|
+
lines.push(current);
|
|
729
|
+
return lines;
|
|
730
|
+
};
|
|
731
|
+
const escapeSvg = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
732
|
+
const titleLines = wrap(title, 28, 3);
|
|
733
|
+
const descLines = description ? wrap(description, 60, 2) : [];
|
|
734
|
+
const titleEls = titleLines
|
|
735
|
+
.map((line, i) => `<tspan x="60" dy="${i === 0 ? 0 : 78}">${escapeSvg(line)}</tspan>`)
|
|
736
|
+
.join('');
|
|
737
|
+
const descEls = descLines
|
|
738
|
+
.map((line, i) => `<tspan x="60" dy="${i === 0 ? 0 : 36}">${escapeSvg(line)}</tspan>`)
|
|
739
|
+
.join('');
|
|
740
|
+
// Layout: site name top-left, title bottom-left, description below title.
|
|
741
|
+
// Coordinates are roughly aligned to the 1200x630 spec used by every major
|
|
742
|
+
// social platform.
|
|
743
|
+
const titleY = descLines.length > 0 ? 360 : 420;
|
|
744
|
+
const descY = titleY + 80 * titleLines.length;
|
|
745
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
746
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630">
|
|
747
|
+
<rect width="1200" height="630" fill="${bg}"/>
|
|
748
|
+
${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>` : ''}
|
|
749
|
+
<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>
|
|
750
|
+
${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>` : ''}
|
|
751
|
+
<rect x="60" y="560" width="60" height="6" fill="${fg}" rx="3"/>
|
|
752
|
+
</svg>`;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Log unexpected query failures from the `safe*` wrappers.
|
|
756
|
+
*
|
|
757
|
+
* The wrappers exist so an optional Prisma model (e.g. a delegate
|
|
758
|
+
* that older schemas don't define) doesn't blow up the route — they
|
|
759
|
+
* return the empty value (`0` / `[]`) when the model isn't available.
|
|
760
|
+
* That defensive contract historically swallowed *every* error,
|
|
761
|
+
* including Prisma's "Unknown argument" rejections that flag a real
|
|
762
|
+
* application bug (see the `relationLoadStrategy` regression
|
|
763
|
+
* discovered while landing Phase 5.5 #5). Logging the underlying
|
|
764
|
+
* error preserves the defensive return semantics while making the
|
|
765
|
+
* actual class of bug visible in Vercel + Sentry logs.
|
|
766
|
+
*
|
|
767
|
+
* Kept private to this module — it's a logging contract, not a
|
|
768
|
+
* public API.
|
|
769
|
+
*/
|
|
770
|
+
export function logSafeQueryFailure(scope, err) {
|
|
771
|
+
// Defensive: never throw from a logger that wraps `safe*` queries
|
|
772
|
+
// — the whole point of those wrappers is to keep the request hot
|
|
773
|
+
// path alive.
|
|
774
|
+
try {
|
|
775
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
776
|
+
console.warn(`[actuate][cms-api] ${scope} query failed: ${message}`);
|
|
777
|
+
}
|
|
778
|
+
catch {
|
|
779
|
+
/* swallow */
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
export async function safeCount(model, where) {
|
|
783
|
+
if (!model || typeof model !== 'object')
|
|
784
|
+
return 0;
|
|
785
|
+
let countFn;
|
|
786
|
+
try {
|
|
787
|
+
countFn = model.count;
|
|
788
|
+
}
|
|
789
|
+
catch {
|
|
790
|
+
return 0;
|
|
791
|
+
}
|
|
792
|
+
if (typeof countFn !== 'function')
|
|
793
|
+
return 0;
|
|
794
|
+
try {
|
|
795
|
+
return await countFn.call(model, where ? { where } : undefined);
|
|
796
|
+
}
|
|
797
|
+
catch (err) {
|
|
798
|
+
logSafeQueryFailure('safeCount', err);
|
|
799
|
+
return 0;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
export async function safeFindMany(model, args) {
|
|
803
|
+
if (!model || typeof model !== 'object')
|
|
804
|
+
return [];
|
|
805
|
+
let findManyFn;
|
|
806
|
+
try {
|
|
807
|
+
findManyFn = model.findMany;
|
|
808
|
+
}
|
|
809
|
+
catch {
|
|
810
|
+
return [];
|
|
811
|
+
}
|
|
812
|
+
if (typeof findManyFn !== 'function')
|
|
813
|
+
return [];
|
|
814
|
+
try {
|
|
815
|
+
return await findManyFn.call(model, args);
|
|
816
|
+
}
|
|
817
|
+
catch (err) {
|
|
818
|
+
logSafeQueryFailure('safeFindMany', err);
|
|
819
|
+
return [];
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
export function isAllowedStorageUrl(url) {
|
|
823
|
+
try {
|
|
824
|
+
const parsed = new URL(url);
|
|
825
|
+
if (!['https:', 'http:'].includes(parsed.protocol))
|
|
826
|
+
return false;
|
|
827
|
+
const h = parsed.hostname;
|
|
828
|
+
if (h === 'localhost' || h === '127.0.0.1' || h === '::1')
|
|
829
|
+
return false;
|
|
830
|
+
if (h.startsWith('10.') || h.startsWith('192.168.'))
|
|
831
|
+
return false;
|
|
832
|
+
if (/^172\.(1[6-9]|2\d|3[01])\./.test(h))
|
|
833
|
+
return false;
|
|
834
|
+
if (h === '169.254.169.254')
|
|
835
|
+
return false;
|
|
836
|
+
if (h.endsWith('.internal') || h.endsWith('.local'))
|
|
837
|
+
return false;
|
|
838
|
+
return true;
|
|
839
|
+
}
|
|
840
|
+
catch {
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
/** Max image size (bytes) we'll pull into memory for vision analysis. */
|
|
845
|
+
export const MAX_VISION_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
846
|
+
/**
|
|
847
|
+
* Fetch image bytes for multimodal (vision) analysis through {@link safeFetch}
|
|
848
|
+
* (SSRF-safe: re-validates the host, DNS-resolves to defeat rebinding, no
|
|
849
|
+
* redirects). Returns `null` on any failure (non-image, oversize, blocked,
|
|
850
|
+
* network) so the caller transparently falls back to a context-only heuristic.
|
|
851
|
+
*/
|
|
852
|
+
export async function fetchImageForVision(url, knownMimeType) {
|
|
853
|
+
try {
|
|
854
|
+
const resp = await safeFetch(url, { method: 'GET', timeoutMs: 5000 });
|
|
855
|
+
if (!resp.ok)
|
|
856
|
+
return null;
|
|
857
|
+
const contentType = ((resp.headers.get('content-type') ?? knownMimeType ?? '').split(';')[0] ?? '').trim();
|
|
858
|
+
if (!contentType.startsWith('image/'))
|
|
859
|
+
return null;
|
|
860
|
+
const declaredLength = Number(resp.headers.get('content-length') ?? '0');
|
|
861
|
+
if (declaredLength > MAX_VISION_IMAGE_BYTES)
|
|
862
|
+
return null;
|
|
863
|
+
const buffer = Buffer.from(await resp.arrayBuffer());
|
|
864
|
+
if (buffer.byteLength === 0 || buffer.byteLength > MAX_VISION_IMAGE_BYTES)
|
|
865
|
+
return null;
|
|
866
|
+
return { base64: buffer.toString('base64'), mimeType: contentType };
|
|
867
|
+
}
|
|
868
|
+
catch {
|
|
869
|
+
return null;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
export const ALLOWED_SORT_FIELDS = new Set([
|
|
873
|
+
'createdAt',
|
|
874
|
+
'updatedAt',
|
|
875
|
+
'publishedAt',
|
|
876
|
+
'status',
|
|
877
|
+
'collection',
|
|
878
|
+
]);
|
|
879
|
+
let _secretMissing = false;
|
|
880
|
+
let _secretWarningLogged = false;
|
|
881
|
+
export function getSessionSecret() {
|
|
882
|
+
const secret = process.env.CMS_SECRET ?? process.env.CMS_SESSION_SECRET ?? getActuateConfig()?.secret;
|
|
883
|
+
if (!secret) {
|
|
884
|
+
_secretMissing = true;
|
|
885
|
+
if (!_secretWarningLogged) {
|
|
886
|
+
_secretWarningLogged = true;
|
|
887
|
+
console.error('[Actuate CMS] Missing CMS secret. Set the CMS_SECRET environment variable (min 32 characters) ' +
|
|
888
|
+
'or pass `secret` in your actuate.config.ts. ' +
|
|
889
|
+
"Generate one with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\" " +
|
|
890
|
+
'-- All authenticated API routes will return 503 until this is configured.');
|
|
891
|
+
}
|
|
892
|
+
throw new Error('CMS secret not configured');
|
|
893
|
+
}
|
|
894
|
+
if (secret.length < 32) {
|
|
895
|
+
throw new Error('[Actuate CMS] CMS secret must be at least 32 characters (got ' +
|
|
896
|
+
secret.length +
|
|
897
|
+
'). ' +
|
|
898
|
+
"Generate a secure value with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"");
|
|
899
|
+
}
|
|
900
|
+
_secretMissing = false;
|
|
901
|
+
return secret;
|
|
902
|
+
}
|
|
903
|
+
export function isSecretMissing() {
|
|
904
|
+
if (_secretMissing)
|
|
905
|
+
return true;
|
|
906
|
+
try {
|
|
907
|
+
getSessionSecret();
|
|
908
|
+
return false;
|
|
909
|
+
}
|
|
910
|
+
catch {
|
|
911
|
+
return true;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
export async function extractSession(request) {
|
|
915
|
+
if (isSecretMissing())
|
|
916
|
+
return null;
|
|
917
|
+
let token;
|
|
918
|
+
const authHeader = request.headers.get('Authorization');
|
|
919
|
+
if (authHeader?.startsWith('Bearer ')) {
|
|
920
|
+
token = authHeader.slice(7);
|
|
921
|
+
}
|
|
922
|
+
if (!token) {
|
|
923
|
+
const cookieHeader = request.headers.get('cookie') ?? '';
|
|
924
|
+
const cookies = parseCookieHeader(cookieHeader);
|
|
925
|
+
token = cookies['actuate_session'];
|
|
926
|
+
}
|
|
927
|
+
if (!token)
|
|
928
|
+
return null;
|
|
929
|
+
// API key path. Keys are recognized by the `act_sk_` prefix and looked up
|
|
930
|
+
// by SHA-256 hash. We never JWT-verify these tokens — they are opaque
|
|
931
|
+
// random secrets stored as hashes in `actuate_api_keys`.
|
|
932
|
+
if (looksLikeApiKey(token)) {
|
|
933
|
+
try {
|
|
934
|
+
const d = getDB();
|
|
935
|
+
if (!hasModel(d, 'apiKey'))
|
|
936
|
+
return null;
|
|
937
|
+
const hash = await hashApiKey(token);
|
|
938
|
+
const apiKey = await d.apiKey.findUnique({ where: { keyHash: hash } });
|
|
939
|
+
if (!apiKey)
|
|
940
|
+
return null;
|
|
941
|
+
if (apiKey.revokedAt)
|
|
942
|
+
return null;
|
|
943
|
+
if (apiKey.expiresAt && new Date(apiKey.expiresAt).getTime() < Date.now())
|
|
944
|
+
return null;
|
|
945
|
+
const ipRestrictions = Array.isArray(apiKey.ipRestrictions)
|
|
946
|
+
? apiKey.ipRestrictions
|
|
947
|
+
: apiKey.ipRestrictions
|
|
948
|
+
? (apiKey.ipRestrictions.allow ?? null)
|
|
949
|
+
: null;
|
|
950
|
+
if (ipRestrictions && ipRestrictions.length > 0) {
|
|
951
|
+
const ip = getClientIp(request);
|
|
952
|
+
if (!validateApiKeyIp(ipRestrictions, ip))
|
|
953
|
+
return null;
|
|
954
|
+
}
|
|
955
|
+
const scopes = apiKey.scopes ?? {};
|
|
956
|
+
// Fire-and-forget lastUsedAt update; never block the request on it.
|
|
957
|
+
void d.apiKey
|
|
958
|
+
.update({ where: { id: apiKey.id }, data: { lastUsedAt: new Date() } })
|
|
959
|
+
.catch(() => { });
|
|
960
|
+
return {
|
|
961
|
+
userId: apiKey.userId,
|
|
962
|
+
role: scopes.admin ? 'ADMIN' : 'API_KEY',
|
|
963
|
+
sessionId: apiKey.id,
|
|
964
|
+
apiKey: { id: apiKey.id, scopes },
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
catch {
|
|
968
|
+
return null;
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
// Session JWT path.
|
|
972
|
+
try {
|
|
973
|
+
const payload = await verifySession(token, { secret: getSessionSecret() });
|
|
974
|
+
const d = getDB();
|
|
975
|
+
if (hasModel(d, 'session')) {
|
|
976
|
+
const dbSession = await d.session.findUnique({
|
|
977
|
+
where: { id: payload.sessionId },
|
|
978
|
+
select: { revokedAt: true },
|
|
979
|
+
});
|
|
980
|
+
if (!dbSession || dbSession.revokedAt)
|
|
981
|
+
return null;
|
|
982
|
+
}
|
|
983
|
+
return payload;
|
|
984
|
+
}
|
|
985
|
+
catch {
|
|
986
|
+
return null;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
export function parseCookieHeader(cookieHeader) {
|
|
990
|
+
const cookies = {};
|
|
991
|
+
for (const pair of cookieHeader.split(';')) {
|
|
992
|
+
const [key, ...rest] = pair.split('=');
|
|
993
|
+
if (key) {
|
|
994
|
+
cookies[key.trim()] = rest.join('=').trim();
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
return cookies;
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Verify a password (or "current password") posted in the X-Reauth-Password
|
|
1001
|
+
* header against the authenticated user. Returns an error Response when the
|
|
1002
|
+
* header is missing or the password is wrong; returns null on success.
|
|
1003
|
+
*
|
|
1004
|
+
* Use this for high-impact account changes (TOTP enable/disable, role change,
|
|
1005
|
+
* delete user, etc.) so a stolen session alone cannot perform them.
|
|
1006
|
+
*/
|
|
1007
|
+
export async function requirePasswordReauth(request, userId) {
|
|
1008
|
+
const password = request.headers.get('x-reauth-password');
|
|
1009
|
+
if (!password) {
|
|
1010
|
+
return new Response(JSON.stringify({
|
|
1011
|
+
error: 'Re-authentication required for this action.',
|
|
1012
|
+
code: 'REAUTH_REQUIRED',
|
|
1013
|
+
method: 'password',
|
|
1014
|
+
}), { status: 401, headers: { ...SECURITY_HEADERS } });
|
|
1015
|
+
}
|
|
1016
|
+
try {
|
|
1017
|
+
const { getDB } = await import('../db.js');
|
|
1018
|
+
const ok = await verifyReauth(userId, password, 'password', getDB());
|
|
1019
|
+
if (!ok) {
|
|
1020
|
+
return errorResponse('Re-authentication failed.', 401);
|
|
1021
|
+
}
|
|
1022
|
+
return null;
|
|
1023
|
+
}
|
|
1024
|
+
catch (err) {
|
|
1025
|
+
console.error('[actuate][reauth] verify failed:', err instanceof Error ? err.message : err);
|
|
1026
|
+
return errorResponse('Re-authentication failed.', 401);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
export async function requireAuth(request) {
|
|
1030
|
+
if (isSecretMissing()) {
|
|
1031
|
+
return {
|
|
1032
|
+
error: json({
|
|
1033
|
+
error: 'CMS secret not configured. Set CMS_SECRET or CMS_SESSION_SECRET environment variable (min 32 characters).',
|
|
1034
|
+
code: 'MISSING_SECRET',
|
|
1035
|
+
}, 503),
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
const session = await extractSession(request);
|
|
1039
|
+
if (!session) {
|
|
1040
|
+
return { error: errorResponse('Unauthorized', 401) };
|
|
1041
|
+
}
|
|
1042
|
+
return { session };
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Check that the request's auth context permits `action` on `collection`.
|
|
1046
|
+
* - Session-authenticated requests fall through to `requireRole` semantics:
|
|
1047
|
+
* write actions require WRITE_ROLES.
|
|
1048
|
+
* - API-key-authenticated requests must have an explicit scope match.
|
|
1049
|
+
*/
|
|
1050
|
+
export function requireCollectionScope(session, collection, action) {
|
|
1051
|
+
if (session.apiKey) {
|
|
1052
|
+
if (!validateApiKeyScope(session.apiKey.scopes, collection, action)) {
|
|
1053
|
+
return errorResponse(`API key does not have permission to ${action} on collection "${collection}"`, 403);
|
|
1054
|
+
}
|
|
1055
|
+
return null;
|
|
1056
|
+
}
|
|
1057
|
+
if (action === 'read')
|
|
1058
|
+
return null;
|
|
1059
|
+
return requireRole(session.role, WRITE_ROLES);
|
|
1060
|
+
}
|
|
1061
|
+
export function requireGlobalScope(session, slug) {
|
|
1062
|
+
if (session.apiKey) {
|
|
1063
|
+
if (!validateApiKeyGlobalScope(session.apiKey.scopes, slug)) {
|
|
1064
|
+
return errorResponse(`API key does not have permission for global "${slug}"`, 403);
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
return null;
|
|
1068
|
+
}
|
|
1069
|
+
export function requireMediaScope(session) {
|
|
1070
|
+
if (session.apiKey) {
|
|
1071
|
+
if (!validateApiKeyMediaScope(session.apiKey.scopes)) {
|
|
1072
|
+
return errorResponse('API key does not have media scope', 403);
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return null;
|
|
1076
|
+
}
|
|
1077
|
+
export function requirePageBuilderScope(session) {
|
|
1078
|
+
if (session.apiKey) {
|
|
1079
|
+
if (!validateApiKeyPageBuilderScope(session.apiKey.scopes)) {
|
|
1080
|
+
return errorResponse('API key does not have pageBuilder scope', 403);
|
|
1081
|
+
}
|
|
1082
|
+
return null;
|
|
1083
|
+
}
|
|
1084
|
+
return requireRole(session.role, ADMIN_ROLES);
|
|
1085
|
+
}
|
|
1086
|
+
export function requireAdminScope(session) {
|
|
1087
|
+
if (session.apiKey) {
|
|
1088
|
+
if (!session.apiKey.scopes.admin) {
|
|
1089
|
+
return errorResponse('API key does not have admin scope', 403);
|
|
1090
|
+
}
|
|
1091
|
+
return null;
|
|
1092
|
+
}
|
|
1093
|
+
return requireRole(session.role, ADMIN_ROLES);
|
|
1094
|
+
}
|
|
1095
|
+
export function buildActionContext(session, db, locale) {
|
|
1096
|
+
return {
|
|
1097
|
+
userId: session.userId,
|
|
1098
|
+
role: session.role,
|
|
1099
|
+
locale,
|
|
1100
|
+
db,
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
export const WRITE_ROLES = new Set(['OWNER', 'ADMIN', 'EDITOR', 'AUTHOR']);
|
|
1104
|
+
export const ADMIN_ROLES = new Set(['OWNER', 'ADMIN']);
|
|
1105
|
+
export function requireRole(role, allowedRoles) {
|
|
1106
|
+
if (!allowedRoles.has(role)) {
|
|
1107
|
+
return errorResponse('Insufficient permissions', 403);
|
|
1108
|
+
}
|
|
1109
|
+
return null;
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Build the shared {@link TeamOptions} for the Users endpoints from config +
|
|
1113
|
+
* session: the workspace domain (for external-domain detection) and the seat
|
|
1114
|
+
* cap (config-provided; null = unlimited until billing exists).
|
|
1115
|
+
*/
|
|
1116
|
+
export function teamOptionsFor(session) {
|
|
1117
|
+
const cfg = getActuateConfig();
|
|
1118
|
+
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ??
|
|
1119
|
+
cfg?.seo?.siteUrl ??
|
|
1120
|
+
null;
|
|
1121
|
+
const seatLimit = cfg?.users?.seatLimit ??
|
|
1122
|
+
cfg?.admin?.seatLimit ??
|
|
1123
|
+
null;
|
|
1124
|
+
return {
|
|
1125
|
+
workspaceDomain: workspaceDomainFromUrl(siteUrl),
|
|
1126
|
+
seatLimit,
|
|
1127
|
+
currentUserId: session.userId,
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
/** Whether the configured email provider can actually send mail. */
|
|
1131
|
+
export function isEmailConfigured() {
|
|
1132
|
+
const cfg = getActuateConfig();
|
|
1133
|
+
if (cfg?.platform?.email)
|
|
1134
|
+
return true;
|
|
1135
|
+
return !!resolveEmailSender();
|
|
1136
|
+
}
|
|
1137
|
+
export const loginLimiter = createRateLimiter({ maxRequests: 5, windowMs: 15 * 60 * 1000 });
|
|
1138
|
+
// Admin-gated, but bounds invitation-email volume (and accidental loops) per
|
|
1139
|
+
// admin: enough to onboard a team, low enough to deter abuse.
|
|
1140
|
+
export const inviteLimiter = createRateLimiter({ maxRequests: 20, windowMs: 60 * 60 * 1000 });
|
|
1141
|
+
export const totpLimiter = createRateLimiter({ maxRequests: 10, windowMs: 15 * 60 * 1000 });
|
|
1142
|
+
export const formLimiterGlobal = createRateLimiter({ maxRequests: 10, windowMs: 60_000 });
|
|
1143
|
+
export const aiGenerateLimiter = createRateLimiter({ maxRequests: 20, windowMs: 60 * 60 * 1000 });
|
|
1144
|
+
// Strict per-user upload cap (security rule: uploads strict at 20/hour) — guards
|
|
1145
|
+
// storage cost and optimization abuse beyond the global per-IP API bucket.
|
|
1146
|
+
export const uploadLimiter = createRateLimiter({ maxRequests: 20, windowMs: 60 * 60 * 1000 });
|
|
1147
|
+
// Deterministic (no provider) AI-adjacent routes that scan/iterate documents.
|
|
1148
|
+
// Cheaper than the generation budget but still bounded against cost/DoS.
|
|
1149
|
+
export const aiAnalysisLimiter = createRateLimiter({ maxRequests: 60, windowMs: 60 * 60 * 1000 });
|
|
1150
|
+
// Upper bound on free-text inputs to the deterministic analysis routes
|
|
1151
|
+
// (document body / link-candidate content) — caps memory + scan work.
|
|
1152
|
+
export const AI_ANALYSIS_MAX_CHARS = 50_000;
|
|
1153
|
+
export const linkHealthLimiter = createRateLimiter({ maxRequests: 4, windowMs: 60 * 60 * 1000 });
|
|
1154
|
+
export const seoAuditLimiter = createRateLimiter({ maxRequests: 10, windowMs: 60 * 60 * 1000 });
|
|
1155
|
+
export async function checkRateLimitAsync(limiter, key) {
|
|
1156
|
+
// Explicit, environment-gated bypass for test harnesses. Production never
|
|
1157
|
+
// sets this — Vercel + the deploy guide both omit it. We deliberately do
|
|
1158
|
+
// NOT key off `NODE_ENV === 'test'` because Next.js builds run with
|
|
1159
|
+
// NODE_ENV=test in some CI configurations and we want rate limiting
|
|
1160
|
+
// exercised by unit tests that explicitly opt in.
|
|
1161
|
+
if (process.env.ACTUATE_DISABLE_RATE_LIMIT === '1') {
|
|
1162
|
+
return true;
|
|
1163
|
+
}
|
|
1164
|
+
const result = await limiter.check(key);
|
|
1165
|
+
return result.allowed;
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Resolve the client IP from trusted-proxy headers (Vercel first, then x-real-ip,
|
|
1169
|
+
* then x-forwarded-for only when ACTUATE_TRUST_PROXY=1). Returns 'unknown' when
|
|
1170
|
+
* no trustworthy source is available — callers MUST treat that case as a hard
|
|
1171
|
+
* failure for security-sensitive decisions like rate-limit keys and IP allowlists.
|
|
1172
|
+
*/
|
|
1173
|
+
export function clientIp(request) {
|
|
1174
|
+
return getClientIp(request);
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Compute a before/after diff of top-level scalar (string/number/boolean) keys
|
|
1178
|
+
* between a stored record and an incoming patch. Used to audit settings changes
|
|
1179
|
+
* without ever logging nested objects (which may hold secret blobs).
|
|
1180
|
+
*/
|
|
1181
|
+
export function diffScalarKeys(previous, next) {
|
|
1182
|
+
const isScalar = (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null;
|
|
1183
|
+
const changes = [];
|
|
1184
|
+
for (const key of Object.keys(next)) {
|
|
1185
|
+
const to = next[key];
|
|
1186
|
+
if (!isScalar(to))
|
|
1187
|
+
continue;
|
|
1188
|
+
const from = previous[key];
|
|
1189
|
+
if (isScalar(from) && from === to)
|
|
1190
|
+
continue;
|
|
1191
|
+
if (!isScalar(from) && from !== undefined)
|
|
1192
|
+
continue;
|
|
1193
|
+
changes.push({ key, from: isScalar(from) ? from : undefined, to });
|
|
1194
|
+
}
|
|
1195
|
+
return changes;
|
|
1196
|
+
}
|
|
1197
|
+
export const MAX_CONCURRENT_SESSIONS = 5;
|
|
1198
|
+
/**
|
|
1199
|
+
* After a successful primary-credential check, prune the user's active sessions
|
|
1200
|
+
* down to the configured concurrent maximum (default 5; configurable via
|
|
1201
|
+
* `auth.maxConcurrentSessions`). Strategy is "revoke oldest" so a user can
|
|
1202
|
+
* always sign in.
|
|
1203
|
+
*/
|
|
1204
|
+
export async function enforceSessionLimitsForUser(d, userId) {
|
|
1205
|
+
if (!hasModel(d, 'session'))
|
|
1206
|
+
return;
|
|
1207
|
+
// Precedence: explicitly-saved Security setting (database) ▸ auth config ▸
|
|
1208
|
+
// default. We read the stored value directly (rather than the parsed
|
|
1209
|
+
// defaults) so an unsaved policy doesn't shadow a config-provided override.
|
|
1210
|
+
let storedMax;
|
|
1211
|
+
try {
|
|
1212
|
+
if (hasModel(d, 'document')) {
|
|
1213
|
+
const row = await d.document.findFirst({
|
|
1214
|
+
where: { collection: 'settings', deletedAt: null },
|
|
1215
|
+
select: { data: true },
|
|
1216
|
+
});
|
|
1217
|
+
const stored = row?.data?.security;
|
|
1218
|
+
const v = stored?.session?.maxConcurrentSessions;
|
|
1219
|
+
if (typeof v === 'number' && Number.isInteger(v) && v >= 0)
|
|
1220
|
+
storedMax = v;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
catch {
|
|
1224
|
+
/* fall back to config/default below */
|
|
1225
|
+
}
|
|
1226
|
+
const auth = getActuateConfig()?.auth;
|
|
1227
|
+
const max = storedMax !== undefined
|
|
1228
|
+
? storedMax
|
|
1229
|
+
: typeof auth?.maxConcurrentSessions === 'number' && auth.maxConcurrentSessions > 0
|
|
1230
|
+
? auth.maxConcurrentSessions
|
|
1231
|
+
: MAX_CONCURRENT_SESSIONS;
|
|
1232
|
+
// 0 ⇒ unlimited: skip pruning entirely.
|
|
1233
|
+
if (max <= 0)
|
|
1234
|
+
return;
|
|
1235
|
+
const active = await d.session.findMany({
|
|
1236
|
+
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
|
|
1237
|
+
select: { id: true, createdAt: true },
|
|
1238
|
+
});
|
|
1239
|
+
const decision = enforceSessionLimits(active.map((s) => ({ sessionId: s.id, userId, createdAt: s.createdAt })), { maxConcurrentSessions: max, strategy: 'revoke_oldest' });
|
|
1240
|
+
if (decision.sessionsToRevoke.length > 0) {
|
|
1241
|
+
await d.session.updateMany({
|
|
1242
|
+
where: { id: { in: decision.sessionsToRevoke } },
|
|
1243
|
+
data: { revokedAt: new Date() },
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
export function getAdminPath() {
|
|
1248
|
+
return process.env.ACTUATE_ADMIN_PATH ?? getActuateConfig()?.admin?.path ?? '/admin';
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Resolve a collection definition from the runtime config, tolerating both
|
|
1252
|
+
* the array and the record (keyed-by-slug) shapes consumers use.
|
|
1253
|
+
*/
|
|
1254
|
+
export function findCollectionDef(slug) {
|
|
1255
|
+
const collections = getActuateConfig()?.collections;
|
|
1256
|
+
if (Array.isArray(collections)) {
|
|
1257
|
+
return collections.find((c) => c?.slug === slug);
|
|
1258
|
+
}
|
|
1259
|
+
if (collections && typeof collections === 'object') {
|
|
1260
|
+
const rec = collections;
|
|
1261
|
+
return rec[slug] ?? Object.values(rec).find((c) => c?.slug === slug);
|
|
1262
|
+
}
|
|
1263
|
+
return undefined;
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* True when `collection` declares a `sections` JSON field — the storage
|
|
1267
|
+
* contract the flat Page Editor + section endpoints rely on. Guards against
|
|
1268
|
+
* silently dropping section writes on a collection that never declared the
|
|
1269
|
+
* field (the field-access layer strips undeclared keys).
|
|
1270
|
+
*/
|
|
1271
|
+
export function collectionSupportsSections(slug) {
|
|
1272
|
+
const def = findCollectionDef(slug);
|
|
1273
|
+
if (!def)
|
|
1274
|
+
return false;
|
|
1275
|
+
const fields = def.fields;
|
|
1276
|
+
if (Array.isArray(fields)) {
|
|
1277
|
+
return fields.some((f) => f?.name === 'sections' && f?.type === 'json');
|
|
1278
|
+
}
|
|
1279
|
+
if (fields && typeof fields === 'object') {
|
|
1280
|
+
const f = fields.sections;
|
|
1281
|
+
return f?.type === 'json';
|
|
1282
|
+
}
|
|
1283
|
+
return false;
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Gate a per-document read for endpoints (e.g. SEO analysis) that fetch a
|
|
1287
|
+
* document directly rather than through the collection CRUD routes. Enforces
|
|
1288
|
+
* both the API-key collection scope and the collection's `access.read` rule
|
|
1289
|
+
* so an AUTHOR scoped to one collection cannot read another's content.
|
|
1290
|
+
* Returns a `Response` to short-circuit with, or `null` when allowed.
|
|
1291
|
+
*/
|
|
1292
|
+
export async function enforceDocumentReadAccess(session, collection) {
|
|
1293
|
+
const scopeErr = requireCollectionScope(session, collection, 'read');
|
|
1294
|
+
if (scopeErr)
|
|
1295
|
+
return scopeErr;
|
|
1296
|
+
try {
|
|
1297
|
+
await assertCollectionAccess(collection, 'read', buildActionContext(session, guardedDb()));
|
|
1298
|
+
}
|
|
1299
|
+
catch (err) {
|
|
1300
|
+
if (err instanceof Error && err.message.includes('Access denied')) {
|
|
1301
|
+
return errorResponse('Insufficient permissions', 403);
|
|
1302
|
+
}
|
|
1303
|
+
throw err;
|
|
1304
|
+
}
|
|
1305
|
+
return null;
|
|
1306
|
+
}
|
|
1307
|
+
//# sourceMappingURL=route-helpers.js.map
|