@cossackframework/cms 0.9.2 → 0.9.4

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 (120) hide show
  1. package/agent-docs.json +8 -8
  2. package/app/cossack-recipe.json +12 -8
  3. package/app/src/auth-events.ts +33 -0
  4. package/app/src/auth-input.ts +3 -0
  5. package/app/src/auth-options.ts +39 -7
  6. package/app/src/auth.ts +1309 -641
  7. package/app/src/avatars.ts +13 -0
  8. package/app/src/brand.ts +24 -2
  9. package/app/src/cms/actor.ts +13 -0
  10. package/app/src/cms/collab/room.ts +1 -1
  11. package/app/src/cms/content-api.ts +2 -1
  12. package/app/src/cms/content.ts +3 -2
  13. package/app/src/cms/dev-mail.ts +77 -0
  14. package/app/src/cms/index.ts +37 -10
  15. package/app/src/cms/maintenance.ts +1 -6
  16. package/app/src/cms/manage.ts +17 -14
  17. package/app/src/cms/middleware.ts +58 -18
  18. package/app/src/cms/network-accounts.ts +110 -0
  19. package/app/src/cms/notes-announce.ts +1 -1
  20. package/app/src/cms/people.ts +177 -0
  21. package/app/src/cms/recovery.ts +9 -14
  22. package/app/src/cms/request-calls.ts +56 -0
  23. package/app/src/cms/settings-form.ts +23 -6
  24. package/app/src/cms/settings-network.ts +8 -4
  25. package/app/src/cms/settings-search.ts +1 -0
  26. package/app/src/cms/site-editing.ts +3 -2
  27. package/app/src/cms/site-registration.ts +64 -0
  28. package/app/src/cms/site.ts +30 -19
  29. package/app/src/cms/sites.ts +182 -0
  30. package/app/src/dashboard/access.ts +3 -2
  31. package/app/src/dashboard/modules/users.ts +1 -0
  32. package/app/src/lib/permissions.ts +24 -0
  33. package/app/src/lib/uuid.ts +6 -0
  34. package/app/src/mail.ts +15 -0
  35. package/app/src/middlewares/auth.ts +6 -2
  36. package/app/src/middlewares/tenant.ts +108 -0
  37. package/app/src/pages/(site)/[...path]/index.ts +1 -1
  38. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
  39. package/app/src/pages/api/cms/dev/mail.ts +19 -0
  40. package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
  41. package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
  42. package/app/src/pages/auth/login/index.ts +1 -1
  43. package/app/src/pages/auth/magic/index.ts +1 -1
  44. package/app/src/pages/auth/recovery.ts +20 -0
  45. package/app/src/pages/auth/register-site/index.ts +146 -0
  46. package/app/src/pages/auth/setup/index.ts +8 -3
  47. package/app/src/pages/auth/tenant/callback.ts +23 -0
  48. package/app/src/pages/auth/tenant/redirect.ts +91 -0
  49. package/app/src/pages/auth/verify/index.ts +3 -7
  50. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
  51. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
  52. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
  53. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
  54. package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
  55. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
  56. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
  57. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
  58. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
  59. package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
  60. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
  61. package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
  62. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
  63. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
  64. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
  65. package/app/src/pages/dashboard/index.ts +3 -2
  66. package/app/src/pages/dashboard/roles/index.ts +2 -2
  67. package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
  68. package/app/src/services/api-tokens.ts +86 -0
  69. package/app/src/services/rbac.ts +26 -15
  70. package/app/src/services/roles.ts +125 -35
  71. package/app/src/services/security.ts +384 -0
  72. package/app/src/services/tenants.ts +447 -0
  73. package/app/src/services/users.ts +241 -97
  74. package/app/src/tenants.ts +219 -0
  75. package/package.json +48 -12
  76. package/src/block-references.ts +3 -3
  77. package/src/collections.ts +3 -1
  78. package/src/forms.ts +4 -2
  79. package/src/hooks.ts +19 -1
  80. package/src/index.ts +4 -4
  81. package/src/isolate-core.ts +1 -1
  82. package/src/isolation.ts +1 -0
  83. package/src/manifest.ts +43 -2
  84. package/src/permissions.ts +13 -7
  85. package/src/resource.ts +85 -2
  86. package/src/server/attempts.ts +64 -0
  87. package/src/server/automations.ts +2 -2
  88. package/src/server/batch.ts +106 -0
  89. package/src/server/budget.ts +17 -0
  90. package/src/server/field-values.ts +207 -0
  91. package/src/server/forms.ts +3 -3
  92. package/src/server/host-schema.ts +55 -7
  93. package/src/server/host.ts +213 -85
  94. package/src/server/index.ts +9 -14
  95. package/src/server/isolation.ts +10 -0
  96. package/src/server/network.ts +129 -44
  97. package/src/server/outbox.ts +2 -2
  98. package/src/server/people.ts +191 -0
  99. package/src/server/reconcile.ts +5 -5
  100. package/src/server/repository.ts +243 -84
  101. package/src/server/shared-read.ts +34 -0
  102. package/src/server/site-export.ts +23 -13
  103. package/src/server/site-import.ts +12 -33
  104. package/src/server/site-settings.ts +9 -3
  105. package/src/server/sites.ts +117 -187
  106. package/src/server/stores.ts +3 -300
  107. package/src/server/taxonomies.ts +64 -13
  108. package/src/server/users.ts +151 -498
  109. package/src/settings-controls.ts +8 -4
  110. package/src/settings.ts +26 -3
  111. package/src/storage/cloudflare.ts +2 -0
  112. package/src/storage/index.ts +6 -0
  113. package/src/theme.ts +2 -2
  114. package/src/version.ts +1 -1
  115. package/app/src/cms/handoff.ts +0 -202
  116. package/src/server/accounts.ts +0 -418
  117. package/src/server/api-tokens.ts +0 -91
  118. package/src/server/auth.ts +0 -89
  119. package/src/server/handoffs.ts +0 -107
  120. package/src/server/security.ts +0 -391
