@basicbenframework/cms 0.7.3 → 0.9.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.
Files changed (53) hide show
  1. package/db/migrations/043_add_private_content.js +32 -0
  2. package/db/migrations/044_add_post_autosave_key.js +20 -0
  3. package/lib/client/components/admin/MediaPicker.js +3 -1
  4. package/lib/client/components/admin/SnippetPicker.js +3 -1
  5. package/lib/client/components/admin/SocialImageField.d.ts +24 -0
  6. package/lib/client/components/admin/SocialImageField.js +70 -0
  7. package/lib/client/i18n/locales/es/content.js +2 -0
  8. package/lib/client/i18n/locales/es/editor.js +18 -1
  9. package/lib/client/pages/Authentication.js +1 -1
  10. package/lib/client/pages/Database.js +15 -10
  11. package/lib/client/pages/Testing.js +1 -1
  12. package/lib/client/pages/admin/Pages.js +2 -2
  13. package/lib/client/pages/admin/PostEditor.js +103 -9
  14. package/lib/client/pages/admin/Posts.js +2 -2
  15. package/lib/controllers/FeedController.js +2 -2
  16. package/lib/controllers/MediaController.js +18 -1
  17. package/lib/controllers/PageController.js +5 -1
  18. package/lib/controllers/PostController.d.ts +14 -0
  19. package/lib/controllers/PostController.js +83 -1
  20. package/lib/features/members/Member.js +3 -2
  21. package/lib/helpers/autosave.d.ts +13 -0
  22. package/lib/helpers/autosave.js +19 -0
  23. package/lib/helpers/comment-mail.js +8 -3
  24. package/lib/helpers/insert-row.d.ts +18 -0
  25. package/lib/helpers/insert-row.js +18 -0
  26. package/lib/helpers/redirects.d.ts +7 -1
  27. package/lib/helpers/redirects.js +7 -1
  28. package/lib/helpers/seo-fields.d.ts +7 -0
  29. package/lib/helpers/seo-fields.js +9 -0
  30. package/lib/hooks.js +21 -0
  31. package/lib/models/Category.js +3 -2
  32. package/lib/models/Comment.js +3 -2
  33. package/lib/models/ContentType.js +3 -2
  34. package/lib/models/Credential.js +5 -1
  35. package/lib/models/Media.d.ts +4 -1
  36. package/lib/models/Media.js +21 -3
  37. package/lib/models/Menu.js +7 -6
  38. package/lib/models/Page.d.ts +2 -0
  39. package/lib/models/Page.js +9 -5
  40. package/lib/models/Post.d.ts +16 -0
  41. package/lib/models/Post.js +24 -3
  42. package/lib/models/PostRevision.js +4 -3
  43. package/lib/models/PublicContent.d.ts +1 -1
  44. package/lib/models/PublicContent.js +5 -5
  45. package/lib/models/Snippet.js +3 -2
  46. package/lib/models/Tag.js +3 -2
  47. package/lib/models/Taxonomy.js +5 -2
  48. package/lib/models/User.js +5 -1
  49. package/lib/models/visibility.d.ts +9 -0
  50. package/lib/models/visibility.js +15 -1
  51. package/lib/routes/api/posts.js +3 -0
  52. package/lib/types/index.d.ts +4 -0
  53. package/package.json +3 -3
