@quad-education/sdk 0.2.0 → 0.4.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 (42) hide show
  1. package/README.md +4 -2
  2. package/dist/contract-tests/apps.d.ts +3 -112
  3. package/dist/contract-tests/apps.js +6 -183
  4. package/dist/contract-tests/harness.d.ts +2 -2
  5. package/dist/contract-tests/index.d.ts +2 -3
  6. package/dist/contract-tests/index.js +1 -2
  7. package/dist/contract-tests/suite.d.ts +3 -10
  8. package/dist/contract-tests/suite.js +49 -502
  9. package/dist/src/client/connect.d.ts +3 -13
  10. package/dist/src/client/connect.js +3 -21
  11. package/dist/src/client/create-client.js +0 -3
  12. package/dist/src/client/handshake-client.d.ts +0 -2
  13. package/dist/src/client/handshake-client.js +0 -2
  14. package/dist/src/contract/errors.d.ts +1 -1
  15. package/dist/src/contract/recipients.d.ts +2 -8
  16. package/dist/src/contract/types.d.ts +7 -44
  17. package/dist/src/contract/types.js +1 -1
  18. package/dist/src/engine/engine.d.ts +10 -46
  19. package/dist/src/engine/engine.js +42 -222
  20. package/dist/src/engine/host.d.ts +2 -2
  21. package/dist/src/engine/in-process.d.ts +2 -2
  22. package/dist/src/engine/runner.js +2 -4
  23. package/dist/src/engine/state.d.ts +6 -17
  24. package/dist/src/engine/state.js +3 -31
  25. package/dist/src/engine/tasks.js +3 -10
  26. package/dist/src/index.d.ts +0 -1
  27. package/dist/src/index.js +0 -1
  28. package/dist/src/jobs/define.d.ts +2 -2
  29. package/dist/src/platform-types.d.ts +2 -2
  30. package/dist/src/protocol.d.ts +1 -1
  31. package/dist/src/protocol.js +0 -1
  32. package/package.json +4 -4
  33. package/dist/contract-tests/standalone-apps.d.ts +0 -183
  34. package/dist/contract-tests/standalone-apps.js +0 -178
  35. package/dist/contract-tests/standalone.d.ts +0 -2
  36. package/dist/contract-tests/standalone.js +0 -709
  37. package/dist/src/client/http-transport.d.ts +0 -18
  38. package/dist/src/client/http-transport.js +0 -76
  39. package/dist/src/client/live.d.ts +0 -39
  40. package/dist/src/client/live.js +0 -122
  41. package/dist/src/contract/principals.d.ts +0 -30
  42. package/dist/src/contract/principals.js +0 -12
@@ -1,14 +1,13 @@
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, classify, parseManifest, schemaHash, schoolRolesOf, servedRoles, } from '@quad-education/schema';
2
+ import { DEFAULT_ACCESS, parseManifest, schemaHash, servedRoles, } from '@quad-education/schema';
3
3
  import { QuadError } from "../contract/errors.js";
4
- import { staticDirectory, } from "../contract/principals.js";
5
4
  import { SDK_VERSION } from "../contract/types.js";
6
5
  import { clockNow } from "../protocol.js";
7
6
  import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
8
7
  import { checkIndexCoverage } from "./db-indexes.js";
9
8
  import { runQuery } from "./query.js";
10
9
  import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
11
- import { isStaffOrSystem, roleNamesOf, schoolPrincipal, } from "./state.js";
10
+ import { isStaffOrSystem, } from "./state.js";
12
11
  import { MemoryStore } from "./memory-store.js";
13
12
  import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
14
13
  import { entityOf, fieldOf, validateInput } from "./validate-input.js";
@@ -20,16 +19,8 @@ const str = (v, what) => {
20
19
  throw new QuadError('VALIDATION', `${what} must be a non-empty string`);
21
20
  return v;
22
21
  };
23
- /**
24
- * What an app may read of one entity: the tiers granted to it and allowed to the principal (D23), plus
25
- * the varying fields its version 1 manifest declared (null for version 0, which has no declaration).
26
- */
22
+ /** What an app may read of one entity: the tiers granted to it and allowed to the principal (D23). */
27
23
  class Grant extends Set {
28
- declared;
29
- constructor(tiers, declared) {
30
- super(tiers);
31
- this.declared = declared;
32
- }
33
24
  }
