@dyrected/core 2.5.16 → 2.5.18
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/app-BElen1tP.d.cts +1690 -0
- package/dist/app-BElen1tP.d.ts +1690 -0
- package/dist/app-D0ffogDd.d.cts +1690 -0
- package/dist/app-D0ffogDd.d.ts +1690 -0
- package/dist/app-D2uR47gK.d.cts +1690 -0
- package/dist/app-D2uR47gK.d.ts +1690 -0
- package/dist/chunk-ALNQINX7.js +2496 -0
- package/dist/chunk-B6KDKYXB.js +2502 -0
- package/dist/chunk-EXXOPW3I.js +2483 -0
- package/dist/chunk-TUUHGLB5.js +2609 -0
- package/dist/chunk-YNJ3YC4N.js +2483 -0
- package/dist/index.cjs +170 -36
- package/dist/index.d.cts +9 -2
- package/dist/index.d.ts +9 -2
- package/dist/index.js +1 -1
- package/dist/server.cjs +170 -36
- package/dist/server.d.cts +10 -10
- package/dist/server.d.ts +10 -10
- package/dist/server.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,2502 @@
|
|
|
1
|
+
// src/utils/config.ts
|
|
2
|
+
var AUDIT_COLLECTION_SLUG = "__audit";
|
|
3
|
+
var SYSTEM_FIELDS = [
|
|
4
|
+
{
|
|
5
|
+
name: "createdAt",
|
|
6
|
+
type: "date",
|
|
7
|
+
label: "Created At",
|
|
8
|
+
admin: { readOnly: true, hidden: true }
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
name: "updatedAt",
|
|
12
|
+
type: "date",
|
|
13
|
+
label: "Updated At",
|
|
14
|
+
admin: { readOnly: true, hidden: true }
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "createdBy",
|
|
18
|
+
type: "text",
|
|
19
|
+
label: "Created By",
|
|
20
|
+
admin: { readOnly: true, hidden: true }
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "updatedBy",
|
|
24
|
+
type: "text",
|
|
25
|
+
label: "Updated By",
|
|
26
|
+
admin: { readOnly: true, hidden: true }
|
|
27
|
+
}
|
|
28
|
+
];
|
|
29
|
+
var AUDIT_COLLECTION = {
|
|
30
|
+
slug: AUDIT_COLLECTION_SLUG,
|
|
31
|
+
labels: { singular: "Audit Log", plural: "Audit Logs" },
|
|
32
|
+
fields: [
|
|
33
|
+
{ name: "collection", type: "text", label: "Collection", required: true },
|
|
34
|
+
{ name: "documentId", type: "text", label: "Document ID" },
|
|
35
|
+
{ name: "operation", type: "select", label: "Operation", options: ["create", "update", "delete"], required: true },
|
|
36
|
+
{ name: "user", type: "text", label: "User ID" },
|
|
37
|
+
{ name: "timestamp", type: "date", label: "Timestamp", required: true },
|
|
38
|
+
{ name: "changes", type: "json", label: "Changes" }
|
|
39
|
+
],
|
|
40
|
+
admin: { hidden: true }
|
|
41
|
+
};
|
|
42
|
+
function normalizeConfig(config) {
|
|
43
|
+
const collections = config?.collections || [];
|
|
44
|
+
const globals = config?.globals || [];
|
|
45
|
+
const needsAudit = collections.some((col) => col.audit);
|
|
46
|
+
const normalizedCollections = collections.map((col) => {
|
|
47
|
+
let fields = col.fields || [];
|
|
48
|
+
const existingFieldNames = new Set(fields.map((f) => f.name));
|
|
49
|
+
if (col.auth) {
|
|
50
|
+
if (!existingFieldNames.has("email")) {
|
|
51
|
+
fields = [
|
|
52
|
+
...fields,
|
|
53
|
+
{
|
|
54
|
+
name: "email",
|
|
55
|
+
type: "email",
|
|
56
|
+
label: "Email",
|
|
57
|
+
required: true,
|
|
58
|
+
unique: true,
|
|
59
|
+
promoted: true,
|
|
60
|
+
access: {
|
|
61
|
+
update: "!id"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
];
|
|
65
|
+
}
|
|
66
|
+
if (!existingFieldNames.has("password")) {
|
|
67
|
+
fields = [
|
|
68
|
+
...fields,
|
|
69
|
+
{
|
|
70
|
+
name: "password",
|
|
71
|
+
type: "text",
|
|
72
|
+
label: "Password",
|
|
73
|
+
required: true,
|
|
74
|
+
access: {
|
|
75
|
+
update: "!id || user.id == id"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
];
|
|
79
|
+
}
|
|
80
|
+
if (!existingFieldNames.has("roles")) {
|
|
81
|
+
fields = [
|
|
82
|
+
...fields,
|
|
83
|
+
{
|
|
84
|
+
name: "roles",
|
|
85
|
+
type: "select",
|
|
86
|
+
label: "Roles",
|
|
87
|
+
defaultValue: [],
|
|
88
|
+
options: [
|
|
89
|
+
{ value: "admin", label: "Admin" },
|
|
90
|
+
{ value: "editor", label: "Editor" },
|
|
91
|
+
{ value: "viewer", label: "Viewer" }
|
|
92
|
+
],
|
|
93
|
+
access: {
|
|
94
|
+
update: "user.roles && 'admin' in user.roles"
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
];
|
|
98
|
+
}
|
|
99
|
+
fields = fields.map((field) => {
|
|
100
|
+
if (field.name === "email") {
|
|
101
|
+
return {
|
|
102
|
+
...field,
|
|
103
|
+
access: {
|
|
104
|
+
...field.access || {},
|
|
105
|
+
update: "!id"
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
if (field.name === "password") {
|
|
110
|
+
return {
|
|
111
|
+
...field,
|
|
112
|
+
admin: { ...field.admin || {} },
|
|
113
|
+
access: {
|
|
114
|
+
...field.access || {},
|
|
115
|
+
update: "!id || user.id == id"
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
if (field.name === "roles") {
|
|
120
|
+
return {
|
|
121
|
+
...field,
|
|
122
|
+
access: {
|
|
123
|
+
...field.access || {},
|
|
124
|
+
// Must be an admin; cannot edit own roles (no self-elevation).
|
|
125
|
+
update: "user.roles && 'admin' in user.roles && user.id != id"
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return field;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
const updatedFieldNames = new Set(fields.map((f) => f.name));
|
|
133
|
+
const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
|
|
134
|
+
return {
|
|
135
|
+
...col,
|
|
136
|
+
fields: [...fields, ...fieldsToInject]
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
|
|
140
|
+
return {
|
|
141
|
+
...config,
|
|
142
|
+
collections: [...normalizedCollections, ...needsAudit && !hasAuditCollection ? [AUDIT_COLLECTION] : []],
|
|
143
|
+
globals
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/utils/hooks.ts
|
|
148
|
+
async function runCollectionHooks(hooks, args, options = {}) {
|
|
149
|
+
if (!hooks || hooks.length === 0) {
|
|
150
|
+
return args.data ?? args.doc ?? void 0;
|
|
151
|
+
}
|
|
152
|
+
let currentPayload = args.data ?? args.doc ?? void 0;
|
|
153
|
+
for (const hook of hooks) {
|
|
154
|
+
try {
|
|
155
|
+
const result = await hook({
|
|
156
|
+
...args,
|
|
157
|
+
data: args.data !== void 0 ? currentPayload : void 0,
|
|
158
|
+
doc: args.doc !== void 0 ? currentPayload : void 0
|
|
159
|
+
});
|
|
160
|
+
if (result !== void 0) {
|
|
161
|
+
currentPayload = result;
|
|
162
|
+
}
|
|
163
|
+
} catch (err) {
|
|
164
|
+
if (options.isolated) {
|
|
165
|
+
console.error("[dyrected/core] Side-effect hook failed (error isolated \u2014 DB write was successful):", err);
|
|
166
|
+
} else {
|
|
167
|
+
throw err;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return currentPayload;
|
|
172
|
+
}
|
|
173
|
+
async function executeFieldBeforeChange(fields, data, originalDoc, user) {
|
|
174
|
+
if (!data || typeof data !== "object") return data;
|
|
175
|
+
const result = { ...data };
|
|
176
|
+
for (const field of fields) {
|
|
177
|
+
if (!field.name) continue;
|
|
178
|
+
const value = result[field.name];
|
|
179
|
+
const origValue = originalDoc?.[field.name];
|
|
180
|
+
let updatedValue = value;
|
|
181
|
+
if (field.hooks?.beforeChange) {
|
|
182
|
+
for (const hook of field.hooks.beforeChange) {
|
|
183
|
+
updatedValue = await hook({
|
|
184
|
+
value: updatedValue,
|
|
185
|
+
originalDoc: originalDoc ?? void 0,
|
|
186
|
+
data: result,
|
|
187
|
+
user
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
result[field.name] = updatedValue;
|
|
191
|
+
}
|
|
192
|
+
if (updatedValue !== void 0 && updatedValue !== null) {
|
|
193
|
+
if (field.type === "object" && field.fields) {
|
|
194
|
+
result[field.name] = await executeFieldBeforeChange(
|
|
195
|
+
field.fields,
|
|
196
|
+
updatedValue,
|
|
197
|
+
origValue,
|
|
198
|
+
user
|
|
199
|
+
);
|
|
200
|
+
} else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
|
|
201
|
+
const arrayResult = [];
|
|
202
|
+
for (let i = 0; i < updatedValue.length; i++) {
|
|
203
|
+
const item = updatedValue[i];
|
|
204
|
+
const origItem = Array.isArray(origValue) ? origValue[i] : null;
|
|
205
|
+
arrayResult.push(
|
|
206
|
+
await executeFieldBeforeChange(field.fields, item, origItem, user)
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
result[field.name] = arrayResult;
|
|
210
|
+
} else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
|
|
211
|
+
const blocksResult = [];
|
|
212
|
+
for (let i = 0; i < updatedValue.length; i++) {
|
|
213
|
+
const blockData = updatedValue[i];
|
|
214
|
+
const origBlock = Array.isArray(origValue) ? origValue[i] : null;
|
|
215
|
+
const blockConfig = field.blocks.find(
|
|
216
|
+
(b) => b.slug === blockData.blockType
|
|
217
|
+
);
|
|
218
|
+
if (blockConfig) {
|
|
219
|
+
blocksResult.push(
|
|
220
|
+
await executeFieldBeforeChange(
|
|
221
|
+
blockConfig.fields,
|
|
222
|
+
blockData,
|
|
223
|
+
origBlock,
|
|
224
|
+
user
|
|
225
|
+
)
|
|
226
|
+
);
|
|
227
|
+
} else {
|
|
228
|
+
blocksResult.push(blockData);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
result[field.name] = blocksResult;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return result;
|
|
236
|
+
}
|
|
237
|
+
async function executeFieldAfterRead(fields, doc, user) {
|
|
238
|
+
if (!doc || typeof doc !== "object") return doc;
|
|
239
|
+
const result = { ...doc };
|
|
240
|
+
for (const field of fields) {
|
|
241
|
+
if (!field.name) continue;
|
|
242
|
+
const value = result[field.name];
|
|
243
|
+
let updatedValue = value;
|
|
244
|
+
if (field.hooks?.afterRead) {
|
|
245
|
+
for (const hook of field.hooks.afterRead) {
|
|
246
|
+
updatedValue = await hook({
|
|
247
|
+
value: updatedValue,
|
|
248
|
+
doc: result,
|
|
249
|
+
user
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
result[field.name] = updatedValue;
|
|
253
|
+
}
|
|
254
|
+
if (updatedValue !== void 0 && updatedValue !== null) {
|
|
255
|
+
if (field.type === "object" && field.fields) {
|
|
256
|
+
result[field.name] = await executeFieldAfterRead(
|
|
257
|
+
field.fields,
|
|
258
|
+
updatedValue,
|
|
259
|
+
user
|
|
260
|
+
);
|
|
261
|
+
} else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
|
|
262
|
+
const arrayResult = [];
|
|
263
|
+
for (const item of updatedValue) {
|
|
264
|
+
arrayResult.push(
|
|
265
|
+
await executeFieldAfterRead(
|
|
266
|
+
field.fields,
|
|
267
|
+
item,
|
|
268
|
+
user
|
|
269
|
+
)
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
result[field.name] = arrayResult;
|
|
273
|
+
} else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
|
|
274
|
+
const blocksResult = [];
|
|
275
|
+
for (const blockData of updatedValue) {
|
|
276
|
+
const typedBlock = blockData;
|
|
277
|
+
const blockConfig = field.blocks.find(
|
|
278
|
+
(b) => b.slug === typedBlock.blockType
|
|
279
|
+
);
|
|
280
|
+
if (blockConfig) {
|
|
281
|
+
blocksResult.push(
|
|
282
|
+
await executeFieldAfterRead(
|
|
283
|
+
blockConfig.fields,
|
|
284
|
+
typedBlock,
|
|
285
|
+
user
|
|
286
|
+
)
|
|
287
|
+
);
|
|
288
|
+
} else {
|
|
289
|
+
blocksResult.push(blockData);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
result[field.name] = blocksResult;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return result;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/services/defaults.service.ts
|
|
300
|
+
var DefaultsService = class {
|
|
301
|
+
/**
|
|
302
|
+
* Recursively apply default values to a data object based on field definitions.
|
|
303
|
+
*/
|
|
304
|
+
static apply(fields, data = {}) {
|
|
305
|
+
const result = { ...data || {} };
|
|
306
|
+
fields.forEach((field) => {
|
|
307
|
+
if (field.type === "join") return;
|
|
308
|
+
if (field.type === "row" && field.fields) {
|
|
309
|
+
Object.assign(result, this.apply(field.fields, data));
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (!field.name) return;
|
|
313
|
+
let value = result[field.name];
|
|
314
|
+
if ((value === void 0 || value === null) && field.renameTo) {
|
|
315
|
+
const legacyValue = result[field.renameTo];
|
|
316
|
+
if (legacyValue !== void 0 && legacyValue !== null) {
|
|
317
|
+
value = legacyValue;
|
|
318
|
+
result[field.name] = legacyValue;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (value === void 0 || value === null) {
|
|
322
|
+
if (field.defaultValue !== void 0) {
|
|
323
|
+
result[field.name] = field.defaultValue;
|
|
324
|
+
} else {
|
|
325
|
+
if (field.type === "boolean") result[field.name] = false;
|
|
326
|
+
else if (field.type === "array") result[field.name] = [];
|
|
327
|
+
else if (field.type === "multiSelect") result[field.name] = [];
|
|
328
|
+
else if (field.type === "object") {
|
|
329
|
+
result[field.name] = this.apply(field.fields || [], {});
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
} else if (field.type === "object" && field.fields) {
|
|
333
|
+
result[field.name] = this.apply(field.fields, value);
|
|
334
|
+
} else if (field.type === "array" && field.fields && Array.isArray(value)) {
|
|
335
|
+
result[field.name] = value.map((item) => this.apply(field.fields, item));
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
return result;
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// src/services/population.service.ts
|
|
343
|
+
var PopulationService = class {
|
|
344
|
+
db;
|
|
345
|
+
collections;
|
|
346
|
+
constructor(db, collections) {
|
|
347
|
+
this.db = db;
|
|
348
|
+
this.collections = collections;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Recursively populate relationship fields in a document or array of documents.
|
|
352
|
+
*/
|
|
353
|
+
async populate(args) {
|
|
354
|
+
const { data, fields, currentDepth = 0, maxDepth = 10 } = args;
|
|
355
|
+
if (currentDepth >= maxDepth || !data) {
|
|
356
|
+
return data;
|
|
357
|
+
}
|
|
358
|
+
if (Array.isArray(data)) {
|
|
359
|
+
return Promise.all(data.map((item) => this.populate({ ...args, data: item })));
|
|
360
|
+
}
|
|
361
|
+
const populatedDoc = { ...data };
|
|
362
|
+
for (const field of fields) {
|
|
363
|
+
if (field.type === "join") continue;
|
|
364
|
+
if (field.type === "row" && field.fields) {
|
|
365
|
+
const rowPopulated = await this.populate({ data, fields: field.fields, currentDepth, maxDepth });
|
|
366
|
+
Object.assign(populatedDoc, rowPopulated);
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
if (!field.name) continue;
|
|
370
|
+
const value = populatedDoc[field.name];
|
|
371
|
+
if (field.type === "relationship" && field.relationTo && value) {
|
|
372
|
+
const relatedCollection = this.collections.find((c) => c.slug === field.relationTo);
|
|
373
|
+
if (!relatedCollection) continue;
|
|
374
|
+
if (Array.isArray(value)) {
|
|
375
|
+
populatedDoc[field.name] = await Promise.all(
|
|
376
|
+
value.map(async (id) => {
|
|
377
|
+
if (!id) return id;
|
|
378
|
+
let doc = id;
|
|
379
|
+
if (typeof id === "string") {
|
|
380
|
+
doc = await this.db.findOne({ collection: field.relationTo, id });
|
|
381
|
+
}
|
|
382
|
+
if (!doc || typeof doc !== "object") return id;
|
|
383
|
+
const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
|
|
384
|
+
return this.populate({
|
|
385
|
+
data: docWithDefaults,
|
|
386
|
+
fields: relatedCollection.fields,
|
|
387
|
+
currentDepth: currentDepth + 1,
|
|
388
|
+
maxDepth
|
|
389
|
+
});
|
|
390
|
+
})
|
|
391
|
+
);
|
|
392
|
+
} else if (value) {
|
|
393
|
+
let doc = value;
|
|
394
|
+
if (typeof value === "string") {
|
|
395
|
+
doc = await this.db.findOne({ collection: field.relationTo, id: value });
|
|
396
|
+
}
|
|
397
|
+
if (doc && typeof doc === "object") {
|
|
398
|
+
const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
|
|
399
|
+
populatedDoc[field.name] = await this.populate({
|
|
400
|
+
data: docWithDefaults,
|
|
401
|
+
fields: relatedCollection.fields,
|
|
402
|
+
currentDepth: currentDepth + 1,
|
|
403
|
+
maxDepth
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (field.type === "url" && value && typeof value === "object" && value.type === "internal" && value.relationTo && value.value) {
|
|
409
|
+
const relatedCollection = this.collections.find((c) => c.slug === value.relationTo);
|
|
410
|
+
if (relatedCollection) {
|
|
411
|
+
const doc = await this.db.findOne({ collection: value.relationTo, id: value.value });
|
|
412
|
+
if (doc && typeof doc === "object") {
|
|
413
|
+
const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
|
|
414
|
+
const populatedDocValue = await this.populate({
|
|
415
|
+
data: docWithDefaults,
|
|
416
|
+
fields: relatedCollection.fields,
|
|
417
|
+
currentDepth: currentDepth + 1,
|
|
418
|
+
maxDepth
|
|
419
|
+
});
|
|
420
|
+
const identifier = docWithDefaults.slug || docWithDefaults.id;
|
|
421
|
+
const resolvedUrl = `/collections/${value.relationTo}/${identifier}`;
|
|
422
|
+
populatedDoc[field.name] = {
|
|
423
|
+
...value,
|
|
424
|
+
url: resolvedUrl,
|
|
425
|
+
doc: populatedDocValue
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if ((field.type === "array" || field.type === "object") && field.fields && value) {
|
|
431
|
+
populatedDoc[field.name] = await this.populate({
|
|
432
|
+
data: value,
|
|
433
|
+
fields: field.fields,
|
|
434
|
+
currentDepth,
|
|
435
|
+
// Nested fields don't consume depth, only relationships do
|
|
436
|
+
maxDepth
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
if (field.type === "blocks" && field.blocks && Array.isArray(value)) {
|
|
440
|
+
populatedDoc[field.name] = await Promise.all(
|
|
441
|
+
value.map(async (blockData) => {
|
|
442
|
+
const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
|
|
443
|
+
if (!blockConfig) return blockData;
|
|
444
|
+
return this.populate({
|
|
445
|
+
data: blockData,
|
|
446
|
+
fields: blockConfig.fields,
|
|
447
|
+
currentDepth,
|
|
448
|
+
maxDepth
|
|
449
|
+
});
|
|
450
|
+
})
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return populatedDoc;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Helper to populate a PaginatedResult
|
|
458
|
+
*/
|
|
459
|
+
async populateResult(result, fields, maxDepth) {
|
|
460
|
+
if (maxDepth <= 0) return result;
|
|
461
|
+
const populatedDocs = await this.populate({
|
|
462
|
+
data: result.docs,
|
|
463
|
+
fields,
|
|
464
|
+
currentDepth: 0,
|
|
465
|
+
maxDepth
|
|
466
|
+
});
|
|
467
|
+
return {
|
|
468
|
+
...result,
|
|
469
|
+
docs: populatedDocs
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// src/services/audit.service.ts
|
|
475
|
+
var AuditService = class {
|
|
476
|
+
/**
|
|
477
|
+
* Writes a single entry to the __audit collection.
|
|
478
|
+
* Called without await — runs asynchronously and never blocks the primary operation.
|
|
479
|
+
*/
|
|
480
|
+
static async log(db, args) {
|
|
481
|
+
try {
|
|
482
|
+
await db.create({
|
|
483
|
+
collection: "__audit",
|
|
484
|
+
data: {
|
|
485
|
+
collection: args.collection,
|
|
486
|
+
documentId: args.documentId ?? null,
|
|
487
|
+
operation: args.operation,
|
|
488
|
+
user: args.user?.id ?? null,
|
|
489
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
490
|
+
changes: JSON.stringify({
|
|
491
|
+
before: args.before ?? null,
|
|
492
|
+
after: args.after ?? null
|
|
493
|
+
})
|
|
494
|
+
}
|
|
495
|
+
});
|
|
496
|
+
} catch (err) {
|
|
497
|
+
console.error("[dyrected/audit] Failed to write audit log:", err);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// src/auth/password.ts
|
|
503
|
+
import { promisify } from "util";
|
|
504
|
+
import { scrypt, randomBytes, timingSafeEqual } from "crypto";
|
|
505
|
+
var scryptAsync = promisify(scrypt);
|
|
506
|
+
var SALT_LEN = 16;
|
|
507
|
+
var KEY_LEN = 64;
|
|
508
|
+
async function hashPassword(plain) {
|
|
509
|
+
const salt = randomBytes(SALT_LEN).toString("hex");
|
|
510
|
+
const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
|
|
511
|
+
return `${salt}:${derivedKey.toString("hex")}`;
|
|
512
|
+
}
|
|
513
|
+
async function verifyPassword(plain, stored) {
|
|
514
|
+
const [salt, storedHash] = stored.split(":");
|
|
515
|
+
if (!salt || !storedHash) return false;
|
|
516
|
+
const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
|
|
517
|
+
const storedBuffer = Buffer.from(storedHash, "hex");
|
|
518
|
+
if (derivedKey.length !== storedBuffer.length) return false;
|
|
519
|
+
return timingSafeEqual(derivedKey, storedBuffer);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// src/controllers/collection.controller.ts
|
|
523
|
+
var CollectionController = class {
|
|
524
|
+
collection;
|
|
525
|
+
constructor(collection) {
|
|
526
|
+
this.collection = collection;
|
|
527
|
+
}
|
|
528
|
+
async find(c) {
|
|
529
|
+
const config = c.get("config");
|
|
530
|
+
const db = config.db;
|
|
531
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
532
|
+
const limit = Number(c.req.query("limit")) || 10;
|
|
533
|
+
const page = Number(c.req.query("page")) || 1;
|
|
534
|
+
const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 2;
|
|
535
|
+
const sort = c.req.query("sort") || void 0;
|
|
536
|
+
const user = c.get("user");
|
|
537
|
+
let where = void 0;
|
|
538
|
+
const whereRaw = c.req.query("where");
|
|
539
|
+
if (whereRaw) {
|
|
540
|
+
try {
|
|
541
|
+
where = JSON.parse(decodeURIComponent(whereRaw));
|
|
542
|
+
} catch {
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const beforeReadResult = await runCollectionHooks(this.collection.hooks?.beforeRead, {
|
|
546
|
+
req: c.req,
|
|
547
|
+
query: where,
|
|
548
|
+
user
|
|
549
|
+
});
|
|
550
|
+
if (beforeReadResult !== void 0) {
|
|
551
|
+
where = beforeReadResult;
|
|
552
|
+
}
|
|
553
|
+
let result = await db.find({
|
|
554
|
+
collection: this.collection.slug,
|
|
555
|
+
limit,
|
|
556
|
+
page,
|
|
557
|
+
sort,
|
|
558
|
+
where
|
|
559
|
+
});
|
|
560
|
+
if (result.total === 0 && this.collection.initialData && !where && page === 1) {
|
|
561
|
+
console.log(`[dyrected/core] Auto-seeding collection "${this.collection.slug}" from config.initialData`);
|
|
562
|
+
for (const data of this.collection.initialData) {
|
|
563
|
+
await db.create({ collection: this.collection.slug, data });
|
|
564
|
+
}
|
|
565
|
+
result = await db.find({
|
|
566
|
+
collection: this.collection.slug,
|
|
567
|
+
limit,
|
|
568
|
+
page,
|
|
569
|
+
sort,
|
|
570
|
+
where
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
result.docs = result.docs.map((doc) => DefaultsService.apply(this.collection.fields, doc));
|
|
574
|
+
const processedDocs = [];
|
|
575
|
+
for (const doc of result.docs) {
|
|
576
|
+
const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
|
|
577
|
+
doc,
|
|
578
|
+
req: c.req,
|
|
579
|
+
user
|
|
580
|
+
});
|
|
581
|
+
const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user);
|
|
582
|
+
processedDocs.push(docWithFieldHooks);
|
|
583
|
+
}
|
|
584
|
+
result.docs = processedDocs;
|
|
585
|
+
if (depth > 0) {
|
|
586
|
+
const populationService = new PopulationService(db, config.collections);
|
|
587
|
+
result = await populationService.populateResult(result, this.collection.fields, depth);
|
|
588
|
+
}
|
|
589
|
+
return c.json(result);
|
|
590
|
+
}
|
|
591
|
+
async findOne(c) {
|
|
592
|
+
const config = c.get("config");
|
|
593
|
+
const db = config.db;
|
|
594
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
595
|
+
const id = c.req.param("id");
|
|
596
|
+
const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
|
|
597
|
+
const user = c.get("user");
|
|
598
|
+
if (!id) return c.json({ message: "Missing ID" }, 400);
|
|
599
|
+
const doc = await db.findOne({ collection: this.collection.slug, id });
|
|
600
|
+
if (!doc) return c.json({ message: "Not Found" }, 404);
|
|
601
|
+
const docWithDefaults = DefaultsService.apply(this.collection.fields, doc);
|
|
602
|
+
const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
|
|
603
|
+
doc: docWithDefaults,
|
|
604
|
+
req: c.req,
|
|
605
|
+
user
|
|
606
|
+
});
|
|
607
|
+
const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user);
|
|
608
|
+
if (depth > 0 && docWithFieldHooks) {
|
|
609
|
+
const populationService = new PopulationService(db, config.collections);
|
|
610
|
+
const populatedDoc = await populationService.populate({
|
|
611
|
+
data: docWithFieldHooks,
|
|
612
|
+
fields: this.collection.fields,
|
|
613
|
+
currentDepth: 0,
|
|
614
|
+
maxDepth: depth
|
|
615
|
+
});
|
|
616
|
+
return c.json(populatedDoc);
|
|
617
|
+
}
|
|
618
|
+
return c.json(docWithFieldHooks);
|
|
619
|
+
}
|
|
620
|
+
async create(c) {
|
|
621
|
+
const config = c.get("config");
|
|
622
|
+
const db = config.db;
|
|
623
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
624
|
+
const contentType = c.req.header("Content-Type") || "";
|
|
625
|
+
if (contentType.toLowerCase().includes("multipart/form-data")) {
|
|
626
|
+
return this.upload(c);
|
|
627
|
+
}
|
|
628
|
+
const body = await c.req.json();
|
|
629
|
+
const user = c.get("user");
|
|
630
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
631
|
+
let data = {
|
|
632
|
+
...body,
|
|
633
|
+
createdAt: now,
|
|
634
|
+
updatedAt: now,
|
|
635
|
+
createdBy: user?.sub ?? null,
|
|
636
|
+
updatedBy: user?.sub ?? null
|
|
637
|
+
};
|
|
638
|
+
if (this.collection.auth && data.password) {
|
|
639
|
+
data.password = await hashPassword(data.password);
|
|
640
|
+
}
|
|
641
|
+
data = await executeFieldBeforeChange(this.collection.fields, data, null, user);
|
|
642
|
+
data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
|
|
643
|
+
data,
|
|
644
|
+
req: c.req,
|
|
645
|
+
user,
|
|
646
|
+
operation: "create"
|
|
647
|
+
});
|
|
648
|
+
const doc = await db.create({ collection: this.collection.slug, data });
|
|
649
|
+
if (this.collection.audit && db) {
|
|
650
|
+
AuditService.log(db, {
|
|
651
|
+
operation: "create",
|
|
652
|
+
collection: this.collection.slug,
|
|
653
|
+
documentId: doc.id,
|
|
654
|
+
user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
|
|
655
|
+
before: null,
|
|
656
|
+
after: doc
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
await runCollectionHooks(this.collection.hooks?.afterChange, {
|
|
660
|
+
doc,
|
|
661
|
+
user,
|
|
662
|
+
req: c.req,
|
|
663
|
+
operation: "create"
|
|
664
|
+
}, { isolated: true });
|
|
665
|
+
const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
|
|
666
|
+
doc,
|
|
667
|
+
req: c.req,
|
|
668
|
+
user
|
|
669
|
+
});
|
|
670
|
+
const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
|
|
671
|
+
return c.json(finalDoc, 201);
|
|
672
|
+
}
|
|
673
|
+
async upload(c) {
|
|
674
|
+
const config = c.get("config");
|
|
675
|
+
const storage = config.storage;
|
|
676
|
+
if (!storage) return c.json({ message: "Storage not configured" }, 500);
|
|
677
|
+
const formData = await c.req.formData();
|
|
678
|
+
const file = formData.get("file");
|
|
679
|
+
if (!file) return c.json({ message: "No file uploaded" }, 400);
|
|
680
|
+
const buffer = new Uint8Array(await file.arrayBuffer());
|
|
681
|
+
const siteId = c.get("siteId");
|
|
682
|
+
const workspaceId = c.get("workspaceId");
|
|
683
|
+
const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId;
|
|
684
|
+
const fileData = await storage.upload({
|
|
685
|
+
filename: file.name,
|
|
686
|
+
buffer,
|
|
687
|
+
mimeType: file.type,
|
|
688
|
+
prefix
|
|
689
|
+
});
|
|
690
|
+
const otherData = {};
|
|
691
|
+
formData.forEach((value, key) => {
|
|
692
|
+
if (key !== "file" && typeof value === "string") {
|
|
693
|
+
otherData[key] = value;
|
|
694
|
+
}
|
|
695
|
+
});
|
|
696
|
+
const user = c.get("user");
|
|
697
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
698
|
+
let data = {
|
|
699
|
+
...otherData,
|
|
700
|
+
...fileData,
|
|
701
|
+
createdAt: now,
|
|
702
|
+
updatedAt: now,
|
|
703
|
+
createdBy: user?.sub ?? null,
|
|
704
|
+
updatedBy: user?.sub ?? null
|
|
705
|
+
};
|
|
706
|
+
data = await executeFieldBeforeChange(this.collection.fields, data, null, user);
|
|
707
|
+
data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
|
|
708
|
+
data,
|
|
709
|
+
req: c.req,
|
|
710
|
+
user,
|
|
711
|
+
operation: "create"
|
|
712
|
+
});
|
|
713
|
+
const doc = await config.db.create({
|
|
714
|
+
collection: this.collection.slug,
|
|
715
|
+
data
|
|
716
|
+
});
|
|
717
|
+
await runCollectionHooks(this.collection.hooks?.afterChange, {
|
|
718
|
+
doc,
|
|
719
|
+
user,
|
|
720
|
+
req: c.req,
|
|
721
|
+
operation: "create"
|
|
722
|
+
}, { isolated: true });
|
|
723
|
+
const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
|
|
724
|
+
doc,
|
|
725
|
+
req: c.req,
|
|
726
|
+
user
|
|
727
|
+
});
|
|
728
|
+
const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
|
|
729
|
+
return c.json(finalDoc, 201);
|
|
730
|
+
}
|
|
731
|
+
async update(c) {
|
|
732
|
+
const config = c.get("config");
|
|
733
|
+
const db = config.db;
|
|
734
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
735
|
+
const id = c.req.param("id");
|
|
736
|
+
if (!id) return c.json({ message: "Missing ID" }, 400);
|
|
737
|
+
const body = await c.req.json();
|
|
738
|
+
const user = c.get("user");
|
|
739
|
+
let data = { ...body };
|
|
740
|
+
if (this.collection.auth) {
|
|
741
|
+
delete data.password;
|
|
742
|
+
delete data.oldPassword;
|
|
743
|
+
delete data.confirmPassword;
|
|
744
|
+
}
|
|
745
|
+
Object.assign(data, {
|
|
746
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
747
|
+
updatedBy: user?.sub ?? null
|
|
748
|
+
});
|
|
749
|
+
const originalDoc = await db.findOne({ collection: this.collection.slug, id });
|
|
750
|
+
if (!originalDoc) return c.json({ message: "Not Found" }, 404);
|
|
751
|
+
let before = null;
|
|
752
|
+
if (this.collection.audit) {
|
|
753
|
+
before = originalDoc;
|
|
754
|
+
}
|
|
755
|
+
data = await executeFieldBeforeChange(this.collection.fields, data, originalDoc, user);
|
|
756
|
+
data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
|
|
757
|
+
data,
|
|
758
|
+
doc: originalDoc,
|
|
759
|
+
req: c.req,
|
|
760
|
+
user,
|
|
761
|
+
operation: "update"
|
|
762
|
+
});
|
|
763
|
+
const doc = await db.update({ collection: this.collection.slug, id, data });
|
|
764
|
+
if (this.collection.audit && db) {
|
|
765
|
+
AuditService.log(db, {
|
|
766
|
+
operation: "update",
|
|
767
|
+
collection: this.collection.slug,
|
|
768
|
+
documentId: id,
|
|
769
|
+
user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
|
|
770
|
+
before,
|
|
771
|
+
after: doc
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
await runCollectionHooks(this.collection.hooks?.afterChange, {
|
|
775
|
+
doc,
|
|
776
|
+
previousDoc: originalDoc,
|
|
777
|
+
user,
|
|
778
|
+
req: c.req,
|
|
779
|
+
operation: "update"
|
|
780
|
+
}, { isolated: true });
|
|
781
|
+
const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
|
|
782
|
+
doc,
|
|
783
|
+
req: c.req,
|
|
784
|
+
user
|
|
785
|
+
});
|
|
786
|
+
const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
|
|
787
|
+
return c.json(finalDoc);
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* POST /api/collections/:slug/:id/change-password
|
|
791
|
+
*
|
|
792
|
+
* Dedicated endpoint for password changes. Requires the caller to supply:
|
|
793
|
+
* { oldPassword, newPassword, confirmPassword }
|
|
794
|
+
*
|
|
795
|
+
* Rules:
|
|
796
|
+
* - Only the account owner or an admin may change the password.
|
|
797
|
+
* - Non-admin callers MUST provide a valid oldPassword.
|
|
798
|
+
* - newPassword and confirmPassword must match.
|
|
799
|
+
*/
|
|
800
|
+
async changePassword(c) {
|
|
801
|
+
const config = c.get("config");
|
|
802
|
+
const db = config.db;
|
|
803
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
804
|
+
if (!this.collection.auth) {
|
|
805
|
+
return c.json({ message: "This collection does not support authentication" }, 400);
|
|
806
|
+
}
|
|
807
|
+
const id = c.req.param("id");
|
|
808
|
+
if (!id) return c.json({ message: "Missing ID" }, 400);
|
|
809
|
+
const user = c.get("user");
|
|
810
|
+
if (!user) return c.json({ message: "Authentication required" }, 401);
|
|
811
|
+
const body = await c.req.json().catch(() => null);
|
|
812
|
+
const { oldPassword, newPassword, confirmPassword } = body ?? {};
|
|
813
|
+
if (!newPassword) {
|
|
814
|
+
return c.json({ message: "newPassword is required" }, 400);
|
|
815
|
+
}
|
|
816
|
+
if (newPassword !== confirmPassword) {
|
|
817
|
+
return c.json({ message: "Passwords do not match" }, 400);
|
|
818
|
+
}
|
|
819
|
+
if (newPassword.length < 8) {
|
|
820
|
+
return c.json({ message: "Password must be at least 8 characters" }, 400);
|
|
821
|
+
}
|
|
822
|
+
const isAdmin = Array.isArray(user.roles) && user.roles.includes("admin");
|
|
823
|
+
const isSelf = user.sub === id;
|
|
824
|
+
if (!isAdmin && !isSelf) {
|
|
825
|
+
return c.json({ message: "You are not authorised to change this password" }, 403);
|
|
826
|
+
}
|
|
827
|
+
if (!isAdmin) {
|
|
828
|
+
if (!oldPassword) {
|
|
829
|
+
return c.json({ message: "Current password is required" }, 400);
|
|
830
|
+
}
|
|
831
|
+
const existing = await db.findOne({ collection: this.collection.slug, id });
|
|
832
|
+
if (!existing) return c.json({ message: "User not found" }, 404);
|
|
833
|
+
const valid = await verifyPassword(oldPassword, existing.password);
|
|
834
|
+
if (!valid) {
|
|
835
|
+
return c.json({ message: "Invalid current password" }, 400);
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const hashed = await hashPassword(newPassword);
|
|
839
|
+
const doc = await db.update({
|
|
840
|
+
collection: this.collection.slug,
|
|
841
|
+
id,
|
|
842
|
+
data: {
|
|
843
|
+
password: hashed,
|
|
844
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
845
|
+
updatedBy: user.sub
|
|
846
|
+
}
|
|
847
|
+
});
|
|
848
|
+
if (this.collection.audit) {
|
|
849
|
+
AuditService.log(db, {
|
|
850
|
+
operation: "update",
|
|
851
|
+
collection: this.collection.slug,
|
|
852
|
+
documentId: id,
|
|
853
|
+
user: { id: user.sub, collection: user.collection, email: user.email },
|
|
854
|
+
before: null,
|
|
855
|
+
after: { id }
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
return c.json({ success: true, message: "Password updated successfully" });
|
|
859
|
+
}
|
|
860
|
+
async delete(c) {
|
|
861
|
+
const config = c.get("config");
|
|
862
|
+
const db = config.db;
|
|
863
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
864
|
+
const id = c.req.param("id");
|
|
865
|
+
if (!id) return c.json({ message: "Missing ID" }, 400);
|
|
866
|
+
const user = c.get("user");
|
|
867
|
+
const doc = await db.findOne({ collection: this.collection.slug, id });
|
|
868
|
+
if (!doc) return c.json({ message: "Not Found" }, 404);
|
|
869
|
+
let before = null;
|
|
870
|
+
if (this.collection.audit) {
|
|
871
|
+
before = doc;
|
|
872
|
+
}
|
|
873
|
+
await runCollectionHooks(this.collection.hooks?.beforeDelete, {
|
|
874
|
+
id,
|
|
875
|
+
doc,
|
|
876
|
+
user,
|
|
877
|
+
req: c.req
|
|
878
|
+
});
|
|
879
|
+
await db.delete({ collection: this.collection.slug, id });
|
|
880
|
+
if (this.collection.audit && db) {
|
|
881
|
+
AuditService.log(db, {
|
|
882
|
+
operation: "delete",
|
|
883
|
+
collection: this.collection.slug,
|
|
884
|
+
documentId: id,
|
|
885
|
+
user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
|
|
886
|
+
before,
|
|
887
|
+
after: null
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
await runCollectionHooks(this.collection.hooks?.afterDelete, {
|
|
891
|
+
id,
|
|
892
|
+
doc,
|
|
893
|
+
user,
|
|
894
|
+
req: c.req
|
|
895
|
+
}, { isolated: true });
|
|
896
|
+
return c.json({ message: "Deleted" });
|
|
897
|
+
}
|
|
898
|
+
async deleteMany(c) {
|
|
899
|
+
const config = c.get("config");
|
|
900
|
+
const db = config.db;
|
|
901
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
902
|
+
const user = c.get("user");
|
|
903
|
+
let ids = [];
|
|
904
|
+
try {
|
|
905
|
+
const body = await c.req.json().catch(() => null);
|
|
906
|
+
if (body?.ids && Array.isArray(body.ids)) {
|
|
907
|
+
ids = body.ids;
|
|
908
|
+
}
|
|
909
|
+
} catch {
|
|
910
|
+
}
|
|
911
|
+
if (!ids.length) {
|
|
912
|
+
const raw = c.req.queries("ids") ?? c.req.queries("ids[]") ?? [];
|
|
913
|
+
ids = raw.filter(Boolean);
|
|
914
|
+
}
|
|
915
|
+
if (!ids.length) return c.json({ message: "No IDs provided" }, 400);
|
|
916
|
+
const deleted = [];
|
|
917
|
+
const failed = [];
|
|
918
|
+
for (const id of ids) {
|
|
919
|
+
try {
|
|
920
|
+
const doc = await db.findOne({ collection: this.collection.slug, id });
|
|
921
|
+
if (!doc) {
|
|
922
|
+
failed.push({ id, error: "Not Found" });
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
let before = null;
|
|
926
|
+
if (this.collection.audit) {
|
|
927
|
+
before = doc;
|
|
928
|
+
}
|
|
929
|
+
await runCollectionHooks(this.collection.hooks?.beforeDelete, {
|
|
930
|
+
id,
|
|
931
|
+
doc,
|
|
932
|
+
user,
|
|
933
|
+
req: c.req
|
|
934
|
+
});
|
|
935
|
+
await db.delete({ collection: this.collection.slug, id });
|
|
936
|
+
deleted.push(id);
|
|
937
|
+
if (this.collection.audit) {
|
|
938
|
+
AuditService.log(db, {
|
|
939
|
+
operation: "delete",
|
|
940
|
+
collection: this.collection.slug,
|
|
941
|
+
documentId: id,
|
|
942
|
+
user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
|
|
943
|
+
before,
|
|
944
|
+
after: null
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
await runCollectionHooks(this.collection.hooks?.afterDelete, {
|
|
948
|
+
id,
|
|
949
|
+
doc,
|
|
950
|
+
user,
|
|
951
|
+
req: c.req
|
|
952
|
+
}, { isolated: true });
|
|
953
|
+
} catch (err) {
|
|
954
|
+
failed.push({ id, error: err?.message ?? "Unknown error" });
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
return c.json({
|
|
958
|
+
message: `Deleted ${deleted.length} document(s)`,
|
|
959
|
+
deleted,
|
|
960
|
+
...failed.length ? { failed } : {}
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
async seed(c) {
|
|
964
|
+
const config = c.get("config");
|
|
965
|
+
const db = config.db;
|
|
966
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
967
|
+
const body = await c.req.json();
|
|
968
|
+
const initialData = body.data;
|
|
969
|
+
if (!initialData || !Array.isArray(initialData)) {
|
|
970
|
+
return c.json({ message: "Invalid initial data" }, 400);
|
|
971
|
+
}
|
|
972
|
+
const result = await db.find({ collection: this.collection.slug, limit: 1 });
|
|
973
|
+
if (result.total > 0) {
|
|
974
|
+
return c.json({ message: "Collection is not empty, skipping seed" });
|
|
975
|
+
}
|
|
976
|
+
console.log(`[dyrected/core] Auto-seeding collection: ${this.collection.slug}`);
|
|
977
|
+
const createdDocs = [];
|
|
978
|
+
for (const data of initialData) {
|
|
979
|
+
const doc = await db.create({ collection: this.collection.slug, data });
|
|
980
|
+
createdDocs.push(doc);
|
|
981
|
+
}
|
|
982
|
+
return c.json({ message: "Seed successful", count: createdDocs.length }, 201);
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
|
|
986
|
+
// src/controllers/global.controller.ts
|
|
987
|
+
var GlobalController = class {
|
|
988
|
+
global;
|
|
989
|
+
constructor(global) {
|
|
990
|
+
this.global = global;
|
|
991
|
+
}
|
|
992
|
+
async get(c) {
|
|
993
|
+
const config = c.get("config");
|
|
994
|
+
const db = config.db;
|
|
995
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
996
|
+
const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
|
|
997
|
+
const user = c.get("user");
|
|
998
|
+
let query = void 0;
|
|
999
|
+
const beforeReadResult = await runCollectionHooks(this.global.hooks?.beforeRead, {
|
|
1000
|
+
req: c.req,
|
|
1001
|
+
query,
|
|
1002
|
+
user
|
|
1003
|
+
});
|
|
1004
|
+
if (beforeReadResult !== void 0) {
|
|
1005
|
+
query = beforeReadResult;
|
|
1006
|
+
}
|
|
1007
|
+
let data = await db.getGlobal({ slug: this.global.slug });
|
|
1008
|
+
const isEmpty = !data || Object.keys(data).length === 0;
|
|
1009
|
+
if (isEmpty && this.global.initialData) {
|
|
1010
|
+
console.log(`[dyrected/core] Auto-seeding global "${this.global.slug}" from config.initialData`);
|
|
1011
|
+
await db.updateGlobal({ slug: this.global.slug, data: this.global.initialData });
|
|
1012
|
+
data = this.global.initialData;
|
|
1013
|
+
}
|
|
1014
|
+
const dataWithDefaults = DefaultsService.apply(this.global.fields, data);
|
|
1015
|
+
const docWithCollectionHooks = await runCollectionHooks(this.global.hooks?.afterRead, {
|
|
1016
|
+
doc: dataWithDefaults,
|
|
1017
|
+
req: c.req,
|
|
1018
|
+
user
|
|
1019
|
+
});
|
|
1020
|
+
const docWithFieldHooks = await executeFieldAfterRead(this.global.fields, docWithCollectionHooks, user);
|
|
1021
|
+
if (depth > 0 && docWithFieldHooks) {
|
|
1022
|
+
const populationService = new PopulationService(db, config.collections);
|
|
1023
|
+
const populatedData = await populationService.populate({
|
|
1024
|
+
data: docWithFieldHooks,
|
|
1025
|
+
fields: this.global.fields,
|
|
1026
|
+
currentDepth: 0,
|
|
1027
|
+
maxDepth: depth
|
|
1028
|
+
});
|
|
1029
|
+
return c.json(populatedData);
|
|
1030
|
+
}
|
|
1031
|
+
return c.json(docWithFieldHooks);
|
|
1032
|
+
}
|
|
1033
|
+
async update(c) {
|
|
1034
|
+
const db = c.get("config").db;
|
|
1035
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1036
|
+
const body = await c.req.json();
|
|
1037
|
+
const user = c.get("user");
|
|
1038
|
+
const originalDoc = await db.getGlobal({ slug: this.global.slug }) || {};
|
|
1039
|
+
let data = await executeFieldBeforeChange(this.global.fields, body, originalDoc, user);
|
|
1040
|
+
data = await runCollectionHooks(this.global.hooks?.beforeChange, {
|
|
1041
|
+
data,
|
|
1042
|
+
doc: originalDoc,
|
|
1043
|
+
req: c.req,
|
|
1044
|
+
user,
|
|
1045
|
+
operation: "update"
|
|
1046
|
+
});
|
|
1047
|
+
const updated = await db.updateGlobal({ slug: this.global.slug, data });
|
|
1048
|
+
await runCollectionHooks(this.global.hooks?.afterChange, {
|
|
1049
|
+
doc: updated,
|
|
1050
|
+
previousDoc: originalDoc,
|
|
1051
|
+
user,
|
|
1052
|
+
req: c.req,
|
|
1053
|
+
operation: "update"
|
|
1054
|
+
}, { isolated: true });
|
|
1055
|
+
const readDoc = await runCollectionHooks(this.global.hooks?.afterRead, {
|
|
1056
|
+
doc: updated,
|
|
1057
|
+
req: c.req,
|
|
1058
|
+
user
|
|
1059
|
+
});
|
|
1060
|
+
const finalDoc = await executeFieldAfterRead(this.global.fields, readDoc, user);
|
|
1061
|
+
return c.json(finalDoc);
|
|
1062
|
+
}
|
|
1063
|
+
async seed(c) {
|
|
1064
|
+
const config = c.get("config");
|
|
1065
|
+
const db = config.db;
|
|
1066
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1067
|
+
const body = await c.req.json();
|
|
1068
|
+
const initialData = body.data;
|
|
1069
|
+
if (!initialData) {
|
|
1070
|
+
return c.json({ message: "Invalid initial data" }, 400);
|
|
1071
|
+
}
|
|
1072
|
+
const existing = await db.getGlobal({ slug: this.global.slug });
|
|
1073
|
+
if (existing && Object.keys(existing).length > 0) {
|
|
1074
|
+
return c.json({ message: "Global is not empty, skipping seed" });
|
|
1075
|
+
}
|
|
1076
|
+
console.log(`[dyrected/core] Auto-seeding global: ${this.global.slug}`);
|
|
1077
|
+
await db.updateGlobal({ slug: this.global.slug, data: initialData });
|
|
1078
|
+
return c.json({ message: "Seed successful", data: initialData }, 201);
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
|
|
1082
|
+
// src/controllers/media.controller.ts
|
|
1083
|
+
var MediaController = class {
|
|
1084
|
+
collection;
|
|
1085
|
+
constructor(collection = "media") {
|
|
1086
|
+
this.collection = collection;
|
|
1087
|
+
}
|
|
1088
|
+
async upload(c) {
|
|
1089
|
+
const config = c.get("config");
|
|
1090
|
+
const storage = config.storage;
|
|
1091
|
+
const imageService = config.image;
|
|
1092
|
+
if (!storage) {
|
|
1093
|
+
return c.json({ message: "Storage not configured" }, 500);
|
|
1094
|
+
}
|
|
1095
|
+
const body = await c.req.parseBody();
|
|
1096
|
+
const file = body["file"];
|
|
1097
|
+
const focalPointStr = body["focalPoint"];
|
|
1098
|
+
const focalPoint = focalPointStr ? JSON.parse(focalPointStr) : void 0;
|
|
1099
|
+
if (!file) {
|
|
1100
|
+
return c.json({ message: "No file uploaded" }, 400);
|
|
1101
|
+
}
|
|
1102
|
+
const buffer = new Uint8Array(await file.arrayBuffer());
|
|
1103
|
+
const siteId = c.get("siteId");
|
|
1104
|
+
const workspaceId = c.get("workspaceId");
|
|
1105
|
+
const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId || "default";
|
|
1106
|
+
let imageMetadata = {};
|
|
1107
|
+
let imageSizes = {};
|
|
1108
|
+
if (imageService && file.type.startsWith("image/")) {
|
|
1109
|
+
let colConfig = config.collections.find((col) => col.slug === this.collection);
|
|
1110
|
+
if (!colConfig && config.onSchemaFetch && siteId) {
|
|
1111
|
+
const dynamic = await config.onSchemaFetch(siteId);
|
|
1112
|
+
colConfig = dynamic.collections?.find((col) => col.slug === this.collection);
|
|
1113
|
+
}
|
|
1114
|
+
try {
|
|
1115
|
+
const processed = await imageService.process({
|
|
1116
|
+
buffer,
|
|
1117
|
+
mimeType: file.type,
|
|
1118
|
+
config: colConfig?.upload,
|
|
1119
|
+
focalPoint
|
|
1120
|
+
});
|
|
1121
|
+
imageMetadata = processed.metadata;
|
|
1122
|
+
imageSizes = processed.sizes;
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
console.error("[MediaController] Image processing failed:", err);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
const fileData = await storage.upload({
|
|
1128
|
+
filename: file.name,
|
|
1129
|
+
buffer,
|
|
1130
|
+
mimeType: file.type,
|
|
1131
|
+
prefix
|
|
1132
|
+
});
|
|
1133
|
+
const finalFileData = {
|
|
1134
|
+
...fileData,
|
|
1135
|
+
...imageMetadata,
|
|
1136
|
+
focalPoint,
|
|
1137
|
+
sizes: {}
|
|
1138
|
+
};
|
|
1139
|
+
if (imageSizes) {
|
|
1140
|
+
for (const [sizeName, sizeData] of Object.entries(imageSizes)) {
|
|
1141
|
+
const ext = file.name.split(".").pop();
|
|
1142
|
+
const baseName = file.name.substring(0, file.name.lastIndexOf("."));
|
|
1143
|
+
const sizeFilename = `${baseName}-${sizeName}.${ext}`;
|
|
1144
|
+
try {
|
|
1145
|
+
const sizeFileData = await storage.upload({
|
|
1146
|
+
filename: sizeFilename,
|
|
1147
|
+
buffer: sizeData.buffer,
|
|
1148
|
+
mimeType: file.type,
|
|
1149
|
+
prefix
|
|
1150
|
+
});
|
|
1151
|
+
finalFileData.sizes[sizeName] = {
|
|
1152
|
+
...sizeFileData,
|
|
1153
|
+
width: sizeData.width,
|
|
1154
|
+
height: sizeData.height
|
|
1155
|
+
};
|
|
1156
|
+
} catch (err) {
|
|
1157
|
+
console.error(`[MediaController] Failed to upload size ${sizeName}:`, err);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
const db = config.db;
|
|
1162
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1163
|
+
const doc = await db.create({
|
|
1164
|
+
collection: this.collection,
|
|
1165
|
+
data: finalFileData
|
|
1166
|
+
});
|
|
1167
|
+
return c.json(doc, 201);
|
|
1168
|
+
}
|
|
1169
|
+
async find(c) {
|
|
1170
|
+
const db = c.get("config").db;
|
|
1171
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1172
|
+
const limit = Number(c.req.query("limit")) || 10;
|
|
1173
|
+
const page = Number(c.req.query("page")) || 1;
|
|
1174
|
+
const result = await db.find({
|
|
1175
|
+
collection: this.collection,
|
|
1176
|
+
limit,
|
|
1177
|
+
page
|
|
1178
|
+
});
|
|
1179
|
+
return c.json(result);
|
|
1180
|
+
}
|
|
1181
|
+
async delete(c) {
|
|
1182
|
+
const config = c.get("config");
|
|
1183
|
+
const storage = config.storage;
|
|
1184
|
+
const db = config.db;
|
|
1185
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1186
|
+
const id = c.req.param("id");
|
|
1187
|
+
if (!id) return c.json({ message: "Missing ID" }, 400);
|
|
1188
|
+
const doc = await db.findOne({ collection: this.collection, id });
|
|
1189
|
+
if (!doc) return c.json({ message: "Not Found" }, 404);
|
|
1190
|
+
if (storage) {
|
|
1191
|
+
await storage.delete({ filename: doc.filename });
|
|
1192
|
+
if (doc.sizes) {
|
|
1193
|
+
for (const size of Object.values(doc.sizes)) {
|
|
1194
|
+
if (size.filename) {
|
|
1195
|
+
await storage.delete({ filename: size.filename });
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
await db.delete({ collection: this.collection, id });
|
|
1201
|
+
return c.json({ message: "Deleted" });
|
|
1202
|
+
}
|
|
1203
|
+
async serve(c) {
|
|
1204
|
+
const config = c.get("config");
|
|
1205
|
+
const storage = config.storage;
|
|
1206
|
+
if (!storage || !storage.resolve) {
|
|
1207
|
+
return c.json({ message: "Storage not configured for serving" }, 404);
|
|
1208
|
+
}
|
|
1209
|
+
const filename = c.req.param("filename");
|
|
1210
|
+
if (!filename) return c.json({ message: "Missing filename" }, 400);
|
|
1211
|
+
let res = await storage.resolve({ filename });
|
|
1212
|
+
if (!res && !filename.includes("/")) {
|
|
1213
|
+
res = await storage.resolve({ filename: `default/${filename}` });
|
|
1214
|
+
}
|
|
1215
|
+
if (!res) return c.json({ message: "Not Found" }, 404);
|
|
1216
|
+
c.header("Content-Type", res.mimeType);
|
|
1217
|
+
return c.body(res.buffer);
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
|
|
1221
|
+
// src/auth/token.ts
|
|
1222
|
+
import { SignJWT, jwtVerify, decodeJwt } from "jose";
|
|
1223
|
+
import { TextEncoder } from "util";
|
|
1224
|
+
function getSecret() {
|
|
1225
|
+
const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET;
|
|
1226
|
+
if (!secret) {
|
|
1227
|
+
throw new Error(
|
|
1228
|
+
"[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
|
|
1229
|
+
);
|
|
1230
|
+
}
|
|
1231
|
+
return new TextEncoder().encode(secret);
|
|
1232
|
+
}
|
|
1233
|
+
var DEFAULT_EXPIRY = "7d";
|
|
1234
|
+
async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
|
|
1235
|
+
return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
|
|
1236
|
+
}
|
|
1237
|
+
async function verifyCollectionToken(token) {
|
|
1238
|
+
const { payload } = await jwtVerify(token, getSecret());
|
|
1239
|
+
return payload;
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
// src/services/email.service.ts
|
|
1243
|
+
var _devSend = null;
|
|
1244
|
+
var _devSendPromise = null;
|
|
1245
|
+
async function getDevSend() {
|
|
1246
|
+
if (_devSend) return _devSend;
|
|
1247
|
+
if (_devSendPromise) return _devSendPromise;
|
|
1248
|
+
_devSendPromise = (async () => {
|
|
1249
|
+
try {
|
|
1250
|
+
const nodemailer = await import("nodemailer");
|
|
1251
|
+
const account = await nodemailer.default.createTestAccount();
|
|
1252
|
+
const transport = nodemailer.default.createTransport({
|
|
1253
|
+
host: "smtp.ethereal.email",
|
|
1254
|
+
port: 587,
|
|
1255
|
+
auth: { user: account.user, pass: account.pass }
|
|
1256
|
+
});
|
|
1257
|
+
console.log("[dyrected/core] No email config \u2014 using Ethereal for dev email preview.");
|
|
1258
|
+
console.log(`[dyrected/core] Ethereal login: https://ethereal.email user: ${account.user} pass: ${account.pass}`);
|
|
1259
|
+
_devSend = async ({ to, subject, html }) => {
|
|
1260
|
+
const info = await transport.sendMail({ from: '"Dyrected Dev" <dev@dyrected.local>', to, subject, html });
|
|
1261
|
+
console.log(`[dyrected/core] Email preview URL: ${nodemailer.default.getTestMessageUrl(info)}`);
|
|
1262
|
+
};
|
|
1263
|
+
return _devSend;
|
|
1264
|
+
} catch {
|
|
1265
|
+
console.warn("[dyrected/core] nodemailer not available \u2014 emails will not be sent in dev.");
|
|
1266
|
+
return null;
|
|
1267
|
+
}
|
|
1268
|
+
})();
|
|
1269
|
+
return _devSendPromise;
|
|
1270
|
+
}
|
|
1271
|
+
async function sendEmail(config, payload) {
|
|
1272
|
+
if (config.email) {
|
|
1273
|
+
await config.email.send(payload);
|
|
1274
|
+
return;
|
|
1275
|
+
}
|
|
1276
|
+
if (process.env.NODE_ENV !== "production") {
|
|
1277
|
+
const devSend = await getDevSend();
|
|
1278
|
+
await devSend?.(payload);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
function buildWelcomeEmail(config, args) {
|
|
1282
|
+
const custom = config.email?.templates?.welcome?.(args);
|
|
1283
|
+
return {
|
|
1284
|
+
subject: custom?.subject ?? "Welcome \u2014 your account is ready",
|
|
1285
|
+
html: custom?.html ?? `
|
|
1286
|
+
<div style="font-family:sans-serif;max-width:600px;margin:0 auto">
|
|
1287
|
+
<h2>Welcome!</h2>
|
|
1288
|
+
<p>Your account has been created. You can now log in with:</p>
|
|
1289
|
+
<p><strong>${args.email}</strong></p>
|
|
1290
|
+
</div>`
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
function buildInviteEmail(config, args) {
|
|
1294
|
+
const custom = config.email?.templates?.invite?.(args);
|
|
1295
|
+
return {
|
|
1296
|
+
subject: custom?.subject ?? "You've been invited",
|
|
1297
|
+
html: custom?.html ?? `
|
|
1298
|
+
<div style="font-family:sans-serif;max-width:600px;margin:0 auto">
|
|
1299
|
+
<h2>You've been invited</h2>
|
|
1300
|
+
${args.invitedByEmail ? `<p>Invited by <strong>${args.invitedByEmail}</strong>.</p>` : ""}
|
|
1301
|
+
<p>Use the token below to accept your invitation. It expires in 7 days.</p>
|
|
1302
|
+
<pre style="background:#f4f4f4;padding:12px;border-radius:4px;word-break:break-all">${args.token}</pre>
|
|
1303
|
+
</div>`
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
function buildResetPasswordEmail(config, args) {
|
|
1307
|
+
const custom = config.email?.templates?.resetPassword?.(args);
|
|
1308
|
+
const resetLink = args.url;
|
|
1309
|
+
return {
|
|
1310
|
+
subject: custom?.subject ?? "Reset your password",
|
|
1311
|
+
html: custom?.html ?? `
|
|
1312
|
+
<div style="font-family:sans-serif;max-width:600px;margin:0 auto;padding:20px;border:1px solid #e5e7eb;border-radius:12px;background-color:#ffffff">
|
|
1313
|
+
<h2 style="font-size:20px;font-weight:600;color:#111827;margin-bottom:16px">Reset your password</h2>
|
|
1314
|
+
<p style="font-size:14px;color:#4b5563;line-height:1.5;margin-bottom:24px">
|
|
1315
|
+
We received a request to reset your password. Use the button below to set a new password. It will expire in 1 hour.
|
|
1316
|
+
</p>
|
|
1317
|
+
${resetLink ? `
|
|
1318
|
+
<div style="margin-bottom:28px">
|
|
1319
|
+
<a href="${resetLink}" style="display:inline-block;background-color:#111827;color:#ffffff;font-size:14px;font-weight:500;padding:10px 24px;text-decoration:none;border-radius:6px">
|
|
1320
|
+
Reset Password
|
|
1321
|
+
</a>
|
|
1322
|
+
</div>
|
|
1323
|
+
` : ""}
|
|
1324
|
+
<p style="font-size:12px;color:#9ca3af;margin-bottom:8px">Or copy and paste this token manually in the admin dashboard:</p>
|
|
1325
|
+
<table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f3f4f6;border-radius:6px;margin:0;table-layout:fixed">
|
|
1326
|
+
<tr>
|
|
1327
|
+
<td style="padding:12px;font-family:monospace;font-size:12px;color:#374151;word-break:break-all;white-space:normal;line-height:1.4">
|
|
1328
|
+
${args.token}
|
|
1329
|
+
</td>
|
|
1330
|
+
</tr>
|
|
1331
|
+
</table>
|
|
1332
|
+
</div>`
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
function buildPasswordChangedEmail(config, args) {
|
|
1336
|
+
const custom = config.email?.templates?.passwordChanged?.(args);
|
|
1337
|
+
return {
|
|
1338
|
+
subject: custom?.subject ?? "Your password has been changed",
|
|
1339
|
+
html: custom?.html ?? `
|
|
1340
|
+
<div style="font-family:sans-serif;max-width:600px;margin:0 auto">
|
|
1341
|
+
<h2>Password changed</h2>
|
|
1342
|
+
<p>The password for <strong>${args.email}</strong> was just changed.</p>
|
|
1343
|
+
<p>If you did not make this change, please contact support immediately.</p>
|
|
1344
|
+
</div>`
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// src/controllers/auth.controller.ts
|
|
1349
|
+
var AuthController = class {
|
|
1350
|
+
collection;
|
|
1351
|
+
constructor(collection) {
|
|
1352
|
+
this.collection = collection;
|
|
1353
|
+
}
|
|
1354
|
+
// ---------------------------------------------------------------------------
|
|
1355
|
+
// GET /init
|
|
1356
|
+
// Checks if the first user needs to be created.
|
|
1357
|
+
// ---------------------------------------------------------------------------
|
|
1358
|
+
async init(c) {
|
|
1359
|
+
const db = c.get("config").db;
|
|
1360
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1361
|
+
const result = await db.find({
|
|
1362
|
+
collection: this.collection.slug,
|
|
1363
|
+
limit: 1
|
|
1364
|
+
});
|
|
1365
|
+
return c.json({
|
|
1366
|
+
initialized: result.total > 0
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
// ---------------------------------------------------------------------------
|
|
1370
|
+
// POST /first-user
|
|
1371
|
+
// Creates the first user if none exist.
|
|
1372
|
+
// ---------------------------------------------------------------------------
|
|
1373
|
+
async registerFirstUser(c) {
|
|
1374
|
+
const config = c.get("config");
|
|
1375
|
+
const db = config.db;
|
|
1376
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1377
|
+
const check = await db.find({
|
|
1378
|
+
collection: this.collection.slug,
|
|
1379
|
+
limit: 1
|
|
1380
|
+
});
|
|
1381
|
+
if (check.total > 0) {
|
|
1382
|
+
return c.json({ error: true, message: "Initial user already exists." }, 403);
|
|
1383
|
+
}
|
|
1384
|
+
const body = await c.req.json().catch(() => null);
|
|
1385
|
+
if (!body?.email || !body?.password) {
|
|
1386
|
+
return c.json({ error: true, message: "email and password are required." }, 400);
|
|
1387
|
+
}
|
|
1388
|
+
const hashedPassword = await hashPassword(body.password);
|
|
1389
|
+
const user = await db.create({
|
|
1390
|
+
collection: this.collection.slug,
|
|
1391
|
+
data: {
|
|
1392
|
+
...body,
|
|
1393
|
+
password: hashedPassword,
|
|
1394
|
+
roles: ["admin"]
|
|
1395
|
+
// Default first user to admin
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
const token = await signCollectionToken({
|
|
1399
|
+
sub: user.id,
|
|
1400
|
+
email: user.email,
|
|
1401
|
+
collection: this.collection.slug
|
|
1402
|
+
});
|
|
1403
|
+
const { subject, html } = buildWelcomeEmail(config, { email: body.email });
|
|
1404
|
+
sendEmail(config, { to: body.email, subject, html }).catch(
|
|
1405
|
+
(err) => console.error("[dyrected/core] Failed to send welcome email:", err)
|
|
1406
|
+
);
|
|
1407
|
+
const { password: _, ...safeUser } = user;
|
|
1408
|
+
return c.json({ token, user: safeUser });
|
|
1409
|
+
}
|
|
1410
|
+
// ---------------------------------------------------------------------------
|
|
1411
|
+
// POST /login
|
|
1412
|
+
// ---------------------------------------------------------------------------
|
|
1413
|
+
async login(c) {
|
|
1414
|
+
const db = c.get("config").db;
|
|
1415
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1416
|
+
const body = await c.req.json().catch(() => null);
|
|
1417
|
+
if (!body?.email || !body?.password) {
|
|
1418
|
+
return c.json({ error: true, message: "email and password are required." }, 400);
|
|
1419
|
+
}
|
|
1420
|
+
const result = await db.find({
|
|
1421
|
+
collection: this.collection.slug,
|
|
1422
|
+
where: { email: body.email },
|
|
1423
|
+
limit: 1
|
|
1424
|
+
});
|
|
1425
|
+
const user = result.docs[0];
|
|
1426
|
+
if (!user) {
|
|
1427
|
+
return c.json({ error: true, message: "Invalid email or password." }, 401);
|
|
1428
|
+
}
|
|
1429
|
+
const valid = await verifyPassword(body.password, user.password);
|
|
1430
|
+
if (!valid) {
|
|
1431
|
+
return c.json({ error: true, message: "Invalid email or password." }, 401);
|
|
1432
|
+
}
|
|
1433
|
+
const token = await signCollectionToken({
|
|
1434
|
+
sub: user.id,
|
|
1435
|
+
email: user.email,
|
|
1436
|
+
collection: this.collection.slug
|
|
1437
|
+
});
|
|
1438
|
+
const { password: _, ...safeUser } = user;
|
|
1439
|
+
return c.json({ token, user: safeUser });
|
|
1440
|
+
}
|
|
1441
|
+
// ---------------------------------------------------------------------------
|
|
1442
|
+
// POST /logout
|
|
1443
|
+
// Auth collections use stateless JWTs — logout is handled client-side.
|
|
1444
|
+
// This endpoint exists so clients have a consistent API surface.
|
|
1445
|
+
// ---------------------------------------------------------------------------
|
|
1446
|
+
async logout(c) {
|
|
1447
|
+
return c.json({ success: true, message: "Logged out. Discard your token." });
|
|
1448
|
+
}
|
|
1449
|
+
// ---------------------------------------------------------------------------
|
|
1450
|
+
// GET /me
|
|
1451
|
+
// ---------------------------------------------------------------------------
|
|
1452
|
+
async me(c) {
|
|
1453
|
+
const db = c.get("config").db;
|
|
1454
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1455
|
+
const requestUser = c.get("user");
|
|
1456
|
+
if (!requestUser) {
|
|
1457
|
+
return c.json({ error: true, message: "Authentication required." }, 401);
|
|
1458
|
+
}
|
|
1459
|
+
const user = await db.findOne({ collection: this.collection.slug, id: requestUser.sub });
|
|
1460
|
+
if (!user) {
|
|
1461
|
+
return c.json({ error: true, message: "User not found." }, 404);
|
|
1462
|
+
}
|
|
1463
|
+
const { password: _, ...safeUser } = user;
|
|
1464
|
+
return c.json(safeUser);
|
|
1465
|
+
}
|
|
1466
|
+
// ---------------------------------------------------------------------------
|
|
1467
|
+
// POST /refresh-token
|
|
1468
|
+
// ---------------------------------------------------------------------------
|
|
1469
|
+
async refreshToken(c) {
|
|
1470
|
+
const requestUser = c.get("user");
|
|
1471
|
+
if (!requestUser) {
|
|
1472
|
+
return c.json({ error: true, message: "Authentication required." }, 401);
|
|
1473
|
+
}
|
|
1474
|
+
const token = await signCollectionToken({
|
|
1475
|
+
sub: requestUser.sub,
|
|
1476
|
+
email: requestUser.email,
|
|
1477
|
+
collection: this.collection.slug
|
|
1478
|
+
});
|
|
1479
|
+
return c.json({ token });
|
|
1480
|
+
}
|
|
1481
|
+
// ---------------------------------------------------------------------------
|
|
1482
|
+
// POST /forgot-password
|
|
1483
|
+
// Requires config.email to be set. Silently succeeds if email not found
|
|
1484
|
+
// to prevent email enumeration.
|
|
1485
|
+
// ---------------------------------------------------------------------------
|
|
1486
|
+
async forgotPassword(c) {
|
|
1487
|
+
const config = c.get("config");
|
|
1488
|
+
const db = config.db;
|
|
1489
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1490
|
+
const body = await c.req.json().catch(() => null);
|
|
1491
|
+
if (!body?.email) {
|
|
1492
|
+
return c.json({ error: true, message: "email is required." }, 400);
|
|
1493
|
+
}
|
|
1494
|
+
const result = await db.find({
|
|
1495
|
+
collection: this.collection.slug,
|
|
1496
|
+
where: { email: body.email },
|
|
1497
|
+
limit: 1
|
|
1498
|
+
});
|
|
1499
|
+
const user = result.docs[0];
|
|
1500
|
+
if (user) {
|
|
1501
|
+
const resetToken = await signCollectionToken(
|
|
1502
|
+
{ sub: user.id, email: user.email, collection: this.collection.slug, purpose: "reset" },
|
|
1503
|
+
"1h"
|
|
1504
|
+
);
|
|
1505
|
+
const resetUrl = body?.resetUrl;
|
|
1506
|
+
const url = resetUrl ? `${resetUrl}${resetUrl.includes("?") ? "&" : "?"}token=${encodeURIComponent(resetToken)}` : void 0;
|
|
1507
|
+
try {
|
|
1508
|
+
const { subject, html } = buildResetPasswordEmail(config, { token: resetToken, url });
|
|
1509
|
+
await sendEmail(config, { to: user.email, subject, html });
|
|
1510
|
+
} catch (err) {
|
|
1511
|
+
console.error("[dyrected/core] Failed to send password reset email:", err);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return c.json({
|
|
1515
|
+
success: true,
|
|
1516
|
+
message: "If an account with that email exists, a reset link has been sent."
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
// ---------------------------------------------------------------------------
|
|
1520
|
+
// POST /reset-password
|
|
1521
|
+
// Expects { token: string, password: string } in body.
|
|
1522
|
+
// The token is the reset JWT issued by /forgot-password.
|
|
1523
|
+
// ---------------------------------------------------------------------------
|
|
1524
|
+
async resetPassword(c) {
|
|
1525
|
+
const config = c.get("config");
|
|
1526
|
+
const db = config.db;
|
|
1527
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1528
|
+
const body = await c.req.json().catch(() => null);
|
|
1529
|
+
if (!body?.token || !body?.password) {
|
|
1530
|
+
return c.json({ error: true, message: "token and password are required." }, 400);
|
|
1531
|
+
}
|
|
1532
|
+
let payload;
|
|
1533
|
+
try {
|
|
1534
|
+
payload = await verifyCollectionToken(body.token);
|
|
1535
|
+
} catch {
|
|
1536
|
+
return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
|
|
1537
|
+
}
|
|
1538
|
+
if (payload.collection !== this.collection.slug || payload.purpose !== "reset") {
|
|
1539
|
+
return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
|
|
1540
|
+
}
|
|
1541
|
+
const hashedPassword = await hashPassword(body.password);
|
|
1542
|
+
await db.update({
|
|
1543
|
+
collection: this.collection.slug,
|
|
1544
|
+
id: payload.sub,
|
|
1545
|
+
data: { password: hashedPassword }
|
|
1546
|
+
});
|
|
1547
|
+
const { subject, html } = buildPasswordChangedEmail(config, { email: payload.email });
|
|
1548
|
+
sendEmail(config, { to: payload.email, subject, html }).catch(
|
|
1549
|
+
(err) => console.error("[dyrected/core] Failed to send password-changed email:", err)
|
|
1550
|
+
);
|
|
1551
|
+
return c.json({ success: true, message: "Password has been reset. You can now log in." });
|
|
1552
|
+
}
|
|
1553
|
+
// ---------------------------------------------------------------------------
|
|
1554
|
+
// POST /invite
|
|
1555
|
+
// Requires auth. Issues a signed invite token and emails it to the invitee.
|
|
1556
|
+
// ---------------------------------------------------------------------------
|
|
1557
|
+
async invite(c) {
|
|
1558
|
+
const config = c.get("config");
|
|
1559
|
+
const db = config.db;
|
|
1560
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1561
|
+
const requestUser = c.get("user");
|
|
1562
|
+
if (!requestUser) {
|
|
1563
|
+
return c.json({ error: true, message: "Authentication required." }, 401);
|
|
1564
|
+
}
|
|
1565
|
+
const body = await c.req.json().catch(() => null);
|
|
1566
|
+
if (!body?.email) {
|
|
1567
|
+
return c.json({ error: true, message: "email is required." }, 400);
|
|
1568
|
+
}
|
|
1569
|
+
const existing = await db.find({
|
|
1570
|
+
collection: this.collection.slug,
|
|
1571
|
+
where: { email: body.email },
|
|
1572
|
+
limit: 1
|
|
1573
|
+
});
|
|
1574
|
+
if (existing.total > 0) {
|
|
1575
|
+
return c.json({ error: true, message: "An account with that email already exists." }, 409);
|
|
1576
|
+
}
|
|
1577
|
+
const inviteToken = await signCollectionToken(
|
|
1578
|
+
{ sub: body.email, email: body.email, collection: this.collection.slug, purpose: "invite" },
|
|
1579
|
+
"7d"
|
|
1580
|
+
);
|
|
1581
|
+
try {
|
|
1582
|
+
const { subject, html } = buildInviteEmail(config, {
|
|
1583
|
+
token: inviteToken,
|
|
1584
|
+
invitedByEmail: requestUser.email
|
|
1585
|
+
});
|
|
1586
|
+
await sendEmail(config, { to: body.email, subject, html });
|
|
1587
|
+
} catch (err) {
|
|
1588
|
+
console.error("[dyrected/core] Failed to send invite email:", err);
|
|
1589
|
+
}
|
|
1590
|
+
return c.json({ success: true, message: `Invite sent to ${body.email}.` });
|
|
1591
|
+
}
|
|
1592
|
+
// ---------------------------------------------------------------------------
|
|
1593
|
+
// POST /accept-invite
|
|
1594
|
+
// Public. Validates the invite token and creates the user account.
|
|
1595
|
+
// Body: { token, password, ...extraFields }
|
|
1596
|
+
// ---------------------------------------------------------------------------
|
|
1597
|
+
async acceptInvite(c) {
|
|
1598
|
+
const config = c.get("config");
|
|
1599
|
+
const db = config.db;
|
|
1600
|
+
if (!db) return c.json({ message: "Database not configured" }, 500);
|
|
1601
|
+
const body = await c.req.json().catch(() => null);
|
|
1602
|
+
if (!body?.token || !body?.password) {
|
|
1603
|
+
return c.json({ error: true, message: "token and password are required." }, 400);
|
|
1604
|
+
}
|
|
1605
|
+
let payload;
|
|
1606
|
+
try {
|
|
1607
|
+
payload = await verifyCollectionToken(body.token);
|
|
1608
|
+
} catch {
|
|
1609
|
+
return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
|
|
1610
|
+
}
|
|
1611
|
+
if (payload.collection !== this.collection.slug || payload.purpose !== "invite") {
|
|
1612
|
+
return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
|
|
1613
|
+
}
|
|
1614
|
+
const inviteeEmail = payload.sub;
|
|
1615
|
+
const existing = await db.find({
|
|
1616
|
+
collection: this.collection.slug,
|
|
1617
|
+
where: { email: inviteeEmail },
|
|
1618
|
+
limit: 1
|
|
1619
|
+
});
|
|
1620
|
+
if (existing.total > 0) {
|
|
1621
|
+
return c.json({ error: true, message: "An account with that email already exists." }, 409);
|
|
1622
|
+
}
|
|
1623
|
+
const { token: _t, password: _p, ...extraFields } = body;
|
|
1624
|
+
const hashedPassword = await hashPassword(body.password);
|
|
1625
|
+
const user = await db.create({
|
|
1626
|
+
collection: this.collection.slug,
|
|
1627
|
+
data: { ...extraFields, email: inviteeEmail, password: hashedPassword }
|
|
1628
|
+
});
|
|
1629
|
+
const sessionToken = await signCollectionToken({
|
|
1630
|
+
sub: user.id,
|
|
1631
|
+
email: inviteeEmail,
|
|
1632
|
+
collection: this.collection.slug
|
|
1633
|
+
});
|
|
1634
|
+
const { subject, html } = buildWelcomeEmail(config, { email: inviteeEmail });
|
|
1635
|
+
sendEmail(config, { to: inviteeEmail, subject, html }).catch(
|
|
1636
|
+
(err) => console.error("[dyrected/core] Failed to send welcome email:", err)
|
|
1637
|
+
);
|
|
1638
|
+
const { password: _, ...safeUser } = user;
|
|
1639
|
+
return c.json({ token: sessionToken, user: safeUser }, 201);
|
|
1640
|
+
}
|
|
1641
|
+
};
|
|
1642
|
+
|
|
1643
|
+
// src/controllers/preview.controller.ts
|
|
1644
|
+
import { SignJWT as SignJWT2, jwtVerify as jwtVerify2 } from "jose";
|
|
1645
|
+
import { TextEncoder as TextEncoder2 } from "util";
|
|
1646
|
+
var PreviewController = class {
|
|
1647
|
+
getSecret() {
|
|
1648
|
+
const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET || "dyrected-preview-secret-change-me";
|
|
1649
|
+
return new TextEncoder2().encode(secret);
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* POST /api/preview-token
|
|
1653
|
+
* Generates a short-lived token for previewing unsaved data.
|
|
1654
|
+
*/
|
|
1655
|
+
async createToken(c) {
|
|
1656
|
+
const body = await c.req.json().catch(() => null);
|
|
1657
|
+
if (!body?.collectionSlug || !body?.data) {
|
|
1658
|
+
return c.json({ error: true, message: "collectionSlug and data are required." }, 400);
|
|
1659
|
+
}
|
|
1660
|
+
const token = await new SignJWT2({
|
|
1661
|
+
collectionSlug: body.collectionSlug,
|
|
1662
|
+
documentId: body.documentId,
|
|
1663
|
+
data: body.data
|
|
1664
|
+
}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("15m").sign(this.getSecret());
|
|
1665
|
+
const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
|
|
1666
|
+
return c.json({ token, expiresAt });
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* GET /api/preview-data?token=<jwt>
|
|
1670
|
+
* Returns the data stored in the preview token.
|
|
1671
|
+
*/
|
|
1672
|
+
async getData(c) {
|
|
1673
|
+
const token = c.req.query("token");
|
|
1674
|
+
if (!token) {
|
|
1675
|
+
return c.json({ error: true, message: "token query parameter is required." }, 400);
|
|
1676
|
+
}
|
|
1677
|
+
try {
|
|
1678
|
+
const { payload } = await jwtVerify2(token, this.getSecret());
|
|
1679
|
+
return c.json(payload);
|
|
1680
|
+
} catch (err) {
|
|
1681
|
+
return c.json({ error: true, message: "Invalid or expired preview token." }, 401);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
|
|
1686
|
+
// src/middleware/auth.ts
|
|
1687
|
+
function requireAuth() {
|
|
1688
|
+
return async (c, next) => {
|
|
1689
|
+
const authHeader = c.req.header("Authorization");
|
|
1690
|
+
const token = authHeader?.replace(/^Bearer\s+/i, "");
|
|
1691
|
+
if (!token) {
|
|
1692
|
+
return c.json({ error: true, message: "Authentication required." }, 401);
|
|
1693
|
+
}
|
|
1694
|
+
try {
|
|
1695
|
+
const user = await verifyCollectionToken(token);
|
|
1696
|
+
c.set("user", user);
|
|
1697
|
+
await next();
|
|
1698
|
+
} catch {
|
|
1699
|
+
return c.json({ error: true, message: "Invalid or expired token." }, 401);
|
|
1700
|
+
}
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
function optionalAuth() {
|
|
1704
|
+
return async (c, next) => {
|
|
1705
|
+
const authHeader = c.req.header("Authorization");
|
|
1706
|
+
const token = authHeader?.replace(/^Bearer\s+/i, "");
|
|
1707
|
+
if (token) {
|
|
1708
|
+
try {
|
|
1709
|
+
const user = await verifyCollectionToken(token);
|
|
1710
|
+
c.set("user", user);
|
|
1711
|
+
} catch {
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
await next();
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
// src/utils/openapi.ts
|
|
1719
|
+
function generateOpenApi(config) {
|
|
1720
|
+
const spec = {
|
|
1721
|
+
openapi: "3.0.0",
|
|
1722
|
+
info: {
|
|
1723
|
+
title: "Dyrected API",
|
|
1724
|
+
version: "1.0.0",
|
|
1725
|
+
description: "Automatically generated OpenAPI specification for the Dyrected project."
|
|
1726
|
+
},
|
|
1727
|
+
components: {
|
|
1728
|
+
schemas: {},
|
|
1729
|
+
securitySchemes: {
|
|
1730
|
+
ApiKeyAuth: {
|
|
1731
|
+
type: "apiKey",
|
|
1732
|
+
in: "header",
|
|
1733
|
+
name: "x-api-key"
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
},
|
|
1737
|
+
paths: {},
|
|
1738
|
+
security: [{ ApiKeyAuth: [] }]
|
|
1739
|
+
};
|
|
1740
|
+
for (const collection of config.collections) {
|
|
1741
|
+
spec.components.schemas[collection.slug] = collectionToSchema(collection);
|
|
1742
|
+
}
|
|
1743
|
+
for (const global of config.globals) {
|
|
1744
|
+
spec.components.schemas[global.slug] = globalToSchema(global);
|
|
1745
|
+
}
|
|
1746
|
+
for (const collection of config.collections) {
|
|
1747
|
+
const slug = collection.slug;
|
|
1748
|
+
const path = `/api/collections/${slug}`;
|
|
1749
|
+
const labels = collection.labels || { singular: slug, plural: `${slug}s` };
|
|
1750
|
+
spec.paths[path] = {
|
|
1751
|
+
get: {
|
|
1752
|
+
tags: ["Collections"],
|
|
1753
|
+
summary: `Find ${labels.plural}`,
|
|
1754
|
+
parameters: [
|
|
1755
|
+
{ name: "limit", in: "query", schema: { type: "integer", default: 10 } },
|
|
1756
|
+
{ name: "page", in: "query", schema: { type: "integer", default: 1 } },
|
|
1757
|
+
{ name: "where", in: "query", schema: { type: "string" }, description: "JSON filter" },
|
|
1758
|
+
{ name: "sort", in: "query", schema: { type: "string" }, description: "Sort field (e.g. -createdAt)" }
|
|
1759
|
+
],
|
|
1760
|
+
responses: {
|
|
1761
|
+
200: {
|
|
1762
|
+
description: "Success",
|
|
1763
|
+
content: {
|
|
1764
|
+
"application/json": {
|
|
1765
|
+
schema: {
|
|
1766
|
+
type: "object",
|
|
1767
|
+
properties: {
|
|
1768
|
+
docs: { type: "array", items: { $ref: `#/components/schemas/${slug}` } },
|
|
1769
|
+
total: { type: "integer" },
|
|
1770
|
+
limit: { type: "integer" },
|
|
1771
|
+
page: { type: "integer" }
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
},
|
|
1779
|
+
post: {
|
|
1780
|
+
tags: ["Collections"],
|
|
1781
|
+
summary: `Create ${labels.singular}`,
|
|
1782
|
+
requestBody: {
|
|
1783
|
+
required: true,
|
|
1784
|
+
content: {
|
|
1785
|
+
"application/json": {
|
|
1786
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
},
|
|
1790
|
+
responses: {
|
|
1791
|
+
201: {
|
|
1792
|
+
description: "Created",
|
|
1793
|
+
content: {
|
|
1794
|
+
"application/json": {
|
|
1795
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
spec.paths[`${path}/{id}`] = {
|
|
1803
|
+
get: {
|
|
1804
|
+
tags: ["Collections"],
|
|
1805
|
+
summary: `Get a single ${labels.singular}`,
|
|
1806
|
+
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
|
1807
|
+
responses: {
|
|
1808
|
+
200: {
|
|
1809
|
+
description: "Success",
|
|
1810
|
+
content: {
|
|
1811
|
+
"application/json": {
|
|
1812
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
},
|
|
1818
|
+
patch: {
|
|
1819
|
+
tags: ["Collections"],
|
|
1820
|
+
summary: `Update ${labels.singular}`,
|
|
1821
|
+
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
|
1822
|
+
requestBody: {
|
|
1823
|
+
required: true,
|
|
1824
|
+
content: {
|
|
1825
|
+
"application/json": {
|
|
1826
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
},
|
|
1830
|
+
responses: {
|
|
1831
|
+
200: {
|
|
1832
|
+
description: "Updated",
|
|
1833
|
+
content: {
|
|
1834
|
+
"application/json": {
|
|
1835
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
},
|
|
1841
|
+
delete: {
|
|
1842
|
+
tags: ["Collections"],
|
|
1843
|
+
summary: `Delete ${labels.singular}`,
|
|
1844
|
+
parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
|
|
1845
|
+
responses: {
|
|
1846
|
+
204: { description: "Deleted" }
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
for (const global of config.globals) {
|
|
1852
|
+
const slug = global.slug;
|
|
1853
|
+
const path = `/api/globals/${slug}`;
|
|
1854
|
+
spec.paths[path] = {
|
|
1855
|
+
get: {
|
|
1856
|
+
tags: ["Globals"],
|
|
1857
|
+
summary: `Get ${global.label || slug}`,
|
|
1858
|
+
responses: {
|
|
1859
|
+
200: {
|
|
1860
|
+
description: "Success",
|
|
1861
|
+
content: {
|
|
1862
|
+
"application/json": {
|
|
1863
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
},
|
|
1869
|
+
patch: {
|
|
1870
|
+
tags: ["Globals"],
|
|
1871
|
+
summary: `Update ${global.label || slug}`,
|
|
1872
|
+
requestBody: {
|
|
1873
|
+
required: true,
|
|
1874
|
+
content: {
|
|
1875
|
+
"application/json": {
|
|
1876
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
},
|
|
1880
|
+
responses: {
|
|
1881
|
+
200: {
|
|
1882
|
+
description: "Updated",
|
|
1883
|
+
content: {
|
|
1884
|
+
"application/json": {
|
|
1885
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
if (config.storage) {
|
|
1894
|
+
spec.paths["/api/media"] = {
|
|
1895
|
+
get: {
|
|
1896
|
+
tags: ["Media"],
|
|
1897
|
+
summary: "List Media",
|
|
1898
|
+
responses: {
|
|
1899
|
+
200: {
|
|
1900
|
+
description: "Success",
|
|
1901
|
+
content: {
|
|
1902
|
+
"application/json": {
|
|
1903
|
+
schema: {
|
|
1904
|
+
type: "object",
|
|
1905
|
+
properties: {
|
|
1906
|
+
docs: { type: "array", items: { type: "object", additionalProperties: true } }
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
},
|
|
1914
|
+
post: {
|
|
1915
|
+
tags: ["Media"],
|
|
1916
|
+
summary: "Upload Media",
|
|
1917
|
+
requestBody: {
|
|
1918
|
+
content: {
|
|
1919
|
+
"multipart/form-data": {
|
|
1920
|
+
schema: {
|
|
1921
|
+
type: "object",
|
|
1922
|
+
properties: {
|
|
1923
|
+
file: { type: "string", format: "binary" }
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
},
|
|
1929
|
+
responses: {
|
|
1930
|
+
201: { description: "Uploaded" }
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
};
|
|
1934
|
+
}
|
|
1935
|
+
return spec;
|
|
1936
|
+
}
|
|
1937
|
+
function collectionToSchema(collection) {
|
|
1938
|
+
const { properties, required } = fieldsToProperties(collection.fields);
|
|
1939
|
+
return {
|
|
1940
|
+
type: "object",
|
|
1941
|
+
properties: {
|
|
1942
|
+
id: { type: "string" },
|
|
1943
|
+
createdAt: { type: "string", format: "date-time" },
|
|
1944
|
+
updatedAt: { type: "string", format: "date-time" },
|
|
1945
|
+
...properties
|
|
1946
|
+
},
|
|
1947
|
+
required: ["id", ...required]
|
|
1948
|
+
};
|
|
1949
|
+
}
|
|
1950
|
+
function globalToSchema(global) {
|
|
1951
|
+
const { properties, required } = fieldsToProperties(global.fields);
|
|
1952
|
+
return {
|
|
1953
|
+
type: "object",
|
|
1954
|
+
properties,
|
|
1955
|
+
required
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
function fieldsToProperties(fields) {
|
|
1959
|
+
const props = {};
|
|
1960
|
+
const required = [];
|
|
1961
|
+
for (const field of fields) {
|
|
1962
|
+
if (!field.name || field.type === "join" || field.type === "row") continue;
|
|
1963
|
+
props[field.name] = fieldToSchema(field);
|
|
1964
|
+
if (field.required) {
|
|
1965
|
+
required.push(field.name);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
return { properties: props, required };
|
|
1969
|
+
}
|
|
1970
|
+
function fieldToSchema(field) {
|
|
1971
|
+
let schema = {};
|
|
1972
|
+
switch (field.type) {
|
|
1973
|
+
case "text":
|
|
1974
|
+
case "textarea":
|
|
1975
|
+
case "email":
|
|
1976
|
+
case "url":
|
|
1977
|
+
schema = { type: "string" };
|
|
1978
|
+
break;
|
|
1979
|
+
case "number":
|
|
1980
|
+
schema = { type: "number" };
|
|
1981
|
+
break;
|
|
1982
|
+
case "boolean":
|
|
1983
|
+
schema = { type: "boolean" };
|
|
1984
|
+
break;
|
|
1985
|
+
case "date":
|
|
1986
|
+
schema = { type: "string", format: "date-time" };
|
|
1987
|
+
break;
|
|
1988
|
+
case "select":
|
|
1989
|
+
case "radio":
|
|
1990
|
+
schema = { type: "string", enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0 };
|
|
1991
|
+
break;
|
|
1992
|
+
case "multiSelect":
|
|
1993
|
+
schema = {
|
|
1994
|
+
type: "array",
|
|
1995
|
+
items: { type: "string", enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0 }
|
|
1996
|
+
};
|
|
1997
|
+
break;
|
|
1998
|
+
case "relationship":
|
|
1999
|
+
schema = { type: "string", description: `ID of a ${field.relationTo} record` };
|
|
2000
|
+
break;
|
|
2001
|
+
case "object": {
|
|
2002
|
+
const { properties, required } = fieldsToProperties(field.fields || []);
|
|
2003
|
+
schema = { type: "object", properties, required };
|
|
2004
|
+
break;
|
|
2005
|
+
}
|
|
2006
|
+
case "array": {
|
|
2007
|
+
const { properties, required } = fieldsToProperties(field.fields || []);
|
|
2008
|
+
schema = { type: "array", items: { type: "object", properties, required } };
|
|
2009
|
+
break;
|
|
2010
|
+
}
|
|
2011
|
+
case "json":
|
|
2012
|
+
case "richText":
|
|
2013
|
+
schema = { type: "object", additionalProperties: true };
|
|
2014
|
+
break;
|
|
2015
|
+
case "blocks":
|
|
2016
|
+
schema = {
|
|
2017
|
+
type: "array",
|
|
2018
|
+
items: {
|
|
2019
|
+
oneOf: field.blocks?.map((block) => {
|
|
2020
|
+
const { properties, required } = fieldsToProperties(block.fields);
|
|
2021
|
+
return {
|
|
2022
|
+
type: "object",
|
|
2023
|
+
properties: {
|
|
2024
|
+
blockType: { type: "string", enum: [block.slug] },
|
|
2025
|
+
...properties
|
|
2026
|
+
},
|
|
2027
|
+
required: ["blockType", ...required]
|
|
2028
|
+
};
|
|
2029
|
+
})
|
|
2030
|
+
}
|
|
2031
|
+
};
|
|
2032
|
+
break;
|
|
2033
|
+
default:
|
|
2034
|
+
schema = { type: "string" };
|
|
2035
|
+
}
|
|
2036
|
+
if (field.label) schema.description = field.label;
|
|
2037
|
+
return schema;
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
// src/utils/swagger.ts
|
|
2041
|
+
function getSwaggerHtml(specUrl = "/api/openapi.json") {
|
|
2042
|
+
return `
|
|
2043
|
+
<!DOCTYPE html>
|
|
2044
|
+
<html lang="en">
|
|
2045
|
+
<head>
|
|
2046
|
+
<meta charset="utf-8" />
|
|
2047
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2048
|
+
<meta name="description" content="SwaggerUI" />
|
|
2049
|
+
<title>Dyrected API Documentation</title>
|
|
2050
|
+
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
|
|
2051
|
+
</head>
|
|
2052
|
+
<body>
|
|
2053
|
+
<div id="swagger-ui"></div>
|
|
2054
|
+
<script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" charset="UTF-8"></script>
|
|
2055
|
+
<script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-standalone-preset.js" charset="UTF-8"></script>
|
|
2056
|
+
<script>
|
|
2057
|
+
window.onload = () => {
|
|
2058
|
+
// Forward the apikey query param when loading the spec and making API calls
|
|
2059
|
+
const params = new URLSearchParams(window.location.search);
|
|
2060
|
+
const apiKey = params.get('apikey');
|
|
2061
|
+
const specUrlWithKey = apiKey ? '${specUrl}?apikey=' + encodeURIComponent(apiKey) : '${specUrl}';
|
|
2062
|
+
|
|
2063
|
+
window.ui = SwaggerUIBundle({
|
|
2064
|
+
url: specUrlWithKey,
|
|
2065
|
+
dom_id: '#swagger-ui',
|
|
2066
|
+
presets: [
|
|
2067
|
+
SwaggerUIBundle.presets.apis,
|
|
2068
|
+
SwaggerUIStandalonePreset
|
|
2069
|
+
],
|
|
2070
|
+
layout: "BaseLayout",
|
|
2071
|
+
deepLinking: true,
|
|
2072
|
+
showExtensions: true,
|
|
2073
|
+
showCommonExtensions: true,
|
|
2074
|
+
// Inject x-api-key header on every request made from the Swagger UI
|
|
2075
|
+
requestInterceptor: (request) => {
|
|
2076
|
+
if (apiKey) {
|
|
2077
|
+
request.headers['x-api-key'] = apiKey;
|
|
2078
|
+
}
|
|
2079
|
+
return request;
|
|
2080
|
+
}
|
|
2081
|
+
});
|
|
2082
|
+
};
|
|
2083
|
+
</script>
|
|
2084
|
+
</body>
|
|
2085
|
+
</html>
|
|
2086
|
+
`;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
// src/auth/jexl.ts
|
|
2090
|
+
import jexl from "jexl";
|
|
2091
|
+
async function evaluateAccess(expression, context) {
|
|
2092
|
+
if (expression === void 0 || expression === null) return false;
|
|
2093
|
+
if (typeof expression === "boolean") return expression;
|
|
2094
|
+
try {
|
|
2095
|
+
const result = await jexl.eval(expression, context);
|
|
2096
|
+
return !!result;
|
|
2097
|
+
} catch (err) {
|
|
2098
|
+
console.error("[dyrected/core] Jexl evaluation failed:", err);
|
|
2099
|
+
return false;
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
// src/router.ts
|
|
2104
|
+
function accessGate(target, action) {
|
|
2105
|
+
return async (c, next) => {
|
|
2106
|
+
const user = c.get("user");
|
|
2107
|
+
const accessExpr = target.access?.[action];
|
|
2108
|
+
if (accessExpr === void 0 || accessExpr === null) {
|
|
2109
|
+
return await next();
|
|
2110
|
+
}
|
|
2111
|
+
const accessArgs = { user, req: c.req, doc: null };
|
|
2112
|
+
const allowed = await evaluateAccess(accessExpr, accessArgs);
|
|
2113
|
+
if (!allowed) {
|
|
2114
|
+
return c.json({ error: true, message: `Access denied: ${action} on ${target.slug}` }, 403);
|
|
2115
|
+
}
|
|
2116
|
+
await next();
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
async function checkAccess(access, accessArgs) {
|
|
2120
|
+
if (access === void 0 || access === null) return true;
|
|
2121
|
+
if (typeof access === "function") {
|
|
2122
|
+
try {
|
|
2123
|
+
const result = await access(accessArgs);
|
|
2124
|
+
return typeof result === "boolean" ? result : !!result;
|
|
2125
|
+
} catch (err) {
|
|
2126
|
+
console.error("[dyrected/core] Functional access check failed:", err);
|
|
2127
|
+
return false;
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
if (typeof access === "string" || typeof access === "boolean") {
|
|
2131
|
+
return evaluateAccess(access, accessArgs);
|
|
2132
|
+
}
|
|
2133
|
+
return true;
|
|
2134
|
+
}
|
|
2135
|
+
function serializeFieldForApi(f) {
|
|
2136
|
+
if (!f) return f;
|
|
2137
|
+
const serialized = { ...f };
|
|
2138
|
+
if (serialized.admin?.hooks) {
|
|
2139
|
+
const hooks = { ...serialized.admin.hooks };
|
|
2140
|
+
if (typeof hooks.onChange === "function") {
|
|
2141
|
+
hooks.onChange = hooks.onChange.toString();
|
|
2142
|
+
}
|
|
2143
|
+
if (typeof hooks.options === "function") {
|
|
2144
|
+
hooks.options = hooks.options.toString();
|
|
2145
|
+
}
|
|
2146
|
+
serialized.admin = { ...serialized.admin, hooks };
|
|
2147
|
+
}
|
|
2148
|
+
if (typeof serialized.options === "function" || serialized.options && typeof serialized.options === "object" && "resolve" in serialized.options) {
|
|
2149
|
+
serialized.options = { _dynamic: true };
|
|
2150
|
+
}
|
|
2151
|
+
if (serialized.fields) {
|
|
2152
|
+
serialized.fields = serialized.fields.map(serializeFieldForApi);
|
|
2153
|
+
}
|
|
2154
|
+
if (serialized.blocks) {
|
|
2155
|
+
serialized.blocks = serialized.blocks.map((b) => ({
|
|
2156
|
+
...b,
|
|
2157
|
+
fields: b.fields?.map(serializeFieldForApi)
|
|
2158
|
+
}));
|
|
2159
|
+
}
|
|
2160
|
+
return serialized;
|
|
2161
|
+
}
|
|
2162
|
+
function registerRoutes(app, config) {
|
|
2163
|
+
app.get("/api/schemas", optionalAuth(), async (c) => {
|
|
2164
|
+
const siteId = c.req.header("X-Site-Id");
|
|
2165
|
+
let collections = [...config.collections];
|
|
2166
|
+
let globals = [...config.globals];
|
|
2167
|
+
if (siteId && config.onSchemaFetch) {
|
|
2168
|
+
const dynamic = await config.onSchemaFetch(siteId);
|
|
2169
|
+
if (dynamic.collections) collections = [...collections, ...dynamic.collections];
|
|
2170
|
+
if (dynamic.globals) globals = [...globals, ...dynamic.globals];
|
|
2171
|
+
if (dynamic.admin) {
|
|
2172
|
+
config.admin = { ...config.admin, ...dynamic.admin };
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
const user = c.get("user");
|
|
2176
|
+
const accessArgs = { user, req: c.req, doc: null };
|
|
2177
|
+
const serializeAccess = async (access) => {
|
|
2178
|
+
if (typeof access === "string") return access;
|
|
2179
|
+
if (typeof access === "boolean") return access;
|
|
2180
|
+
return checkAccess(access, accessArgs);
|
|
2181
|
+
};
|
|
2182
|
+
const filteredCollections = await Promise.all(collections.filter((col) => !siteId || col.shared || !col.siteId || col.siteId === siteId).map(async (col) => ({
|
|
2183
|
+
slug: col.slug,
|
|
2184
|
+
labels: col.labels,
|
|
2185
|
+
access: {
|
|
2186
|
+
read: await serializeAccess(col.access?.read),
|
|
2187
|
+
create: await serializeAccess(col.access?.create),
|
|
2188
|
+
update: await serializeAccess(col.access?.update),
|
|
2189
|
+
delete: await serializeAccess(col.access?.delete)
|
|
2190
|
+
},
|
|
2191
|
+
fields: await Promise.all(col.fields.map(serializeFieldForApi).map(async (f) => ({
|
|
2192
|
+
name: f.name,
|
|
2193
|
+
type: f.type,
|
|
2194
|
+
label: f.label,
|
|
2195
|
+
required: f.required,
|
|
2196
|
+
defaultValue: f.defaultValue,
|
|
2197
|
+
options: f.options,
|
|
2198
|
+
relationTo: f.relationTo,
|
|
2199
|
+
hasMany: f.hasMany,
|
|
2200
|
+
fields: f.fields,
|
|
2201
|
+
blocks: f.blocks,
|
|
2202
|
+
admin: f.admin,
|
|
2203
|
+
access: {
|
|
2204
|
+
read: await serializeAccess(f.access?.read),
|
|
2205
|
+
update: await serializeAccess(f.access?.update)
|
|
2206
|
+
}
|
|
2207
|
+
}))),
|
|
2208
|
+
upload: !!col.upload,
|
|
2209
|
+
auth: !!col.auth,
|
|
2210
|
+
admin: col.admin
|
|
2211
|
+
})));
|
|
2212
|
+
const filteredGlobals = await Promise.all(globals.filter((glb) => !siteId || glb.shared || !glb.siteId || glb.siteId === siteId).map(async (glb) => ({
|
|
2213
|
+
slug: glb.slug,
|
|
2214
|
+
label: glb.label,
|
|
2215
|
+
access: {
|
|
2216
|
+
read: await serializeAccess(glb.access?.read),
|
|
2217
|
+
update: await serializeAccess(glb.access?.update)
|
|
2218
|
+
},
|
|
2219
|
+
fields: await Promise.all(glb.fields.map(serializeFieldForApi).map(async (f) => ({
|
|
2220
|
+
name: f.name,
|
|
2221
|
+
type: f.type,
|
|
2222
|
+
label: f.label,
|
|
2223
|
+
required: f.required,
|
|
2224
|
+
defaultValue: f.defaultValue,
|
|
2225
|
+
options: f.options,
|
|
2226
|
+
relationTo: f.relationTo,
|
|
2227
|
+
hasMany: f.hasMany,
|
|
2228
|
+
fields: f.fields,
|
|
2229
|
+
blocks: f.blocks,
|
|
2230
|
+
admin: f.admin,
|
|
2231
|
+
access: {
|
|
2232
|
+
read: await serializeAccess(f.access?.read),
|
|
2233
|
+
update: await serializeAccess(f.access?.update)
|
|
2234
|
+
}
|
|
2235
|
+
}))),
|
|
2236
|
+
admin: glb.admin
|
|
2237
|
+
})));
|
|
2238
|
+
return c.json({
|
|
2239
|
+
collections: filteredCollections,
|
|
2240
|
+
globals: filteredGlobals,
|
|
2241
|
+
admin: config.admin || {}
|
|
2242
|
+
});
|
|
2243
|
+
});
|
|
2244
|
+
app.get("/api/dyrected/options/:collection/:field", optionalAuth(), async (c) => {
|
|
2245
|
+
const { collection: colSlug, field: fieldName } = c.req.param();
|
|
2246
|
+
const siteId = c.req.header("X-Site-Id");
|
|
2247
|
+
let collections = [...config.collections];
|
|
2248
|
+
if (siteId && config.onSchemaFetch) {
|
|
2249
|
+
const dynamic = await config.onSchemaFetch(siteId);
|
|
2250
|
+
if (dynamic.collections) collections = [...collections, ...dynamic.collections];
|
|
2251
|
+
}
|
|
2252
|
+
const user = c.get("user");
|
|
2253
|
+
let collection = collections.find((col) => col.slug === colSlug);
|
|
2254
|
+
let field;
|
|
2255
|
+
if (collection) {
|
|
2256
|
+
const accessExpr = collection.access?.read;
|
|
2257
|
+
if (accessExpr !== void 0 && accessExpr !== null) {
|
|
2258
|
+
const accessArgs = { user, req: c.req, doc: null };
|
|
2259
|
+
const allowed = await checkAccess(accessExpr, accessArgs);
|
|
2260
|
+
if (!allowed) {
|
|
2261
|
+
return c.json({ error: true, message: `Access denied: read on ${colSlug}` }, 403);
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
field = collection.fields.find((f) => f.name === fieldName);
|
|
2265
|
+
} else {
|
|
2266
|
+
let globals = [...config.globals];
|
|
2267
|
+
if (siteId && config.onSchemaFetch) {
|
|
2268
|
+
const dynamic = await config.onSchemaFetch(siteId);
|
|
2269
|
+
if (dynamic.globals) globals = [...globals, ...dynamic.globals];
|
|
2270
|
+
}
|
|
2271
|
+
const glb = globals.find((g) => g.slug === colSlug);
|
|
2272
|
+
if (!glb) {
|
|
2273
|
+
return c.json({ error: true, message: `${colSlug} not found as collection or global` }, 404);
|
|
2274
|
+
}
|
|
2275
|
+
const accessExpr = glb.access?.read;
|
|
2276
|
+
if (accessExpr !== void 0 && accessExpr !== null) {
|
|
2277
|
+
const accessArgs = { user, req: c.req, doc: null };
|
|
2278
|
+
const allowed = await checkAccess(accessExpr, accessArgs);
|
|
2279
|
+
if (!allowed) {
|
|
2280
|
+
return c.json({ error: true, message: `Access denied: read on global ${colSlug}` }, 403);
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
field = glb.fields.find((f) => f.name === fieldName);
|
|
2284
|
+
}
|
|
2285
|
+
if (!field) {
|
|
2286
|
+
return c.json({ error: true, message: `Field ${fieldName} not found in ${colSlug}` }, 404);
|
|
2287
|
+
}
|
|
2288
|
+
let resolver;
|
|
2289
|
+
if (typeof field.options === "function") {
|
|
2290
|
+
resolver = field.options;
|
|
2291
|
+
} else if (field.options && typeof field.options === "object" && "resolve" in field.options) {
|
|
2292
|
+
resolver = field.options.resolve;
|
|
2293
|
+
}
|
|
2294
|
+
if (!resolver) {
|
|
2295
|
+
return c.json({ error: true, message: `Field ${fieldName} in ${colSlug} is not dynamic` }, 400);
|
|
2296
|
+
}
|
|
2297
|
+
try {
|
|
2298
|
+
const db = c.get("db") || config.db;
|
|
2299
|
+
const queryParams = c.req.query();
|
|
2300
|
+
const reqContext = {
|
|
2301
|
+
query: queryParams,
|
|
2302
|
+
headers: c.req.header(),
|
|
2303
|
+
raw: c.req.raw
|
|
2304
|
+
};
|
|
2305
|
+
const result = await resolver({
|
|
2306
|
+
db,
|
|
2307
|
+
user,
|
|
2308
|
+
req: reqContext
|
|
2309
|
+
});
|
|
2310
|
+
return c.json(result);
|
|
2311
|
+
} catch (err) {
|
|
2312
|
+
console.error(`[dyrected/core] Failed to resolve dynamic options for field ${fieldName}:`, err);
|
|
2313
|
+
return c.json({ error: true, message: err.message || "Failed to resolve dynamic options" }, 500);
|
|
2314
|
+
}
|
|
2315
|
+
});
|
|
2316
|
+
app.get("/api/openapi.json", (c) => {
|
|
2317
|
+
return c.json(generateOpenApi(config));
|
|
2318
|
+
});
|
|
2319
|
+
app.get("/api/docs", (c) => {
|
|
2320
|
+
return c.html(getSwaggerHtml());
|
|
2321
|
+
});
|
|
2322
|
+
app.get("/api/media/:filename{.+$}", async (c) => {
|
|
2323
|
+
const mediaController = new MediaController("media");
|
|
2324
|
+
return mediaController.serve(c);
|
|
2325
|
+
});
|
|
2326
|
+
app.get("/media/:filename{.+$}", async (c) => {
|
|
2327
|
+
const mediaController = new MediaController("media");
|
|
2328
|
+
return mediaController.serve(c);
|
|
2329
|
+
});
|
|
2330
|
+
if (config.storage) {
|
|
2331
|
+
const uploadCollections = config.collections.filter((c) => c.upload);
|
|
2332
|
+
for (const col of uploadCollections) {
|
|
2333
|
+
const mediaController = new MediaController(col.slug);
|
|
2334
|
+
const prefix = `/api/collections/${col.slug}`;
|
|
2335
|
+
app.get(`${prefix}/media`, accessGate(col, "read"), (c) => mediaController.find(c));
|
|
2336
|
+
app.get(`${prefix}/media/:filename{.+$}`, (c) => mediaController.serve(c));
|
|
2337
|
+
app.post(`${prefix}/media`, accessGate(col, "create"), (c) => mediaController.upload(c));
|
|
2338
|
+
app.delete(`${prefix}/media/:id`, accessGate(col, "delete"), (c) => mediaController.delete(c));
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
for (const collection of config.collections) {
|
|
2342
|
+
if (!collection.auth) continue;
|
|
2343
|
+
const path = `/api/collections/${collection.slug}`;
|
|
2344
|
+
const authController = new AuthController(collection);
|
|
2345
|
+
app.post(`${path}/login`, (c) => authController.login(c));
|
|
2346
|
+
app.post(`${path}/logout`, (c) => authController.logout(c));
|
|
2347
|
+
app.get(`${path}/init`, (c) => authController.init(c));
|
|
2348
|
+
app.post(`${path}/first-user`, (c) => authController.registerFirstUser(c));
|
|
2349
|
+
app.get(`${path}/me`, requireAuth(), (c) => authController.me(c));
|
|
2350
|
+
app.post(`${path}/refresh-token`, requireAuth(), (c) => authController.refreshToken(c));
|
|
2351
|
+
app.post(`${path}/forgot-password`, (c) => authController.forgotPassword(c));
|
|
2352
|
+
app.post(`${path}/reset-password`, (c) => authController.resetPassword(c));
|
|
2353
|
+
app.post(`${path}/invite`, requireAuth(), (c) => authController.invite(c));
|
|
2354
|
+
app.post(`${path}/accept-invite`, (c) => authController.acceptInvite(c));
|
|
2355
|
+
}
|
|
2356
|
+
for (const collection of config.collections) {
|
|
2357
|
+
const path = `/api/collections/${collection.slug}`;
|
|
2358
|
+
const controller = new CollectionController(collection);
|
|
2359
|
+
app.get(path, accessGate(collection, "read"), (c) => controller.find(c));
|
|
2360
|
+
app.post(path, accessGate(collection, "create"), (c) => controller.create(c));
|
|
2361
|
+
app.post(`${path}/media`, accessGate(collection, "create"), (c) => controller.create(c));
|
|
2362
|
+
app.delete(`${path}/delete-many`, accessGate(collection, "delete"), (c) => controller.deleteMany(c));
|
|
2363
|
+
app.get(`${path}/:id`, accessGate(collection, "read"), (c) => controller.findOne(c));
|
|
2364
|
+
app.patch(`${path}/:id`, accessGate(collection, "update"), (c) => controller.update(c));
|
|
2365
|
+
app.delete(`${path}/:id`, accessGate(collection, "delete"), (c) => controller.delete(c));
|
|
2366
|
+
app.post(`${path}/seed`, (c) => controller.seed(c));
|
|
2367
|
+
if (collection.auth) {
|
|
2368
|
+
app.post(`${path}/:id/change-password`, requireAuth(), (c) => controller.changePassword(c));
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
for (const global of config.globals) {
|
|
2372
|
+
const path = `/api/globals/${global.slug}`;
|
|
2373
|
+
const controller = new GlobalController(global);
|
|
2374
|
+
app.get(path, accessGate(global, "read"), (c) => controller.get(c));
|
|
2375
|
+
app.patch(path, accessGate(global, "update"), (c) => controller.update(c));
|
|
2376
|
+
app.post(`${path}/seed`, (c) => controller.seed(c));
|
|
2377
|
+
}
|
|
2378
|
+
const previewController = new PreviewController();
|
|
2379
|
+
app.post("/api/preview-token", requireAuth(), (c) => previewController.createToken(c));
|
|
2380
|
+
app.get("/api/preview-data", (c) => previewController.getData(c));
|
|
2381
|
+
app.all("/api/collections/:slug/:id?", async (c) => {
|
|
2382
|
+
const slug = c.req.param("slug");
|
|
2383
|
+
const id = c.req.param("id");
|
|
2384
|
+
const siteId = c.req.header("X-Site-Id") || c.get("siteId");
|
|
2385
|
+
const config2 = c.get("config");
|
|
2386
|
+
if (config2.collections.some((col) => col.slug === slug)) {
|
|
2387
|
+
return c.json({ message: "Method Not Allowed" }, 405);
|
|
2388
|
+
}
|
|
2389
|
+
if (config2.onSchemaFetch && siteId) {
|
|
2390
|
+
const dynamic = await config2.onSchemaFetch(siteId);
|
|
2391
|
+
let collection = dynamic.collections?.find((col) => col.slug === slug);
|
|
2392
|
+
if (!collection && slug === "media") {
|
|
2393
|
+
collection = {
|
|
2394
|
+
slug: "media",
|
|
2395
|
+
labels: { singular: "Media", plural: "Media" },
|
|
2396
|
+
upload: true,
|
|
2397
|
+
fields: []
|
|
2398
|
+
};
|
|
2399
|
+
}
|
|
2400
|
+
if (collection) {
|
|
2401
|
+
if (collection.auth && id) {
|
|
2402
|
+
const authController = new AuthController(collection);
|
|
2403
|
+
const method2 = c.req.method;
|
|
2404
|
+
if (method2 === "POST" && id === "login") return authController.login(c);
|
|
2405
|
+
if (method2 === "POST" && id === "logout") return authController.logout(c);
|
|
2406
|
+
if (method2 === "GET" && id === "me") return authController.me(c);
|
|
2407
|
+
if (method2 === "POST" && id === "refresh-token") return authController.refreshToken(c);
|
|
2408
|
+
if (method2 === "POST" && id === "forgot-password") return authController.forgotPassword(c);
|
|
2409
|
+
if (method2 === "POST" && id === "reset-password") return authController.resetPassword(c);
|
|
2410
|
+
}
|
|
2411
|
+
const controller = new CollectionController(collection);
|
|
2412
|
+
const method = c.req.method;
|
|
2413
|
+
if (id) {
|
|
2414
|
+
if (method === "GET") return controller.findOne(c);
|
|
2415
|
+
if (method === "PATCH") return controller.update(c);
|
|
2416
|
+
if (method === "DELETE" && id === "delete-many") return controller.deleteMany(c);
|
|
2417
|
+
if (method === "DELETE") return controller.delete(c);
|
|
2418
|
+
if (method === "POST" && id === "media") return controller.create(c);
|
|
2419
|
+
if (method === "POST" && id === "seed") return controller.seed(c);
|
|
2420
|
+
} else {
|
|
2421
|
+
if (method === "GET") return controller.find(c);
|
|
2422
|
+
if (method === "POST") return controller.create(c);
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
return c.json({ message: `Collection "${slug}" not found` }, 404);
|
|
2427
|
+
});
|
|
2428
|
+
app.all("/api/globals/:slug", async (c) => {
|
|
2429
|
+
const slug = c.req.param("slug");
|
|
2430
|
+
const siteId = c.req.header("X-Site-Id") || c.get("siteId");
|
|
2431
|
+
const config2 = c.get("config");
|
|
2432
|
+
if (config2.globals.some((glb) => glb.slug === slug)) {
|
|
2433
|
+
return c.json({ message: "Method Not Allowed" }, 405);
|
|
2434
|
+
}
|
|
2435
|
+
if (config2.onSchemaFetch && siteId) {
|
|
2436
|
+
const dynamic = await config2.onSchemaFetch(siteId);
|
|
2437
|
+
const global = dynamic.globals?.find((glb) => glb.slug === slug);
|
|
2438
|
+
if (global) {
|
|
2439
|
+
const controller = new GlobalController(global);
|
|
2440
|
+
if (c.req.method === "GET") return controller.get(c);
|
|
2441
|
+
if (c.req.method === "PATCH") return controller.update(c);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
return c.json({ message: `Global "${slug}" not found` }, 404);
|
|
2445
|
+
});
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
// src/app.ts
|
|
2449
|
+
import { Hono } from "hono";
|
|
2450
|
+
import { cors } from "hono/cors";
|
|
2451
|
+
import { requestId } from "hono/request-id";
|
|
2452
|
+
async function createDyrectedApp(rawConfig) {
|
|
2453
|
+
const config = normalizeConfig(rawConfig);
|
|
2454
|
+
const app = new Hono();
|
|
2455
|
+
if (config.db?.sync) {
|
|
2456
|
+
await config.db.sync(config.collections, config.globals);
|
|
2457
|
+
}
|
|
2458
|
+
app.use("*", requestId());
|
|
2459
|
+
app.use("*", optionalAuth());
|
|
2460
|
+
app.use("*", async (c, next) => {
|
|
2461
|
+
const start = Date.now();
|
|
2462
|
+
await next();
|
|
2463
|
+
const ms = Date.now() - start;
|
|
2464
|
+
console.log(`[dyrected/api] ${c.req.method} ${c.req.path} ${c.res.status} - ${ms}ms`);
|
|
2465
|
+
});
|
|
2466
|
+
app.use("*", cors());
|
|
2467
|
+
app.use("*", async (c, next) => {
|
|
2468
|
+
c.set("config", config);
|
|
2469
|
+
if (!c.get("siteId")) {
|
|
2470
|
+
c.set("siteId", "default");
|
|
2471
|
+
}
|
|
2472
|
+
await next();
|
|
2473
|
+
});
|
|
2474
|
+
app.get("/health", (c) => c.json({ status: "ok", version: "0.0.1" }));
|
|
2475
|
+
app.get("/routes", (c) => {
|
|
2476
|
+
const routes = app.routes.map((r) => ({ method: r.method, path: r.path }));
|
|
2477
|
+
return c.json({ routes });
|
|
2478
|
+
});
|
|
2479
|
+
app.onError((err, c) => {
|
|
2480
|
+
console.error(`[dyrected/core] Uncaught Error:`, err);
|
|
2481
|
+
return c.json({
|
|
2482
|
+
message: err.message || "Internal Server Error",
|
|
2483
|
+
stack: process.env.NODE_ENV === "development" ? err.stack : void 0
|
|
2484
|
+
}, 500);
|
|
2485
|
+
});
|
|
2486
|
+
registerRoutes(app, config);
|
|
2487
|
+
return app;
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
export {
|
|
2491
|
+
normalizeConfig,
|
|
2492
|
+
runCollectionHooks,
|
|
2493
|
+
executeFieldBeforeChange,
|
|
2494
|
+
executeFieldAfterRead,
|
|
2495
|
+
CollectionController,
|
|
2496
|
+
GlobalController,
|
|
2497
|
+
MediaController,
|
|
2498
|
+
AuthController,
|
|
2499
|
+
PreviewController,
|
|
2500
|
+
registerRoutes,
|
|
2501
|
+
createDyrectedApp
|
|
2502
|
+
};
|