@quad-education/sdk 0.1.4 → 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 +1 -0
  2. package/dist/contract-tests/apps.d.ts +79 -0
  3. package/dist/contract-tests/apps.js +56 -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 +207 -42
  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 +53 -17
  34. package/dist/src/engine/engine.js +260 -156
  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
1
  import { AUDITED_TIERS, isDerived, isWindowed, 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';
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'];
@@ -34,10 +36,19 @@ export class Engine {
34
36
  clock = { kind: 'offset', offsetMs: 0 };
35
37
  byId = new Map();
36
38
  dataset;
37
- storage;
38
- constructor(dataset, storage) {
39
- this.dataset = dataset;
40
- 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;
41
52
  for (const entity of Object.keys(ENTITIES)) {
42
53
  if (isDerived(entity)) {
43
54
  // Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
@@ -52,120 +63,120 @@ export class Engine {
52
63
  }
53
64
  }
54
65
  static async create(options) {
55
- const storage = await EngineStorage.open(options.indexedDB, options.dbName);
56
- 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);
57
81
  }
58
82
  close() {
59
- this.storage.close();
83
+ void this.store.close();
60
84
  }
61
85
  // ---- Platform-side API (shell and tests) ----
62
86
  /** Load an app, resetting its store if the schema changed since last time (D12). */
63
- async installApp({ manifest, schema }) {
87
+ async installApp({ manifest, schema, timezone, }) {
64
88
  const parsed = parseManifest(manifest);
65
89
  if (!parsed.ok)
66
90
  throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
67
91
  const appId = parsed.manifest.id;
68
- const hash = schemaHash(schema);
69
- const meta = await this.storage.getMeta(appId);
70
- if (meta && meta.schemaHash !== hash)
71
- await this.storage.clearApp(appId, { schemaChangeOnly: true });
72
- await this.storage.put('meta', [{ appId, schemaHash: hash }]);
73
- const app = {
74
- manifest: parsed.manifest,
75
- schema,
76
- records: new Map(),
77
- keys: new Map(),
78
- tasks: new Map(),
79
- schedules: new Map(),
80
- runs: new Map(),
81
- cron: new Map(),
82
- audit: [],
83
- };
84
- for (const entity of Object.keys(schema))
85
- app.records.set(entity, new Map());
86
- for (const r of await this.storage.getAll('records', appId)) {
87
- app.records.get(r.entity)?.set(r.id, r.data);
88
- }
89
- for (const k of await this.storage.getAll('keys', appId))
90
- app.keys.set(k.key, k.result);
91
- for (const row of await this.storage.getAll('platform', appId)) {
92
- if (row.kind === 'task')
93
- app.tasks.set(row.id, row.data);
94
- // Rows stored before run-as rules (D7) have no runAs; those were system-scheduled.
95
- else if (row.kind === 'schedule' || row.kind === 'run') {
96
- const data = row.data;
97
- const withRunAs = { ...data, runAs: data.runAs ?? { kind: 'system', appId } };
98
- if (row.kind === 'schedule')
99
- app.schedules.set(row.id, withRunAs);
100
- else
101
- app.runs.set(row.id, withRunAs);
102
- }
103
- else if (row.kind === 'cron')
104
- app.cron.set(row.id, row.data);
105
- else
106
- app.audit.push(row.data);
107
- }
108
- app.audit.sort((a, b) => a.seq - b.seq);
109
- // Cron jobs no longer in the manifest stop; new ones start from now.
110
- for (const name of app.cron.keys())
111
- if (!app.manifest.cron.some((c) => c.name === name))
112
- app.cron.delete(name);
92
+ await this.store.open(appId, schemaHash(schema), schema);
93
+ const app = { manifest: parsed.manifest, schema, ...(timezone ? { timezone } : {}) };
113
94
  this.apps.set(appId, app);
114
95
  await initCron(this, app);
115
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
+ }
116
123
  manifest(appId) {
117
124
  return this.appFor(appId).manifest;
118
125
  }
119
126
  /** Clear an app's data and outbox (the shell's reset button). */
120
127
  async resetApp(appId) {
121
128
  const app = this.appFor(appId);
122
- await this.storage.clearApp(appId);
123
- for (const records of app.records.values())
124
- records.clear();
125
- app.keys.clear();
126
- app.tasks.clear();
127
- app.schedules.clear();
128
- app.runs.clear();
129
- app.cron.clear();
130
- app.audit.length = 0;
129
+ await this.store.clear(appId);
131
130
  await initCron(this, app);
132
131
  }
133
132
  // ---- Platform-side API for Slice B (shell and tests) ----
134
133
  /** Open tasks assigned to a person: the shell's inbox (D6). */
135
- inbox(appId, personId) {
134
+ async inbox(appId, personId) {
136
135
  const app = this.appFor(appId);
137
- const ctx = { app, principal: { kind: 'system', appId }, actorId: `system:${appId}` };
138
- 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));
139
143
  }
140
144
  /** Every audit entry, including CIO-only ones (the shell's audit viewer, D19). */
141
- auditLog(appId) {
142
- 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 }));
143
150
  }
