@quad-education/sdk 0.1.3 → 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 (54) hide show
  1. package/README.md +2 -0
  2. package/dist/contract-tests/apps.d.ts +105 -0
  3. package/dist/contract-tests/apps.js +167 -0
  4. package/dist/contract-tests/harness.d.ts +11 -0
  5. package/dist/contract-tests/harness.js +40 -0
  6. package/dist/contract-tests/helpers.d.ts +5 -0
  7. package/dist/contract-tests/helpers.js +25 -0
  8. package/dist/contract-tests/index.d.ts +4 -2
  9. package/dist/contract-tests/index.js +3 -1
  10. package/dist/contract-tests/standalone-apps.d.ts +183 -0
  11. package/dist/contract-tests/standalone-apps.js +178 -0
  12. package/dist/contract-tests/standalone.d.ts +2 -0
  13. package/dist/contract-tests/standalone.js +709 -0
  14. package/dist/contract-tests/suite.d.ts +10 -3
  15. package/dist/contract-tests/suite.js +536 -44
  16. package/dist/src/client/connect.d.ts +13 -3
  17. package/dist/src/client/connect.js +21 -3
  18. package/dist/src/client/handshake-client.d.ts +2 -0
  19. package/dist/src/client/handshake-client.js +2 -0
  20. package/dist/src/client/http-transport.d.ts +18 -0
  21. package/dist/src/client/http-transport.js +76 -0
  22. package/dist/src/client/live.d.ts +39 -0
  23. package/dist/src/client/live.js +122 -0
  24. package/dist/src/contract/errors.d.ts +1 -1
  25. package/dist/src/contract/principals.d.ts +30 -0
  26. package/dist/src/contract/principals.js +12 -0
  27. package/dist/src/contract/recipients.d.ts +8 -2
  28. package/dist/src/contract/types.d.ts +18 -2
  29. package/dist/src/contract/types.js +1 -1
  30. package/dist/src/engine/audit.d.ts +2 -2
  31. package/dist/src/engine/audit.js +8 -6
  32. package/dist/src/engine/db-indexes.js +6 -1
  33. package/dist/src/engine/engine.d.ts +60 -22
  34. package/dist/src/engine/engine.js +281 -162
  35. package/dist/src/engine/host.d.ts +2 -2
  36. package/dist/src/engine/host.js +1 -1
  37. package/dist/src/engine/in-process.d.ts +2 -2
  38. package/dist/src/engine/index.d.ts +3 -1
  39. package/dist/src/engine/index.js +1 -0
  40. package/dist/src/engine/memory-store.d.ts +32 -0
  41. package/dist/src/engine/memory-store.js +123 -0
  42. package/dist/src/engine/runner.d.ts +2 -2
  43. package/dist/src/engine/runner.js +31 -26
  44. package/dist/src/engine/state.d.ts +21 -15
  45. package/dist/src/engine/state.js +31 -3
  46. package/dist/src/engine/store.d.ts +48 -0
  47. package/dist/src/engine/store.js +1 -0
  48. package/dist/src/engine/tasks.d.ts +4 -6
  49. package/dist/src/engine/tasks.js +27 -24
  50. package/dist/src/index.d.ts +1 -0
  51. package/dist/src/index.js +1 -0
  52. package/dist/src/jobs/define.d.ts +2 -2
  53. package/dist/src/platform-types.d.ts +2 -2
  54. package/package.json +4 -4
