@quad-education/sdk 0.7.0 → 0.9.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 (58) hide show
  1. package/README.md +5 -2
  2. package/dist/contract-tests/apps.d.ts +617 -0
  3. package/dist/contract-tests/apps.js +215 -1
  4. package/dist/contract-tests/harness.d.ts +1 -1
  5. package/dist/contract-tests/harness.js +7 -0
  6. package/dist/contract-tests/lists-and-files.d.ts +19 -0
  7. package/dist/contract-tests/lists-and-files.js +279 -0
  8. package/dist/contract-tests/live.d.ts +3 -0
  9. package/dist/contract-tests/live.js +156 -0
  10. package/dist/contract-tests/notifications.d.ts +3 -0
  11. package/dist/contract-tests/notifications.js +218 -0
  12. package/dist/contract-tests/search-and-totals.d.ts +13 -0
  13. package/dist/contract-tests/search-and-totals.js +226 -0
  14. package/dist/contract-tests/suite.d.ts +7 -0
  15. package/dist/contract-tests/suite.js +180 -2
  16. package/dist/contract-tests/writes.d.ts +3 -0
  17. package/dist/contract-tests/writes.js +265 -0
  18. package/dist/src/base64.d.ts +3 -0
  19. package/dist/src/base64.js +52 -0
  20. package/dist/src/client/connect.d.ts +1 -0
  21. package/dist/src/client/connect.js +1 -0
  22. package/dist/src/client/create-client.js +39 -5
  23. package/dist/src/client/save-file.d.ts +16 -0
  24. package/dist/src/client/save-file.js +28 -0
  25. package/dist/src/client/watch.d.ts +20 -0
  26. package/dist/src/client/watch.js +175 -0
  27. package/dist/src/contract/errors.d.ts +1 -1
  28. package/dist/src/contract/types.d.ts +220 -10
  29. package/dist/src/contract/types.js +4 -1
  30. package/dist/src/engine/engine.d.ts +91 -2
  31. package/dist/src/engine/engine.js +604 -67
  32. package/dist/src/engine/files.d.ts +25 -0
  33. package/dist/src/engine/files.js +88 -0
  34. package/dist/src/engine/index.d.ts +1 -1
  35. package/dist/src/engine/memory-store.d.ts +33 -3
  36. package/dist/src/engine/memory-store.js +116 -8
  37. package/dist/src/engine/notify-content.d.ts +9 -0
  38. package/dist/src/engine/notify-content.js +88 -0
  39. package/dist/src/engine/query.d.ts +14 -2
  40. package/dist/src/engine/query.js +45 -13
  41. package/dist/src/engine/search.d.ts +8 -0
  42. package/dist/src/engine/search.js +32 -0
  43. package/dist/src/engine/state.d.ts +5 -0
  44. package/dist/src/engine/storage.d.ts +46 -1
  45. package/dist/src/engine/storage.js +46 -3
  46. package/dist/src/engine/store.d.ts +39 -2
  47. package/dist/src/engine/summary.d.ts +25 -0
  48. package/dist/src/engine/summary.js +107 -0
  49. package/dist/src/engine/validate-input.d.ts +7 -1
  50. package/dist/src/engine/validate-input.js +28 -1
  51. package/dist/src/engine/working-copy.d.ts +30 -0
  52. package/dist/src/engine/working-copy.js +91 -0
  53. package/dist/src/platform-types.d.ts +11 -1
  54. package/dist/src/protocol.d.ts +1 -1
  55. package/dist/src/protocol.js +9 -0
  56. package/dist/src/testing/index.d.ts +9 -0
  57. package/dist/src/testing/index.js +16 -1
  58. package/package.json +4 -4
@@ -1,16 +1,21 @@
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';
1
+ import { AUDITED_TIERS, isDerived, isWindowed, BASE_FIELDS, ENTITIES, STAFF_ONLY_TIERS, eligibleParents, fieldVisible, filterFields, grantedTiers, principalTiers, visibleRecords, visibleStudentIds, } from '@quad-education/canonical';
2
+ import { DEFAULT_ACCESS, MAX_BATCH_OPERATIONS, MAX_UNIQUE_TEXT, listedField, parseListed, parseManifest, schemaHash, servedRoles, } from '@quad-education/schema';
3
3
  import { QuadError } from "../contract/errors.js";
4
4
  import { SDK_VERSION } from "../contract/types.js";
5
5
  import { clockNow } from "../protocol.js";
6
6
  import { appendAudit, auditView, listAudit, recordAudit } from "./audit.js";
7
7
  import { checkIndexCoverage } from "./db-indexes.js";
8
- import { runQuery } from "./query.js";
8
+ import { filterRows, runQuery } from "./query.js";
9
9
  import { cronList, finishRun, initCron, redeliverRun, releaseRun, scheduleAt, scheduleCancel, scheduleList, startDueRuns, } from "./runner.js";
10
10
  import { isStaffOrSystem, } from "./state.js";
11
+ import { MAX_APP_FILE_BYTES, UNATTACHED_MS, acceptProblem, checkUpload, fileId, fileInfo, filesNamed, schemaKeepsFiles, } from "./files.js";
12
+ import { toBase64 } from "../base64.js";
13
+ import { MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, checkContent, plainText } from "./notify-content.js";
14
+ import { TOTALS, checkSummarySize, queryOptions, summarise, summaryPlan } from "./summary.js";
11
15
  import { MemoryStore } from "./memory-store.js";
16
+ import { WorkingCopy } from "./working-copy.js";
12
17
  import { assignTask, cancelTask, completeTask, getTask, inbox, listTasks, taskView, } from "./tasks.js";
13
- import { entityOf, fieldOf, validateInput } from "./validate-input.js";
18
+ import { entityOf, fieldOf, heldBy, validateInput, valuesOf } from "./validate-input.js";
14
19
  const SYSTEM_FIELDS = ['id', 'createdAt', 'createdBy', 'updatedAt', 'updatedBy'];
15
20
  const PEOPLE = { staff: 'staff', student: 'students', parent: 'parents' };