@@ -30,7 +30,8 @@ export const MediaController = {
30
30
  const perPage = Math.min(100, Math.max(1, parseInt(req.query.per_page) || 20));
31
31
  const search = req.query.search || undefined;
32
32
  const type = req.query.type || undefined;
33
- const { items, total } = await Media.all(page, perPage, { search, type });
33
+ const servedAt = servedPath(req.query.url);
34
+ const { items, total } = await Media.all(page, perPage, { search, type, servedAt });
34
35
  res.json({
35
36
  media: await withUrls(items),
36
37
  pagination: {
@@ -187,3 +188,19 @@ async function withUrls(items) {
187
188
  url: storage.publicUrl(item.path)
188
189
  }));
189
190
  }
191
+ /**
192
+ * The path part of a pasted URL, for `?url=`: the editor's "paste a URL" box
193
+ * finds the library item a URL serves. Absolute or root-relative; anything
194
+ * that is not a URL at all matches nothing.
195
+ */
196
+ function servedPath(value) {
197
+ if (typeof value !== 'string' || !value.trim())
198
+ return undefined;
199
+ try {
200
+ const path = decodeURIComponent(new URL(value.trim(), 'http://localhost').pathname).replace(/^\/+/, '');
201
+ return path ? path.slice(0, 1024) : undefined;
202
+ }
203
+ catch {
204
+ return undefined;
205
+ }
206
+ }
@@ -1,7 +1,7 @@
1
1
  import { validate, rules } from '@basicbenframework/core/validation';
2
2
  import { hooks, HOOKS } from '@basicbenframework/core/hooks';
3
3
  import { Page } from "../models/Page.js";
4
- import { seoFields } from "../helpers/seo-fields.js";
4
+ import { seoFields, privateFlag } from "../helpers/seo-fields.js";
5
5
  import { redirectIfSlugChanged, releasePath } from "../helpers/redirects.js";
6
6
  import { pagePath } from "../helpers/content-paths.js";
7
7
  import { paginationFrom, meta } from "../models/pagination.js";
@@ -69,6 +69,9 @@ export const PageController = {
69
69
  featured_image: mediaId(featured_image),
70
70
  template,
71
71
  published,
72
+ // Published for the people who can edit pages, hidden from every public
73
+ // surface. See migration 043 and `livePage`.
74
+ ...('is_private' in req.body ? { is_private: privateFlag(req.body.is_private) } : {}),
72
75
  parent_id,
73
76
  menu_order,
74
77
  meta_title,
@@ -121,6 +124,7 @@ export const PageController = {
121
124
  ...('featured_image' in req.body ? { featured_image: mediaId(featured_image) } : {}),
122
125
  template,
123
126
  published,
127
+ ...('is_private' in req.body ? { is_private: privateFlag(req.body.is_private) } : {}),
124
128
  parent_id,
125
129
  menu_order,
126
130
  meta_title,
@@ -46,6 +46,20 @@ export declare const PostController: {
46
46
  * editor offers it back if the page is reopened before a real save.
47
47
  */
48
48
  autosave(req: Request, res: Response): Promise<void>;
49
+ /**
50
+ * The first autosave of a post that has never been saved.
51
+ *
52
+ * Autosave needs a post to hang its copy on, so a new post had none: a tab
53
+ * closed before the first Save lost everything typed into it. The editor
54
+ * calls this once, on the first title or body worth keeping, and gets a
55
+ * draft back; from then on it autosaves against that id like any other post.
56
+ *
57
+ * Always a draft, whatever is sent — this never publishes, schedules or makes
58
+ * anything public — and only the text is taken. The rules a real save
59
+ * enforces on a title and body (three and ten characters) wait for that
60
+ * save: a draft is allowed to be the first few words of itself.
61
+ */
62
+ autosaveNew(req: Request, res: Response): Promise<void>;
49
63
  feed(req: Request, res: Response): Promise<void>;
50
64
  feedShow(req: Request, res: Response): Promise<void>;
51
65
  };
@@ -4,7 +4,8 @@ import { can } from '@basicbenframework/core/auth/permissions';
4
4
  import { Post } from "../models/Post.js";
5
5
  import { paginationFrom, meta } from "../models/pagination.js";
6
6
  import { PostRevision } from "../models/PostRevision.js";
7
- import { seoFields } from "../helpers/seo-fields.js";
7
+ import { seoFields, privateFlag } from "../helpers/seo-fields.js";
8
+ import { worthAutosaving, validAutosaveKey } from "../helpers/autosave.js";
8
9
  import { LISTING_FILTERS } from "../models/Post.js";
9
10
  import { POST_STATUSES, toStoredTimestamp } from "../models/visibility.js";
10
11
  import { lockConflict } from "./PostLockController.js";
@@ -322,6 +323,83 @@ export const PostController = {
322
323
  });
323
324
  res.json({ autosave: { id: saved?.id, created_at: saved?.created_at } });
324
325
  },
326
+ /**
327
+ * The first autosave of a post that has never been saved.
328
+ *
329
+ * Autosave needs a post to hang its copy on, so a new post had none: a tab
330
+ * closed before the first Save lost everything typed into it. The editor
331
+ * calls this once, on the first title or body worth keeping, and gets a
332
+ * draft back; from then on it autosaves against that id like any other post.
333
+ *
334
+ * Always a draft, whatever is sent — this never publishes, schedules or makes
335
+ * anything public — and only the text is taken. The rules a real save
336
+ * enforces on a title and body (three and ten characters) wait for that
337
+ * save: a draft is allowed to be the first few words of itself.
338
+ */
339
+ async autosaveNew(req, res) {
340
+ const { title, content, excerpt, post_type, autosave_key } = (req.body ?? {});
341
+ if (typeof title !== 'string' || typeof content !== 'string') {
342
+ return res.json({ error: 'title and content are required' }, 422);
343
+ }
344
+ // A stray keystroke is not a draft: see helpers/autosave.ts.
345
+ if (!worthAutosaving(title, content)) {
346
+ return res.json({ error: 'Nothing to save yet' }, 422);
347
+ }
348
+ // The editor's key for this screen. A repeat — its earlier response lost
349
+ // after the row was written — gets the draft that request made, not a
350
+ // second one.
351
+ const key = validAutosaveKey(autosave_key) ? autosave_key : null;
352
+ if (autosave_key !== undefined && !key)
353
+ return res.json({ errors: { autosave_key: ['Invalid key'] } }, 422);
354
+ if (key) {
355
+ const earlier = await Post.findByAutosaveKey(req.userId, key);
356
+ if (earlier)
357
+ return res.json({ post: earlier });
358
+ }
359
+ const typed = await typeAndFields(post_type === undefined ? {} : { post_type }, null);
360
+ if ('errors' in typed)
361
+ return res.json({ errors: typed.errors }, 422);
362
+ const creating = await guardWrite(HOOKS.POST_CREATING, {
363
+ user_id: req.userId,
364
+ title: title.slice(0, 200),
365
+ content,
366
+ ...(typeof excerpt === 'string' ? { excerpt } : {}),
367
+ ...typed.values,
368
+ status: 'draft',
369
+ published: 0
370
+ }, { req }, { refused: 'Post rejected.' });
371
+ if (!creating.ok)
372
+ return res.json({ error: creating.error }, creating.status);
373
+ // A listener may adjust the text, not the state: what comes out of here is
374
+ // a draft of the signed-in user's, whatever the filter returned.
375
+ const value = creating.value;
376
+ let post;
377
+ try {
378
+ post = await Post.create({
379
+ title: String(value.title ?? ''),
380
+ content: String(value.content ?? ''),
381
+ ...(typeof value.excerpt === 'string' ? { excerpt: value.excerpt } : {}),
382
+ ...(typeof value.post_type === 'string' ? { post_type: value.post_type } : {}),
383
+ ...(key ? { autosave_key: key } : {}),
384
+ user_id: req.userId,
385
+ status: 'draft',
386
+ published: false
387
+ });
388
+ }
389
+ catch (error) {
390
+ // Two requests with one key raced, and the unique index let one in.
391
+ const earlier = key ? await Post.findByAutosaveKey(req.userId, key) : undefined;
392
+ if (earlier)
393
+ return res.json({ post: earlier });
394
+ throw error;
395
+ }
396
+ // Its address is chosen on the first real save, from the title it has by
397
+ // then, not from the first few letters typed.
398
+ await Post.forgetSlug(post.id);
399
+ post.slug = null;
400
+ await hooks.fire(HOOKS.POST_CREATED, { post, userId: req.userId });
401
+ res.json({ post }, 201);
402
+ },
325
403
  async feed(req, res) {
326
404
  // The built-in blog's feed. Restricted bodies are withheld unless the
327
405
  // access policy lets this reader have them — see helpers/gating.ts.
@@ -395,6 +473,10 @@ function editableFields(body, existing) {
395
473
  Object.assign(errors, seo.errors);
396
474
  else
397
475
  Object.assign(fields, seo.values);
476
+ // Private: published for the people who can edit it, hidden from every
477
+ // public surface. See migration 043 and `livePost`.
478
+ if ('is_private' in payload)
479
+ fields.is_private = privateFlag(payload.is_private);
398
480
  // Who may read the body: `public` or a level the access policy offers. The
399
481
  // level the post already has is always accepted, so a post saved under a
400
482
  // feature that has since been removed can still be edited without being
@@ -7,7 +7,8 @@
7
7
  */
8
8
  import { hooks } from '@basicbenframework/core/hooks';
9
9
  import { MEMBER_HOOKS } from "./events.js";
10
- import { getDb, query } from '@basicbenframework/core/db';
10
+ import { getDb } from '@basicbenframework/core/db';
11
+ import { insertRow } from "../../helpers/insert-row.js";
11
12
  import { normalizeEmail } from "./session.js";
12
13
  import { parseStoredTimestamp } from "../../models/visibility.js";
13
14
  export const MEMBER_STATUSES = ['active', 'unsubscribed'];
@@ -48,7 +49,7 @@ export const Member = {
48
49
  const now = new Date().toISOString();
49
50
  const status = data.status ?? 'active';
50
51
  // Through the query builder for RETURNING id on Postgres — see Post.create.
51
- const result = await (await query('members')).insert({
52
+ const result = await insertRow('members', {
52
53
  email: normalizeEmail(data.email),
53
54
  name: data.name ?? null,
54
55
  status,
@@ -0,0 +1,13 @@
1
+ /**
2
+ * When a new post has enough in it to be saved as a draft.
3
+ *
4
+ * Shared by the editor, which waits for it before its first autosave, and the
5
+ * server, which refuses anything less — so a stray keystroke on New post and a
6
+ * closed tab leave nothing behind. The same lengths a real save asks of a
7
+ * title and a body; either one is enough.
8
+ */
9
+ export declare const AUTOSAVE_MIN_TITLE = 3;
10
+ export declare const AUTOSAVE_MIN_CONTENT = 10;
11
+ export declare function worthAutosaving(title: unknown, content: unknown): boolean;
12
+ /** The shape of the editor's idempotency key: short, URL-safe, its own. */
13
+ export declare function validAutosaveKey(value: unknown): value is string;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * When a new post has enough in it to be saved as a draft.
3
+ *
4
+ * Shared by the editor, which waits for it before its first autosave, and the
5
+ * server, which refuses anything less — so a stray keystroke on New post and a
6
+ * closed tab leave nothing behind. The same lengths a real save asks of a
7
+ * title and a body; either one is enough.
8
+ */
9
+ export const AUTOSAVE_MIN_TITLE = 3;
10
+ export const AUTOSAVE_MIN_CONTENT = 10;
11
+ export function worthAutosaving(title, content) {
12
+ const t = typeof title === 'string' ? title.trim().length : 0;
13
+ const c = typeof content === 'string' ? content.trim().length : 0;
14
+ return t >= AUTOSAVE_MIN_TITLE || c >= AUTOSAVE_MIN_CONTENT;
15
+ }
16
+ /** The shape of the editor's idempotency key: short, URL-safe, its own. */
17
+ export function validAutosaveKey(value) {
18
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(value);
19
+ }
@@ -25,6 +25,7 @@ import { renderMail } from "./mail-templates.js";
25
25
  import { capabilitiesFor, ROLES } from '@basicbenframework/core/auth/permissions';
26
26
  import { getDb } from '@basicbenframework/core/db';
27
27
  import { Comment } from "../models/Comment.js";
28
+ import { livePost } from "../models/visibility.js";
28
29
  import { Settings } from "../models/Settings.js";
29
30
  import { issueUnsubscribeToken } from "./comment-guard.js";
30
31
  const appUrl = () => process.env.APP_URL || 'http://localhost:3000';
@@ -156,12 +157,16 @@ export async function notifyParentOfReply(replyId) {
156
157
  const sameAccount = reply.user_id && parent.user_id && Number(reply.user_id) === Number(parent.user_id);
157
158
  if (sameAccount || (replyEmail && replyEmail === to.toLowerCase()))
158
159
  return;
159
- if (!(await Comment.claimReplyNotification(Number(reply.id))))
160
- return;
160
+ // Only for a post readers can see. One made private (or unpublished, or
161
+ // trashed) since the comment was left must not be named, or linked, in a
162
+ // mail to someone who cannot open it. Checked before the claim, so nothing
163
+ // is marked sent that was not.
161
164
  const db = await getDb();
162
- const post = await db.get('SELECT id, title FROM posts WHERE id = ?', [reply.post_id]);
165
+ const post = await db.get(`SELECT id, title FROM posts WHERE id = ? AND ${livePost('posts')}`, [reply.post_id]);
163
166
  if (!post)
164
167
  return;
168
+ if (!(await Comment.claimReplyNotification(Number(reply.id))))
169
+ return;
165
170
  const unsubscribeUrl = `${appUrl()}/api/comments/unsubscribe?token=${encodeURIComponent(issueUnsubscribeToken(Number(parent.id)))}`;
166
171
  const replyUrl = `${appUrl()}/feed/${post.id}#comment-${reply.id}`;
167
172
  const name = parent.user_name || parent.author_name || 'there';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Insert a row the model built field by field. Returns the builder's result,
3
+ * whose `lastInsertRowid` is the new id.
4
+ *
5
+ * Core refuses a write that does not name its columns (strict mass
6
+ * assignment, core 0.9). A row written here is an object literal in the
7
+ * model's own code — every key is one the model chose — so its keys are the
8
+ * allowlist. A write that spreads in data from outside (a request body, a
9
+ * caller's record) must not come through here: it names its columns with
10
+ * `only()` itself, so a new key in that data can never reach the table.
11
+ *
12
+ * Inserts go through the query builder rather than raw SQL so Postgres gets a
13
+ * `RETURNING id` and the id comes back; a raw INSERT yields null there.
14
+ */
15
+ export declare function insertRow(table: string, row: Record<string, unknown>): Promise<{
16
+ lastInsertRowid: number | bigint;
17
+ changes: number;
18
+ }>;
@@ -0,0 +1,18 @@
1
+ import { query } from '@basicbenframework/core/db';
2
+ /**
3
+ * Insert a row the model built field by field. Returns the builder's result,
4
+ * whose `lastInsertRowid` is the new id.
5
+ *
6
+ * Core refuses a write that does not name its columns (strict mass
7
+ * assignment, core 0.9). A row written here is an object literal in the
8
+ * model's own code — every key is one the model chose — so its keys are the
9
+ * allowlist. A write that spreads in data from outside (a request body, a
10
+ * caller's record) must not come through here: it names its columns with
11
+ * `only()` itself, so a new key in that data can never reach the table.
12
+ *
13
+ * Inserts go through the query builder rather than raw SQL so Postgres gets a
14
+ * `RETURNING id` and the id comes back; a raw INSERT yields null there.
15
+ */
16
+ export async function insertRow(table, row) {
17
+ return (await query(table)).only(...Object.keys(row)).insert(row);
18
+ }
@@ -24,6 +24,8 @@ interface Movable {
24
24
  slug?: string | null;
25
25
  published?: boolean | number | null;
26
26
  deleted_at?: string | null;
27
+ /** Private (migration 043): published, but not public. */
28
+ is_private?: boolean | number | null;
27
29
  /** The post's content type key; absent or `post` means `/blog`. */
28
30
  post_type?: string | null;
29
31
  }
@@ -33,7 +35,11 @@ interface Movable {
33
35
  *
34
36
  * Only content that was public before the save: a draft's slug was never a
35
37
  * URL anyone could have linked to, so redirecting from it would only litter
36
- * the table. A post without a slug answered to its id, and still does — the
38
+ * the table. Nor a private one, on either side of the save: its slugs were
39
+ * never public, and `/api/v1/redirects` lists every redirect to anyone, so
40
+ * recording one would publish the old address and the new.
41
+ *
42
+ * A post without a slug answered to its id, and still does — the
37
43
  * content API accepts an id wherever it accepts a slug — so it needs nothing.
38
44
  */
39
45
  export declare function redirectIfSlugChanged(kind: 'post' | 'page', before: Movable, after: Movable | null | undefined, routeBases?: {
@@ -53,7 +53,11 @@ async function baseFor(type) {
53
53
  *
54
54
  * Only content that was public before the save: a draft's slug was never a
55
55
  * URL anyone could have linked to, so redirecting from it would only litter
56
- * the table. A post without a slug answered to its id, and still does — the
56
+ * the table. Nor a private one, on either side of the save: its slugs were
57
+ * never public, and `/api/v1/redirects` lists every redirect to anyone, so
58
+ * recording one would publish the old address and the new.
59
+ *
60
+ * A post without a slug answered to its id, and still does — the
57
61
  * content API accepts an id wherever it accepts a slug — so it needs nothing.
58
62
  */
59
63
  export async function redirectIfSlugChanged(kind, before, after,
@@ -65,6 +69,8 @@ routeBases = {}) {
65
69
  return;
66
70
  if (!before.published || before.deleted_at)
67
71
  return;
72
+ if (Number(before.is_private) || Number(after.is_private))
73
+ return;
68
74
  // Looked up from the rows themselves when the caller did not say, so the
69
75
  // controller's one-line call covers custom types without knowing about them.
70
76
  // A plain post never touches the database here.
@@ -11,3 +11,10 @@ export declare function seoFields(body: unknown): {
11
11
  errors: Record<string, string[]>;
12
12
  };
13
13
  export declare const SEO_COLUMNS: string[];
14
+ /**
15
+ * The private flag (migration 043) as stored: 1 or 0.
16
+ *
17
+ * A checkbox arrives as true, "true", "on" or "1" depending on the client, and
18
+ * anything else — including absent-but-present-as-null — is public.
19
+ */
20
+ export declare function privateFlag(value: unknown): 0 | 1;
@@ -50,3 +50,12 @@ export const SEO_COLUMNS = [
50
50
  'og_title', 'og_description', 'og_image', 'twitter_title', 'twitter_description',
51
51
  'twitter_image', 'canonical_url', 'noindex'
52
52
  ];
53
+ /**
54
+ * The private flag (migration 043) as stored: 1 or 0.
55
+ *
56
+ * A checkbox arrives as true, "true", "on" or "1" depending on the client, and
57
+ * anything else — including absent-but-present-as-null — is public.
58
+ */
59
+ export function privateFlag(value) {
60
+ return [true, 1, '1', 'true', 'on'].includes(value) ? 1 : 0;
61
+ }
package/lib/hooks.js CHANGED
@@ -99,3 +99,24 @@ for (const [event, kind] of CONTENT_EVENTS) {
99
99
  * is no process to keep a timer, so a platform cron calls GET /api/cron/tick.
100
100
  */
101
101
  hooks.on(HOOKS.SERVER_STARTED, async () => startCronInterval(), { name: 'cron:interval' });
102
+ /**
103
+ * One value per query key, as the CMS has always read them.
104
+ *
105
+ * Core 0.9 hands a repeated key over as an array (`?tag=a&tag=b` gives
106
+ * `['a', 'b']`). Every reader in the CMS takes a key as one string, many of
107
+ * them through an `as string` that the compiler cannot check, and an array
108
+ * there reaches a model, a `.trim()` or a SQL parameter it was never meant
109
+ * for. So the last value wins, which is what core did before 0.9, and nothing
110
+ * past this point ever sees an array. It runs first (priority 0), ahead of
111
+ * the theme's home page and every route.
112
+ */
113
+ hooks.on(HOOKS.REQUEST_BEFORE, async (context) => {
114
+ const query = context.req.query;
115
+ if (query) {
116
+ for (const [key, value] of Object.entries(query)) {
117
+ if (Array.isArray(value))
118
+ query[key] = value[value.length - 1];
119
+ }
120
+ }
121
+ return context;
122
+ }, { name: 'query:single-values', priority: 0 });
@@ -1,4 +1,5 @@
1
- import { getDb, query } from '@basicbenframework/core/db';
1
+ import { getDb } from '@basicbenframework/core/db';
2
+ import { insertRow } from "../helpers/insert-row.js";
2
3
  import { livePost } from "./visibility.js";
3
4
  function slugify(text) {
4
5
  return text
@@ -48,7 +49,7 @@ export const Category = {
48
49
  // INSERT there reports lastInsertRowid as null, so the row is written and
49
50
  // the caller is handed an object with no id — the failure looks like a bug
50
51
  // in whatever used the id next.
51
- const result = await (await query('categories')).insert({
52
+ const result = await insertRow('categories', {
52
53
  name: data.name,
53
54
  slug,
54
55
  description: data.description || null,
@@ -1,4 +1,5 @@
1
- import { getDb, query } from '@basicbenframework/core/db';
1
+ import { getDb } from '@basicbenframework/core/db';
2
+ import { insertRow } from "../helpers/insert-row.js";
2
3
  import { MAX_DEPTH } from "../helpers/comment-guard.js";
3
4
  /**
4
5
  * The listing a moderator works from.
@@ -141,7 +142,7 @@ export const Comment = {
141
142
  // Through the query builder, which appends RETURNING id on Postgres. A raw
142
143
  // INSERT there reports lastInsertRowid as null, so the row is written and
143
144
  // the caller is handed an object with no id.
144
- const result = await (await query('comments')).insert({
145
+ const result = await insertRow('comments', {
145
146
  post_id: data.post_id,
146
147
  user_id: data.user_id || null,
147
148
  parent_id: data.parent_id || null,
@@ -12,7 +12,8 @@
12
12
  * a database. Imports carry `.ts` extensions so the module also loads under
13
13
  * plain Node, which is how tests/phase3-content-model.test.js exercises it.
14
14
  */
15
- import { getDb, query } from '@basicbenframework/core/db';
15
+ import { getDb } from '@basicbenframework/core/db';
16
+ import { insertRow } from "../helpers/insert-row.js";
16
17
  import { isHttpUrl, isRelativePath, MAX_URL_LENGTH, normalizeRouteBase, POST_ROUTE_BASE } from "../helpers/content-paths.js";
17
18
  /** The kinds of custom field an editor can declare. */
18
19
  export const FIELD_TYPES = ['text', 'textarea', 'number', 'url', 'date', 'boolean', 'select'];
@@ -408,7 +409,7 @@ export const ContentType = {
408
409
  },
409
410
  async create(values) {
410
411
  // Through the query builder, which appends RETURNING id on Postgres.
411
- const result = await (await query('content_types')).insert({ ...columnsFor(values), builtin: 0 });
412
+ const result = await insertRow('content_types', { ...columnsFor(values), builtin: 0 });
412
413
  const id = Number(result.lastInsertRowid);
413
414
  if (values.fields)
414
415
  await this.replaceFields(id, values.fields);
@@ -9,8 +9,12 @@ export const Credential = {
9
9
  return db.get('SELECT * FROM user_credentials WHERE credential_id = ?', [credentialId]);
10
10
  },
11
11
  async create(data) {
12
+ // The columns a new passkey may set. `id`, `created_at` and `last_used_at`
13
+ // are the database's and the sign-in path's.
12
14
  const credentials = await query('user_credentials');
13
- await credentials.insert(data);
15
+ await credentials
16
+ .only('user_id', 'credential_id', 'public_key', 'algorithm', 'sign_count', 'transports', 'label', 'backed_up')
17
+ .insert(data);
14
18
  return this.findByCredentialId(data.credential_id);
15
19
  },
16
20
  async recordUse(id, signCount) {
@@ -25,11 +25,14 @@ export declare const Media: {
25
25
  * @param perPage
26
26
  * @param filters - `search` matches the original filename; `type` is a mime
27
27
  * prefix such as 'image', or 'other' for anything that is not image, video
28
- * or audio.
28
+ * or audio. `servedAt` is the path of a URL the file is served from: it
29
+ * matches the item whose storage key that path ends with, which is how a
30
+ * pasted URL is turned back into the library item it points at.
29
31
  */
30
32
  all(page?: number, perPage?: number, filters?: {
31
33
  search?: string;
32
34
  type?: string;
35
+ servedAt?: string;
33
36
  }): Promise<{
34
37
  items: MediaType[];
35
38
  total: number;
@@ -1,4 +1,5 @@
1
- import { getDb, query } from '@basicbenframework/core/db';
1
+ import { getDb } from '@basicbenframework/core/db';
2
+ import { insertRow } from "../helpers/insert-row.js";
2
3
  export const Media = {
3
4
  /**
4
5
  * A page of media, optionally filtered.
@@ -11,7 +12,9 @@ export const Media = {
11
12
  * @param perPage
12
13
  * @param filters - `search` matches the original filename; `type` is a mime
13
14
  * prefix such as 'image', or 'other' for anything that is not image, video
14
- * or audio.
15
+ * or audio. `servedAt` is the path of a URL the file is served from: it
16
+ * matches the item whose storage key that path ends with, which is how a
17
+ * pasted URL is turned back into the library item it points at.
15
18
  */
16
19
  async all(page = 1, perPage = 20, filters = {}) {
17
20
  const db = await getDb();
@@ -22,6 +25,21 @@ export const Media = {
22
25
  where.push('m.original_name LIKE ?');
23
26
  params.push(`%${filters.search}%`);
24
27
  }
28
+ if (filters.servedAt) {
29
+ // Every storage driver serves a key at a URL ending in that key, after
30
+ // whatever prefix its bucket, CDN or local route adds. So the key is one
31
+ // of the path's whole-segment suffixes: compared exactly, because a
32
+ // stored key used as a LIKE pattern would make `_` and `%` wildcards.
33
+ const segments = filters.servedAt.split('/').filter(Boolean).slice(-20);
34
+ const suffixes = segments.map((_, i) => segments.slice(i).join('/'));
35
+ if (suffixes.length) {
36
+ where.push(`m.path IN (${suffixes.map(() => '?').join(', ')})`);
37
+ params.push(...suffixes);
38
+ }
39
+ else {
40
+ where.push('1 = 0');
41
+ }
42
+ }
25
43
  if (filters.type === 'other') {
26
44
  where.push("COALESCE(m.mime_type, '') NOT LIKE 'image/%'");
27
45
  where.push("COALESCE(m.mime_type, '') NOT LIKE 'video/%'");
@@ -66,7 +84,7 @@ export const Media = {
66
84
  // Through the query builder, which appends RETURNING id on Postgres. A raw
67
85
  // INSERT there reports lastInsertRowid as null, so the row is written and
68
86
  // the caller is handed an object with no id.
69
- const result = await (await query('media')).insert({
87
+ const result = await insertRow('media', {
70
88
  user_id: data.user_id || null,
71
89
  filename: data.filename,
72
90
  original_name: data.original_name,
@@ -6,8 +6,9 @@
6
6
  * leaves out anything a visitor could not open — so a menu never links to a
7
7
  * draft, a trashed post, or a page that was deleted out from under it.
8
8
  */
9
- import { getDb, query } from '@basicbenframework/core/db';
10
- import { livePost } from "./visibility.js";
9
+ import { getDb } from '@basicbenframework/core/db';
10
+ import { insertRow } from "../helpers/insert-row.js";
11
+ import { livePost, livePage } from "./visibility.js";
11
12
  import { postPath, pagePath, categoryPath, isSafeLinkUrl } from "../helpers/content-paths.js";
12
13
  export const TARGET_TYPES = ['post', 'page', 'category'];
13
14
  /**
@@ -218,7 +219,7 @@ export const Menu = {
218
219
  const now = new Date().toISOString();
219
220
  // There is no natural unique key to read an item back by, so this one
220
221
  // goes through the query builder, which appends RETURNING id on Postgres.
221
- const result = await (await query('menu_items')).insert({
222
+ const result = await insertRow('menu_items', {
222
223
  menu_id: menuId,
223
224
  parent_id: data.parent_id,
224
225
  label: data.label,
@@ -296,11 +297,11 @@ export const Menu = {
296
297
  return map;
297
298
  };
298
299
  // The same visibility rules as the rest of the public API: `livePost` for
299
- // posts (published, not trashed, its time has come), `published = 1` for
300
- // pages. Categories have no visibility of their own.
300
+ // posts (published, not trashed, its time has come, not private), `livePage`
301
+ // for pages. Categories have no visibility of their own.
301
302
  const targets = {
302
303
  post: await lookup('post', list => `SELECT posts.id, posts.slug FROM posts WHERE posts.id IN (${list}) AND ${livePost('posts')}`),
303
- page: await lookup('page', list => `SELECT id, slug FROM pages WHERE id IN (${list}) AND published = 1`),
304
+ page: await lookup('page', list => `SELECT pages.id, pages.slug FROM pages WHERE pages.id IN (${list}) AND ${livePage('pages')}`),
304
305
  category: await lookup('category', list => `SELECT id, slug FROM categories WHERE id IN (${list})`)
305
306
  };
306
307
  const result = {};
@@ -6,6 +6,7 @@ interface CreatePageData {
6
6
  featured_image?: number | null;
7
7
  template?: string;
8
8
  published?: boolean;
9
+ is_private?: number;
9
10
  parent_id?: number;
10
11
  menu_order?: number;
11
12
  meta_title?: string;
@@ -18,6 +19,7 @@ interface UpdatePageData {
18
19
  featured_image?: number | null;
19
20
  template?: string;
20
21
  published?: boolean;
22
+ is_private?: number;
21
23
  parent_id?: number;
22
24
  menu_order?: number;
23
25
  meta_title?: string;