Repository navigation
Expand file tree
/
Copy pathshared-record-ids.ts
More file actions
365 lines (350 loc) · 17.4 KB
/
Copy pathshared-record-ids.ts
File metadata and controls
365 lines (350 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* [ADR-0155 D1] `SharedRecordIds` — one branded comparand value meaning *"the
* ids of the records of object `object` that `sys_record_share` grants to the
* user `recipient`"*: at every access level (the read form), or at the levels
* it names (the write form, ADR-0155 ③ ruled A).
*
* It sits where the share arm's list of granted ids sat before the producer's
* switch (ADR-0155 plan step 6), as the comparand of `$in` on the object's `id`:
*
* ```ts
* { id: { $in: SharedRecordIds.read('account', 'u1') } }
* ```
*
* It denotes ADR-0155 D-0's set G(object, recipient, levels), the whole of it:
* the `record_id` values of the `sys_record_share` rows with that
* `object_name`, `recipient_type = 'user'`, that `recipient_id`, a `record_id`
* that is neither NULL nor empty and, on the write form, an `access_level` in
* the levels it carries. Read with system authority, with no organization
* predicate (ADR-0155 ① ruled A), with no cap and no ordering. The list the
* share arm bound before the switch is retired; the share arm now carries this
* leaf, which is G at every count. A SQL driver compiles it in the list's own
* position, as {@link SharedRecordIds.innerRead} describes:
*
* ```sql
* id IN (SELECT record_id FROM sys_record_share
* WHERE object_name = :object AND recipient_type = 'user' AND recipient_id = :recipient
* AND record_id IS NOT NULL AND record_id <> '')
* -- the write form adds, inside the subquery: AND access_level IN (:levels)
* ```
*
* This module declares the value and nothing else: no operator, no schema, no
* evaluation. ⛔ No `EXISTS`, no correlated form and no join (D1): the leaf
* sits in the list's own position, so `find`, `count` and `aggregate` agree by
* construction, and a record matched by several grant rows is still one row.
*
* ## Its own brand
*
* It is not a mode of `ReadableIds` (`./readable-ids.ts`) and not a mode of
* ADR-0147's leaf: one brand carries one meaning, so no composer has to ask
* which meaning it holds (ADR-0147 D-a, read from ADR-0139 D1). The brand
* device is ADR-0139 D1's, unchanged:
*
* - The key is `Symbol.for(…)` (the global registry), so a duplicated copy of
* this package resolves the same key.
* - The brand is non-enumerable, non-writable and non-configurable, so
* `JSON.stringify`, structured clone, a serializing wire and an object
* spread all produce an UNBRANDED copy, `{ object, recipient }`.
* - An unbranded copy is a plain object in a `$in` comparand, and the
* comparand-shape door refuses it as a non-list comparand (`INVALID_FILTER`
* / 400). ⛔ It is never dropped and never read as an empty list: dropping
* the `$in` would leave the rest of the branch standing alone, and an empty
* list would take away every grant.
* - The value is frozen, and so is the level list it carries, so a holder of
* the reference cannot re-point it at another object or another user after
* the engine's seam has judged it.
*
* ## What it carries: the inputs of G and nothing else
*
* The object's name, the recipient's user id, and the admitted access levels:
* none on the read form, which admits every level, and the producer's write
* levels on the write form. The producer supplies the levels (plugin-sharing's
* `WRITE_ACCESS_LEVELS`), so the level vocabulary keeps its one home and this
* package never restates it. `recipient_type = 'user'` is fixed, not carried.
* It carries no organization, no caller scope and no reading context. The
* inputs are ordinary enumerable properties, as `ReadableIds`' object name is,
* so two users' leaves never compare or serialise as equal; only the brand is
* non-enumerable.
*
* **The recipient is the producer's.** It is captured from the context the
* scope is built for, where the retired list's `recipient_id` came from. ⛔ No
* seam and no driver re-derives it from the reading context: the engine's seam
* (ADR-0155 D4) compares it with the reading context's user and delegator and
* never replaces it.
*
* ## It arrives composed
*
* Unlike `ReadableIds`, the engine composes nothing for this leaf: it asks no
* security service and its set is fixed by its inputs. The engine's executor
* seam checks its position, its verb and its recipient and hands it to the
* driver as it stands (ADR-0155 D4). The shared pieces it has in common with
* ADR-0147's leaf (the comparand door's option, the fixed inner read's
* description, the conformance case-set) live in `./fixed-read-leaf.ts` and
* `./fixed-read-leaf-conformance.ts`, built once in the two-leaf shape.
*
* ## Where it is legal (the engine's rule, ADR-0155 D1)
*
* Only as the `$in` comparand of `id` on the object it names: directly in that
* object's `where`, or inside the composed scope of a `ReadableIds` leaf whose
* parent is that object, under `$and`, `$or` and `$not` like any `$in`. The
* read form on `find`, `findOne`, `count` and `aggregate` (`where` only); the
* write form in the `where` of a predicate `update`. On `delete`, in a
* `having`, or at any other position, the engine refuses it loudly with ADR-0139
* D3's composition-fault envelope (`INTERNAL_ERROR` / 500).
*
* ## No request can spell it
*
* No operator joins `FieldOperatorsSchema` or `VALID_AST_OPERATORS`
* (`./filter.zod.ts`), and there is no CEL function and no lint vocabulary. One
* producer writes it: plugin-sharing's read-scope builder, and its write-scope
* builder. The engine's callers of the comparand-shape door admit it (ADR-0155
* plan step 2), and that producer writes it from its switch on (plan step 6).
*
* Like `./readable-ids.ts`, the module is tolerant of bare, un-parsed input:
* {@link isSharedRecordIds} accepts `unknown` and answers `false` for every
* degraded shape.
*
* @see ./fixed-read-leaf.ts for the description type and the door's brand dispatch
* @see ./fixed-read-leaf-conformance.ts for the per-driver case-set
*/
import type { FixedInnerRead } from './fixed-read-leaf';
/**
* The symbol key the `SharedRecordIds` brand lives under — a key of its own,
* never `READABLE_IDS_BRAND` or `COMPOSED_READABLE_IDS_BRAND`.
*
* Exported so a consumer that cannot import {@link isSharedRecordIds} (a
* duplicated package instance) can resolve the same key through `Symbol.for`.
* Everything else asks {@link isSharedRecordIds}, and a caller of the
* comparand-shape door names it in `admitFixedReadLeaves`.
*/
export const SHARED_RECORD_IDS_BRAND: unique symbol = Symbol.for('objectstack.filter.sharedRecordIds');
/**
* A `SharedRecordIds` leaf: the ids of the records of
* {@link SharedRecordIds.object} that `sys_record_share` grants to the user
* {@link SharedRecordIds.recipient}.
*
* Built only by {@link SharedRecordIds.read} and {@link SharedRecordIds.write}.
* The brand is part of the type, so an object literal does not type-check as
* one.
*/
export interface SharedRecordIds {
/** The machine name of the object whose shared record ids the leaf stands for (`object_name`). */
readonly object: string;
/** The user id the grants are to (`recipient_id`, with `recipient_type = 'user'` fixed). The producer's. */
readonly recipient: string;
/**
* The admitted access levels (`access_level IN …`), on the WRITE form only:
* a non-empty, frozen list the producer supplies. Absent on the read form,
* which admits every level — absent, not empty: an empty list would admit no
* grant at all.
*/
readonly accessLevels?: readonly string[];
/** The brand. Non-enumerable at runtime, so a copy of the leaf drops it. */
readonly [SHARED_RECORD_IDS_BRAND]: true;
}
/** The own string keys a `SharedRecordIds` leaf may carry; the read form carries the first two. */
const LEAF_KEYS: ReadonlySet<string> = new Set(['object', 'recipient', 'accessLevels']);
const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.length > 0;
/** The leaf's inputs, as read from its own data properties. */
interface LeafFields {
readonly object: string;
readonly recipient: string;
readonly accessLevels?: readonly string[];
}
/**
* The write form's level list read from its own data properties: a fresh
* frozen copy, or `undefined` unless `value` is a non-empty, frozen array of
* non-empty strings held as data, with no accessor at any index.
*/
function readLevelList(value: unknown): readonly string[] | undefined {
if (!Array.isArray(value) || value.length === 0 || !Object.isFrozen(value)) return undefined;
const levels: string[] = [];
for (let index = 0; index < value.length; index++) {
const descriptor = Object.getOwnPropertyDescriptor(value, index);
if (descriptor === undefined || !('value' in descriptor) || !isNonEmptyString(descriptor.value)) return undefined;
levels.push(descriptor.value);
}
return Object.freeze(levels);
}
/**
* The ONE reading of a value as a leaf, shared by {@link isSharedRecordIds}
* and {@link SharedRecordIds.innerRead} so the guard and the description
* answer the same question about the same bytes: the inputs, read from the
* value's own property DESCRIPTORS, or `undefined` when it is no leaf.
*
* `Object.isFrozen` tests writability on data properties only, so it is not
* enough on its own. A frozen value can still hold an accessor, which may
* answer differently to each reader, or inherit a field through a prototype
* that stays mutable. So this reading asks four things:
*
* - The prototype is the one the factories produce (`Object.prototype`).
* - Every own key, of either kind, is a DATA property.
* - The symbol keys are exactly the brand, non-enumerable and holding `true`.
* - The string keys are within `object`, `recipient` and `accessLevels`, each
* enumerable.
*
* It reads each input from the descriptor it judged, never through a property
* access.
*/
function readLeaf(value: unknown): LeafFields | undefined {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;
if (Object.getPrototypeOf(value) !== Object.prototype || !Object.isFrozen(value)) return undefined;
const fields: Record<string, unknown> = {};
let branded = false;
for (const key of Reflect.ownKeys(value)) {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor === undefined || !('value' in descriptor)) return undefined;
if (typeof key === 'symbol') {
if (key !== SHARED_RECORD_IDS_BRAND || descriptor.enumerable || descriptor.value !== true) return undefined;
branded = true;
} else {
if (!LEAF_KEYS.has(key) || !descriptor.enumerable) return undefined;
fields[key] = descriptor.value;
}
}
if (!branded || !isNonEmptyString(fields.object) || !isNonEmptyString(fields.recipient)) return undefined;
if (!Object.prototype.hasOwnProperty.call(fields, 'accessLevels')) {
return { object: fields.object, recipient: fields.recipient };
}
const accessLevels = readLevelList(fields.accessLevels);
return accessLevels === undefined ? undefined : { object: fields.object, recipient: fields.recipient, accessLevels };
}
/**
* Is `value` a branded `SharedRecordIds` leaf?
*
* Every own key must be a data property, on a frozen value whose prototype is
* the factories' (`Object.prototype`):
*
* - Exactly one symbol key, the brand: non-enumerable, holding only the
* declared value `true`. No other symbol-keyed property sits beside it, so
* no value answers to two leaf brands.
* - `object` and `recipient` own, enumerable, non-empty strings.
* - No own string key but `object`, `recipient` and `accessLevels`, enumerable
* or not.
* - `accessLevels`, when it is an own key, a non-empty frozen list of
* non-empty strings.
*
* These all answer `false`:
*
* - a copy that lost the brand (JSON, structured clone, a spread);
* - a brand holding any other value;
* - a value that also carries the `ReadableIds` brand or the composed one;
* - an unfrozen look-alike;
* - a frozen look-alike that holds a field as an accessor, inherits one, or
* hides one as non-enumerable;
* - `null` and every primitive.
*/
export function isSharedRecordIds(value: unknown): value is SharedRecordIds {
return readLeaf(value) !== undefined;
}
/** How a refused argument is named in a factory's `TypeError`. */
function describeArgument(value: unknown): string {
if (value === null) return 'null';
if (Array.isArray(value)) return value.length === 0 ? 'an empty array' : 'an array';
if (typeof value === 'string') return value.length === 0 ? 'an empty string' : 'a string';
return typeof value;
}
/** The frozen, branded leaf over already-judged inputs. */
function brand(fields: { object: string; recipient: string; accessLevels?: readonly string[] }): SharedRecordIds {
const leaf = { ...fields };
Object.defineProperty(leaf, SHARED_RECORD_IDS_BRAND, {
value: true,
enumerable: false,
writable: false,
configurable: false,
});
return Object.freeze(leaf) as SharedRecordIds;
}
/** Refuse an `object` / `recipient` that is not a non-empty string, naming the factory. */
function assertInputs(factory: string, object: unknown, recipient: unknown): void {
if (!isNonEmptyString(object)) {
throw new TypeError(
`SharedRecordIds.${factory}() needs the machine name of an object, received ${describeArgument(object)}.`,
);
}
if (!isNonEmptyString(recipient)) {
throw new TypeError(
`SharedRecordIds.${factory}() needs the user id the grants on '${object}' are to, received ` +
`${describeArgument(recipient)}. The recipient is captured from the context the scope is built for.`,
);
}
}
/** The table and columns of the inner read — named once, here. */
const TABLE = 'sys_record_share';
const COLUMN = 'record_id';
/**
* The `SharedRecordIds` factory. `read(object, recipient)` builds the read
* form, `write(object, recipient, accessLevels)` the write form, and
* `innerRead(leaf)` describes the fixed inner read either form denotes.
*/
export const SharedRecordIds: {
/**
* The READ form: the ids of the records of `object` shared with the user
* `recipient` at any access level. The read scope's share arm, placed as the
* comparand of `$in` on `id`.
*
* @param object the machine name of the object the grants are on.
* @param recipient the user id the grants are to, captured from the context
* the scope is built for.
* @throws TypeError when either is not a non-empty string.
*/
readonly read: (object: string, recipient: string) => SharedRecordIds;
/**
* The WRITE form (ADR-0155 ③ ruled A): the ids of the records of `object`
* shared with the user `recipient` at one of `accessLevels`. The predicate
* update's share arm, placed as the comparand of `$in` on `id`.
*
* @param accessLevels the admitted levels, supplied by the producer (the
* write levels of its own vocabulary); copied and frozen.
* @throws TypeError when `object` or `recipient` is not a non-empty string,
* or `accessLevels` is not a non-empty list of non-empty strings: an
* empty list would admit no grant, and the read form is the spelling
* of "every level".
*/
readonly write: (object: string, recipient: string, accessLevels: readonly string[]) => SharedRecordIds;
/**
* The fixed inner read the leaf denotes, as `./fixed-read-leaf.ts` declares
* it: what an evaluator compiles or evaluates, so ⛔ no evaluator restates
* this leaf's predicate by hand (ADR-0155 D4). A fresh frozen value per call.
*
* @throws TypeError when `leaf` is not a branded {@link SharedRecordIds} leaf.
*/
readonly innerRead: (leaf: SharedRecordIds) => FixedInnerRead;
} = Object.freeze({
read(object: string, recipient: string): SharedRecordIds {
assertInputs('read', object, recipient);
return brand({ object, recipient });
},
write(object: string, recipient: string, accessLevels: readonly string[]): SharedRecordIds {
assertInputs('write', object, recipient);
if (!Array.isArray(accessLevels) || accessLevels.length === 0 || !accessLevels.every(isNonEmptyString)) {
throw new TypeError(
`SharedRecordIds.write() needs the access levels a grant on '${object}' must hold, as a non-empty list ` +
`of non-empty strings, received ${describeArgument(accessLevels)}${
Array.isArray(accessLevels) && accessLevels.length > 0 ? ' holding a member that is not one' : ''
}. For every level, build the read form with SharedRecordIds.read().`,
);
}
return brand({ object, recipient, accessLevels: Object.freeze([...accessLevels]) });
},
innerRead(leaf: SharedRecordIds): FixedInnerRead {
// The guard's own reading: the inputs come from the descriptors it judged.
const fields = readLeaf(leaf);
if (fields === undefined) {
throw new TypeError(
`SharedRecordIds.innerRead() needs a leaf built by SharedRecordIds.read() or .write(), received ` +
`${describeArgument(leaf)}${leaf !== null && typeof leaf === 'object' ? ' without the SharedRecordIds brand' : ''}.`,
);
}
const memberOf: Record<string, readonly string[]> = {};
if (fields.accessLevels !== undefined) memberOf.access_level = fields.accessLevels;
return Object.freeze({
table: TABLE,
column: COLUMN,
equals: Object.freeze({ object_name: fields.object, recipient_type: 'user', recipient_id: fields.recipient }),
memberOf: Object.freeze(memberOf),
tenantScope: 'none' as const,
});
},
});