@fabrika/db 0.9.0-dev.32 → 0.9.0-dev.33

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.32",
3
+ "version": "0.9.0-dev.33",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/testing.ts",
@@ -96,9 +96,9 @@
96
96
  "test": "bun test"
97
97
  },
98
98
  "dependencies": {
99
- "@fabrika/auth-core": "0.9.0-dev.32",
100
- "@fabrika/platform": "0.9.0-dev.32",
101
- "@fabrika/platform-node": "0.9.0-dev.32",
99
+ "@fabrika/auth-core": "0.9.0-dev.33",
100
+ "@fabrika/platform": "0.9.0-dev.33",
101
+ "@fabrika/platform-node": "0.9.0-dev.33",
102
102
  "kysely": "0.29.6",
103
103
  "kysely-postgres-js": "5.0.1",
104
104
  "zod": "^3.25.76"
package/src/errors.ts CHANGED
@@ -48,7 +48,8 @@ export const QUERY_REFUSALS = {
48
48
  unexpected_row: 'the database answered a row in another shape than its migration declares',
49
49
  statement_shape: 'the compiled statement has a form the guard does not admit',
50
50
  scope_predicate: 'the scope predicate is missing or is not a top-level conjunct',
51
- list_page: 'a list limit, cursor or order outside what a page admits',
51
+ list_page: 'a list limit or order outside what a page admits',
52
+ list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order",
52
53
  too_many_rows: 'all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate',
53
54
  undeclared_reach: 'the site reaches data it did not declare (sql or unscoped, or their mode)',
54
55
  sql_template: 'ctx.sql was not called as one tagged template whose values are interpolated whole',
@@ -0,0 +1,82 @@
1
+ // A list's cursor, signed with the database's own key (`fabrika_list_cursor_key`, which the framework migration writes
2
+ // once), so a cursor a client edited is the caller's `list_cursor`, never a statement the database refuses (a 500) or a
3
+ // page from a position no page ended at. A cursor is `<payload>.<signature>`: the payload is the base64url JSON of the
4
+ // last row's order values, and the signature an HMAC-SHA256 over the list it belongs to (its table and whole order) and
5
+ // the payload. The list is signed, not carried, so the cursor names no table or column.
6
+
7
+ import { parseList } from './builtins'
8
+ import { runFixedStatement, type Session } from './database'
9
+ import { QueryRefusedError } from './errors'
10
+ import type { DialectTexts } from './job-leases'
11
+ import { LIST_CURSOR_KEY_TABLE } from './migrations'
12
+
13
+ /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
14
+ export type CursorValue = string | null
15
+
16
+ const SQL_KEY: DialectTexts = {
17
+ postgres: `select secret from ${LIST_CURSOR_KEY_TABLE} where id = 1`,
18
+ sqlite: `select secret from ${LIST_CURSOR_KEY_TABLE} where id = 1`,
19
+ }
20
+
21
+ const BASE64URL = /^[A-Za-z0-9_-]+$/
22
+
23
+ /** The database's cursor key, read in `session`; the framework migration wrote it, so its absence is no caller's fault. */
24
+ export async function cursorKey(session: Session): Promise<CryptoKey> {
25
+ const [row] = await runFixedStatement(session, SQL_KEY[session.dialect], [])
26
+ const secret: unknown = typeof row === 'object' && row !== null ? Reflect.get(row, 'secret') : undefined
27
+ if (typeof secret !== 'string' || secret.length === 0) {
28
+ throw new QueryRefusedError('unexpected_row', `${LIST_CURSOR_KEY_TABLE} holds no key; the framework migrations did not run`)
29
+ }
30
+ return await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify'])
31
+ }
32
+
33
+ function signed(list: string, payload: string): Uint8Array<ArrayBuffer> {
34
+ return new TextEncoder().encode(`fabrika-list-cursor\n${list}\n${payload}`)
35
+ }
36
+
37
+ /** The cursor of the page after the row whose order values are `values`, in the list `list` names. */
38
+ export async function signCursor(key: () => Promise<CryptoKey>, list: string, values: readonly CursorValue[]): Promise<string> {
39
+ const payload = Buffer.from(JSON.stringify(values)).toString('base64url')
40
+ const signature = await crypto.subtle.sign('HMAC', await key(), signed(list, payload))
41
+ return `${payload}.${Buffer.from(signature).toString('base64url')}`
42
+ }
43
+
44
+ /**
45
+ * The order values of `after` when it is a cursor this database signed for the list `list` names, with one plain value
46
+ * per order column (`count`). Anything else is the caller's `list_cursor`: undecodable, unsigned, edited, of another
47
+ * list or order, or of another shape.
48
+ */
49
+ export async function openCursor(key: () => Promise<CryptoKey>, list: string, after: unknown, count: number): Promise<readonly CursorValue[]> {
50
+ const refused = () => new QueryRefusedError('list_cursor', 'after takes the next cursor of a page of this same list')
51
+ if (typeof after !== 'string') {
52
+ throw refused()
53
+ }
54
+ const [payload = '', given = '', ...rest] = after.split('.')
55
+ if (rest.length > 0 || !BASE64URL.test(payload) || !BASE64URL.test(given)) {
56
+ throw refused()
57
+ }
58
+ const signature = Buffer.from(given, 'base64url')
59
+ // One spelling per signature: the last character's padding bits decode to nothing, and a cursor has exactly one.
60
+ if (signature.toString('base64url') !== given) {
61
+ throw refused()
62
+ }
63
+ if (!(await crypto.subtle.verify('HMAC', await key(), new Uint8Array(signature), signed(list, payload)))) {
64
+ throw refused()
65
+ }
66
+ let parsed: unknown
67
+ try {
68
+ parsed = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
69
+ } catch {
70
+ throw refused()
71
+ }
72
+ const values = parseList(parsed, (value): CursorValue => {
73
+ if (typeof value === 'string' || value === null) {
74
+ return value
75
+ }
76
+ throw refused()
77
+ })
78
+ if (values === undefined || values.length !== count) {
79
+ throw refused()
80
+ }
81
+ return values
82
+ }
@@ -18,6 +18,7 @@ import {
18
18
  JOB_KICKS_TABLE,
19
19
  JOB_LEASES_TABLE,
20
20
  JOB_WAKES_TABLE,
21
+ LIST_CURSOR_KEY_TABLE,
21
22
  REQUEST_RECEIPTS_TABLE,
22
23
  WEBHOOK_BINDINGS_TABLE,
23
24
  WEBHOOK_DELIVERIES_TABLE,
@@ -176,6 +177,17 @@ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
176
177
  PRIMARY KEY (principal, request_key)
177
178
  ) STRICT;
178
179
  CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
180
+ `,
181
+ }),
182
+ Object.freeze({
183
+ name: '0006_list_cursor_key.sql',
184
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
185
+ -- here once and only read afterwards. 32 random bytes as hex.
186
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
187
+ id INTEGER PRIMARY KEY CHECK (id = 1),
188
+ secret TEXT NOT NULL
189
+ ) STRICT;
190
+ INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, hex(randomblob(32)));
179
191
  `,
180
192
  }),