16
21
  const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -28,6 +33,7 @@ export class Engine {
28
33
  byId = new Map();
29
34
  /** Each app's admins, as person ids (D133). The platform sets them, as a school does; apps only read them. */
30
35
  admins = new Map();
36
+ roles = new Map();
31
37
  school;
32
38
  store;
33
39
  constructor(dataset, store) {
@@ -66,7 +72,9 @@ export class Engine {
66
72
  }
67
73
  static async create(options) {
68
74
  const store = options.store ??
69
- (options.indexedDB ? await MemoryStore.open(options.indexedDB, options.dbName) : undefined);
75
+ (options.indexedDB
76
+ ? await MemoryStore.open(options.indexedDB, options.dbName, options.channel)
77
+ : undefined);
70
78
  if (!store)
71
79
  throw new Error('an engine needs a store or an IndexedDB factory');
72
80
  return new Engine(options.dataset, store);
@@ -89,6 +97,10 @@ export class Engine {
89
97
  manifest(appId) {
90
98
  return this.appFor(appId).manifest;
91
99
  }
100
+ /** The installed app's own tables (D144): what the Sandbox's School data view lists beside the school's. */
101
+ schema(appId) {
102
+ return this.appFor(appId).schema;
103
+ }
92
104
  /**
93
105
  * Who the school has put in charge of an app (D133): staff person ids, replacing any before. Platform only (the
94
106
  * Sandbox's School data view, a test platform); no SDK method writes it. Ids that aren't staff in the school served at
@@ -98,6 +110,25 @@ export class Engine {
98
110
  this.appFor(appId);
99
111
  this.admins.set(appId, [...new Set(personIds)]);
100
112
  }
113
+ /**
114
+ * The app's own roles each person holds (D143), as a school assigns them: person id to role names, replacing any
115
+ * before. Platform only (the Sandbox's School data view, a test platform); no SDK method writes it. A name the
116
+ * manifest's `roles` doesn't have is ignored, and so is a person who isn't in the school served at the time of a read.
117
+ */
118
+ setAppRoles(appId, assignments) {
119
+ this.appFor(appId);
120
+ this.roles.set(appId, new Map(Object.entries(assignments).map(([id, r]) => [id, [...r]])));
121
+ }
122
+ /**
123
+ * The app roles a person holds, in the manifest's spelling and order: the ones assigned to them, and any named like
124
+ * their school role, which everyone with that school role previews (V2s D84).
125
+ */
126
+ heldAppRoles(app, principal) {
127
+ if (app.manifest.manifestVersion !== 1)
128
+ return [];
129
+ const assigned = (this.roles.get(app.manifest.id)?.get(principal.personId) ?? []).map((r) => r.toLowerCase());
130
+ return app.manifest.roles.filter((r) => r.toLowerCase() === principal.role || assigned.includes(r.toLowerCase()));
131
+ }
101
132
  /** The app's admins who are staff in the school served now, in name order. */
102
133
  appAdminRecords(appId) {
103
134
  return (this.admins.get(appId) ?? [])
@@ -134,7 +165,8 @@ export class Engine {
134
165
  }
135
166
  /** Counts of everything a job can change, for run-twice tests (D20). */
136
167
  async effectsSnapshot(appId) {
137
- const [records, tasks, schedules, audit, outbox] = await Promise.all([
168
+ const [files, records, tasks, schedules, audit, outbox] = await Promise.all([
169
+ this.store.allFiles(appId),
138
170
  this.store.recordStamps(appId),
139
171
  this.store.allPlatform(appId, 'task'),
140
172
  this.store.allPlatform(appId, 'schedule'),
@@ -147,6 +179,7 @@ export class Engine {
147
179
  schedules: Object.fromEntries(schedules.map((s) => [s.id, s.status])),
148
180
  audit: audit.length,
149
181
  records,
182
+ files: files.map((f) => f.id),
150
183
  };
151
184
  }
152
185
  /** Runs for the job log, newest first. */
@@ -234,6 +267,9 @@ export class Engine {
234
267
  async handle(appId, principal, method, params) {
235
268
  const ctx = this.context(appId, principal);
236
269
  const p = (params ?? {});
270
+ // Files follow a record's access rules, and a notification may attach one (D148, D152).
271
+ if (method.startsWith('db.') || method.startsWith('files.') || method === 'notify.send')
272
+ await this.resolveGrants(ctx);
237
273
  switch (method) {
238
274
  case 'auth.me':
239
275
  return this.me(ctx);
@@ -254,15 +290,23 @@ export class Engine {
254
290
  case 'school.parentChildren':
255
291
  return this.parentChildren(ctx, p.parentId);
256
292
  case 'db.create':
257
- return this.dbCreate(ctx, p.entity, p.input, p.options);
293
+ return this.single(ctx, (w) => this.dbCreate(ctx, w, p.entity, p.input, p.options));
258
294
  case 'db.update':
259
- return this.dbUpdate(ctx, p.entity, p.id, p.patch);
295
+ return this.single(ctx, (w) => this.dbUpdate(ctx, w, p.entity, p.id, p.patch, p.options));
296
+ case 'db.batch':
297
+ return this.dbBatch(ctx, p.ops, p.options);
298
+ case 'db.changes':
299
+ return this.dbChanges(ctx, p.entities);
260
300
  case 'db.get':
261
301
  return this.dbGet(ctx, p.entity, p.id);
262
302
  case 'db.list':
263
303
  return this.dbList(ctx, p.entity, p.options);
304
+ case 'db.count':
305
+ return this.dbCount(ctx, p.entity, p.options);
306
+ case 'db.summarise':
307
+ return this.dbSummarise(ctx, p.entity, p.options);
264
308
  case 'db.delete':
265
- return this.dbDelete(ctx, p.entity, p.id);
309
+ return this.single(ctx, (w) => this.dbDelete(ctx, w, p.entity, p.id, p.options));
266
310
  case 'notify.send':
267
311
  return this.notify(ctx, p);
268
312
  case 'tasks.assign':
@@ -287,6 +331,12 @@ export class Engine {
287
331
  return recordAudit(this, ctx, p);
288
332
  case 'audit.list':
289
333
  return listAudit(this, ctx, p);
334
+ case 'files.upload':
335
+ return this.filesUpload(ctx, p);
336
+ case 'files.info':
337
+ return fileInfo(await this.readableFile(ctx, fileId(p)));
338
+ case 'files.read':
339
+ return this.filesRead(ctx, fileId(p));
290
340
  default:
291
341
  throw new QuadError('VALIDATION', `unknown method ${String(method)}`);
292
342
  }
@@ -309,8 +359,10 @@ export class Engine {
309
359
  if (!person || person.entity !== PEOPLE[principal.role]) {
310
360
  throw new QuadError('FORBIDDEN', `no ${principal.role} with id ${principal.personId}`);
311
361
  }
312
- // A school persona stands in for an app role of the same name, ignoring case (V2s D84).
313
- if (!servedRoles(app.manifest).includes(principal.role)) {
362
+ // A school persona stands in for an app role of the same name, ignoring case (V2s D84), and anyone the school
363
+ // gave one of the app's roles is served whatever their school role (D143).
364
+ if (!servedRoles(app.manifest).includes(principal.role) &&
365
+ this.heldAppRoles(app, principal).length === 0) {
314
366
  throw new QuadError('FORBIDDEN', `${app.manifest.name} isn't available to ${principal.role} users`);
315
367
  }
316
368
  return { app, principal, actorId: principal.personId };
@@ -322,7 +374,13 @@ export class Engine {
322
374
  const r = this.byId.get(principal.personId).record;
323
375
  const appAdmin = principal.role === 'staff' &&
324
376
  this.appAdminRecords(ctx.app.manifest.id).some((a) => a.id === r.id);
325
- return { kind: 'user', role: principal.role, appAdmin, person: personSummary(r) };
377
+ return {
378
+ kind: 'user',
379
+ role: principal.role,
380
+ appAdmin,
381
+ appRoles: this.heldAppRoles(ctx.app, principal),
382
+ person: personSummary(r),
383
+ };
326
384
  }
327
385
  appAdmins(ctx) {
328
386
  if (ctx.principal.kind === 'user' && ctx.principal.role !== 'staff') {
@@ -403,7 +461,11 @@ export class Engine {
403
461
  async schoolList(ctx, entityValue, options) {
404
462
  const entity = this.entityName(entityValue);
405
463
  const tiers = this.tiers(ctx, entity);
406
- const page = runQuery(this.visibleFor(ctx, entity, options?.where), (options ?? {}), this.allowedFields(entity, tiers));
464
+ const page = runQuery(this.visibleFor(ctx, entity, options?.where), (options ?? {}), this.allowedFields(entity, tiers), undefined,
465
+ // D153: a search looks in the text the app has been granted, among the records the person may see.
466
+ Object.entries(ENTITIES[entity].fields)
467
+ .filter(([, def]) => (def.type === 'string' || def.type === 'stringList') && fieldVisible(def, tiers))
468
+ .map(([name]) => name));
407
469
  await this.auditSensitiveRead(ctx, entity, tiers, page.items.length, 'school.list');
408
470
  return { items: this.shape(entity, tiers, page.items), nextCursor: page.nextCursor };
409
471
  }
@@ -451,18 +513,62 @@ export class Engine {
451
513
  nowIso() {
452
514
  return new Date(this.nowMs()).toISOString();
453
515
  }
454
- /** The rules for an operation: 'system' (full access), or the role's rules (empty = denied). */
516
+ /**
517
+ * The rules for an operation: 'system' (full access), or every rule of the person's school role and of the app
518
+ * roles they hold (D143); empty means denied.
519
+ */
455
520
  rules(ctx, def, op) {
456
521
  if (ctx.principal.kind === 'system')
457
522
  return 'system';
458
523
  const policy = def.access ?? DEFAULT_ACCESS;
459
- // The key may be written in any case: an app role `Staff` is previewed by the staff persona.
460
- const role = ctx.principal.role;
461
- const key = Object.hasOwn(policy, role)
462
- ? role
463
- : Object.keys(policy).find((k) => k.toLowerCase() === role);
464
- const value = key === undefined ? undefined : policy[key]?.[op];
465
- return value === undefined ? [] : Array.isArray(value) ? value : [value];
524
+ // A key may be written in any case: an app role `Staff` is previewed by the staff persona.
525
+ const names = new Set([
526
+ ctx.principal.role,
527
+ ...this.heldAppRoles(ctx.app, ctx.principal).map((r) => r.toLowerCase()),
528
+ ]);
529
+ const rules = new Set();
530
+ for (const [key, ops] of Object.entries(policy)) {
531
+ if (!names.has(key.toLowerCase()))
532
+ continue;
533
+ const value = ops?.[op];
534
+ for (const rule of value === undefined ? [] : Array.isArray(value) ? value : [value])
535
+ rules.add(rule);
536
+ }
537
+ return [...rules];
538
+ }
539
+ /**
540
+ * Which `appAdmin` and `listed:` rules the principal passes (D142). A listing is a row of the named table whose
541
+ * person field holds this person; the lookup ignores that table's own read rules, so tables may name each other.
542
+ */
543
+ async resolveGrants(ctx) {
544
+ const grants = new Set();
545
+ ctx.grants = grants;
546
+ const { principal, app } = ctx;
547
+ if (principal.kind === 'system')
548
+ return;
549
+ const appId = app.manifest.id;
550
+ if (principal.role === 'staff' &&
551
+ this.appAdminRecords(appId).some((a) => a.id === principal.personId))
552
+ grants.add('appAdmin');
553
+ const rules = new Set();
554
+ for (const def of Object.values(app.schema))
555
+ for (const ops of Object.values(def.access ?? {}))
556
+ for (const value of Object.values(ops ?? {}))
557
+ for (const rule of Array.isArray(value) ? value : [value])
558
+ if (parseListed(rule))
559
+ rules.add(rule);
560
+ for (const rule of rules) {
561
+ const listed = parseListed(rule);
562
+ const found = listedField(app.schema, listed, principal.role);
563
+ if (typeof found === 'string')
564
+ continue;
565
+ const rows = await this.store.candidates(appId, listed.entity, {
566
+ where: { [found.field]: principal.personId },
567
+ indexes: app.schema[listed.entity].indexes,
568
+ });
569
+ if (rows.some((r) => r[found.field] === principal.personId))
570
+ grants.add(rule);
571
+ }
466
572
  }
467
573
  /** Whether the current user may see a student, under the school's visibility policy (D4). */
468
574
  seesStudent(ctx, studentId) {
@@ -477,6 +583,8 @@ export class Engine {
477
583
  if (rules === 'system')
478
584
  return true;
479
585
  return rules.some((rule) => rule === 'all' ||
586
+ // `appAdmin` and `listed:` cover every record for whoever passes them (D142).
587
+ ctx.grants?.has(rule) === true ||
480
588
  (rule === 'own' && record.createdBy === ctx.actorId) ||
481
589
  (rule === 'subject' &&
482
590
  def.subject !== undefined &&
@@ -511,15 +619,17 @@ export class Engine {
511
619
  return rules;
512
620
  }
513
621
  /** A readable record, or NOT_FOUND whether it's missing or just not yours (no existence leak). */
514
- async readable(ctx, entity, id) {
515
- const record = await this.store.getRecord(ctx.app.manifest.id, entity.name, str(id, 'id'));
622
+ async readable(ctx, entity, id, w) {
623
+ const record = w
624
+ ? await w.getRecord(entity.name, str(id, 'id'))
625
+ : await this.store.getRecord(ctx.app.manifest.id, entity.name, str(id, 'id'));
516
626
  if (!record || !this.canRead(ctx, entity.def, record)) {
517
627
  throw new QuadError('NOT_FOUND', `no ${entity.name} record ${String(id)}`);
518
628
  }
519
629
  return record;
520
630
  }
521
631
  /** Writes may only touch fields the role can see, and may only point the subject at a visible student. */
522
- async checkWrite(ctx, entity, values) {
632
+ async checkWrite(ctx, entity, values, w) {
523
633
  for (const key of Object.keys(values)) {
524
634
  if (!this.fieldVisible(ctx, entity.def, key)) {
525
635
  throw new QuadError('NOT_PERMITTED', `${entity.name}.${key} isn't available to you`);
@@ -533,19 +643,27 @@ export class Engine {
533
643
  }
534
644
  for (const [key, value] of Object.entries(values)) {
535
645
  const field = fieldOf(entity.def, key);
536
- if (field?.kind !== 'ref' || typeof value !== 'string' || key === subject)
646
+ if (!field || key === subject)
537
647
  continue;
538
- if (field.to.startsWith('school.')) {
539
- const target = field.to.slice('school.'.length);
540
- if (!this.visible(ctx, target).some((r) => r.id === value)) {
541
- throw new QuadError('VALIDATION', `${key}: no ${target} record ${value} visible to you`);
648
+ const held = heldBy(field);
649
+ if (held.kind !== 'ref')
650
+ continue;
651
+ // Every link is checked, whether the field holds one or a list of them (D147).
652
+ for (const item of valuesOf(field, value)) {
653
+ if (typeof item !== 'string')
654
+ continue;
655
+ if (held.to.startsWith('school.')) {
656
+ const target = held.to.slice('school.'.length);
657
+ if (!this.visible(ctx, target).some((r) => r.id === item)) {
658
+ throw new QuadError('VALIDATION', `${key}: no ${target} record ${item} visible to you`);
659
+ }
542
660
  }
543
- }
544
- else {
545
- const targetDef = entityOf(ctx.app.schema, field.to);
546
- const target = await this.store.getRecord(ctx.app.manifest.id, field.to, value);
547
- if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
548
- throw new QuadError('VALIDATION', `${key}: no ${field.to} record ${value}`);
661
+ else {
662
+ const targetDef = entityOf(ctx.app.schema, held.to);
663
+ const target = await w.getRecord(held.to, item);
664
+ if (!targetDef || !target || !this.canRead(ctx, targetDef, target)) {
665
+ throw new QuadError('VALIDATION', `${key}: no ${held.to} record ${item}`);
666
+ }
549
667
  }
550
668
  }
551
669
  }
@@ -558,13 +676,134 @@ export class Engine {
558
676
  return undefined;
559
677
  return `${scope}:${str(options.idempotencyKey, 'idempotencyKey')}`;
560
678
  }
561
- async dbCreate(ctx, entityValue, input, options) {
679
+ // ---- db writes (D149, D150, ADR 0040) ----
680
+ writeQueues = new Map();
681
+ /**
682
+ * Writes to one app run one after another, so a check and the write that follows it are never interleaved with
683
+ * another call's: of two bookings for the last slot started together, one sees the other.
684
+ */
685
+ queued(appId, write) {
686
+ const run = (this.writeQueues.get(appId) ?? Promise.resolve()).then(write, write);
687
+ this.writeQueues.set(appId, run.catch(() => undefined));
688
+ return run;
689
+ }
690
+ /** One create, update or delete: a working copy of its own, committed when it has passed every check. */
691
+ single(ctx, write) {
692
+ return this.queued(ctx.app.manifest.id, async () => {
693
+ const w = new WorkingCopy(this.store, ctx.app.manifest.id);
694
+ const result = await write(w);
695
+ await w.commit();
696
+ return result;
697
+ });
698
+ }
699
+ /** Up to 25 writes, all stored or none (D150). Each is checked as it is on its own. */
700
+ dbBatch(ctx, opsValue, options) {
701
+ if (!Array.isArray(opsValue) || opsValue.length < 1 || opsValue.length > MAX_BATCH_OPERATIONS)
702
+ throw new QuadError('VALIDATION', `db.batch takes a list of 1 to ${MAX_BATCH_OPERATIONS} operations`);
703
+ const ops = opsValue.map((op, i) => {
704
+ const kinds = isObject(op)
705
+ ? ['create', 'update', 'delete'].filter((k) => k in op)
706
+ : [];
707
+ if (!isObject(op) || kinds.length !== 1)
708
+ throw new QuadError('VALIDATION', `operation ${i + 1}: write it as { create: 'entity', input }, { update: 'entity', id, patch } or { delete: 'entity', id }`, { index: i });
709
+ return { kind: kinds[0], op };
710
+ });
711
+ const key = this.idempotencyKey(options, 'db.batch');
712
+ return this.queued(ctx.app.manifest.id, async () => {
713
+ const appId = ctx.app.manifest.id;
714
+ const remembered = key ? await this.store.getKey(appId, key) : undefined;
715
+ if (Array.isArray(remembered)) {
716
+ // The batch was written before: its records as they stand now, for whoever asks again.
717
+ const again = [];
718
+ for (const item of remembered) {
719
+ const def = item ? entityOf(ctx.app.schema, item.entity) : undefined;
720
+ const record = item && def ? await this.store.getRecord(appId, item.entity, item.id) : null;
721
+ again.push(record && def && this.canRead(ctx, def, record)
722
+ ? this.shapeRecord(ctx, def, record)
723
+ : null);
724
+ }
725
+ return again;
726
+ }
727
+ const w = new WorkingCopy(this.store, appId);
728
+ const results = [];
729
+ const written = [];
730
+ for (const [index, { kind, op }] of ops.entries()) {
731
+ try {
732
+ const result = kind === 'create'
733
+ ? await this.dbCreate(ctx, w, op.create, op.input, op)
734
+ : kind === 'update'
735
+ ? await this.dbUpdate(ctx, w, op.update, op.id, op.patch, op)
736
+ : await this.dbDelete(ctx, w, op.delete, op.id, op);
737
+ results.push(result);
738
+ written.push(result ? { entity: op[kind], id: result.id } : null);
739
+ }
740
+ catch (e) {
741
+ if (!(e instanceof QuadError))
742
+ throw e;
743
+ throw new QuadError(e.code, `operation ${index + 1}: ${e.message}`, {
744
+ ...(isObject(e.details) ? e.details : {}),
745
+ index,
746
+ });
747
+ }
748
+ }
749
+ if (key)
750
+ w.putKey(key, written);
751
+ await w.commit();
752
+ return results;
753
+ });
754
+ }
755
+ /** D149: no other record of the entity holds the same values for any of its unique rules. */
756
+ async checkUnique(w, entity, record) {
757
+ const rules = entity.def.unique ?? [];
758
+ if (rules.length === 0)
759
+ return;
760
+ let others;
761
+ for (const fields of rules) {
762
+ const values = fields.map((f) => record[f]);
763
+ // A record that leaves one of the fields empty is not bound by the rule.
764
+ if (values.some((v) => v === undefined || v === null))
765
+ continue;
766
+ const long = fields.find((f) => {
767
+ const v = record[f];
768
+ return typeof v === 'string' && v.length > MAX_UNIQUE_TEXT;
769
+ });
770
+ if (long !== undefined)
771
+ throw new QuadError('VALIDATION', `${entity.name}.${long}: a value in a unique rule is at most ${MAX_UNIQUE_TEXT} characters`);
772
+ others ??= (await w.all(entity.name)).filter((r) => r.id !== record.id);
773
+ // Every record counts, whoever can read it; the refusal never says which one holds the values.
774
+ if (others.some((r) => fields.every((f) => r[f] === record[f])))
775
+ throw new QuadError('CONFLICT', `another ${entity.name} record already has this ${fields.join(' and ')}`, { entity: entity.name, fields: [...fields] });
776
+ }
777
+ }
778
+ /** D150: the write goes ahead only when the record's fields hold the values given; null means empty. */
779
+ checkIf(ctx, entity, existing, options) {
780
+ const condition = isObject(options) ? options.if : undefined;
781
+ if (condition === undefined)
782
+ return;
783
+ if (!isObject(condition) || Object.keys(condition).length === 0)
784
+ throw new QuadError('VALIDATION', 'if: an object of field values, as { status: "free" }');
785
+ const changed = [];
786
+ for (const [field, value] of Object.entries(condition)) {
787
+ const def = fieldOf(entity.def, field);
788
+ if (!def || def.kind === 'list')
789
+ throw new QuadError('VALIDATION', `if.${field}: not a single-valued field of ${entity.name}`);
790
+ if (!this.fieldVisible(ctx, entity.def, field))
791
+ throw new QuadError('NOT_PERMITTED', `${entity.name}.${field} isn't available to you`);
792
+ if (value !== null && !['string', 'number', 'boolean'].includes(typeof value))
793
+ throw new QuadError('VALIDATION', `if.${field}: a value, or null for empty`);
794
+ if ((existing[field] ?? null) !== value)
795
+ changed.push(field);
796
+ }
797
+ if (changed.length > 0)
798
+ throw new QuadError('CONFLICT', `this ${entity.name} record no longer has the ${changed.join(' and ')} you expected`, { entity: entity.name, id: existing.id, fields: changed });
799
+ }
800
+ async dbCreate(ctx, w, entityValue, input, options) {
562
801
  const entity = this.dbEntity(ctx, entityValue);
563
802
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'create');
564
803
  const key = this.idempotencyKey(options, `db.create:${entity.name}`);
565
- const remembered = key ? await this.store.getKey(ctx.app.manifest.id, key) : undefined;
804
+ const remembered = key ? await w.getKey(key) : undefined;
566
805
  if (typeof remembered === 'string') {
567
- const existing = await this.store.getRecord(ctx.app.manifest.id, entity.name, remembered);
806
+ const existing = await w.getRecord(entity.name, remembered);
568
807
  if (existing && this.canRead(ctx, entity.def, existing))
569
808
  return this.shapeRecord(ctx, entity.def, existing);
570
809
  }
@@ -572,7 +811,8 @@ export class Engine {
572
811
  for (const k of Object.keys(values))
573
812
  if (values[k] === null)
574
813
  delete values[k];
575
- await this.checkWrite(ctx, entity, values);
814
+ await this.checkWrite(ctx, entity, values, w);
815
+ const files = await this.planFiles(ctx, w, entity, values);
576
816
  const now = this.nowIso();
577
817
  const record = {
578
818
  id: `${entity.name}_${crypto.randomUUID()}`,
@@ -585,20 +825,24 @@ export class Engine {
585
825
  if (!this.matches(ctx, entity.def, rules, record)) {
586
826
  throw new QuadError('NOT_PERMITTED', `you may not create this ${entity.name} record`);
587
827
  }
588
- await this.store.putRecord(ctx.app.manifest.id, entity.name, record);
828
+ await this.checkUnique(w, entity, record);
829
+ await w.putRecord(entity.name, record);
830
+ this.applyFiles(w, entity.name, record.id, files);
589
831
  if (key)
590
- await this.remember(ctx, key, record.id);
832
+ w.putKey(key, record.id);
591
833
  return this.shapeRecord(ctx, entity.def, record);
592
834
  }
593
- async dbUpdate(ctx, entityValue, id, patch) {
835
+ async dbUpdate(ctx, w, entityValue, id, patch, options) {
594
836
  const entity = this.dbEntity(ctx, entityValue);
595
- const existing = await this.readable(ctx, entity, id);
837
+ const existing = await this.readable(ctx, entity, id, w);
596
838
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'update');
597
839
  if (!this.matches(ctx, entity.def, rules, existing)) {
598
840
  throw new QuadError('NOT_PERMITTED', `you may not update this ${entity.name} record`);
599
841
  }
842
+ this.checkIf(ctx, entity, existing, options);
600
843
  const values = validateInput(entity.name, entity.def, patch, { partial: true });
601
- await this.checkWrite(ctx, entity, values);
844
+ await this.checkWrite(ctx, entity, values, w);
845
+ const files = await this.planFiles(ctx, w, entity, values, existing);
602
846
  const record = { ...existing };
603
847
  for (const [k, v] of Object.entries(values)) {
604
848
  if (v === null)
@@ -611,7 +855,9 @@ export class Engine {
611
855
  if (!this.matches(ctx, entity.def, rules, record)) {
612
856
  throw new QuadError('NOT_PERMITTED', `this change would take the ${entity.name} record out of your reach`);
613
857
  }
614
- await this.store.putRecord(ctx.app.manifest.id, entity.name, record, existing);
858
+ await this.checkUnique(w, entity, record);
859
+ await w.putRecord(entity.name, record);
860
+ this.applyFiles(w, entity.name, existing.id, files);
615
861
  return this.shapeRecord(ctx, entity.def, record);
616
862
  }
617
863
  async dbGet(ctx, entityValue, id) {
@@ -619,6 +865,90 @@ export class Engine {
619
865
  this.requireOperation(ctx, entity.name, entity.def, 'read');
620
866
  return this.shapeRecord(ctx, entity.def, await this.readable(ctx, entity, id));
621
867
  }
868
+ /**
869
+ * The records of an entity the caller may read, with what a query over them may use: the fields they can see,
870
+ * which of those are lists, and where a search looks (D153). Access comes first: filters, pages, counts and
871
+ * totals only ever cover readable records.
872
+ */
873
+ async dbReadable(ctx, entity, rules, query) {
874
+ const candidates = await this.store.candidates(ctx.app.manifest.id, entity.name, {
875
+ // A rule the caller doesn't pass adds nothing, so only the ones that could match decide the hint.
876
+ ...(rules !== 'system' &&
877
+ rules
878
+ .filter((r) => r === 'own' || r === 'all' || r === 'subject' || ctx.grants?.has(r))
879
+ .every((r) => r === 'own')
880
+ ? { ownedBy: ctx.actorId }
881
+ : {}),
882
+ where: query.where,
883
+ orderBy: query.orderBy,
884
+ indexes: entity.def.indexes,
885
+ });
886
+ const readable = candidates.filter((r) => this.canRead(ctx, entity.def, r));
887
+ const fields = new Set([
888
+ ...SYSTEM_FIELDS,
889
+ ...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
890
+ ]);
891
+ const lists = new Set(Object.entries(entity.def.fields)
892
+ .filter(([, f]) => f.kind === 'list')
893
+ .map(([name]) => name));
894
+ // D153: a search never looks in a field hidden from the reader, so a match tells them nothing about it.
895
+ const searchFields = entity.def.search
896
+ ? entity.def.search.filter((f) => fields.has(f))
897
+ : {
898
+ refusal: `${entity.name} can't be searched: add search: ['field', …] to it in schema/, naming its text fields`,
899
+ };
900
+ // D37: sorts and range filters need a declared index, as on the platform's data API.
901
+ checkIndexCoverage(entity.name, entity.def.indexes, query, fields);
902
+ return { readable, fields, lists, searchFields };
903
+ }
904
+ /**
905
+ * D157: a stamp for each entity, different after any write to it, for a caller who may read the entity. It
906
+ * reads no records. An entity's stamp also moves with every table its rules look people up in (`listed:`),
907
+ * because a change there changes who may read what.
908
+ */
909
+ async dbChanges(ctx, value) {
910
+ const count = Object.keys(ctx.app.schema).length;
911
+ if (!Array.isArray(value) || value.length < 1 || value.length > count)
912
+ throw new QuadError('VALIDATION', "db.watch takes a list of one or more of the app's entities");
913
+ const names = new Map();
914
+ for (const item of value) {
915
+ const entity = this.dbEntity(ctx, item);
916
+ this.requireOperation(ctx, entity.name, entity.def, 'read');
917
+ const related = new Set([entity.name]);
918
+ for (const ops of Object.values(entity.def.access ?? {}))
919
+ for (const rules of Object.values(ops ?? {}))
920
+ for (const rule of Array.isArray(rules) ? rules : [rules]) {
921
+ const listed = parseListed(rule);
922
+ if (listed && ctx.app.schema[listed.entity])
923
+ related.add(listed.entity);
924
+ }
925
+ names.set(entity.name, [...related]);
926
+ }
927
+ const stamps = await this.store.versions(ctx.app.manifest.id, [
928
+ ...new Set([...names.values()].flat()),
929
+ ]);
930
+ return Object.fromEntries([...names].map(([name, related]) => [name, related.map((r) => stamps[r]).join('.')]));
931
+ }
932
+ /** D154: how many records match, of those the caller may read. */
933
+ async dbCount(ctx, entityValue, options) {
934
+ const entity = this.dbEntity(ctx, entityValue);
935
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
936
+ const query = queryOptions(options, ['where', 'search'], 'count');
937
+ const { readable, fields, lists, searchFields } = await this.dbReadable(ctx, entity, rules, query);
938
+ const count = filterRows(readable, query, fields, lists, searchFields).length;
939
+ checkSummarySize(entity.name, count);
940
+ return count;
941
+ }
942
+ /** D154: the count, and totals of number fields, of the records the caller may read; by group when asked. */
943
+ async dbSummarise(ctx, entityValue, options) {
944
+ const entity = this.dbEntity(ctx, entityValue);
945
+ const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
946
+ const query = queryOptions(options, ['where', 'search', 'groupBy', ...TOTALS], 'summarise');
947
+ const { readable, fields, lists, searchFields } = await this.dbReadable(ctx, entity, rules, query);
948
+ const plan = summaryPlan(entity.name, entity.def, query, fields);
949
+ const rows = filterRows(readable, query, fields, lists, searchFields);
950
+ return summarise(entity.name, rows, plan);
951
+ }
622
952
  async dbList(ctx, entityValue, options) {
623
953
  const entity = this.dbEntity(ctx, entityValue);
624
954
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'read');
@@ -627,27 +957,16 @@ export class Engine {
627
957
  if (!includes)
628
958
  throw new QuadError('VALIDATION', 'include must be an array of ref field names');
629
959
  for (const f of includes) {
960
+ const field = typeof f === 'string' ? fieldOf(entity.def, f) : undefined;
630
961
  if (typeof f !== 'string' ||
631
- fieldOf(entity.def, f)?.kind !== 'ref' ||
962
+ !field ||
963
+ heldBy(field).kind !== 'ref' ||
632
964
  !this.fieldVisible(ctx, entity.def, f)) {
633
965
  throw new QuadError('VALIDATION', `include: '${String(f)}' is not a ref field of ${entity.name}`);
634
966
  }
635
967
  }
636
- // Access first, then filters and pages: results and cursors only ever cover readable records.
637
- const candidates = await this.store.candidates(ctx.app.manifest.id, entity.name, {
638
- ...(rules !== 'system' && rules.every((r) => r === 'own') ? { ownedBy: ctx.actorId } : {}),
639
- where: query.where,
640
- orderBy: query.orderBy,
641
- indexes: entity.def.indexes,
642
- });
643
- const readable = candidates.filter((r) => this.canRead(ctx, entity.def, r));
644
- const fields = new Set([
645
- ...SYSTEM_FIELDS,
646
- ...Object.keys(entity.def.fields).filter((f) => this.fieldVisible(ctx, entity.def, f)),
647
- ]);
648
- // D37: sorts and range filters need a declared index, as on the platform's data API.
649
- checkIndexCoverage(entity.name, entity.def.indexes, query, fields);
650
- const page = runQuery(readable, query, fields);
968
+ const { readable, fields, lists, searchFields } = await this.dbReadable(ctx, entity, rules, query);
969
+ const page = runQuery(readable, query, fields, lists, searchFields);
651
970
  const items = page.items.map((r) => this.shapeRecord(ctx, entity.def, r));
652
971
  if (includes.length === 0)
653
972
  return { items, nextCursor: page.nextCursor };
@@ -655,8 +974,19 @@ export class Engine {
655
974
  const withIncluded = [];
656
975
  for (const r of items) {
657
976
  const included = {};
658
- for (const f of includes)
659
- included[f] = await this.resolveRef(ctx, entity.def.fields[f], r[f], schoolReads);
977
+ for (const f of includes) {
978
+ const field = entity.def.fields[f];
979
+ const held = heldBy(field);
980
+ if (field.kind !== 'list')
981
+ included[f] = await this.resolveRef(ctx, held, r[f], schoolReads);
982
+ else {
983
+ // D147: the linked records in the list's order, null where one is missing or out of reach.
984
+ const found = [];
985
+ for (const item of valuesOf(field, r[f]))
986
+ found.push(await this.resolveRef(ctx, held, item, schoolReads));
987
+ included[f] = found;
988
+ }
989
+ }
660
990
  withIncluded.push({ ...r, $included: included });
661
991
  }
662
992
  for (const [target, count] of schoolReads) {
@@ -685,16 +1015,129 @@ export class Engine {
685
1015
  ? this.shapeRecord(ctx, def, record)
686
1016
  : null;
687
1017
  }
688
- async dbDelete(ctx, entityValue, id) {
1018
+ async dbDelete(ctx, w, entityValue, id, options) {
689
1019
  const entity = this.dbEntity(ctx, entityValue);
690
- const existing = await this.readable(ctx, entity, id);
1020
+ const existing = await this.readable(ctx, entity, id, w);
691
1021
  const rules = this.requireOperation(ctx, entity.name, entity.def, 'delete');
692
1022
  if (!this.matches(ctx, entity.def, rules, existing)) {
693
1023
  throw new QuadError('NOT_PERMITTED', `you may not delete this ${entity.name} record`);
694
1024
  }
695
- await this.store.deleteRecord(ctx.app.manifest.id, entity.name, existing);
1025
+ this.checkIf(ctx, entity, existing, options);
1026
+ await w.deleteRecord(entity.name, existing);
1027
+ // D148: a record's files go with it.
1028
+ for (const ids of filesNamed(entity.def, existing).values())
1029
+ for (const id of ids)
1030
+ w.deleteFile(id);
696
1031
  return null;
697
1032
  }
1033
+ // ---- files (D148, ADR 0039) ----
1034
+ /** A file nobody attached within a day of its upload is gone, by the engine's clock. */
1035
+ fileExpired(file) {
1036
+ return (!file.attachedTo &&
1037
+ file.sentWith === undefined &&
1038
+ this.nowMs() - Date.parse(file.createdAt) >= UNATTACHED_MS);
1039
+ }
1040
+ async filesUpload(ctx, params) {
1041
+ if (!schemaKeepsFiles(ctx.app.schema))
1042
+ throw new QuadError('VALIDATION', "this app's schema has no file field, so there is nowhere to attach a file: add file() to an entity in schema/");
1043
+ const { name, type, bytes } = checkUpload(params);
1044
+ const appId = ctx.app.manifest.id;
1045
+ let total = bytes.length;
1046
+ for (const kept of await this.store.allFiles(appId)) {
1047
+ if (this.fileExpired(kept))
1048
+ await this.store.deleteFile(appId, kept.id);
1049
+ else
1050
+ total += kept.size;
1051
+ }
1052
+ if (total > MAX_APP_FILE_BYTES)
1053
+ throw new QuadError('VALIDATION', `this app's files would total more than ${MAX_APP_FILE_BYTES / (1024 * 1024)} MB`);
1054
+ const file = {
1055
+ id: `file_${crypto.randomUUID()}`,
1056
+ name,
1057
+ type,
1058
+ size: bytes.length,
1059
+ createdAt: this.nowIso(),
1060
+ createdBy: ctx.actorId,
1061
+ };
1062
+ await this.store.putFile(appId, file, bytes);
1063
+ return fileInfo(file);
1064
+ }
1065
+ /**
1066
+ * A file the caller may read, or NOT_FOUND whether it is missing or just not theirs. Unattached, it is its
1067
+ * uploader's alone; attached, it follows the field of the record that holds it.
1068
+ */
1069
+ async readableFile(ctx, id) {
1070
+ const appId = ctx.app.manifest.id;
1071
+ const file = await this.store.getFile(appId, id);
1072
+ const missing = new QuadError('NOT_FOUND', `no file ${id}`);
1073
+ // A copy a notification carries is the message's, not a file an app reads (D152).
1074
+ if (!file || this.fileExpired(file) || file.sentWith !== undefined)
1075
+ throw missing;
1076
+ if (!file.attachedTo) {
1077
+ if (file.createdBy !== ctx.actorId)
1078
+ throw missing;
1079
+ return file;
1080
+ }
1081
+ const { entity, recordId, field } = file.attachedTo;
1082
+ const def = entityOf(ctx.app.schema, entity);
1083
+ const record = await this.store.getRecord(appId, entity, recordId);
1084
+ if (!def ||
1085
+ !record ||
1086
+ !this.canRead(ctx, def, record) ||
1087
+ !this.fieldVisible(ctx, def, field) ||
1088
+ !filesNamed(def, record).get(field)?.includes(id))
1089
+ throw missing;
1090
+ return file;
1091
+ }
1092
+ async filesRead(ctx, id) {
1093
+ const file = await this.readableFile(ctx, id);
1094
+ const bytes = await this.store.fileBytes(ctx.app.manifest.id, id);
1095
+ if (!bytes)
1096
+ throw new QuadError('NOT_FOUND', `no file ${id}`);
1097
+ return { info: fileInfo(file), data: toBase64(bytes) };
1098
+ }
1099
+ /**
1100
+ * What a write does to files: which to attach and which to remove. A file is attached once, by whoever uploaded
1101
+ * it, to one field of one record; an id the record's field already holds stays as it is.
1102
+ */
1103
+ async planFiles(ctx, w, entity, values, existing) {
1104
+ const next = filesNamed(entity.def, values);
1105
+ const before = existing ? filesNamed(entity.def, existing) : new Map();
1106
+ const named = new Set();
1107
+ for (const [field, ids] of before)
1108
+ if (!next.has(field))
1109
+ for (const id of ids)
1110
+ named.add(id);
1111
+ const attach = [];
1112
+ const remove = [];
1113
+ for (const [field, ids] of next) {
1114
+ const had = before.get(field) ?? [];
1115
+ for (const id of ids) {
1116
+ if (named.has(id))
1117
+ throw new QuadError('VALIDATION', `${field}: file ${id} is named more than once`);
1118
+ named.add(id);
1119
+ if (had.includes(id))
1120
+ continue;
1121
+ const file = await w.getFile(id);
1122
+ if (!file || this.fileExpired(file) || file.attachedTo || file.createdBy !== ctx.actorId)
1123
+ throw new QuadError('VALIDATION', `${field}: no file ${id} of yours to attach. Upload it with sdk.files.upload first; a file is attached once, by whoever uploaded it`);
1124
+ const problem = acceptProblem(heldBy(fieldOf(entity.def, field)), file);
1125
+ if (problem)
1126
+ throw new QuadError('VALIDATION', `${field}: ${problem}`);
1127
+ attach.push({ file, field });
1128
+ }
1129
+ for (const id of had)
1130
+ if (!ids.includes(id))
1131
+ remove.push(id);
1132
+ }
1133
+ return { attach, remove };
1134
+ }
1135
+ applyFiles(w, entity, recordId, files) {
1136
+ for (const { file, field } of files.attach)
1137
+ w.putFile({ ...file, attachedTo: { entity, recordId, field } });
1138
+ for (const id of files.remove)
1139
+ w.deleteFile(id);
1140
+ }
698
1141
  // ---- notify (D10, D17) ----
699
1142
  async notify(ctx, input) {
700
1143
  const { manifest } = ctx.app;
@@ -707,7 +1150,10 @@ export class Engine {
707
1150
  if (remembered !== undefined)
708
1151
  return remembered;
709
1152
  const subject = str(input.subject, 'subject');
710
- const body = str(input.body, 'body');
1153
+ // D151: a message in blocks, plain text, or both; with blocks alone the plain text is made from them.
1154
+ const content = input.content === undefined ? undefined : checkContent(input.content);
1155
+ const body = content && input.body === undefined ? plainText(content) : str(input.body, 'body');
1156
+ const attached = await this.attachmentsFor(ctx, input.attachments);
711
1157
  const channel = input.channel ?? 'inApp';
712
1158
  if (channel !== 'inApp' && channel !== 'email')
713
1159
  throw new QuadError('VALIDATION', "channel must be 'inApp' or 'email'");
@@ -724,7 +1170,9 @@ export class Engine {
724
1170
  throw new QuadError('VALIDATION', `no student ${regarding}`);
725
1171
  }
726
1172
  const { recipients, suppressed } = await this.resolveRecipients(ctx, input.to, regarding);
1173
+ this.checkAttachmentRoles(ctx, attached, recipients);
727
1174
  const sentAt = this.nowIso();
1175
+ const copies = recipients.length > 0 ? await this.copyAttachments(ctx, attached, sentAt) : [];
728
1176
  const entries = recipients.map((r) => ({
729
1177
  id: `out_${crypto.randomUUID()}`,
730
1178
  appId: manifest.id,
@@ -734,6 +1182,8 @@ export class Engine {
734
1182
  recipientRole: r.role,
735
1183
  subject,
736
1184
  body,
1185
+ ...(content ? { content } : {}),
1186
+ ...(copies.length > 0 ? { attachments: copies } : {}),
737
1187
  ...(typeof input.link === 'string' ? { link: input.link } : {}),
738
1188
  ...(r.regarding ? { regardingStudentId: r.regarding } : {}),
739
1189
  sentAt,
@@ -750,12 +1200,99 @@ export class Engine {
750
1200
  visibility: 'app',
751
1201
  data: { type, channel: channel, recipients: entries.map((e) => e.recipientId) },
752
1202
  });
1203
+ if (copies.length > 0)
1204
+ // For the school, not the app: which files left their records, and for whom (D152).
1205
+ await appendAudit(this, ctx.app, {
1206
+ source: 'platform',
1207
+ action: 'notification.attachments',
1208
+ actor: ctx.actorId,
1209
+ summary: `${copies.length} file${copies.length === 1 ? '' : 's'} sent with ${type} to ${entries.length} recipient${entries.length === 1 ? '' : 's'}`,
1210
+ entity: 'notification',
1211
+ visibility: 'cio',
1212
+ data: {
1213
+ type,
1214
+ recipients: entries.map((e) => e.recipientId),
1215
+ files: attached.map((f) => ({ name: f.name, ...(f.attachedTo ?? {}) })),
1216
+ },
1217
+ });
753
1218
  await this.auditSuppressed(ctx, 'notification.suppressed', type, suppressed);
754
1219
  const result = { recipients: recipients.map(({ personId, role }) => ({ personId, role })) };
755
1220
  if (key)
756
1221
  await this.remember(ctx, key, result);
757
1222
  return result;
758
1223
  }
1224
+ /** D152: the files a notification names, each one the sender can read, within the limits. */
1225
+ async attachmentsFor(ctx, value) {
1226
+ if (value === undefined)
1227
+ return [];
1228
+ if (!Array.isArray(value) ||
1229
+ value.length === 0 ||
1230
+ value.length > MAX_ATTACHMENTS ||
1231
+ !value.every((id) => typeof id === 'string' && id.length > 0) ||
1232
+ new Set(value).size !== value.length)
1233
+ throw new QuadError('VALIDATION', `attachments: 1 to ${MAX_ATTACHMENTS} different file ids`);
1234
+ const files = [];
1235
+ for (const id of value)
1236
+ files.push(await this.readableFile(ctx, id));
1237
+ if (files.reduce((n, f) => n + f.size, 0) > MAX_ATTACHMENT_BYTES)
1238
+ throw new QuadError('VALIDATION', `attachments can total at most ${MAX_ATTACHMENT_BYTES / (1024 * 1024)} MB`);
1239
+ return files;
1240
+ }
1241
+ /**
1242
+ * D152: a file never goes to a role its field is hidden from (`visibleTo`), and one at a staff-only level goes
1243
+ * only to staff. The app declared both; a notification does not get round them.
1244
+ */
1245
+ checkAttachmentRoles(ctx, files, recipients) {
1246
+ for (const file of files) {
1247
+ if (!file.attachedTo)
1248
+ continue;
1249
+ const { entity, field } = file.attachedTo;
1250
+ const def = entityOf(ctx.app.schema, entity);
1251
+ const fieldDef = def ? fieldOf(def, field) : undefined;
1252
+ if (!fieldDef)
1253
+ continue;
1254
+ const allowed = STAFF_ONLY_TIERS.includes(fieldDef.tier)
1255
+ ? ['staff']
1256
+ : fieldDef.visibleTo?.map((r) => r.toLowerCase());
1257
+ const refused = allowed ? recipients.find((r) => !allowed.includes(r.role)) : undefined;
1258
+ if (refused)
1259
+ throw new QuadError('NOT_PERMITTED', `'${file.name}' comes from ${entity}.${field}, which only ${allowed.join(' and ')} may see, so it can't be sent to a ${refused.role}`);
1260
+ }
1261
+ }
1262
+ /** D152: the copies a message carries, made as it is sent, so they outlast the records they came from. */
1263
+ async copyAttachments(ctx, files, sentAt) {
1264
+ if (files.length === 0)
1265
+ return [];
1266
+ const appId = ctx.app.manifest.id;
1267
+ const kept = (await this.store.allFiles(appId)).reduce((n, f) => n + f.size, 0);
1268
+ if (kept + files.reduce((n, f) => n + f.size, 0) > MAX_APP_FILE_BYTES)
1269
+ throw new QuadError('VALIDATION', `this app's files would total more than ${MAX_APP_FILE_BYTES / (1024 * 1024)} MB`);
1270
+ const sentWith = `send_${crypto.randomUUID()}`;
1271
+ const copies = [];
1272
+ for (const file of files) {
1273
+ const bytes = await this.store.fileBytes(appId, file.id);
1274
+ if (!bytes)
1275
+ throw new QuadError('NOT_FOUND', `no file ${file.id}`);
1276
+ const copy = {
1277
+ id: `sent_${crypto.randomUUID()}`,
1278
+ name: file.name,
1279
+ type: file.type,
1280
+ size: file.size,
1281
+ createdAt: sentAt,
1282
+ createdBy: ctx.actorId,
1283
+ sentWith,
1284
+ };
1285
+ await this.store.putFile(appId, copy, bytes);
1286
+ copies.push({ id: copy.id, name: copy.name, type: copy.type, size: copy.size });
1287
+ }
1288
+ return copies;
1289
+ }
1290
+ /** A file a sent notification carries, for the shell's outbox and tests. Never part of the SDK. */
1291
+ async sentFile(appId, id) {
1292
+ const file = await this.store.getFile(appId, id);
1293
+ const bytes = file?.sentWith === undefined ? undefined : await this.store.fileBytes(appId, id);
1294
+ return file && bytes ? { info: fileInfo(file), bytes } : undefined;
1295
+ }
759
1296
  roleOf(personId) {
760
1297
  const entity = this.byId.get(personId)?.entity;
761
1298
  return entity === 'staff'