@proteinjs/user 1.14.0 → 1.16.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 (38) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/src/SharedScopeKeyOwners.d.ts +91 -0
  9. package/dist/src/SharedScopeKeyOwners.d.ts.map +1 -0
  10. package/dist/src/SharedScopeKeyOwners.js +282 -0
  11. package/dist/src/SharedScopeKeyOwners.js.map +1 -0
  12. package/dist/src/tables/AccessGrantTable.d.ts.map +1 -1
  13. package/dist/src/tables/AccessGrantTable.js +7 -0
  14. package/dist/src/tables/AccessGrantTable.js.map +1 -1
  15. package/dist/src/tables/InviteTable.d.ts +7 -0
  16. package/dist/src/tables/InviteTable.d.ts.map +1 -1
  17. package/dist/src/tables/InviteTable.js +11 -0
  18. package/dist/src/tables/InviteTable.js.map +1 -1
  19. package/dist/src/tables/SessionTable.d.ts +7 -0
  20. package/dist/src/tables/SessionTable.d.ts.map +1 -1
  21. package/dist/src/tables/SessionTable.js +11 -0
  22. package/dist/src/tables/SessionTable.js.map +1 -1
  23. package/dist/src/tables/UserTable.d.ts +3 -1
  24. package/dist/src/tables/UserTable.d.ts.map +1 -1
  25. package/dist/src/tables/UserTable.js.map +1 -1
  26. package/dist/test/recordTableDeclarations.test.d.ts +2 -0
  27. package/dist/test/recordTableDeclarations.test.d.ts.map +1 -0
  28. package/dist/test/recordTableDeclarations.test.js +39 -0
  29. package/dist/test/recordTableDeclarations.test.js.map +1 -0
  30. package/generated/index.ts +1 -1
  31. package/index.ts +1 -0
  32. package/package.json +3 -3
  33. package/src/SharedScopeKeyOwners.ts +237 -0
  34. package/src/tables/AccessGrantTable.ts +7 -0
  35. package/src/tables/InviteTable.ts +11 -0
  36. package/src/tables/SessionTable.ts +11 -0
  37. package/src/tables/UserTable.ts +3 -1
  38. package/test/recordTableDeclarations.test.ts +34 -0
