domma-cms 0.24.0 → 0.25.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.
@@ -124,7 +124,7 @@ function redactTokenHash(entry) {
124
124
  * @param {object} payload - listEntries() result or a single entry
125
125
  * @returns {object}
126
126
  */
127
- function applyReadFieldAllowlist(schema, payload) {
127
+ export function applyReadFieldAllowlist(schema, payload) {
128
128
  const fields = schema.api?.read?.fields;
129
129
  if (!Array.isArray(fields) || fields.length === 0) return payload;
130
130
  const strip = (e) => ({
@@ -145,7 +145,7 @@ function applyReadFieldAllowlist(schema, payload) {
145
145
  * @param {object} reply - Fastify reply
146
146
  * @returns {Promise<object|undefined>}
147
147
  */
148
- async function checkPublicAccess(schema, operation, request, reply) {
148
+ export async function checkPublicAccess(schema, operation, request, reply) {
149
149
  const access = schema.api?.[operation];
150
150
  if (!access?.enabled) {
151
151
  return reply.status(403).send({ error: `Public ${operation} is disabled for this collection` });
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Custom API Endpoints — public surface
3
+ *
4
+ * One catch-all serves every user-defined endpoint:
5
+ * GET /api/x/<project><path> e.g. /api/x/world-cup/fixtures-day/2026-06-11
6
+ *
7
+ * Definitions live in the `api-endpoints` preset collection and are matched
8
+ * at request time by services/apiEndpoints.js. Auth (public / token / role),
9
+ * project binding, token scopes, and the read field allowlist all reuse the
10
+ * public collections machinery via a synthesized schema — one battle-tested
11
+ * code path for every external read.
12
+ *
13
+ * Unknown project, unknown path, and disabled endpoints all 404 identically
14
+ * (no existence oracle). GET-only in v1.
15
+ */
16
+ import {EndpointParamError, executeEndpoint, matchEndpoint} from '../../services/apiEndpoints.js';
17
+ import {applyReadFieldAllowlist, checkPublicAccess} from './collections.js';
18
+ import * as cache from '../../services/cache/index.js';
19
+
20
+ /** Cached sentinel for single-mode misses — a miss is a cacheable answer. */
21
+ const NOT_FOUND = {__endpointNotFound: true};
22
+
23
+ /**
24
+ * Stable query-string representation for cache keys.
25
+ *
26
+ * @param {Record<string, string>} query
27
+ * @returns {string}
28
+ */
29
+ function sortedQueryString(query) {
30
+ return Object.keys(query || {})
31
+ .sort()
32
+ .map(k => `${k}=${query[k]}`)
33
+ .join('&');
34
+ }
35
+
36
+ export async function endpointsPublicRoutes(fastify) {
37
+ fastify.get('/x/*', async (request, reply) => {
38
+ const segments = String(request.params['*'] || '').split('/').filter(Boolean);
39
+ if (segments.length < 2) return reply.status(404).send({ error: 'Not found' });
40
+
41
+ const [project, ...rest] = segments;
42
+ const match = await matchEndpoint(project, rest);
43
+ if (!match) return reply.status(404).send({ error: 'Not found' });
44
+
45
+ const {def, params} = match;
46
+
47
+ // Synthesized schema — checkPublicAccess reads exactly api.read,
48
+ // slug (token scopes), and meta.project (token project binding).
49
+ const synth = {
50
+ slug: def.collection,
51
+ api: { read: { enabled: true, access: def.auth, fields: def.fields } },
52
+ meta: { project: def.project }
53
+ };
54
+ const denied = await checkPublicAccess(synth, 'read', request, reply);
55
+ if (denied !== undefined) return;
56
+
57
+ const run = async () => {
58
+ const result = await executeEndpoint(def, params, request.query);
59
+ if (def.mode === 'single') {
60
+ return result === null ? NOT_FOUND : applyReadFieldAllowlist(synth, result);
61
+ }
62
+ return applyReadFieldAllowlist(synth, result);
63
+ };
64
+
65
+ try {
66
+ // Only public responses are cacheable — token/role responses are
67
+ // caller-dependent. Both tags are invalidated by the service layer
68
+ // on every write path: entry mutations bust collection:<slug>, and
69
+ // definition edits (entries in api-endpoints) bust
70
+ // collection:api-endpoints. No manual invalidation needed.
71
+ const payload = def.auth === 'public'
72
+ ? await cache.wrap(
73
+ `apix:${project}:${rest.join('/')}:${sortedQueryString(request.query)}`,
74
+ run,
75
+ { tags: [`collection:${def.collection}`, 'collection:api-endpoints'] }
76
+ )
77
+ : await run();
78
+
79
+ if (payload?.__endpointNotFound) return reply.status(404).send({ error: 'Not found' });
80
+ return payload;
81
+ } catch (err) {
82
+ if (err instanceof EndpointParamError) {
83
+ return reply.status(400).send({ error: err.message });
84
+ }
85
+ throw err;
86
+ }
87
+ });
88
+ }
package/server/server.js CHANGED
@@ -209,6 +209,10 @@ try {
209
209
  groupText: 'System',
210
210
  item: {text: 'API Tokens', url: '#/api-tokens', icon: 'key', permission: 'api-tokens'}
211
211
  });
212
+ await ensureSidebarItem({
213
+ groupText: 'Data',
214
+ item: {text: 'API Builder', url: '#/api-endpoints', icon: 'code', permission: 'api-endpoints'}
215
+ });
212
216
  } catch (err) {
213
217
  app.log.warn(`[admin-sidebar] Migration skipped: ${err.message}`);
214
218
  }
@@ -285,6 +289,8 @@ const {menusRoutes} = await import('./routes/api/menus.js');
285
289
  const {menuLocationsRoutes} = await import('./routes/api/menu-locations.js');
286
290
  const {projectsRoutes} = await import('./routes/api/projects.js');
287
291
  const {apiTokensRoutes} = await import('./routes/api/api-tokens.js');
292
+ const {apiEndpointsRoutes} = await import('./routes/api/api-endpoints.js');
293
+ const {endpointsPublicRoutes} = await import('./routes/api/endpoints-public.js');
288
294
  const {sidebarRoutes} = await import('./routes/api/sidebar.js');
289
295
  const { mediaRoutes } = await import('./routes/api/media.js');
290
296
  const { usersRoutes } = await import('./routes/api/users.js');
@@ -311,6 +317,8 @@ await app.register(menusRoutes, {prefix: '/api'});
311
317
  await app.register(menuLocationsRoutes, {prefix: '/api'});
312
318
  await app.register(projectsRoutes, {prefix: '/api'});
313
319
  await app.register(apiTokensRoutes, {prefix: '/api'});
320
+ await app.register(apiEndpointsRoutes, {prefix: '/api'});
321
+ await app.register(endpointsPublicRoutes, {prefix: '/api'});
314
322
  await app.register(sidebarRoutes, {prefix: '/api'});
315
323
  await app.register(mediaRoutes, { prefix: '/api' });
316
324
  await app.register(usersRoutes, { prefix: '/api' });
@@ -0,0 +1,402 @@
1
+ /**
2
+ * API Endpoints
3
+ * User-defined, curated REST endpoints over collection data, served at
4
+ * `/api/x/<project><path>` by one catch-all route.
5
+ *
6
+ * Definitions are DATA, never code: entries in the file-based `api-endpoints`
7
+ * preset collection. A definition binds a URL path (with `:param` segments)
8
+ * to a collection query — fixed filters whose values may carry
9
+ * `{{params.<name>}}` / `{{query.<name>}}` placeholders, sort/limit, a read
10
+ * field allowlist, and an auth mode (public / token / role) that reuses the
11
+ * exact machinery of the public collections API.
12
+ *
13
+ * Substituted values only ever feed the filterEngine — there is no eval and
14
+ * no way for a definition to execute code.
15
+ */
16
+ import {createEntry, deleteEntry, getCollection, getEntry, listEntries, updateEntry} from './collections.js';
17
+ import {canSeeArtefact, getProject} from './projects.js';
18
+ import {getRoleMap} from './roles.js';
19
+ import {parseFilterKey} from './filterEngine.js';
20
+ import {hooks} from './hooks.js';
21
+
22
+ export const API_ENDPOINTS_COLLECTION_SLUG = 'api-endpoints';
23
+
24
+ const STATIC_SEGMENT_RE = /^[a-z0-9-]+$/;
25
+ const PARAM_SEGMENT_RE = /^:[a-zA-Z_][a-zA-Z0-9_]*$/;
26
+ const TEMPLATE_RE = /\{\{\s*(params|query)\.([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g;
27
+ const MODES = ['list', 'single'];
28
+ const ORDERS = ['asc', 'desc'];
29
+
30
+ /** Thrown when a {{params.*}} placeholder cannot be resolved at request time. */
31
+ export class EndpointParamError extends Error {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = 'EndpointParamError';
35
+ }
36
+ }
37
+
38
+ /** Compiled registry: Map<project, compiled[]>; null = needs rebuild. */
39
+ let registry = null;
40
+
41
+ function invalidateRegistry() {
42
+ registry = null;
43
+ }
44
+
45
+ // Generic admin collection endpoints emit these for ALL collections — the
46
+ // service's own mutations invalidate directly, this catches edits made
47
+ // through the admin entries grid.
48
+ for (const ev of ['collection:entryCreated', 'collection:entryUpdated', 'collection:entryDeleted']) {
49
+ hooks.on(ev, (payload) => {
50
+ if (payload?.slug === API_ENDPOINTS_COLLECTION_SLUG) invalidateRegistry();
51
+ });
52
+ }
53
+
54
+ /**
55
+ * Strip an entry down to the public definition shape.
56
+ *
57
+ * @param {object} entry - Raw collection entry { id, data, meta }
58
+ * @returns {object}
59
+ */
60
+ function sanitise(entry) {
61
+ const d = entry.data || {};
62
+ return {
63
+ id: entry.id,
64
+ name: d.name,
65
+ project: d.project,
66
+ path: d.path,
67
+ collection: d.collection,
68
+ auth: d.auth || 'public',
69
+ mode: MODES.includes(d.mode) ? d.mode : 'list',
70
+ filter: (d.filter && typeof d.filter === 'object') ? d.filter : {},
71
+ sort: d.sort || null,
72
+ order: ORDERS.includes(d.order) ? d.order : 'desc',
73
+ limit: Number.isInteger(d.limit) ? d.limit : 50,
74
+ fields: Array.isArray(d.fields) ? d.fields : [],
75
+ enabled: d.enabled !== false,
76
+ createdBy: d.createdBy || null,
77
+ meta: entry.meta
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Normalise a path to its shape for duplicate detection — every `:param`
83
+ * segment collapses to `:` so `/a/:x` and `/a/:y` are the same shape.
84
+ *
85
+ * @param {string} path
86
+ * @returns {string}
87
+ */
88
+ function pathShape(path) {
89
+ return String(path).split('/').filter(Boolean)
90
+ .map(s => s.startsWith(':') ? ':' : s)
91
+ .join('/');
92
+ }
93
+
94
+ /**
95
+ * Validate a full endpoint definition. Throws on the first failure; the
96
+ * duplicate-shape error carries `code: 'DUPLICATE'` so routes can map it
97
+ * to 409.
98
+ *
99
+ * @param {object} data
100
+ * @param {{excludeId?: string}} [opts] - Skip this entry id in the duplicate check (updates)
101
+ * @returns {Promise<void>}
102
+ */
103
+ async function validateDefinition(data, {excludeId} = {}) {
104
+ if (!data.name || typeof data.name !== 'string' || !data.name.trim()) {
105
+ throw new Error('Endpoint name is required');
106
+ }
107
+ if (!data.project || typeof data.project !== 'string') throw new Error('Endpoint project is required');
108
+ if (!await getProject(data.project)) throw new Error(`Unknown project "${data.project}"`);
109
+
110
+ if (!data.collection || typeof data.collection !== 'string') throw new Error('Endpoint collection is required');
111
+ const schema = await getCollection(data.collection);
112
+ if (!schema) throw new Error(`Unknown collection "${data.collection}"`);
113
+ if (schema.systemManaged || schema.preset) {
114
+ throw new Error(`Collection "${data.collection}" is system-managed and cannot be exposed`);
115
+ }
116
+
117
+ if (typeof data.path !== 'string' || !data.path.startsWith('/')) {
118
+ throw new Error('Path must start with "/"');
119
+ }
120
+ const segments = data.path.split('/').filter(Boolean);
121
+ if (!segments.length) throw new Error('Path needs at least one segment');
122
+ const paramNames = new Set();
123
+ for (const seg of segments) {
124
+ if (PARAM_SEGMENT_RE.test(seg)) {
125
+ paramNames.add(seg.slice(1));
126
+ } else if (!STATIC_SEGMENT_RE.test(seg)) {
127
+ throw new Error(`Invalid path segment "${seg}" — use lowercase letters, numbers, hyphens, or :param`);
128
+ }
129
+ }
130
+
131
+ const auth = data.auth || 'public';
132
+ if (auth !== 'public' && auth !== 'token' && !getRoleMap().has(auth)) {
133
+ throw new Error(`Unknown auth mode "${auth}" — use public, token, or a role name`);
134
+ }
135
+
136
+ if (data.mode != null && !MODES.includes(data.mode)) throw new Error('mode must be "list" or "single"');
137
+ if (data.order != null && !ORDERS.includes(data.order)) throw new Error('order must be "asc" or "desc"');
138
+ if (data.limit != null && (!Number.isInteger(data.limit) || data.limit < 0 || data.limit > 500)) {
139
+ throw new Error('limit must be an integer between 0 and 500');
140
+ }
141
+ if (data.fields != null && (!Array.isArray(data.fields) || data.fields.some(f => typeof f !== 'string'))) {
142
+ throw new Error('fields must be an array of field names');
143
+ }
144
+
145
+ if (data.filter != null) {
146
+ if (typeof data.filter !== 'object' || Array.isArray(data.filter)) {
147
+ throw new Error('filter must be an object of { field_op: value }');
148
+ }
149
+ for (const [key, value] of Object.entries(data.filter)) {
150
+ const {field} = parseFilterKey(key);
151
+ if (!field) throw new Error(`Invalid filter key "${key}"`);
152
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
153
+ throw new Error(`Filter "${key}" must have a string, number, or boolean value`);
154
+ }
155
+ // Save-time check: every {{params.X}} must have a matching :X segment.
156
+ if (typeof value === 'string') {
157
+ for (const m of value.matchAll(TEMPLATE_RE)) {
158
+ if (m[1] === 'params' && !paramNames.has(m[2])) {
159
+ throw new Error(`Filter "${key}" references {{params.${m[2]}}} but the path has no :${m[2]} segment`);
160
+ }
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ // Duplicate shape per project — `/a/:x` and `/a/:y` collide.
167
+ const shape = pathShape(data.path);
168
+ const {entries} = await listEntries(API_ENDPOINTS_COLLECTION_SLUG, {limit: 0});
169
+ const clash = entries.find(e =>
170
+ e.id !== excludeId
171
+ && e.data?.project === data.project
172
+ && pathShape(e.data?.path || '') === shape
173
+ );
174
+ if (clash) {
175
+ const err = new Error(`An endpoint with the path shape "${data.path}" already exists in project "${data.project}" ("${clash.data.name}")`);
176
+ err.code = 'DUPLICATE';
177
+ throw err;
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Create an endpoint definition.
183
+ *
184
+ * @param {object} input
185
+ * @returns {Promise<object>} Sanitised definition
186
+ * @throws {Error} Validation failure (code 'DUPLICATE' for path clashes)
187
+ */
188
+ export async function createEndpoint(input) {
189
+ const data = {
190
+ name: String(input.name || '').trim(),
191
+ project: input.project,
192
+ path: input.path,
193
+ collection: input.collection,
194
+ auth: input.auth || 'public',
195
+ mode: input.mode || 'list',
196
+ filter: input.filter || {},
197
+ sort: input.sort || null,
198
+ order: input.order || 'desc',
199
+ limit: input.limit ?? 50,
200
+ fields: input.fields || [],
201
+ enabled: input.enabled !== false,
202
+ createdBy: input.createdBy || null
203
+ };
204
+ await validateDefinition(data);
205
+ const entry = await createEntry(API_ENDPOINTS_COLLECTION_SLUG, data, {createdBy: data.createdBy, source: 'admin'});
206
+ invalidateRegistry();
207
+ return sanitise(entry);
208
+ }
209
+
210
+ /**
211
+ * Update an endpoint. The project binding is immutable (it is the endpoint's
212
+ * URL namespace) — create a new endpoint to move one.
213
+ *
214
+ * @param {string} id
215
+ * @param {object} patch
216
+ * @returns {Promise<object|null>}
217
+ */
218
+ export async function updateEndpoint(id, patch = {}) {
219
+ const entry = await getEntry(API_ENDPOINTS_COLLECTION_SLUG, id);
220
+ if (!entry) return null;
221
+
222
+ const data = {...entry.data};
223
+ for (const key of ['name', 'path', 'collection', 'auth', 'mode', 'filter', 'sort', 'order', 'limit', 'fields']) {
224
+ if (patch[key] !== undefined) data[key] = patch[key];
225
+ }
226
+ if (patch.enabled !== undefined) data.enabled = patch.enabled !== false;
227
+ if (typeof data.name === 'string') data.name = data.name.trim();
228
+
229
+ await validateDefinition(data, {excludeId: id});
230
+ const updated = await updateEntry(API_ENDPOINTS_COLLECTION_SLUG, id, data);
231
+ invalidateRegistry();
232
+ return updated ? sanitise(updated) : null;
233
+ }
234
+
235
+ /**
236
+ * Delete an endpoint definition.
237
+ *
238
+ * @param {string} id
239
+ * @returns {Promise<boolean>}
240
+ */
241
+ export async function deleteEndpoint(id) {
242
+ const entry = await getEntry(API_ENDPOINTS_COLLECTION_SLUG, id);
243
+ if (!entry) return false;
244
+ await deleteEntry(API_ENDPOINTS_COLLECTION_SLUG, id);
245
+ invalidateRegistry();
246
+ return true;
247
+ }
248
+
249
+ /**
250
+ * List endpoints visible to the given admin user (project scope applies).
251
+ *
252
+ * @param {object} user
253
+ * @returns {Promise<object[]>}
254
+ */
255
+ export async function listEndpointsSanitised(user) {
256
+ const {entries} = await listEntries(API_ENDPOINTS_COLLECTION_SLUG, {limit: 0});
257
+ return entries
258
+ .filter(e => canSeeArtefact(user, {meta: {project: e.data?.project}}))
259
+ .map(sanitise);
260
+ }
261
+
262
+ /**
263
+ * Fetch a single endpoint, sanitised. Caller does the canSeeArtefact check.
264
+ *
265
+ * @param {string} id
266
+ * @returns {Promise<object|null>}
267
+ */
268
+ export async function getEndpointSanitised(id) {
269
+ const entry = await getEntry(API_ENDPOINTS_COLLECTION_SLUG, id);
270
+ return entry ? sanitise(entry) : null;
271
+ }
272
+
273
+ /**
274
+ * Look up an endpoint by project + path SHAPE (`:x` ≡ `:y`).
275
+ * Used for scaffolder idempotency.
276
+ *
277
+ * @param {string} project
278
+ * @param {string} path
279
+ * @returns {Promise<object|null>}
280
+ */
281
+ export async function findEndpointByPath(project, path) {
282
+ const shape = pathShape(path);
283
+ const {entries} = await listEntries(API_ENDPOINTS_COLLECTION_SLUG, {limit: 0});
284
+ const entry = entries.find(e => e.data?.project === project && pathShape(e.data?.path || '') === shape);
285
+ return entry ? sanitise(entry) : null;
286
+ }
287
+
288
+ /**
289
+ * Build the compiled registry from enabled definitions. Within a project,
290
+ * endpoints sort by static-segment count descending so static paths beat
291
+ * `:param` paths when both match.
292
+ *
293
+ * @returns {Promise<Map<string, object[]>>}
294
+ */
295
+ async function buildRegistry() {
296
+ const {entries} = await listEntries(API_ENDPOINTS_COLLECTION_SLUG, {limit: 0});
297
+ const map = new Map();
298
+ for (const entry of entries) {
299
+ const def = sanitise(entry);
300
+ if (!def.enabled || !def.project || !def.path) continue;
301
+ const segments = def.path.split('/').filter(Boolean).map(s =>
302
+ s.startsWith(':') ? {param: s.slice(1)} : {static: s}
303
+ );
304
+ const compiled = {
305
+ def,
306
+ segments,
307
+ staticCount: segments.filter(s => s.static).length
308
+ };
309
+ if (!map.has(def.project)) map.set(def.project, []);
310
+ map.get(def.project).push(compiled);
311
+ }
312
+ for (const list of map.values()) {
313
+ list.sort((a, b) => b.staticCount - a.staticCount);
314
+ }
315
+ return map;
316
+ }
317
+
318
+ /**
319
+ * Match a request path against the registry.
320
+ *
321
+ * @param {string} project - First wildcard segment
322
+ * @param {string[]} segments - Remaining wildcard segments (raw, URL-encoded)
323
+ * @returns {Promise<{def: object, params: Record<string, string>}|null>}
324
+ */
325
+ export async function matchEndpoint(project, segments) {
326
+ if (!registry) registry = await buildRegistry();
327
+ const candidates = registry.get(project);
328
+ if (!candidates) return null;
329
+
330
+ outer:
331
+ for (const c of candidates) {
332
+ if (c.segments.length !== segments.length) continue;
333
+ const params = {};
334
+ for (let i = 0; i < c.segments.length; i++) {
335
+ const spec = c.segments[i];
336
+ if (spec.static !== undefined) {
337
+ if (spec.static !== segments[i]) continue outer;
338
+ } else {
339
+ try { params[spec.param] = decodeURIComponent(segments[i]); }
340
+ catch { params[spec.param] = segments[i]; }
341
+ }
342
+ }
343
+ return {def: c.def, params};
344
+ }
345
+ return null;
346
+ }
347
+
348
+ /**
349
+ * Substitute {{params.X}} / {{query.X}} placeholders in the definition's
350
+ * filter values. Unresolved params throw (route maps to 400); a clause whose
351
+ * {{query.X}} stays unresolved is DROPPED, so query placeholders act as
352
+ * optional refinements.
353
+ *
354
+ * @param {object} filterTemplate
355
+ * @param {Record<string, string>} params
356
+ * @param {Record<string, string>} query
357
+ * @returns {object} Concrete filter for the filterEngine
358
+ */
359
+ function substituteFilter(filterTemplate, params, query) {
360
+ const out = {};
361
+ for (const [key, raw] of Object.entries(filterTemplate || {})) {
362
+ if (typeof raw !== 'string') { out[key] = raw; continue; }
363
+
364
+ let dropped = false;
365
+ const value = raw.replace(TEMPLATE_RE, (_m, kind, name) => {
366
+ const source = kind === 'params' ? params : query;
367
+ const v = source?.[name];
368
+ if (v === undefined || v === null || v === '') {
369
+ if (kind === 'params') {
370
+ throw new EndpointParamError(`Missing required path parameter "${name}"`);
371
+ }
372
+ dropped = true;
373
+ return '';
374
+ }
375
+ return String(v);
376
+ });
377
+ if (!dropped) out[key] = value;
378
+ }
379
+ return out;
380
+ }
381
+
382
+ /**
383
+ * Execute a matched endpoint definition.
384
+ *
385
+ * @param {object} def
386
+ * @param {Record<string, string>} params - Decoded path params
387
+ * @param {Record<string, string>} query - Request query object
388
+ * @returns {Promise<object|null>} list payload, single entry, or null (single miss)
389
+ * @throws {EndpointParamError}
390
+ */
391
+ export async function executeEndpoint(def, params, query) {
392
+ const filter = substituteFilter(def.filter, params, query || {});
393
+ const result = await listEntries(def.collection, {
394
+ page: 1,
395
+ limit: def.mode === 'single' ? 1 : (def.limit ?? 50),
396
+ sort: def.sort || 'createdAt',
397
+ order: def.order || 'desc',
398
+ filter: Object.keys(filter).length ? filter : undefined
399
+ });
400
+ if (def.mode === 'single') return result.entries[0] || null;
401
+ return result;
402
+ }
@@ -22,6 +22,15 @@ const LAST_USED_THROTTLE_MS = 60_000;
22
22
  /** In-memory hash → entry cache; null = needs rebuild. */
23
23
  let tokenCache = null;
24
24
 
25
+ /**
26
+ * Serialises this service's fire-and-forget writes (the throttled lastUsedAt
27
+ * update) against its mutations. FileAdapter does unlocked read-modify-write,
28
+ * so an in-flight lastUsedAt update that read the data file BEFORE a revoke
29
+ * wrote it would write the revoked token straight back — resurrection.
30
+ * Mutations await the chain; lastUsedAt updates append to it.
31
+ */
32
+ let writeChain = Promise.resolve();
33
+
25
34
  function invalidateCache() {
26
35
  tokenCache = null;
27
36
  }
@@ -178,7 +187,10 @@ export async function validateToken(plaintext) {
178
187
  // updateEntry replaces data wholesale — pass the full object.
179
188
  const data = {...entry.data, lastUsedAt: new Date().toISOString()};
180
189
  entry.data = data; // keep the cached copy current without invalidating
181
- updateEntry(API_TOKENS_COLLECTION_SLUG, entry.id, data).catch(() => {});
190
+ // Fire-and-forget, but chained so revoke/update can await it.
191
+ writeChain = writeChain
192
+ .then(() => updateEntry(API_TOKENS_COLLECTION_SLUG, entry.id, data))
193
+ .catch(() => {});
182
194
  }
183
195
 
184
196
  return sanitise(entry);
@@ -218,6 +230,7 @@ export async function getTokenSanitised(id) {
218
230
  * @throws {Error} On validation failure
219
231
  */
220
232
  export async function updateToken(id, patch = {}) {
233
+ await writeChain; // drain any in-flight lastUsedAt write first
221
234
  const entry = await getEntry(API_TOKENS_COLLECTION_SLUG, id);
222
235
  if (!entry) return null;
223
236
 
@@ -251,6 +264,7 @@ export async function updateToken(id, patch = {}) {
251
264
  * @returns {Promise<boolean>}
252
265
  */
253
266
  export async function revokeToken(id) {
267
+ await writeChain; // drain any in-flight lastUsedAt write — revoke must be final
254
268
  const entry = await getEntry(API_TOKENS_COLLECTION_SLUG, id);
255
269
  if (!entry) return false;
256
270
  await deleteEntry(API_TOKENS_COLLECTION_SLUG, id);
@@ -215,6 +215,19 @@ export const REGISTRY = [
215
215
  {key: 'update', label: 'Edit', description: 'Rename, enable/disable, or edit token scopes'},
216
216
  {key: 'delete', label: 'Revoke', description: 'Revoke (delete) API tokens'}
217
217
  ]
218
+ },
219
+ {
220
+ key: 'api-endpoints',
221
+ label: 'API Builder',
222
+ description: 'Build custom REST endpoints over collection data (/api/x/*).',
223
+ icon: 'code',
224
+ group: 'Configuration',
225
+ actions: [
226
+ {key: 'read', label: 'View', description: 'View custom API endpoint definitions'},
227
+ {key: 'create', label: 'Create', description: 'Create new endpoint definitions'},
228
+ {key: 'update', label: 'Edit', description: 'Edit endpoint definitions'},
229
+ {key: 'delete', label: 'Delete', description: 'Delete endpoint definitions'}
230
+ ]
218
231
  }
219
232
  ];
220
233
 
@@ -85,6 +85,35 @@ const PRESETS = [
85
85
  delete: {enabled: false, access: 'admin'}
86
86
  }
87
87
  }
88
+ ,
89
+ {
90
+ slug: 'api-endpoints',
91
+ title: 'API Endpoints',
92
+ description: 'Curated custom REST endpoints over collection data (/api/x/*).',
93
+ preset: true,
94
+ systemManaged: true,
95
+ fields: [
96
+ {name: 'name', label: 'Name', type: 'text', required: true},
97
+ {name: 'project', label: 'Project', type: 'text', required: true},
98
+ {name: 'path', label: 'Path', type: 'text', required: true},
99
+ {name: 'collection', label: 'Collection', type: 'text', required: true},
100
+ {name: 'auth', label: 'Auth', type: 'text', default: 'public'},
101
+ {name: 'mode', label: 'Mode', type: 'select', options: ['list', 'single'], default: 'list'},
102
+ {name: 'filter', label: 'Filter', type: 'object', default: {}},
103
+ {name: 'sort', label: 'Sort Field', type: 'text'},
104
+ {name: 'order', label: 'Sort Order', type: 'select', options: ['asc', 'desc'], default: 'desc'},
105
+ {name: 'limit', label: 'Limit', type: 'number', default: 50},
106
+ {name: 'fields', label: 'Fields', type: 'array', items: 'string', default: []},
107
+ {name: 'enabled', label: 'Enabled', type: 'boolean', default: true},
108
+ {name: 'createdBy', label: 'Created By', type: 'text'}
109
+ ],
110
+ api: {
111
+ create: {enabled: false, access: 'admin'},
112
+ read: {enabled: false, access: 'admin'},
113
+ update: {enabled: false, access: 'admin'},
114
+ delete: {enabled: false, access: 'admin'}
115
+ }
116
+ }
88
117
  ];
89
118
 
90
119
  /** Slugs exported for use in adapterRegistry and the delete guard. */