@proteinjs/user 1.10.0 → 1.10.1

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 (48) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/src/SharedRecord.d.ts.map +1 -1
  5. package/dist/src/SharedRecord.js +141 -8
  6. package/dist/src/SharedRecord.js.map +1 -1
  7. package/dist/src/services/AccessInviteService.d.ts +5 -1
  8. package/dist/src/services/AccessInviteService.d.ts.map +1 -1
  9. package/dist/src/tables/AccessGrantTable.d.ts +17 -11
  10. package/dist/src/tables/AccessGrantTable.d.ts.map +1 -1
  11. package/dist/src/tables/AccessGrantTable.js +64 -15
  12. package/dist/src/tables/AccessGrantTable.js.map +1 -1
  13. package/dist/src/tables/AccessInviteTable.d.ts +2 -1
  14. package/dist/src/tables/AccessInviteTable.d.ts.map +1 -1
  15. package/dist/src/tables/AccessInviteTable.js +8 -6
  16. package/dist/src/tables/AccessInviteTable.js.map +1 -1
  17. package/dist/src/tables/RoleGrantEventTable.d.ts +1 -10
  18. package/dist/src/tables/RoleGrantEventTable.d.ts.map +1 -1
  19. package/dist/src/tables/RoleGrantEventTable.js.map +1 -1
  20. package/dist/src/tables/SessionTable.d.ts +1 -10
  21. package/dist/src/tables/SessionTable.d.ts.map +1 -1
  22. package/dist/src/tables/SessionTable.js.map +1 -1
  23. package/dist/src/tables/UserStatusEventTable.d.ts +1 -9
  24. package/dist/src/tables/UserStatusEventTable.d.ts.map +1 -1
  25. package/dist/src/tables/UserStatusEventTable.js.map +1 -1
  26. package/dist/test/CapabilityEnforcement.test.d.ts +47 -0
  27. package/dist/test/CapabilityEnforcement.test.d.ts.map +1 -0
  28. package/dist/test/CapabilityEnforcement.test.js +649 -0
  29. package/dist/test/CapabilityEnforcement.test.js.map +1 -0
  30. package/dist/test/ClientRootCreationBootstrap.test.d.ts +36 -0
  31. package/dist/test/ClientRootCreationBootstrap.test.d.ts.map +1 -0
  32. package/dist/test/ClientRootCreationBootstrap.test.js +330 -0
  33. package/dist/test/ClientRootCreationBootstrap.test.js.map +1 -0
  34. package/dist/test/ScopedRecord.test.d.ts +1 -8
  35. package/dist/test/ScopedRecord.test.d.ts.map +1 -1
  36. package/dist/test/ScopedRecord.test.js.map +1 -1
  37. package/generated/index.ts +1 -1
  38. package/package.json +8 -8
  39. package/src/SharedRecord.ts +127 -16
  40. package/src/services/AccessInviteService.ts +5 -1
  41. package/src/tables/AccessGrantTable.ts +78 -11
  42. package/src/tables/AccessInviteTable.ts +17 -5
  43. package/src/tables/RoleGrantEventTable.ts +1 -1
  44. package/src/tables/SessionTable.ts +1 -1
  45. package/src/tables/UserStatusEventTable.ts +1 -1
  46. package/test/CapabilityEnforcement.test.ts +421 -0
  47. package/test/ClientRootCreationBootstrap.test.ts +205 -0
  48. package/test/ScopedRecord.test.ts +1 -1
