@proteinjs/user 1.13.0 → 1.15.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.
@@ -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'),
@@ -0,0 +1,44 @@
1
+ import { DateTimeColumn, Table } from '@proteinjs/db';
2
+ import { Moment } from 'moment';
3
+ import { ScopedRecord, createScopedIndex, withScopedRecordColumns } from '../ScopedRecord';
4
+ import { USER_PERMISSIONS } from '../permissions';
5
+
6
+ /**
7
+ * LAST ACTIVITY (human presence): the most recent request a signed-in human made through a live
8
+ * interactive session — one row per user (`scope` = their id, unique). This is the ONE owner of
9
+ * "when was this person last here"; admin surfaces that speak "last active" read it.
10
+ *
11
+ * The stamp is keyed on TRANSPORT, not on what the work was: only requests that arrive through
12
+ * the session-cookie request path write it (user-server's UserActivityStamp, invoked from the
13
+ * per-request session-cache build). Machinery acting on a user's behalf — routine ticks,
14
+ * watchers, background flow runs, delegated machine-account work — executes under seeded
15
+ * session contexts (`runInUserScope`) that never traverse that path, so no background actor can
16
+ * ever read as presence; machine accounts are refused by the stamp even though their requests do
17
+ * arrive over real sessions. Deliberately NOT derived from the usage ledger: spend measures
18
+ * model work (which routines rack up all day), not the human being present.
19
+ *
20
+ * Reads are people-management trust ('users', the Users-page permission); writes are
21
+ * system-written only (no service/db write door — the stamp rides the system path), so the
22
+ * record surfaces cannot fabricate presence. Scoped with no retain policy: presence rows purge
23
+ * with the account (the privacy-safe default for a behavioral fact).
24
+ */
25
+ export type UserActivity = ScopedRecord & {
26
+ /** When the user's most recent interactive request arrived (stamp cadence is throttled — see UserActivityStamp). */
27
+ lastActiveAt: Moment;
28
+ };
29
+
30
+ export class UserActivityTable extends Table<UserActivity> {
31
+ name = 'user_activity';
32
+ auth: Table<UserActivity>['auth'] = {
33
+ db: {
34
+ query: { permission: USER_PERMISSIONS.users },
35
+ },
36
+ service: {
37
+ query: { permission: USER_PERMISSIONS.users },
38
+ },
39
+ };
40
+ indexes = [createScopedIndex<UserActivity>({ columns: [], name: 'user_activity_scope_unique', unique: true })];
41
+ columns: Table<UserActivity>['columns'] = withScopedRecordColumns<UserActivity>({
42
+ lastActiveAt: new DateTimeColumn('last_active_at'),
43
+ });
44
+ }
@@ -7,6 +7,7 @@ import { Invite, InviteTable } from './InviteTable';
7
7
  import { AccessInvite, AccessInviteTable } from './AccessInviteTable';
8
8
  import { RoleGrantEvent, RoleGrantEventTable } from './RoleGrantEventTable';
9
9
  import { UserStatusEvent, UserStatusEventTable } from './UserStatusEventTable';
10
+ import { UserActivity, UserActivityTable } from './UserActivityTable';
10
11
 
11
12
  export const tables = {
12
13
  AccessGrant: new AccessGrantTable() as Table<AccessGrant>,
@@ -15,6 +16,7 @@ export const tables = {
15
16
  Invite: new InviteTable() as Table<Invite>,
16
17
  RoleGrantEvent: new RoleGrantEventTable() as Table<RoleGrantEvent>,
17
18
  User: new UserTable() as Table<User>,
19
+ UserActivity: new UserActivityTable() as Table<UserActivity>,
18
20
  UserStatusEvent: new UserStatusEventTable() as Table<UserStatusEvent>,
19
21
  Session: new SessionTable() as Table<Session>,
20
22
  };