@proteinjs/user-server 1.24.5 → 1.26.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 (32) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/generated/index.d.ts.map +1 -1
  3. package/dist/generated/index.js +3 -1
  4. package/dist/generated/index.js.map +1 -1
  5. package/dist/src/migrations/BackfillUserRolesArray.d.ts +8 -5
  6. package/dist/src/migrations/BackfillUserRolesArray.d.ts.map +1 -1
  7. package/dist/src/migrations/BackfillUserRolesArray.js +8 -5
  8. package/dist/src/migrations/BackfillUserRolesArray.js.map +1 -1
  9. package/dist/src/migrations/RetireLegacyUserRolesColumn.d.ts +42 -0
  10. package/dist/src/migrations/RetireLegacyUserRolesColumn.d.ts.map +1 -0
  11. package/dist/src/migrations/RetireLegacyUserRolesColumn.js +136 -0
  12. package/dist/src/migrations/RetireLegacyUserRolesColumn.js.map +1 -0
  13. package/dist/src/routes/devLogin.d.ts +3 -1
  14. package/dist/src/routes/devLogin.d.ts.map +1 -1
  15. package/dist/src/routes/devLogin.js +5 -2
  16. package/dist/src/routes/devLogin.js.map +1 -1
  17. package/dist/src/routes/devLoopDoorsOpen.d.ts +13 -0
  18. package/dist/src/routes/devLoopDoorsOpen.d.ts.map +1 -0
  19. package/dist/src/routes/devLoopDoorsOpen.js +17 -0
  20. package/dist/src/routes/devLoopDoorsOpen.js.map +1 -0
  21. package/dist/test/BackfillUserRolesArray.integration.test.js +174 -9
  22. package/dist/test/BackfillUserRolesArray.integration.test.js.map +1 -1
  23. package/dist/test/DevLogin.test.js +50 -2
  24. package/dist/test/DevLogin.test.js.map +1 -1
  25. package/generated/index.ts +3 -1
  26. package/package.json +5 -5
  27. package/src/migrations/BackfillUserRolesArray.ts +8 -5
  28. package/src/migrations/RetireLegacyUserRolesColumn.ts +66 -0
  29. package/src/routes/devLogin.ts +5 -2
  30. package/src/routes/devLoopDoorsOpen.ts +12 -0
  31. package/test/BackfillUserRolesArray.integration.test.ts +79 -5
  32. package/test/DevLogin.test.ts +32 -2
@@ -0,0 +1,66 @@
1
+ import { Db, Migration, SourceRecordLoader, tables as dbTables } from '@proteinjs/db';
2
+ import { tables } from '@proteinjs/user';
3
+ import { Logger } from '@proteinjs/logger';
4
+
5
+ /**
6
+ * Retires the legacy `user.roles` text column's data. The cutover to the typed `role_list` array
7
+ * (BackfillUserRolesArray) left the old comma-text column physically present and undeclared, its
8
+ * cells intact on every pre-cutover row: a stored key that is also the property's name (`roles`),
9
+ * riding every read of the table. The row reader seats a cell by its declared column name alone
10
+ * (@proteinjs/db ≥ 1.55.0), so the cell is inert — but data no declared column owns has no
11
+ * business on the row. This NULLs it wherever the typed column already carries the roles, or the
12
+ * legacy cell holds nothing to carry (the empty string a pre-cutover signup wrote).
13
+ *
14
+ * Never a legacy value the backfill has not consumed: a row with legacy text and no `role_list`
15
+ * is left for BackfillUserRolesArray — this migration cannot run ahead of it by construction.
16
+ *
17
+ * Idempotent by shape: a NULLed cell no longer matches. Automated (the deploy-gated series); the
18
+ * column itself goes in a later `manual` migration (a destructive contraction), once every
19
+ * environment reads zero legacy cells. Raw SQL through the driver on both sides, as the backfill
20
+ * reads it: the column is undeclared, so the ORM neither reads nor writes it. A database whose
21
+ * user table never had the column (a fresh install) is a clean no-op.
22
+ */
23
+ export class RetireLegacyUserRolesColumn implements SourceRecordLoader<Migration> {
24
+ table = dbTables.Migration;
25
+ record = {
26
+ id: '2f6c0b9e-9c7a-4e0d-8f1b-5a3d7c2e9b41',
27
+ description: `Retire the legacy comma-text user.roles column's cells once role_list carries the roles`,
28
+ estimate: async () => {
29
+ if (!(await this.legacyColumnExists())) {
30
+ return { units: 0, unit: 'rows', note: 'no legacy roles column on the user table' };
31
+ }
32
+
33
+ const counted = (await Db.getDefaultDbDriver().runQuery(() => ({
34
+ sql: `SELECT COUNT(*) AS pending FROM ${tables.User.name} WHERE ${this.retirableCells()}`,
35
+ }))) as unknown as Array<{ pending: number | string }>;
36
+ return { units: Number(counted[0]?.pending ?? 0), unit: 'rows' };
37
+ },
38
+ run: async () => {
39
+ const logger = new Logger({ name: this.constructor.name });
40
+ if (!(await this.legacyColumnExists())) {
41
+ logger.info({ message: `No legacy roles column on ${tables.User.name}; nothing to retire` });
42
+ return { retired: 0 };
43
+ }
44
+
45
+ const retired = await Db.getDefaultDbDriver().runDml(() => ({
46
+ sql: `UPDATE ${tables.User.name} SET roles = NULL WHERE ${this.retirableCells()}`,
47
+ }));
48
+ logger.info({ message: `Retired legacy user roles cells`, obj: { retired } });
49
+ return { retired };
50
+ },
51
+ };
52
+
53
+ /** The cells this migration may NULL: a legacy value the typed column already carries, or nothing at all. */
54
+ private retirableCells(): string {
55
+ return `roles IS NOT NULL AND (role_list IS NOT NULL OR roles = '')`;
56
+ }
57
+
58
+ private async legacyColumnExists(): Promise<boolean> {
59
+ const legacyColumn = await Db.getDefaultDbDriver().runQuery(() => ({
60
+ sql:
61
+ `SELECT column_name FROM information_schema.columns ` +
62
+ `WHERE table_name = '${tables.User.name}' AND column_name = 'roles'`,
63
+ }));
64
+ return legacyColumn.length > 0;
65
+ }
66
+ }
@@ -8,6 +8,7 @@ import { establishSession } from '../authentication/establishSession';
8
8
  import { Roles } from '../services/Roles';
