cogens 0.0.0-stage → 0.2.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 (46) hide show
  1. package/LICENSE +22 -0
  2. package/NOTICE +25 -0
  3. package/README.md +385 -2
  4. package/editor/editor-dark.css +2 -0
  5. package/editor/editor.css +9 -0
  6. package/editor/entry.js +28 -0
  7. package/migrations/0001_entries.sql +43 -0
  8. package/migrations/auth/0001_sessions.sql +50 -0
  9. package/migrations/koguma-upgrade.sql +13 -0
  10. package/package.json +86 -4
  11. package/scripts/build-admin-editor.ts +155 -0
  12. package/scripts/print-migration.ts +50 -0
  13. package/src/admin/app.ts +608 -0
  14. package/src/admin/assets.ts +52 -0
  15. package/src/admin/fields.ts +172 -0
  16. package/src/admin/forms.ts +64 -0
  17. package/src/admin/index.ts +16 -0
  18. package/src/admin/rules.ts +63 -0
  19. package/src/admin/types.ts +99 -0
  20. package/src/admin/views.ts +360 -0
  21. package/src/auth/handoff.ts +56 -0
  22. package/src/auth/index.ts +29 -0
  23. package/src/auth/password.ts +201 -0
  24. package/src/auth/principal.ts +40 -0
  25. package/src/auth/session.ts +143 -0
  26. package/src/core/access/ability.ts +86 -0
  27. package/src/core/access/can.ts +66 -0
  28. package/src/core/access/compile.ts +62 -0
  29. package/src/core/access/permits.ts +45 -0
  30. package/src/core/access/when.ts +59 -0
  31. package/src/core/access/where.ts +95 -0
  32. package/src/core/columns.ts +7 -0
  33. package/src/core/config/define.ts +206 -0
  34. package/src/core/config/field.ts +119 -0
  35. package/src/core/errors.ts +99 -0
  36. package/src/core/index.ts +44 -0
  37. package/src/core/media/index.ts +132 -0
  38. package/src/core/principal.ts +49 -0
  39. package/src/core/store/assets.ts +2 -0
  40. package/src/core/store/cms.ts +199 -0
  41. package/src/core/store/content.ts +453 -0
  42. package/src/core/store/sql.ts +239 -0
  43. package/src/core/store/types.ts +100 -0
  44. package/src/core/testing/index.ts +75 -0
  45. package/src/testing/db.ts +53 -0
  46. package/src/testing/index.ts +9 -0
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `resolvePrincipal`: the one function a host calls to learn who a request is.
3
+ * An admin session gives `{ kind: 'admin' }`; a session of another kind goes
4
+ * through the host's own mapping; anything else is null (the host then decides
5
+ * anonymous or a 401). The package never learns what an owner is.
6
+ */
7
+ import { resolveAdminSession, ADMIN_KIND, type PasswordOptions } from './password.ts';
8
+ import { readSession, type RequestSource, type Session, type SessionConfig } from './session.ts';
9
+
10
+ export interface SessionSource<P extends { kind: string }> {
11
+ /** The cookie and key for this kind of session, from the env; undefined when unconfigured. */
12
+ config(env: Record<string, unknown>): SessionConfig | undefined;
13
+ /** The host's principal for a session of this source, or null to refuse it. */
14
+ principal(session: Session, env: Record<string, unknown>): P | null | Promise<P | null>;
15
+ }
16
+
17
+ export interface PrincipalOptions<P extends { kind: string }> {
18
+ admin?: PasswordOptions;
19
+ sessions?: SessionSource<P>[];
20
+ /** The D1 binding's name (default `DB`). */
21
+ dbName?: string;
22
+ }
23
+
24
+ export function createPrincipalResolver<P extends { kind: string } = never>(options: PrincipalOptions<P> = {}) {
25
+ return async function resolvePrincipal(request: Request, env: Record<string, unknown>): Promise<{ kind: 'admin' } | P | null> {
26
+ const source: RequestSource = { req: { raw: request } };
27
+ const admin = await resolveAdminSession(source, env, options.admin ?? {});
28
+ if (admin.session) return { kind: ADMIN_KIND };
29
+ const db = env[options.dbName ?? options.admin?.envNames?.db ?? 'DB'] as D1Database | undefined;
30
+ for (const candidate of options.sessions ?? []) {
31
+ const config = candidate.config(env);
32
+ if (!config) continue;
33
+ const read = await readSession(source, db, config);
34
+ if (!read.session || read.session.kind === ADMIN_KIND) continue;
35
+ const principal = await candidate.principal(read.session, env);
36
+ if (principal) return principal;
37
+ }
38
+ return null;
39
+ };
40
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Sessions: a row in `sessions` named by a signed cookie. The cookie holds only a
3
+ * random id; the row says whose session it is (an opaque `owner_id`, null for the
4
+ * operator), what `kind` of person (`admin`, or whatever the host calls them), how
5
+ * it was started (`method`) and when it ends. Times are epoch milliseconds.
6
+ */
7
+ import type { Context } from 'hono';
8
+ import { deleteCookie, getSignedCookie, setSignedCookie } from 'hono/cookie';
9
+
10
+ export interface SessionConfig {
11
+ /** The cookie's name. A host with two kinds of session uses two names. */
12
+ cookieName: string;
13
+ /** The signing key, at least 32 characters. Never a password. */
14
+ secret: string;
15
+ /** How long a session lasts, in seconds. */
16
+ lifetimeSeconds: number;
17
+ /** The clock, in epoch milliseconds; tests move it. */
18
+ now?: () => number;
19
+ }
20
+
21
+ export interface Session {
22
+ id: string;
23
+ ownerId: string | null;
24
+ kind: string;
25
+ method: string;
26
+ createdAt: number;
27
+ expiresAt: number;
28
+ }
29
+
30
+ export interface NewSession {
31
+ ownerId: string | null;
32
+ kind: string;
33
+ method: string;
34
+ }
35
+
36
+ /** Anything that carries the request: a Hono context, or `{ req: { raw } }` built from a Request. */
37
+ export interface RequestSource {
38
+ req: { raw: Request };
39
+ }
40
+
41
+ export type SessionRead =
42
+ | { session: Session }
43
+ | { session: null; reason: 'unconfigured' | 'missing' | 'invalid' | 'expired' | 'gone'; clear: boolean };
44
+
45
+ export const MIN_KEY_LENGTH = 32;
46
+
47
+ interface Row {
48
+ id: string;
49
+ owner_id: string | null;
50
+ kind: string;
51
+ method: string;
52
+ created_at: number;
53
+ expires_at: number;
54
+ }
55
+
56
+ const toSession = (row: Row): Session => ({
57
+ id: row.id,
58
+ ownerId: row.owner_id,
59
+ kind: row.kind,
60
+ method: row.method,
61
+ createdAt: row.created_at,
62
+ expiresAt: row.expires_at
63
+ });
64
+
65
+ export const clock = (config: { now?: () => number }): number => (config.now ?? Date.now)();
66
+
67
+ export function hasKey(config: SessionConfig): boolean {
68
+ return typeof config.secret === 'string' && config.secret.length >= MIN_KEY_LENGTH;
69
+ }
70
+
71
+ export function randomToken(bytes = 32): string {
72
+ const raw = crypto.getRandomValues(new Uint8Array(bytes));
73
+ return btoa(String.fromCharCode(...raw)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
74
+ }
75
+
76
+ const cookieOptions = (maxAge: number) => ({ path: '/', httpOnly: true, secure: true, sameSite: 'Strict' as const, maxAge });
77
+
78
+ /** Starts a session: writes the row and sets the signed cookie. */
79
+ export async function createSession(c: Context, db: D1Database, config: SessionConfig, init: NewSession): Promise<Session> {
80
+ if (!hasKey(config)) throw new Error(`The session signing key must be at least ${MIN_KEY_LENGTH} characters.`);
81
+ if (!init.kind || !init.method) throw new TypeError('A session records its kind and method.');
82
+ const createdAt = clock(config);
83
+ const session: Session = {
84
+ id: randomToken(),
85
+ ownerId: init.ownerId,
86
+ kind: init.kind,
87
+ method: init.method,
88
+ createdAt,
89
+ expiresAt: createdAt + config.lifetimeSeconds * 1000
90
+ };
91
+ await db
92
+ .prepare('INSERT INTO sessions (id, owner_id, kind, method, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)')
93
+ .bind(session.id, session.ownerId, session.kind, session.method, session.createdAt, session.expiresAt)
94
+ .run();
95
+ await setSignedCookie(c, config.cookieName, session.id, config.secret, cookieOptions(config.lifetimeSeconds));
96
+ return session;
97
+ }
98
+
99
+ /** The session the request's cookie names, or why there is none. Read-only. */
100
+ export async function readSession(source: RequestSource, db: D1Database | undefined, config: SessionConfig): Promise<SessionRead> {
101
+ if (!db || !hasKey(config)) return { session: null, reason: 'unconfigured', clear: false };
102
+ const value = await getSignedCookie(source as unknown as Context, config.secret, config.cookieName);
103
+ if (value === undefined) return { session: null, reason: 'missing', clear: false };
104
+ if (value === false || value === '') return { session: null, reason: 'invalid', clear: false };
105
+ const row = await db.prepare('SELECT id, owner_id, kind, method, created_at, expires_at FROM sessions WHERE id = ?').bind(value).first<Row>();
106
+ if (!row) return { session: null, reason: 'gone', clear: true };
107
+ if (row.expires_at <= clock(config)) return { session: null, reason: 'expired', clear: true };
108
+ return { session: toSession(row) };
109
+ }
110
+
111
+ /** Clears the session cookie on the response. */
112
+ export function clearSessionCookie(c: Context, config: SessionConfig): void {
113
+ deleteCookie(c, config.cookieName, { path: '/', httpOnly: true, secure: true, sameSite: 'Strict' } as Parameters<typeof deleteCookie>[2]);
114
+ }
115
+
116
+ /** Signs out: removes the row the cookie names, if it is validly signed, and clears the cookie. */
117
+ export async function endSession(c: Context, db: D1Database, config: SessionConfig): Promise<void> {
118
+ if (hasKey(config)) {
119
+ const value = await getSignedCookie(c, config.secret, config.cookieName);
120
+ if (typeof value === 'string' && value) await db.prepare('DELETE FROM sessions WHERE id = ?').bind(value).run();
121
+ }
122
+ clearSessionCookie(c, config);
123
+ }
124
+
125
+ /**
126
+ * Deletes every session of one owner, of one kind, or both together; returns how
127
+ * many. With neither given it refuses, so a missing id cannot end everyone's.
128
+ */
129
+ export async function revokeSessions(db: D1Database, filter: { ownerId?: string; kind?: string }): Promise<number> {
130
+ const where: string[] = [];
131
+ const values: string[] = [];
132
+ if (filter.ownerId !== undefined) (where.push('owner_id = ?'), values.push(filter.ownerId));
133
+ if (filter.kind !== undefined) (where.push('kind = ?'), values.push(filter.kind));
134
+ if (where.length === 0) throw new TypeError('Revoking sessions needs an owner, a kind, or both.');
135
+ const result = await db.prepare(`DELETE FROM sessions WHERE ${where.join(' AND ')}`).bind(...values).run();
136
+ return result.meta?.changes ?? 0;
137
+ }
138
+
139
+ /** Removes sessions past their end; the host may run it daily. Returns how many. */
140
+ export async function purgeExpiredSessions(db: D1Database, now: number = Date.now()): Promise<number> {
141
+ const result = await db.prepare('DELETE FROM sessions WHERE expires_at <= ?').bind(now).run();
142
+ return result.meta?.changes ?? 0;
143
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The decision engine: grants in, answers about one row out. This is the only
3
+ * file that imports CASL, and nothing here is exported by the package's index:
4
+ * a host sees `RuleSet`, whose methods take and return plain values.
5
+ */
6
+ import { createMongoAbility, mongoQueryMatcher, subject, type ConditionsMatcher, type MongoAbility, type RawRuleOf } from '@casl/ability';
7
+ import { permittedFieldsOf } from '@casl/ability/extra';
8
+ import type { Operation } from '../errors.ts';
9
+ import type { Grant } from './can.ts';
10
+ import { toMongo } from './where.ts';
11
+
12
+ /** Stands for "every field that is not a system field" in a grant with no field list. */
13
+ const ORDINARY = '*';
14
+
15
+ /** A row as rules see it: the built-in columns and the values of the indexed fields. */
16
+ export type RuleRow = Record<string, unknown>;
17
+
18
+ type Rule = RawRuleOf<MongoAbility>;
19
+
20
+ type Match = (row: Record<string, unknown>) => boolean;
21
+
22
+ /**
23
+ * CASL's matcher knows equals and `$in` but not `$and` or `$or`, so those two are
24
+ * handled here and everything under them (the equals and `in` leaves) is still
25
+ * decided by CASL's own matcher.
26
+ */
27
+ const conditionsMatcher: ConditionsMatcher<any> = conditions => {
28
+ const compile = (c: Record<string, unknown>): Match => {
29
+ if ('$and' in c) {
30
+ const parts = (c.$and as Record<string, unknown>[]).map(compile);
31
+ return row => parts.every(p => p(row));
32
+ }
33
+ if ('$or' in c) {
34
+ const parts = (c.$or as Record<string, unknown>[]).map(compile);
35
+ return row => parts.some(p => p(row));
36
+ }
37
+ return mongoQueryMatcher(c as never) as Match;
38
+ };
39
+ return compile(conditions);
40
+ };
41
+
42
+ export interface PermittedFields {
43
+ /** The grants that match the row allow every ordinary field. */
44
+ ordinary: boolean;
45
+ /** Fields a matching grant lists by name (these may be system fields). */
46
+ listed: Set<string>;
47
+ }
48
+
49
+ export class RuleSet {
50
+ private readonly ability: MongoAbility;
51
+
52
+ constructor(
53
+ readonly type: string,
54
+ readonly grants: readonly Grant[]
55
+ ) {
56
+ const rules: Rule[] = grants.map(g => ({
57
+ action: g.bySlug ? 'lookup' : g.operation,
58
+ subject: type,
59
+ ...(g.where === undefined ? {} : { conditions: toMongo(g.where) }),
60
+ fields: g.fields ?? [ORDINARY]
61
+ }));
62
+ this.ability = createMongoAbility(rules, { conditionsMatcher });
63
+ }
64
+
65
+ /** Whether any grant gives the operation, whatever the row. */
66
+ has(operation: Operation | 'lookup'): boolean {
67
+ return this.ability.rulesFor(operation, this.type).length > 0;
68
+ }
69
+
70
+ /** Whether a grant for the operation matches this row. */
71
+ allows(operation: Operation, row: RuleRow): boolean {
72
+ return this.ability.can(operation, subject(this.type, { ...row }));
73
+ }
74
+
75
+ /** A lookup by slug is answered by the read grants and the by-slug ones. */
76
+ allowsLookup(row: RuleRow): boolean {
77
+ return this.allows('read', row) || this.ability.can('lookup', subject(this.type, { ...row }));
78
+ }
79
+
80
+ permittedFields(operation: Operation, row: RuleRow): PermittedFields {
81
+ const fields = permittedFieldsOf(this.ability, operation, subject(this.type, { ...row }), {
82
+ fieldsFrom: rule => rule.fields ?? [ORDINARY]
83
+ });
84
+ return { ordinary: fields.includes(ORDINARY), listed: new Set(fields.filter(f => f !== ORDINARY)) };
85
+ }
86
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The `can` builder a type's access function calls to grant operations. It
3
+ * records plain grants (`Grant`) and nothing else, so no type exposes the engine
4
+ * under it; ability.ts turns the grants into the engine's rules.
5
+ *
6
+ * access(principal, { can }) {
7
+ * can('read', { where: { status: 'published' } });
8
+ * if (principal.kind === 'composer') can(['update', 'delete'], { where: { owner_id: principal.ownerId } });
9
+ * }
10
+ */
11
+ import { ConditionError, type Operation } from '../errors.ts';
12
+ import { walkWhere, type Where } from './where.ts';
13
+
14
+ export const OPERATIONS: readonly Operation[] = ['create', 'read', 'update', 'delete', 'publish'];
15
+
16
+ export interface GrantOptions {
17
+ /** Confines the grant to rows that match. Absent means every row of the type. */
18
+ where?: Where;
19
+ /**
20
+ * The fields the grant lets the caller write (create and update), by name. Absent means every field that is not
21
+ * a system field. A system field, `owner_id`, `slug`, `parent_id` or `sort_key` is writable only when listed here.
22
+ */
23
+ fields?: readonly string[];
24
+ /**
25
+ * Read only: the grant applies to a lookup by slug and not to a list or a get by id, so a type can let a caller
26
+ * read an entry whose slug it knows without letting it list that entry.
27
+ */
28
+ bySlug?: boolean;
29
+ }
30
+
31
+ /** One grant, as recorded; also what `cms.access.rulesFor` hands a page. */
32
+ export interface Grant {
33
+ operation: Operation;
34
+ where?: Where;
35
+ fields?: string[];
36
+ bySlug?: boolean;
37
+ }
38
+
39
+ export type Can = (operation: Operation | readonly Operation[], options?: GrantOptions) => void;
40
+
41
+ export interface AccessContext {
42
+ can: Can;
43
+ }
44
+
45
+ export type AccessFn<P = unknown> = (principal: P, context: AccessContext) => void;
46
+
47
+ export function runAccess<P>(access: AccessFn<P>, principal: P): Grant[] {
48
+ const grants: Grant[] = [];
49
+ const can: Can = (operation, options = {}) => {
50
+ const operations = Array.isArray(operation) ? operation : [operation as Operation];
51
+ if (operations.length === 0) throw new ConditionError('`can` needs at least one operation.');
52
+ for (const op of operations) {
53
+ if (!OPERATIONS.includes(op)) throw new ConditionError(`Unknown operation "${String(op)}".`);
54
+ if (options.bySlug && op !== 'read') throw new ConditionError('`bySlug` applies to read only.');
55
+ if (options.where !== undefined) walkWhere(options.where, () => {});
56
+ grants.push({
57
+ operation: op,
58
+ ...(options.where === undefined ? {} : { where: options.where }),
59
+ ...(options.fields === undefined ? {} : { fields: [...options.fields] }),
60
+ ...(options.bySlug ? { bySlug: true } : {})
61
+ });
62
+ }
63
+ };
64
+ access(principal, { can });
65
+ return grants;
66
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The condition compiler: a condition (where.ts) to a parameterised SQL
3
+ * fragment, ANDed by the store into every SELECT, UPDATE and DELETE. Equals,
4
+ * `in` (at most 90 values), `and` and `or`; nothing else is accepted. It
5
+ * touches no table: the store gives it the column a field is read from.
6
+ */
7
+ import { ConditionError } from '../errors.ts';
8
+ import { isBuiltin, normaliseScalar, walkWhere, type Scalar, type Where } from './where.ts';
9
+
10
+ export interface Sql {
11
+ sql: string;
12
+ params: (string | number)[];
13
+ }
14
+
15
+ /** The SQL expression a field is read from, or null when a condition may not name it. */
16
+ export type ColumnOf = (field: string) => string | null;
17
+
18
+ export function compileWhere(where: Where, columnOf: ColumnOf): Sql {
19
+ // Validate first, so an unsupported operator is named before any SQL is built.
20
+ walkWhere(where, field => {
21
+ if (columnOf(field) === null) {
22
+ throw new ConditionError(`The condition names "${field}", which is neither a built-in column nor an indexed field.`, field);
23
+ }
24
+ });
25
+ return build(where, columnOf);
26
+ }
27
+
28
+ function build(where: Where, columnOf: ColumnOf): Sql {
29
+ const keys = Object.keys(where);
30
+ if (keys[0] === 'and' || keys[0] === 'or') {
31
+ const parts = (where as Record<string, Where[]>)[keys[0]]!.map(w => build(w, columnOf));
32
+ return {
33
+ sql: `(${parts.map(p => p.sql).join(keys[0] === 'and' ? ' AND ' : ' OR ')})`,
34
+ params: parts.flatMap(p => p.params)
35
+ };
36
+ }
37
+ const parts: Sql[] = [];
38
+ for (const [field, value] of Object.entries(where as Record<string, Scalar | { in: Scalar[] }>)) {
39
+ const column = columnOf(field)!;
40
+ if (typeof value === 'object') {
41
+ parts.push(
42
+ value.in.length === 0
43
+ ? { sql: '0', params: [] }
44
+ : { sql: `${column} IN (${value.in.map(() => '?').join(', ')})`, params: value.in.map(normaliseScalar) }
45
+ );
46
+ } else {
47
+ parts.push({ sql: `${column} = ?`, params: [normaliseScalar(value)] });
48
+ }
49
+ }
50
+ if (parts.length === 0) return { sql: '1', params: [] };
51
+ return { sql: parts.length === 1 ? parts[0]!.sql : `(${parts.map(p => p.sql).join(' AND ')})`, params: parts.flatMap(p => p.params) };
52
+ }
53
+
54
+ /** Grants are alternatives: a row matches when any grant's condition does. No grant, no rows (null). */
55
+ export function compileAny(conditions: (Where | undefined)[], columnOf: ColumnOf): Sql | null {
56
+ if (conditions.length === 0) return null;
57
+ if (conditions.some(c => c === undefined || Object.keys(c).length === 0)) return { sql: '1', params: [] };
58
+ const parts = conditions.map(c => compileWhere(c!, columnOf));
59
+ return { sql: `(${parts.map(p => p.sql).join(' OR ')})`, params: parts.flatMap(p => p.params) };
60
+ }
61
+
62
+ export { isBuiltin };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The rules in a form a page can use to show or hide controls. `cms.access.rulesFor`
3
+ * packs a caller's grants into plain JSON, and `permits` answers from that JSON
4
+ * alone. It is for display: enforcement is the store's, and the policy test
5
+ * helper checks that the two agree.
6
+ */
7
+ import type { Operation } from '../errors.ts';
8
+ import type { Grant } from './can.ts';
9
+ import { normaliseScalar, type Scalar, type Where } from './where.ts';
10
+
11
+ export interface PackedTypeRules {
12
+ type: string;
13
+ grants: Grant[];
14
+ }
15
+
16
+ export type PackedRules = PackedTypeRules[];
17
+
18
+ /** Whether a row satisfies a condition; the row holds the built-in columns and the indexed fields. */
19
+ export function matches(where: Where, row: Record<string, unknown>): boolean {
20
+ const keys = Object.keys(where);
21
+ if (keys[0] === 'and') return (where as { and: Where[] }).and.every(w => matches(w, row));
22
+ if (keys[0] === 'or') return (where as { or: Where[] }).or.some(w => matches(w, row));
23
+ return Object.entries(where as Record<string, Scalar | { in: Scalar[] }>).every(([field, value]) => {
24
+ const actual = row[field];
25
+ if (typeof value === 'object') return value.in.some(v => normaliseScalar(v) === actual);
26
+ return normaliseScalar(value) === actual;
27
+ });
28
+ }
29
+
30
+ /**
31
+ * Whether the packed rules give the caller the operation on the type: on any row when `row` is left out, on that
32
+ * row otherwise. A slug lookup is `operation: 'lookup'`.
33
+ */
34
+ export function permits(rules: PackedRules, type: string, operation: Operation | 'lookup', row?: Record<string, unknown>): boolean {
35
+ const grants = rules.find(r => r.type === type)?.grants ?? [];
36
+ const wanted = grants.filter(g =>
37
+ operation === 'lookup' ? g.operation === 'read' : g.operation === operation && !g.bySlug
38
+ );
39
+ return wanted.some(g => row === undefined || g.where === undefined || matches(g.where, row));
40
+ }
41
+
42
+ /** What a grant lists by name for a row: undefined when no matching grant, the list otherwise. */
43
+ export function pack(type: string, grants: readonly Grant[]): PackedTypeRules {
44
+ return { type, grants: JSON.parse(JSON.stringify(grants)) as Grant[] };
45
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The precondition of a conditional update: equals, less than, greater than and
3
+ * is-null on a named field, combined with `or` (fields of one object are ANDed).
4
+ * Compiled to SQL and run in the same statement as the write, so it holds at the
5
+ * moment of writing.
6
+ */
7
+ import { ConditionError } from '../errors.ts';
8
+ import type { When } from '../store/types.ts';
9
+ import { isBuiltin } from './where.ts';
10
+ import type { Sql } from './compile.ts';
11
+
12
+ /** The SQL expression a field is read from, or null when the type has no such field. */
13
+ export type ReadField = (field: string) => string | null;
14
+
15
+ export function compileWhen(when: When, read: ReadField): Sql {
16
+ if (typeof when !== 'object' || when === null || Array.isArray(when)) throw new ConditionError('A precondition is an object.');
17
+ const keys = Object.keys(when);
18
+ if (keys.length === 0) throw new ConditionError('A precondition names at least one field.');
19
+ if (keys.includes('or')) {
20
+ if (keys.length !== 1) throw new ConditionError('`or` stands alone in a precondition; nest the other fields inside.');
21
+ const list = (when as { or: When[] }).or;
22
+ if (!Array.isArray(list) || list.length === 0) throw new ConditionError('`or` takes a list of one or more preconditions.');
23
+ const parts = list.map(w => compileWhen(w, read));
24
+ return { sql: `(${parts.map(p => p.sql).join(' OR ')})`, params: parts.flatMap(p => p.params) };
25
+ }
26
+ const parts: Sql[] = [];
27
+ for (const [field, compare] of Object.entries(when as Record<string, unknown>)) {
28
+ const column = read(field);
29
+ if (column === null) {
30
+ throw new ConditionError(`The precondition names "${field}", which is neither a built-in column nor a field of the type.`, field);
31
+ }
32
+ if (typeof compare !== 'object' || compare === null || Array.isArray(compare) || Object.keys(compare).length !== 1) {
33
+ throw new ConditionError(`The precondition on "${field}" is one of equals, lt, gt or isNull.`, field);
34
+ }
35
+ const [op, value] = Object.entries(compare)[0]!;
36
+ switch (op) {
37
+ case 'equals': {
38
+ if (typeof value === 'boolean') parts.push({ sql: `${column} = ?`, params: [value ? 1 : 0] });
39
+ else if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))) {
40
+ if (isBuiltin(field) && typeof value !== 'string') throw new ConditionError(`The precondition on "${field}" must compare with a string.`, field);
41
+ parts.push({ sql: `${column} = ?`, params: [value] });
42
+ } else throw new ConditionError(`The precondition on "${field}" compares with a string, number or boolean; use isNull for null.`, field);
43
+ break;
44
+ }
45
+ case 'lt':
46
+ case 'gt':
47
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new ConditionError(`The precondition on "${field}" compares with a number.`, field);
48
+ parts.push({ sql: `${column} ${op === 'lt' ? '<' : '>'} ?`, params: [value] });
49
+ break;
50
+ case 'isNull':
51
+ if (typeof value !== 'boolean') throw new ConditionError(`isNull on "${field}" takes true or false.`, field);
52
+ parts.push({ sql: `${column} IS ${value ? '' : 'NOT '}NULL`, params: [] });
53
+ break;
54
+ default:
55
+ throw new ConditionError(`The precondition on "${field}" uses "${op}"; only equals, lt, gt and isNull are supported.`, field);
56
+ }
57
+ }
58
+ return { sql: parts.length === 1 ? parts[0]!.sql : `(${parts.map(p => p.sql).join(' AND ')})`, params: parts.flatMap(p => p.params) };
59
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Conditions: the one vocabulary a rule uses to confine a grant to some rows.
3
+ * Equality, membership in a list of at most 90 values, and `and` / `or`. The same
4
+ * condition is compiled to SQL (compile.ts) and handed to the ability for the
5
+ * in-memory answer (ability.ts), so a rule means the same in both.
6
+ */
7
+ import { ConditionError } from '../errors.ts';
8
+
9
+ export type Scalar = string | number | boolean;
10
+
11
+ export type Where =
12
+ | { and: Where[] }
13
+ | { or: Where[] }
14
+ | { [field: string]: Scalar | { in: Scalar[] } };
15
+
16
+ /** The most values one `in` may hold; D1 allows 100 bound values in a statement. */
17
+ export const MAX_IN_VALUES = 90;
18
+
19
+ /** The columns every entry has, which a condition may name without declaring them. */
20
+ export const BUILTIN_COLUMNS = ['id', 'owner_id', 'slug', 'status', 'parent_id', 'parent_status'] as const;
21
+ export type BuiltinColumn = (typeof BUILTIN_COLUMNS)[number];
22
+ export const isBuiltin = (field: string): field is BuiltinColumn => (BUILTIN_COLUMNS as readonly string[]).includes(field);
23
+
24
+ /** Booleans are stored as 0 and 1 in the column a generated field reads, so both sides use that. */
25
+ export const normaliseScalar = (value: Scalar): string | number => (typeof value === 'boolean' ? (value ? 1 : 0) : value);
26
+
27
+ function checkScalar(field: string, value: unknown): Scalar {
28
+ if (typeof value === 'string' || typeof value === 'boolean') return value;
29
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
30
+ throw new ConditionError(
31
+ `The condition on "${field}" compares with ${value === null || value === undefined ? String(value) : typeof value}; use a string, number or boolean.`,
32
+ field
33
+ );
34
+ }
35
+
36
+ /** What a built-in column holds: text. A number there would be compared as text by SQL and as a number in memory. */
37
+ function checkColumnValue(field: string, value: Scalar): void {
38
+ if (isBuiltin(field) && typeof value !== 'string') {
39
+ throw new ConditionError(`The condition on "${field}" must compare with a string.`, field);
40
+ }
41
+ }
42
+
43
+ /** Walks a condition, calling `onField` for each field it names; throws on anything outside the vocabulary. */
44
+ export function walkWhere(where: Where, onField: (field: string, value: Scalar | { in: Scalar[] }) => void): void {
45
+ if (typeof where !== 'object' || where === null || Array.isArray(where)) {
46
+ throw new ConditionError('A condition is an object.');
47
+ }
48
+ const keys = Object.keys(where);
49
+ if (keys.includes('and') || keys.includes('or')) {
50
+ if (keys.length !== 1) throw new ConditionError('`and` and `or` stand alone in a condition; nest the other fields inside.');
51
+ const key = keys[0] as 'and' | 'or';
52
+ const list = (where as Record<string, unknown>)[key];
53
+ if (!Array.isArray(list) || list.length === 0) {
54
+ throw new ConditionError(`\`${key}\` takes a list of one or more conditions.`);
55
+ }
56
+ for (const part of list) walkWhere(part as Where, onField);
57
+ return;
58
+ }
59
+ for (const field of keys) {
60
+ const value = (where as Record<string, unknown>)[field];
61
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
62
+ const ops = Object.keys(value);
63
+ if (ops.length !== 1 || ops[0] !== 'in' || !Array.isArray((value as { in: unknown }).in)) {
64
+ throw new ConditionError(`The condition on "${field}" is not supported: only equals and \`in\` are.`, field);
65
+ }
66
+ const list = (value as { in: unknown[] }).in;
67
+ if (list.length > MAX_IN_VALUES) {
68
+ throw new ConditionError(
69
+ `The condition on "${field}" lists ${list.length} values; the limit is ${MAX_IN_VALUES}.`,
70
+ field
71
+ );
72
+ }
73
+ for (const v of list) checkColumnValue(field, checkScalar(field, v));
74
+ onField(field, { in: list as Scalar[] });
75
+ } else {
76
+ checkColumnValue(field, checkScalar(field, value));
77
+ onField(field, value as Scalar);
78
+ }
79
+ }
80
+ }
81
+
82
+ /** The condition in the form the ability matches rows with. */
83
+ export function toMongo(where: Where): Record<string, unknown> {
84
+ const keys = Object.keys(where);
85
+ if (keys[0] === 'and' || keys[0] === 'or') {
86
+ const list = (where as Record<string, Where[]>)[keys[0]]!;
87
+ return { [keys[0] === 'and' ? '$and' : '$or']: list.map(toMongo) };
88
+ }
89
+ const out: Record<string, unknown> = {};
90
+ for (const [field, value] of Object.entries(where as Record<string, Scalar | { in: Scalar[] }>)) {
91
+ out[field] =
92
+ typeof value === 'object' ? { $in: value.in.map(normaliseScalar) } : normaliseScalar(value);
93
+ }
94
+ return out;
95
+ }
@@ -0,0 +1,7 @@
1
+ /** Names of columns of `entries` that more than the SQL layer needs (the migration printer, the startup check). */
2
+
3
+ /** The column a generated (indexed) field is read from. */
4
+ export const indexedColumn = (field: string) => `f_${field}`;
5
+
6
+ /** The built-in columns a migration adds beyond Koguma's, which startup looks for. */
7
+ export const ADDED_COLUMNS = ['owner_id', 'parent_id', 'sort_key', 'parent_status'] as const;