@latticecms/core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +1174 -2
  2. package/dist/access.d.ts +210 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +225 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/build.d.ts +507 -0
  7. package/dist/build.d.ts.map +1 -0
  8. package/dist/build.js +598 -0
  9. package/dist/build.js.map +1 -0
  10. package/dist/collection.d.ts +480 -0
  11. package/dist/collection.d.ts.map +1 -0
  12. package/dist/collection.js +344 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/crud.d.ts +30 -0
  15. package/dist/crud.d.ts.map +1 -0
  16. package/dist/crud.js +539 -0
  17. package/dist/crud.js.map +1 -0
  18. package/dist/describe.d.ts +89 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +119 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/errors.d.ts +179 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +146 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/family.d.ts +80 -0
  27. package/dist/family.d.ts.map +1 -0
  28. package/dist/family.js +231 -0
  29. package/dist/family.js.map +1 -0
  30. package/dist/index.d.ts +14 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +10 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/marker.d.ts +15 -0
  35. package/dist/marker.d.ts.map +1 -0
  36. package/dist/marker.js +28 -0
  37. package/dist/marker.js.map +1 -0
  38. package/dist/mask.d.ts +69 -0
  39. package/dist/mask.d.ts.map +1 -0
  40. package/dist/mask.js +255 -0
  41. package/dist/mask.js.map +1 -0
  42. package/dist/populate.d.ts +32 -0
  43. package/dist/populate.d.ts.map +1 -0
  44. package/dist/populate.js +73 -0
  45. package/dist/populate.js.map +1 -0
  46. package/dist/relations.d.ts +143 -0
  47. package/dist/relations.d.ts.map +1 -0
  48. package/dist/relations.js +128 -0
  49. package/dist/relations.js.map +1 -0
  50. package/dist/repo.d.ts +99 -0
  51. package/dist/repo.d.ts.map +1 -0
  52. package/dist/repo.js +83 -0
  53. package/dist/repo.js.map +1 -0
  54. package/dist/sort.d.ts +61 -0
  55. package/dist/sort.d.ts.map +1 -0
  56. package/dist/sort.js +145 -0
  57. package/dist/sort.js.map +1 -0
  58. package/dist/store/conformance.d.ts +15 -0
  59. package/dist/store/conformance.d.ts.map +1 -0
  60. package/dist/store/conformance.js +683 -0
  61. package/dist/store/conformance.js.map +1 -0
  62. package/dist/store/index.d.ts +9 -0
  63. package/dist/store/index.d.ts.map +1 -0
  64. package/dist/store/index.js +8 -0
  65. package/dist/store/index.js.map +1 -0
  66. package/dist/store.d.ts +113 -0
  67. package/dist/store.d.ts.map +1 -0
  68. package/dist/store.js +176 -0
  69. package/dist/store.js.map +1 -0
  70. package/dist/tenancy.d.ts +66 -0
  71. package/dist/tenancy.d.ts.map +1 -0
  72. package/dist/tenancy.js +69 -0
  73. package/dist/tenancy.js.map +1 -0
  74. package/dist/tracing.d.ts +12 -0
  75. package/dist/tracing.d.ts.map +1 -0
  76. package/dist/tracing.js +27 -0
  77. package/dist/tracing.js.map +1 -0
  78. package/dist/where.d.ts +95 -0
  79. package/dist/where.d.ts.map +1 -0
  80. package/dist/where.js +308 -0
  81. package/dist/where.js.map +1 -0
  82. package/package.json +79 -2
  83. package/skills/lattice/SKILL.md +106 -0
  84. package/skills/lattice/references/access.md +76 -0
  85. package/skills/lattice/references/cli.md +87 -0
  86. package/skills/lattice/references/collection.md +91 -0
  87. package/skills/lattice/references/event-handler.md +88 -0
  88. package/skills/lattice/references/masking.md +72 -0
  89. package/skills/lattice/references/method.md +85 -0
  90. package/skills/lattice/references/override.md +77 -0
  91. package/skills/lattice/references/relations.md +90 -0
  92. package/skills/lattice/references/tenancy.md +82 -0
  93. package/skills/lattice/references/testing.md +75 -0
  94. package/src/access.ts +429 -0
  95. package/src/build.ts +1722 -0
  96. package/src/collection.ts +1018 -0
  97. package/src/crud.ts +795 -0
  98. package/src/describe.ts +232 -0
  99. package/src/errors.ts +170 -0
  100. package/src/family.ts +334 -0
  101. package/src/index.ts +42 -0
  102. package/src/marker.ts +54 -0
  103. package/src/mask.ts +307 -0
  104. package/src/populate.ts +96 -0
  105. package/src/relations.ts +353 -0
  106. package/src/repo.ts +209 -0
  107. package/src/sort.ts +214 -0
  108. package/src/store/conformance.ts +1007 -0
  109. package/src/store/index.ts +16 -0
  110. package/src/store.ts +309 -0
  111. package/src/tenancy.ts +124 -0
  112. package/src/tracing.ts +29 -0
  113. package/src/where.ts +463 -0
