@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.
- package/agent-docs.json +8 -8
- package/app/cossack-recipe.json +12 -8
- package/app/src/auth-events.ts +33 -0
- package/app/src/auth-input.ts +3 -0
- package/app/src/auth-options.ts +39 -7
- package/app/src/auth.ts +1309 -641
- package/app/src/avatars.ts +13 -0
- package/app/src/brand.ts +24 -2
- package/app/src/cms/actor.ts +13 -0
- package/app/src/cms/collab/room.ts +1 -1
- package/app/src/cms/content-api.ts +2 -1
- package/app/src/cms/content.ts +3 -2
- package/app/src/cms/dev-mail.ts +77 -0
- package/app/src/cms/index.ts +37 -10
- package/app/src/cms/maintenance.ts +1 -6
- package/app/src/cms/manage.ts +17 -14
- package/app/src/cms/middleware.ts +58 -18
- package/app/src/cms/network-accounts.ts +110 -0
- package/app/src/cms/notes-announce.ts +1 -1
- package/app/src/cms/people.ts +177 -0
- package/app/src/cms/recovery.ts +9 -14
- package/app/src/cms/request-calls.ts +56 -0
- package/app/src/cms/settings-form.ts +23 -6
- package/app/src/cms/settings-network.ts +8 -4
- package/app/src/cms/settings-search.ts +1 -0
- package/app/src/cms/site-editing.ts +3 -2
- package/app/src/cms/site-registration.ts +64 -0
- package/app/src/cms/site.ts +30 -19
- package/app/src/cms/sites.ts +182 -0
- package/app/src/dashboard/access.ts +3 -2
- package/app/src/dashboard/modules/users.ts +1 -0
- package/app/src/lib/permissions.ts +24 -0
- package/app/src/lib/uuid.ts +6 -0
- package/app/src/mail.ts +15 -0
- package/app/src/middlewares/auth.ts +6 -2
- package/app/src/middlewares/tenant.ts +108 -0
- package/app/src/pages/(site)/[...path]/index.ts +1 -1
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
- package/app/src/pages/api/cms/dev/mail.ts +19 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
- package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
- package/app/src/pages/auth/login/index.ts +1 -1
- package/app/src/pages/auth/magic/index.ts +1 -1
- package/app/src/pages/auth/recovery.ts +20 -0
- package/app/src/pages/auth/register-site/index.ts +146 -0
- package/app/src/pages/auth/setup/index.ts +8 -3
- package/app/src/pages/auth/tenant/callback.ts +23 -0
- package/app/src/pages/auth/tenant/redirect.ts +91 -0
- package/app/src/pages/auth/verify/index.ts +3 -7
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
- package/app/src/pages/dashboard/index.ts +3 -2
- package/app/src/pages/dashboard/roles/index.ts +2 -2
- package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
- package/app/src/services/api-tokens.ts +86 -0
- package/app/src/services/rbac.ts +26 -15
- package/app/src/services/roles.ts +125 -35
- package/app/src/services/security.ts +384 -0
- package/app/src/services/tenants.ts +447 -0
- package/app/src/services/users.ts +241 -97
- package/app/src/tenants.ts +219 -0
- package/package.json +48 -12
- package/src/block-references.ts +3 -3
- package/src/collections.ts +3 -1
- package/src/forms.ts +4 -2
- package/src/hooks.ts +19 -1
- package/src/index.ts +4 -4
- package/src/isolate-core.ts +1 -1
- package/src/isolation.ts +1 -0
- package/src/manifest.ts +43 -2
- package/src/permissions.ts +13 -7
- package/src/resource.ts +85 -2
- package/src/server/attempts.ts +64 -0
- package/src/server/automations.ts +2 -2
- package/src/server/batch.ts +106 -0
- package/src/server/budget.ts +17 -0
- package/src/server/field-values.ts +207 -0
- package/src/server/forms.ts +3 -3
- package/src/server/host-schema.ts +55 -7
- package/src/server/host.ts +213 -85
- package/src/server/index.ts +9 -14
- package/src/server/isolation.ts +10 -0
- package/src/server/network.ts +129 -44
- package/src/server/outbox.ts +2 -2
- package/src/server/people.ts +191 -0
- package/src/server/reconcile.ts +5 -5
- package/src/server/repository.ts +243 -84
- package/src/server/shared-read.ts +34 -0
- package/src/server/site-export.ts +23 -13
- package/src/server/site-import.ts +12 -33
- package/src/server/site-settings.ts +9 -3
- package/src/server/sites.ts +117 -187
- package/src/server/stores.ts +3 -300
- package/src/server/taxonomies.ts +64 -13
- package/src/server/users.ts +151 -498
- package/src/settings-controls.ts +8 -4
- package/src/settings.ts +26 -3
- package/src/storage/cloudflare.ts +2 -0
- package/src/storage/index.ts +6 -0
- package/src/theme.ts +2 -2
- package/src/version.ts +1 -1
- package/app/src/cms/handoff.ts +0 -202
- package/src/server/accounts.ts +0 -418
- package/src/server/api-tokens.ts +0 -91
- package/src/server/auth.ts +0 -89
- package/src/server/handoffs.ts +0 -107
- package/src/server/security.ts +0 -391
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Write batches: several record writes that commit together in one RomeDB request, or not at
|
|
3
|
+
* all, under guards that count other records in the same request. Each write is prepared as it
|
|
4
|
+
* would be alone (access, validation, write filters); every condition the batch needs (the
|
|
5
|
+
* guards, each record still as it was read, a membership) becomes a `cms_assertions` row whose
|
|
6
|
+
* CHECK rolls the whole request back when it does not hold.
|
|
7
|
+
*/
|
|
8
|
+
import { ClientError, MAX_STATEMENTS, RequestTooLargeError, statementBytes, UncertainWriteError, type Statement } from '@cossackframework/romedb';
|
|
9
|
+
import { CmsError } from '../errors';
|
|
10
|
+
import type { RecordShape } from '../records';
|
|
11
|
+
import { assertionStatements, isAssertionFailure, type BatchGuard, type BatchWrite, type OperationContext, type PreparedWrite } from './repository';
|
|
12
|
+
import type { CmsHost } from './host';
|
|
13
|
+
|
|
14
|
+
/** Writes and guards one batch takes. */
|
|
15
|
+
export const BATCH_LIMITS = Object.freeze({ writes: 10, guards: 10 });
|
|
16
|
+
|
|
17
|
+
/** The resource a batch write names. */
|
|
18
|
+
export function batchResource(write: BatchWrite): string {
|
|
19
|
+
return 'create' in write ? write.create : 'update' in write ? write.update : write.delete;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** What a batch refused names: a guard by its name, or a record by `<resource>:<id>`. */
|
|
23
|
+
interface Condition {
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly kind: 'guard' | 'record' | 'member';
|
|
26
|
+
readonly statement: Statement;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Run the writes in order, in one request: every one commits, or none does. Returns each
|
|
31
|
+
* write's record as the principal reads it (null for a delete). Refusals: `CMS_CONFLICT` when
|
|
32
|
+
* a guard does not hold or a record changed since it was read (`fields` names them),
|
|
33
|
+
* `CMS_FORBIDDEN` for a membership the principal lacks, and what each write refuses alone.
|
|
34
|
+
*/
|
|
35
|
+
export async function writeBatch(host: CmsHost, writes: readonly BatchWrite[], context: OperationContext & { readonly guards?: readonly BatchGuard[] }): Promise<(RecordShape | null)[]> {
|
|
36
|
+
if (!Array.isArray(writes) || writes.length < 1 || writes.length > BATCH_LIMITS.writes) throw new CmsError('CMS_VALIDATION', `A batch has 1-${BATCH_LIMITS.writes} writes.`);
|
|
37
|
+
const guards = context.guards ?? [];
|
|
38
|
+
if (!Array.isArray(guards) || guards.length > BATCH_LIMITS.guards) throw new CmsError('CMS_VALIDATION', `A batch has at most ${BATCH_LIMITS.guards} guards.`);
|
|
39
|
+
const names = new Set<string>();
|
|
40
|
+
for (const guard of guards) {
|
|
41
|
+
if (!guard || typeof guard.name !== 'string' || !/^[A-Za-z0-9_.:-]{1,80}$/.test(guard.name) || names.has(guard.name)) throw new CmsError('CMS_VALIDATION', 'Each guard needs a distinct name of letters, digits, dots, colons, underscores or hyphens.');
|
|
42
|
+
names.add(guard.name);
|
|
43
|
+
}
|
|
44
|
+
// A record written twice would be checked against its first state only.
|
|
45
|
+
const touched = new Set<string>();
|
|
46
|
+
for (const write of writes) {
|
|
47
|
+
if (!write || typeof write !== 'object') throw new CmsError('CMS_VALIDATION', 'A write creates, updates or deletes a record.');
|
|
48
|
+
const id = 'create' in write ? write.id : write.id;
|
|
49
|
+
if (id === undefined) continue;
|
|
50
|
+
const key = `${batchResource(write)}:${id}`;
|
|
51
|
+
if (touched.has(key)) throw new CmsError('CMS_VALIDATION', `A batch writes ${key} once.`);
|
|
52
|
+
touched.add(key);
|
|
53
|
+
}
|
|
54
|
+
const prepared: PreparedWrite[] = [];
|
|
55
|
+
for (const write of writes) prepared.push(await host.resource(batchResource(write)).prepare(write, context));
|
|
56
|
+
const conditions: Condition[] = [
|
|
57
|
+
...guards.map(guard => ({ name: guard.name, kind: 'guard' as const, statement: host.resource(guard.resource).guardCondition(guard) })),
|
|
58
|
+
...prepared.flatMap(write => [
|
|
59
|
+
...(write.precondition ? [{ name: `${write.resource}:${write.id}`, kind: 'record' as const, statement: write.precondition }] : []),
|
|
60
|
+
...write.assertions.map(statement => ({ name: `${write.resource}:${write.id}`, kind: 'member' as const, statement })),
|
|
61
|
+
]),
|
|
62
|
+
];
|
|
63
|
+
// The first write's operation ID names the request: its audit row is how recovery knows the batch committed.
|
|
64
|
+
const op = prepared[0]!.op;
|
|
65
|
+
const assertions = assertionStatements(conditions.map(condition => condition.statement), op);
|
|
66
|
+
const statements = [...assertions.insert, ...prepared.flatMap(write => write.statements), ...assertions.remove];
|
|
67
|
+
if (statements.length > MAX_STATEMENTS || statementBytes(statements) > await host.db.maxRequestBytes() - 2048) {
|
|
68
|
+
throw new CmsError('CMS_LIMIT', 'These changes are too large for one batch. Make fewer at a time.');
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
await host.db.write(statements, { requestId: op, kind: 'cms.resource.write', ...(context.signal ? { signal: context.signal } : {}), workLimits: host.writeLimits });
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error instanceof RequestTooLargeError) throw new CmsError('CMS_LIMIT', 'These changes are too large for one batch. Make fewer at a time.', { cause: error });
|
|
74
|
+
if (error instanceof UncertainWriteError) throw new CmsError('CMS_UNCERTAIN', 'The changes were sent but not confirmed. They will be completed or reported shortly.', { requestId: error.requestId, cause: error });
|
|
75
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back') {
|
|
76
|
+
if (isAssertionFailure(error)) throw await refusal(host, conditions, context, error);
|
|
77
|
+
if (error.code === 'RDB_WRITE_CONFLICT') throw new CmsError('CMS_CONFLICT', 'A record changed while the batch ran. Reload and try again.', { cause: error });
|
|
78
|
+
if (error.code === 'RDB_LIMIT') throw new CmsError('CMS_LIMIT', 'These changes are too large for one write. Make them in smaller steps.', { cause: error });
|
|
79
|
+
if (error.code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'A record with the same ID or unique value already exists.', { cause: error });
|
|
80
|
+
if (error.code === 'RDB_VALIDATION') throw new CmsError('CMS_VALIDATION', 'The database rejected the values.', { cause: error });
|
|
81
|
+
}
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
host.outboxWritten();
|
|
85
|
+
return prepared.map(write => write.record);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Which conditions did not hold, read again after the refusal: the batch reports them by name.
|
|
90
|
+
* A condition that changed back since is not named; the refusal stands.
|
|
91
|
+
*/
|
|
92
|
+
async function refusal(host: CmsHost, conditions: readonly Condition[], context: OperationContext, cause: ClientError): Promise<CmsError> {
|
|
93
|
+
let failed: Condition[] = [];
|
|
94
|
+
try {
|
|
95
|
+
const result = await host.db.read(conditions.map(condition => ({ ...condition.statement, rql: `SELECT CASE WHEN ${condition.statement.rql} THEN 1 ELSE 0 END` })), {
|
|
96
|
+
...(context.signal ? { signal: context.signal } : {}), workLimits: host.readLimits,
|
|
97
|
+
});
|
|
98
|
+
failed = conditions.filter((_, index) => Number(result.results[index]!.rows[0]?.[0] ?? 0) !== 1);
|
|
99
|
+
} catch { /* the refusal stands without names */ }
|
|
100
|
+
if (failed.some(condition => condition.kind === 'member') && failed.every(condition => condition.kind === 'member')) {
|
|
101
|
+
return new CmsError('CMS_FORBIDDEN', 'A record of the batch is somewhere you are not a member.', { cause, fields: Object.fromEntries(failed.map(condition => [condition.name, 'is not yours to write there.'])) });
|
|
102
|
+
}
|
|
103
|
+
const fields = Object.fromEntries(failed.map(condition => [condition.name, condition.kind === 'guard' ? 'does not hold.' : condition.kind === 'record' ? 'changed since it was read.' : 'is not yours to write there.']));
|
|
104
|
+
const message = failed.length ? `The batch was not written: ${failed.map(condition => condition.name).join(', ')} ${failed.length === 1 ? 'does' : 'do'} not hold.` : 'The batch was not written: a condition did not hold.';
|
|
105
|
+
return new CmsError('CMS_CONFLICT', message, { cause, ...(failed.length ? { fields } : {}) });
|
|
106
|
+
}
|
package/src/server/budget.ts
CHANGED
|
@@ -72,6 +72,23 @@ export async function readPaged(db: RomeDB, statement: (limit: number, offset: n
|
|
|
72
72
|
return rows;
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/**
|
|
76
|
+
* {@link readPaged} for several lists at once: up to `count` rows of each in one request, one
|
|
77
|
+
* statement per list, so a request makes one read where it would make one per list. When the
|
|
78
|
+
* result is over the budget, the lists are read one after another in smaller pages.
|
|
79
|
+
*/
|
|
80
|
+
export async function readPagedTogether(db: RomeDB, statements: readonly ((limit: number, offset: number) => Statement)[], count: number, options: ReadOptions = {}): Promise<Row[][]> {
|
|
81
|
+
try {
|
|
82
|
+
const result = await db.read(statements.map(statement => statement(count, 0)), options);
|
|
83
|
+
return result.results.map(list => list.rows);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!isResultTooLarge(error)) throw error;
|
|
86
|
+
}
|
|
87
|
+
const lists: Row[][] = [];
|
|
88
|
+
for (const statement of statements) lists.push(await readPaged(db, statement, count, 0, options));
|
|
89
|
+
return lists;
|
|
90
|
+
}
|
|
91
|
+
|
|
75
92
|
/**
|
|
76
93
|
* Read the rows for `ids` with one statement per slice of them, in as few reads as the result
|
|
77
94
|
* budget allows: a slice whose result is too large is read again in halves. For `WHERE id IN`
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a field's value is kept in a document, and read back: the same for an entry of a
|
|
3
|
+
* collection and for the field values of a user or a term. A reference is a record link, a
|
|
4
|
+
* fractional number an explicit float, and rich text, blocks and rows are nested values.
|
|
5
|
+
*/
|
|
6
|
+
import { Float64, RecordId, Vector, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
|
|
7
|
+
import { SYSTEM_META } from '../field-groups';
|
|
8
|
+
import { readByIds } from './budget';
|
|
9
|
+
import { validateValue, type FieldDeclaration } from '../fields';
|
|
10
|
+
import type { Resource } from '../resource';
|
|
11
|
+
|
|
12
|
+
/** The value to store for a field. `storageOf` names the collection a reference's target is kept in. */
|
|
13
|
+
export function storedValue(declaration: FieldDeclaration, value: unknown, storageOf: (resourceId: string) => string): Value {
|
|
14
|
+
if (value === null) return null;
|
|
15
|
+
// A multiple field stores its items as the kind stores one.
|
|
16
|
+
if (declaration.multiple) return (value as unknown[]).map(item => storedValue({ ...declaration, multiple: false }, item, storageOf));
|
|
17
|
+
switch (declaration.kind) {
|
|
18
|
+
case 'bigint': return BigInt(value as string | bigint);
|
|
19
|
+
case 'number': return new Float64(value as number);
|
|
20
|
+
case 'reference': return new RecordId(storageOf(declaration.target!), value as string);
|
|
21
|
+
case 'vector': return Vector.float32(value as number[]);
|
|
22
|
+
case 'json': case 'blocks': case 'richtext': case 'rows': return storedJson(value);
|
|
23
|
+
default: return value as Value;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A stored value as the application reads it: a reference is the key of its record. */
|
|
28
|
+
export function publicValue(declaration: FieldDeclaration, value: Value): unknown {
|
|
29
|
+
if (value === null) return null;
|
|
30
|
+
if (declaration.multiple) return Array.isArray(value) ? value.map(item => publicValue({ ...declaration, multiple: false }, item)) : [];
|
|
31
|
+
switch (declaration.kind) {
|
|
32
|
+
case 'integer': case 'datetime': return Number(value as bigint);
|
|
33
|
+
case 'bigint': return String(value);
|
|
34
|
+
case 'number': return value instanceof Float64 ? value.value : Number(value as bigint);
|
|
35
|
+
case 'reference': return value instanceof RecordId ? String(value.key) : null;
|
|
36
|
+
case 'json': case 'blocks': case 'richtext': case 'rows': return toJson(value);
|
|
37
|
+
case 'vector': {
|
|
38
|
+
const bytes = (value as Vector).bytes;
|
|
39
|
+
return [...new Float32Array(bytes.buffer, bytes.byteOffset, Math.floor(bytes.byteLength / 4))];
|
|
40
|
+
}
|
|
41
|
+
default: return value;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Plain JSON for storage: fractional numbers become explicit floats, integers stay int64. */
|
|
46
|
+
export function storedJson(value: unknown): Value {
|
|
47
|
+
if (typeof value === 'number') return Number.isInteger(value) ? value : new Float64(value);
|
|
48
|
+
if (Array.isArray(value)) return value.map(storedJson);
|
|
49
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, storedJson(entry)]));
|
|
50
|
+
return value as Value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A stored nested value as plain JSON. */
|
|
54
|
+
export function toJson(value: Value): unknown {
|
|
55
|
+
if (typeof value === 'bigint') return Number(value);
|
|
56
|
+
if (value instanceof Float64) return value.value;
|
|
57
|
+
if (value instanceof RecordId) return `${value.table}:${String(value.key)}`;
|
|
58
|
+
if (Array.isArray(value)) return value.map(toJson);
|
|
59
|
+
if (value && typeof value === 'object' && !(value instanceof Uint8Array) && !(value instanceof Vector)) {
|
|
60
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, toJson(entry)]));
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- The field values of a row -----------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
/** Keys of a values document that are the host's bookkeeping, not values. */
|
|
69
|
+
const BOOKKEEPING = new Set(['id', '_rev', '_op', '_createdAt', '_updatedAt', '_owner', '_media']);
|
|
70
|
+
const quote = (name: string) => `"${name}"`;
|
|
71
|
+
|
|
72
|
+
export interface FieldValuesOptions {
|
|
73
|
+
/** The internal resource whose fields these are, as it is now: the groups attached to the target change it. */
|
|
74
|
+
readonly resource: () => Resource;
|
|
75
|
+
/** The collection a reference's target is kept in. */
|
|
76
|
+
readonly storageOf: (resourceId: string) => string;
|
|
77
|
+
/** The media files a set of values names, kept beside them so "which rows use this file" is a filter. */
|
|
78
|
+
readonly media?: (values: { readonly [field: string]: unknown }) => readonly string[];
|
|
79
|
+
readonly now?: () => number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The field group values of rows that are not entries (users, terms), one document per row
|
|
84
|
+
* under the row's ID, in the storage of an internal resource. A field is a field of the
|
|
85
|
+
* document, stored as an entry's is, so the indexes the schema planner makes for the resource
|
|
86
|
+
* apply. Its statements go into the caller's write, so a row and its values change together.
|
|
87
|
+
*
|
|
88
|
+
* A value that is cleared is unset, never set to null: RomeDB refuses null in the parent of
|
|
89
|
+
* an indexed nested field (request Q2). Setting and unsetting are two statements (Q3).
|
|
90
|
+
*/
|
|
91
|
+
/**
|
|
92
|
+
* The field whose unique index refused a write, from the engine's message, which names a
|
|
93
|
+
* document index in hex. Undefined when the message is about something else.
|
|
94
|
+
*/
|
|
95
|
+
export function uniqueFieldOf(message: string): string | undefined {
|
|
96
|
+
const index = /UNIQUE constraint failed: __romedb_i_([0-9a-f]+)/i.exec(message);
|
|
97
|
+
if (!index) return undefined;
|
|
98
|
+
return (index[1]!.match(/../g) ?? []).map(pair => String.fromCharCode(parseInt(pair, 16))).join('').split('__u_')[1] ?? '';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class FieldValues {
|
|
102
|
+
readonly #db: RomeDB;
|
|
103
|
+
readonly #options: FieldValuesOptions;
|
|
104
|
+
readonly #now: () => number;
|
|
105
|
+
|
|
106
|
+
constructor(db: RomeDB, options: FieldValuesOptions) {
|
|
107
|
+
this.#db = db;
|
|
108
|
+
this.#options = options;
|
|
109
|
+
this.#now = options.now ?? Date.now;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
get storage(): string { return this.#options.resource().storage; }
|
|
113
|
+
|
|
114
|
+
#id(key: string): RecordId { return new RecordId(this.storage, key); }
|
|
115
|
+
|
|
116
|
+
#stored(name: string, value: unknown): Value {
|
|
117
|
+
const declaration = this.#options.resource().fields[name];
|
|
118
|
+
// A system value (`_recent_blocks`) has no declaration: it is kept as plain JSON.
|
|
119
|
+
return declaration ? storedValue(declaration, value, this.#options.storageOf) : storedJson(value);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Statements that make the row's values exactly `values`, given what it holds now
|
|
124
|
+
* (`previous`; null for a new row): the document is made when missing, changed fields are
|
|
125
|
+
* set, and fields no longer present are unset.
|
|
126
|
+
*/
|
|
127
|
+
save(key: string, values: { readonly [field: string]: unknown }, previous: { readonly [field: string]: unknown } | null, op: string, guard?: { readonly rql: string; readonly params: { readonly [key: string]: Value } }): Statement[] {
|
|
128
|
+
const now = this.#now();
|
|
129
|
+
const id = this.#id(key);
|
|
130
|
+
// The host's bookkeeping fields are never values.
|
|
131
|
+
const present = Object.entries(values).filter(([name, value]) => !BOOKKEEPING.has(name) && value !== undefined && value !== null);
|
|
132
|
+
const cleared = Object.keys(previous ?? {}).filter(name => !BOOKKEEPING.has(name) && (values[name] === undefined || values[name] === null));
|
|
133
|
+
const media = this.#options.media ? [...new Set(this.#options.media(Object.fromEntries(present)))].sort() : [];
|
|
134
|
+
const params: { [key: string]: Value } = { $id: id, $op: op, $now: now };
|
|
135
|
+
const assignments = ['"_rev" = "_rev" + 1', '"_op" = $op', '"_updatedAt" = $now'];
|
|
136
|
+
present.forEach(([name, value], index) => { params[`$v${index}`] = this.#stored(name, value); assignments.push(`${quote(name)} = $v${index}`); });
|
|
137
|
+
if (media.length) { params.$media = media; assignments.push('"_media" = $media'); }
|
|
138
|
+
// A guard is a condition on relational rows (the row these values belong to): a document write may carry one.
|
|
139
|
+
const when = guard ? ` AND ${guard.rql}` : '';
|
|
140
|
+
const guarded = guard?.params ?? {};
|
|
141
|
+
return [
|
|
142
|
+
// The document, when the row has none yet.
|
|
143
|
+
{ rql: `INSERT INTO ${this.storage} ("id", "_rev", "_op", "_createdAt", "_updatedAt") SELECT $id, 1, $op, $now, $now WHERE true${when} ON CONFLICT ("id") DO NOTHING`, params: { $id: id, $op: op, $now: now, ...guarded } },
|
|
144
|
+
{ rql: `UPDATE ${this.storage} SET ${assignments.join(', ')} WHERE id = $id${when}`, params: { ...params, ...guarded } },
|
|
145
|
+
...(cleared.length || !media.length ? [{ rql: `UPDATE ${this.storage} UNSET ${[...cleared, ...(media.length ? [] : ['_media'])].map(quote).join(', ')} WHERE id = $id${when}`, params: { $id: id, ...guarded } }] : []),
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Set one value without reading the others, or unset it (null): two writers of different fields both keep theirs. */
|
|
150
|
+
setOne(key: string, name: string, value: unknown, op: string): Statement[] {
|
|
151
|
+
if (BOOKKEEPING.has(name)) throw new TypeError(`${name} is not a value.`);
|
|
152
|
+
const now = this.#now();
|
|
153
|
+
const id = this.#id(key);
|
|
154
|
+
const ensure: Statement = { rql: `INSERT INTO ${this.storage} ("id", "_rev", "_op", "_createdAt", "_updatedAt") VALUES ($id, 1, $op, $now, $now) ON CONFLICT ("id") DO NOTHING`, params: { $id: id, $op: op, $now: now } };
|
|
155
|
+
if (value === null || value === undefined) return [ensure, { rql: `UPDATE ${this.storage} UNSET ${quote(name)} WHERE id = $id`, params: { $id: id } }];
|
|
156
|
+
return [ensure, { rql: `UPDATE ${this.storage} SET ${quote(name)} = $value, "_rev" = "_rev" + 1, "_op" = $op, "_updatedAt" = $now WHERE id = $id`, params: { $id: id, $value: this.#stored(name, value), $op: op, $now: now } }];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The statement that removes a row's values, for the write that removes the row. */
|
|
160
|
+
remove(key: string): Statement {
|
|
161
|
+
return { rql: `DELETE FROM ${this.storage} WHERE id = $id`, params: { $id: this.#id(key) } };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The statement that reads these rows' documents, 200 at most, for a read the caller batches. */
|
|
165
|
+
readStatement(keys: readonly string[]): Statement {
|
|
166
|
+
const params = Object.fromEntries(keys.map((key, index) => [`$k${index}`, this.#id(key) as Value]));
|
|
167
|
+
return { rql: `SELECT * FROM ${this.storage} WHERE id IN (${keys.map((_, index) => `$k${index}`).join(', ')})`, params };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The values of each row, by key, from the rows of `readStatement`. A row without a document has none. */
|
|
171
|
+
decode(rows: readonly (readonly Value[])[]): Map<string, { readonly [field: string]: unknown }> {
|
|
172
|
+
const fields = this.#options.resource().fields;
|
|
173
|
+
const result = new Map<string, { readonly [field: string]: unknown }>();
|
|
174
|
+
for (const row of rows) {
|
|
175
|
+
const document = row[0] as { [field: string]: Value } | null;
|
|
176
|
+
if (!document || !(document.id instanceof RecordId)) continue;
|
|
177
|
+
const values: { [field: string]: unknown } = {};
|
|
178
|
+
for (const [name, value] of Object.entries(document)) {
|
|
179
|
+
if (BOOKKEEPING.has(name) || value === null) continue;
|
|
180
|
+
const declaration = Object.hasOwn(fields, name) ? fields[name] : undefined;
|
|
181
|
+
if (!declaration) {
|
|
182
|
+
// The host's own values are kept as they are; a value of a field that is gone is not shown.
|
|
183
|
+
if (SYSTEM_META.test(name)) values[name] = toJson(value);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
// A value from before its field changed reads as unset, as an entry's does.
|
|
187
|
+
let shaped: unknown;
|
|
188
|
+
try { shaped = publicValue(declaration, value); } catch { shaped = undefined; }
|
|
189
|
+
if (shaped !== undefined && shaped !== null && validateValue(name, declaration, shaped) === undefined) values[name] = shaped;
|
|
190
|
+
}
|
|
191
|
+
result.set(String(document.id.key), Object.freeze(values));
|
|
192
|
+
}
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async read(keys: readonly string[]): Promise<Map<string, { readonly [field: string]: unknown }>> {
|
|
197
|
+
if (!keys.length) return new Map();
|
|
198
|
+
// Documents can be large: the keys are read in as few requests as the result budget allows.
|
|
199
|
+
return this.decode(await readByIds(this.#db, keys, slice => this.readStatement(slice)));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The keys of the rows whose values name this media file, 50 at most. */
|
|
203
|
+
async usingFile(fileId: string): Promise<string[]> {
|
|
204
|
+
const result = await this.#db.read([{ rql: `SELECT record::id(id) FROM ${this.storage} WHERE array::contains("_media", $file) LIMIT 50`, params: { $file: fileId } }]);
|
|
205
|
+
return result.results[0]!.rows.map(row => String(row[0]));
|
|
206
|
+
}
|
|
207
|
+
}
|
package/src/server/forms.ts
CHANGED
|
@@ -295,15 +295,15 @@ export class CmsForms {
|
|
|
295
295
|
}
|
|
296
296
|
}
|
|
297
297
|
// One send per address in the window, counted in one conditional write once the send is checked, so a burst gets one through.
|
|
298
|
-
if (ipHash && !(await this.#host.
|
|
298
|
+
if (ipHash && !(await this.#host.attempts.attempt('form', ipHash, 1, THROTTLE_MS))) throw new CmsError('CMS_LIMIT', 'You sent this form a moment ago. Wait a few seconds and try again.');
|
|
299
299
|
// Once per user or address: sends at the same moment are held to one by a claim on the key
|
|
300
300
|
// (a minute, by which time the first is stored), and stored ones by looking them up. A send
|
|
301
301
|
// that goes no further gives its claims back, so a retry is not refused for nothing.
|
|
302
302
|
const claims: string[] = [];
|
|
303
|
-
const release = () => Promise.all(claims.map(key => this.#host.
|
|
303
|
+
const release = () => Promise.all(claims.map(key => this.#host.attempts.release('form-once', key).catch(() => undefined)));
|
|
304
304
|
const claim = async (key: string) => {
|
|
305
305
|
const scoped = `${form.ref.id}:${key}`;
|
|
306
|
-
if (!(await this.#host.
|
|
306
|
+
if (!(await this.#host.attempts.attempt('form-once', scoped, 1, ONCE_CLAIM_MS))) return false;
|
|
307
307
|
claims.push(scoped);
|
|
308
308
|
return true;
|
|
309
309
|
};
|
|
@@ -19,13 +19,12 @@ const split = (script: string): Statement[] => script.split(';').map(rql => rql.
|
|
|
19
19
|
.map(rql => ({ rql: rql.replace(/\bIF NOT EXISTS\s+/g, '') }));
|
|
20
20
|
|
|
21
21
|
export const HOST_TABLES = [
|
|
22
|
-
'cms_migrations', 'cms_schema_state', '
|
|
23
|
-
'
|
|
24
|
-
'
|
|
25
|
-
'
|
|
26
|
-
'
|
|
27
|
-
'
|
|
28
|
-
'cms_drafts', 'cms_notes', 'cms_note_mentions', 'cms_schedules', 'cms_automations', 'cms_registrations', 'cms_search', 'cms_attempts', 'cms_schema_generations',
|
|
22
|
+
'cms_migrations', 'cms_schema_state', 'cms_grants', 'cms_audit', 'cms_revisions', 'cms_outbox', 'cms_files', 'cms_terms', 'cms_settings',
|
|
23
|
+
'cms_collections', 'cms_taxonomies', 'cms_field_groups', 'cms_menus', 'cms_menu_locations', 'cms_preview_tokens', 'cms_autosaves',
|
|
24
|
+
'cms_file_variants', 'cms_redirects', 'cms_webhooks', 'cms_webhook_deliveries', 'cms_comments', 'cms_areas', 'cms_form_sends', 'cms_form_mail',
|
|
25
|
+
'cms_form_results', 'cms_crawler_visits', 'cms_not_found', 'cms_cache', 'cms_network', 'cossack_jobs', 'cossack_notifications', 'cms_drafts',
|
|
26
|
+
'cms_notes', 'cms_note_mentions', 'cms_schedules', 'cms_automations', 'cms_search', 'cms_attempts', 'cms_schema_generations', 'cms_assertions',
|
|
27
|
+
'cms_authors',
|
|
29
28
|
] as const;
|
|
30
29
|
|
|
31
30
|
export const HOST_STEPS: readonly HostStep[] = [{
|
|
@@ -295,6 +294,55 @@ export const HOST_STEPS: readonly HostStep[] = [{
|
|
|
295
294
|
// 1 for an account created waiting for a site's approval: it is not an unconfirmed registration, so another registration of its email never replaces it.
|
|
296
295
|
{ rql: 'ALTER TABLE cms_accounts ADD COLUMN held INTEGER' },
|
|
297
296
|
],
|
|
297
|
+
}, {
|
|
298
|
+
version: 14,
|
|
299
|
+
description: 'Guarded write batches',
|
|
300
|
+
statements: [
|
|
301
|
+
// A write batch (`CmsHost.batch`) inserts one row per condition, held = 1 when it holds, and deletes them in its last statement: a condition that does not hold fails the CHECK, and the whole batch rolls back. No row outlives its batch.
|
|
302
|
+
{ rql: 'CREATE TABLE cms_assertions (id TEXT PRIMARY KEY, held INTEGER NOT NULL CHECK (held = 1))' },
|
|
303
|
+
],
|
|
304
|
+
}, {
|
|
305
|
+
version: 15,
|
|
306
|
+
description: 'Field values of users and terms are documents',
|
|
307
|
+
statements: [
|
|
308
|
+
// The values of the field groups attached to users are fields of a document under the member's ID, in the storage of the internal resource cms/user_fields: they can be indexed, kept unique and written one at a time. The JSON text they were kept in goes.
|
|
309
|
+
{ rql: 'ALTER TABLE cms_users DROP COLUMN meta' },
|
|
310
|
+
// A term's, in the storage of its taxonomy's internal resource (cms/tf_<taxonomy>), which exists while groups are attached to the taxonomy.
|
|
311
|
+
{ rql: 'ALTER TABLE cms_terms DROP COLUMN meta' },
|
|
312
|
+
],
|
|
313
|
+
}, {
|
|
314
|
+
version: 16,
|
|
315
|
+
description: 'Author slugs beside the people port',
|
|
316
|
+
statements: [
|
|
317
|
+
// With users kept by the application (the people port, specs/cms-on-dashboard.md), the CMS keeps a user's author slug itself, under the user's ID.
|
|
318
|
+
{ rql: 'CREATE TABLE cms_authors (user_id TEXT PRIMARY KEY, slug TEXT NOT NULL UNIQUE)' },
|
|
319
|
+
],
|
|
320
|
+
}, {
|
|
321
|
+
version: 17,
|
|
322
|
+
description: 'Accounts, roles, sessions and sites are the application\'s',
|
|
323
|
+
statements: [
|
|
324
|
+
// Who signs in, their roles and sessions, second factors, application passwords, and a network's sites and members are kept by the
|
|
325
|
+
// application now (the dashboard package's tables, specs/cms-on-dashboard.md). The CMS's own tables for them go; nothing is carried over.
|
|
326
|
+
{ rql: 'DROP TABLE IF EXISTS cms_users' },
|
|
327
|
+
{ rql: 'DROP TABLE IF EXISTS cms_roles' },
|
|
328
|
+
{ rql: 'DROP TABLE IF EXISTS cms_user_roles' },
|
|
329
|
+
{ rql: 'DROP TABLE IF EXISTS cms_auth_sessions' },
|
|
330
|
+
{ rql: 'DROP TABLE IF EXISTS cms_oauth_states' },
|
|
331
|
+
{ rql: 'DROP TABLE IF EXISTS cms_password_resets' },
|
|
332
|
+
{ rql: 'DROP TABLE IF EXISTS cms_sessions' },
|
|
333
|
+
{ rql: 'DROP TABLE IF EXISTS cms_session_values' },
|
|
334
|
+
{ rql: 'DROP TABLE IF EXISTS cms_api_tokens' },
|
|
335
|
+
{ rql: 'DROP TABLE IF EXISTS cms_user_security' },
|
|
336
|
+
{ rql: 'DROP TABLE IF EXISTS cms_passkeys' },
|
|
337
|
+
{ rql: 'DROP TABLE IF EXISTS cms_auth_challenges' },
|
|
338
|
+
{ rql: 'DROP TABLE IF EXISTS cms_accounts' },
|
|
339
|
+
{ rql: 'DROP TABLE IF EXISTS cms_sites' },
|
|
340
|
+
{ rql: 'DROP TABLE IF EXISTS cms_site_domains' },
|
|
341
|
+
{ rql: 'DROP TABLE IF EXISTS cms_handoffs' },
|
|
342
|
+
{ rql: 'DROP TABLE IF EXISTS cms_session_sites' },
|
|
343
|
+
{ rql: 'DROP TABLE IF EXISTS cms_memberships' },
|
|
344
|
+
{ rql: 'DROP TABLE IF EXISTS cms_registrations' },
|
|
345
|
+
],
|
|
298
346
|
}];
|
|
299
347
|
|
|
300
348
|
/**
|