144
151
  /** Counts of everything a job can change, for run-twice tests (D20). */
145
152
  async effectsSnapshot(appId) {
146
- const app = this.appFor(appId);
147
- const records = {};
148
- for (const [entity, rows] of app.records) {
149
- records[entity] = Object.fromEntries([...rows.values()].map((r) => [r.id, r.updatedAt]));
150
- }
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
+ ]);
151
160
  return {
152
- outbox: (await this.outbox(appId)).length,
153
- tasks: Object.fromEntries([...app.tasks.values()].map((t) => [t.id, t.status])),
154
- schedules: Object.fromEntries([...app.schedules.values()].map((s) => [s.id, s.status])),
155
- 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,
156
165
  records,
157
166
  };
158
167
  }
159
168
  /** Runs for the job log, newest first. */
160
- runs(appId) {
161
- 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));
162
172
  }
163
173
  /**
164
174
  * Who a call from the jobs host acts as: the principal of the run it belongs to (D7).
165
175
  * Only runs that are currently running count, so a finished run's id can't be replayed.
166
176
  */
167
- runPrincipal(appId, runId) {
168
- 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);
169
180
  if (!run || run.status !== 'running') {
170
181
  throw new QuadError('FORBIDDEN', 'calls from the jobs host must belong to a running job');
171
182
  }
@@ -194,14 +205,14 @@ export class Engine {
194
205
  : { kind: 'offset', offsetMs: this.clock.offsetMs + ms };
195
206
  }
196
207
  // ---- Kernel (used by the Slice B modules) ----