@@ -0,0 +1,237 @@
1
+ import { DataEncryptionKeyTable, QueryBuilder, Reference, Table, getDbAsSystem } from '@proteinjs/db';
2
+ import type { DataEncryptionKey, DbEncryptionConfig } from '@proteinjs/db';
3
+
4
+ import { AccessGrant } from './tables/AccessGrantTable';
5
+ import { isSharedTable, skipAccessGrantsEnabled } from './SharedRecord';
6
+ import { UserRepo } from './UserRepo';
7
+ import { tables } from './tables/tables';
8
+
9
+ /** One resolved scope-root owner, cached briefly (see `SharedScopeKeyOwners`). */
10
+ interface OwnerCacheEntry {
11
+ cachedAt: number;
12
+ owner: string;
13
+ }
14
+
15
+ /**
16
+ * The sharing-aware half of the column-encryption key model (TRUST_AND_COMPLIANCE §4/§4.4;
17
+ * SHARING_EXPANSION §3): rows in a shared permission scope are keyed by the SCOPE-ROOT
18
+ * OWNER's data key, and a reader's encrypted-search fingerprints fan out over the owners
19
+ * sharing content into their view. Compose an instance into the app's `DbEncryptionConfig`:
20
+ *
21
+ * ```ts
22
+ * const keyOwners = new SharedScopeKeyOwners();
23
+ * const config: DbEncryptionConfig = {
24
+ * masterKeyProvider,
25
+ * resolveKeyOwner: (args) => keyOwners.resolveKeyOwner(args),
26
+ * getAccessibleKeyOwners: (args) => keyOwners.getAccessibleKeyOwners(args),
27
+ * };
28
+ * ```
29
+ *
30
+ * Design facts this class is the single owner of:
31
+ *
32
+ * - **Owner-keyed shared scopes.** A `SharedRecord` row's key owner is the principal of the
33
+ * EARLIEST `owner` grant on its permission source (creation order; the creator). A
34
+ * contributor's write into someone else's document is keyed by the DOCUMENT owner, never
35
+ * the writer — so crypto-shred agrees exactly with the account-deletion purge walker,
36
+ * which drains shared trees grant-derived (by owned permission sources, never by the
37
+ * writer's scope): the rows a deletion removes and the rows a shred unreads are the same
38
+ * set. Keys are NOT access control — whether a reader may see a row is the permission
39
+ * layer's decision; revoking a share revokes access without re-encrypting anything.
40
+ * - **Root birth.** A scope root's owner grant is minted only after its insert lands
41
+ * (`SharedRecord.onAfterInsert`), so a root insert that touches encrypted columns resolves
42
+ * the creator (the session user) directly — the same identity the grant is about to name.
43
+ * - **Accessible owners = self + every OTHER owner-grant principal on resources the caller
44
+ * holds any grant on.** Resource-agnostic (thought, chat, space — whatever rides
45
+ * AccessGrant) and bounded by how much is shared with the caller. This includes conferred
46
+ * co-owners in both directions. Computed fresh per query — a revoked share drops out of
47
+ * the fan-out immediately (the permission layer already refused the rows themselves).
48
+ * - **System queries** (`runAsSystem`) search under EVERY key owner (the
49
+ * `data_encryption_key` owner set): an unscoped query silently missing rows of
50
+ * inaccessible owners would be a wrong answer, not a degraded one. Rare by design;
51
+ * cost scales with the owner count, correctness does not.
52
+ * - **Non-shared tables fall through** (`resolveKeyOwner` returns undefined): the framework
53
+ * default — the row's `scope` column — already IS the scope owner for ScopedRecord tables.
54
+ *
55
+ * Named limitation (owner transfer): after a full ownership transfer (a conferred owner
56
+ * grant plus deletion of the original owner's), NEW writes key under the new owner while
57
+ * historical rows keep their old envelopes. Readers whose grant set no longer reaches the
58
+ * old owner can still read those rows (envelopes are self-describing) but search fan-out no
59
+ * longer covers them; a lifecycle re-encrypt walk over the tree converges the envelopes to
60
+ * the current owner.
61
+ */
62
+ export class SharedScopeKeyOwners {
63
+ /** Scope-root owner cache TTL — bounds cross-process staleness after an ownership transfer. */
64
+ private static readonly OWNER_TTL_MS = 60 * 1000;
65
+ private static readonly OWNER_CACHE_MAX_ENTRIES = 10_000;
66
+ private static readonly OWNER_CACHE_GLOBAL_KEY = '__proteinjs_user_sharedScopeOwnerCache';
67
+
68
+ /**
69
+ * The data-key owner for a `SharedRecord` row being written: the earliest `owner`-grant
70
+ * principal on the row's permission source, or the session user for a scope-root birth
71
+ * (whose grant is minted post-DML). Returns undefined for non-shared tables and for rows
72
+ * whose owner cannot be resolved — the framework then falls through to the row's `scope`
73
+ * value or refuses the write loudly (`EncryptionRecordHooks.resolveKeyOwnerForWrite`).
74
+ */
75
+ async resolveKeyOwner(args: { table: Table<any>; record: any }): Promise<string | undefined> {
76
+ const { table, record } = args;
77
+ if (!isSharedTable(table)) {
78
+ return undefined;
79
+ }
80
+
81
+ const sourceId = this.referenceId(record?.permissionSource);
82
+ const sourceTable: string = record?.permissionSourceTable ?? table.name;
83
+ if (!sourceId) {
84
+ return undefined;
85
+ }
86
+
87
+ if (skipAccessGrantsEnabled()) {
88
+ // Grant machinery is off (test environments): the only resolvable owner is the caller.
89
+ return new UserRepo().getUser().id || undefined;
90
+ }
91
+
92
+ const cacheKey = `${sourceTable}:${sourceId}`;
93
+ const cached = this.ownerCache().get(cacheKey);
94
+ if (cached && Date.now() - cached.cachedAt < SharedScopeKeyOwners.OWNER_TTL_MS) {
95
+ return cached.owner;
96
+ }
97
+
98
+ const owner = await this.scopeRootOwner(sourceId, sourceTable);
99
+ if (owner) {
100
+ this.cacheOwner(cacheKey, owner);
101
+ return owner;
102
+ }
103
+
104
+ // Scope-root birth: the row IS its own permission source and its owner grant does not
105
+ // exist yet — the creator (session user) is the owner that grant is about to name. Not
106
+ // cached: the authoritative grant lands post-DML.
107
+ if (sourceId === record?.id && sourceTable === table.name) {
108
+ return new UserRepo().getUser().id || undefined;
109
+ }
110
+
111
+ return undefined;
112
+ }
113
+
114
+ /**
115
+ * The key owners whose rows the current caller's encrypted searches must cover (see the
116
+ * class doc for the definition). Loud refusal when no caller identity exists on a
117
+ * non-system query: returning an empty set would make the search silently match nothing.
118
+ */
119
+ async getAccessibleKeyOwners(args: { runAsSystem: boolean }): Promise<string[]> {
120
+ if (args.runAsSystem) {
121
+ return await this.allKeyOwners();
122
+ }
123
+
124
+ const callerId = new UserRepo().getUser().id;
125
+ if (!callerId) {
126
+ throw new Error(
127
+ `Cannot search encrypted columns without a caller identity: no session user is present. ` +
128
+ `System-context searches cover all key owners; caller-context searches require a signed-in user.`
129
+ );
130
+ }
131
+
132
+ if (skipAccessGrantsEnabled()) {
133
+ return [callerId];
134
+ }
135
+ // Every OTHER owner-grant principal on resources the caller holds any grant on — the
136
+ // same subquery shape SharedRecord's access filter uses, inverted onto the owner side.
137
+ const callerResources = new QueryBuilder(tables.AccessGrant.name);
138
+ callerResources.select({ fields: ['resource'] });
139
+ callerResources.condition({ field: 'principal', operator: '=', value: callerId });
140
+
141
+ const qb = new QueryBuilder(tables.AccessGrant.name);
142
+ qb.condition({ field: 'accessLevel', operator: '=', value: 'owner' });
143
+ qb.condition({ field: 'principal', operator: '!=', value: callerId });
144
+ qb.condition({ field: 'resource', operator: 'IN', value: callerResources });
145
+ const otherOwnerGrants = await getDbAsSystem<AccessGrant>().query(tables.AccessGrant, qb);
146
+
147
+ const owners = new Set<string>([callerId]);
148
+ for (const grant of otherOwnerGrants) {
149
+ const principalId = this.referenceId(grant.principal);
150
+ if (principalId) {
151
+ owners.add(principalId);
152
+ }
153
+ }
154
+
155
+ return Array.from(owners);
156
+ }
157
+
158
+ /**
159
+ * The earliest `owner`-grant principal on a permission source — the scope-root owner.
160
+ * Earliest by creation (id tiebreak) so a document with conferred co-owners still keys
161
+ * deterministically by its original owner.
162
+ */
163
+ private async scopeRootOwner(sourceId: string, sourceTable: string): Promise<string | undefined> {
164
+ const qb = new QueryBuilder(tables.AccessGrant.name);
165
+ qb.condition({ field: 'resource', operator: '=', value: sourceId });
166
+ qb.condition({ field: 'resourceTable', operator: '=', value: sourceTable });
167
+ qb.condition({ field: 'accessLevel', operator: '=', value: 'owner' });
168
+ const grants = await getDbAsSystem<AccessGrant>().query(tables.AccessGrant, qb);
169
+ if (grants.length === 0) {
170
+ return undefined;
171
+ }
172
+
173
+ const earliest = grants.reduce((best, candidate) => {
174
+ const bestCreated = best.created?.valueOf() ?? 0;
175
+ const candidateCreated = candidate.created?.valueOf() ?? 0;
176
+ if (candidateCreated !== bestCreated) {
177
+ return candidateCreated < bestCreated ? candidate : best;
178
+ }
179
+ return candidate.id < best.id ? candidate : best;
180
+ });
181
+ return this.referenceId(earliest.principal);
182
+ }
183
+
184
+ /** Every key owner that exists — the distinct `data_encryption_key` owner set. */
185
+ private async allKeyOwners(): Promise<string[]> {
186
+ const keyTable = new DataEncryptionKeyTable() as Table<DataEncryptionKey>;
187
+ const rows = await getDbAsSystem<DataEncryptionKey>().query(keyTable, {} as Partial<DataEncryptionKey>);
188
+ return Array.from(new Set(rows.map((row) => row.owner)));
189
+ }
190
+
191
+ /** The id inside a `Reference`-or-string field, or undefined. */
192
+ private referenceId(value: Reference<any> | string | undefined | null): string | undefined {
193
+ if (!value) {
194
+ return undefined;
195
+ }
196
+ if (typeof value === 'string') {
197
+ return value;
198
+ }
199
+ return value._id || undefined;
200
+ }
201
+
202
+ /**
203
+ * Cache on the global object (the duplicate-module pattern — see `setSkipAccessGrants`):
204
+ * per-package installs put multiple live copies of this class in one process, and the
205
+ * scope-root owner must be one answer across all of them.
206
+ */
207
+ private ownerCache(): Map<string, OwnerCacheEntry> {
208
+ const globalObject = globalThis as any;
209
+ if (!globalObject[SharedScopeKeyOwners.OWNER_CACHE_GLOBAL_KEY]) {
210
+ globalObject[SharedScopeKeyOwners.OWNER_CACHE_GLOBAL_KEY] = new Map<string, OwnerCacheEntry>();
211
+ }
212
+ return globalObject[SharedScopeKeyOwners.OWNER_CACHE_GLOBAL_KEY];
213
+ }
214
+
215
+ private cacheOwner(cacheKey: string, owner: string) {
216
+ const cache = this.ownerCache();
217
+ if (cache.size >= SharedScopeKeyOwners.OWNER_CACHE_MAX_ENTRIES) {
218
+ cache.clear();
219
+ }
220
+ cache.set(cacheKey, { cachedAt: Date.now(), owner });
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Type-level check that the two methods satisfy the framework seams they compose into —
226
+ * a drifted signature fails compilation here, not at an app's config site.
227
+ */
228
+ type _ResolveKeyOwnerSeam = NonNullable<DbEncryptionConfig['resolveKeyOwner']>;
229
+ type _GetAccessibleKeyOwnersSeam = NonNullable<DbEncryptionConfig['getAccessibleKeyOwners']>;
230
+ const _seamCheck: {
231
+ resolveKeyOwner: _ResolveKeyOwnerSeam;
232
+ getAccessibleKeyOwners: _GetAccessibleKeyOwnersSeam;
233
+ } = {
234
+ resolveKeyOwner: (args) => new SharedScopeKeyOwners().resolveKeyOwner(args),
235
+ getAccessibleKeyOwners: (args) => new SharedScopeKeyOwners().getAccessibleKeyOwners(args),
236
+ };
237
+ void _seamCheck;
@@ -82,6 +82,13 @@ export class AccessGrantTable extends Table<AccessGrant> {
82
82
  name: 'idx_ag_principal_table_level_resource',
83
83
  columns: ['principal', 'resourceTable', 'accessLevel', 'resource'] satisfies (keyof AccessGrant)[],
84
84
  },
85
+ // The resource-side axis: scope-root owner resolution (SharedScopeKeyOwners — per
86
+ // encrypted write into a shared scope) and outbound-grant enumeration (deletion
87
+ // manifests, rosters) look grants up BY RESOURCE; without this they scan.
88
+ {
89
+ name: 'idx_ag_resource_level_principal',
90
+ columns: ['resource', 'accessLevel', 'principal'] satisfies (keyof AccessGrant)[],
91
+ },
85
92
  ];
86
93
  columns: Table<AccessGrant>['columns'] = withRecordColumns<AccessGrant>({
87
94
  accessLevel: new StringColumn('access_level'),
@@ -38,6 +38,17 @@ export class InviteTable extends Table<Invite> {
38
38
  delete: { permission: USER_PERMISSIONS.users },
39
39
  },
40
40
  };
41
+ /**
42
+ * The row scan: who's invited, by whom, until when. The redeemable `token` is auth material
43
+ * with no business in a row scan (founder admin review, v1.22 — also a hygiene win); it stays
44
+ * on the record form for the odd support case. The doors above (no insert) already mean the
45
+ * generic surfaces derive no create affordance — invites are minted by SignupService.sendInvite.
46
+ */
47
+ ui: Table<Invite>['ui'] = {
48
+ recordTable: {
49
+ columns: ['email', 'invitedBy', 'tokenExpiresAt'],
50
+ },
51
+ };
41
52
  columns = withRecordColumns<Invite>({
42
53
  email: new StringColumn('email', {}, 250),
43
54
  token: new StringColumn('token'),
@@ -24,6 +24,17 @@ export class SessionTable extends Table<Session> {
24
24
  query: { permission: USER_PERMISSIONS.sessions },
25
25
  },
26
26
  };
27
+ /**
28
+ * The row scan: whose session, when it dies, which one. The serialized session blob (cookie
29
+ * material) has no business in a row scan (founder admin review, v1.22) — it stays on the
30
+ * record form for 'sessions' holders. The query-only doors above already mean the generic
31
+ * surfaces derive no create/delete affordances here (rows are system-written).
32
+ */
33
+ ui: Table<Session>['ui'] = {
34
+ recordTable: {
35
+ columns: ['userEmail', 'expires', 'sessionId'],
36
+ },
37
+ };
27
38
  columns: Table<Session>['columns'] = withRecordColumns<Session>({
28
39
  sessionId: new StringColumn('session_id'),
29
40
  session: new StringColumn('serialized_session', {}, 4000),
@@ -53,7 +53,9 @@ export type User = SourceRecord & {
53
53
  * Account standing. Written ONLY by the SetUserStatus service (audited per change). New rows
54
54
  * default to 'active'; rows predating the column read null, which every gate treats as active —
55
55
  * only an explicit 'deactivated' is refused (authentication and session resolution both gate on
56
- * it in @proteinjs/user-server).
56
+ * it in @proteinjs/user-server). The legacy null state is retired by the
57
+ * BackfillUserStatusActive migration (@proteinjs/user-server), so deployed rows read a real
58
+ * value; the gates' null-tolerant reading stays as the contract for any not-yet-migrated env.
57
59
  */
58
60
  status?: UserStatus | null;
59
61
  /** When the user asked for their account to be deleted. Written by the account-deletion flow only. */
@@ -0,0 +1,34 @@
1
+ import { InviteTable } from '../src/tables/InviteTable';
2
+ import { SessionTable } from '../src/tables/SessionTable';
3
+
4
+ /**
5
+ * The admin row-scan declarations (founder admin review, v1.22): what the generic record table
6
+ * renders for invites and sessions is DECLARED here (Table.ui.recordTable.columns — db-ui
7
+ * renders what tables declare). Two pins with teeth:
8
+ * - the invite row scan never carries the redeemable `token` (auth material; hygiene) — it
9
+ * stays on the record form;
10
+ * - the session row scan never carries the serialized session blob (cookie material).
11
+ * Every declared name must be a real column property, so a schema rename cannot silently
12
+ * strand the declaration.
13
+ */
14
+ describe('admin row-scan declarations', () => {
15
+ it('invite rows: who, by whom, until when — never the token', () => {
16
+ const table = new InviteTable();
17
+ const declared = table.ui?.recordTable?.columns;
18
+ expect(declared).toEqual(['email', 'invitedBy', 'tokenExpiresAt']);
19
+ expect(declared).not.toContain('token');
20
+ for (const column of declared!) {
21
+ expect((table.columns as any)[column]).toBeDefined();
22
+ }
23
+ });
24
+
25
+ it('session rows: whose, when it dies, which one — never the serialized session', () => {
26
+ const table = new SessionTable();
27
+ const declared = table.ui?.recordTable?.columns;
28
+ expect(declared).toEqual(['userEmail', 'expires', 'sessionId']);
29
+ expect(declared).not.toContain('session');
30
+ for (const column of declared!) {
31
+ expect((table.columns as any)[column]).toBeDefined();
32
+ }
33
+ });
34
+ });