@kidecms/core 0.31.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/api.ts +234 -47
- package/core/auth-engine.ts +16 -1
- package/core/generator.ts +4 -0
- package/core/index.ts +2 -1
- package/internals/mcp.ts +3 -2
- package/package.json +1 -1
- package/routes/admin/forgot-password.astro +34 -14
- package/routes/admin/login.astro +2 -2
- package/routes/api/auth/forgot-password.ts +5 -0
package/core/api.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { and, asc, desc, eq, inArray, like, lte, ne, or, sql } from "drizzle-orm";
|
|
1
|
+
import { and, asc, desc, eq, inArray, like, lte, ne, or, sql, type SQL } from "drizzle-orm";
|
|
2
2
|
import { setCloudflareImageMode } from "./image";
|
|
3
3
|
import { nanoid } from "nanoid";
|
|
4
4
|
|
|
@@ -22,7 +22,24 @@ import { drainTasks, enqueueTask, pruneTasks, tickSchedules, type EnqueueTaskOpt
|
|
|
22
22
|
import { cloneValue, createRichTextFromPlainText, slugify } from "./values";
|
|
23
23
|
import { dispatchWebhooks } from "./webhooks";
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Operators for a `where` key. Scalar fields: `ne`, `gt`, `gte`, `lt`, `lte`, `in`,
|
|
27
|
+
* `notIn` (`ne: null` = "is set"). Array fields (`hasMany` relations, `array`):
|
|
28
|
+
* `contains` (has this item), `in` (has any of), `notIn` (has none of).
|
|
29
|
+
*/
|
|
30
|
+
export type WhereOperators = {
|
|
31
|
+
ne?: unknown;
|
|
32
|
+
gt?: unknown;
|
|
33
|
+
gte?: unknown;
|
|
34
|
+
lt?: unknown;
|
|
35
|
+
lte?: unknown;
|
|
36
|
+
in?: unknown[];
|
|
37
|
+
notIn?: unknown[];
|
|
38
|
+
contains?: unknown;
|
|
39
|
+
};
|
|
40
|
+
|
|
25
41
|
export type FindOptions = {
|
|
42
|
+
/** A plain value means equality; a `WhereOperators` object ANDs its operators. */
|
|
26
43
|
where?: Record<string, unknown>;
|
|
27
44
|
sort?: {
|
|
28
45
|
field: string;
|
|
@@ -78,6 +95,184 @@ const isJsonField = (field: FieldConfig) =>
|
|
|
78
95
|
field.type === "blocks" ||
|
|
79
96
|
(field.type === "relation" && field.hasMany);
|
|
80
97
|
|
|
98
|
+
const isArrayValuedField = (field: FieldConfig | undefined) =>
|
|
99
|
+
!!field && (field.type === "array" || (field.type === "relation" && !!field.hasMany));
|
|
100
|
+
|
|
101
|
+
const WHERE_OPERATORS = new Set(["ne", "gt", "gte", "lt", "lte", "in", "notIn", "contains"]);
|
|
102
|
+
const SCALAR_OPERATORS = new Set(["ne", "gt", "gte", "lt", "lte", "in", "notIn"]);
|
|
103
|
+
const ARRAY_OPERATORS = new Set(["contains", "in", "notIn"]);
|
|
104
|
+
|
|
105
|
+
const isOperatorObject = (value: unknown): value is Record<string, unknown> =>
|
|
106
|
+
typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
|
|
107
|
+
|
|
108
|
+
// Raw SQL skips drizzle's column mapper, so booleans must be bound as 0/1 and dates as ISO text.
|
|
109
|
+
const bindWhereValue = (value: unknown) => {
|
|
110
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
111
|
+
if (value instanceof Date) return value.toISOString();
|
|
112
|
+
if (typeof value === "object" && value !== null) return JSON.stringify(value);
|
|
113
|
+
return value;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* A field's value as published reads see it: the `_published` snapshot holds the live
|
|
118
|
+
* values while a published document has pending draft edits in the main row.
|
|
119
|
+
*/
|
|
120
|
+
const publishedValue = (collection: CollectionConfig, tables: any, key: string): unknown => {
|
|
121
|
+
const field = collection.fields[key];
|
|
122
|
+
if (!tables.main._published || !field) return tables.main[key];
|
|
123
|
+
const path = `$.${key}`;
|
|
124
|
+
const value = sql`(CASE WHEN json_type(${tables.main._published}, ${path}) IS NOT NULL THEN json_extract(${tables.main._published}, ${path}) ELSE ${tables.main[key]} END)`;
|
|
125
|
+
// A CASE has no column affinity; the CAST restores it so "3" still matches a number field.
|
|
126
|
+
if (isJsonField(field)) return value;
|
|
127
|
+
return field.type === "number" || field.type === "boolean"
|
|
128
|
+
? sql`CAST(${value} AS NUMERIC)`
|
|
129
|
+
: sql`CAST(${value} AS TEXT)`;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const operatorCondition = (column: unknown, op: string, value: unknown, arrayValued: boolean): SQL => {
|
|
133
|
+
const list = () =>
|
|
134
|
+
sql.join(
|
|
135
|
+
(value as unknown[]).map((item) => sql`${bindWhereValue(item)}`),
|
|
136
|
+
sql`, `,
|
|
137
|
+
);
|
|
138
|
+
if (arrayValued) {
|
|
139
|
+
const members = (match: SQL) => sql`EXISTS (SELECT 1 FROM json_each(${column}) WHERE json_each.value ${match})`;
|
|
140
|
+
if (op === "contains") return members(sql`= ${bindWhereValue(value)}`);
|
|
141
|
+
if (op === "in") return (value as unknown[]).length === 0 ? sql`0` : members(sql`IN (${list()})`);
|
|
142
|
+
return (value as unknown[]).length === 0 ? sql`1` : sql`NOT ${members(sql`IN (${list()})`)}`;
|
|
143
|
+
}
|
|
144
|
+
switch (op) {
|
|
145
|
+
case "ne":
|
|
146
|
+
return value === null
|
|
147
|
+
? sql`${column} IS NOT NULL`
|
|
148
|
+
: sql`(${column} IS NULL OR ${column} <> ${bindWhereValue(value)})`;
|
|
149
|
+
case "gt":
|
|
150
|
+
return sql`${column} > ${bindWhereValue(value)}`;
|
|
151
|
+
case "gte":
|
|
152
|
+
return sql`${column} >= ${bindWhereValue(value)}`;
|
|
153
|
+
case "lt":
|
|
154
|
+
return sql`${column} < ${bindWhereValue(value)}`;
|
|
155
|
+
case "lte":
|
|
156
|
+
return sql`${column} <= ${bindWhereValue(value)}`;
|
|
157
|
+
case "in":
|
|
158
|
+
return (value as unknown[]).length === 0 ? sql`0` : sql`${column} IN (${list()})`;
|
|
159
|
+
default:
|
|
160
|
+
return (value as unknown[]).length === 0 ? sql`1` : sql`(${column} IS NULL OR ${column} NOT IN (${list()}))`;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const SYSTEM_FILTER_COLUMNS = new Set([
|
|
165
|
+
"_id",
|
|
166
|
+
"_status",
|
|
167
|
+
"_createdAt",
|
|
168
|
+
"_updatedAt",
|
|
169
|
+
"_publishedAt",
|
|
170
|
+
"_publishAt",
|
|
171
|
+
"_unpublishAt",
|
|
172
|
+
"_sourceLocale",
|
|
173
|
+
]);
|
|
174
|
+
|
|
175
|
+
/** Columns an untrusted caller must not range-probe: credentials, internals and fields behind a read rule. */
|
|
176
|
+
const isHiddenFromFilters = (collection: CollectionConfig, key: string) => {
|
|
177
|
+
const field = collection.fields[key];
|
|
178
|
+
if (!field) return !SYSTEM_FILTER_COLUMNS.has(key);
|
|
179
|
+
return (!!collection.auth && key === "password") || !!field.access?.read;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Turn a `where` filter into SQL conditions. A plain value is equality (unchanged
|
|
184
|
+
* behavior); an object is a set of operators ANDed together. Keys that aren't
|
|
185
|
+
* columns are ignored. With `locale`, translatable fields match their effective
|
|
186
|
+
* (translation-overlaid) value; with `published`, fields match the published snapshot.
|
|
187
|
+
*/
|
|
188
|
+
const buildWhereConditions = (
|
|
189
|
+
collection: CollectionConfig,
|
|
190
|
+
tables: any,
|
|
191
|
+
where: Record<string, unknown> | undefined,
|
|
192
|
+
options: { locale?: string; system?: boolean; published?: boolean },
|
|
193
|
+
): { conditions: SQL[]; byCandidates: boolean } => {
|
|
194
|
+
const conditions: SQL[] = [];
|
|
195
|
+
let byCandidates = false;
|
|
196
|
+
if (!where) return { conditions, byCandidates };
|
|
197
|
+
const translatableFields = new Set(getTranslatableFieldNames(collection));
|
|
198
|
+
|
|
199
|
+
for (const [key, value] of Object.entries(where)) {
|
|
200
|
+
if (!(key in tables.main)) continue;
|
|
201
|
+
const field = collection.fields[key];
|
|
202
|
+
const arrayValued = isArrayValuedField(field);
|
|
203
|
+
|
|
204
|
+
let match: (column: unknown) => SQL;
|
|
205
|
+
if (isOperatorObject(value)) {
|
|
206
|
+
const ops = Object.entries(value).filter(([, operand]) => operand !== undefined);
|
|
207
|
+
// Skipping it would widen the filter — and deleteMany would clear the collection.
|
|
208
|
+
if (ops.length === 0) throw new Error(`Empty where operator object on ${collection.slug}.${key}.`);
|
|
209
|
+
if (!options.system && isHiddenFromFilters(collection, key)) {
|
|
210
|
+
throw new Error(`Cannot filter ${collection.slug}.${key} with operators.`);
|
|
211
|
+
}
|
|
212
|
+
if (field && !arrayValued && isJsonField(field)) {
|
|
213
|
+
throw new Error(`Field ${collection.slug}.${key} (${field.type}) doesn't support where operators.`);
|
|
214
|
+
}
|
|
215
|
+
const allowed = arrayValued ? ARRAY_OPERATORS : SCALAR_OPERATORS;
|
|
216
|
+
for (const [op] of ops) {
|
|
217
|
+
if (!WHERE_OPERATORS.has(op)) throw new Error(`Unknown where operator "${op}" on ${collection.slug}.${key}.`);
|
|
218
|
+
if (!allowed.has(op)) {
|
|
219
|
+
throw new Error(
|
|
220
|
+
`where operator "${op}" isn't supported on ${arrayValued ? "array" : "scalar"} field ${collection.slug}.${key}.`,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
const isList = op === "in" || op === "notIn";
|
|
224
|
+
if (isList !== Array.isArray(value[op])) {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`where operator "${op}" on ${collection.slug}.${key} expects ${isList ? "an array" : "a single value"}.`,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
if (isList && (value[op] as unknown[]).some((item) => item === null || item === undefined)) {
|
|
230
|
+
throw new Error(`where operator "${op}" on ${collection.slug}.${key} can't list null; use ne: null.`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
match = (column) => {
|
|
234
|
+
const parts = ops.map(([op, operand]) => operatorCondition(column, op, operand, arrayValued));
|
|
235
|
+
return parts.length === 1 ? parts[0] : and(...parts)!;
|
|
236
|
+
};
|
|
237
|
+
} else {
|
|
238
|
+
match = (column) => sql`${column} = ${bindWhereValue(value)}`;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const mainValue = options.published ? publishedValue(collection, tables, key) : tables.main[key];
|
|
242
|
+
|
|
243
|
+
if (options.locale && tables.translations && translatableFields.has(key)) {
|
|
244
|
+
// Translatable fields live in the translations table for non-default locales:
|
|
245
|
+
// match the translation when one exists for this locale, the main-table value
|
|
246
|
+
// otherwise. Without this, e.g. findOne({ slug, locale: "en" }) can never match
|
|
247
|
+
// a translated slug.
|
|
248
|
+
const tr = tables.translations;
|
|
249
|
+
conditions.push(
|
|
250
|
+
sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${match(tr[key])}) OR (${match(mainValue)} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
|
|
251
|
+
);
|
|
252
|
+
} else if (mainValue !== tables.main[key]) {
|
|
253
|
+
// Candidates come from the column's own index plus the few documents with
|
|
254
|
+
// pending drafts (pending index; `> ''` keeps it a range seek); the
|
|
255
|
+
// snapshot-aware match then decides.
|
|
256
|
+
const main = tables.main;
|
|
257
|
+
byCandidates = true;
|
|
258
|
+
conditions.push(
|
|
259
|
+
sql`${main._id} IN (SELECT ${main._id} FROM ${main} WHERE ${match(main[key])} UNION ALL SELECT ${main._id} FROM ${main} WHERE ${main._published} > '')`,
|
|
260
|
+
match(mainValue),
|
|
261
|
+
);
|
|
262
|
+
} else if (isOperatorObject(value)) {
|
|
263
|
+
conditions.push(match(tables.main[key]));
|
|
264
|
+
} else {
|
|
265
|
+
conditions.push(eq(tables.main[key], value));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return { conditions, byCandidates };
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// With snapshot candidates in play, the unary + keeps SQLite (no ANALYZE stats) from
|
|
272
|
+
// picking the low-selectivity _status index over the candidate _id lookup.
|
|
273
|
+
const statusCondition = (tables: any, status: string, byCandidates: boolean) =>
|
|
274
|
+
byCandidates ? sql`+${tables.main._status} = ${status}` : eq(tables.main._status, status);
|
|
275
|
+
|
|
81
276
|
const ensureCollection = (config: CMSConfig, slug: string) => {
|
|
82
277
|
const collection = getCollectionMap(config)[slug];
|
|
83
278
|
if (!collection) {
|
|
@@ -365,12 +560,21 @@ const stripUnreadableFields = async (
|
|
|
365
560
|
) => {
|
|
366
561
|
if (context._system) return doc;
|
|
367
562
|
const accessCtx = { user: context.user ?? null, doc, operation: "read", collection: collection.slug };
|
|
368
|
-
|
|
563
|
+
const denied: string[] = [];
|
|
369
564
|
for (const [fieldName, field] of Object.entries(collection.fields)) {
|
|
370
|
-
if (
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
565
|
+
if (field.access?.read && !(await field.access.read(accessCtx))) denied.push(fieldName);
|
|
566
|
+
}
|
|
567
|
+
if (denied.length === 0) return doc;
|
|
568
|
+
const result = { ...doc };
|
|
569
|
+
for (const fieldName of denied) delete result[fieldName];
|
|
570
|
+
// The pending-draft snapshot carries the same fields; strip them there too.
|
|
571
|
+
if (typeof result._published === "string") {
|
|
572
|
+
try {
|
|
573
|
+
const snapshot = JSON.parse(result._published);
|
|
574
|
+
for (const fieldName of denied) delete snapshot[fieldName];
|
|
575
|
+
result._published = JSON.stringify(snapshot);
|
|
576
|
+
} catch {
|
|
577
|
+
delete result._published;
|
|
374
578
|
}
|
|
375
579
|
}
|
|
376
580
|
return result;
|
|
@@ -601,31 +805,17 @@ export const createCms = (config: CMSConfig) => {
|
|
|
601
805
|
const tables = await getTableRefs(slug);
|
|
602
806
|
const status = options.status ?? (collection.drafts ? "published" : "any");
|
|
603
807
|
const filterAfterReadAccess = hasReadRule(collection) && !context._system;
|
|
808
|
+
const published = status === "published" && !!collection.drafts;
|
|
809
|
+
const readValue = (key: string) => (published ? publishedValue(collection, tables, key) : tables.main[key]);
|
|
604
810
|
|
|
605
|
-
const
|
|
811
|
+
const where = buildWhereConditions(collection, tables, options.where, {
|
|
812
|
+
locale: options.locale,
|
|
813
|
+
system: context._system,
|
|
814
|
+
published,
|
|
815
|
+
});
|
|
816
|
+
const conditions: any[] = [...where.conditions];
|
|
606
817
|
if (status !== "any" && collection.drafts) {
|
|
607
|
-
conditions.
|
|
608
|
-
}
|
|
609
|
-
if (options.where) {
|
|
610
|
-
const translatableFields = new Set(getTranslatableFieldNames(collection));
|
|
611
|
-
for (const [key, value] of Object.entries(options.where)) {
|
|
612
|
-
if (!(key in tables.main)) continue;
|
|
613
|
-
if (options.locale && tables.translations && translatableFields.has(key)) {
|
|
614
|
-
// Translatable fields live in the translations table for non-default
|
|
615
|
-
// locales: match the effective (overlaid) value — the translation when
|
|
616
|
-
// one exists for this locale, the main-table value otherwise. Without
|
|
617
|
-
// this, e.g. findOne({ slug, locale: "en" }) can never match a
|
|
618
|
-
// translated slug.
|
|
619
|
-
const tr = tables.translations;
|
|
620
|
-
// Raw SQL skips drizzle's column mapper, so booleans must be bound as 0/1.
|
|
621
|
-
const bound = typeof value === "boolean" ? (value ? 1 : 0) : value;
|
|
622
|
-
conditions.push(
|
|
623
|
-
sql`(EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} = ${bound}) OR (${tables.main[key]} = ${bound} AND NOT EXISTS (SELECT 1 FROM ${tr} WHERE ${tr._entityId} = ${tables.main._id} AND ${tr._languageCode} = ${options.locale} AND ${tr[key]} IS NOT NULL)))`,
|
|
624
|
-
);
|
|
625
|
-
} else {
|
|
626
|
-
conditions.push(eq(tables.main[key], value));
|
|
627
|
-
}
|
|
628
|
-
}
|
|
818
|
+
conditions.unshift(statusCondition(tables, status, where.byCandidates));
|
|
629
819
|
}
|
|
630
820
|
const availability = availabilityCondition(tables, options);
|
|
631
821
|
if (availability) conditions.push(availability);
|
|
@@ -636,7 +826,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
636
826
|
const searchConditions = Object.entries(collection.fields)
|
|
637
827
|
.filter(([, field]) => searchableTypes.has(field.type))
|
|
638
828
|
.filter(([name]) => name in tables.main)
|
|
639
|
-
.map(([name]) => like(sql`lower(${
|
|
829
|
+
.map(([name]) => like(sql`lower(${readValue(name)})`, searchTerm));
|
|
640
830
|
if (searchConditions.length > 0) {
|
|
641
831
|
conditions.push(or(...searchConditions)!);
|
|
642
832
|
}
|
|
@@ -648,8 +838,8 @@ export const createCms = (config: CMSConfig) => {
|
|
|
648
838
|
}
|
|
649
839
|
|
|
650
840
|
if (options.sort) {
|
|
651
|
-
|
|
652
|
-
|
|
841
|
+
if (tables.main[options.sort.field]) {
|
|
842
|
+
const col = readValue(options.sort.field) as any;
|
|
653
843
|
query = query.orderBy(options.sort.direction === "desc" ? desc(col) : asc(col)) as any;
|
|
654
844
|
}
|
|
655
845
|
}
|
|
@@ -1045,7 +1235,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1045
1235
|
},
|
|
1046
1236
|
|
|
1047
1237
|
/**
|
|
1048
|
-
* Delete every document matching `filter` (
|
|
1238
|
+
* Delete every document matching `filter` (same shape as `find`'s `where`;
|
|
1049
1239
|
* empty filter clears the whole collection), along with their translation,
|
|
1050
1240
|
* version and search-index rows. Returns the number of documents removed.
|
|
1051
1241
|
*
|
|
@@ -1062,10 +1252,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1062
1252
|
const db = await getDb();
|
|
1063
1253
|
const tables = await getTableRefs(slug);
|
|
1064
1254
|
|
|
1065
|
-
const conditions
|
|
1066
|
-
for (const [key, value] of Object.entries(filter)) {
|
|
1067
|
-
if (key in tables.main) conditions.push(eq(tables.main[key], value));
|
|
1068
|
-
}
|
|
1255
|
+
const { conditions } = buildWhereConditions(collection, tables, filter, { system: context._system });
|
|
1069
1256
|
let idQuery = db.select({ _id: tables.main._id }).from(tables.main);
|
|
1070
1257
|
if (conditions.length > 0) {
|
|
1071
1258
|
idQuery = idQuery.where(conditions.length === 1 ? conditions[0] : and(...conditions)) as any;
|
|
@@ -1275,17 +1462,17 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1275
1462
|
const db = await getDb();
|
|
1276
1463
|
const tables = await getTableRefs(slug);
|
|
1277
1464
|
const status = filter.status ?? (collection.drafts ? "published" : "any");
|
|
1465
|
+
const published = status === "published" && !!collection.drafts;
|
|
1466
|
+
const readValue = (key: string) => (published ? publishedValue(collection, tables, key) : tables.main[key]);
|
|
1278
1467
|
|
|
1279
|
-
const
|
|
1468
|
+
const where = buildWhereConditions(collection, tables, filter.where, {
|
|
1469
|
+
locale: filter.locale,
|
|
1470
|
+
system: context._system,
|
|
1471
|
+
published,
|
|
1472
|
+
});
|
|
1473
|
+
const conditions: any[] = [...where.conditions];
|
|
1280
1474
|
if (status !== "any" && collection.drafts) {
|
|
1281
|
-
conditions.
|
|
1282
|
-
}
|
|
1283
|
-
if (filter.where) {
|
|
1284
|
-
for (const [key, value] of Object.entries(filter.where)) {
|
|
1285
|
-
if (key in tables.main) {
|
|
1286
|
-
conditions.push(eq(tables.main[key], value));
|
|
1287
|
-
}
|
|
1288
|
-
}
|
|
1475
|
+
conditions.unshift(statusCondition(tables, status, where.byCandidates));
|
|
1289
1476
|
}
|
|
1290
1477
|
const availability = availabilityCondition(tables, filter);
|
|
1291
1478
|
if (availability) conditions.push(availability);
|
|
@@ -1295,7 +1482,7 @@ export const createCms = (config: CMSConfig) => {
|
|
|
1295
1482
|
const searchConditions = Object.entries(collection.fields)
|
|
1296
1483
|
.filter(([, field]) => searchableTypes.has(field.type))
|
|
1297
1484
|
.filter(([name]) => name in tables.main)
|
|
1298
|
-
.map(([name]) => like(sql`lower(${
|
|
1485
|
+
.map(([name]) => like(sql`lower(${readValue(name)})`, searchTerm));
|
|
1299
1486
|
if (searchConditions.length > 0) {
|
|
1300
1487
|
conditions.push(or(...searchConditions)!);
|
|
1301
1488
|
}
|
package/core/auth-engine.ts
CHANGED
|
@@ -251,6 +251,15 @@ const toGenericOAuth = (provider: AdminAuthSsoProviderConfig): GenericOAuthConfi
|
|
|
251
251
|
} as GenericOAuthConfig;
|
|
252
252
|
};
|
|
253
253
|
|
|
254
|
+
/**
|
|
255
|
+
* How a password reset link reaches the user: by email when an adapter is configured, in the
|
|
256
|
+
* dev server's terminal during development, otherwise not at all (the flow is then hidden).
|
|
257
|
+
*/
|
|
258
|
+
export const passwordResetDelivery = (): "email" | "console" | null => {
|
|
259
|
+
if (getEmail().isEmailConfigured()) return "email";
|
|
260
|
+
return process.env.NODE_ENV === "development" ? "console" : null;
|
|
261
|
+
};
|
|
262
|
+
|
|
254
263
|
const DEV_SECRET = "kide-development-secret-do-not-use-in-production";
|
|
255
264
|
let warnedDevSecret = false;
|
|
256
265
|
|
|
@@ -326,7 +335,13 @@ export const buildAdminAuthOptions = (config: CMSConfig, deps: AuthDeps = {}): B
|
|
|
326
335
|
sendResetPassword: async ({ user, token }) => {
|
|
327
336
|
const resetUrl = new URL("/admin/reset-password", baseURL);
|
|
328
337
|
resetUrl.searchParams.set("token", token);
|
|
329
|
-
|
|
338
|
+
const delivery = passwordResetDelivery();
|
|
339
|
+
if (delivery === "email") {
|
|
340
|
+
const sent = await getEmail().sendPasswordResetEmail?.(user.email, resetUrl.toString());
|
|
341
|
+
if (!sent) console.error(`[kide] The password reset email to ${user.email} could not be sent.`);
|
|
342
|
+
} else if (delivery === "console") {
|
|
343
|
+
console.info(`[kide] Email isn't configured — password reset link for ${user.email}:\n ${resetUrl}`);
|
|
344
|
+
}
|
|
330
345
|
},
|
|
331
346
|
},
|
|
332
347
|
session: {
|
package/core/generator.ts
CHANGED
|
@@ -146,6 +146,10 @@ const generateMainTable = (
|
|
|
146
146
|
if (collection.drafts) {
|
|
147
147
|
indexes.push(` publishIdx: index("${idxPrefix}_publish_idx").on(table._status, table._publishAt),`);
|
|
148
148
|
indexes.push(` unpublishIdx: index("${idxPrefix}_unpublish_idx").on(table._status, table._unpublishAt),`);
|
|
149
|
+
// Published reads filter on the _published snapshot for documents with pending
|
|
150
|
+
// draft edits; this keeps that lookup to those few rows instead of a full scan.
|
|
151
|
+
// Plain, not partial: drizzle-kit can't round-trip a partial index.
|
|
152
|
+
indexes.push(` pendingIdx: index("${idxPrefix}_pending_idx").on(table._published),`);
|
|
149
153
|
}
|
|
150
154
|
// The admin lists, the Recent view and most editorial listings sort by
|
|
151
155
|
// _updatedAt; without an index each of them is a full scan plus a temp
|
package/core/index.ts
CHANGED
|
@@ -112,7 +112,7 @@ export type {
|
|
|
112
112
|
} from "./define";
|
|
113
113
|
|
|
114
114
|
export { createCms, FieldError } from "./api";
|
|
115
|
-
export type { FindOptions } from "./api";
|
|
115
|
+
export type { FindOptions, WhereOperators } from "./api";
|
|
116
116
|
|
|
117
117
|
export { enqueueTask, drainTasks, tickSchedules, pruneTasks } from "./tasks";
|
|
118
118
|
export { peekRateLimit, hitRateLimit, recordRateLimit, clearRateLimit, pruneRateLimits } from "./rate-limit";
|
|
@@ -160,6 +160,7 @@ export {
|
|
|
160
160
|
loadAuthUser,
|
|
161
161
|
markSsoVerified,
|
|
162
162
|
migrateLegacyAuth,
|
|
163
|
+
passwordResetDelivery,
|
|
163
164
|
registerAuthConfig,
|
|
164
165
|
resetAuthEngine,
|
|
165
166
|
resolveAdminSession,
|
package/internals/mcp.ts
CHANGED
|
@@ -199,7 +199,7 @@ server.registerTool(
|
|
|
199
199
|
{
|
|
200
200
|
title: "List documents",
|
|
201
201
|
description:
|
|
202
|
-
"List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation), 'missing' only those that don't; the default 'fallback' lists every document.",
|
|
202
|
+
"List documents in a collection with optional filters, search, sort, locale, status, limit, and offset. where: a plain value is equality; an object applies operators — scalar fields: ne, gt, gte, lt, lte, in, notIn (e.g. { startDate: { gte: '2026-01-01' } }); hasMany relation / array fields: contains, in (any of), notIn. With locale, availability 'exact' lists only documents that exist in that locale (their _sourceLocale or a translation), 'missing' only those that don't; the default 'fallback' lists every document.",
|
|
203
203
|
inputSchema: {
|
|
204
204
|
collection: z.string().min(1),
|
|
205
205
|
where: jsonObjectSchema.optional(),
|
|
@@ -219,7 +219,8 @@ server.registerTool(
|
|
|
219
219
|
"kide_count_documents",
|
|
220
220
|
{
|
|
221
221
|
title: "Count documents",
|
|
222
|
-
description:
|
|
222
|
+
description:
|
|
223
|
+
"Count documents in a collection with optional filters, search, locale, and status. where accepts the same operators as kide_list_documents.",
|
|
223
224
|
inputSchema: {
|
|
224
225
|
collection: z.string().min(1),
|
|
225
226
|
where: jsonObjectSchema.optional(),
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../..
|
|
|
5
5
|
import { Input } from "../../admin/components/ui/input";
|
|
6
6
|
import { Label } from "../../admin/components/ui/label";
|
|
7
7
|
import { buttonVariants } from "../../admin/components/ui/button";
|
|
8
|
-
import { resolveAdminAuth } from "../../core";
|
|
8
|
+
import { passwordResetDelivery, resolveAdminAuth } from "../../core";
|
|
9
9
|
import config from "virtual:kide/config";
|
|
10
10
|
|
|
11
11
|
export const prerender = false;
|
|
@@ -13,6 +13,7 @@ export const prerender = false;
|
|
|
13
13
|
const auth = resolveAdminAuth(config);
|
|
14
14
|
if (!auth.password.forgotPassword) return Astro.redirect("/admin/login");
|
|
15
15
|
|
|
16
|
+
const delivery = passwordResetDelivery();
|
|
16
17
|
const status = Astro.url.searchParams.get("status");
|
|
17
18
|
---
|
|
18
19
|
|
|
@@ -32,26 +33,45 @@ const status = Astro.url.searchParams.get("status");
|
|
|
32
33
|
<Card>
|
|
33
34
|
<CardHeader>
|
|
34
35
|
<CardTitle>Reset password</CardTitle>
|
|
35
|
-
<CardDescription>
|
|
36
|
+
<CardDescription>
|
|
37
|
+
{delivery ? "Enter your email and we'll send a reset link" : "Reset by email isn't available"}
|
|
38
|
+
</CardDescription>
|
|
36
39
|
</CardHeader>
|
|
37
40
|
<CardContent>
|
|
38
41
|
{
|
|
39
|
-
status === "sent" && (
|
|
42
|
+
status === "sent" && delivery && (
|
|
40
43
|
<div class="border-border bg-muted mb-4 rounded-lg border px-3 py-2 text-sm">
|
|
41
|
-
|
|
44
|
+
{delivery === "email"
|
|
45
|
+
? "If that account exists, a reset link has been sent."
|
|
46
|
+
: "Email isn't set up, so if that account exists, its reset link was printed in the dev server's terminal."}
|
|
47
|
+
</div>
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
{
|
|
51
|
+
delivery ? (
|
|
52
|
+
<form method="post" action="/api/cms/auth/forgot-password" class="grid gap-4">
|
|
53
|
+
<div class="grid gap-2">
|
|
54
|
+
<Label htmlFor="email">Email</Label>
|
|
55
|
+
<Input id="email" name="email" type="email" placeholder="admin@example.com" required autoFocus />
|
|
56
|
+
</div>
|
|
57
|
+
<button class={buttonVariants({ size: "lg", className: "w-full" })} type="submit">
|
|
58
|
+
Send reset link
|
|
59
|
+
</button>
|
|
60
|
+
<a class="text-muted-foreground hover:text-foreground text-center text-sm" href="/admin/login">
|
|
61
|
+
Back to sign in
|
|
62
|
+
</a>
|
|
63
|
+
</form>
|
|
64
|
+
) : (
|
|
65
|
+
<div class="grid gap-4">
|
|
66
|
+
<p class="text-muted-foreground text-sm">
|
|
67
|
+
Password reset by email isn't set up for this site. Ask an administrator to help you get back in.
|
|
68
|
+
</p>
|
|
69
|
+
<a class="text-muted-foreground hover:text-foreground text-center text-sm" href="/admin/login">
|
|
70
|
+
Back to sign in
|
|
71
|
+
</a>
|
|
42
72
|
</div>
|
|
43
73
|
)
|
|
44
74
|
}
|
|
45
|
-
<form method="post" action="/api/cms/auth/forgot-password" class="grid gap-4">
|
|
46
|
-
<div class="grid gap-2">
|
|
47
|
-
<Label htmlFor="email">Email</Label>
|
|
48
|
-
<Input id="email" name="email" type="email" placeholder="admin@example.com" required autoFocus />
|
|
49
|
-
</div>
|
|
50
|
-
<button class={buttonVariants({ size: "lg", className: "w-full" })} type="submit">Send reset link</button>
|
|
51
|
-
<a class="text-muted-foreground hover:text-foreground text-center text-sm" href="/admin/login">
|
|
52
|
-
Back to sign in
|
|
53
|
-
</a>
|
|
54
|
-
</form>
|
|
55
75
|
</CardContent>
|
|
56
76
|
</Card>
|
|
57
77
|
</div>
|
package/routes/admin/login.astro
CHANGED
|
@@ -6,7 +6,7 @@ import { Input } from "../../admin/components/ui/input";
|
|
|
6
6
|
import { Label } from "../../admin/components/ui/label";
|
|
7
7
|
import { buttonVariants } from "../../admin/components/ui/button";
|
|
8
8
|
import PasskeySignIn from "../../admin/components/PasskeySignIn";
|
|
9
|
-
import { getSsoProvider, resolveAdminAuth } from "../../core";
|
|
9
|
+
import { getSsoProvider, passwordResetDelivery, resolveAdminAuth } from "../../core";
|
|
10
10
|
import config from "virtual:kide/config";
|
|
11
11
|
|
|
12
12
|
export const prerender = false;
|
|
@@ -122,7 +122,7 @@ const hasSso = auth.ssoProviders.length > 0;
|
|
|
122
122
|
<div class="grid gap-2">
|
|
123
123
|
<div class="flex items-center justify-between gap-3">
|
|
124
124
|
<Label htmlFor="password">Password</Label>
|
|
125
|
-
{auth.password.forgotPassword && (
|
|
125
|
+
{auth.password.forgotPassword && passwordResetDelivery() && (
|
|
126
126
|
<a class="text-muted-foreground hover:text-foreground text-xs" href="/admin/forgot-password">
|
|
127
127
|
Forgot password?
|
|
128
128
|
</a>
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
getAdminAuth,
|
|
10
10
|
listSignInMethods,
|
|
11
11
|
loadAuthUser,
|
|
12
|
+
passwordResetDelivery,
|
|
12
13
|
resolveAdminAuth,
|
|
13
14
|
} from "../../../core";
|
|
14
15
|
import config from "virtual:kide/config";
|
|
@@ -19,6 +20,10 @@ export const prerender = false;
|
|
|
19
20
|
export const POST: APIRoute = async ({ request, clientAddress }) => {
|
|
20
21
|
const auth = resolveAdminAuth(config);
|
|
21
22
|
if (!auth.password.forgotPassword) return Response.json({ error: "Not found" }, { status: 404 });
|
|
23
|
+
// No way to deliver a link: the page explains that instead of pretending to send one.
|
|
24
|
+
if (!passwordResetDelivery()) {
|
|
25
|
+
return new Response(null, { status: 303, headers: { Location: "/admin/forgot-password" } });
|
|
26
|
+
}
|
|
22
27
|
|
|
23
28
|
const formData = await request.formData();
|
|
24
29
|
const email = String(formData.get("email") ?? "")
|