@@ -0,0 +1,82 @@
1
+ # Tenancy
2
+
3
+ A collection with `tenant: 'organizationId'` keeps each tenant's rows apart. Lattice adds the field to the output, stamps it on create, and filters every call by the caller's tenant. A collection without `tenant` is global.
4
+
5
+ The family says each call's tenant:
6
+
7
+ ```ts
8
+ // examples/crm/src/app/use-cases/context.ts
9
+ /** The app's one use case family. Generated and hand-written use cases share it. */
10
+ export const AppUseCase = family({
11
+ actor: actorSchema,
12
+ actorId: (actor) => actor.userId,
13
+ tenantOf: (actor) =>
14
+ 'support' in actor ? tenancy.bypass : actor.organizationId,
15
+ });
16
+ ```
17
+
18
+ ## How it works
19
+
20
+ - `tenantOf` returns the actor's tenant id, or `tenancy.bypass` for a platform actor such as support staff. A framework with a tenanted collection requires it.
21
+ - The tenant field is in `Doc` and `Where`, never in create or update input. Create stamps it after `beforeChange`. Update never writes it.
22
+ - Every scope is the tenant clause ANDed with the access `Where`. Another tenant's row is `NOT_FOUND`, and `find` never returns it, page after page.
23
+ - A bypassed call reads across tenants and writes nothing on a tenanted collection: generated create, update and delete are `FORBIDDEN`, and so is a repo write through its scope. Each bypassed scope writes one `tenancy.bypass` log line.
24
+ - The actor schema validates the bypass flag. The edge sets it from server config, never from the request.
25
+
26
+ The crm proves isolation over HTTP:
27
+
28
+ ```ts
29
+ // examples/crm/src/servers/http/tenancy.test.ts
30
+ // An id from another organization is not there at all.
31
+ expect(await code(a, 'companies/get', { id: bolt })).toBe('NOT_FOUND');
32
+ expect(await code(b, 'companies/get', { id: acme })).toBe('NOT_FOUND');
33
+ // A where on the tenant field cannot reach past the tenant filter.
34
+ expect(
35
+ await ok(a, 'companies/find', {
36
+ where: { organizationId: { eq: 'org-b' } },
37
+ }),
38
+ ).toMatchObject({ docs: [] });
39
+ ```
40
+
41
+ ## Server code names its tenant
42
+
43
+ Code that acts for no caller says which tenant it works in. An event handler reads with `tenancy.scope(C, tenantId)`: the tenant clause, and no access. An insert through it is stamped with that tenant.
44
+
45
+ ```ts
46
+ // examples/crm/src/app/event-handlers/deal-closed-integration.ts
47
+ const { dealId, outcome, tenantId } = event.payload;
48
+ const deal = await this.deps.deals.get(
49
+ dealId,
50
+ tenancy.scope(Deals, tenantId),
51
+ );
52
+ ```
53
+
54
+ `unscoped` reads and writes every tenant. A script that acts for no tenant passes it. It cannot insert into a tenanted collection, since the row would belong to no tenant.
55
+
56
+ A global collection, such as the crm's `organizations` and `memberships`, has no tenant field. Its `read` access does the narrowing:
57
+
58
+ ```ts
59
+ // examples/crm/src/servers/rpc/contract.ts
60
+ .collection(Organizations, {
61
+ // A member reads the organization it acts in, and support every one.
62
+ // No create, update or delete: only trusted code writes them.
63
+ access: {
64
+ read: ({ actor }) =>
65
+ 'support' in actor ? true : { id: { eq: actor.organizationId } },
66
+ },
67
+ });
68
+ ```
69
+
70
+ ## Do not
71
+
72
+ - Do not put the tenant field in the schema. Lattice adds it.
73
+ - Do not take the tenant from the request body. The edge checks membership and puts the tenant on the actor.
74
+ - Do not pass `unscoped` in an event handler. Use the event's `tenantId` with `tenancy.scope`.
75
+ - Do not write through a bypass. Support reads; a write is a separate, audited path.
76
+
77
+ ## Errors you will see
78
+
79
+ - A schema field with the tenant's name fails `collection()` with `'~error'`: `tenant "organizationId" is stamped by Lattice; it cannot be a schema field, a reserved name or an invalid field name`.
80
+ - A tenanted collection in a family without `tenantOf` fails `.collection()`: `"notes" is tenanted, but the family has no tenantOf`.
81
+ - `insert` with `unscoped` on a tenanted collection does not compile, and throws `"notes" is tenanted, so insert needs a scope with a tenant, such as tenancy.scope()`.
82
+ - At runtime, a bypass write is `FORBIDDEN`, and another tenant's row is `NOT_FOUND`.
@@ -0,0 +1,75 @@
1
+ # Testing
2
+
3
+ Test a story through the contract. Build the app over a store, and call it with ts-pf's `createLocalClient`, as a client would. The local client runs the same router as HTTP: access, tenancy, masking and validation.
4
+
5
+ The smallest app, from core's quick start:
6
+
7
+ ```ts
8
+ // examples/crm/src/quickstart/quickstart.ts
9
+ const client = createLocalClient(app, {
10
+ context: { actor: { userId: 'ann' }, logger: new NoopLogger() },
11
+ });
12
+ const note = await client.notes.create({ title: 'Write the docs' });
13
+ await client.notes.update({ id: note.id, done: true });
14
+ const { docs } = await client.notes.find({ where: { done: { eq: true } } });
15
+ ```
16
+
17
+ ## The app's tests
18
+
19
+ The crm builds its app the way the server does, and gives the client an actor:
20
+
21
+ ```ts
22
+ // examples/crm/src/servers/app.test.ts
23
+ function setup() {
24
+ const events = new MemoryDomainEventPublisher();
25
+ const crm = createApp({ store: store(), events });
26
+ const local = createLocalClient(crm.app, {
27
+ context: { actor, logger: new NoopLogger() },
28
+ });
29
+ return { ...crm, events, local };
30
+ }
31
+ ```
32
+
33
+ A client needs no annotations. A refusal is a typed error:
34
+
35
+ ```ts
36
+ // examples/crm/src/servers/app.test.ts
37
+ const again = await asResult(
38
+ local.deals.close({ id: deal.id, outcome: 'lost' }),
39
+ );
40
+ if (again.ok) throw new Error('expected AlreadyClosed');
41
+ if (again.error.code !== 'AlreadyClosed')
42
+ throw new Error(again.error.code);
43
+ expectTypeOf(again.error.data).toEqualTypeOf<{ id: string }>();
44
+ expect(again.error.data).toEqual({ id: deal.id });
45
+ expect(again.error.status).toBe(409);
46
+ ```
47
+
48
+ - `MemoryStore` needs no server. The crm runs the same tests on `MemoryStore` and `MongoStore`, through `describe.each(backends)` in `src/test/stores.ts`.
49
+ - `build().repos` seeds and reads data directly, with a scope. `build().context({ actor, logger })` makes a context for a direct `useCases.*.execute` call. Prefer the client.
50
+ - A collection's own test, as `lattice collection` writes it, builds nothing: it checks the contract has the slug and its operations, and that the schema parses a document. Test behavior through the app's setup, as above.
51
+ - A test of a handler builds it with repos and a fake port, and calls `handle` with an event instance.
52
+ - Masking and tenancy are tested over HTTP in the crm: `src/servers/http/masking.test.ts` and `tenancy.test.ts`.
53
+
54
+ ## A store adapter
55
+
56
+ A new store passes the conformance suite from `@latticecms/core/store/conformance`, with a fresh store per case:
57
+
58
+ ```ts
59
+ // packages/store-mongo/src/mongo-store.test.ts
60
+ it.each(storeCases)('$name', ({ run }) => run(store));
61
+ ```
62
+
63
+ A case that needs a capability names it in `needs`. A store without transactions filters out `needs: ['transactions']`.
64
+
65
+ ## Do not
66
+
67
+ - Do not test through a mock of the store or the router. `MemoryStore` is the in-memory adapter.
68
+ - Do not cast a client's result. Narrow it: `asResult`, `'field' in doc`.
69
+ - Do not call `useCases` to test what a client sees. Masking happens in the router, so `useCases` return whole documents.
70
+ - Do not share one access context across calls. Make one per call with `context()`.
71
+
72
+ ## Errors you will see
73
+
74
+ - A test that expects a masked field from `useCases` passes and proves nothing. Call through `createLocalClient`.
75
+ - A tenanted collection seeded through `unscoped` does not compile. Seed with `tenancy.scope(C, tenantId)`.
package/src/access.ts ADDED
@@ -0,0 +1,429 @@
1
+ import { Adapter, Port, validate } from 'hexok';
2
+ import type { z } from 'zod';
3
+ import type { Action, AnyCollection } from './collection.js';
4
+ import { LatticeError } from './errors.js';
5
+ import type { CallContext, Family, FamilyContext } from './family.js';
6
+ import type { Doc } from './repo.js';
7
+ import { Scope, type Tenant, tenancy, tenantClause } from './tenancy.js';
8
+ import { type AnyWhere, both, type FieldWhere, type Where } from './where.js';
9
+
10
+ /** What `Access.check` decides on: who does what to which collection. */
11
+ export type AccessRequest<Actor> = {
12
+ readonly actor: Actor;
13
+ readonly collection: string;
14
+ /** A generated operation, or a method's name. */
15
+ readonly action: Action | (string & {});
16
+ /** The parsed input. Passed for `create` only. */
17
+ readonly data?: unknown;
18
+ };
19
+
20
+ /**
21
+ * Decides what a call may see and change (0005). `true` allows every row,
22
+ * `false` refuses the call with FORBIDDEN, and a `Where` limits it to the
23
+ * rows that match. The `Where` names the collection's fields; the port spans
24
+ * every collection, so it is untyped here.
25
+ */
26
+ export abstract class Access<Actor = unknown> extends Port('Access') {
27
+ abstract check(request: AccessRequest<Actor>): Promise<boolean | AnyWhere>;
28
+ /**
29
+ * Which of `fields`, a collection's maskable fields, `actor` may read.
30
+ * A field not in the answer is withheld from what the caller receives,
31
+ * so an adapter that forgets a field withholds it.
32
+ */
33
+ abstract readable(request: {
34
+ readonly actor: Actor;
35
+ readonly collection: string;
36
+ readonly fields: readonly string[];
37
+ }): Promise<readonly string[]>;
38
+ }
39
+
40
+ /**
41
+ * One access function as the default adapter stores it. A method signature,
42
+ * so its parameter is bivariant: a function typed by the app's actor and a
43
+ * collection's document fits.
44
+ */
45
+ type AccessFunction = {
46
+ fn(args: {
47
+ readonly actor: unknown;
48
+ readonly data?: unknown;
49
+ }): boolean | AnyWhere | Promise<boolean | AnyWhere>;
50
+ }['fn'];
51
+
52
+ /** The access functions given at `.collection()`, by action or method name. */
53
+ export type AccessMap = Readonly<Record<string, AccessFunction>>;
54
+
55
+ /** One field rule as the default adapter stores it; bivariant, as above. */
56
+ type ReadRule = {
57
+ fn(args: { readonly actor: unknown }): boolean | Promise<boolean>;
58
+ }['fn'];
59
+
60
+ /** The `fields` rules given at `.collection()`, by field. */
61
+ export type FieldsMap = Readonly<Record<string, { readonly read: ReadRule }>>;
62
+
63
+ /** The keys of `access` besides method names. `read` serves find, count and get. */
64
+ type AccessAction = 'read' | 'create' | 'update' | 'delete';
65
+
66
+ /** What an access function may return for `A`. Create has no row to filter. */
67
+ type Allowed<A, D> = A extends 'create' ? boolean : boolean | Where<D>;
68
+
69
+ /** What an access function receives for `A`. Create also gets its input. */
70
+ type AccessArgs<Actor, A, C extends AnyCollection> = A extends 'create'
71
+ ? { readonly actor: Actor; readonly data: z.output<C['schema']> }
72
+ : { readonly actor: Actor };
73
+
74
+ /**
75
+ * The return types `R` of a collection's access functions, by key. Inferred
76
+ * from the functions, so `AccessCheck` can read the keys of each `Where`:
77
+ * TypeScript does not check excess properties on an object literal that an
78
+ * arrow function returns.
79
+ */
80
+ export type AccessReturns<R, C extends AnyCollection> = {
81
+ [A in keyof R]: Allowed<A, Doc<C>>;
82
+ };
83
+
84
+ /** The `access` option of `.collection()`, typed by the app's actor. */
85
+ export type AccessFns<Actor, R, C extends AnyCollection> = {
86
+ readonly [A in keyof R]: (
87
+ args: AccessArgs<Actor, A, C>,
88
+ ) => R[A] | Promise<R[A]>;
89
+ };
90
+
91
+ /** Each key of a returned `Where` that names no field and no operator. */
92
+ type Unknown<W, D> = W extends boolean
93
+ ? never
94
+ :
95
+ | Exclude<keyof W, keyof D | 'and' | 'or'>
96
+ | {
97
+ [K in keyof W & keyof D]: Exclude<keyof W[K], keyof FieldWhere<D[K]>>;
98
+ }[keyof W & keyof D]
99
+ | (W extends { readonly and: readonly (infer I)[] }
100
+ ? Unknown<I, D>
101
+ : never)
102
+ | (W extends { readonly or: readonly (infer I)[] }
103
+ ? Unknown<I, D>
104
+ : never);
105
+
106
+ type AccessError<R, M, C extends AnyCollection> =
107
+ | {
108
+ [A in keyof R]: A extends AccessAction | keyof M
109
+ ? [Unknown<R[A], Doc<C>>] extends [never]
110
+ ? never
111
+ : `access.${A & string} filters on "${Unknown<R[A], Doc<C>> & string}", which ${C['slug']} does not have`
112
+ : `"${A & string}" is not an action of ${C['slug']}`;
113
+ }[keyof R]
114
+ | {
115
+ [N in Exclude<
116
+ keyof M,
117
+ keyof R
118
+ >]: `${C['slug']}.${N & string} has no access function; it is always FORBIDDEN`;
119
+ }[Exclude<keyof M, keyof R>];
120
+
121
+ /**
122
+ * Checks `.collection()`'s options: each `Where` names the collection's
123
+ * fields, each key is an action or a method, and each method has a
124
+ * function. On the options object, not on `access`: a check on `access`
125
+ * would depend on the functions it types, and `actor` would lose its type.
126
+ */
127
+ export type AccessCheck<R, M, C extends AnyCollection> = [
128
+ AccessError<R, M, C>,
129
+ ] extends [never]
130
+ ? unknown
131
+ : { readonly '~error': AccessError<R, M, C> };
132
+
133
+ /**
134
+ * The default adapter: the functions given at `.collection(C, { access })`.
135
+ * `find`, `count` and `get` run `read`. A missing function denies.
136
+ */
137
+ export class CollectionAccess extends Adapter(Access) {
138
+ constructor(
139
+ private readonly maps: ReadonlyMap<string, AccessMap>,
140
+ private readonly fields: ReadonlyMap<string, FieldsMap> = new Map(),
141
+ ) {
142
+ super();
143
+ }
144
+
145
+ override async readable(request: {
146
+ readonly actor: unknown;
147
+ readonly collection: string;
148
+ readonly fields: readonly string[];
149
+ }): Promise<readonly string[]> {
150
+ const rules = this.fields.get(request.collection) ?? {};
151
+ const answers = await Promise.all(
152
+ request.fields.map(async (field) => {
153
+ // Own keys only, as for access; a missing rule withholds.
154
+ const rule = Object.hasOwn(rules, field) ? rules[field] : undefined;
155
+ return rule !== undefined &&
156
+ (await rule.read({ actor: request.actor })) === true
157
+ ? [field]
158
+ : [];
159
+ }),
160
+ );
161
+ return answers.flat();
162
+ }
163
+
164
+ override async check(request: AccessRequest<unknown>) {
165
+ const { actor, collection, action, data } = request;
166
+ const map = this.maps.get(collection);
167
+ const name =
168
+ action === 'find' || action === 'get' || action === 'count'
169
+ ? 'read'
170
+ : action;
171
+ // Own keys only: an action named `toString` must not reach the prototype.
172
+ const fn =
173
+ map !== undefined && Object.hasOwn(map, name) ? map[name] : undefined;
174
+ if (fn === undefined) return false;
175
+ return fn(action === 'create' ? { actor, data } : { actor });
176
+ }
177
+ }
178
+
179
+ /**
180
+ * What trusted code passes to a `Repo` call instead of a `Scope`: event
181
+ * handlers, workers and scripts that act for no caller. It reads and writes
182
+ * every row.
183
+ */
184
+ export const unscoped: unique symbol = Symbol('lattice.unscoped');
185
+
186
+ /** What one call's `CallAccess` asks its caller for. */
187
+ type Caller = {
188
+ /** The access answer for `action` on `collection`. */
189
+ check(
190
+ collection: string,
191
+ action: string,
192
+ data: unknown,
193
+ ): Promise<boolean | AnyWhere>;
194
+ /** The actor's tenant. Asked after the guards, so the actor is valid. */
195
+ tenant(): Tenant | undefined;
196
+ /** Logs a bypassed scope of a tenanted collection. */
197
+ bypassed(collection: string, action: string): void;
198
+ /** Which of a collection's maskable `fields` the actor may read. */
199
+ readable(
200
+ collection: string,
201
+ fields: readonly string[],
202
+ ): Promise<readonly string[]>;
203
+ };
204
+
205
+ /** The generated writes a bypass may not make on a tenanted collection. */
206
+ const writes: readonly string[] = ['create', 'update', 'delete'];
207
+
208
+ /**
209
+ * The access and tenant of one call, on `ctx.access`. Each access answer is
210
+ * kept for the life of the context, so a guard and `execute` check once
211
+ * between them. Create is never kept: its answer depends on `data`.
212
+ */
213
+ export class CallAccess {
214
+ /** Answers by collection slug, then action. */
215
+ readonly #answers = new Map<
216
+ string,
217
+ Map<string, Promise<boolean | AnyWhere>>
218
+ >();
219
+ /** The tenant, once asked. */
220
+ #tenant: { readonly value: Tenant | undefined } | undefined;
221
+ /** The bypassed scopes already logged, as `slug action`. */
222
+ readonly #logged = new Set<string>();
223
+ /** The maskable fields withheld from the caller, by collection slug. */
224
+ readonly #withheld = new Map<string, Promise<ReadonlySet<string>>>();
225
+
226
+ /**
227
+ * @param actor The call's actor as the family's schema parsed it, or a
228
+ * failed parse. The family's first guard reads it: nothing after that
229
+ * guard sees an actor the schema did not produce.
230
+ */
231
+ constructor(
232
+ private readonly caller: Caller,
233
+ private readonly actor:
234
+ | { readonly ok: true; readonly value: unknown }
235
+ | { readonly ok: false },
236
+ ) {}
237
+
238
+ /**
239
+ * Whether `access` is a call's access whose actor parsed, and `actor` is
240
+ * that parsed value. A context made any other way, or whose actor was
241
+ * swapped after the parse, is refused.
242
+ */
243
+ static parsed(access: unknown, actor: unknown): boolean {
244
+ return (
245
+ access instanceof CallAccess &&
246
+ access.actor.ok &&
247
+ access.actor.value === actor
248
+ );
249
+ }
250
+
251
+ /**
252
+ * The scope of `action` on `collection`: the tenant clause ANDed with the
253
+ * access `Where`. Throws FORBIDDEN when access says no; an unknown action
254
+ * has no function, so it is refused too. A bypass reads across tenants,
255
+ * and a generated write under it is FORBIDDEN.
256
+ */
257
+ async scope<C extends AnyCollection>(
258
+ collection: C,
259
+ action: Action | (string & {}),
260
+ data?: unknown,
261
+ ): Promise<Scope<C['slug']>> {
262
+ const { slug } = collection;
263
+ const tenant = this.#tenantOf(collection);
264
+ // A relation's set writes too: `<relation>.set`. Method names have no dot.
265
+ if (
266
+ tenant === tenancy.bypass &&
267
+ (writes.includes(action) || action.endsWith('.set'))
268
+ ) {
269
+ throw LatticeError.FORBIDDEN();
270
+ }
271
+ const answer = await this.answer(slug, action, data);
272
+ if (answer === false) throw LatticeError.FORBIDDEN();
273
+ if (tenant === tenancy.bypass) this.#logBypass(slug, action);
274
+ return new Scope(
275
+ slug,
276
+ both(
277
+ tenantClause(collection, tenant),
278
+ answer === true ? undefined : answer,
279
+ ),
280
+ typeof tenant === 'string' ? tenant : undefined,
281
+ );
282
+ }
283
+
284
+ /**
285
+ * The maskable fields of `collection` the caller of `access` may not read,
286
+ * asked of `Access.readable` once per call. Empty when nothing is
287
+ * maskable. Static, like `stampOf`, so it is not on `ctx.access`: the
288
+ * family guard and the router call it, and apps do not.
289
+ */
290
+ static withheld(
291
+ access: CallAccess,
292
+ collection: {
293
+ readonly slug: string;
294
+ readonly maskable: readonly string[];
295
+ },
296
+ ): Promise<ReadonlySet<string>> {
297
+ const { slug, maskable } = collection;
298
+ if (maskable.length === 0) return Promise.resolve(new Set());
299
+ let answer = access.#withheld.get(slug);
300
+ if (answer === undefined) {
301
+ answer = access.caller
302
+ .readable(slug, maskable)
303
+ .then(
304
+ (readable) =>
305
+ new Set(maskable.filter((field) => !readable.includes(field))),
306
+ );
307
+ access.#withheld.set(slug, answer);
308
+ }
309
+ return answer;
310
+ }
311
+
312
+ /**
313
+ * The tenant id a generated create stamps on `collection`, without asking
314
+ * access again: the guard did, with the create's data. Undefined for a
315
+ * global collection.
316
+ */
317
+ static stampOf(
318
+ access: CallAccess,
319
+ collection: AnyCollection,
320
+ ): string | undefined {
321
+ const tenant = access.#tenantOf(collection);
322
+ return typeof tenant === 'string' ? tenant : undefined;
323
+ }
324
+
325
+ /** The caller's tenant on `collection`, or undefined when it is global. */
326
+ #tenantOf(collection: AnyCollection): Tenant | undefined {
327
+ if (collection.tenant === undefined) return undefined;
328
+ this.#tenant ??= { value: this.caller.tenant() };
329
+ const { value } = this.#tenant;
330
+ // Fail closed: a null tenant would match rows with no tenant (Mongo's
331
+ // null rule), and an empty one would stamp rows no tenant owns. An app
332
+ // bug, not a client refusal, so a plain Error.
333
+ if (
334
+ value !== tenancy.bypass &&
335
+ (typeof value !== 'string' || value === '')
336
+ ) {
337
+ throw new Error(
338
+ value === undefined
339
+ ? `Lattice: "${collection.slug}" is tenanted, but the family has no tenantOf`
340
+ : `Lattice: tenantOf returned ${JSON.stringify(value) ?? String(value)} for "${collection.slug}"; it must return a non-empty string or tenancy.bypass`,
341
+ );
342
+ }
343
+ return value;
344
+ }
345
+
346
+ #logBypass(slug: string, action: string): void {
347
+ const key = `${slug} ${action}`;
348
+ if (this.#logged.has(key)) return;
349
+ this.#logged.add(key);
350
+ this.caller.bypassed(slug, action);
351
+ }
352
+
353
+ private answer(
354
+ slug: string,
355
+ action: string,
356
+ data: unknown,
357
+ ): Promise<boolean | AnyWhere> {
358
+ if (action === 'create') return this.caller.check(slug, action, data);
359
+ let answers = this.#answers.get(slug);
360
+ if (answers === undefined) {
361
+ answers = new Map();
362
+ this.#answers.set(slug, answers);
363
+ }
364
+ const kept = answers.get(action);
365
+ if (kept !== undefined) return kept;
366
+ const answer = this.caller.check(slug, action, undefined);
367
+ answers.set(action, answer);
368
+ return answer;
369
+ }
370
+ }
371
+
372
+ /**
373
+ * The context of one call. The actor is parsed once, here, with the
374
+ * family's schema, and everything downstream gets the parsed value: access
375
+ * functions, `tenantOf`, `actorId`, the log lines, `execute` and events. So
376
+ * a key the schema strips, or a value it transforms, never reaches them.
377
+ * An actor that does not parse is kept as given, and the family's first
378
+ * guard refuses the call before anything reads it.
379
+ */
380
+ export function familyContext<Actor>(
381
+ access: Access<Actor>,
382
+ base: CallContext<Actor>,
383
+ family: Pick<Family<Actor>, 'actor' | 'actorId' | 'tenantOf'>,
384
+ ): FamilyContext<Actor> {
385
+ const parsed = validate(family.actor, base.actor);
386
+ const actor = parsed.ok ? parsed.value : base.actor;
387
+ const { logger } = base;
388
+ const caller: Caller = {
389
+ check: (collection, action, data) =>
390
+ access.check({
391
+ actor,
392
+ collection,
393
+ action,
394
+ ...(action === 'create' ? { data } : {}),
395
+ }),
396
+ tenant: () => family.tenantOf?.(actor),
397
+ bypassed: (collection, action) =>
398
+ logger.info('tenancy.bypass', {
399
+ actorId: family.actorId(actor),
400
+ collection,
401
+ action,
402
+ tenancy: 'bypass',
403
+ }),
404
+ readable: (collection, fields) =>
405
+ access.readable({ actor, collection, fields }),
406
+ };
407
+ return {
408
+ ...base,
409
+ actor,
410
+ access: new CallAccess(
411
+ caller,
412
+ parsed.ok ? { ok: true, value: actor } : { ok: false },
413
+ ),
414
+ };
415
+ }
416
+
417
+ /** The filter a `Repo` call runs under. A scope for another collection throws. */
418
+ export function whereOf(
419
+ slug: string,
420
+ scope: Scope | typeof unscoped,
421
+ ): AnyWhere | undefined {
422
+ if (scope === unscoped) return undefined;
423
+ if (scope.collection !== slug) {
424
+ throw new Error(
425
+ `Lattice: the "${slug}" repo was given a scope for "${scope.collection}"`,
426
+ );
427
+ }
428
+ return scope.where;
429
+ }