@@ -1,301 +1,10 @@
1
1
  /**
2
- * RomeDB implementations of the auth and framework stores, on relational host tables.
3
- * Each operation is one atomic request; conditional operations check the affected count.
4
- * The interfaces are structural copies, so this package does not depend on the framework.
2
+ * The stores the framework's jobs and notifications keep in the site's database. Sessions,
3
+ * OAuth states and what signs people in are the application's, with its accounts.
5
4
  */
6
5
  import { createSqlJobStore, type JobStore } from '@cossackframework/core/jobs';
7
6
  import { createSqlNotificationStore, type NotificationStore } from '@cossackframework/core/notifications';
8
- import { rqlDatabase, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
9
- import { readPaged } from './budget';
10
-
11
- const TOKEN = /^[A-Za-z0-9_-]{1,191}$/;
12
- const n = (value: Value | undefined) => Number(value as bigint);
13
-
14
- export interface AuthSessionRecord { readonly id: string; readonly userId: string; readonly kind: 'auth'; readonly createdAt: number; readonly expiresAt: number }
15
-
16
- /**
17
- * A stored session. On a site other than the main one it is a child session: the network
18
- * session it came from (`parentId`, that session's public reference) and the account's network
19
- * role at the handoff, so site requests need not read the network database.
20
- */
21
- export interface CmsAuthSession extends AuthSessionRecord {
22
- readonly parentId: string | null;
23
- readonly networkRole: string | null;
24
- /** Whether the sign-in that made it used a second factor; a child session copies its network session's. */
25
- readonly secondFactor: boolean;
26
- }
27
-
28
- /** What a child session takes from its network session's handoff. */
29
- export interface ChildSession {
30
- /** The network session's public reference. */
31
- readonly parentId: string;
32
- readonly networkRole: string | null;
33
- /** The network session's expiry. */
34
- readonly expiresAt: number;
35
- /** Whether the network session's sign-in used a second factor; missing means it did not. */
36
- readonly secondFactor?: boolean;
37
- }
38
-
39
- /** Network sessions that ended: one by its public reference, or an account's (all but `except`). Their child sessions end with them. */
40
- export type EndedSessions = { readonly session: string } | { readonly user: string; readonly except?: string };
41
- /** Structural `AuthSessionStore` from `@cossackframework/auth`. */
42
- export interface CmsAuthSessionStore {
43
- create(record: AuthSessionRecord, context?: unknown): Promise<void>;
44
- read(id: string, context?: unknown): Promise<AuthSessionRecord | null>;
45
- replace(expected: AuthSessionRecord, replacement: AuthSessionRecord, now: number, context?: unknown): Promise<boolean>;
46
- revoke(id: string, context?: unknown): Promise<void>;
47
- }
48
-
49
- export interface OAuthStateRecord { readonly key: string; readonly provider: string; readonly createdAt: number; readonly expiresAt: number }
50
- /** Structural `OAuthStateStore` from `@cossackframework/auth`. */
51
- export interface CmsOAuthStateStore {
52
- create(record: OAuthStateRecord, context?: unknown): Promise<void>;
53
- consume(key: string, provider: string, now: number, context?: unknown): Promise<boolean>;
54
- }
55
-
56
- /** Structural `SessionStore` from `@cossackframework/framework/session`. */
57
- export interface CmsSessionStore {
58
- create(ttlMs?: number): Promise<string>;
59
- has(sessionId: string): Promise<boolean>;
60
- load(sessionId: string): Promise<Record<string, unknown>>;
61
- get<T = unknown>(sessionId: string, key: string): Promise<T | undefined>;
62
- getAll(sessionId: string): Promise<Record<string, unknown>>;
63
- set(sessionId: string, key: string, value: unknown, ttlMs?: number): Promise<void>;
64
- unset(sessionId: string, key: string): Promise<void>;
65
- destroy(sessionId: string): Promise<void>;
66
- bindUser(sessionId: string, userId: string): Promise<void>;
67
- purgeExpired(): Promise<number>;
68
- }
69
-
70
- /**
71
- * Auth sessions keyed by token. Rotation is one conditional update of the key; the public
72
- * reference survives it, so realtime descriptors detect rotation through the fingerprint.
73
- */
74
- export function createAuthSessionStore(db: RomeDB, options: { now?: () => number; request?: (context: unknown) => { ip?: string; userAgent?: string }; sessionsEnded?: (ended: EndedSessions) => Promise<void> } = {}): Omit<CmsAuthSessionStore, 'read' | 'create'> & {
75
- read(id: string, context?: unknown): Promise<CmsAuthSession | null>;
76
- /** A session whose sign-in used a second factor (`secondFactor`) or did not; `also` joins the session's write (its sign-in event). */
77
- create(record: AuthSessionRecord, context?: unknown, options?: { secondFactor?: boolean; also?: readonly Statement[] }): Promise<void>;
78
- /** Mark a session as having used a second factor: its user just added one in it. */
79
- markSecondFactor(id: string): Promise<boolean>;
80
- /** A child session on a site, from a network session's handoff. It expires no later than its parent, and rotation keeps that. */
81
- createChild(record: AuthSessionRecord, child: ChildSession, context?: unknown, options?: { also?: readonly Statement[] }): Promise<void>;
82
- /** End the child sessions of these network sessions, or all of an account's (but `except`'s). */
83
- revokeChildren(ended: EndedSessions): Promise<number>;
84
- publicReference(id: string): Promise<string | null>;
85
- findByReference(reference: string): Promise<{ id: string; userId: string; expiresAt: number; secondFactor: boolean } | null>;
86
- listForUser(userId: string, now: number): Promise<{ reference: string; createdAt: number; expiresAt: number; ip: string | null; userAgent: string | null }[]>;
87
- /** The newest sessions across users, for the dashboard's sign-in activity. Sessions end at sign-out, so this shows who is signed in. */
88
- listRecent(now: number, limit?: number): Promise<{ reference: string; userId: string; createdAt: number; ip: string | null; userAgent: string | null }[]>;
89
- revokeAllForUser(userId: string, except?: string): Promise<number>;
90
- /** Revoke one of the user's sessions by its public reference, never the `current` token. */
91
- revokeByReference(userId: string, reference: string, current?: string): Promise<boolean>;
92
- } {
93
- const now = options.now ?? Date.now;
94
- const ended = (scope: EndedSessions) => options.sessionsEnded?.(scope).catch(error => console.error('[cms] could not end child sessions', error));
95
- const insert = async (record: AuthSessionRecord, child: ChildSession | null, context: unknown, secondFactor: boolean, also: readonly Statement[] = []) => {
96
- assertRecord(record);
97
- const expires = child ? Math.min(record.expiresAt, child.expiresAt) : record.expiresAt;
98
- if (expires <= record.createdAt) throw new Error('The network session has expired.');
99
- const meta = options.request?.(context) ?? {};
100
- await db.write([{
101
- rql: 'INSERT INTO cms_auth_sessions (id, public_id, user_id, created_at, expires_at, ip, user_agent, parent_id, network_role, second_factor) VALUES ($id, $public, $user, $created, $expires, $ip, $agent, $parent, $role, $factor)',
102
- params: { $id: record.id, $public: crypto.randomUUID(), $user: record.userId, $created: record.createdAt, $expires: expires, $ip: meta.ip?.slice(0, 64) ?? null, $agent: meta.userAgent?.slice(0, 512) ?? null,
103
- $parent: child?.parentId ?? null, $role: child?.networkRole ?? null, $factor: secondFactor ? 1 : 0 },
104
- }, {
105
- // The account keeps the sign-in time after the session ends, and so does its member row on the main site.
106
- rql: 'UPDATE cms_accounts SET last_sign_in_at = $created WHERE id = $user',
107
- params: { $user: record.userId, $created: record.createdAt },
108
- }, {
109
- rql: 'UPDATE cms_users SET last_sign_in_at = $created WHERE id = $user',
110
- params: { $user: record.userId, $created: record.createdAt },
111
- }, ...also], { kind: 'cms.auth.session', retryConflicts: 5 });
112
- };
113
- return {
114
- create: (record, context, extra) => insert(record, null, context, extra?.secondFactor === true, extra?.also),
115
- createChild: (record, child, context, extra) => insert(record, child, context, child.secondFactor === true, extra?.also),
116
- async markSecondFactor(id) {
117
- if (!TOKEN.test(id)) return false;
118
- const result = await db.write([{ rql: 'UPDATE cms_auth_sessions SET second_factor = 1 WHERE id = $id', params: { $id: id } }], { kind: 'cms.auth.session', retryConflicts: 5 });
119
- return result.results[0]!.affected === 1n;
120
- },
121
- async read(id) {
122
- if (!TOKEN.test(id)) return null;
123
- const result = await db.read([{ rql: 'SELECT id, user_id, created_at, expires_at, parent_id, network_role, second_factor FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }]);
124
- const row = result.results[0]!.rows[0];
125
- return row ? Object.freeze({ id: row[0] as string, userId: row[1] as string, kind: 'auth' as const, createdAt: n(row[2]), expiresAt: n(row[3]), parentId: row[4] as string | null, networkRole: row[5] as string | null,
126
- secondFactor: row[6] !== null && n(row[6]) === 1 }) : null;
127
- },
128
- async replace(expected, replacement, at) {
129
- assertRecord(expected);
130
- assertRecord(replacement);
131
- if (replacement.userId !== expected.userId) return false;
132
- const guard = 'WHERE id = $id AND user_id = $user AND created_at = $oldCreated AND expires_at = $oldExpires AND expires_at > $now';
133
- const params = { $next: replacement.id, $created: replacement.createdAt, $id: expected.id, $user: expected.userId,
134
- $oldCreated: expected.createdAt, $oldExpires: expected.expiresAt, $now: Math.max(at, now()) };
135
- // A child session keeps its expiry, so it never outlives the network session it came from.
136
- const result = await db.write([
137
- { rql: `UPDATE cms_auth_sessions SET id = $next, created_at = $created, expires_at = $expires ${guard} AND parent_id IS NULL`, params: { ...params, $expires: replacement.expiresAt } },
138
- { rql: `UPDATE cms_auth_sessions SET id = $next, created_at = $created ${guard} AND parent_id IS NOT NULL`, params },
139
- ], { kind: 'cms.auth.session', retryConflicts: 5 });
140
- return result.results[0]!.affected + result.results[1]!.affected === 1n;
141
- },
142
- async revoke(id) {
143
- if (!TOKEN.test(id)) return;
144
- const found = await db.read([{ rql: 'SELECT public_id, parent_id FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }]);
145
- await db.write([{ rql: 'DELETE FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }], { kind: 'cms.auth.session', retryConflicts: 5 });
146
- const row = found.results[0]!.rows[0];
147
- if (row && row[1] === null) await ended({ session: row[0] as string });
148
- },
149
- async publicReference(id) {
150
- if (!TOKEN.test(id)) return null;
151
- const result = await db.read([{ rql: 'SELECT public_id FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }]);
152
- return (result.results[0]!.rows[0]?.[0] as string | undefined) ?? null;
153
- },
154
- async findByReference(reference) {
155
- if (!/^[0-9a-f-]{36}$/.test(reference)) return null;
156
- const result = await db.read([{ rql: 'SELECT id, user_id, expires_at, second_factor FROM cms_auth_sessions WHERE public_id = $ref', params: { $ref: reference } }]);
157
- const row = result.results[0]!.rows[0];
158
- return row ? { id: row[0] as string, userId: row[1] as string, expiresAt: n(row[2]), secondFactor: row[3] !== null && n(row[3]) === 1 } : null;
159
- },
160
- async listForUser(userId, at) {
161
- const result = await db.read([{
162
- rql: 'SELECT public_id, created_at, expires_at, ip, user_agent FROM cms_auth_sessions WHERE user_id = $user AND expires_at > $now ORDER BY created_at DESC LIMIT 100',
163
- params: { $user: userId, $now: at },
164
- }]);
165
- return result.results[0]!.rows.map(row => ({ reference: row[0] as string, createdAt: n(row[1]), expiresAt: n(row[2]), ip: row[3] as string | null, userAgent: row[4] as string | null }));
166
- },
167
- async listRecent(at, limit = 10) {
168
- const result = await db.read([{
169
- rql: 'SELECT public_id, user_id, created_at, ip, user_agent FROM cms_auth_sessions WHERE expires_at > $now ORDER BY created_at DESC LIMIT $limit',
170
- params: { $now: at, $limit: Math.min(Math.max(limit, 1), 100) },
171
- }]);
172
- return result.results[0]!.rows.map(row => ({ reference: row[0] as string, userId: row[1] as string, createdAt: n(row[2]), ip: row[3] as string | null, userAgent: row[4] as string | null }));
173
- },
174
- async revokeByReference(userId, reference, current) {
175
- if (!/^[0-9a-f-]{36}$/.test(reference)) return false;
176
- const result = await db.write([{
177
- rql: `DELETE FROM cms_auth_sessions WHERE public_id = $ref AND user_id = $user${current ? ' AND id != $current' : ''}`,
178
- params: { $ref: reference, $user: userId, ...(current ? { $current: current } : {}) },
179
- }], { kind: 'cms.auth.session', retryConflicts: 5 });
180
- if (result.results[0]!.affected !== 1n) return false;
181
- await ended({ session: reference });
182
- return true;
183
- },
184
- async revokeAllForUser(userId, except) {
185
- const kept = except && TOKEN.test(except) ? (await db.read([{ rql: 'SELECT public_id FROM cms_auth_sessions WHERE id = $id', params: { $id: except } }])).results[0]!.rows[0]?.[0] as string | undefined : undefined;
186
- const result = await db.write([{
187
- rql: `DELETE FROM cms_auth_sessions WHERE user_id = $user${except ? ' AND id != $except' : ''}`,
188
- params: { $user: userId, ...(except ? { $except: except } : {}) },
189
- }], { kind: 'cms.auth.session', retryConflicts: 5 });
190
- await ended({ user: userId, ...(kept ? { except: kept } : {}) });
191
- return Number(result.results[0]!.affected);
192
- },
193
- async revokeChildren(scope) {
194
- const result = await db.write(['session' in scope
195
- ? { rql: 'DELETE FROM cms_auth_sessions WHERE parent_id = $parent', params: { $parent: scope.session } }
196
- : { rql: `DELETE FROM cms_auth_sessions WHERE user_id = $user AND parent_id IS NOT NULL${scope.except ? ' AND parent_id != $except' : ''}`, params: { $user: scope.user, ...(scope.except ? { $except: scope.except } : {}) } },
197
- ], { kind: 'cms.auth.session', retryConflicts: 5 });
198
- return Number(result.results[0]!.affected);
199
- },
200
- };
201
- }
202
-
203
- /** OAuth state consumed by one conditional delete: exactly one callback can win. */
204
- export function createOAuthStateStore(db: RomeDB): CmsOAuthStateStore & { purgeExpired(now: number): Promise<number> } {
205
- return {
206
- async create(record) {
207
- if (!/^[a-f0-9]{64}$/.test(record.key) || !/^[a-z0-9_-]{1,64}$/.test(record.provider)) throw new TypeError('Invalid OAuth state record.');
208
- await db.write([{ rql: 'INSERT INTO cms_oauth_states (key, provider, created_at, expires_at) VALUES ($key, $provider, $created, $expires)',
209
- params: { $key: record.key, $provider: record.provider, $created: record.createdAt, $expires: record.expiresAt } }], { kind: 'cms.auth.oauth', retryConflicts: 5 });
210
- },
211
- async consume(key, provider, now) {
212
- if (!/^[a-f0-9]{64}$/.test(key)) return false;
213
- const result = await db.write([{ rql: 'DELETE FROM cms_oauth_states WHERE key = $key AND provider = $provider AND expires_at > $now',
214
- params: { $key: key, $provider: provider, $now: Math.max(now, Date.now()) } }], { kind: 'cms.auth.oauth', retryConflicts: 5 });
215
- return result.results[0]!.affected === 1n;
216
- },
217
- async purgeExpired(now) {
218
- const expired = await db.read([{ rql: 'SELECT 1 FROM cms_oauth_states WHERE expires_at <= $now LIMIT 1', params: { $now: now } }]);
219
- if (!expired.results[0]!.rows.length) return 0;
220
- const result = await db.write([{ rql: 'DELETE FROM cms_oauth_states WHERE key IN (SELECT key FROM cms_oauth_states WHERE expires_at <= $now LIMIT 1000)', params: { $now: now } }], { kind: 'cms.auth.oauth', retryConflicts: 5 });
221
- return Number(result.results[0]!.affected);
222
- },
223
- };
224
- }
225
-
226
- /**
227
- * The framework session bag. Each key is its own row, so a write to one key never
228
- * replaces a concurrent write to another; writes slide the expiry.
229
- */
230
- export function createSessionStore(db: RomeDB, options: { ttlMs?: number; now?: () => number } = {}): CmsSessionStore {
231
- const now = options.now ?? Date.now;
232
- const defaultTtl = options.ttlMs ?? 30 * 24 * 60 * 60 * 1000;
233
- const live = 'EXISTS (SELECT 1 FROM cms_sessions WHERE id = $id AND expires_at > $now)';
234
- const read = async (sessionId: string): Promise<Record<string, unknown>> => {
235
- if (!TOKEN.test(sessionId)) return {};
236
- const at = now();
237
- const rows = await readPaged(db, (size, offset) => ({ rql: `SELECT key, value FROM cms_session_values WHERE session_id = $id AND ${live} ORDER BY key LIMIT $limit OFFSET $offset`, params: { $id: sessionId, $now: at, $limit: size, $offset: offset } }), 1000, 0);
238
- return Object.fromEntries(rows.map(([key, value]) => [key as string, JSON.parse(value as string)]));
239
- };
240
- return {
241
- async create(ttlMs = defaultTtl) {
242
- const bytes = crypto.getRandomValues(new Uint8Array(32));
243
- const id = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');
244
- const at = now();
245
- await db.write([{ rql: 'INSERT INTO cms_sessions (id, user_id, created_at, expires_at) VALUES ($id, NULL, $at, $expires)', params: { $id: id, $at: at, $expires: at + ttlMs } }], { kind: 'cms.session', retryConflicts: 5 });
246
- return id;
247
- },
248
- async has(sessionId) {
249
- if (!TOKEN.test(sessionId)) return false;
250
- const result = await db.read([{ rql: 'SELECT 1 FROM cms_sessions WHERE id = $id AND expires_at > $now', params: { $id: sessionId, $now: now() } }]);
251
- return result.results[0]!.rows.length === 1;
252
- },
253
- load: read,
254
- getAll: read,
255
- async get<T>(sessionId: string, key: string) {
256
- if (!TOKEN.test(sessionId)) return undefined;
257
- const result = await db.read([{ rql: `SELECT value FROM cms_session_values WHERE session_id = $id AND key = $key AND ${live}`, params: { $id: sessionId, $key: key, $now: now() } }]);
258
- const value = result.results[0]!.rows[0]?.[0];
259
- return value === undefined ? undefined : JSON.parse(value as string) as T;
260
- },
261
- async set(sessionId, key, value, ttlMs = defaultTtl) {
262
- if (!TOKEN.test(sessionId)) throw new TypeError('Invalid session ID.');
263
- const encoded = JSON.stringify(value);
264
- if (encoded === undefined) throw new TypeError('Session values must be JSON.');
265
- const at = now();
266
- await db.write([
267
- { rql: `INSERT INTO cms_session_values (session_id, key, value) SELECT $id, $key, $value WHERE ${live}
268
- ON CONFLICT (session_id, key) DO UPDATE SET value = excluded.value`, params: { $id: sessionId, $key: key, $value: encoded, $now: at } },
269
- { rql: 'UPDATE cms_sessions SET expires_at = $expires WHERE id = $id AND expires_at > $now', params: { $id: sessionId, $expires: at + ttlMs, $now: at } },
270
- ], { kind: 'cms.session', retryConflicts: 5 });
271
- },
272
- async unset(sessionId, key) {
273
- if (!TOKEN.test(sessionId)) return;
274
- await db.write([{ rql: 'DELETE FROM cms_session_values WHERE session_id = $id AND key = $key', params: { $id: sessionId, $key: key } }], { kind: 'cms.session', retryConflicts: 5 });
275
- },
276
- async destroy(sessionId) {
277
- if (!TOKEN.test(sessionId)) return;
278
- await db.write([
279
- { rql: 'DELETE FROM cms_session_values WHERE session_id = $id', params: { $id: sessionId } },
280
- { rql: 'DELETE FROM cms_sessions WHERE id = $id', params: { $id: sessionId } },
281
- ], { kind: 'cms.session', retryConflicts: 5 });
282
- },
283
- async bindUser(sessionId, userId) {
284
- if (!TOKEN.test(sessionId)) return;
285
- await db.write([{ rql: 'UPDATE cms_sessions SET user_id = $user WHERE id = $id', params: { $id: sessionId, $user: userId } }], { kind: 'cms.session', retryConflicts: 5 });
286
- },
287
- async purgeExpired() {
288
- const at = now();
289
- const expired = await db.read([{ rql: 'SELECT 1 FROM cms_sessions WHERE expires_at <= $now LIMIT 1', params: { $now: at } }]);
290
- if (!expired.results[0]!.rows.length) return 0;
291
- const result = await db.write([
292
- { rql: 'DELETE FROM cms_session_values WHERE session_id IN (SELECT id FROM cms_sessions WHERE expires_at <= $now LIMIT 500)', params: { $now: at } },
293
- { rql: 'DELETE FROM cms_sessions WHERE id IN (SELECT id FROM cms_sessions WHERE expires_at <= $now LIMIT 500)', params: { $now: at } },
294
- ], { kind: 'cms.session', retryConflicts: 5 });
295
- return Number(result.results[1]!.affected);
296
- },
297
- };
298
- }
7
+ import { rqlDatabase, type RomeDB } from '@cossackframework/romedb';
299
8
 
300
9
  /** Job ledger with the same lease and fencing semantics as the D1 store. */
301
10
  export function createJobStore(db: RomeDB): JobStore {
@@ -306,9 +15,3 @@ export function createJobStore(db: RomeDB): JobStore {
306
15
  export function createNotificationStore(db: RomeDB): NotificationStore {
307
16
  return createSqlNotificationStore(rqlDatabase(db, { kind: 'cms.notifications' }));
308
17
  }
309
-
310
- function assertRecord(record: AuthSessionRecord): void {
311
- if (!TOKEN.test(record.id) || typeof record.userId !== 'string' || !record.userId || !Number.isSafeInteger(record.createdAt) || !Number.isSafeInteger(record.expiresAt)) {
312
- throw new TypeError('Invalid auth session record.');
313
- }
314
- }
@@ -13,6 +13,7 @@ import type { TaxonomyDeclaration, TermShape } from '../taxonomy';
13
13
  import { containsPattern, inList } from './users';
14
14
  import { uuidv7 } from '@cossackframework/core';
15
15
  import { readBatches, readByIds, readPaged } from './budget';
16
+ import { uniqueFieldOf, type FieldValues } from './field-values';
16
17
 
17
18
  export type { TaxonomyDeclaration, TermShape };
18
19
 
@@ -42,7 +43,7 @@ export type MetaCheck = (meta: unknown, previous: { readonly [field: string]: un
42
43
  const ID = /^[A-Za-z0-9_-]{1,80}$/;
43
44
  const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
44
45
  const WRITE = { kind: 'cms.terms', retryConflicts: 5 } as const;
45
- const COLUMNS = 'id, taxonomy, name, slug, description, parent_id, path, depth, created_at, updated_at, icon, meta';
46
+ const COLUMNS = 'id, taxonomy, name, slug, description, parent_id, path, depth, created_at, updated_at, icon';
46
47
  const ICON = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
47
48
  const MAX_TERMS = 1000;
48
49
 
@@ -55,6 +56,7 @@ export class CmsTaxonomies {
55
56
  readonly #slugChanged: ((taxonomy: TaxonomyDeclaration, from: string, to: string, guard: { rql: string; params: { [key: string]: Value } }) => Statement[]) | undefined;
56
57
  readonly #beforeSave: ((draft: TermDraft, input: TermWriteInput) => Promise<TermDraft>) | undefined;
57
58
  readonly #checkMeta: ((taxonomy: string) => MetaCheck) | undefined;
59
+ readonly #fields: ((taxonomy: string) => FieldValues | null) | undefined;
58
60
  readonly #changed: (() => void | Promise<void>) | undefined;
59
61
 
60
62
  constructor(db: RomeDB, options: {
@@ -69,6 +71,8 @@ export class CmsTaxonomies {
69
71
  beforeSave?: (draft: TermDraft, input: TermWriteInput) => Promise<TermDraft>;
70
72
  /** The meta check for a taxonomy's field groups. */
71
73
  checkMeta?: (taxonomy: string) => MetaCheck;
74
+ /** Where a taxonomy's terms keep their field values: a document beside each term. Null while the taxonomy has no fields. */
75
+ fields?: (taxonomy: string) => FieldValues | null;
72
76
  /** Called after a committed change, for the host to purge the site's pages: terms show on entries and in menus. */
73
77
  changed?: () => void | Promise<void>;
74
78
  now?: () => number;
@@ -81,6 +85,7 @@ export class CmsTaxonomies {
81
85
  this.#slugChanged = options.slugChanged;
82
86
  this.#beforeSave = options.beforeSave;
83
87
  this.#checkMeta = options.checkMeta;
88
+ this.#fields = options.fields;
84
89
  this.#changed = options.changed;
85
90
  }
86
91
 
@@ -104,7 +109,7 @@ export class CmsTaxonomies {
104
109
  if (!wanted.length) return new Map();
105
110
  // Terms hold a description and meta: many may come in smaller reads.
106
111
  const rows = await readByIds(this.#db, wanted, slice => { const list = inList('t', slice); return { rql: `SELECT ${COLUMNS} FROM cms_terms WHERE id IN ${list.rql}`, params: list.params }; });
107
- return new Map(rows.map(row => { const term = termOf(row); return [term.id, term]; }));
112
+ return new Map((await this.#terms(rows)).map(term => [term.id, term]));
108
113
  }
109
114
 
110
115
  async bySlug(taxonomy: string, slug: string): Promise<TermShape | null> {
@@ -112,7 +117,7 @@ export class CmsTaxonomies {
112
117
  if (!SLUG.test(slug)) return null;
113
118
  const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE taxonomy = $taxonomy AND slug = $slug`, params: { $taxonomy: taxonomy, $slug: slug } }]);
114
119
  const row = result.results[0]!.rows[0];
115
- return row ? termOf(row) : null;
120
+ return row ? (await this.#terms([row]))[0]! : null;
116
121
  }
117
122
 
118
123
  /** Terms by name, with search and pagination. */
@@ -124,13 +129,32 @@ export class CmsTaxonomies {
124
129
  const counted = await this.#db.read([{ rql: `SELECT count(*) FROM cms_terms WHERE ${where}`, params }]);
125
130
  const rows = await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE ${where} ORDER BY lower(name), id LIMIT $limit OFFSET $offset`, params: { ...params, $limit: size, $offset: at } }),
126
131
  Math.min(Math.max(options.limit ?? 50, 1), 200), Math.max(options.offset ?? 0, 0), { afterSequence: counted.sequence });
127
- return { items: rows.map(termOf), total: Number(counted.results[0]!.rows[0]![0] as bigint) };
132
+ return { items: await this.#terms(rows), total: Number(counted.results[0]!.rows[0]![0] as bigint) };
133
+ }
134
+
135
+ /**
136
+ * Terms from their rows, with their field values. The values are documents beside the rows,
137
+ * one table per taxonomy that has fields: a taxonomy without fields costs no read.
138
+ */
139
+ async #terms(rows: readonly (readonly Value[])[]): Promise<TermShape[]> {
140
+ const byTaxonomy = new Map<string, string[]>();
141
+ for (const row of rows) byTaxonomy.set(row[1] as string, [...(byTaxonomy.get(row[1] as string) ?? []), row[0] as string]);
142
+ const values = new Map<string, { readonly [field: string]: unknown }>();
143
+ await Promise.all([...byTaxonomy].map(async ([taxonomy, ids]) => {
144
+ const store = this.#fields?.(taxonomy);
145
+ if (!store) return;
146
+ for (let at = 0; at < ids.length; at += 200) {
147
+ const found = store.decode(await readByIds(this.#db, ids.slice(at, at + 200), slice => store.readStatement(slice)));
148
+ for (const [id, entry] of found) values.set(id, entry);
149
+ }
150
+ }));
151
+ return rows.map(row => termOf(row, values.get(row[0] as string) ?? NO_VALUES));
128
152
  }
129
153
 
130
154
  /** Every term in tree order: each parent before its children, siblings by name. */
131
155
  async tree(taxonomy: string): Promise<TermShape[]> {
132
156
  this.declaration(taxonomy);
133
- const terms = (await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE taxonomy = $taxonomy ORDER BY path LIMIT $limit OFFSET $offset`, params: { $taxonomy: taxonomy, $limit: size, $offset: at } }), MAX_TERMS, 0)).map(termOf);
157
+ const terms = await this.#terms(await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE taxonomy = $taxonomy ORDER BY path LIMIT $limit OFFSET $offset`, params: { $taxonomy: taxonomy, $limit: size, $offset: at } }), MAX_TERMS, 0));
134
158
  const children = new Map<string | null, TermShape[]>();
135
159
  const known = new Set(terms.map(term => term.id));
136
160
  for (const term of terms) {
@@ -192,11 +216,14 @@ export class CmsTaxonomies {
192
216
  const params = {
193
217
  $id: id, $taxonomy: taxonomy, $name: name, $slug: slug, $description: checkDescription(draft.description), $parent: parent?.id ?? null,
194
218
  $path: `${parent?.path ?? '/'}${id}/`, $depth: parent ? parent.depth + 1 : 0, $now: now, $parentPath: parent?.path ?? null, $icon: checkIcon(draft.icon),
195
- $meta: JSON.stringify(draft.meta ?? {}),
196
219
  };
197
220
  // A parent that moved or disappeared since it was read inserts nothing.
198
221
  const guard = parent ? ' WHERE EXISTS (SELECT 1 FROM cms_terms WHERE id = $parent AND path = $parentPath)' : '';
199
- const result = await this.#write([bound(`INSERT INTO cms_terms (${COLUMNS}) SELECT $id, $taxonomy, $name, $slug, $description, $parent, $path, $depth, $now, $now, $icon, $meta${guard}`, params)]);
222
+ const result = await this.#write([
223
+ bound(`INSERT INTO cms_terms (${COLUMNS}) SELECT $id, $taxonomy, $name, $slug, $description, $parent, $path, $depth, $now, $now, $icon${guard}`, params),
224
+ // The term's field values, in the same write and only when the term was made.
225
+ ...this.#values(taxonomy, id, draft.meta ?? {}, null, { rql: 'EXISTS (SELECT 1 FROM cms_terms WHERE id = $tId)', params: { $tId: id } }),
226
+ ]);
200
227
  if (result.results[0]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The parent changed while the term was saved. Try again.');
201
228
  return (await this.get(id))!;
202
229
  }
@@ -236,11 +263,14 @@ export class CmsTaxonomies {
236
263
  $parent: parent?.id ?? null, $parentPath: parent?.path ?? null,
237
264
  }));
238
265
  }
239
- statements.push({ rql: `UPDATE cms_terms SET name = $name, slug = $slug, description = $description, parent_id = $parentId, icon = $icon, meta = $meta, updated_at = $now WHERE id = $id AND path = $path`,
240
- params: { $name: name, $slug: slug, $description: description, $parentId: parentId, $icon: icon, $meta: JSON.stringify(draft.meta ?? {}), $now: now, $id: id, $path: path } });
266
+ statements.push({ rql: `UPDATE cms_terms SET name = $name, slug = $slug, description = $description, parent_id = $parentId, icon = $icon, updated_at = $now WHERE id = $id AND path = $path`,
267
+ params: { $name: name, $slug: slug, $description: description, $parentId: parentId, $icon: icon, $now: now, $id: id, $path: path } });
241
268
  const own = statements.length - 1;
269
+ // The term's field values, in the same write and only when the term's own update applied.
270
+ const applied = { rql: 'EXISTS (SELECT 1 FROM cms_terms WHERE id = $tId AND slug = $tSlug AND updated_at = $tNow)', params: { $tId: id, $tSlug: slug, $tNow: now } };
271
+ if (draft.meta !== term.meta) statements.push(...this.#values(term.taxonomy, id, draft.meta ?? {}, term.meta, applied));
242
272
  if (slug !== term.slug && this.#slugChanged) {
243
- statements.push(...this.#slugChanged(declaration, term.slug, slug, { rql: 'EXISTS (SELECT 1 FROM cms_terms WHERE id = $tId AND slug = $tSlug AND updated_at = $tNow)', params: { $tId: id, $tSlug: slug, $tNow: now } }));
273
+ statements.push(...this.#slugChanged(declaration, term.slug, slug, applied));
244
274
  }
245
275
  const result = await this.#write(statements);
246
276
  if (result.results[own]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The term changed while it was saved. Reload and try again.');
@@ -263,6 +293,7 @@ export class CmsTaxonomies {
263
293
  bound(`UPDATE cms_terms SET path = $parentPath || substr(path, $length + 1), depth = depth - 1, updated_at = $now
264
294
  WHERE taxonomy = $taxonomy AND path LIKE $prefix AND id != $id AND ${guard}`, params),
265
295
  bound('DELETE FROM cms_terms WHERE id = $id AND path = $path', params),
296
+ ...this.#removed(term.taxonomy, id),
266
297
  ]);
267
298
  if (result.results[2]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The term changed while it was deleted. Reload and try again.');
268
299
  }
@@ -287,7 +318,7 @@ export class CmsTaxonomies {
287
318
  const id = uuidv7();
288
319
  bySlug.set(slug, id);
289
320
  // A term another request created first wins; its ID is read back below.
290
- return { rql: `INSERT INTO cms_terms (${COLUMNS}) VALUES ($id, $taxonomy, $name, $slug, '', NULL, $path, 0, $now, $now, '', '{}') ON CONFLICT (taxonomy, slug) DO NOTHING`,
321
+ return { rql: `INSERT INTO cms_terms (${COLUMNS}) VALUES ($id, $taxonomy, $name, $slug, '', NULL, $path, 0, $now, $now, '') ON CONFLICT (taxonomy, slug) DO NOTHING`,
291
322
  params: { $id: id, $taxonomy: taxonomy, $name: checkName(name), $slug: SLUG.test(slug) ? slug : slugify(slug) || `term-${id.slice(0, 8)}`, $path: `/${id}/`, $now: now } };
292
323
  });
293
324
  await this.#write(statements);
@@ -310,6 +341,21 @@ export class CmsTaxonomies {
310
341
  }
311
342
 
312
343
  /** The draft after the before-save filter, when the host has one. */
344
+ /** Statements that store a term's field values, applied only while `guard` holds. Nothing for a taxonomy without fields. */
345
+ #values(taxonomy: string, id: string, values: { readonly [field: string]: unknown }, previous: { readonly [field: string]: unknown } | null, guard: { rql: string; params: { [key: string]: Value } }): Statement[] {
346
+ const store = this.#fields?.(taxonomy);
347
+ if (!store || (!Object.keys(values).length && !Object.keys(previous ?? {}).length)) return [];
348
+ return store.save(id, values, previous, crypto.randomUUID(), guard);
349
+ }
350
+
351
+ /** The statement that removes a deleted term's field values, once its row is gone. */
352
+ #removed(taxonomy: string, id: string): Statement[] {
353
+ const store = this.#fields?.(taxonomy);
354
+ if (!store) return [];
355
+ const remove = store.remove(id);
356
+ return [{ rql: `${remove.rql} AND NOT EXISTS (SELECT 1 FROM cms_terms WHERE id = $tId)`, params: { ...remove.params, $tId: id } }];
357
+ }
358
+
313
359
  /** The meta to store: the field groups' check, or the input as given when the taxonomy has none. */
314
360
  async #meta(taxonomy: string, meta: unknown, previous: { readonly [field: string]: unknown } | null, principal: Principal): Promise<{ readonly [field: string]: unknown }> {
315
361
  if (this.#checkMeta) return this.#checkMeta(taxonomy)(meta, previous, principal);
@@ -351,6 +397,9 @@ export class CmsTaxonomies {
351
397
  await this.#changed?.();
352
398
  return result;
353
399
  } catch (error) {
400
+ // A unique field of the term's document, or the term's slug.
401
+ const name = error instanceof ClientError && error.outcome === 'rolled-back' ? uniqueFieldOf(error.message) : undefined;
402
+ if (name !== undefined) throw new CmsError('CMS_CONFLICT', 'Another term has the same value in a unique field.', name ? { fields: { [name]: 'is taken.' } } : {});
354
403
  if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|constraint/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'A term with this slug already exists.', { fields: { slug: 'is taken.' } });
355
404
  throw error;
356
405
  }
@@ -369,12 +418,14 @@ function bound(rql: string, params: { readonly [key: string]: Value }): Statemen
369
418
  return used.length ? { rql, params: Object.fromEntries(used) } : { rql };
370
419
  }
371
420
 
372
- function termOf(row: readonly Value[]): TermShape {
421
+ const NO_VALUES: { readonly [field: string]: unknown } = Object.freeze({});
422
+
423
+ function termOf(row: readonly Value[], meta: { readonly [field: string]: unknown }): TermShape {
373
424
  return Object.freeze({
374
425
  id: row[0] as string, taxonomy: row[1] as string, name: row[2] as string, slug: row[3] as string, description: row[4] as string,
375
426
  parent: row[5] as string | null, path: row[6] as string, depth: Number(row[7] as bigint), createdAt: Number(row[8] as bigint), updatedAt: Number(row[9] as bigint),
376
427
  icon: typeof row[10] === 'string' ? row[10] : '',
377
- meta: parseMeta(row[11]),
428
+ meta,
378
429
  });
379
430
  }
380
431