9
9
  import { Signup } from '../services/Signup';
10
10
  import { DevBootstrapRoles } from './DevBootstrapRoles';
11
+ import { devLoopDoorsOpen } from './devLoopDoorsOpen';
11
12
 
12
13
  const logger = new Logger({ name: 'devLogin' });
13
14
 
@@ -23,7 +24,9 @@ const emailDomain = (address: string) => address.slice(address.lastIndexOf('@')
23
24
  * used as before.
24
25
  *
25
26
  * Double-gated, acts only when BOTH hold; otherwise the path answers 404 as if unregistered:
26
- * 1. `process.env.DEVELOPMENT` — the dev-server switch, never set in prod images.
27
+ * 1. A dev switch (`devLoopDoorsOpen`): `DEVELOPMENT` — the whole dev-server switch, never set in a
28
+ * deployed image — OR `DEV_LOOP_DOORS`, the doors' own switch for a hosted development deployment,
29
+ * which runs the production shape and so can never carry `DEVELOPMENT`; test and prod set neither.
27
30
  * 2. `DEV_AUTO_LOGIN_EMAIL` — explicit per-launch opt-in naming the default account.
28
31
  *
29
32
  * Domain rail: `?email` must share `DEV_AUTO_LOGIN_EMAIL`'s domain — even a dev server must not
@@ -70,7 +73,7 @@ export const devLogin: Route = {
70
73
  method: 'get',
71
74
  onRequest: async (request: any, response): Promise<void> => {
72
75
  const envEmail = (process.env.DEV_AUTO_LOGIN_EMAIL ?? '').trim();
73
- if (!process.env.DEVELOPMENT || !envEmail) {
76
+ if (!devLoopDoorsOpen(process.env) || !envEmail) {
74
77
  response.status(404).send();
75
78
  return;
76
79
  }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The dev-loop doors' switch, read in ONE place. A door (`/dev/login` and its kin) is open when either
3
+ * holds; a deployment outside development sets neither name:
4
+ * - `DEVELOPMENT` — the WHOLE dev-server switch (a developer's own server: its local stores, its log
5
+ * writer, its middleware all ride on it), never set in a deployed image.
6
+ * - `DEV_LOOP_DOORS` — the doors' OWN switch, for a hosted development deployment: it runs the
7
+ * production shape (real stores, the production middleware) and so can never carry `DEVELOPMENT`,
8
+ * yet it is where the dev loop's agent-driven proofs sign in, so its doors must open.
9
+ * Either is read the way the doors always read `DEVELOPMENT`: present and non-empty = set. Each door
10
+ * keeps its own second gate (`DEV_AUTO_LOGIN_EMAIL`, the explicit per-launch opt-in) on top.
11
+ */
12
+ export const devLoopDoorsOpen = (env: NodeJS.ProcessEnv): boolean => Boolean(env.DEVELOPMENT || env.DEV_LOOP_DOORS);
@@ -4,18 +4,26 @@ import { SpannerEmulatorProvisioner, getDropTestTable } from '@proteinjs/db-driv
4
4
  import { SourceRepository } from '@proteinjs/reflection';
5
5
  import { tables } from '@proteinjs/user';
6
6
  import { BackfillUserRolesArray } from '../src/migrations/BackfillUserRolesArray';
7
+ import { RetireLegacyUserRolesColumn } from '../src/migrations/RetireLegacyUserRolesColumn';
7
8
 
8
9
  /**
9
- * The user.roles cutover migration against a real Spanner emulator, simulating a deployed
10
+ * The user.roles cutover migrations against a real Spanner emulator, simulating a deployed
10
11
  * database: the user table carries the NEW schema (role_list, added by schema sync) PLUS the
11
12
  * legacy comma-string `roles` column with pre-cutover data — exactly the state a deployment is
12
- * in when the migration runs.
13
+ * in when the migrations run. Every read below goes through the ORM: what the row reader makes
14
+ * of a row holding BOTH cells — the legacy `roles` (a word, an empty string, NULL) and the typed
15
+ * `role_list` — is the law this suite proves, not a comment's claim.
13
16
  *
14
17
  * Pinned outcomes:
15
18
  * - legacy comma strings land in role_list as normalized arrays (trim, drop empties, dedupe)
16
- * - empty/NULL legacy values stay untouched (no roles then, no roles now)
17
- * - rows already carrying role_list are never clobbered (idempotence / post-cutover grants win)
18
- * - a database that never had the legacy column (fresh install) is a clean no-op
19
+ * - empty/NULL legacy values stay untouched by the backfill (no roles then, no roles now)
20
+ * - rows already carrying role_list are never clobbered (idempotence / post-cutover grants win),
21
+ * and the ORM reads the array beside the stale legacy word
22
+ * - the retirement NULLs every legacy cell the typed column has absorbed — or that held nothing —
23
+ * and never one the backfill has not consumed; the ORM reads the same arrays before and after
24
+ * (a NULL legacy cell beside the array is the shape a row reader seating by property name
25
+ * would blank)
26
+ * - a database that never had the legacy column (fresh install) is a clean no-op for both
19
27
  */
20
28
 
21
29
  const spannerDriver = new SpannerDriver({
@@ -33,6 +41,8 @@ class DbDriverFactory {
33
41
  const dropTable = getDropTestTable(spannerDriver);
34
42
 
35
43
  const runMigration = async () => await new BackfillUserRolesArray().record.run();
44
+ const runRetirement = async () => await new RetireLegacyUserRolesColumn().record.run();
45
+ const estimateRetirement = async () => await new RetireLegacyUserRolesColumn().record.estimate();
36
46
 
37
47
  const rawUserInsert = async (id: string, legacyRoles: string | null) => {
38
48
  const rolesValue = legacyRoles === null ? 'NULL' : `'${legacyRoles}'`;
@@ -51,6 +61,14 @@ const rawRoleList = async (id: string) =>
51
61
  }))) as unknown as Array<{ role_list: string | null }>
52
62
  )[0].role_list;
53
63
 
64
+ /** The legacy cell as the database holds it. */
65
+ const rawRoles = async (id: string) =>
66
+ (
67
+ (await spannerDriver.runQuery(() => ({
68
+ sql: `SELECT roles FROM ${tables.User.name} WHERE id = '${id}'`,
69
+ }))) as unknown as Array<{ roles: string | null }>
70
+ )[0].roles;
71
+
54
72
  describe('BackfillUserRolesArray — legacy comma-string roles → typed role_list', () => {
55
73
  beforeAll(async () => {
56
74
  (SourceRepository.get() as any).objectCache['@proteinjs/db/DefaultDbDriverFactory'] = [new DbDriverFactory()];
@@ -72,8 +90,64 @@ describe('BackfillUserRolesArray — legacy comma-string roles → typed role_li
72
90
 
73
91
  it('is a clean no-op on a database that never had the legacy roles column', async () => {
74
92
  expect(await runMigration()).toEqual({ backfilled: 0 });
93
+ expect(await runRetirement()).toEqual({ retired: 0 });
94
+ expect(await estimateRetirement()).toMatchObject({ units: 0, unit: 'rows' });
75
95
  }, 60000);
76
96
 
97
+ it('retires every legacy cell the typed column has absorbed, never one the backfill has not consumed; the ORM reads the same arrays before and after', async () => {
98
+ await spannerDriver.runUpdateSchema(`ALTER TABLE ${tables.User.name} ADD COLUMN roles STRING(255)`);
99
+ const db = getDbAsSystem();
100
+ try {
101
+ await rawUserInsert('retire-carried', 'admin');
102
+ await rawUserInsert('retire-empty', '');
103
+ await rawUserInsert('retire-null', null);
104
+ // A legacy value the backfill has not consumed yet: role_list NULL, legacy text present.
105
+ await rawUserInsert('retire-unconsumed', 'ops');
106
+ // A post-cutover grant beside a stale legacy word (the collision shape).
107
+ const granted = await db.insert(tables.User, {
108
+ name: 'Granted',
109
+ email: 'granted@test.local',
110
+ password: 'test',
111
+ emailVerified: false,
112
+ roles: ['ops', 'dev'],
113
+ });
114
+ await spannerDriver.runDml(() => ({
115
+ sql: `UPDATE ${tables.User.name} SET roles = 'admin' WHERE id = '${granted.id}'`,
116
+ }));
117
+ // Carry the one consumable legacy value over (as the backfill would); leave 'retire-unconsumed' as a later backfill's.
118
+ await db.update(tables.User, { id: 'retire-carried', roles: ['admin'] });
119
+
120
+ // Before: the ORM reads the arrays beside the legacy cells, whatever they hold.
121
+ expect((await db.get(tables.User, { id: 'retire-carried' })).roles).toEqual(['admin']);
122
+ expect((await db.get(tables.User, { id: granted.id })).roles).toEqual(['ops', 'dev']);
123
+
124
+ expect(await estimateRetirement()).toMatchObject({ units: 3, unit: 'rows' });
125
+ expect(await runRetirement()).toEqual({ retired: 3 });
126
+
127
+ // The retired cells are NULL; the unconsumed legacy value is untouched.
128
+ expect(await rawRoles('retire-carried')).toBeNull();
129
+ expect(await rawRoles('retire-empty')).toBeNull();
130
+ expect(await rawRoles('retire-null')).toBeNull();
131
+ expect(await rawRoles(granted.id)).toBeNull();
132
+ expect(await rawRoles('retire-unconsumed')).toBe('ops');
133
+ expect(await rawRoleList('retire-unconsumed')).toBeNull();
134
+
135
+ // After: a NULL legacy cell beside the array — the ORM still reads the array.
136
+ expect((await db.get(tables.User, { id: 'retire-carried' })).roles).toEqual(['admin']);
137
+ expect((await db.get(tables.User, { id: granted.id })).roles).toEqual(['ops', 'dev']);
138
+ const everyone = await db.query(tables.User, {});
139
+ expect(everyone.find((user) => user.id === granted.id)?.roles).toEqual(['ops', 'dev']);
140
+ expect(everyone.find((user) => user.id === 'retire-carried')?.roles).toEqual(['admin']);
141
+
142
+ // Re-run: nothing left to retire.
143
+ expect(await runRetirement()).toEqual({ retired: 0 });
144
+ expect(await estimateRetirement()).toMatchObject({ units: 0, unit: 'rows' });
145
+ } finally {
146
+ await dropTable(tables.User as Table<any>);
147
+ await spannerDriver.getTableManager().loadTable(tables.User);
148
+ }
149
+ }, 120000);
150
+
77
151
  it('backfills, normalizes, preserves, and re-runs clean on a deployed-shape database', async () => {
78
152
  // Simulate the deployed state: the legacy column exists beside the new schema.
79
153
  await spannerDriver.runUpdateSchema(`ALTER TABLE ${tables.User.name} ADD COLUMN roles STRING(255)`);
@@ -12,7 +12,8 @@ const testEnv = new UserServerTestEnvironment();
12
12
  * `?email=` (absent → `DEV_AUTO_LOGIN_EMAIL`), auto-creating a missing account through the normal
13
13
  * signup creation path (`Signup.createAccount`) so parallel agent-driven verification can
14
14
  * self-serve distinct users. Two rails under test:
15
- * - Double gate: `DEVELOPMENT` AND `DEV_AUTO_LOGIN_EMAIL` both present, else 404 (unchanged).
15
+ * - Double gate: a dev switch (`DEVELOPMENT`, or `DEV_LOOP_DOORS` for a hosted development deployment
16
+ * that cannot carry the whole dev-server switch) AND `DEV_AUTO_LOGIN_EMAIL` both present, else 404.
16
17
  * - Domain rail: a `?email=` param must share `DEV_AUTO_LOGIN_EMAIL`'s domain — even a dev server
17
18
  * must not mint sessions (much less accounts) for arbitrary domains. Others 400.
18
19
  * The first-admin door (`DEV_BOOTSTRAP_ADMIN_EMAIL`) and the role-bootstrap door (`DEV_BOOTSTRAP_ROLES`)
@@ -27,6 +28,7 @@ const getUserRow = async (email: string) => await getDbAsSystem().get(tables.Use
27
28
  describe('devLogin route', () => {
28
29
  const originalEnv = {
29
30
  DEVELOPMENT: process.env.DEVELOPMENT,
31
+ DEV_LOOP_DOORS: process.env.DEV_LOOP_DOORS,
30
32
  DEV_AUTO_LOGIN_EMAIL: process.env.DEV_AUTO_LOGIN_EMAIL,
31
33
  DEV_BOOTSTRAP_ADMIN_EMAIL: process.env.DEV_BOOTSTRAP_ADMIN_EMAIL,
32
34
  DEV_BOOTSTRAP_ROLES: process.env.DEV_BOOTSTRAP_ROLES,
@@ -42,6 +44,7 @@ describe('devLogin route', () => {
42
44
 
43
45
  beforeEach(() => {
44
46
  process.env.DEVELOPMENT = 'true';
47
+ delete process.env.DEV_LOOP_DOORS;
45
48
  process.env.DEV_AUTO_LOGIN_EMAIL = ENV_EMAIL;
46
49
  delete process.env.DEV_BOOTSTRAP_ADMIN_EMAIL;
47
50
  delete process.env.DEV_BOOTSTRAP_ROLES;
@@ -207,7 +210,7 @@ describe('devLogin route', () => {
207
210
  expect(await getUserRow('agent6+lane-a@test.local')).toBeDefined();
208
211
  });
209
212
 
210
- it('404s when DEVELOPMENT is unset, even with a ?email', async () => {
213
+ it('404s with neither switch (DEVELOPMENT and DEV_LOOP_DOORS unset), even with a ?email', async () => {
211
214
  delete process.env.DEVELOPMENT;
212
215
 
213
216
  const outcome = await invokeDevLogin({ email: 'agent4@test.local' });
@@ -217,6 +220,33 @@ describe('devLogin route', () => {
217
220
  expect(await getUserRow('agent4@test.local')).toBeUndefined();
218
221
  });
219
222
 
223
+ it('opens under the dev-loop switch alone (DEV_LOOP_DOORS=1, DEVELOPMENT unset — a hosted development deployment): a session for a same-domain ?email, redirect to /', async () => {
224
+ delete process.env.DEVELOPMENT;
225
+ process.env.DEV_LOOP_DOORS = '1';
226
+
227
+ const outcome = await invokeDevLogin({ email: 'agent7@test.local' });
228
+
229
+ expect(outcome.status).toBeUndefined();
230
+ expect(outcome.loggedInAs).toBe('agent7@test.local');
231
+ expect(outcome.sessionRegenerated).toBe(true);
232
+ expect(outcome.sessionSaved).toBe(true);
233
+ expect(outcome.redirect).toBe('/');
234
+ expect(await getUserRow('agent7@test.local')).toBeDefined();
235
+ });
236
+
237
+ it('404s under DEV_LOOP_DOORS=1 when DEV_AUTO_LOGIN_EMAIL is unset — the double gate holds under the new switch', async () => {
238
+ delete process.env.DEVELOPMENT;
239
+ process.env.DEV_LOOP_DOORS = '1';
240
+ delete process.env.DEV_AUTO_LOGIN_EMAIL;
241
+
242
+ const outcome = await invokeDevLogin({ email: 'agent8@test.local' });
243
+
244
+ expect(outcome.status).toBe(404);
245
+ expect(outcome.loggedInAs).toBeUndefined();
246
+ expect(outcome.sessionSaved).toBe(false);
247
+ expect(await getUserRow('agent8@test.local')).toBeUndefined();
248
+ });
249
+
220
250
  it('404s when DEV_AUTO_LOGIN_EMAIL is unset, even with a ?email', async () => {
221
251
  delete process.env.DEV_AUTO_LOGIN_EMAIL;
222
252