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