181
193
  ])
package/src/migrations.ts CHANGED
@@ -17,6 +17,7 @@ export const FORM_BYTES_TABLE = 'fabrika_form_bytes'
17
17
  export const FILES_TABLE = 'fabrika_files'
18
18
  export const FILE_DELETIONS_TABLE = 'fabrika_file_deletions'
19
19
  export const REQUEST_RECEIPTS_TABLE = 'fabrika_request_receipts'
20
+ export const LIST_CURSOR_KEY_TABLE = 'fabrika_list_cursor_key'
20
21
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
21
22
  export const FILES_RELEASE_FUNCTION = 'fabrika_files_release'
22
23
  /**
@@ -297,6 +298,17 @@ CREATE TABLE ${REQUEST_RECEIPTS_TABLE} (
297
298
  PRIMARY KEY (principal, request_key)
298
299
  );
299
300
  CREATE INDEX ${REQUEST_RECEIPTS_TABLE}_created_at ON ${REQUEST_RECEIPTS_TABLE} (created_at);
301
+ `,
302
+ }),
303
+ Object.freeze({
304
+ name: '0012_list_cursor_key.sql',
305
+ sql: `-- The key a list's cursor is signed with (list-cursor.ts), so a cursor a client edited is refused: one row, written
306
+ -- here once and only read afterwards. Two random UUIDs give it 244 random bits.
307
+ CREATE TABLE ${LIST_CURSOR_KEY_TABLE} (
308
+ id INTEGER PRIMARY KEY CHECK (id = 1),
309
+ secret TEXT NOT NULL
310
+ );
311
+ INSERT INTO ${LIST_CURSOR_KEY_TABLE} (id, secret) VALUES (1, gen_random_uuid()::text || gen_random_uuid()::text);
300
312
  `,
301
313
  }),
302
314
  ])
package/src/orm.ts CHANGED
@@ -24,6 +24,7 @@ import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError }
24
24
  import { answerFiles, type FileBinding } from './file-columns'
25
25
  import { databaseNow } from './job-leases'
26
26
  import { rearmClaim } from './job-wakes'
27
+ import { cursorKey, type CursorValue, openCursor, signCursor } from './list-cursor'
27
28
  import {
28
29
  aggregateNode,
29
30
  allOf,
@@ -1301,11 +1302,18 @@ function rowState(table: string, conditions: readonly (Compare | Contains)[], or
1301
1302
  return { origin: freeze({}), table, columns: undefined, conditions, orderBy: order, limit, offset: undefined, joins: [] }
1302
1303
  }
1303
1304
 
1304
- /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
1305
- type CursorValue = string | null
1305
+ /** The list a cursor belongs to, as its signature covers it: its table and its whole order, the tiebreak included. */
1306
+ function cursorList(table: string, order: readonly OrderColumn[]): string {
1307
+ return JSON.stringify([table, order.map((term) => [term.column, term.direction])])
1308
+ }
1306
1309
 