34
25
  export class Engine {
35
26
  apps = new Map();
@@ -37,18 +28,9 @@ export class Engine {
37
28
  byId = new Map();
38
29
  dataset;
39
30
  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 ?? {};
31
+ constructor(dataset, store) {
32
+ this.dataset = dataset;
46
33
  this.store = store;
47
- this.directory = directory;
48
- this.hasSchool = hasSchool;
49
- this.zone = zone;
50
- if (!dataset || !hasSchool)
51
- return;
52
34
  for (const entity of Object.keys(ENTITIES)) {
53
35
  if (isDerived(entity)) {
54
36
  // Worked out when an app first reads it (V2s S4.1), so it isn't indexed by id here.
@@ -63,63 +45,27 @@ export class Engine {
63
45
  }
64
46
  }
65
47
  static async create(options) {
66
- const hasSchool = options.school !== false;
67
- if (hasSchool && !options.dataset)
68
- throw new Error('an engine with a school needs a dataset');
69
48
  const store = options.store ??
70
49
  (options.indexedDB ? await MemoryStore.open(options.indexedDB, options.dbName) : undefined);
71
50
  if (!store)
72
51
  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);
52
+ return new Engine(options.dataset, store);
81
53
  }
82
54
  close() {
83
55
  void this.store.close();
84
56
  }
85
57
  // ---- Platform-side API (shell and tests) ----
86
58
  /** Load an app, resetting its store if the schema changed since last time (D12). */
87
- async installApp({ manifest, schema, timezone, }) {
59
+ async installApp({ manifest, schema }) {
88
60
  const parsed = parseManifest(manifest);
89
61
  if (!parsed.ok)
90
62
  throw new QuadError('VALIDATION', `invalid manifest: ${parsed.problems.join('; ')}`);
91
63
  const appId = parsed.manifest.id;
92
64
  await this.store.open(appId, schemaHash(schema), schema);
93
- const app = { manifest: parsed.manifest, schema, ...(timezone ? { timezone } : {}) };
65
+ const app = { manifest: parsed.manifest, schema };
94
66
  this.apps.set(appId, app);
95
67
  await initCron(this, app);
96
68
  }
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
- }
123
69
  manifest(appId) {
124
70
  return this.appFor(appId).manifest;
125
71
  }
@@ -137,7 +83,6 @@ export class Engine {
137
83
  app,
138
84
  principal: { kind: 'system', appId },
139
85
  actorId: `system:${appId}`,
140
- school: this.usesSchool(app),
141
86
  };
142
87
  return (await inbox(this, appId, personId)).map((t) => taskView(ctx, t));
143
88
  }
@@ -205,8 +150,8 @@ export class Engine {
205
150
  : { kind: 'offset', offsetMs: this.clock.offsetMs + ms };
206
151
  }
207
152
  // ---- Kernel (used by the Slice B modules) ----
208
- timezone(app) {
209
- return app?.timezone ?? this.zone;
153
+ timezone() {
154
+ return this.dataset.schools[0].timezone;
210
155
  }
211
156
  async persistPlatform(app, kind, items) {
212
157
  await this.store.putPlatform(app.manifest.id, kind, items);
@@ -243,13 +188,12 @@ export class Engine {
243
188
  return clockNow(this.clock, Date.now());
244
189
  }
245
190
  sessionInfo(appId) {
246
- return { appId, timezone: this.timezone(this.appFor(appId)), clock: this.clock };
191
+ this.appFor(appId);
192
+ return { appId, timezone: this.timezone(), clock: this.clock };
247
193
  }
248
194
  /** Handle one SDK call from `appId` on behalf of `principal`. */
249
195
  async handle(appId, principal, method, params) {
250
- const ctx = await this.context(appId, principal);
251
- if (method.startsWith('school.'))
252
- schoolPrincipal(ctx);
196
+ const ctx = this.context(appId, principal);
253
197
  const p = (params ?? {});
254
198
  switch (method) {
255
199
  case 'auth.me':
@@ -268,8 +212,6 @@ export class Engine {
268
212
  return this.studentParents(ctx, p.studentId);
269
213
  case 'school.parentChildren':
270
214
  return this.parentChildren(ctx, p.parentId);
271
- case 'school.calendar':
272
- return this.calendar(ctx, p);
273
215
  case 'db.create':
274
216
  return this.dbCreate(ctx, p.entity, p.input, p.options);
275
217
  case 'db.update':
@@ -315,40 +257,12 @@ export class Engine {
315
257
  throw new QuadError('NOT_FOUND', `app ${appId} is not installed`);
316
258
  return app;
317
259
  }
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) {
260
+ context(appId, principal) {
331
261
  const app = this.appFor(appId);
332
- const school = this.usesSchool(app);
333
262
  if (principal.kind === 'system') {
334
263
  if (principal.appId !== appId)
335
264
  throw new QuadError('FORBIDDEN', 'system principal belongs to another app');
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 };
265
+ return { app, principal, actorId: `system:${appId}` };
352
266
  }
353
267
  const person = this.byId.get(principal.personId);
354
268
  if (!person || person.entity !== PEOPLE[principal.role]) {
@@ -358,22 +272,12 @@ export class Engine {
358
272
  if (!servedRoles(app.manifest).includes(principal.role)) {
359
273
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
360
274
  }
361
- return { app, principal, actorId: principal.personId, school };
275
+ return { app, principal, actorId: principal.personId };
362
276
  }
363
- async me(ctx) {
277
+ me(ctx) {
364
278
  const { principal } = ctx;
365
279
  if (principal.kind === 'system')
366
280
  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
- }
377
281
  const r = this.byId.get(principal.personId).record;
378
282
  return {
379
283
  kind: 'user',
@@ -404,29 +308,25 @@ export class Engine {
404
308
  return value;
405
309
  }
406
310
  /**
407
- * Tiers the app is granted and the principal may see, with the fields it declared (V2s D85);
408
- * SCOPE_NOT_GRANTED if the app has no scope for the entity.
311
+ * Tiers the app is granted and the principal may see; SCOPE_NOT_GRANTED if the app has no scope for the entity.
409
312
  */
410
313
  tiers(ctx, entity) {
411
314
  const granted = grantedTiers(ctx.app.manifest.scopes, entity);
412
315
  if (granted.size === 0) {
413
316
  throw new QuadError('SCOPE_NOT_GRANTED', `${ctx.app.manifest.id} has no scope for ${entity}; add e.g. ${entity}.basic:read`);
414
317
  }
415
- const allowed = principalTiers(schoolPrincipal(ctx), entity);
416
- // A version 1 manifest declares the varying fields it reads; core fields come with the entity.
417
- const entry = ctx.app.manifest.data?.[entity];
418
- const declared = entry ? new Set([...entry.required, ...entry.optional]) : null;
419
- return new Grant([...granted].filter((t) => allowed.has(t)), declared);
318
+ const allowed = principalTiers(ctx.principal, entity);
319
+ return new Grant([...granted].filter((t) => allowed.has(t)));
420
320
  }
421
321
  allowedFields(entity, grant) {
422
322
  const fields = new Set(Object.keys(BASE_FIELDS));
423
323
  for (const [key, def] of Object.entries(ENTITIES[entity].fields))
424
- if (fieldVisible(def, key, grant, grant.declared))
324
+ if (fieldVisible(def, grant))
425
325
  fields.add(key);
426
326
  return fields;
427
327
  }
428
328
  visible(ctx, entity) {
429
- return visibleRecords(schoolPrincipal(ctx), entity, this.dataset);
329
+ return visibleRecords(ctx.principal, entity, this.dataset);
430
330
  }
431
331
  /**
432
332
  * The records a read may start from. A windowed entity (the register, V2s S4.2) is never built whole: the
@@ -440,16 +340,16 @@ export class Engine {
440
340
  : undefined;
441
341
  if (typeof select !== 'function')
442
342
  return this.visible(ctx, entity);
443
- ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
343
+ ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
444
344
  const made = select.call(this.dataset, entity, { where, students: ctx.students });
445
345
  if (made === null)
446
346
  return this.visible(ctx, entity);
447
347
  if (!made.ok)
448
348
  throw new QuadError('VALIDATION', made.message);
449
- return visibleRecords(schoolPrincipal(ctx), entity, this.dataset, made.rows);
349
+ return visibleRecords(ctx.principal, entity, this.dataset, made.rows);
450
350
  }
451
351
  shape(entity, grant, records) {
452
- return records.map((r) => filterFields(entity, r, grant, grant.declared));
352
+ return records.map((r) => filterFields(entity, r, grant));
453
353
  }
454
354
  async schoolGet(ctx, entityValue, id) {
455
355
  const entity = this.entityName(entityValue);
@@ -458,7 +358,7 @@ export class Engine {
458
358
  if (!record)
459
359
  throw new QuadError('NOT_FOUND', `no ${entity} record ${String(id)}`);
460
360
  await this.auditSensitiveRead(ctx, entity, tiers, 1, 'school.get');
461
- return filterFields(entity, record, tiers, tiers.declared);
361
+ return filterFields(entity, record, tiers);
462
362
  }
463
363
  async schoolList(ctx, entityValue, options) {
464
364
  const entity = this.entityName(entityValue);
@@ -470,7 +370,7 @@ export class Engine {
470
370
  cohortByCode(ctx, code) {
471
371
  const tiers = this.tiers(ctx, 'cohorts');
472
372
  const cohort = this.visible(ctx, 'cohorts').find((c) => c.code === str(code, 'code'));
473
- return cohort ? filterFields('cohorts', cohort, tiers, tiers.declared) : null;
373
+ return cohort ? filterFields('cohorts', cohort, tiers) : null;
474
374
  }
475
375
  cohortMembers(ctx, cohortId, options) {
476
376
  const tiers = this.tiers(ctx, 'cohortMemberships');
@@ -500,33 +400,6 @@ export class Engine {
500
400
  const linked = new Set(this.dataset.parentStudentLinks.filter((l) => l.parentId === id).map((l) => l.studentId));
501
401
  return this.shape('students', tiers, this.visible(ctx, 'students').filter((s) => linked.has(s.id)));
502
402
  }
503
- calendar(ctx, p) {
504
- const tiers = this.tiers(ctx, 'calendarEvents');
505
- const from = str(p.from, 'from');
506
- const to = str(p.to, 'to');
507
- if (Number.isNaN(Date.parse(from)) || Number.isNaN(Date.parse(to))) {
508
- throw new QuadError('VALIDATION', 'from and to must be ISO dates or instants');
509
- }
510
- const fromMs = Date.parse(from);
511
- const toMs = Date.parse(to);
512
- let relevant = null;
513
- if (p.cohortId !== undefined) {
514
- // A cohort's events include those for its ancestors, e.g. a class sees its year's events.
515
- relevant = new Set();
516
- const cohorts = new Map(this.dataset.cohorts.map((c) => [c.id, c]));
517
- let current = cohorts.get(str(p.cohortId, 'cohortId'));
518
- if (!current)
519
- throw new QuadError('NOT_FOUND', `no cohort ${String(p.cohortId)}`);
520
- while (current) {
521
- relevant.add(current.id);
522
- current = current.parentCohortId ? cohorts.get(current.parentCohortId) : undefined;
523
- }
524
- }
525
- const events = this.visible(ctx, 'calendarEvents').filter((e) => Date.parse(e.start) < toMs &&
526
- Date.parse(e.end) > fromMs &&
527
- (relevant === null || e.cohortIds.length === 0 || e.cohortIds.some((c) => relevant.has(c))));
528
- return this.shape('calendarEvents', tiers, [...events].sort((a, b) => a.start.localeCompare(b.start)));
529
- }
530
403
  // ---- db (access control: D25) ----
531
404
  dbEntity(ctx, value) {
532
405
  const def = typeof value === 'string' ? entityOf(ctx.app.schema, value) : undefined;
@@ -544,29 +417,18 @@ export class Engine {
544
417
  return 'system';
545
418
  const policy = def.access ?? DEFAULT_ACCESS;
546
419
  // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
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];
420
+ const role = ctx.principal.role;
421
+ const key = Object.hasOwn(policy, role)
422
+ ? role
423
+ : Object.keys(policy).find((k) => k.toLowerCase() === role);
424
+ const value = key === undefined ? undefined : policy[key]?.[op];
425
+ return value === undefined ? [] : Array.isArray(value) ? value : [value];
564
426
  }
565
427
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
566
428
  seesStudent(ctx, studentId) {
567
429
  if (typeof studentId !== 'string')
568
430
  return false;
569
- ctx.students ??= visibleStudentIds(schoolPrincipal(ctx), this.dataset);
431
+ ctx.students ??= visibleStudentIds(ctx.principal, this.dataset);
570
432
  return ctx.students === 'all'
571
433
  ? this.byId.get(studentId)?.entity === 'students'
572
434
  : ctx.students.has(studentId);
@@ -577,7 +439,6 @@ export class Engine {
577
439
  return rules.some((rule) => rule === 'all' ||
578
440
  (rule === 'own' && record.createdBy === ctx.actorId) ||
579
441
  (rule === 'subject' &&
580
- ctx.school &&
581
442
  def.subject !== undefined &&
582
443
  this.seesStudent(ctx, record[def.subject])));
583
444
  }
@@ -587,9 +448,11 @@ export class Engine {
587
448
  /** Fields the current role may see or write (D25 visibleTo). The system principal sees all. */
588
449
  fieldVisible(ctx, def, field) {
589
450
  const visibleTo = fieldOf(def, field)?.visibleTo;
590
- return (ctx.principal.kind === 'system' ||
591
- visibleTo === undefined ||
592
- roleNamesOf(ctx.principal).some((r) => visibleTo.some((v) => v.toLowerCase() === r.toLowerCase())));
451
+ if (ctx.principal.kind === 'system' || visibleTo === undefined)
452
+ return true;
453
+ // Written in any case: an app role `Staff` is previewed by the staff persona.
454
+ const role = ctx.principal.role;
455
+ return visibleTo.some((v) => v.toLowerCase() === role);
593
456
  }
594
457
  /** A record as the current role receives it: hidden fields removed, not just emptied. */
595
458
  shapeRecord(ctx, def, record) {
@@ -602,7 +465,7 @@ export class Engine {
602
465
  requireOperation(ctx, entity, def, op) {
603
466
  const rules = this.rules(ctx, def, op);
604
467
  if (rules !== 'system' && rules.length === 0) {
605
- const who = ctx.principal.kind === 'system' ? 'system' : roleNamesOf(ctx.principal).join('/');
468
+ const who = ctx.principal.kind === 'system' ? 'system' : ctx.principal.role;
606
469
  throw new QuadError('NOT_PERMITTED', `${who} users may not ${op} ${entity} records`);
607
470
  }
608
471
  return rules;
@@ -623,10 +486,7 @@ export class Engine {
623
486
  }
624
487
  }
625
488
  const subject = entity.def.subject;
626
- if (subject !== undefined &&
627
- subject in values &&
628
- ctx.principal.kind !== 'system' &&
629
- ctx.school) {
489
+ if (subject !== undefined && subject in values && ctx.principal.kind !== 'system') {
630
490
  if (!this.seesStudent(ctx, values[subject])) {
631
491
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${subject}: not a student you can see`);
632
492
  }
@@ -776,7 +636,7 @@ export class Engine {
776
636
  return null;
777
637
  schoolReads.set(target, (schoolReads.get(target) ?? 0) + 1);
778
638
  const grant = this.tiers(ctx, target);
779
- return filterFields(target, record, grant, grant.declared);
639
+ return filterFields(target, record, grant);
780
640
  }
781
641
  // Included app records follow their own entity's rules (D25).
782
642
  const def = entityOf(ctx.app.schema, field.to);
@@ -875,10 +735,6 @@ export class Engine {
875
735
  if (list.length === 0)
876
736
  throw new QuadError('VALIDATION', 'to must name at least one recipient');
877
737
  const roles = servedRoles(ctx.app.manifest);
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
738
  const senderIsStaff = isStaffOrSystem(ctx);
883
739
  const out = new Map();
884
740
  const suppressed = new Map();
@@ -985,42 +841,6 @@ export class Engine {
985
841
  }
986
842
  return { recipients: [...out.values()], suppressed: [...suppressed.values()] };
987
843
  }
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
- }
1024
844
  suppressionReason(parentId, studentId, purpose) {
1025
845
  const link = this.dataset.parentStudentLinks.find((l) => l.parentId === parentId && l.studentId === studentId);
1026
846
  if (!link)
@@ -1,4 +1,4 @@
1
- import type { ActingAs } from '../contract/principals.ts';
1
+ import type { Principal } from '@quad-education/canonical';
2
2
  import type { RunRequest, RunResult } from '../jobs/define.ts';
3
3
  import type { Engine } from './engine.ts';
4
4
  export type RejectedMessage = {
@@ -11,7 +11,7 @@ export type HostedFrame = {
11
11
  readonly kind: 'ui' | 'jobs';
12
12
  readonly iframe: HTMLIFrameElement;
13
13
  /** Who the frame acts as. The app never chooses its own principal. */
14
- readonly principal: () => ActingAs;
14
+ readonly principal: () => Principal;
15
15
  };
16
16
  export type HostOptions = {
17
17
  engine: Engine;
@@ -1,5 +1,5 @@
1
- import type { ActingAs } from '../contract/principals.ts';
1
+ import type { Principal } from '@quad-education/canonical';
2
2
  import type { QuadSdk } from '../contract/types.ts';
3
3
  import type { Engine } from './engine.ts';
4
4
  /** An SDK connected to an engine in the same JavaScript context (tests). */
5
- export declare function connectInProcess(engine: Engine, appId: string, principal: ActingAs): QuadSdk;
5
+ export declare function connectInProcess(engine: Engine, appId: string, principal: Principal): QuadSdk;
@@ -16,8 +16,6 @@ const ownsSchedule = (ctx, s) => ctx.principal.kind === 'system' || s.createdBy
16
16
  export async function scheduleAt(k, ctx, input) {
17
17
  // Anyone the app serves may schedule (the session already checked the role). The job
18
18
  // runs as the caller, so it can never do more than the caller could (D7).
19
- if (ctx.principal.kind === 'guest')
20
- throw new QuadError('FORBIDDEN', 'guests cannot schedule jobs: nobody is signed in to run them as');
21
19
  const job = str(input.job, 'job');
22
20
  if (!ctx.app.manifest.scheduled.includes(job)) {
23
21
  throw new QuadError('UNDECLARED_TYPE', `job '${job}' isn't in the manifest's scheduled list`);
@@ -67,7 +65,7 @@ export async function scheduleList(k, ctx, options) {
67
65
  .map(scheduleView);
68
66
  }
69
67
  export async function cronList(k, ctx) {
70
- const tz = k.timezone(ctx.app);
68
+ const tz = k.timezone();
71
69
  const states = await k.store.allPlatform(ctx.app.manifest.id, 'cron');
72
70
  return ctx.app.manifest.cron.map((job) => {
73
71
  const next = nextOccurrence(job.schedule, tz, k.nowMs());
@@ -136,7 +134,7 @@ export async function startDueRuns(k, app) {
136
134
  const state = await k.store.getPlatform(id, 'cron', job.name);
137
135
  if (!state)
138
136
  continue;
139
- const latest = latestOccurrence(job.schedule, k.timezone(app), Date.parse(state.lastScheduledFor), now);
137
+ const latest = latestOccurrence(job.schedule, k.timezone(), Date.parse(state.lastScheduledFor), now);
140
138
  if (latest === null)
141
139
  continue;
142
140
  const scheduledFor = new Date(latest).toISOString();
@@ -1,6 +1,5 @@
1
1
  import { type Dataset, type Principal, type Role } from '@quad-education/canonical';
2
2
  import type { AppSchema, Manifest } from '@quad-education/schema';
3
- import type { ActingAs } from '../contract/principals.ts';
4
3
  import type { AuditEntry, JsonValue, ScheduledRun, Task } from '../contract/types.ts';
5
4
  import type { AppStore, PlatformKind } from './store.ts';
6
5
  export type StoredTask = Omit<Task, 'assignedToMe' | 'assignees'> & {
@@ -19,7 +18,7 @@ export type StoredSchedule = Omit<ScheduledRun, 'runsAs'> & {
19
18
  readonly appId: string;
20
19
  status: ScheduledRun['status'];
21
20
  /** Who the job runs as: whoever scheduled it, in their session (D7). */
22
- readonly runAs: ActingAs;
21
+ readonly runAs: Principal;
23
22
  };
24
23
  export type RunStatus = 'pending' | 'running' | 'succeeded' | 'failed';
25
24
  /** One delivery target of a job: a cron occurrence or a scheduled one-off (D7, D8). */
@@ -33,7 +32,7 @@ export type StoredRun = {
33
32
  readonly scheduledFor: string;
34
33
  readonly payload: JsonValue;
35
34
  /** Cron runs as the system principal; a scheduled run as whoever scheduled it (D7). */
36
- readonly runAs: ActingAs;
35
+ readonly runAs: Principal;
37
36
  status: RunStatus;
38
37
  attempts: number;
39
38
  deliveries: number;
@@ -56,26 +55,16 @@ export type StoredAudit = AuditEntry & {
56
55
  export type App = {
57
56
  manifest: Manifest;
58
57
  schema: AppSchema;
59
- /** An app with no school has its own timezone (V2c); otherwise the school's. */
60
- timezone?: string;
61
58
  };
62
59
  export type Ctx = {
63
60
  app: App;
64
- principal: ActingAs;
61
+ principal: Principal;
65
62
  actorId: string;
66
- /** Whether this call can reach a school: a school app, in an environment that has one (V2c, D100). */
67
- school: boolean;
68
63
  /** Students this principal can see, computed once per call. */
69
64
  students?: 'all' | Set<string>;
70
65
  };
71
66
  export declare const isStaffOrSystem: (ctx: Ctx) => boolean;
72
- /**
73
- * The school principal for a call that needs a school, or NOT_AVAILABLE: an account or a guest has no school,
74
- * nor does a standalone app, nor an environment configured without one (V2c, D100).
75
- */
76
- export declare function schoolPrincipal(ctx: Ctx): Principal;
77
- /** The role names a principal acts under: its school role, an account's app roles, or `guest`. */
78
- export declare function roleNamesOf(p: ActingAs): readonly string[];
67
+ export declare const roleOfPrincipal: (ctx: Ctx) => Role | "system";
79
68
  /** Why a parent recipient was left out (D17). Recorded only in CIO-visible audit entries. */
80
69
  export type SuppressedRecipient = {
81
70
  personId: string;
@@ -85,7 +74,7 @@ export type SuppressedRecipient = {
85
74
  export type ResolvedRecipients = {
86
75
  recipients: {
87
76
  personId: string;
88
- role: Role | (string & {});
77
+ role: Role;
89
78
  regarding?: string;
90
79
  purpose?: 'correspondence' | 'consent';
91
80
  }[];
@@ -97,7 +86,7 @@ export interface Kernel {
97
86
  readonly store: AppStore;
98
87
  nowIso(): string;
99
88
  nowMs(): number;
100
- timezone(app: App): string;
89
+ timezone(): string;
101
90
  persistPlatform(app: App, kind: PlatformKind, items: readonly {
102
91
  id: string;
103
92
  }[]): Promise<void>;
@@ -1,31 +1,6 @@
1
1
  import { visibleStudentIds, } from '@quad-education/canonical';
2
- import { QuadError } from "../contract/errors.js";
3
- export const isStaffOrSystem = (ctx) => ctx.principal.kind === 'system' ||
4
- (ctx.principal.kind === 'user' && ctx.principal.role === 'staff');
5
- /**
6
- * The school principal for a call that needs a school, or NOT_AVAILABLE: an account or a guest has no school,
7
- * nor does a standalone app, nor an environment configured without one (V2c, D100).
8
- */
9
- export function schoolPrincipal(ctx) {
10
- const p = ctx.principal;
11
- if (!ctx.school || p.kind === 'account' || p.kind === 'guest') {
12
- throw new QuadError('NOT_AVAILABLE', 'there is no school here: this needs a school app running in a school');
13
- }
14
- return p;
15
- }
16
- /** The role names a principal acts under: its school role, an account's app roles, or `guest`. */
17
- export function roleNamesOf(p) {
18
- switch (p.kind) {
19
- case 'user':
20
- return [p.role];
21
- case 'account':
22
- return p.roles;
23
- case 'guest':
24
- return ['guest'];
25
- default:
26
- return [];
27
- }
28
- }
2
+ export const isStaffOrSystem = (ctx) => ctx.principal.kind === 'system' || ctx.principal.role === 'staff';
3
+ export const roleOfPrincipal = (ctx) => ctx.principal.kind === 'system' ? 'system' : ctx.principal.role;
29
4
  /**
30
5
  * Whether the current principal can see a subject student, under the school's visibility
31
6
  * policy (D4). Tasks and audit entries about a student follow it for everyone, staff
@@ -34,10 +9,7 @@ export function roleNamesOf(p) {
34
9
  export function seesSubject(k, ctx, studentId) {
35
10
  if (studentId === undefined || ctx.principal.kind === 'system')
36
11
  return true;
37
- const principal = schoolPrincipal(ctx);
38
- if (principal.kind === 'system')
39
- return true;
40
- ctx.students ??= visibleStudentIds(principal, k.dataset);
12
+ ctx.students ??= visibleStudentIds(ctx.principal, k.dataset);
41
13
  return ctx.students === 'all'
42
14
  ? k.dataset.students.some((s) => s.id === studentId)
43
15
  : ctx.students.has(studentId);