@haverstack/core 0.29.0 → 0.30.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 (73) hide show
  1. package/dist/adapter-entry.d.ts +1 -1
  2. package/dist/adapter-entry.d.ts.map +1 -1
  3. package/dist/adapter-entry.js +1 -1
  4. package/dist/adapter-entry.js.map +1 -1
  5. package/dist/changes.d.ts +14 -0
  6. package/dist/changes.d.ts.map +1 -1
  7. package/dist/changes.js +35 -0
  8. package/dist/changes.js.map +1 -1
  9. package/dist/errors.d.ts +173 -0
  10. package/dist/errors.d.ts.map +1 -0
  11. package/dist/errors.js +208 -0
  12. package/dist/errors.js.map +1 -0
  13. package/dist/grants.d.ts +84 -0
  14. package/dist/grants.d.ts.map +1 -0
  15. package/dist/grants.js +157 -0
  16. package/dist/grants.js.map +1 -0
  17. package/dist/id.d.ts +7 -5
  18. package/dist/id.d.ts.map +1 -1
  19. package/dist/id.js +17 -15
  20. package/dist/id.js.map +1 -1
  21. package/dist/identity-bindings.d.ts +13 -0
  22. package/dist/identity-bindings.d.ts.map +1 -0
  23. package/dist/identity-bindings.js +42 -0
  24. package/dist/identity-bindings.js.map +1 -0
  25. package/dist/index.d.ts +6 -3
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +5 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/limits.d.ts +23 -0
  30. package/dist/limits.d.ts.map +1 -0
  31. package/dist/limits.js +35 -0
  32. package/dist/limits.js.map +1 -0
  33. package/dist/query-validation.d.ts +80 -0
  34. package/dist/query-validation.d.ts.map +1 -0
  35. package/dist/query-validation.js +223 -0
  36. package/dist/query-validation.js.map +1 -0
  37. package/dist/record-changes.d.ts +89 -0
  38. package/dist/record-changes.d.ts.map +1 -0
  39. package/dist/record-changes.js +201 -0
  40. package/dist/record-changes.js.map +1 -0
  41. package/dist/record-id.d.ts +70 -0
  42. package/dist/record-id.d.ts.map +1 -0
  43. package/dist/record-id.js +127 -0
  44. package/dist/record-id.js.map +1 -0
  45. package/dist/scoped-stack.d.ts +460 -0
  46. package/dist/scoped-stack.d.ts.map +1 -0
  47. package/dist/scoped-stack.js +1163 -0
  48. package/dist/scoped-stack.js.map +1 -0
  49. package/dist/stack-reads.d.ts +38 -0
  50. package/dist/stack-reads.d.ts.map +1 -0
  51. package/dist/stack-reads.js +79 -0
  52. package/dist/stack-reads.js.map +1 -0
  53. package/dist/stack.d.ts +37 -643
  54. package/dist/stack.d.ts.map +1 -1
  55. package/dist/stack.js +102 -2254
  56. package/dist/stack.js.map +1 -1
  57. package/dist/testing.d.ts.map +1 -1
  58. package/dist/testing.js +3 -1
  59. package/dist/testing.js.map +1 -1
  60. package/dist/types.d.ts +9 -2
  61. package/dist/types.d.ts.map +1 -1
  62. package/dist/types.js +8 -0
  63. package/dist/types.js.map +1 -1
  64. package/dist/wire-entry.d.ts +2 -2
  65. package/dist/wire-entry.d.ts.map +1 -1
  66. package/dist/wire-entry.js +2 -2
  67. package/dist/wire-entry.js.map +1 -1
  68. package/dist/wire-record.js +1 -1
  69. package/dist/wire-record.js.map +1 -1
  70. package/dist/wire-request.d.ts.map +1 -1
  71. package/dist/wire-request.js +3 -2
  72. package/dist/wire-request.js.map +1 -1
  73. package/package.json +1 -1