1307
- /** A page's position: the text of its last row's order columns (`keyset.c<n>`), as opaque text. */
1308
- function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly OrderColumn[]): string {
1310
+ /** A page's position: the text of its last row's order columns (`keyset.c<n>`), signed for its list. */
1311
+ async function encodeCursor(
1312
+ key: () => Promise<CryptoKey>,
1313
+ table: string,
1314
+ row: Readonly<Record<string, unknown>>,
1315
+ order: readonly OrderColumn[],
1316
+ ): Promise<string> {
1309
1317
  const values: CursorValue[] = order.map(({ column: name }, index) => {
1310
1318
  const value = hasOwn(row, cursorAlias(index)) ? row[cursorAlias(index)] : null
1311
1319
  if (typeof value === 'string' || value === null) {
@@ -1313,7 +1321,7 @@ function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly Or
1313
1321
  }
1314
1322
  throw new QueryRefusedError('list_page', `${name} came back as ${typeof value} text, which a list cannot page by`)
1315
1323
  })
1316
- return Buffer.from(JSON.stringify(values)).toString('base64url')
1324
+ return await signCursor(key, cursorList(table, order), values)
1317
1325
  }
1318
1326
 
1319
1327
  /** A row as the caller sees it: the position columns stay the layer's. */
@@ -1330,30 +1338,6 @@ function withoutCursor(row: Readonly<Record<string, unknown>>, order: readonly O
1330
1338
  return item
1331
1339
  }
1332
1340
 
1333
- /** The cursor `after` names, parsed at the boundary: one plain value per order column. */
1334
- function decodeCursor(after: unknown, order: readonly OrderColumn[]): readonly CursorValue[] {
1335
- const refused = () => new QueryRefusedError('list_page', 'after takes the next cursor of a page of this same list')
1336
- if (typeof after !== 'string' || after.length === 0) {
1337
- throw refused()
1338
- }
1339
- let parsed: unknown
1340
- try {
1341
- parsed = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'))
1342
- } catch {
1343
- throw refused()
1344
- }
1345
- const values = parseList(parsed, (value): CursorValue => {
1346
- if (typeof value === 'string' || value === null) {
1347
- return value
1348
- }
1349
- throw refused()
1350
- })
1351
- if (values === undefined || values.length !== order.length) {
1352
- throw refused()
1353
- }
1354
- return values
1355
- }
1356
-
1357
1341
  function compare(table: string, name: string, operator: '>' | '<' | '=', value: Primitive): OperationNode {
1358
1342
  return BinaryOperationNode.create(column(table, name), OperatorNode.create(operator), ValueNode.create(value))
1359
1343
  }
@@ -1406,7 +1390,13 @@ async function listRows(
1406
1390
  const conditions = conditionsOf(context, shape, options['where'])
1407
1391
  const order = orderOf(shape, options['orderBy'], tiebreak)
1408
1392
  const limit = limitOf(options['limit'])
1409
- const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1393
+ const session = await run.read()
1394
+ // Read once per page, whether the page verifies `after`, signs `next` or both.
1395
+ let read: Promise<CryptoKey> | undefined
1396
+ const key = (): Promise<CryptoKey> => (read ??= cursorKey(session))
1397
+ const position = options['after'] === undefined
1398
+ ? undefined
1399
+ : keysetAfter(table, order, await openCursor(key, cursorList(table, order), options['after'], order.length))
1410
1400
  if (scope === undefined) {
1411
1401
  return { items: [], next: null }
1412
1402
  }
@@ -1416,7 +1406,6 @@ async function listRows(
1416
1406
  table,
1417
1407
  order.map((term) => term.column),
1418
1408
  )
1419
- const session = await run.read()
1420
1409
  const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
1421
1410
  root: 'SelectQueryNode',
1422
1411
  table,
@@ -1430,7 +1419,7 @@ async function listRows(
1430
1419
  const items = page.map((row) => withoutCursor(row, order))
1431
1420
  return {
1432
1421
  items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
1433
- next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
1422
+ next: rows.length > limit && last !== undefined ? await encodeCursor(key, table, last, order) : null,
1434
1423
  }
1435
1424
  }
1436
1425
 
@@ -40,7 +40,8 @@ export declare const QUERY_REFUSALS: {
40
40
  readonly unexpected_row: "the database answered a row in another shape than its migration declares";
41
41
  readonly statement_shape: "the compiled statement has a form the guard does not admit";
42
42
  readonly scope_predicate: "the scope predicate is missing or is not a top-level conjunct";
43
- readonly list_page: "a list limit, cursor or order outside what a page admits";
43
+ readonly list_page: "a list limit or order outside what a page admits";
44
+ readonly list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order";
44
45
  readonly too_many_rows: "all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate";
45
46
  readonly undeclared_reach: "the site reaches data it did not declare (sql or unscoped, or their mode)";
46
47
  readonly sql_template: "ctx.sql was not called as one tagged template whose values are interpolated whole";
@@ -0,0 +1,13 @@
1
+ import { type Session } from './database';
2
+ /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
3
+ export type CursorValue = string | null;
4
+ /** The database's cursor key, read in `session`; the framework migration wrote it, so its absence is no caller's fault. */
5
+ export declare function cursorKey(session: Session): Promise<CryptoKey>;
6
+ /** The cursor of the page after the row whose order values are `values`, in the list `list` names. */
7
+ export declare function signCursor(key: () => Promise<CryptoKey>, list: string, values: readonly CursorValue[]): Promise<string>;
8
+ /**
9
+ * The order values of `after` when it is a cursor this database signed for the list `list` names, with one plain value
10
+ * per order column (`count`). Anything else is the caller's `list_cursor`: undecodable, unsigned, edited, of another
11
+ * list or order, or of another shape.
12
+ */
13
+ export declare function openCursor(key: () => Promise<CryptoKey>, list: string, after: unknown, count: number): Promise<readonly CursorValue[]>;
@@ -12,6 +12,7 @@ export declare const FORM_BYTES_TABLE = "fabrika_form_bytes";
12
12
  export declare const FILES_TABLE = "fabrika_files";
13
13
  export declare const FILE_DELETIONS_TABLE = "fabrika_file_deletions";
14
14
  export declare const REQUEST_RECEIPTS_TABLE = "fabrika_request_receipts";
15
+ export declare const LIST_CURSOR_KEY_TABLE = "fabrika_list_cursor_key";
15
16
  /** The function an application's last adoption migration calls with the name of a file collection it adopted. */
16
17
  export declare const FILES_RELEASE_FUNCTION = "fabrika_files_release";
17
18
  /**