@@ -0,0 +1,205 @@
1
+ import { UserRepo } from '../src/UserRepo';
2
+
3
+ import moment from 'moment';
4
+ import { Db, QueryBuilderFactory, Reference, StringColumn, Table, Transaction, getDbAsSystem } from '@proteinjs/db';
5
+ import { KnexDriver } from '@proteinjs/db-driver-knex';
6
+ import { SharedRecord, withSharedRecordColumns } from '../src/SharedRecord';
7
+ import { AccessGrant, AccessGrantTable } from '../src/tables/AccessGrantTable';
8
+ import { Session, SessionData, SessionDataStorage } from '@proteinjs/server-api';
9
+ import { SourceRepository } from '@proteinjs/reflection';
10
+ import { tables } from '../src/tables/tables';
11
+
12
+ /**
13
+ * Browser-path root creation (the 2026-08-22 release blocker). A NEW root shared record created
14
+ * from the BROWSER rides the client `Transaction` queue, and `Transaction.insert` applies column
15
+ * defaults CLIENT-SIDE — in an environment with no `DefaultDbDriverFactory` (the browser has no
16
+ * driver; `new Db()` throws). The escalation fix moved the owner-grant bootstrap into the
17
+ * `permissionSource` defaultValue as a `getDbAsSystem()` insert, which made the default IMPURE and
18
+ * broke every browser root creation with "Unable to find a @proteinjs/db/DefaultDbDriverFactory
19
+ * implementation".
20
+ *
21
+ * The floor pinned here: the column default is PURE (client-side default application needs no db),
22
+ * and the owner-grant bootstrap runs SERVER-SIDE on the insert path — so the whole client flow
23
+ * (queue with defaults in a driverless context, then run the ops server-side) succeeds AND ends
24
+ * with exactly one platform-conferred owner grant.
25
+ *
26
+ * Outcome bar: assertions are against persisted rows and grant state read back as system.
27
+ */
28
+
29
+ export interface ClientRootItem extends SharedRecord {
30
+ name: string;
31
+ }
32
+
33
+ class TestSessionDataStorage implements SessionDataStorage {
34
+ environment = 'node' as 'node';
35
+ static SESSION_DATA: { [id: string]: SessionData } = {};
36
+ setData(data: SessionData) {
37
+ TestSessionDataStorage.SESSION_DATA['sessionData'] = data;
38
+ }
39
+ getData(): SessionData {
40
+ return TestSessionDataStorage.SESSION_DATA['sessionData'];
41
+ }
42
+ }
43
+
44
+ const users = [0, 1].map((i) => ({
45
+ name: `Test user${i}`,
46
+ email: `test.user${i}`,
47
+ password: 'test',
48
+ emailVerified: false,
49
+ roles: [] as string[],
50
+ created: moment(),
51
+ updated: moment(),
52
+ id: `user${i}`,
53
+ }));
54
+
55
+ export class ClientRootItemTable extends Table<ClientRootItem> {
56
+ name = 'user_test_client_root_item';
57
+ auth: Table<ClientRootItem>['auth'] = {
58
+ db: { all: 'authenticated' },
59
+ service: { all: 'authenticated' },
60
+ };
61
+ columns = withSharedRecordColumns<ClientRootItem>({
62
+ name: new StringColumn('name'),
63
+ });
64
+ }
65
+
66
+ const dbDriver = new KnexDriver({ host: 'localhost', user: 'root', password: '', dbName: 'test' });
67
+ const userRepo = new UserRepo();
68
+ const clientRootItemTable = new ClientRootItemTable() as Table<ClientRootItem>;
69
+
70
+ const dropTable = async (table: Table<any>) => {
71
+ if (await dbDriver.getKnex().schema.withSchema(dbDriver.getDbName()).hasTable(table.name)) {
72
+ await dbDriver.getKnex().schema.withSchema(dbDriver.getDbName()).dropTable(table.name);
73
+ }
74
+ };
75
+
76
+ const runAs = (userIndex: number) => userRepo.setUser(users[userIndex]);
77
+
78
+ const grantsFor = async (userId: string, resourceId: string): Promise<AccessGrant[]> => {
79
+ const qb = new QueryBuilderFactory()
80
+ .getQueryBuilder(tables.AccessGrant)
81
+ .condition({ field: 'principal', operator: '=', value: userId })
82
+ .condition({ field: 'resource', operator: '=', value: resourceId })
83
+ .condition({ field: 'resourceTable', operator: '=', value: clientRootItemTable.name });
84
+ return await getDbAsSystem().query(tables.AccessGrant, qb);
85
+ };
86
+
87
+ /**
88
+ * The browser has no `DefaultDbDriverFactory`: any code path that constructs a `Db` during
89
+ * client-side default application dies with this exact error (Db.getDefaultDbDriver). Mock the
90
+ * static resolver to throw it, run `fn`, restore the server driver.
91
+ */
92
+ const inDriverlessClientContext = async <T>(fn: () => Promise<T>): Promise<T> => {
93
+ jest.spyOn(Db, 'getDefaultDbDriver').mockImplementation(() => {
94
+ throw new Error(
95
+ `Unable to find a @proteinjs/db/DefaultDbDriverFactory implementation. Either implement DefaultDbDriverFactory or pass in a db driver when instantiating Db.`
96
+ );
97
+ });
98
+ try {
99
+ return await fn();
100
+ } finally {
101
+ jest.spyOn(Db, 'getDefaultDbDriver').mockImplementation(() => dbDriver);
102
+ }
103
+ };
104
+
105
+ describe('Client-path root creation owner-grant bootstrap', () => {
106
+ beforeAll(async () => {
107
+ (SourceRepository.get() as any).objectCache['@proteinjs/db/DefaultDbDriverFactory'] = [
108
+ { getDbDriver: () => dbDriver },
109
+ ];
110
+ (SourceRepository.get() as any).objectCache['@proteinjs/server-api/SessionDataStorage'] = [
111
+ new TestSessionDataStorage(),
112
+ ];
113
+ (SourceRepository.get() as any).objectCache['@proteinjs/db/Table'] = [tables.AccessGrant, clientRootItemTable];
114
+ (SourceRepository.get() as any).objectCache['@proteinjs/user-auth/AuthenticatedUserRepo'] = [userRepo];
115
+
116
+ Session.setData({ sessionId: 'test-session', user: 'guest', data: {} });
117
+ runAs(0);
118
+
119
+ if (dbDriver.start) {
120
+ await dbDriver.start();
121
+ }
122
+
123
+ jest.spyOn(Db, 'getDefaultDbDriver').mockImplementation(() => dbDriver);
124
+ });
125
+
126
+ beforeEach(async () => {
127
+ await dbDriver.getTableManager().loadTable(clientRootItemTable);
128
+ await dbDriver.getTableManager().loadTable(tables.AccessGrant);
129
+ });
130
+
131
+ afterEach(async () => {
132
+ await dropTable(clientRootItemTable);
133
+ await dropTable(new AccessGrantTable());
134
+ });
135
+
136
+ afterAll(() => {
137
+ if (dbDriver.stop) {
138
+ dbDriver.stop();
139
+ }
140
+ });
141
+
142
+ it('a driverless client Transaction insert succeeds and the owner grant lands server-side, exactly once', async () => {
143
+ runAs(0);
144
+
145
+ // CLIENT PHASE — the browser: queue the root insert; Transaction.insert applies column
146
+ // defaults right here, with NO db driver resolvable. The release regression died on this
147
+ // await (the permissionSource default called getDbAsSystem()).
148
+ const transaction = new Transaction();
149
+ const queued = await inDriverlessClientContext(
150
+ async () => await transaction.insert(clientRootItemTable, { name: 'root from browser' } as any)
151
+ );
152
+ expect(queued.id).toBeDefined();
153
+
154
+ // No grant may exist yet — the bootstrap is a SERVER-side act; a client-side mint would mean
155
+ // the default is still impure.
156
+ expect(await grantsFor(users[0].id, queued.id)).toHaveLength(0);
157
+
158
+ // SERVER PHASE — run the queued ops the way TransactionRunner does (driver restored).
159
+ await transaction.run();
160
+
161
+ // OUTCOMES: the row exists, and the creator holds exactly one platform-conferred owner grant.
162
+ const persisted = await getDbAsSystem().get(clientRootItemTable, { id: queued.id });
163
+ expect(persisted?.name).toBe('root from browser');
164
+
165
+ const grants = await grantsFor(users[0].id, queued.id);
166
+ expect(grants.map((grant) => grant.accessLevel)).toEqual(['owner']);
167
+ });
168
+
169
+ it('PIN — the row-injection guard still refuses a non-root insert into a foreign scope on the client path', async () => {
170
+ runAs(0);
171
+ const victim = await transactionalInsert({ name: 'user0 root' });
172
+
173
+ // user1 queues an insert that points its permissionSource at user0's root — the client
174
+ // Transaction path must be refused server-side exactly like the direct path (HOLE 2 pin).
175
+ runAs(1);
176
+ const injectionTx = new Transaction();
177
+ await inDriverlessClientContext(
178
+ async () =>
179
+ await injectionTx.insert(clientRootItemTable, {
180
+ name: 'injected row',
181
+ permissionSource: new Reference(clientRootItemTable.name, victim.id),
182
+ } as any)
183
+ );
184
+
185
+ await expect(injectionTx.run()).rejects.toThrow();
186
+
187
+ const rowsInVictimScope = await getDbAsSystem().query(clientRootItemTable, {
188
+ permissionSource: victim.id,
189
+ } as any);
190
+ expect(rowsInVictimScope.map((r: any) => r.name)).not.toContain('injected row');
191
+
192
+ // And no grant of any kind landed for user1.
193
+ expect(await grantsFor(users[1].id, victim.id)).toHaveLength(0);
194
+ });
195
+
196
+ /** Full client flow: queue driverless, run server-side, return the inserted record. */
197
+ const transactionalInsert = async (record: Partial<ClientRootItem>): Promise<ClientRootItem> => {
198
+ const transaction = new Transaction();
199
+ const queued = await inDriverlessClientContext(
200
+ async () => await transaction.insert(clientRootItemTable, record as any)
201
+ );
202
+ await transaction.run();
203
+ return queued as ClientRootItem;
204
+ };
205
+ });
@@ -19,7 +19,7 @@ export class FavoriteTable extends Table<Favorite> {
19
19
  db: { all: 'public' },
20
20
  service: { all: 'public' },
21
21
  };
22
- columns = withRecordColumns<Favorite>({
22
+ columns: Table<Favorite>['columns'] = withRecordColumns<Favorite>({
23
23
  name: new StringColumn('name'),
24
24
  scope: new StringColumn('scope', {
25
25
  defaultValue: async (table: any, favorite: Favorite) =>