@@ -0,0 +1,1163 @@
1
+ /**
2
+ * ScopedStack — the permission-enforcing view
3
+ * -------------------------------------------------------
4
+ * A `Stack` answers every question; a `ScopedStack` answers only the ones a
5
+ * particular requester is entitled to. It wraps a Stack rather than an
6
+ * adapter, so every invariant the Stack layer holds is already in force by
7
+ * the time a check here runs, and the gates below only ever narrow.
8
+ *
9
+ * Two identities, one rule: **the principal governs authority, the subject
10
+ * governs attribution.** Both are DIDs and both are often equal, which is
11
+ * what makes them easy to confuse — so the split is stated on every gate
12
+ * that depends on it.
13
+ *
14
+ * Also holds the feed side of the same rule: a subscription's deliveries
15
+ * run through the same canRead() a get() answers with, so a feed can never
16
+ * disagree with a read about what a session sees.
17
+ *
18
+ * See docs/spec/access-control.md and docs/spec/events.md § Permission scoping.
19
+ */
20
+ import { baseIdOf } from './schema.js';
21
+ import { validatePatchValues } from './validate.js';
22
+ import { checkAccess, groupRoleFromAssociations, isOwnerActingAlone } from './access.js';
23
+ import { ChangeEmitter, Subscription, matchesFilter, passesUnlistedBoundary, assertSinceUsable, } from './changes.js';
24
+ import { SYSTEM_TYPES } from './types.js';
25
+ import { StackConflictError, StackError, StackNotFoundError, StackPermissionError, StackRelayScopeError, StackValidationError, } from './errors.js';
26
+ import { assertSortCapability, assertValidRelatedTo, assertValidSort, filtersContent, } from './query-validation.js';
27
+ import { grantConveys, grantCoversGrantee, loadGrantRecords, UNGRANTABLE_SYSTEM_TYPES, } from './grants.js';
28
+ import { bindingFieldsOf } from './identity-bindings.js';
29
+ import { assertAttachmentSize } from './limits.js';
30
+ import { validateIdTimestampSkew, validateRecordId } from './record-id.js';
31
+ import { DEFAULT_QUERY_LIMIT, MAX_QUERY_LIMIT, findFirstMatch, lookupEntityByDid, queryAllPages, } from './stack-reads.js';
32
+ import { associationEqual, isGroupRecord, presentDeleted, stripVersionPermissions, assertNonEmptyChangeSet, } from './record-changes.js';
33
+ /**
34
+ * The authority lookups canRead needs, held for the life of one
35
+ * subscription. A subscription is long-lived where a query is not, so the
36
+ * cache is only safe because every write that can change canRead's answer
37
+ * arrives as an event that drops it — see ScopedSubscription.
38
+ */
39
+ class FeedAuthorityCache {
40
+ grantRecords = null;
41
+ /**
42
+ * Bumped by every invalidation, so a load that was already in flight can
43
+ * tell that its result is stale before seating it.
44
+ */
45
+ generation = 0;
46
+ /** Roster roles, memoized per group, as ScopedStack.query() does per query. */
47
+ roles = new Map();
48
+ /** Every `_grant` record, refilled through `load` after an invalidation. */
49
+ async grants(load) {
50
+ if (this.grantRecords !== null)
51
+ return this.grantRecords;
52
+ const generation = this.generation;
53
+ const loaded = await load();
54
+ // An invalidation during the load already dropped the set these
55
+ // replace, so seating them would outlive the write that expired them
56
+ // and no later event would drop them again. The event being decided
57
+ // precedes that write, so it is still decided on what was loaded.
58
+ if (this.generation === generation)
59
+ this.grantRecords = loaded;
60
+ return loaded;
61
+ }
62
+ invalidateFor(typeFamily) {
63
+ if (typeFamily === SYSTEM_TYPES.GRANT) {
64
+ this.grantRecords = null;
65
+ this.generation++;
66
+ }
67
+ if (typeFamily === SYSTEM_TYPES.GROUP)
68
+ this.roles = new Map();
69
+ }
70
+ }
71
+ /**
72
+ * A ScopedStack's delivery: canRead per event, with the grant and roster
73
+ * lookups it needs cached for the life of the subscription and dropped the
74
+ * moment anything that feeds them changes.
75
+ *
76
+ * Two properties do the work, and neither is optional:
77
+ *
78
+ * **Deliveries are serialized.** The permission decision is asynchronous,
79
+ * so without a queue two changes to one record could resolve out of order
80
+ * and be delivered newest-first — breaking the one ordering guarantee the
81
+ * feed makes. Every emission is appended to a chain instead.
82
+ *
83
+ * **The filter fails closed.** A permission check that throws drops the
84
+ * event and reports the error; it never delivers on the assumption that a
85
+ * failed check would have passed.
86
+ *
87
+ * See docs/spec/events.md § Permission scoping.
88
+ */
89
+ class ScopedSubscription extends Subscription {
90
+ canRead;
91
+ cache = new FeedAuthorityCache();
92
+ /** Tail of the delivery chain — see the class comment. */
93
+ queue = Promise.resolve();
94
+ constructor(canRead, handler, opts) {
95
+ super(handler, opts);
96
+ this.canRead = canRead;
97
+ }
98
+ accept(emission) {
99
+ // Invalidation reads every emission, including the ones this
100
+ // subscriber may not see: a revocation the subscriber cannot read is
101
+ // exactly the one that must still expire its cache.
102
+ this.invalidateFor(emission);
103
+ if (!matchesFilter(emission, this.opts.filter))
104
+ return;
105
+ this.queue = this.queue.then(() => this.filterAndDeliver(emission));
106
+ }
107
+ /**
108
+ * A cached grant set outlives the write that revokes it unless something
109
+ * drops it. Both writes that can change canRead's answer — a `_grant`
110
+ * record, or a `_group` roster — arrive here as ordinary events, which
111
+ * is what makes the cache safe to hold at all. A future authority change
112
+ * that did not emit would silently strand it.
113
+ */
114
+ invalidateFor(emission) {
115
+ this.cache.invalidateFor(baseIdOf(emission.change.typeId));
116
+ }
117
+ async filterAndDeliver(emission) {
118
+ if (this.isClosed)
119
+ return;
120
+ if (!passesUnlistedBoundary(emission, this.opts.includeUnlisted))
121
+ return;
122
+ try {
123
+ if (!(await this.canRead(emission.record, this.cache)))
124
+ return;
125
+ }
126
+ catch (err) {
127
+ // Fail closed: an undecided permission question is not a yes.
128
+ this.reportError(err);
129
+ return;
130
+ }
131
+ // After the permission decision, which needs the whole record: a frame
132
+ // carrying a deleted record's body would be a read channel around the
133
+ // tombstone. See docs/spec/events.md § Soft-deleted records reach the
134
+ // feed as tombstones.
135
+ this.deliver(this.project(emission));
136
+ }
137
+ project(emission) {
138
+ const record = presentDeleted(emission.record);
139
+ return record === emission.record ? emission : { ...emission, record };
140
+ }
141
+ }
142
+ /**
143
+ * A permission-enforcing view of a Stack for a single (principal, subject)
144
+ * pair, obtained via `stack.asEntity(entityId)`. A record the request
145
+ * cannot read answers exactly as a missing one does — null on reads,
146
+ * StackNotFoundError on the verbs that name one — so only a requester who
147
+ * could have read it is told a refusal was about access.
148
+ * See docs/spec/access-control.md § Errors and information exposure.
149
+ *
150
+ * Two identities, one rule: **the principal governs authority, the subject
151
+ * governs attribution.** Grant lookup and the privilege-bearing gates that
152
+ * no grant reaches (resharing, group management, hard delete, widening
153
+ * access at create time) key on `principalEntityId`; authorship, `-own`
154
+ * matching, record-level permission resolution, and "files I uploaded"
155
+ * lookups key on `subjectEntityId`.
156
+ *
157
+ * Unconditional owner access follows that same split rather than one
158
+ * identity: it answers *what data is reachable* for the subject (an owner
159
+ * subject resolves past every permission check) and *who may exercise a
160
+ * privileged verb* for the principal (an owner app is not bounded by
161
+ * grants). Under delegation both halves apply, and a mistake on the
162
+ * authority side is an escalation rather than a preference.
163
+ */
164
+ export class ScopedStack {
165
+ stack;
166
+ principalEntityId;
167
+ subjectEntityId;
168
+ idTimestampSkewMs;
169
+ adapter;
170
+ changes;
171
+ constructor(stack, principalEntityId, subjectEntityId, idTimestampSkewMs,
172
+ // Bytes-storage primitive for putAttachment(). Held directly because
173
+ // ScopedStack always composes bytes + its own create() — the record
174
+ // must carry the subject's entityId and the principal behind it,
175
+ // neither of which the adapter-level atomic capability takes.
176
+ adapter,
177
+ // The stack's own stream, filtered by subscribe(). Held here rather
178
+ // than reached through a method on Stack so the unfiltered stream
179
+ // stays inside this module.
180
+ changes) {
181
+ this.stack = stack;
182
+ this.principalEntityId = principalEntityId;
183
+ this.subjectEntityId = subjectEntityId;
184
+ this.idTimestampSkewMs = idTimestampSkewMs;
185
+ this.adapter = adapter;
186
+ this.changes = changes;
187
+ }
188
+ get features() {
189
+ return this.stack.features;
190
+ }
191
+ resolveRecord = (id) => this.stack.get(id);
192
+ /** Every `_grant` Record — see loadGrantRecords(). */
193
+ loadGrants = () => loadGrantRecords((q) => this.stack.query(q));
194
+ /** Whether a delegated app is acting for someone other than itself. */
195
+ get delegated() {
196
+ return this.subjectEntityId !== this.principalEntityId;
197
+ }
198
+ /**
199
+ * Who this request is, for stamping onto whatever it mutates. Attribution
200
+ * follows record-level authorship: the subject is the actor, and the
201
+ * principal is named beside it only when the two differ.
202
+ * See docs/spec/data-model.md § Authorship and attribution.
203
+ */
204
+ get actor() {
205
+ // Both keys are always present, so spreading this last overrides
206
+ // anything a caller passed: a scoped requester names itself by making
207
+ // the request, never by describing itself in the options.
208
+ return {
209
+ updatedBy: this.subjectEntityId ?? undefined,
210
+ updatedVia: this.delegated ? (this.principalEntityId ?? undefined) : undefined,
211
+ };
212
+ }
213
+ /**
214
+ * Whether unconditional owner authority applies — the owner acting as
215
+ * itself. The verbs that rest on it are irreversible or disclose the
216
+ * sharing graph, so delegation never carries one to a subject, whichever
217
+ * side the owner is on. Shared with the predicate a server applies to a
218
+ * session, which decides the same tier one step earlier. See
219
+ * docs/spec/access-control.md § Delegation: principal and subject.
220
+ */
221
+ get ownerActingAlone() {
222
+ return isOwnerActingAlone({ principalId: this.principalEntityId, subjectId: this.subjectEntityId }, this.stack.ownerEntityId);
223
+ }
224
+ /**
225
+ * Refuse anything but the owner acting as itself. The verbs resting on
226
+ * this tier are irreversible or disclose the sharing graph, so delegation
227
+ * never carries one to a subject — see ownerActingAlone.
228
+ */
229
+ requireOwnerActingAlone(message) {
230
+ if (!this.ownerActingAlone)
231
+ throw new StackPermissionError(message);
232
+ }
233
+ checkRead(record) {
234
+ return checkAccess(record, this.subjectEntityId, this.stack.ownerEntityId, 'read', this.resolveRecord);
235
+ }
236
+ checkWrite(record) {
237
+ return checkAccess(record, this.subjectEntityId, this.stack.ownerEntityId, 'write', this.resolveRecord);
238
+ }
239
+ /**
240
+ * Whether `grantee` holds a _grant covering one of `actions` for the
241
+ * type's family (grants match by baseId, so a version bump never orphans
242
+ * one). -own actions additionally require record.entityId === grantee,
243
+ * unless `matchOwn` is false — on the principal side of a delegated
244
+ * request the suffix is read as the bare verb, since which records are
245
+ * reachable is the subject's business. `allowDefault` decides whether a
246
+ * grant naming nobody counts. Anonymous grantees always return false.
247
+ *
248
+ * Reached only through subjectAllows()/principalAllows(), which fix those
249
+ * two flags per side of the intersection. Call one of those instead.
250
+ * See docs/spec/access-control.md § Type-level grants.
251
+ */
252
+ async hasGrant(typeId, actions, opts) {
253
+ const { grantee, record, prefetchedGrants, matchOwn = true, allowDefault = true, allowGroup = true, } = opts;
254
+ if (!grantee)
255
+ return false;
256
+ // Absent when the caller has no operation-scoped map to share — one
257
+ // call's worth of memoization, which is still every grant record in
258
+ // this loop naming the same group.
259
+ const groupRoles = opts.groupRoles ?? new Map();
260
+ const familyId = baseIdOf(typeId);
261
+ // grant() refuses to write these, but a _grant record is an ordinary
262
+ // Record: an unscoped Stack, an import, or a server mapping a request
263
+ // body onto Stack can mint one anyway. Refusing at the point of use is
264
+ // what makes the rule hold regardless of how the record got there.
265
+ if (UNGRANTABLE_SYSTEM_TYPES.has(familyId))
266
+ return false;
267
+ let grantRecords;
268
+ if (prefetchedGrants !== undefined) {
269
+ grantRecords = prefetchedGrants;
270
+ }
271
+ else {
272
+ // No content-field prefilter: a stored grant's typeId may be a bare
273
+ // baseId or versioned, so exact matching would wrongly exclude family
274
+ // versions. Cursor-walked to see grants past page one.
275
+ grantRecords = await this.loadGrants();
276
+ }
277
+ for (const r of grantRecords) {
278
+ const c = r.content;
279
+ if (baseIdOf(c.typeId) !== familyId)
280
+ continue;
281
+ const covers = await grantCoversGrantee(c, grantee, {
282
+ allowDefault,
283
+ allowGroup,
284
+ groupRoles,
285
+ resolveRecord: this.resolveRecord,
286
+ });
287
+ if (!covers)
288
+ continue;
289
+ const matches = actions.some((action) => {
290
+ if (!grantConveys(c.actions, action))
291
+ return false;
292
+ if (matchOwn && action.endsWith('-own'))
293
+ return record?.entityId === grantee;
294
+ return true;
295
+ });
296
+ if (matches)
297
+ return true;
298
+ }
299
+ return false;
300
+ }
301
+ /**
302
+ * The principal half of a delegated request's authority: does the app
303
+ * hold any grant permitting these verbs on this type at all. Bounds what
304
+ * the subject's own authority can reach through it, so a powerful app
305
+ * can never lend its reach to a weaker subject — nor the reverse.
306
+ * Vacuously true when there's no delegation, where the principal and
307
+ * subject checks would be the same question asked twice.
308
+ *
309
+ * Default grants don't count here. "Any authenticated entity" is about
310
+ * people who turn up, not software the owner installed — an app reaches
311
+ * only the types named to it, which is the whole of what containment
312
+ * promises.
313
+ *
314
+ * Group-targeted grants don't count here either, one step removed: a
315
+ * roster is editable by any of the group's admins, so authority reaching
316
+ * a principal through one would let someone other than the owner name an
317
+ * app to a type. See docs/spec/access-control.md § Type-level grants.
318
+ */
319
+ principalAllows(typeId, actions, prefetchedGrants) {
320
+ if (!this.delegated)
321
+ return Promise.resolve(true);
322
+ if (this.principalEntityId === this.stack.ownerEntityId)
323
+ return Promise.resolve(true);
324
+ return this.hasGrant(typeId, actions, {
325
+ grantee: this.principalEntityId,
326
+ prefetchedGrants,
327
+ matchOwn: false,
328
+ allowDefault: false,
329
+ allowGroup: false,
330
+ });
331
+ }
332
+ /**
333
+ * The subject half: which records are reachable, answered with `-own`
334
+ * matching and default grants both in force — the ordinary reading of a
335
+ * grant, since the subject is the entity a grant is written about.
336
+ *
337
+ * Paired with principalAllows() so that the two halves of the
338
+ * intersection are the only callers of hasGrant(): its flags differ per
339
+ * side and mean nothing on their own, so no call site sets them by hand.
340
+ */
341
+ subjectAllows(typeId, actions, opts = {}) {
342
+ return this.hasGrant(typeId, actions, {
343
+ grantee: this.subjectEntityId,
344
+ record: opts.record,
345
+ prefetchedGrants: opts.prefetchedGrants,
346
+ groupRoles: opts.groupRoles,
347
+ });
348
+ }
349
+ /**
350
+ * How to refuse a record this request addressed by ID. A requester who
351
+ * can read the record is told it exists and the verb was refused;
352
+ * everyone else is told what a missing ID is told, so no one learns an ID
353
+ * is live who could not have learned it by reading. `message` therefore
354
+ * only ever reaches someone holding the record already.
355
+ * See docs/spec/access-control.md § Errors and information exposure.
356
+ */
357
+ async denialFor(record, message) {
358
+ // Prefetched here rather than threaded down from the gate: a write
359
+ // carried by a record-level permission settles without reading a grant
360
+ // at all, and that path must not pay for this one. Both halves of
361
+ // canRead share the one scan.
362
+ const grants = this.principalEntityId || this.subjectEntityId ? await this.loadGrants() : undefined;
363
+ if (await this.canRead(record, grants))
364
+ return new StackPermissionError(message);
365
+ return new StackNotFoundError(`Record not found: "${record.id}"`);
366
+ }
367
+ async canRead(record, prefetchedGrants, groupRoles) {
368
+ const reachable = (await this.checkRead(record)) ||
369
+ (await this.subjectAllows(record.typeId, ['read-own', 'read-any'], {
370
+ record,
371
+ prefetchedGrants,
372
+ groupRoles,
373
+ }));
374
+ if (!reachable)
375
+ return false;
376
+ return this.principalAllows(record.typeId, ['read-own', 'read-any'], prefetchedGrants);
377
+ }
378
+ async checkCreateGrant(typeId) {
379
+ if (this.ownerActingAlone)
380
+ return true;
381
+ const reachable = this.subjectEntityId === this.stack.ownerEntityId ||
382
+ (await this.subjectAllows(typeId, ['create']));
383
+ if (!reachable)
384
+ return false;
385
+ return this.principalAllows(typeId, ['create']);
386
+ }
387
+ /**
388
+ * `_group` records are managed, not merely written: only the owner or an
389
+ * `admin` roster holder may mutate them — ordinary write permissions and
390
+ * grants don't apply. Asked of both identities under delegation, like
391
+ * a reshare. See docs/spec/identity.md § Group.
392
+ */
393
+ isGroupManager(record) {
394
+ if (!this.managesGroup(this.principalEntityId, record))
395
+ return false;
396
+ return !this.delegated || this.managesGroup(this.subjectEntityId, record);
397
+ }
398
+ /** Whether one identity, on its own, manages `record` — see isGroupManager(). */
399
+ managesGroup(entityId, record) {
400
+ if (!entityId)
401
+ return false;
402
+ if (entityId === this.stack.ownerEntityId)
403
+ return true;
404
+ return groupRoleFromAssociations(record.associations, entityId) === 'admin';
405
+ }
406
+ /**
407
+ * Fetch a record the subject can reach and the principal holds `update` on
408
+ * (via permissions or an update grant), or throw. `mutating: false` marks
409
+ * the history readers, which borrow this gate without changing anything —
410
+ * the one way through it a `_grant` Record stays open to.
411
+ */
412
+ async requireUpdatable(id, opts = {}) {
413
+ const mutating = opts.mutating ?? true;
414
+ // The `_grant` write fence applies to mutating callers only: reading a
415
+ // grant Record's history is not the escalation that fence exists to stop.
416
+ const record = await this.requireVerb(id, ['update-own', 'update-any'], {
417
+ fenceGrantRecord: mutating,
418
+ });
419
+ return this.refuseIfDeleted(record, mutating);
420
+ }
421
+ /**
422
+ * The write gate both requireUpdatable() and requireDeletable() are: the
423
+ * subject can reach the record (record-level permission or a grant) and
424
+ * the principal holds the same verb, intersected — or, for a `_group`, the
425
+ * stricter management rule that no grant reaches.
426
+ * See docs/spec/access-control.md § Delegation: principal and subject.
427
+ */
428
+ async requireVerb(id, actions, opts) {
429
+ const record = await this.stack.get(id);
430
+ if (!record)
431
+ throw new StackNotFoundError(`Record not found: "${id}"`);
432
+ if (opts.fenceGrantRecord)
433
+ await this.requireOwnerForGrantRecord(record);
434
+ if (isGroupRecord(record)) {
435
+ if (!this.isGroupManager(record))
436
+ throw await this.denialFor(record);
437
+ return record;
438
+ }
439
+ const allowed = ((await this.checkWrite(record)) ||
440
+ (await this.subjectAllows(record.typeId, actions, { record }))) &&
441
+ (await this.principalAllows(record.typeId, actions));
442
+ if (!allowed)
443
+ throw await this.denialFor(record);
444
+ return record;
445
+ }
446
+ /**
447
+ * Refuse a mutation aimed at a soft-deleted Record. Asked only of a
448
+ * mutating caller, so the history readers borrowing this gate still work,
449
+ * and only after the authority decision, so "exists but deleted" is never
450
+ * a probe a stranger can run. See docs/spec/versioning.md § Mutations are
451
+ * refused, not applied to a tombstone.
452
+ */
453
+ refuseIfDeleted(record, mutating) {
454
+ if (mutating && record.deletedAt) {
455
+ throw new StackConflictError(`Record "${record.id}" is soft-deleted; undelete it before mutating it.`);
456
+ }
457
+ return record;
458
+ }
459
+ /**
460
+ * Fetch a record the subject can reach and the principal holds `delete` on
461
+ * (via permissions or a delete grant), or throw.
462
+ */
463
+ requireDeletable(id) {
464
+ // No soft-delete refusal: undelete() shares this gate, and a tombstone
465
+ // is exactly what it addresses.
466
+ return this.requireVerb(id, ['delete-own', 'delete-any'], { fenceGrantRecord: true });
467
+ }
468
+ /**
469
+ * Whether this request may reference `recordId` (as a parentId or
470
+ * relationship target). Missing and unreadable both return false —
471
+ * indistinguishable, so this can't probe for a record's existence.
472
+ */
473
+ async canReadReferent(recordId) {
474
+ const record = await this.stack.get(recordId);
475
+ if (!record)
476
+ return false;
477
+ return this.canRead(record);
478
+ }
479
+ /**
480
+ * Whether this request can read some record referencing `fileId` —
481
+ * shared by canAccessFile() and the non-owner _attachment@1 create()
482
+ * carve-out, which deliberately excludes the uploader clause. Walks
483
+ * every referencing record, short-circuiting on the first readable one.
484
+ * `_attachment@1` records are excluded from matching outright: the
485
+ * carve-out must be satisfied by some *other* record referencing the
486
+ * file, never by the requester's own prior metadata record for it —
487
+ * allowing that would let one successful guess unlock unlimited further
488
+ * metadata records for the same fileId, reintroducing the circularity
489
+ * the carve-out's uploader-clause exclusion closes.
490
+ * See docs/spec/attachments.md § Creating `_attachment@1` records directly.
491
+ */
492
+ async hasReadableReference(fileId) {
493
+ const prefetchedGrants = this.subjectEntityId ? await this.loadGrants() : undefined;
494
+ const groupRoles = new Map();
495
+ const match = await findFirstMatch((q) => this.stack.query(q),
496
+ // Reach, not enumeration: a record readable by ID conveys the file it
497
+ // references. See docs/spec/unlisted.md.
498
+ { filter: { attachmentFileId: fileId, includeUnlisted: true } }, (record) => baseIdOf(record.typeId) !== SYSTEM_TYPES.ATTACHMENT &&
499
+ this.canRead(record, prefetchedGrants, groupRoles));
500
+ return match !== undefined;
501
+ }
502
+ /**
503
+ * Whether this request may reference or download `fileId` — the dual of
504
+ * getAttachment()'s access rule. Nonexistent and inaccessible are
505
+ * indistinguishable (both false), so no confirmation oracle for guessed
506
+ * hashes. See docs/spec/access-control.md § Reference-creation gating.
507
+ */
508
+ async canAccessFile(fileId) {
509
+ if (this.ownerActingAlone)
510
+ return true;
511
+ // Reaching a file through a record this request can read is already
512
+ // fully intersected — canRead() applied the principal's mask against
513
+ // that record's own type, which is the type the reference lives on.
514
+ if (await this.hasReadableReference(fileId))
515
+ return true;
516
+ if (!this.subjectEntityId)
517
+ return false;
518
+ // The remaining paths are authorship facts about the subject, so they
519
+ // decide *which* files match — they are not themselves a grant, and the
520
+ // principal still needs one of its own on the attachment type.
521
+ if (!(await this.principalAllows(`${SYSTEM_TYPES.ATTACHMENT}@1`, ['read-own', 'read-any']))) {
522
+ return false;
523
+ }
524
+ if (this.subjectEntityId === this.stack.ownerEntityId)
525
+ return true;
526
+ return filtersContent(this.stack.features)
527
+ ? (await this.stack.query({
528
+ filter: {
529
+ typeId: `${SYSTEM_TYPES.ATTACHMENT}@1`,
530
+ entityId: this.subjectEntityId,
531
+ content: { fileId },
532
+ },
533
+ limit: 1,
534
+ })).records.length > 0
535
+ : (await queryAllPages((q) => this.stack.query(q), {
536
+ filter: { typeId: `${SYSTEM_TYPES.ATTACHMENT}@1`, entityId: this.subjectEntityId },
537
+ })).some((r) => r.content.fileId === fileId);
538
+ }
539
+ /** Names of the type's top-level file-ref fields — the content-reference half of attachmentFileId matching. */
540
+ async fileRefFieldNames(typeId) {
541
+ const type = await this.stack.getType(typeId);
542
+ if (!type)
543
+ return [];
544
+ return Object.entries(type.schema)
545
+ .filter(([, def]) => def.kind === 'file-ref')
546
+ .map(([field]) => field);
547
+ }
548
+ /**
549
+ * Gates file-ref content fields on file access, mirroring the
550
+ * attachment-association gate — a file-ref field conveys attachment
551
+ * access exactly like an `attachment` association. Only fields present
552
+ * in `content` are checked (a content patch is a merge patch; untouched fields
553
+ * carry no new reference).
554
+ */
555
+ async requireFileRefAccess(typeId, content) {
556
+ for (const field of await this.fileRefFieldNames(typeId)) {
557
+ const value = content[field];
558
+ if (typeof value !== 'string')
559
+ continue;
560
+ if (!(await this.canAccessFile(value)))
561
+ throw new StackPermissionError();
562
+ }
563
+ }
564
+ /**
565
+ * Reference-creation gate for one association: `attachment` requires
566
+ * file access, and a `relationship` naming a record in this stack
567
+ * requires read access to it. `tag` is unchecked, and `_group` roster
568
+ * associations are gated by the stricter isGroupManager() instead.
569
+ *
570
+ * The other target arms are ungated because the gate's purpose —
571
+ * refusing a reference that would convey access to, or confirm the
572
+ * existence of, an unreadable record — has nothing to bite on: core
573
+ * never resolves them, so no access flows through one.
574
+ * See docs/spec/access-control.md § Reference-creation gating.
575
+ */
576
+ async requireAssociationAccess(typeId, association) {
577
+ if (association.kind === 'attachment') {
578
+ if (!(await this.canAccessFile(association.fileId)))
579
+ throw new StackPermissionError();
580
+ }
581
+ else if (association.kind === 'relationship' && baseIdOf(typeId) !== SYSTEM_TYPES.GROUP) {
582
+ const { target } = association;
583
+ // `stackUrl` is tested for a value, not for presence: absent and
584
+ // empty are one target — storage, targetEqual() and the filter all
585
+ // read them as this stack — so a check on presence alone would
586
+ // leave one spelling of a local Record ungated.
587
+ if (target.scope !== 'record' || target.stackUrl)
588
+ return;
589
+ if (!(await this.canReadReferent(target.recordId)))
590
+ throw new StackPermissionError();
591
+ }
592
+ }
593
+ /**
594
+ * Create a record on behalf of the subject: create grant required,
595
+ * anonymous denied, entityId set to the subject, client IDs skew-checked,
596
+ * reference-creating options gated, and non-owner `_attachment@1`
597
+ * creation refused save one carve-out. A scoped create always stamps
598
+ * authorship — an absent entityId means an unscoped `Stack` wrote it.
599
+ * `createdAt`/`updatedAt` are refused to everyone but the owner acting
600
+ * alone — see the guard below and docs/spec/data-model.md § Record IDs.
601
+ * See also docs/spec/access-control.md and docs/spec/attachments.md.
602
+ */
603
+ async create(typeId, content, opts = {}) {
604
+ const principal = this.principalEntityId;
605
+ if (!principal)
606
+ throw new StackPermissionError('Anonymous requesters cannot create records');
607
+ // createdAt/updatedAt let a caller backdate a record's clock fields —
608
+ // and, without `id` also supplied, its sort position too. Refused to
609
+ // everyone but the owner acting alone (undelegated, authenticated as
610
+ // themselves): a grantee is exactly the untrusted actor the `id`
611
+ // skew check below already exists to stop from forging a sort
612
+ // position, and a delegated app acting for the owner inherits none of
613
+ // the owner's extra trust — same reasoning as mayGrantAccess() below.
614
+ // Refused rather than silently dropped, so an app never believes it
615
+ // published something it didn't — asked value-wise, since an
616
+ // `undefined` carries no date and Stack.create() reads it as absent.
617
+ // This is also the enforcement a server built on ScopedStack inherits
618
+ // for `POST /records`: an owner-authenticated request may carry both
619
+ // fields, anyone else's has them ignored.
620
+ if ((opts.createdAt !== undefined || opts.updatedAt !== undefined) && !this.ownerActingAlone) {
621
+ throw new StackPermissionError('createdAt/updatedAt can only be set by the stack owner acting alone; a grantee or delegated create always stamps the current time.');
622
+ }
623
+ if (!(await this.checkCreateGrant(typeId))) {
624
+ throw new StackPermissionError(`No create grant for type "${typeId}"`);
625
+ }
626
+ // The exemption is the owner's own, so delegation doesn't carry it: an
627
+ // owner principal acting for someone else would otherwise let that
628
+ // subject name any fileId and reach the bytes through the uploader
629
+ // clause, which matches on the subject this create stamps.
630
+ if (!this.ownerActingAlone && baseIdOf(typeId) === SYSTEM_TYPES.ATTACHMENT) {
631
+ const fileId = content.fileId;
632
+ if (typeof fileId !== 'string' || !(await this.hasReadableReference(fileId))) {
633
+ throw new StackPermissionError();
634
+ }
635
+ }
636
+ if (opts.permissions?.length && !this.mayGrantAccess()) {
637
+ throw new StackPermissionError('A delegated principal cannot set permissions, at create time or after');
638
+ }
639
+ if (opts.unlisted && !this.mayGrantAccess()) {
640
+ throw new StackPermissionError('A delegated principal cannot create an unlisted record, at create time or after');
641
+ }
642
+ this.requireOwnerForOwnerDid(typeId, content.did);
643
+ await this.requireAppIdMatchesPrincipal(opts.appId);
644
+ if (opts.id !== undefined) {
645
+ validateRecordId(opts.id);
646
+ // Skipped when createdAt is also supplied: only the owner reaches
647
+ // here with that combination (checked above), and Stack.create()
648
+ // below checks the id against createdAt instead of "now" — the
649
+ // check here exists for a live grantee write, and a backdated
650
+ // owner create is deliberately not one. See
651
+ // docs/spec/data-model.md § Record IDs.
652
+ if (opts.createdAt === undefined) {
653
+ validateIdTimestampSkew(opts.id, this.idTimestampSkewMs, Date.now(), 'the current time');
654
+ }
655
+ }
656
+ if (opts.parentId !== undefined && !(await this.canReadReferent(opts.parentId))) {
657
+ throw new StackPermissionError();
658
+ }
659
+ for (const assoc of opts.associations ?? []) {
660
+ await this.requireAssociationAccess(typeId, assoc);
661
+ }
662
+ await this.requireFileRefAccess(typeId, content);
663
+ return this.stack.create(typeId, content, {
664
+ ...opts,
665
+ entityId: this.subjectEntityId ?? undefined,
666
+ principalId: this.delegated ? principal : undefined,
667
+ });
668
+ }
669
+ /**
670
+ * Whether this request may decide who else reaches a record — the rule
671
+ * a reshare enforces, asked at create time too so the reach it
672
+ * withholds can't be taken one step earlier while authoring. A delegated
673
+ * app is denied it: widening access is the one thing containment most
674
+ * needs to hold. Refused rather than silently ignored, so an app never
675
+ * believes it published something it didn't. Not `ownerActingAlone`:
676
+ * the record is the subject's own, so an owner principal grants it no
677
+ * reach the subject lacks.
678
+ * See docs/spec/access-control.md § Delegation: principal and subject.
679
+ */
680
+ mayGrantAccess() {
681
+ return !this.delegated || this.principalEntityId === this.stack.ownerEntityId;
682
+ }
683
+ /**
684
+ * Whether one identity, on its own, may decide who else reaches `record`
685
+ * — the owner-or-creator rule a reshare enforces, asked of one
686
+ * side at a time. See
687
+ * docs/spec/access-control.md § Delegation: principal and subject.
688
+ */
689
+ mayReshare(entityId, record) {
690
+ if (!entityId)
691
+ return false;
692
+ return entityId === this.stack.ownerEntityId || entityId === record.entityId;
693
+ }
694
+ /**
695
+ * A record this request may read, or null. Never throws
696
+ * StackPermissionError: an unreadable record answers exactly as a missing
697
+ * one does, so a caller learns only what it may read.
698
+ * See docs/spec/access-control.md § Errors and information exposure.
699
+ */
700
+ async get(id, opts = {}) {
701
+ const record = await this.stack.get(id, opts);
702
+ if (!record)
703
+ return null;
704
+ if (!(await this.canRead(record)))
705
+ return null;
706
+ return presentDeleted(record);
707
+ }
708
+ /**
709
+ * Runs through this.query(), so canRead() still applies — this answers a
710
+ * question the caller asks on its own behalf. includeUnlisted is passed
711
+ * only when the request is the owner acting alone, per
712
+ * docs/spec/identity.md § DID bindings.
713
+ */
714
+ async getEntityByDid(did) {
715
+ return lookupEntityByDid((q) => this.query(q), did, filtersContent(this.stack.features), this.ownerActingAlone);
716
+ }
717
+ async getOwnerEntity() {
718
+ return this.getEntityByDid(this.stack.ownerEntityId);
719
+ }
720
+ /**
721
+ * Query records, filtered to those this request can read. Pages are
722
+ * filtered then refilled, so a page may slightly overshoot `limit` but
723
+ * never skips a record. Grants are prefetched once, cursor-walked to
724
+ * exhaustion.
725
+ */
726
+ async query(query = {}) {
727
+ assertValidSort(query.sort);
728
+ assertSortCapability(query.sort, this.stack.features);
729
+ assertValidRelatedTo(query.filter?.relatedTo);
730
+ if (query.filter?.includeUnlisted && !this.ownerActingAlone) {
731
+ throw new StackPermissionError('includeUnlisted is owner-only');
732
+ }
733
+ const limit = Math.min(query.limit ?? DEFAULT_QUERY_LIMIT, MAX_QUERY_LIMIT);
734
+ const records = [];
735
+ const maxFetched = limit * 10;
736
+ let totalFetched = 0;
737
+ const prefetchedGrants = this.principalEntityId ? await this.loadGrants() : undefined;
738
+ // Scoped to this query, like prefetchedGrants beside it: every
739
+ // candidate Record shares one roster resolution per group, and nothing
740
+ // is carried into the next operation.
741
+ const groupRoles = new Map();
742
+ let page = { records: [], cursor: query.cursor ?? null };
743
+ do {
744
+ page = await this.stack.query({ ...query, cursor: page.cursor ?? undefined });
745
+ totalFetched += page.records.length;
746
+ for (const record of page.records) {
747
+ // Projected here as well as in get(), or `includeDeleted` would be
748
+ // a strictly better read channel than the fetch-by-ID it is
749
+ // supposed to match.
750
+ if (await this.canRead(record, prefetchedGrants, groupRoles)) {
751
+ records.push(presentDeleted(record));
752
+ }
753
+ }
754
+ } while (records.length < limit && page.cursor && totalFetched < maxFetched);
755
+ return { records, cursor: page.cursor };
756
+ }
757
+ /**
758
+ * Apply a change set on behalf of the subject. Authority is resolved
759
+ * **per key** and every gate reads the record as it stands, never as the
760
+ * change set would leave it: a widened `permissions` never satisfies the
761
+ * read check on a `parentId` named in the same call, and a `_group`
762
+ * roster never satisfies the admin check that same call has to pass.
763
+ * One refused key refuses the whole call, so nothing is partially
764
+ * applied and no key is silently dropped.
765
+ * See docs/spec/access-control.md § Composing a change set.
766
+ */
767
+ async mutate(id, changes, opts = {}) {
768
+ // Ahead of every gate: a malformed change set is a validation error
769
+ // for every requester, rather than one for the owner and a permission
770
+ // refusal for everyone else.
771
+ assertNonEmptyChangeSet(changes);
772
+ if (changes.contentPatch) {
773
+ const patchErrors = validatePatchValues(changes.contentPatch);
774
+ if (patchErrors.length > 0)
775
+ throw new StackValidationError(patchErrors);
776
+ }
777
+ const reshares = changes.permissions !== undefined || changes.unlisted !== undefined;
778
+ const writes = changes.contentPatch !== undefined ||
779
+ changes.associations !== undefined ||
780
+ changes.parentId !== undefined;
781
+ // requireUpdatable() reads the record and applies the write gate; the
782
+ // reshare keys need the record before their own gate, and a change set
783
+ // carrying only those must not be held to the write gate it doesn't
784
+ // need. One read either way.
785
+ const record = writes ? await this.requireUpdatable(id) : await this.requireReshareable(id);
786
+ if (writes && reshares)
787
+ await this.requireReshareOf(record);
788
+ if (changes.contentPatch) {
789
+ const patch = changes.contentPatch;
790
+ // Value-wise, not presence-wise: a client that reads a card, edits
791
+ // its `name` and sends the whole content object back is not setting
792
+ // the binding it round-trips, and `name` is writable by record-level
793
+ // permission. Same predicate restoreVersion() applies to a snapshot.
794
+ this.requireOwnerForAppIdentity(record.typeId, (field) => field in patch && patch[field] !== record.content[field]);
795
+ // Likewise value-wise: re-sending the DID a card already holds
796
+ // claims nothing, and immutability refuses changing it regardless.
797
+ if ('did' in patch && patch.did !== record.content.did) {
798
+ this.requireOwnerForOwnerDid(record.typeId, patch.did);
799
+ }
800
+ await this.requireFileRefAccess(record.typeId, patch);
801
+ }
802
+ // Every association the change set would add is a reference this
803
+ // requester has to be allowed to create — asked against the stored
804
+ // set, so an association already on the record is not re-gated.
805
+ for (const assoc of changes.associations ?? []) {
806
+ if ((record.associations ?? []).some((a) => associationEqual(a, assoc)))
807
+ continue;
808
+ await this.requireAssociationAccess(record.typeId, assoc);
809
+ }
810
+ if (changes.parentId != null && !(await this.canReadReferent(changes.parentId))) {
811
+ throw new StackPermissionError();
812
+ }
813
+ return this.stack.mutate(id, changes, { ...opts, ...this.actor });
814
+ }
815
+ async patchContent(id, patch, opts = {}) {
816
+ return this.mutate(id, { contentPatch: patch }, opts);
817
+ }
818
+ /**
819
+ * The record, having established that this request may decide who else
820
+ * reaches it — the owner-or-creator rule, asked of both sides of a
821
+ * delegation, or a Group's admin rule for a `_group`. The gate the
822
+ * `permissions` and `unlisted` keys carry, which the write bit
823
+ * deliberately does not confer.
824
+ */
825
+ async requireReshareable(id) {
826
+ const record = await this.stack.get(id);
827
+ if (!record)
828
+ throw new StackNotFoundError(`Record not found: "${id}"`);
829
+ await this.requireOwnerForGrantRecord(record);
830
+ await this.requireReshareOf(record);
831
+ // Reached through its own gate rather than requireUpdatable(), so the
832
+ // soft-delete refusal has to be asked here too — after the authority
833
+ // decision above, for the reason refuseIfDeleted() gives.
834
+ return this.refuseIfDeleted(record, true);
835
+ }
836
+ /** The reshare decision alone, for a record already read and write-gated. */
837
+ async requireReshareOf(record) {
838
+ if (baseIdOf(record.typeId) === SYSTEM_TYPES.GROUP) {
839
+ // Group management, not authorship: a creator later demoted from the
840
+ // admin roster shouldn't retain a side door to reassign who can read
841
+ // or write the group record.
842
+ if (!this.isGroupManager(record))
843
+ throw await this.denialFor(record);
844
+ return;
845
+ }
846
+ // Intersected like every other authority here: the principal must hold
847
+ // the verb, and the subject must be able to reach this record —
848
+ // without which an owner principal would carry its subject to records
849
+ // the subject cannot touch. create() withholds the same reach via
850
+ // mayGrantAccess().
851
+ if (!this.mayReshare(this.principalEntityId, record))
852
+ throw await this.denialFor(record);
853
+ if (this.delegated && !this.mayReshare(this.subjectEntityId, record)) {
854
+ throw await this.denialFor(record);
855
+ }
856
+ }
857
+ /**
858
+ * Naming the software behind a key is the trust decision the `_app`
859
+ * registry exists to record, so both halves of that binding — `did` and
860
+ * `appId` — belong to the owner alone. Same reasoning that makes `_app`
861
+ * ungrantable, applied to the fields a lookup reads. Registering a card
862
+ * is already owner-only; without this, record-level `write` shared on a
863
+ * card would be a second way in: a card carrying no DID yet could be
864
+ * pointed at a write-holder's own key while keeping the name the owner
865
+ * gave it, or relabelled to claim another app's `appId`. `name` and
866
+ * `version` stay writable — they are display, not lookup.
867
+ *
868
+ * Owner *acting alone*, in both directions: a delegated app never holds
869
+ * it, and an owner principal doesn't lend it to a subject holding
870
+ * record-level `write` on a card — which would reopen the same route
871
+ * from the other side.
872
+ *
873
+ * `_entity` deliberately does not get this rule: naming people is what a
874
+ * contacts app does, so its cards stay writable by grant. Uniqueness and
875
+ * immutability still bind them. See docs/spec/identity.md § DID bindings.
876
+ */
877
+ requireOwnerForAppIdentity(typeId, touches) {
878
+ if (baseIdOf(typeId) !== SYSTEM_TYPES.APP)
879
+ return;
880
+ if (!bindingFieldsOf(SYSTEM_TYPES.APP).some(touches))
881
+ return;
882
+ this.requireOwnerActingAlone('Only the stack owner may set an _app record’s did or appId');
883
+ }
884
+ /**
885
+ * A self-reported `appId` must agree with the `_app` card naming the
886
+ * principal's DID, where the owner registered one. `principalId` is
887
+ * verified, so letting the pair disagree would leave a verified principal
888
+ * claiming a name the owner gave different software — the cross-check the
889
+ * registry exists for, refused at the write instead of left to each reader.
890
+ * A principal with no card keeps `appId` as the bare self-report it is for
891
+ * every undelegated writer.
892
+ * See docs/spec/identity.md § Attribution and what can be trusted.
893
+ */
894
+ async requireAppIdMatchesPrincipal(appId) {
895
+ if (appId === undefined || !this.delegated)
896
+ return;
897
+ const card = await findFirstMatch((q) => this.stack.query(q), {
898
+ filter: {
899
+ baseId: SYSTEM_TYPES.APP,
900
+ includeDeleted: true,
901
+ includeUnlisted: true,
902
+ ...(filtersContent(this.stack.features) && {
903
+ content: { did: this.principalEntityId },
904
+ }),
905
+ },
906
+ }, (r) => r.content.did === this.principalEntityId);
907
+ if (card && card.content.appId !== appId) {
908
+ throw new StackPermissionError(`appId "${appId}" is not the appId registered for this principal`);
909
+ }
910
+ }
911
+ /**
912
+ * The owner's own DID is the one `_entity` binding a grantee may not claim.
913
+ * `ownerProfile` adopts whichever card holds it, so a card minted by
914
+ * someone else becomes the stack's own profile, and uniqueness then makes
915
+ * that permanent. Every other DID stays open to a contacts app, which is
916
+ * the reach `_entity` is grantable for.
917
+ * See docs/spec/identity.md § DID bindings.
918
+ */
919
+ requireOwnerForOwnerDid(typeId, did) {
920
+ if (baseIdOf(typeId) !== SYSTEM_TYPES.ENTITY)
921
+ return;
922
+ if (did !== this.stack.ownerEntityId)
923
+ return;
924
+ this.requireOwnerActingAlone('Only the stack owner may claim the owner’s own did');
925
+ }
926
+ /**
927
+ * A `_grant` Record *is* authority, so rewriting one is the escalation
928
+ * UNGRANTABLE_SYSTEM_TYPES refuses at evaluation, reached by editing an
929
+ * existing grant rather than minting a fresh one. `grant()` and `revoke()`
930
+ * live on `Stack`, never `StackClient`, so no scoped write is lost. Writes
931
+ * only: reading a grant Record and its history stays on the ordinary gate.
932
+ * See docs/spec/access-control.md § Type-level grants.
933
+ */
934
+ async requireOwnerForGrantRecord(record) {
935
+ if (baseIdOf(record.typeId) !== SYSTEM_TYPES.GRANT)
936
+ return;
937
+ if (this.ownerActingAlone)
938
+ return;
939
+ throw await this.denialFor(record, 'Only the stack owner may write a _grant record');
940
+ }
941
+ async associate(id, association, opts = {}) {
942
+ const record = await this.requireUpdatable(id);
943
+ await this.requireAssociationAccess(record.typeId, association);
944
+ return this.stack.associate(id, association, { ...opts, ...this.actor });
945
+ }
946
+ async dissociate(id, association, opts = {}) {
947
+ await this.requireUpdatable(id);
948
+ return this.stack.dissociate(id, association, { ...opts, ...this.actor });
949
+ }
950
+ /**
951
+ * Hard delete is owner-only: it is irreversible and destroys version
952
+ * history, so neither the write bit nor delete-own/delete-any grants
953
+ * reach it, and delegation doesn't carry it either. Everyone else is
954
+ * limited to soft delete.
955
+ */
956
+ async delete(id, opts = {}) {
957
+ await this.requireDeletable(id);
958
+ if (opts.hard && !this.ownerActingAlone) {
959
+ throw new StackPermissionError('Hard delete is owner-only');
960
+ }
961
+ return this.stack.delete(id, { ...opts, ...this.actor });
962
+ }
963
+ /**
964
+ * Reverse a soft delete. Gated the same as delete() — undelete is the
965
+ * inverse of soft delete, so granting one direction without the other
966
+ * would be backwards. Idempotent, per Stack.undelete().
967
+ */
968
+ async undelete(id, opts = {}) {
969
+ await this.requireDeletable(id);
970
+ return this.stack.undelete(id, { ...opts, ...this.actor });
971
+ }
972
+ /**
973
+ * History is the mutation/recovery surface, not a read surface — gated
974
+ * like patchContent(), with snapshot `permissions` stripped for everyone but
975
+ * the owner acting alone — a snapshot's permissions are the stack's
976
+ * sharing graph, which delegation is not a route to. Reading history
977
+ * changes nothing, so it is the one path the `_grant` write fence leaves
978
+ * alone: seeing how a Record you can already read got that way is not
979
+ * the escalation that fence exists to stop, and losing it would leave a
980
+ * write-holder unable to audit the Record they hold.
981
+ * See docs/spec/versioning.md § History access.
982
+ */
983
+ async getVersions(id) {
984
+ await this.requireUpdatable(id, { mutating: false });
985
+ const versions = await this.stack.getVersions(id);
986
+ return this.ownerActingAlone ? versions : versions.map(stripVersionPermissions);
987
+ }
988
+ /** See getVersions() — same mutate-surface gate, same permissions stripping. */
989
+ async getVersion(id, version) {
990
+ await this.requireUpdatable(id, { mutating: false });
991
+ const target = await this.stack.getVersion(id, version);
992
+ if (!target)
993
+ return null;
994
+ return this.ownerActingAlone ? target : stripVersionPermissions(target);
995
+ }
996
+ /**
997
+ * Re-runs the reference-creation checks against the snapshot, so a
998
+ * restore can't re-convey access to a file or record the subject can no
999
+ * longer reach today — the snapshot's `parentId` among them, gated
1000
+ * exactly as a change set's `parentId` gates a destination named directly. Only the
1001
+ * owner acting alone is exempt: under delegation the checks resolve
1002
+ * against the subject, which is whose reach the restore would widen.
1003
+ * See docs/spec/versioning.md § Restore semantics.
1004
+ */
1005
+ async restoreVersion(id, version, opts = {}) {
1006
+ const record = await this.requireUpdatable(id);
1007
+ if (!this.ownerActingAlone) {
1008
+ const target = await this.stack.getVersion(id, version);
1009
+ if (target) {
1010
+ // A rollback that would move a card's binding is the same trust
1011
+ // decision a content patch reserves to the owner, reached by another route.
1012
+ this.requireOwnerForAppIdentity(record.typeId, (field) => target.content[field] !==
1013
+ record.content[field]);
1014
+ // Only a restore that moves the record *into* a container creates a
1015
+ // reference. A snapshot at the root names nothing, and a parentId
1016
+ // the restore would not change is not re-gated: the record is
1017
+ // already there, so a content rollback is not refused over a move
1018
+ // it isn't making.
1019
+ if (target.parentId !== undefined &&
1020
+ target.parentId !== record.parentId &&
1021
+ !(await this.canReadReferent(target.parentId))) {
1022
+ throw new StackPermissionError();
1023
+ }
1024
+ await this.requireFileRefAccess(target.typeId, target.content);
1025
+ // Gated against the associations the restore will actually write.
1026
+ // A `_group`'s don't roll back at all, so such a restore introduces
1027
+ // no association and there is nothing here to gate — the same
1028
+ // reason a `parentId` the restore would not change is not re-gated
1029
+ // above.
1030
+ if (!isGroupRecord(record)) {
1031
+ for (const association of target.associations ?? []) {
1032
+ await this.requireAssociationAccess(target.typeId, association);
1033
+ }
1034
+ }
1035
+ }
1036
+ }
1037
+ return this.stack.restoreVersion(id, version, { ...opts, ...this.actor });
1038
+ }
1039
+ /**
1040
+ * Commit a per-record migration — **the owner acting alone, only**.
1041
+ *
1042
+ * Migration is owner-driven by design: `migrateAll()`, the bulk path,
1043
+ * lives on `Stack` and is deliberately absent from `StackClient`, the
1044
+ * same way `grant()`/`revoke()` are. This is its per-record counterpart
1045
+ * and carries the same restriction, rather than inventing a grant model
1046
+ * that the bulk path deliberately doesn't have.
1047
+ *
1048
+ * The restriction is what makes the verb safe to expose at all. Migrate
1049
+ * replaces `content` and `typeId` wholesale, so a grant-based version
1050
+ * would have to re-derive every gate `create()` applies at the
1051
+ * destination *and* every gate `mutate()` applies over the existing
1052
+ * content, and would reopen each one it missed. The sharpest is the
1053
+ * non-owner `_attachment@1` refusal create() carries: without it, a
1054
+ * requester holding a create grant on `_attachment@1` and write access
1055
+ * to any record they authored could migrate that record into the family
1056
+ * naming any `fileId`, then read the bytes through canAccessFile()'s
1057
+ * uploader clause — the exact escalation that carve-out exists to refuse
1058
+ * (see docs/spec/attachments.md § Creating `_attachment@1` records
1059
+ * directly). Ordinary write access to a record is not consent to move it
1060
+ * between families.
1061
+ *
1062
+ * A server implementing `POST /records/:id/migrate` therefore serves it
1063
+ * to the stack owner and answers 403 otherwise. See
1064
+ * docs/spec/data-model.md § Type migrations.
1065
+ */
1066
+ async commitMigration(id, toTypeId, content, opts = {}) {
1067
+ this.requireOwnerActingAlone('Only the stack owner may commit a migration');
1068
+ return this.stack.commitMigration(id, toTypeId, content, { ...opts, ...this.actor });
1069
+ }
1070
+ /**
1071
+ * Store bytes and create an _attachment@1 metadata record (create grant
1072
+ * on `_attachment@1` required; anonymous denied), returning that record.
1073
+ * Authorship and principal are stamped exactly as create() does.
1074
+ */
1075
+ async putAttachment(data, mimeType, filename, appId) {
1076
+ // The one ScopedStack path that reaches the adapter without going
1077
+ // through Stack first — without this, a closed stack would still write
1078
+ // bytes before the delegated create() refused.
1079
+ this.stack.assertOpen();
1080
+ const principal = this.principalEntityId;
1081
+ if (!principal) {
1082
+ throw new StackPermissionError('Anonymous requesters cannot upload attachments');
1083
+ }
1084
+ if (!(await this.checkCreateGrant(`${SYSTEM_TYPES.ATTACHMENT}@1`))) {
1085
+ throw new StackPermissionError(`No create grant for type "${SYSTEM_TYPES.ATTACHMENT}@1"`);
1086
+ }
1087
+ await this.requireAppIdMatchesPrincipal(appId);
1088
+ assertAttachmentSize(data.byteLength, this.features.limits.attachmentBytes);
1089
+ const fileId = await this.adapter.putAttachment(data);
1090
+ return this.stack.create(`${SYSTEM_TYPES.ATTACHMENT}@1`, {
1091
+ fileId,
1092
+ mimeType,
1093
+ size: data.byteLength,
1094
+ ...(filename && { filename }),
1095
+ }, {
1096
+ entityId: this.subjectEntityId ?? undefined,
1097
+ principalId: this.delegated ? principal : undefined,
1098
+ appId,
1099
+ });
1100
+ }
1101
+ /**
1102
+ * Download attachment bytes. Accessible to the owner, a reader of any
1103
+ * referencing record, or the uploader pre-association — the same
1104
+ * predicate as the reference-creation gate (canAccessFile).
1105
+ */
1106
+ async getAttachment(fileId) {
1107
+ if (!(await this.canAccessFile(fileId)))
1108
+ throw new StackPermissionError();
1109
+ return this.stack.getAttachment(fileId);
1110
+ }
1111
+ /**
1112
+ * Delete an attachment. Only the stack owner may delete attachments.
1113
+ * Delegates to Stack.deleteAttachment(), which enforces the "not referenced" check.
1114
+ */
1115
+ async deleteAttachment(fileId) {
1116
+ this.requireOwnerActingAlone('Only the stack owner can delete attachments');
1117
+ return this.stack.deleteAttachment(fileId, this.actor);
1118
+ }
1119
+ /**
1120
+ * Sweep for unreferenced attachment bytes and delete them. Only the stack
1121
+ * owner may run this. Delegates to Stack.collectAttachmentGarbage().
1122
+ */
1123
+ async collectAttachmentGarbage(opts) {
1124
+ this.requireOwnerActingAlone('Only the stack owner can collect attachment garbage');
1125
+ return this.stack.collectAttachmentGarbage({ ...opts, ...this.actor });
1126
+ }
1127
+ /**
1128
+ * Observe the changes this request may read. The predicate is canRead
1129
+ * applied per event — the same one get() and query() answer with, so a
1130
+ * feed can't disagree with them about what this session sees.
1131
+ *
1132
+ * A record the subscriber cannot read produces no event at all, rather
1133
+ * than an empty or redacted one: the existence of a change is itself a
1134
+ * disclosure, the same reasoning that keeps a count of the whole match
1135
+ * off a query result. See docs/spec/events.md § Permission scoping.
1136
+ */
1137
+ async subscribe(handler, opts = {}) {
1138
+ this.stack.assertOpen();
1139
+ if (this.stack.relaysChanges) {
1140
+ throw new StackRelayScopeError('This stack relays changes from elsewhere, and a scoped view cannot narrow that feed: ' +
1141
+ 'a relayed frame was already scoped by the session that opened it, and a purge leaves ' +
1142
+ 'no record to re-check. Subscribe with a session-scoped stack instead.');
1143
+ }
1144
+ // A relaying stack was already refused above, so relaysChanges is
1145
+ // always false here — `since` never has a cursor to mean anything by.
1146
+ assertSinceUsable(opts.since, false);
1147
+ if (opts.includeUnlisted && !this.ownerActingAlone) {
1148
+ throw new StackPermissionError('includeUnlisted is owner-only');
1149
+ }
1150
+ return this.changes.add(new ScopedSubscription((record, cache) => this.canReadCached(record, cache), handler, opts));
1151
+ }
1152
+ /**
1153
+ * canRead for one event, through the subscription's own cache. Grants
1154
+ * are prefetched once and refilled after an invalidation rather than
1155
+ * re-queried per event, which would be a `_grant` scan for every change
1156
+ * the stack makes.
1157
+ */
1158
+ async canReadCached(record, cache) {
1159
+ const grants = this.principalEntityId ? await cache.grants(() => this.loadGrants()) : undefined;
1160
+ return this.canRead(record, grants, cache.roles);
1161
+ }
1162
+ }
1163
+ //# sourceMappingURL=scoped-stack.js.map