@@ -1,13 +1,15 @@
1
- import { AUDITED_TIERS, isDerived, BASE_FIELDS, ENTITIES, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
- import { DEFAULT_ACCESS, parseManifest, schemaHash, servedRoles, } from '@quad-education/schema';
1
+ import { AUDITED_TIERS, isDerived, isWindowed, BASE_FIELDS, ENTITIES, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
+ import { DEFAULT_ACCESS, classify, parseManifest, schemaHash, schoolRolesOf, servedRoles, } from '@quad-education/schema';
3
3
  import { QuadError } from "../contract/errors.js";
4
+ import { staticDirectory, } from "../contract/principals.js";
4
5
  import { SDK_VERSION } from "../contract/types.js";
5
6
  import { clockNow } from "../protocol.js";
6
7
  import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
7
8
  import { checkIndexCoverage } from "./db-indexes.js";
8
9
  import { runQuery } from "./query.js";
9
10
  import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
10
- import { EngineStorage, } from "./storage.js";
11
+ import { isStaffOrSystem, roleNamesOf, schoolPrincipal, } from "./state.js";
12
+ import { MemoryStore } from "./memory-store.js";
11
13
  import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
12
14
  import { entityOf, fieldOf, validateInput } from "./validate-input.js";
13
15
  const SYSTEM_FIELDS = ['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy'];
@@ -29,20 +31,24 @@ class Grant extends Set {
29
31
  this.declared = declared;
30
32
  }
31
33
  }
32
- /**
33
- * The in-browser implementation of the @quad-education/sdk contract (D15). It runs in the demo
34
- * shell's origin, holds the fictional school, and enforces visibility, scopes and D17 on
35
- * every call. Apps reach it only through a transport.
36
- */
37
34
  export class Engine {
38
35
  apps = new Map();
39
36
  clock = { kind: 'offset', offsetMs: 0 };
40
37
  byId = new Map();
41
38
  dataset;
42
- storage;
43
- constructor(dataset, storage) {
44
- this.dataset = dataset;
45
- this.storage = storage;
39
+ store;
40
+ zone;
41
+ directory;
42
+ hasSchool;
43
+ constructor(dataset, store, directory, hasSchool, zone) {
44
+ // With no school nothing reaches the dataset: every school call is refused first (`schoolPrincipal`).
45
+ this.dataset = dataset ?? {};
46
+ this.store = store;
47
+ this.directory = directory;
48
+ this.hasSchool = hasSchool;
49
+ this.zone = zone;
50
+ if (!dataset || !hasSchool)
51
+ return;
46
52
  for (const entity of Object.keys(ENTITIES)) {
47
53
  if (isDerived(entity)) {
48
54
  // Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
@@ -57,120 +63,120 @@ export class Engine {
57
63
  }
58
64
  }
59
65
  static async create(options) {
60
- const storage = await EngineStorage.open(options.indexedDB, options.dbName);
61
- return new Engine(options.dataset, storage);
66
+ const hasSchool = options.school !== false;
67
+ if (hasSchool && !options.dataset)
68
+ throw new Error('an engine with a school needs a dataset');
69
+ const store = options.store ??
70
+ (options.indexedDB ? await MemoryStore.open(options.indexedDB, options.dbName) : undefined);
71
+ if (!store)
72
+ throw new Error('an engine needs a store or an IndexedDB factory');
73
+ const zone = hasSchool
74
+ ? options.dataset.schools[0].timezone
75
+ : (options.timezone ?? 'Australia/Sydney');
76
+ const accounts = options.accounts ?? [];
77
+ const directory = Array.isArray(accounts)
78
+ ? staticDirectory(accounts)
79
+ : accounts;
80
+ return new Engine(options.dataset, store, directory, hasSchool, zone);
62
81
  }
63
82
  close() {
64
- this.storage.close();
83
+ void this.store.close();
65
84
  }
66
85
  // ---- Platform-side API (shell and tests) ----
67
86
  /** Load an app, resetting its store if the schema changed since last time (D12). */
68
- async installApp({ manifest, schema }) {
87
+ async installApp({ manifest, schema, timezone, }) {
69
88
  const parsed = parseManifest(manifest);
70
89
  if (!parsed.ok)
71
90
  throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
72
91
  const appId = parsed.manifest.id;
73
- const hash = schemaHash(schema);
74
- const meta = await this.storage.getMeta(appId);
75
- if (meta && meta.schemaHash !== hash)
76
- await this.storage.clearApp(appId, { schemaChangeOnly: true });
77
- await this.storage.put('meta', [{ appId, schemaHash: hash }]);
78
- const app = {
79
- manifest: parsed.manifest,
80
- schema,
81
- records: new Map(),
82
- keys: new Map(),
83
- tasks: new Map(),
84
- schedules: new Map(),
85
- runs: new Map(),
86
- cron: new Map(),
87
- audit: [],
88
- };
89
- for (const entity of Object.keys(schema))
90
- app.records.set(entity, new Map());
91
- for (const r of await this.storage.getAll('records', appId)) {
92
- app.records.get(r.entity)?.set(r.id, r.data);
93
- }
94
- for (const k of await this.storage.getAll('keys', appId))
95
- app.keys.set(k.key, k.result);
96
- for (const row of await this.storage.getAll('platform', appId)) {
97
- if (row.kind === 'task')
98
- app.tasks.set(row.id, row.data);
99
- // Rows stored before run-as rules (D7) have no runAs; those were system-scheduled.
100
- else if (row.kind === 'schedule' || row.kind === 'run') {
101
- const data = row.data;
102
- const withRunAs = { ...data, runAs: data.runAs ?? { kind: 'system', appId } };
103
- if (row.kind === 'schedule')
104
- app.schedules.set(row.id, withRunAs);
105
- else
106
- app.runs.set(row.id, withRunAs);
107
- }
108
- else if (row.kind === 'cron')
109
- app.cron.set(row.id, row.data);
110
- else
111
- app.audit.push(row.data);
112
- }
113
- app.audit.sort((a, b) => a.seq - b.seq);
114
- // Cron jobs no longer in the manifest stop; new ones start from now.
115
- for (const name of app.cron.keys())
116
- if (!app.manifest.cron.some((c) => c.name === name))
117
- app.cron.delete(name);
92
+ await this.store.open(appId, schemaHash(schema), schema);
93
+ const app = { manifest: parsed.manifest, schema, ...(timezone ? { timezone } : {}) };
118
94
  this.apps.set(appId, app);
119
95
  await initCron(this, app);
120
96
  }
97
+ /**
98
+ * Register an app that is already installed in the store, without touching its state. A stateless server
99
+ * (the data API) does this on each cold start; `installApp` is for publishing and reinstalling.
100
+ */
101
+ attachApp({ manifest, schema, timezone, }) {
102
+ const parsed = parseManifest(manifest);
103
+ if (!parsed.ok)
104
+ throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
105
+ this.apps.set(parsed.manifest.id, {
106
+ manifest: parsed.manifest,
107
+ schema,
108
+ ...(timezone ? { timezone } : {}),
109
+ });
110
+ }
111
+ /** Whether an app is registered with this engine. */
112
+ hasApp(appId) {
113
+ return this.apps.has(appId);
114
+ }
115
+ /** Replace the account directory (the shell rebuilds it when a previewed app's roles change). */
116
+ setAccounts(accounts) {
117
+ this.directory = staticDirectory(accounts);
118
+ }
119
+ /** Whether the app has no school here, so its people are accounts and guests (V2c, D100). */
120
+ isStandalone(appId) {
121
+ return !this.usesSchool(this.appFor(appId));
122
+ }
121
123
  manifest(appId) {
122
124
  return this.appFor(appId).manifest;
123
125
  }
124
126
  /** Clear an app's data and outbox (the shell's reset button). */
125
127
  async resetApp(appId) {
126
128
  const app = this.appFor(appId);
127
- await this.storage.clearApp(appId);
128
- for (const records of app.records.values())
129
- records.clear();
130
- app.keys.clear();
131
- app.tasks.clear();
132
- app.schedules.clear();
133
- app.runs.clear();
134
- app.cron.clear();
135
- app.audit.length = 0;
129
+ await this.store.clear(appId);
136
130
  await initCron(this, app);
137
131
  }
138
132
  // ---- Platform-side API for Slice B (shell and tests) ----
139
133
  /** Open tasks assigned to a person: the shell's inbox (D6). */
140
- inbox(appId, personId) {
134
+ async inbox(appId, personId) {
141
135
  const app = this.appFor(appId);
142
- const ctx = { app, principal: { kind: 'system', appId }, actorId: `system:${appId}` };
143
- return inbox(app, personId).map((t) => taskView(ctx, t));
136
+ const ctx = {
137
+ app,
138
+ principal: { kind: 'system', appId },
139
+ actorId: `system:${appId}`,
140
+ school: this.usesSchool(app),
141
+ };
142
+ return (await inbox(this, appId, personId)).map((t) => taskView(ctx, t));
144
143
  }
145
144
  /** Every audit entry, including CIO-only ones (the shell's audit viewer, D19). */
146
- auditLog(appId) {
147
- return this.appFor(appId).audit.map((e) => ({ ...auditView(e), visibility: e.visibility }));
145
+ async auditLog(appId) {
146
+ const entries = await this.store.allPlatform(appId, 'audit');
147
+ return entries
148
+ .sort((a, b) => a.seq - b.seq)
149
+ .map((e) => ({ ...auditView(e), visibility: e.visibility }));
148
150
  }
149
151
  /** Counts of everything a job can change, for run-twice tests (D20). */
150
152
  async effectsSnapshot(appId) {
151
- const app = this.appFor(appId);
152
- const records = {};
153
- for (const [entity, rows] of app.records) {
154
- records[entity] = Object.fromEntries([...rows.values()].map((r) => [r.id, r.updatedAt]));
155
- }
153
+ const [records, tasks, schedules, audit, outbox] = await Promise.all([
154
+ this.store.recordStamps(appId),
155
+ this.store.allPlatform(appId, 'task'),
156
+ this.store.allPlatform(appId, 'schedule'),
157
+ this.store.allPlatform(appId, 'audit'),
158
+ this.outbox(appId),
159
+ ]);
156
160
  return {
157
- outbox: (await this.outbox(appId)).length,
158
- tasks: Object.fromEntries([...app.tasks.values()].map((t) => [t.id, t.status])),
159
- schedules: Object.fromEntries([...app.schedules.values()].map((s) => [s.id, s.status])),
160
- audit: app.audit.length,
161
+ outbox: outbox.length,
162
+ tasks: Object.fromEntries(tasks.map((t) => [t.id, t.status])),
163
+ schedules: Object.fromEntries(schedules.map((s) => [s.id, s.status])),
164
+ audit: audit.length,
161
165
  records,
162
166
  };
163
167
  }
164
168
  /** Runs for the job log, newest first. */
165
- runs(appId) {
166
- return [...this.appFor(appId).runs.values()].sort((a, b) => b.scheduledFor.localeCompare(a.scheduledFor) || a.id.localeCompare(b.id));
169
+ async runs(appId) {
170
+ const runs = await this.store.allPlatform(appId, 'run');
171
+ return runs.sort((a, b) => b.scheduledFor.localeCompare(a.scheduledFor) || a.id.localeCompare(b.id));
167
172
  }
168
173
  /**
169
174
  * Who a call from the jobs host acts as: the principal of the run it belongs to (D7).
170
175
  * Only runs that are currently running count, so a finished run's id can't be replayed.
171
176
  */
172
- runPrincipal(appId, runId) {
173
- const run = runId === undefined ? undefined : this.appFor(appId).runs.get(runId);
177
+ async runPrincipal(appId, runId) {
178
+ this.appFor(appId);
179
+ const run = runId === undefined ? undefined : await this.store.getPlatform(appId, 'run', runId);
174
180
  if (!run || run.status !== 'running') {
175
181
  throw new QuadError('FORBIDDEN', 'calls from the jobs host must belong to a running job');
176
182
  }
@@ -199,14 +205,14 @@ export class Engine {
199
205
  : { kind: 'offset', offsetMs: this.clock.offsetMs + ms };
200
206
  }
201
207
  // ---- Kernel (used by the Slice B modules) ----
202
- timezone() {
203
- return this.dataset.schools[0].timezone;
208
+ timezone(app) {
209
+ return app?.timezone ?? this.zone;
204
210
  }
205
211
  async persistPlatform(app, kind, items) {
206
- await this.storage.putPlatform(app.manifest.id, kind, items);
212
+ await this.store.putPlatform(app.manifest.id, kind, items);
207
213
  }
208
214
  async outbox(appId) {
209
- const entries = await this.storage.getAll('outbox', appId);
215
+ const entries = await this.store.outbox(appId);
210
216
  return entries.sort((a, b) => a.sentAt.localeCompare(b.sentAt) || a.id.localeCompare(b.id));
211
217
  }
212
218
  /** Freeze the clock at an instant, or return to real time with `null` (D14). */
@@ -237,12 +243,13 @@ export class Engine {
237
243
  return clockNow(this.clock, Date.now());
238
244
  }
239
245
  sessionInfo(appId) {
240
- this.appFor(appId);
241
- return { appId, timezone: this.dataset.schools[0].timezone, clock: this.clock };
246
+ return { appId, timezone: this.timezone(this.appFor(appId)), clock: this.clock };
242
247
  }
243
248
  /** Handle one SDK call from `appId` on behalf of `principal`. */
244
249
  async handle(appId, principal, method, params) {
245
- const ctx = this.context(appId, principal);
250
+ const ctx = await this.context(appId, principal);
251
+ if (method.startsWith('school.'))
252
+ schoolPrincipal(ctx);
246
253
  const p = (params ?? {});
247
254
  switch (method) {
248
255
  case 'auth.me':
@@ -290,7 +297,7 @@ export class Engine {
290
297
  case 'schedule.cancel':
291
298
  return scheduleCancel(this, ctx, p.id);
292
299
  case 'schedule.list':
293
- return scheduleList(ctx, p);
300
+ return scheduleList(this, ctx, p);
294
301
  case 'cron.list':
295
302
  return cronList(this, ctx);
296
303
  case 'audit.record':
@@ -308,12 +315,40 @@ export class Engine {
308
315
  throw new QuadError('NOT_FOUND', `app ${appId} is not installed`);
309
316
  return app;
310
317
  }
311
- context(appId, principal) {
318
+ /** A school app, in an environment that has a school: standalone apps and school-less environments have none. */
319
+ usesSchool(app) {
320
+ const m = app.manifest;
321
+ return (this.hasSchool &&
322
+ classify({
323
+ roles: m.roles,
324
+ schoolRoles: schoolRolesOf(m),
325
+ scopes: m.scopes,
326
+ entities: Object.keys(m.data ?? {}),
327
+ connectorActions: [],
328
+ }).class !== 'standalone');
329
+ }
330
+ async context(appId, principal) {
312
331
  const app = this.appFor(appId);
332
+ const school = this.usesSchool(app);
313
333
  if (principal.kind === 'system') {
314
334
  if (principal.appId !== appId)
315
335
  throw new QuadError('FORBIDDEN', 'system principal belongs to another app');
316
- return { app, principal, actorId: `system:${appId}` };
336
+ return { app, principal, actorId: `system:${appId}`, school };
337
+ }
338
+ if (principal.kind === 'guest') {
339
+ if (!app.manifest.guests)
340
+ throw new QuadError('FORBIDDEN', `${app.manifest.name} doesn't handle guests`);
341
+ return { app, principal, actorId: `guest:${principal.guestId}`, school: false };
342
+ }
343
+ if (principal.kind === 'account') {
344
+ const held = principal.roles.map((r) => r.toLowerCase());
345
+ const served = app.manifest.roles.map((r) => r.toLowerCase());
346
+ if (principal.displayName === undefined && !(await this.directory.get(principal.accountId)))
347
+ throw new QuadError('FORBIDDEN', `no account ${principal.accountId}`);
348
+ if (held.length === 0 || !held.every((r) => served.includes(r))) {
349
+ throw new QuadError('FORBIDDEN', `${app.manifest.name} doesn't have those roles`);
350
+ }
351
+ return { app, principal, actorId: `acct:${principal.accountId}`, school: false };
317
352
  }
318
353
  const person = this.byId.get(principal.personId);
319
354
  if (!person || person.entity !== PEOPLE[principal.role]) {
@@ -323,12 +358,22 @@ export class Engine {
323
358
  if (!servedRoles(app.manifest).includes(principal.role)) {
324
359
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
325
360
  }
326
- return { app, principal, actorId: principal.personId };
361
+ return { app, principal, actorId: principal.personId, school };
327
362
  }
328
- me(ctx) {
363
+ async me(ctx) {
329
364
  const { principal } = ctx;
330
365
  if (principal.kind === 'system')
331
366
  return { kind: 'system', appId: principal.appId };
367
+ if (principal.kind === 'guest')
368
+ return { kind: 'guest', guest: { id: principal.guestId } };
369
+ if (principal.kind === 'account') {
370
+ const displayName = principal.displayName ?? (await this.directory.get(principal.accountId))?.displayName;
371
+ return {
372
+ kind: 'account',
373
+ account: { id: principal.accountId, displayName: displayName ?? principal.accountId },
374
+ roles: [...principal.roles],
375
+ };
376
+ }
332
377
  const r = this.byId.get(principal.personId).record;
333
378
  return {
334
379
  kind: 'user',
@@ -367,7 +412,7 @@ export class Engine {
367
412
  if (granted.size === 0) {
368
413
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
369
414
  }
370
- const allowed = principalTiers(ctx.principal, entity);
415
+ const allowed = principalTiers(schoolPrincipal(ctx), entity);
371
416
  // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
372
417
  const entry = ctx.app.manifest.data?.[entity];
373
418
  const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
@@ -381,7 +426,27 @@ export class Engine {
381
426
  return fields;
382
427
  }
383
428
  visible(ctx, entity) {
384
- return visibleRecords(ctx.principal, entity, this.dataset);
429
+ return visibleRecords(schoolPrincipal(ctx), entity, this.dataset);
430
+ }
431
+ /**
432
+ * The records a read may start from. A windowed entity (the register, V2s S4.2) is never built whole: the
433
+ * dataset makes only the slice the where clause names, for only the students the reader may see, and
434
+ * visibility, fields and the rest of the where clause apply to that slice as to any other. A dataset with no
435
+ * way to select (one wrapped with a custom registry) falls back to building everything.
436
+ */
437
+ visibleFor(ctx, entity, where) {
438
+ const select = isWindowed(entity)
439
+ ? this.dataset.select
440
+ : undefined;
441
+ if (typeof select !== 'function')
442
+ return this.visible(ctx, entity);
443
+ ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
444
+ const made = select.call(this.dataset, entity, { where, students: ctx.students });
445
+ if (made === null)
446
+ return this.visible(ctx, entity);
447
+ if (!made.ok)
448
+ throw new QuadError('VALIDATION', made.message);
449
+ return visibleRecords(schoolPrincipal(ctx), entity, this.dataset, made.rows);
385
450
  }
386
451
  shape(entity, grant, records) {
387
452
  return records.map((r) => filterFields(entity, r, grant, grant.declared));
@@ -389,7 +454,7 @@ export class Engine {
389
454
  async schoolGet(ctx, entityValue, id) {
390
455
  const entity = this.entityName(entityValue);
391
456
  const tiers = this.tiers(ctx, entity);
392
- const record = this.visible(ctx, entity).find((r) => r.id === id);
457
+ const record = this.visibleFor(ctx, entity, { id }).find((r) => r.id === id);
393
458
  if (!record)
394
459
  throw new QuadError('NOT_FOUND', `no ${entity} record ${String(id)}`);
395
460
  await this.auditSensitiveRead(ctx, entity, tiers, 1, 'school.get');
@@ -398,7 +463,7 @@ export class Engine {
398
463
  async schoolList(ctx, entityValue, options) {
399
464
  const entity = this.entityName(entityValue);
400
465
  const tiers = this.tiers(ctx, entity);
401
- const page = runQuery(this.visible(ctx, entity), (options ?? {}), this.allowedFields(entity, tiers));
466
+ const page = runQuery(this.visibleFor(ctx, entity, options?.where), (options ?? {}), this.allowedFields(entity, tiers));
402
467
  await this.auditSensitiveRead(ctx, entity, tiers, page.items.length, 'school.list');
403
468
  return { items: this.shape(entity, tiers, page.items), nextCursor: page.nextCursor };
404
469
  }
@@ -468,7 +533,7 @@ export class Engine {
468
533
  if (typeof value !== 'string' || !def) {
469
534
  throw new QuadError('VALIDATION', `'${String(value)}' is not an entity in this app's schema`);
470
535
  }
471
- return { name: value, def, records: ctx.app.records.get(value) };
536
+ return { name: value, def };
472
537
  }
473
538
  nowIso() {
474
539
  return new Date(this.nowMs()).toISOString();
@@ -479,18 +544,29 @@ export class Engine {
479
544
  return 'system';
480
545
  const policy = def.access ?? DEFAULT_ACCESS;
481
546
  // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
482
- const role = ctx.principal.role;
483
- const key = Object.hasOwn(policy, role)
484
- ? role
485
- : Object.keys(policy).find((k) => k.toLowerCase() === role);
486
- const value = key === undefined ? undefined : policy[key]?.[op];
487
- return value === undefined ? [] : Array.isArray(value) ? value : [value];
547
+ // An account holds several app roles: it gets the union of their rules (V2c, D100).
548
+ const out = new Set();
549
+ for (const role of roleNamesOf(ctx.principal)) {
550
+ const key = Object.hasOwn(policy, role)
551
+ ? role
552
+ : Object.keys(policy).find((k) => k.toLowerCase() === role.toLowerCase());
553
+ const value = key === undefined ? undefined : policy[key]?.[op];
554
+ if (value === undefined)
555
+ continue;
556
+ for (const rule of Array.isArray(value) ? value : [value]) {
557
+ // A guest only ever reaches their own records, whatever the policy says.
558
+ if (ctx.principal.kind === 'guest' && rule !== 'own')
559
+ continue;
560
+ out.add(rule);
561
+ }
562
+ }
563
+ return [...out];
488
564
  }
489
565
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
490
566
  seesStudent(ctx, studentId) {
491
567
  if (typeof studentId !== 'string')
492
568
  return false;
493
- ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
569
+ ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
494
570
  return ctx.students === 'all'
495
571
  ? this.byId.get(studentId)?.entity === 'students'
496
572
  : ctx.students.has(studentId);
@@ -501,6 +577,7 @@ export class Engine {
501
577
  return rules.some((rule) => rule === 'all' ||
502
578
  (rule === 'own' && record.createdBy === ctx.actorId) ||
503
579
  (rule === 'subject' &&
580
+ ctx.school &&
504
581
  def.subject !== undefined &&
505
582
  this.seesStudent(ctx, record[def.subject])));
506
583
  }
@@ -512,7 +589,7 @@ export class Engine {
512
589
  const visibleTo = fieldOf(def, field)?.visibleTo;
513
590
  return (ctx.principal.kind === 'system' ||
514
591
  visibleTo === undefined ||
515
- visibleTo.includes(ctx.principal.role));
592
+ roleNamesOf(ctx.principal).some((r) => visibleTo.some((v) => v.toLowerCase() === r.toLowerCase())));
516
593
  }
517
594
  /** A record as the current role receives it: hidden fields removed, not just emptied. */
518
595
  shapeRecord(ctx, def, record) {
@@ -525,28 +602,31 @@ export class Engine {
525
602
  requireOperation(ctx, entity, def, op) {
526
603
  const rules = this.rules(ctx, def, op);
527
604
  if (rules !== 'system' && rules.length === 0) {
528
- const who = ctx.principal.kind === 'user' ? ctx.principal.role : 'system';
605
+ const who = ctx.principal.kind === 'system' ? 'system' : roleNamesOf(ctx.principal).join('/');
529
606
  throw new QuadError('NOT_PERMITTED', `${who} users may not ${op} ${entity} records`);
530
607
  }
531
608
  return rules;
532
609
  }
533
610
  /** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
534
- readable(ctx, entity, id) {
535
- const record = entity.records.get(str(id, 'id'));
611
+ async readable(ctx, entity, id) {
612
+ const record = await this.store.getRecord(ctx.app.manifest.id, entity.name, str(id, 'id'));
536
613
  if (!record || !this.canRead(ctx, entity.def, record)) {
537
614
  throw new QuadError('NOT_FOUND', `no ${entity.name} record ${String(id)}`);
538
615
  }
539
616
  return record;
540
617
  }
541
618
  /** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
542
- checkWrite(ctx, entity, values) {
619
+ async checkWrite(ctx, entity, values) {
543
620
  for (const key of Object.keys(values)) {
544
621
  if (!this.fieldVisible(ctx, entity.def, key)) {
545
622
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${key} isn't available to you`);
546
623
  }
547
624
  }
548
625
  const subject = entity.def.subject;
549
- if (subject !== undefined && subject in values && ctx.principal.kind !== 'system') {
626
+ if (subject !== undefined &&
627
+ subject in values &&
628
+ ctx.principal.kind !== 'system' &&
629
+ ctx.school) {
550
630
  if (!this.seesStudent(ctx, values[subject])) {
551
631
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${subject}: not a student you can see`);
552
632
  }
@@ -563,7 +643,7 @@ export class Engine {
563
643
  }
564
644
  else {
565
645
  const targetDef = entityOf(ctx.app.schema, field.to);
566
- const target = ctx.app.records.get(field.to)?.get(value);
646
+ const target = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
567
647
  if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
568
648
  throw new QuadError('VALIDATION', `${key}: no ${field.to} record ${value}`);
569
649
  }
@@ -571,25 +651,20 @@ export class Engine {
571
651
  }
572
652
  }
573
653
  async remember(ctx, key, result) {
574
- ctx.app.keys.set(key, result);
575
- await this.storage.put('keys', [{ appId: ctx.app.manifest.id, key, result }]);
654
+ await this.store.putKey(ctx.app.manifest.id, key, result);
576
655
  }
577
656
  idempotencyKey(options, scope) {
578
657
  if (!isObject(options) || options.idempotencyKey === undefined)
579
658
  return undefined;
580
659
  return `${scope}:${str(options.idempotencyKey, 'idempotencyKey')}`;
581
660
  }
582
- async persist(ctx, entity, record) {
583
- await this.storage.put('records', [
584
- { appId: ctx.app.manifest.id, entity, id: record.id, data: record },
585
- ]);
586
- }
587
661
  async dbCreate(ctx, entityValue, input, options) {
588
662
  const entity = this.dbEntity(ctx, entityValue);
589
663
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'create');
590
664
  const key = this.idempotencyKey(options, `db.create:${entity.name}`);
591
- if (key && ctx.app.keys.has(key)) {
592
- const existing = entity.records.get(ctx.app.keys.get(key));
665
+ const remembered = key ? await this.store.getKey(ctx.app.manifest.id, key) : undefined;
666
+ if (typeof remembered === 'string') {
667
+ const existing = await this.store.getRecord(ctx.app.manifest.id, entity.name, remembered);
593
668
  if (existing && this.canRead(ctx, entity.def, existing))
594
669
  return this.shapeRecord(ctx, entity.def, existing);
595
670
  }
@@ -597,7 +672,7 @@ export class Engine {
597
672
  for (const k of Object.keys(values))
598
673
  if (values[k] === null)
599
674
  delete values[k];
600
- this.checkWrite(ctx, entity, values);
675
+ await this.checkWrite(ctx, entity, values);
601
676
  const now = this.nowIso();
602
677
  const record = {
603
678
  id: `${entity.name}_${crypto.randomUUID()}`,
@@ -610,21 +685,20 @@ export class Engine {
610
685
  if (!this.matches(ctx, entity.def, rules, record)) {
611
686
  throw new QuadError('NOT_PERMITTED', `you may not create this ${entity.name} record`);
612
687
  }
613
- entity.records.set(record.id, record);
614
- await this.persist(ctx, entity.name, record);
688
+ await this.store.putRecord(ctx.app.manifest.id, entity.name, record);
615
689
  if (key)
616
690
  await this.remember(ctx, key, record.id);
617
691
  return this.shapeRecord(ctx, entity.def, record);
618
692
  }
619
693
  async dbUpdate(ctx, entityValue, id, patch) {
620
694
  const entity = this.dbEntity(ctx, entityValue);
621
- const existing = this.readable(ctx, entity, id);
695
+ const existing = await this.readable(ctx, entity, id);
622
696
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'update');
623
697
  if (!this.matches(ctx, entity.def, rules, existing)) {
624
698
  throw new QuadError('NOT_PERMITTED', `you may not update this ${entity.name} record`);
625
699
  }
626
700
  const values = validateInput(entity.name, entity.def, patch, { partial: true });
627
- this.checkWrite(ctx, entity, values);
701
+ await this.checkWrite(ctx, entity, values);
628
702
  const record = { ...existing };
629
703
  for (const [k, v] of Object.entries(values)) {
630
704
  if (v === null)
@@ -637,18 +711,17 @@ export class Engine {
637
711
  if (!this.matches(ctx, entity.def, rules, record)) {
638
712
  throw new QuadError('NOT_PERMITTED', `this change would take the ${entity.name} record out of your reach`);
639
713
  }
640
- entity.records.set(existing.id, record);
641
- await this.persist(ctx, entity.name, record);
714
+ await this.store.putRecord(ctx.app.manifest.id, entity.name, record, existing);
642
715
  return this.shapeRecord(ctx, entity.def, record);
643
716
  }
644
- dbGet(ctx, entityValue, id) {
717
+ async dbGet(ctx, entityValue, id) {
645
718
  const entity = this.dbEntity(ctx, entityValue);
646
719
  this.requireOperation(ctx, entity.name, entity.def, 'read');
647
- return this.shapeRecord(ctx, entity.def, this.readable(ctx, entity, id));
720
+ return this.shapeRecord(ctx, entity.def, await this.readable(ctx, entity, id));
648
721
  }
649
722
  async dbList(ctx, entityValue, options) {
650
723
  const entity = this.dbEntity(ctx, entityValue);
651
- this.requireOperation(ctx, entity.name, entity.def, 'read');
724
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
652
725
  const { include, ...query } = (isObject(options) ? options : {});
653
726
  const includes = include === undefined ? [] : Array.isArray(include) ? include : null;
654
727
  if (!includes)
@@ -661,7 +734,13 @@ export class Engine {
661
734
  }
662
735
  }
663
736
  // Access first, then filters and pages: results and cursors only ever cover readable records.
664
- const readable = [...entity.records.values()].filter((r) => this.canRead(ctx, entity.def, r));
737
+ const candidates = await this.store.candidates(ctx.app.manifest.id, entity.name, {
738
+ ...(rules !== 'system' && rules.every((r) => r === 'own') ? { ownedBy: ctx.actorId } : {}),
739
+ where: query.where,
740
+ orderBy: query.orderBy,
741
+ indexes: entity.def.indexes,
742
+ });
743
+ const readable = candidates.filter((r) => this.canRead(ctx, entity.def, r));
665
744
  const fields = new Set([
666
745
  ...SYSTEM_FIELDS,
667
746
  ...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
@@ -673,19 +752,19 @@ export class Engine {
673
752
  if (includes.length === 0)
674
753
  return { items, nextCursor: page.nextCursor };
675
754
  const schoolReads = new Map();
676
- const withIncluded = items.map((r) => ({
677
- ...r,
678
- $included: Object.fromEntries(includes.map((f) => [
679
- f,
680
- this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads),
681
- ])),
682
- }));
755
+ const withIncluded = [];
756
+ for (const r of items) {
757
+ const included = {};
758
+ for (const f of includes)
759
+ included[f] = await this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads);
760
+ withIncluded.push({ ...r, $included: included });
761
+ }
683
762
  for (const [target, count] of schoolReads) {
684
763
  await this.auditSensitiveRead(ctx, target, this.tiers(ctx, target), count, 'db.include');
685
764
  }
686
765
  return { items: withIncluded, nextCursor: page.nextCursor };
687
766
  }
688
- resolveRef(ctx, field, value, schoolReads) {
767
+ async resolveRef(ctx, field, value, schoolReads) {
689
768
  if (typeof value !== 'string' || !field.to)
690
769
  return null;
691
770
  if (field.to.startsWith('school.')) {
@@ -701,20 +780,19 @@ export class Engine {
701
780
  }
702
781
  // Included app records follow their own entity's rules (D25).
703
782
  const def = entityOf(ctx.app.schema, field.to);
704
- const record = ctx.app.records.get(field.to)?.get(value);
783
+ const record = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
705
784
  return def && record && this.canRead(ctx, def, record)
706
785
  ? this.shapeRecord(ctx, def, record)
707
786
  : null;
708
787
  }
709
788
  async dbDelete(ctx, entityValue, id) {
710
789
  const entity = this.dbEntity(ctx, entityValue);
711
- const existing = this.readable(ctx, entity, id);
790
+ const existing = await this.readable(ctx, entity, id);
712
791
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'delete');
713
792
  if (!this.matches(ctx, entity.def, rules, existing)) {
714
793
  throw new QuadError('NOT_PERMITTED', `you may not delete this ${entity.name} record`);
715
794
  }
716
- entity.records.delete(existing.id);
717
- await this.storage.deleteRecord(ctx.app.manifest.id, entity.name, existing.id);
795
+ await this.store.deleteRecord(ctx.app.manifest.id, entity.name, existing);
718
796
  return null;
719
797
  }
720
798
  // ---- notify (D10, D17) ----
@@ -725,8 +803,9 @@ export class Engine {
725
803
  throw new QuadError('UNDECLARED_TYPE', `notification type '${type}' isn't declared in app.manifest.json`);
726
804
  }
727
805
  const key = this.idempotencyKey(input, 'notify.send');
728
- if (key && ctx.app.keys.has(key))
729
- return ctx.app.keys.get(key);
806
+ const remembered = key ? await this.store.getKey(ctx.app.manifest.id, key) : undefined;
807
+ if (remembered !== undefined)
808
+ return remembered;
730
809
  const subject = str(input.subject, 'subject');
731
810
  const body = str(input.body, 'body');
732
811
  const channel = input.channel ?? 'inApp';
@@ -744,7 +823,7 @@ export class Engine {
744
823
  if (this.byId.get(regarding)?.entity !== 'students')
745
824
  throw new QuadError('VALIDATION', `no student ${regarding}`);
746
825
  }
747
- const { recipients, suppressed } = this.resolveRecipients(ctx, input.to, regarding);
826
+ const { recipients, suppressed } = await this.resolveRecipients(ctx, input.to, regarding);
748
827
  const sentAt = this.nowIso();
749
828
  const entries = recipients.map((r) => ({
750
829
  id: `out_${crypto.randomUUID()}`,
@@ -761,8 +840,7 @@ export class Engine {
761
840
  sentBy: ctx.actorId,
762
841
  simulated: true,
763
842
  }));
764
- if (entries.length > 0)
765
- await this.storage.put('outbox', entries);
843
+ await this.store.putOutbox(manifest.id, entries);
766
844
  await appendAudit(this, ctx.app, {
767
845
  source: 'platform',
768
846
  action: 'notification.sent',
@@ -792,12 +870,16 @@ export class Engine {
792
870
  * Resolves recipients to people, applying the app's roles and D17. Parents are only ever
793
871
  * reached about a specific student, and only through an eligible, unrestricted link.
794
872
  */
795
- resolveRecipients(ctx, to, regarding) {
873
+ async resolveRecipients(ctx, to, regarding) {
796
874
  const list = Array.isArray(to) ? to : [to];
797
875
  if (list.length === 0)
798
876
  throw new QuadError('VALIDATION', 'to must name at least one recipient');
799
877
  const roles = servedRoles(ctx.app.manifest);
800
- const senderIsStaff = ctx.principal.kind === 'system' || ctx.principal.role === 'staff';
878
+ if (ctx.principal.kind === 'guest')
879
+ throw new QuadError('FORBIDDEN', 'guests cannot send notifications or assign tasks');
880
+ if (!ctx.school)
881
+ return await this.resolveAppRecipients(ctx, list);
882
+ const senderIsStaff = isStaffOrSystem(ctx);
801
883
  const out = new Map();
802
884
  const suppressed = new Map();
803
885
  const suppress = (personId, studentId, purpose) => {
@@ -857,10 +939,11 @@ export class Engine {
857
939
  else if ('role' in r) {
858
940
  if (!['staff', 'student', 'parent'].includes(r.role))
859
941
  throw new QuadError('VALIDATION', `unknown role ${String(r.role)}`);
860
- if (!roles.includes(r.role))
861
- throw new QuadError('VALIDATION', `${ctx.app.manifest.name} doesn't serve ${r.role} users`);
862
- for (const p of this.dataset[PEOPLE[r.role]])
863
- add(p.id, r.role);
942
+ const role = r.role;
943
+ if (!roles.includes(role))
944
+ throw new QuadError('VALIDATION', `${ctx.app.manifest.name} doesn't serve ${role} users`);
945
+ for (const p of this.dataset[PEOPLE[role]])
946
+ add(p.id, role);
864
947
  }
865
948
  else if ('relationship' in r && r.relationship === 'parentsOf') {
866
949
  const studentId = str(r.studentId, 'studentId');
@@ -902,6 +985,42 @@ export class Engine {
902
985
  }
903
986
  return { recipients: [...out.values()], suppressed: [...suppressed.values()] };
904
987
  }
988
+ /**
989
+ * Recipients outside a school (V2c, D100): Quad accounts, by id or by one of the app's own roles, from the
990
+ * account directory. Everything that needs a school is NOT_AVAILABLE. Guests have no address, so never appear.
991
+ */
992
+ async resolveAppRecipients(ctx, list) {
993
+ const appRoles = ctx.app.manifest.roles;
994
+ const out = new Map();
995
+ for (const r of list) {
996
+ if (!isObject(r))
997
+ throw new QuadError('VALIDATION', 'each recipient must be an object');
998
+ if ('account' in r) {
999
+ const account = await this.directory.get(str(r.account, 'account'));
1000
+ if (!account)
1001
+ throw new QuadError('VALIDATION', `no account ${String(r.account)}`);
1002
+ const role = appRoles.find((a) => account.roles.some((x) => x.toLowerCase() === a.toLowerCase()));
1003
+ out.set(`acct:${account.id}`, {
1004
+ personId: `acct:${account.id}`,
1005
+ role: role ?? account.roles[0],
1006
+ });
1007
+ }
1008
+ else if ('role' in r) {
1009
+ const role = appRoles.find((a) => a.toLowerCase() === String(r.role).toLowerCase());
1010
+ if (role === undefined)
1011
+ throw new QuadError('VALIDATION', `${ctx.app.manifest.name} has no role ${String(r.role)}`);
1012
+ for (const a of await this.directory.withRole(role))
1013
+ out.set(`acct:${a.id}`, { personId: `acct:${a.id}`, role });
1014
+ }
1015
+ else if ('person' in r || 'relationship' in r) {
1016
+ throw new QuadError('NOT_AVAILABLE', 'there is no school here: people and relationships need one');
1017
+ }
1018
+ else {
1019
+ throw new QuadError('VALIDATION', 'unknown recipient; use { account } or { role }');
1020
+ }
1021
+ }
1022
+ return { recipients: [...out.values()], suppressed: [] };
1023
+ }
905
1024
  suppressionReason(parentId, studentId, purpose) {
906
1025
  const link = this.dataset.parentStudentLinks.find((l) => l.parentId === parentId && l.studentId === studentId);
907
1026
  if (!link)