197
- timezone() {
198
- return this.dataset.schools[0].timezone;
208
+ timezone(app) {
209
+ return app?.timezone ?? this.zone;
199
210
  }
200
211
  async persistPlatform(app, kind, items) {
201
- await this.storage.putPlatform(app.manifest.id, kind, items);
212
+ await this.store.putPlatform(app.manifest.id, kind, items);
202
213
  }
203
214
  async outbox(appId) {
204
- const entries = await this.storage.getAll('outbox', appId);
215
+ const entries = await this.store.outbox(appId);
205
216
  return entries.sort((a, b) => a.sentAt.localeCompare(b.sentAt) || a.id.localeCompare(b.id));
206
217
  }
207
218
  /** Freeze the clock at an instant, or return to real time with `null` (D14). */
@@ -232,12 +243,13 @@ export class Engine {
232
243
  return clockNow(this.clock, Date.now());
233
244
  }
234
245
  sessionInfo(appId) {
235
- this.appFor(appId);
236
- return { appId, timezone: this.dataset.schools[0].timezone, clock: this.clock };
246
+ return { appId, timezone: this.timezone(this.appFor(appId)), clock: this.clock };
237
247
  }
238
248
  /** Handle one SDK call from `appId` on behalf of `principal`. */
239
249
  async handle(appId, principal, method, params) {
240
- const ctx = this.context(appId, principal);
250
+ const ctx = await this.context(appId, principal);
251
+ if (method.startsWith('school.'))
252
+ schoolPrincipal(ctx);
241
253
  const p = (params ?? {});
242
254
  switch (method) {
243
255
  case 'auth.me':
@@ -285,7 +297,7 @@ export class Engine {
285
297
  case 'schedule.cancel':
286
298
  return scheduleCancel(this, ctx, p.id);
287
299
  case 'schedule.list':
288
- return scheduleList(ctx, p);
300
+ return scheduleList(this, ctx, p);
289
301
  case 'cron.list':
290
302
  return cronList(this, ctx);
291
303
  case 'audit.record':
@@ -303,12 +315,40 @@ export class Engine {
303
315
  throw new QuadError('NOT_FOUND', `app ${appId} is not installed`);
304
316
  return app;
305
317
  }
306
- 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) {
307
331
  const app = this.appFor(appId);
332
+ const school = this.usesSchool(app);
308
333
  if (principal.kind === 'system') {
309
334
  if (principal.appId !== appId)
310
335
  throw new QuadError('FORBIDDEN', 'system principal belongs to another app');
311
- 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 };
312
352
  }
313
353
  const person = this.byId.get(principal.personId);
314
354
  if (!person || person.entity !== PEOPLE[principal.role]) {
@@ -318,12 +358,22 @@ export class Engine {
318
358
  if (!servedRoles(app.manifest).includes(principal.role)) {
319
359
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
320
360
  }
321
- return { app, principal, actorId: principal.personId };
361
+ return { app, principal, actorId: principal.personId, school };
322
362
  }
323
- me(ctx) {
363
+ async me(ctx) {
324
364
  const { principal } = ctx;
325
365
  if (principal.kind === 'system')
326
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
+ }
327
377
  const r = this.byId.get(principal.personId).record;
328
378
  return {
329
379
  kind: 'user',
@@ -362,7 +412,7 @@ export class Engine {
362
412
  if (granted.size === 0) {
363
413
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
364
414
  }
365
- const allowed = principalTiers(ctx.principal, entity);
415
+ const allowed = principalTiers(schoolPrincipal(ctx), entity);
366
416
  // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
367
417
  const entry = ctx.app.manifest.data?.[entity];
368
418
  const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
@@ -376,7 +426,7 @@ export class Engine {
376
426
  return fields;
377
427
  }
378
428
  visible(ctx, entity) {
379
- return visibleRecords(ctx.principal, entity, this.dataset);
429
+ return visibleRecords(schoolPrincipal(ctx), entity, this.dataset);
380
430
  }
381
431
  /**
382
432
  * The records a read may start from. A windowed entity (the register, V2s S4.2) is never built whole: the
@@ -390,13 +440,13 @@ export class Engine {
390
440
  : undefined;
391
441
  if (typeof select !== 'function')
392
442
  return this.visible(ctx, entity);
393
- ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
443
+ ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
394
444
  const made = select.call(this.dataset, entity, { where, students: ctx.students });
395
445
  if (made === null)
396
446
  return this.visible(ctx, entity);
397
447
  if (!made.ok)
398
448
  throw new QuadError('VALIDATION', made.message);
399
- return visibleRecords(ctx.principal, entity, this.dataset, made.rows);
449
+ return visibleRecords(schoolPrincipal(ctx), entity, this.dataset, made.rows);
400
450
  }
401
451
  shape(entity, grant, records) {
402
452
  return records.map((r) => filterFields(entity, r, grant, grant.declared));
@@ -483,7 +533,7 @@ export class Engine {
483
533
  if (typeof value !== 'string' || !def) {
484
534
  throw new QuadError('VALIDATION', `'${String(value)}' is not an entity in this app's schema`);
485
535
  }
486
- return { name: value, def, records: ctx.app.records.get(value) };
536
+ return { name: value, def };
487
537
  }
488
538
  nowIso() {
489
539
  return new Date(this.nowMs()).toISOString();
@@ -494,18 +544,29 @@ export class Engine {
494
544
  return 'system';
495
545
  const policy = def.access ?? DEFAULT_ACCESS;
496
546
  // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
497
- const role = ctx.principal.role;
498
- const key = Object.hasOwn(policy, role)
499
- ? role
500
- : Object.keys(policy).find((k) => k.toLowerCase() === role);
501
- const value = key === undefined ? undefined : policy[key]?.[op];
502
- 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];
503
564
  }
504
565
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
505
566
  seesStudent(ctx, studentId) {
506
567
  if (typeof studentId !== 'string')
507
568
  return false;
508
- ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
569
+ ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
509
570
  return ctx.students === 'all'
510
571
  ? this.byId.get(studentId)?.entity === 'students'
511
572
  : ctx.students.has(studentId);
@@ -516,6 +577,7 @@ export class Engine {
516
577
  return rules.some((rule) => rule === 'all' ||
517
578
  (rule === 'own' && record.createdBy === ctx.actorId) ||
518
579
  (rule === 'subject' &&
580
+ ctx.school &&
519
581
  def.subject !== undefined &&
520
582
  this.seesStudent(ctx, record[def.subject])));
521
583
  }
@@ -527,7 +589,7 @@ export class Engine {
527
589
  const visibleTo = fieldOf(def, field)?.visibleTo;
528
590
  return (ctx.principal.kind === 'system' ||
529
591
  visibleTo === undefined ||
530
- visibleTo.includes(ctx.principal.role));
592
+ roleNamesOf(ctx.principal).some((r) => visibleTo.some((v) => v.toLowerCase() === r.toLowerCase())));
531
593
  }
532
594
  /** A record as the current role receives it: hidden fields removed, not just emptied. */
533
595
  shapeRecord(ctx, def, record) {
@@ -540,28 +602,31 @@ export class Engine {
540
602
  requireOperation(ctx, entity, def, op) {
541
603
  const rules = this.rules(ctx, def, op);
542
604
  if (rules !== 'system' && rules.length === 0) {
543
- const who = ctx.principal.kind === 'user' ? ctx.principal.role : 'system';
605
+ const who = ctx.principal.kind === 'system' ? 'system' : roleNamesOf(ctx.principal).join('/');
544
606
  throw new QuadError('NOT_PERMITTED', `${who} users may not ${op} ${entity} records`);
545
607
  }
546
608
  return rules;
547
609
  }
548
610
  /** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
549
- readable(ctx, entity, id) {
550
- 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'));
551
613
  if (!record || !this.canRead(ctx, entity.def, record)) {
552
614
  throw new QuadError('NOT_FOUND', `no ${entity.name} record ${String(id)}`);
553
615
  }
554
616
  return record;
555
617
  }
556
618
  /** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
557
- checkWrite(ctx, entity, values) {
619
+ async checkWrite(ctx, entity, values) {
558
620
  for (const key of Object.keys(values)) {
559
621
  if (!this.fieldVisible(ctx, entity.def, key)) {
560
622
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${key} isn't available to you`);
561
623
  }
562
624
  }
563
625
  const subject = entity.def.subject;
564
- 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) {
565
630
  if (!this.seesStudent(ctx, values[subject])) {
566
631
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${subject}: not a student you can see`);
567
632
  }
@@ -578,7 +643,7 @@ export class Engine {
578
643
  }
579
644
  else {
580
645
  const targetDef = entityOf(ctx.app.schema, field.to);
581
- const target = ctx.app.records.get(field.to)?.get(value);
646
+ const target = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
582
647
  if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
583
648
  throw new QuadError('VALIDATION', `${key}: no ${field.to} record ${value}`);
584
649
  }
@@ -586,25 +651,20 @@ export class Engine {
586
651
  }
587
652
  }
588
653
  async remember(ctx, key, result) {
589
- ctx.app.keys.set(key, result);
590
- await this.storage.put('keys', [{ appId: ctx.app.manifest.id, key, result }]);
654
+ await this.store.putKey(ctx.app.manifest.id, key, result);
591
655
  }
592
656
  idempotencyKey(options, scope) {
593
657
  if (!isObject(options) || options.idempotencyKey === undefined)
594
658
  return undefined;
595
659
  return `${scope}:${str(options.idempotencyKey, 'idempotencyKey')}`;
596
660
  }
597
- async persist(ctx, entity, record) {
598
- await this.storage.put('records', [
599
- { appId: ctx.app.manifest.id, entity, id: record.id, data: record },
600
- ]);
601
- }
602
661
  async dbCreate(ctx, entityValue, input, options) {
603
662
  const entity = this.dbEntity(ctx, entityValue);
604
663
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'create');
605
664
  const key = this.idempotencyKey(options, `db.create:${entity.name}`);
606
- if (key && ctx.app.keys.has(key)) {
607
- 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);
608
668
  if (existing && this.canRead(ctx, entity.def, existing))
609
669
  return this.shapeRecord(ctx, entity.def, existing);
610
670
  }
@@ -612,7 +672,7 @@ export class Engine {
612
672
  for (const k of Object.keys(values))
613
673
  if (values[k] === null)
614
674
  delete values[k];
615
- this.checkWrite(ctx, entity, values);
675
+ await this.checkWrite(ctx, entity, values);
616
676
  const now = this.nowIso();
617
677
  const record = {
618
678
  id: `${entity.name}_${crypto.randomUUID()}`,
@@ -625,21 +685,20 @@ export class Engine {
625
685
  if (!this.matches(ctx, entity.def, rules, record)) {
626
686
  throw new QuadError('NOT_PERMITTED', `you may not create this ${entity.name} record`);
627
687
  }
628
- entity.records.set(record.id, record);
629
- await this.persist(ctx, entity.name, record);
688
+ await this.store.putRecord(ctx.app.manifest.id, entity.name, record);
630
689
  if (key)
631
690
  await this.remember(ctx, key, record.id);
632
691
  return this.shapeRecord(ctx, entity.def, record);
633
692
  }
634
693
  async dbUpdate(ctx, entityValue, id, patch) {
635
694
  const entity = this.dbEntity(ctx, entityValue);
636
- const existing = this.readable(ctx, entity, id);
695
+ const existing = await this.readable(ctx, entity, id);
637
696
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'update');
638
697
  if (!this.matches(ctx, entity.def, rules, existing)) {
639
698
  throw new QuadError('NOT_PERMITTED', `you may not update this ${entity.name} record`);
640
699
  }
641
700
  const values = validateInput(entity.name, entity.def, patch, { partial: true });
642
- this.checkWrite(ctx, entity, values);
701
+ await this.checkWrite(ctx, entity, values);
643
702
  const record = { ...existing };
644
703
  for (const [k, v] of Object.entries(values)) {
645
704
  if (v === null)
@@ -652,18 +711,17 @@ export class Engine {
652
711
  if (!this.matches(ctx, entity.def, rules, record)) {
653
712
  throw new QuadError('NOT_PERMITTED', `this change would take the ${entity.name} record out of your reach`);
654
713
  }
655
- entity.records.set(existing.id, record);
656
- await this.persist(ctx, entity.name, record);
714
+ await this.store.putRecord(ctx.app.manifest.id, entity.name, record, existing);
657
715
  return this.shapeRecord(ctx, entity.def, record);
658
716
  }
659
- dbGet(ctx, entityValue, id) {
717
+ async dbGet(ctx, entityValue, id) {
660
718
  const entity = this.dbEntity(ctx, entityValue);
661
719
  this.requireOperation(ctx, entity.name, entity.def, 'read');
662
- return this.shapeRecord(ctx, entity.def, this.readable(ctx, entity, id));
720
+ return this.shapeRecord(ctx, entity.def, await this.readable(ctx, entity, id));
663
721
  }
664
722
  async dbList(ctx, entityValue, options) {
665
723
  const entity = this.dbEntity(ctx, entityValue);
666
- this.requireOperation(ctx, entity.name, entity.def, 'read');
724
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
667
725
  const { include, ...query } = (isObject(options) ? options : {});
668
726
  const includes = include === undefined ? [] : Array.isArray(include) ? include : null;
669
727
  if (!includes)
@@ -676,7 +734,13 @@ export class Engine {
676
734
  }
677
735
  }
678
736
  // Access first, then filters and pages: results and cursors only ever cover readable records.
679
- 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));
680
744
  const fields = new Set([
681
745
  ...SYSTEM_FIELDS,
682
746
  ...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
@@ -688,19 +752,19 @@ export class Engine {
688
752
  if (includes.length === 0)
689
753
  return { items, nextCursor: page.nextCursor };
690
754
  const schoolReads = new Map();
691
- const withIncluded = items.map((r) => ({
692
- ...r,
693
- $included: Object.fromEntries(includes.map((f) => [
694
- f,
695
- this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads),
696
- ])),
697
- }));
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
+ }
698
762
  for (const [target, count] of schoolReads) {
699
763
  await this.auditSensitiveRead(ctx, target, this.tiers(ctx, target), count, 'db.include');
700
764
  }
701
765
  return { items: withIncluded, nextCursor: page.nextCursor };
702
766
  }
703
- resolveRef(ctx, field, value, schoolReads) {
767
+ async resolveRef(ctx, field, value, schoolReads) {
704
768
  if (typeof value !== 'string' || !field.to)
705
769
  return null;
706
770
  if (field.to.startsWith('school.')) {
@@ -716,20 +780,19 @@ export class Engine {
716
780
  }
717
781
  // Included app records follow their own entity's rules (D25).
718
782
  const def = entityOf(ctx.app.schema, field.to);
719
- const record = ctx.app.records.get(field.to)?.get(value);
783
+ const record = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
720
784
  return def && record && this.canRead(ctx, def, record)
721
785
  ? this.shapeRecord(ctx, def, record)
722
786
  : null;
723
787
  }
724
788
  async dbDelete(ctx, entityValue, id) {
725
789
  const entity = this.dbEntity(ctx, entityValue);
726
- const existing = this.readable(ctx, entity, id);
790
+ const existing = await this.readable(ctx, entity, id);
727
791
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'delete');
728
792
  if (!this.matches(ctx, entity.def, rules, existing)) {
729
793
  throw new QuadError('NOT_PERMITTED', `you may not delete this ${entity.name} record`);
730
794
  }
731
- entity.records.delete(existing.id);
732
- await this.storage.deleteRecord(ctx.app.manifest.id, entity.name, existing.id);
795
+ await this.store.deleteRecord(ctx.app.manifest.id, entity.name, existing);
733
796
  return null;
734
797
  }
735
798
  // ---- notify (D10, D17) ----
@@ -740,8 +803,9 @@ export class Engine {
740
803
  throw new QuadError('UNDECLARED_TYPE', `notification type '${type}' isn't declared in app.manifest.json`);
741
804
  }
742
805
  const key = this.idempotencyKey(input, 'notify.send');
743
- if (key && ctx.app.keys.has(key))
744
- 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;
745
809
  const subject = str(input.subject, 'subject');
746
810
  const body = str(input.body, 'body');
747
811
  const channel = input.channel ?? 'inApp';
@@ -759,7 +823,7 @@ export class Engine {
759
823
  if (this.byId.get(regarding)?.entity !== 'students')
760
824
  throw new QuadError('VALIDATION', `no student ${regarding}`);
761
825
  }
762
- const { recipients, suppressed } = this.resolveRecipients(ctx, input.to, regarding);
826
+ const { recipients, suppressed } = await this.resolveRecipients(ctx, input.to, regarding);
763
827
  const sentAt = this.nowIso();
764
828
  const entries = recipients.map((r) => ({
765
829
  id: `out_${crypto.randomUUID()}`,
@@ -776,8 +840,7 @@ export class Engine {
776
840
  sentBy: ctx.actorId,
777
841
  simulated: true,
778
842
  }));
779
- if (entries.length > 0)
780
- await this.storage.put('outbox', entries);
843
+ await this.store.putOutbox(manifest.id, entries);
781
844
  await appendAudit(this, ctx.app, {
782
845
  source: 'platform',
783
846
  action: 'notification.sent',
@@ -807,12 +870,16 @@ export class Engine {
807
870
  * Resolves recipients to people, applying the app's roles and D17. Parents are only ever
808
871
  * reached about a specific student, and only through an eligible, unrestricted link.
809
872
  */
810
- resolveRecipients(ctx, to, regarding) {
873
+ async resolveRecipients(ctx, to, regarding) {
811
874
  const list = Array.isArray(to) ? to : [to];
812
875
  if (list.length === 0)
813
876
  throw new QuadError('VALIDATION', 'to must name at least one recipient');
814
877
  const roles = servedRoles(ctx.app.manifest);
815
- 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);
816
883
  const out = new Map();
817
884
  const suppressed = new Map();
818
885
  const suppress = (personId, studentId, purpose) => {
@@ -872,10 +939,11 @@ export class Engine {
872
939
  else if ('role' in r) {
873
940
  if (!['staff', 'student', 'parent'].includes(r.role))
874
941
  throw new QuadError('VALIDATION', `unknown role ${String(r.role)}`);
875
- if (!roles.includes(r.role))
876
- throw new QuadError('VALIDATION', `${ctx.app.manifest.name} doesn't serve ${r.role} users`);
877
- for (const p of this.dataset[PEOPLE[r.role]])
878
- 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);
879
947
  }
880
948
  else if ('relationship' in r && r.relationship === 'parentsOf') {
881
949
  const studentId = str(r.studentId, 'studentId');
@@ -917,6 +985,42 @@ export class Engine {
917
985
  }
918
986
  return { recipients: [...out.values()], suppressed: [...suppressed.values()] };
919
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
+ }
920
1024
  suppressionReason(parentId, studentId, purpose) {
921
1025
  const link = this.dataset.parentStudentLinks.find((l) => l.parentId === parentId && l.studentId === studentId);
922
1026
  if (!link)