pulse-hub 3.5.0 → 3.6.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 (43) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/backend/.env.example +52 -52
  3. package/backend/agent.js +372 -372
  4. package/backend/cli.js +23 -1
  5. package/backend/emails/env-backup.html +52 -52
  6. package/backend/emails/invite.html +53 -53
  7. package/backend/lib/agent-rpc.js +72 -72
  8. package/backend/lib/async-route.js +17 -17
  9. package/backend/lib/authz/bootstrap.js +35 -35
  10. package/backend/lib/authz/catalog.js +291 -291
  11. package/backend/lib/authz/delegation.js +104 -104
  12. package/backend/lib/authz/effective.js +104 -104
  13. package/backend/lib/authz/engine.js +251 -251
  14. package/backend/lib/authz/index.js +134 -134
  15. package/backend/lib/authz/migrate.js +871 -871
  16. package/backend/lib/authz/mutate.js +87 -87
  17. package/backend/lib/authz/preview.js +327 -327
  18. package/backend/lib/authz/scope.js +282 -282
  19. package/backend/lib/env-mask.js +131 -131
  20. package/backend/lib/invite-helpers.js +83 -83
  21. package/backend/lib/invites.js +160 -160
  22. package/backend/lib/logs.js +244 -244
  23. package/backend/lib/metrics.js +249 -249
  24. package/backend/lib/relay-state.js +564 -564
  25. package/backend/lib/session.js +48 -48
  26. package/backend/middleware/authz.js +65 -65
  27. package/backend/public/assets/favicon.svg +6 -6
  28. package/backend/public/assets/index.js +1 -1
  29. package/backend/public/index.html +23 -24
  30. package/backend/routes/access.js +123 -123
  31. package/backend/routes/audit.js +41 -41
  32. package/backend/routes/auth.js +207 -207
  33. package/backend/routes/invites-public.js +91 -91
  34. package/backend/routes/invites.js +121 -121
  35. package/backend/routes/logs.js +68 -68
  36. package/backend/routes/metrics.js +76 -76
  37. package/backend/routes/policies.js +240 -240
  38. package/backend/routes/teams.js +221 -221
  39. package/backend/routes/users.js +100 -100
  40. package/backend/seed-admins.js +68 -68
  41. package/backend/server.js +106 -106
  42. package/backend/ws/agent-relay.js +159 -159
  43. package/package.json +1 -1
@@ -1,871 +1,871 @@
1
- // Legacy roles/groups/capabilities/tags -> teams/policies/rules/access tags (permissions v2,
2
- // see .claude/plans/permissions-v2-implementation.md §7).
3
- //
4
- // runMigration() is idempotent (guarded by settings.authz_migrated_at), transactional, and
5
- // drives itself off a frozen copy of the old authorization logic (legacy-oracle.js):
6
- // 1. users.is_root := 1 for role='super_admin'
7
- // 2. every legacy group -> one team + one generated policy ("<group> access")
8
- // 3. tags matched by a group tag rule are copied into instance_auth_tags (access tags)
9
- // 4. users the generated teams don't fully cover (zero-group admins, admin capability
10
- // flags, admins' no-service env files) get explicit rules through generated
11
- // "Legacy · ..." teams, grouped by identical rule signature
12
- // 5/6. review items: admin_request, env_edit_via_glob (+ residual_fill / env_restart_broadened
13
- // when something unusual had to be filled or tolerated)
14
- // 7. parity verification over the §7.4 domain (old oracle vs. the real v2 engine)
15
- // 8. settings.authz_migrated_at, revision bump, `migration.applied` audit event
16
- // Any unflagged parity difference rolls the whole thing back and throws a
17
- // MigrationParityError; the startup wrapper (authz/bootstrap.js) turns that into exit(1),
18
- // tests and the CLI just catch it. A pre-migration backup (VACUUM INTO) is taken first.
19
- //
20
- // Everything here goes through `engine.can` / `engine.buildSubject` (via the module object,
21
- // so tests can wrap them) — parity must exercise the real engine, not a reimplementation.
22
-
23
- const path = require('path');
24
- const { db, getSetting, setSetting } = require('../db');
25
- const store = require('../authz-store');
26
- const audit = require('../audit');
27
- const engine = require('./engine');
28
- const { validateRule } = require('./scope');
29
- const { createLegacyOracle } = require('./legacy-oracle');
30
-
31
- const MIGRATED_KEY = 'authz_migrated_at';
32
- const SYSTEM_ACTOR = 'authz-migration';
33
- // An instance id that cannot exist: `can(servers.create, {instanceId: PROBE})` is true only
34
- // for an `all` rule (the "create over all servers" semantics routes/instances.js uses).
35
- const PROBE_INSTANCE = '__pulse_authz_probe__';
36
- const MAX_DOMAIN_NAMES = 400;
37
-
38
- const ENV_ACTIONS = ['env.view', 'env.edit', 'env.restore', 'env.reveal'];
39
- const MANAGE_ACTIONS = [
40
- 'servers.update',
41
- 'servers.delete',
42
- 'servers.tags.manage',
43
- 'servers.agent.update',
44
- 'env.setup',
45
- ];
46
- // §7.3: legacy capability flag -> org actions.
47
- const ORG_FLAG_ACTIONS = {
48
- manageTeam: ['people.view', 'people.invite', 'people.remove'],
49
- assignGroupMembers: [
50
- 'teams.view',
51
- 'teams.create',
52
- 'teams.update',
53
- 'teams.delete',
54
- 'teams.members.manage',
55
- 'teams.policies.manage',
56
- 'policies.view',
57
- 'policies.create',
58
- 'policies.update',
59
- 'policies.delete',
60
- ],
61
- };
62
- // No legacy concept existed, so nobody may gain it through migration.
63
- const NEVER_GRANTED_ORG_ACTIONS = ['audit.view'];
64
-
65
- class MigrationParityError extends Error {
66
- constructor(diffs, report) {
67
- super(`authz migration parity check failed: ${diffs.length} unflagged difference(s)`);
68
- this.name = 'MigrationParityError';
69
- this.code = 'AUTHZ_MIGRATION_PARITY';
70
- this.diffs = diffs;
71
- this.report = report;
72
- }
73
- }
74
-
75
- // Internal: thrown inside the transaction to roll a dry run back.
76
- class DryRunAbort extends Error {
77
- constructor(report) {
78
- super('dry run');
79
- this.report = report;
80
- }
81
- }
82
-
83
- function isMigrated() {
84
- return getSetting(MIGRATED_KEY) !== null;
85
- }
86
-
87
- // ---------------------------------------------------------------------------------------
88
- // Rule construction helpers
89
- // ---------------------------------------------------------------------------------------
90
-
91
- function unique(list) {
92
- return [...new Set(list)];
93
- }
94
-
95
- function uniqueName(base, used) {
96
- const clean = (base || '').trim() || 'Migrated';
97
- let candidate = clean;
98
- for (let n = 2; used.has(candidate.toLowerCase()); n++) candidate = `${clean} (${n})`;
99
- used.add(candidate.toLowerCase());
100
- return candidate;
101
- }
102
-
103
- // §7.2: x* -> startsWith, *x -> endsWith, *x* -> contains, no wildcard -> exact, else glob.
104
- function globToMatcher(glob) {
105
- if (!/[*?]/.test(glob)) return { op: 'exact', value: glob };
106
- let m = /^([^*?]+)\*$/.exec(glob);
107
- if (m) return { op: 'startsWith', value: m[1] };
108
- m = /^\*([^*?]+)$/.exec(glob);
109
- if (m) return { op: 'endsWith', value: m[1] };
110
- m = /^\*([^*?]+)\*$/.exec(glob);
111
- if (m) return { op: 'contains', value: m[1] };
112
- return { op: 'glob', value: glob };
113
- }
114
-
115
- function matchersFromGlobs(globs) {
116
- const seen = new Set();
117
- const out = [];
118
- for (const g of globs) {
119
- const m = globToMatcher(g);
120
- const key = `${m.op}:${m.value}`;
121
- if (!seen.has(key)) {
122
- seen.add(key);
123
- out.push(m);
124
- }
125
- }
126
- return out;
127
- }
128
-
129
- // A group's instance set expressed as server scopes: the explicit ids as one `ids` scope
130
- // plus every tag rule as its own `tags/any/[tag]` scope, so rule union == the old
131
- // "group_instances UNION tag matches" semantics.
132
- function serverScopesForGroups(oracle, groupIds) {
133
- const ids = [];
134
- const tags = [];
135
- for (const groupId of groupIds) {
136
- ids.push(...(oracle.groupInstances.get(groupId) || []));
137
- tags.push(...(oracle.groupTags.get(groupId) || []));
138
- }
139
- const scopes = [];
140
- if (ids.length > 0) scopes.push({ type: 'ids', ids: unique(ids) });
141
- for (const tag of unique(tags)) scopes.push({ type: 'tags', tags: [tag], match: 'any' });
142
- return scopes;
143
- }
144
-
145
- // §7.2 step 2: the rules generated for one legacy group.
146
- function rulesForGroup(oracle, group) {
147
- const scopes = serverScopesForGroups(oracle, [group.id]);
148
- const matchers = matchersFromGlobs(unique(oracle.groupProcesses.get(group.id) || []));
149
- const processServices = matchers.length > 0 ? { matchers } : null;
150
- const allowlist = unique(oracle.groupEnvFiles.get(group.id) || []);
151
- const rules = [];
152
-
153
- for (const servers of scopes) {
154
- rules.push({ action: 'servers.view', scope: { servers } });
155
- for (const action of ['metrics.view', 'logs.view']) {
156
- rules.push({
157
- action,
158
- scope: processServices ? { servers, services: processServices } : { servers },
159
- });
160
- }
161
- if (allowlist.length > 0) {
162
- for (const action of ENV_ACTIONS) {
163
- rules.push({ action, scope: { servers, envFiles: { ids: allowlist } } });
164
- }
165
- } else {
166
- // The old rule required a linked service for non-admins, hence an explicit `*` glob
167
- // when the group has no process restriction (a matcher-less rule would also match
168
- // no-service files, which only admins could touch).
169
- const services = processServices || { matchers: [{ op: 'glob', value: '*' }] };
170
- for (const action of ENV_ACTIONS) rules.push({ action, scope: { servers, services } });
171
- rules.push({ action: 'service.restart', scope: { servers, services } });
172
- }
173
- }
174
-
175
- if (allowlist.length > 0) {
176
- // service.restart has no env-file narrowing, so pin it to each allowlisted file's own
177
- // instance + service name (still only where the group actually grants that instance).
178
- const byInstance = new Map();
179
- for (const file of oracle.envFiles) {
180
- if (!allowlist.includes(file.id) || !file.service_name) continue;
181
- if (oracle.getGroupIdsGrantingInstance([group.id], file.instance_id).length === 0) continue;
182
- if (!byInstance.has(file.instance_id)) byInstance.set(file.instance_id, new Set());
183
- byInstance.get(file.instance_id).add(file.service_name);
184
- }
185
- for (const [instanceId, names] of byInstance) {
186
- rules.push({
187
- action: 'service.restart',
188
- scope: {
189
- servers: { type: 'ids', ids: [instanceId] },
190
- services: { matchers: [...names].map((value) => ({ op: 'exact', value })) },
191
- },
192
- });
193
- }
194
- }
195
- return rules;
196
- }
197
-
198
- // §7.3 structured residual: what a group-derived team can never express for this user.
199
- function structuredRulesForUser(oracle, user) {
200
- const rules = [];
201
- const allowed = oracle.getAllowedInstanceIds(user);
202
- const all = { servers: { type: 'all' } };
203
-
204
- // Zero-group admins were unrestricted — including servers registered tomorrow — so this
205
- // must be an `all` rule, not a snapshot of today's instances.
206
- if (allowed === null) {
207
- for (const action of ['servers.view', 'metrics.view', 'logs.view']) {
208
- rules.push({ action, scope: all });
209
- }
210
- for (const action of ENV_ACTIONS) rules.push({ action, scope: all });
211
- rules.push({ action: 'service.restart', scope: all });
212
- }
213
-
214
- if (oracle.canManageInstances(user)) {
215
- rules.push({ action: 'servers.create', scope: all });
216
- const scopes =
217
- allowed === null
218
- ? [all.servers]
219
- : serverScopesForGroups(oracle, oracle.groupMembers.get(user.id) || []);
220
- for (const servers of scopes) {
221
- for (const action of MANAGE_ACTIONS) rules.push({ action, scope: { servers } });
222
- }
223
- }
224
- return rules;
225
- }
226
-
227
- function assertValid(rule) {
228
- const result = validateRule(rule, { fromMigration: true });
229
- if (!result.ok) {
230
- throw new Error(`migration generated an invalid rule ${JSON.stringify(rule)}: ${result.error}`);
231
- }
232
- }
233
-
234
- // ---------------------------------------------------------------------------------------
235
- // Parity domain + evaluation (shared by the residual fill and the verification)
236
- // ---------------------------------------------------------------------------------------
237
-
238
- // Strings that would distinguish glob semantics from matcher semantics.
239
- function witnessesForGlob(glob) {
240
- const variants = [
241
- glob.replace(/\*/g, '').replace(/\?/g, 'a'),
242
- glob.replace(/[*?]/g, 'x'),
243
- glob.replace(/\*/g, 'xx').replace(/\?/g, 'x'),
244
- ];
245
- const out = new Set();
246
- for (const v of variants) {
247
- if (!v) continue;
248
- out.add(v);
249
- out.add(`${v}x`);
250
- out.add(`x${v}`);
251
- out.add(v.toUpperCase());
252
- if (v.length > 1) out.add(v.slice(0, -1));
253
- }
254
- return out;
255
- }
256
-
257
- function buildDomain(oracle, extraProcessNames = []) {
258
- const names = new Set(['pulse-no-such-process']);
259
- for (const n of extraProcessNames) if (n) names.add(String(n));
260
- for (const file of oracle.envFiles) if (file.service_name) names.add(file.service_name);
261
- for (const globs of oracle.groupProcesses.values()) {
262
- for (const glob of globs) for (const w of witnessesForGlob(glob)) names.add(w);
263
- }
264
- return {
265
- instanceIds: oracle.instanceIds,
266
- envFiles: oracle.envFiles,
267
- names: [...names].filter(Boolean).slice(0, MAX_DOMAIN_NAMES),
268
- };
269
- }
270
-
271
- // One user x whole domain: old verdict (oracle) next to the new verdict (real engine).
272
- function evaluateUser(ctx, user, subject) {
273
- const { oracle, domain } = ctx;
274
- const can = (action, resource) => !!engine.can(subject, action, resource);
275
- const cells = [];
276
- const old = {
277
- manageInstances: !!oracle.canManageInstances(user),
278
- manageTeam: !!oracle.canManageTeam(user),
279
- assignGroupMembers: !!oracle.canAssignGroupMembers(user),
280
- allowed: oracle.getAllowedInstanceIds(user),
281
- };
282
-
283
- for (const [flag, actions] of Object.entries(ORG_FLAG_ACTIONS)) {
284
- for (const action of actions) {
285
- cells.push({ kind: 'org', action, old: old[flag], neu: can(action) });
286
- }
287
- }
288
- for (const action of NEVER_GRANTED_ORG_ACTIONS) {
289
- cells.push({ kind: 'org', action, old: false, neu: can(action) });
290
- }
291
- cells.push({
292
- kind: 'create',
293
- action: 'servers.create',
294
- old: old.manageInstances,
295
- neu: can('servers.create', { instanceId: PROBE_INSTANCE }),
296
- });
297
-
298
- for (const instanceId of domain.instanceIds) {
299
- const visibleOld = old.allowed === null || old.allowed.has(instanceId);
300
- const visibleNew = can('servers.view', { instanceId });
301
- cells.push({
302
- kind: 'view',
303
- action: 'servers.view',
304
- instanceId,
305
- old: visibleOld,
306
- neu: visibleNew,
307
- });
308
- for (const action of MANAGE_ACTIONS) {
309
- cells.push({
310
- kind: 'manage',
311
- action,
312
- instanceId,
313
- old: old.manageInstances && visibleOld,
314
- neu: can(action, { instanceId }),
315
- });
316
- }
317
- if (visibleOld || visibleNew) {
318
- const patterns = oracle.getAllowedProcessNames(user, instanceId);
319
- for (const name of domain.names) {
320
- const matchOld = visibleOld && (!patterns || oracle.matchesAnyPattern(name, patterns));
321
- for (const action of ['metrics.view', 'logs.view']) {
322
- cells.push({
323
- kind: 'proc',
324
- action,
325
- instanceId,
326
- name,
327
- old: matchOld,
328
- neu: visibleNew && can(action, { instanceId, serviceName: name }),
329
- });
330
- }
331
- }
332
- }
333
- }
334
-
335
- for (const file of domain.envFiles) {
336
- const accessOld = !!oracle.canAccessEnvFile(user, file);
337
- const serviceName = file.service_name || undefined;
338
- for (const action of ENV_ACTIONS) {
339
- cells.push({
340
- kind: 'env',
341
- action,
342
- instanceId: file.instance_id,
343
- envFileId: file.id,
344
- noService: !file.service_name,
345
- old: accessOld,
346
- neu: can(action, { instanceId: file.instance_id, serviceName, envFileId: file.id }),
347
- });
348
- }
349
- cells.push({
350
- kind: 'restart',
351
- action: 'service.restart',
352
- instanceId: file.instance_id,
353
- envFileId: file.id,
354
- name: file.service_name || null,
355
- old: accessOld && !!file.service_name,
356
- neu:
357
- !!file.service_name &&
358
- can('service.restart', { instanceId: file.instance_id, serviceName }),
359
- });
360
- }
361
- return cells;
362
- }
363
-
364
- function describeCell(cell) {
365
- const where = cell.envFileId
366
- ? ` env-file ${cell.envFileId} (instance ${cell.instanceId})`
367
- : cell.instanceId
368
- ? ` instance ${cell.instanceId}`
369
- : '';
370
- const name = cell.kind === 'proc' ? ` process "${cell.name}"` : '';
371
- return `${cell.action}${where}${name}`;
372
- }
373
-
374
- // §7.2 step 4: old-yes/new-no cells -> explicit rules (the safety net behind the structured
375
- // rules above). Never converts new-yes/old-no — that is a parity failure, not something to
376
- // "fix" by removing access.
377
- function rulesFromLostCells(cells, domain) {
378
- const lost = cells.filter((c) => c.old && !c.neu);
379
- const rules = [];
380
- const byKey = (list, keyFn) => {
381
- const map = new Map();
382
- for (const item of list) {
383
- const key = keyFn(item);
384
- if (!map.has(key)) map.set(key, []);
385
- map.get(key).push(item);
386
- }
387
- return map;
388
- };
389
-
390
- for (const c of lost.filter((x) => x.kind === 'org')) {
391
- rules.push({ action: c.action, scope: null });
392
- }
393
- if (lost.some((x) => x.kind === 'create')) {
394
- rules.push({ action: 'servers.create', scope: { servers: { type: 'all' } } });
395
- }
396
- for (const [action, group] of byKey(
397
- lost.filter((x) => x.kind === 'view' || x.kind === 'manage'),
398
- (x) => x.action,
399
- )) {
400
- rules.push({
401
- action,
402
- scope: { servers: { type: 'ids', ids: unique(group.map((x) => x.instanceId)) } },
403
- });
404
- }
405
- for (const [, group] of byKey(
406
- lost.filter((x) => x.kind === 'proc'),
407
- (x) => `${x.action}\u0000${x.instanceId}`,
408
- )) {
409
- const servers = { type: 'ids', ids: [group[0].instanceId] };
410
- const names = unique(group.map((x) => x.name));
411
- rules.push({
412
- action: group[0].action,
413
- scope:
414
- names.length >= domain.names.length
415
- ? { servers }
416
- : { servers, services: { matchers: names.map((value) => ({ op: 'exact', value })) } },
417
- });
418
- }
419
- for (const [, group] of byKey(
420
- lost.filter((x) => x.kind === 'env'),
421
- (x) => `${x.action}\u0000${x.instanceId}`,
422
- )) {
423
- rules.push({
424
- action: group[0].action,
425
- scope: {
426
- servers: { type: 'ids', ids: [group[0].instanceId] },
427
- envFiles: { ids: unique(group.map((x) => x.envFileId)) },
428
- },
429
- });
430
- }
431
- for (const [, group] of byKey(
432
- lost.filter((x) => x.kind === 'restart'),
433
- (x) => x.instanceId,
434
- )) {
435
- rules.push({
436
- action: 'service.restart',
437
- scope: {
438
- servers: { type: 'ids', ids: [group[0].instanceId] },
439
- services: {
440
- matchers: unique(group.map((x) => x.name)).map((value) => ({ op: 'exact', value })),
441
- },
442
- },
443
- });
444
- }
445
-
446
- // What the fill covered beyond the two expected categories (org flags, admins' no-service
447
- // env files) deserves a human look.
448
- const unexpected = lost.filter((c) => !(c.kind === 'org' || (c.kind === 'env' && c.noService)));
449
- return { rules, unexpected };
450
- }
451
-
452
- function ruleSignature(rules) {
453
- return JSON.stringify(rules.map((r) => JSON.stringify([r.action, r.scope])).sort());
454
- }
455
-
456
- function describeRuleSet(rules) {
457
- const actions = new Set(rules.map((r) => r.action));
458
- const parts = [];
459
- const hasAllServers = rules.some(
460
- (r) => r.action === 'servers.view' && r.scope && r.scope.servers.type === 'all',
461
- );
462
- if (hasAllServers) parts.push('all servers');
463
- if (actions.has('servers.create')) parts.push('server admin');
464
- if (actions.has('people.invite')) parts.push('people');
465
- if (actions.has('teams.create')) parts.push('teams');
466
- if (rules.some((r) => r.action === 'env.view' && r.scope && r.scope.envFiles)) {
467
- parts.push('env files');
468
- }
469
- return parts.length > 0 ? parts.join(', ') : 'access';
470
- }
471
-
472
- // ---------------------------------------------------------------------------------------
473
- // Parity verification
474
- // ---------------------------------------------------------------------------------------
475
-
476
- function buildContext({ extraProcessNames = [] } = {}) {
477
- const oracle = createLegacyOracle(db);
478
- return { oracle, domain: buildDomain(oracle, extraProcessNames) };
479
- }
480
-
481
- // Compares the legacy oracle against the engine for every non-root user. Returns
482
- // { cells, diffs, tolerated }. `diffs` are fatal; `tolerated` are access differences the
483
- // new model cannot express exactly and that are surfaced as review items instead.
484
- function verifyParity(ctx) {
485
- const { oracle } = ctx;
486
- const diffs = [];
487
- const tolerated = [];
488
- let cellCount = 0;
489
- const rows = db.prepare('SELECT * FROM users ORDER BY created_at ASC, id ASC').all();
490
-
491
- for (const row of rows) {
492
- if (row.role === 'super_admin' && !row.is_root) {
493
- diffs.push({
494
- userId: row.id,
495
- email: row.email,
496
- kind: 'root',
497
- old: true,
498
- neu: false,
499
- description: 'legacy super_admin is not is_root',
500
- });
501
- }
502
- if (row.is_root) continue; // root bypasses every check by design
503
- const subject = engine.buildSubject(row, store);
504
- const cells = evaluateUser(ctx, row, subject);
505
- cellCount += cells.length;
506
- for (const cell of cells) {
507
- if (cell.old === cell.neu) continue;
508
- const diff = {
509
- userId: row.id,
510
- email: row.email,
511
- kind: cell.kind,
512
- action: cell.action,
513
- instanceId: cell.instanceId || null,
514
- envFileId: cell.envFileId || null,
515
- name: cell.name || null,
516
- old: cell.old,
517
- neu: cell.neu,
518
- description: describeCell(cell),
519
- };
520
- // service.restart cannot be narrowed to one env file, so an allowlisted file whose
521
- // instance + service name is shared with another file the user may use broadens to
522
- // that sibling. Everything else is fatal.
523
- if (cell.kind === 'restart' && !cell.old && cell.neu) {
524
- const sibling = oracle.envFiles.find(
525
- (f) =>
526
- f.id !== cell.envFileId &&
527
- f.instance_id === cell.instanceId &&
528
- f.service_name === cell.name &&
529
- oracle.canAccessEnvFile(row, f),
530
- );
531
- if (sibling) {
532
- tolerated.push({ ...diff, reason: 'env_restart_broadened' });
533
- continue;
534
- }
535
- }
536
- diffs.push(diff);
537
- }
538
- }
539
- return { cells: cellCount, diffs, tolerated };
540
- }
541
-
542
- // ---------------------------------------------------------------------------------------
543
- // The migration proper
544
- // ---------------------------------------------------------------------------------------
545
-
546
- function backupDatabase() {
547
- if (db.memory || !db.name) return null;
548
- const file = path.join(path.dirname(db.name), `pulse.pre-authz-${Date.now()}.db`);
549
- db.exec(`VACUUM INTO '${file.replace(/'/g, "''")}'`);
550
- return file;
551
- }
552
-
553
- function applyMigration(ctx, options, report) {
554
- const { oracle } = ctx;
555
- const rootRow = db
556
- .prepare("SELECT id FROM users WHERE role = 'super_admin' ORDER BY created_at ASC, id ASC")
557
- .get();
558
- const anyRow = db.prepare('SELECT id FROM users ORDER BY created_at ASC, id ASC').get();
559
- const createdBy = (rootRow || anyRow).id;
560
-
561
- // 1. root
562
- report.rootUsers = db
563
- .prepare("UPDATE users SET is_root = 1 WHERE role = 'super_admin'")
564
- .run().changes;
565
-
566
- // 2. groups -> teams + policies
567
- const teamNames = new Set(store.listTeams().map((t) => t.name.toLowerCase()));
568
- const policyNames = new Set(store.listPolicies().map((p) => p.name.toLowerCase()));
569
- for (const group of oracle.groups) {
570
- const team = store.createTeam(
571
- {
572
- name: uniqueName(group.name, teamNames),
573
- description: `Migrated from legacy group "${group.name}"`,
574
- },
575
- createdBy,
576
- );
577
- const memberIds = unique(
578
- [...oracle.users.keys()].filter((id) =>
579
- (oracle.groupMembers.get(id) || []).includes(group.id),
580
- ),
581
- );
582
- for (const userId of memberIds) store.addTeamMember(team.id, userId, SYSTEM_ACTOR);
583
- const policy = store.createPolicy(
584
- {
585
- name: uniqueName(`${team.name} access`, policyNames),
586
- description: `Generated from legacy group "${group.name}" (instances, tags, process restriction, env-file allowlist)`,
587
- },
588
- null,
589
- );
590
- const rules = rulesForGroup(oracle, group);
591
- for (const rule of rules) {
592
- assertValid(rule);
593
- store.addPolicyRule(policy.id, rule);
594
- }
595
- store.attachPolicy(team.id, policy.id, SYSTEM_ACTOR);
596
- report.groupTeams.push({
597
- group: group.name,
598
- team: team.name,
599
- policy: policy.name,
600
- members: memberIds.length,
601
- rules: rules.length,
602
- });
603
- }
604
-
605
- // 3. access tags: every tag a group tag rule could match, on every instance carrying it
606
- const copyTag = db.prepare(
607
- 'INSERT OR IGNORE INTO instance_auth_tags (instance_id, tag) SELECT DISTINCT instance_id, tag FROM instance_tags WHERE tag = ?',
608
- );
609
- for (const tag of unique([...oracle.groupTags.values()].flat())) {
610
- report.accessTagsCopied += copyTag.run(tag).changes;
611
- }
612
-
613
- // 4. residual fill, per non-root user
614
- const userRows = db.prepare('SELECT * FROM users ORDER BY created_at ASC, id ASC').all();
615
- const plans = new Map(); // signature -> { rules, users: [row], descSource }
616
- const fillNotes = [];
617
- for (const row of userRows) {
618
- if (row.is_root) continue;
619
- const structured = structuredRulesForUser(oracle, row);
620
- const subject = engine.buildSubject(row, store);
621
- subject.rules.push(...structured.map((r) => ({ ...r, teamId: null, policyId: null })));
622
- const cells = evaluateUser(ctx, row, subject);
623
- const fill = rulesFromLostCells(cells, ctx.domain);
624
- const rules = [...structured, ...fill.rules];
625
- if (fill.unexpected.length > 0) {
626
- fillNotes.push({
627
- userId: row.id,
628
- email: row.email,
629
- cells: fill.unexpected.length,
630
- sample: fill.unexpected.slice(0, 5).map(describeCell),
631
- });
632
- }
633
- if (rules.length === 0) continue;
634
- for (const rule of rules) assertValid(rule);
635
- const signature = ruleSignature(rules);
636
- if (!plans.has(signature)) plans.set(signature, { rules, users: [] });
637
- plans.get(signature).users.push(row);
638
- }
639
- let n = 0;
640
- for (const plan of plans.values()) {
641
- n += 1;
642
- const label = `Legacy · ${describeRuleSet(plan.rules)} · ${n}`;
643
- const team = store.createTeam(
644
- {
645
- name: uniqueName(label, teamNames),
646
- description: 'Generated by the permissions migration to preserve existing access exactly',
647
- },
648
- createdBy,
649
- );
650
- const policy = store.createPolicy(
651
- {
652
- name: uniqueName(label, policyNames),
653
- description: 'Generated by the permissions migration (legacy role/capability residual)',
654
- },
655
- null,
656
- );
657
- for (const rule of plan.rules) store.addPolicyRule(policy.id, rule);
658
- store.attachPolicy(team.id, policy.id, SYSTEM_ACTOR);
659
- for (const user of plan.users) store.addTeamMember(team.id, user.id, SYSTEM_ACTOR);
660
- report.residualTeams.push({
661
- team: team.name,
662
- policy: policy.name,
663
- members: plan.users.map((u) => u.email || u.id),
664
- rules: plan.rules.length,
665
- });
666
- }
667
-
668
- // 5. admin-request flow -> review items
669
- for (const row of userRows) {
670
- if (!row.admin_requested_at) continue;
671
- store.createReviewItem({
672
- kind: 'admin_request',
673
- userId: row.id,
674
- detail: `Requested admin access on ${new Date(row.admin_requested_at).toISOString()}. The approval flow no longer exists; put this person in a team to grant access.`,
675
- });
676
- report.reviewItems.admin_request += 1;
677
- }
678
-
679
- // 6. viewers who could edit env files through a group's process globs
680
- for (const row of userRows) {
681
- if (row.role !== 'viewer' || row.is_root) continue;
682
- for (const file of oracle.envFiles) {
683
- if (!oracle.canAccessEnvFile(row, file)) continue;
684
- store.createReviewItem({
685
- kind: 'env_edit_via_glob',
686
- userId: row.id,
687
- instanceId: file.instance_id,
688
- envFileId: file.id,
689
- detail: `Viewer could edit "${file.label}" (${file.path}) through a group's service access. Migration preserved env view/edit/restore/reveal and restart; review whether that is intended.`,
690
- });
691
- report.reviewItems.env_edit_via_glob += 1;
692
- }
693
- }
694
- for (const note of fillNotes) {
695
- store.createReviewItem({
696
- kind: 'residual_fill',
697
- userId: note.userId,
698
- detail: `Migration had to add ${note.cells} explicit permission(s) beyond the standard mapping: ${note.sample.join('; ')}`,
699
- });
700
- report.reviewItems.residual_fill += 1;
701
- }
702
-
703
- if (typeof options.beforeVerify === 'function') options.beforeVerify({ db, store, engine });
704
-
705
- // 7. parity
706
- const parity = verifyParity(ctx);
707
- report.parity = {
708
- cells: parity.cells,
709
- diffs: parity.diffs,
710
- tolerated: parity.tolerated.length,
711
- };
712
- if (parity.diffs.length > 0) throw new MigrationParityError(parity.diffs, report);
713
- for (const t of parity.tolerated) {
714
- store.createReviewItem({
715
- kind: 'env_restart_broadened',
716
- userId: t.userId,
717
- instanceId: t.instanceId,
718
- envFileId: t.envFileId,
719
- detail: `Restarting "${t.name}" is now also allowed from env file ${t.envFileId}, which the user could not previously restart: service restarts cannot be limited to a single env file.`,
720
- });
721
- report.reviewItems.env_restart_broadened += 1;
722
- }
723
-
724
- if (options.dryRun) throw new DryRunAbort(report);
725
-
726
- // 8. finish
727
- setSetting(MIGRATED_KEY, String(Date.now()));
728
- report.revision = store.bumpAuthzRevision();
729
- audit.record({
730
- action: 'migration.applied',
731
- targetType: 'authz',
732
- outcome: 'succeeded',
733
- summary: `Migrated ${oracle.groups.length} group(s) and ${userRows.length} user(s) to teams and policies`,
734
- metadata: {
735
- groupTeams: report.groupTeams.length,
736
- residualTeams: report.residualTeams.length,
737
- rootUsers: report.rootUsers,
738
- accessTagsCopied: report.accessTagsCopied,
739
- reviewItems: report.reviewItems,
740
- parityCells: report.parity.cells,
741
- backup: report.backupPath,
742
- },
743
- });
744
- }
745
-
746
- function newReport(status) {
747
- return {
748
- status,
749
- dryRun: false,
750
- backupPath: null,
751
- users: 0,
752
- rootUsers: 0,
753
- groupTeams: [],
754
- residualTeams: [],
755
- accessTagsCopied: 0,
756
- reviewItems: {
757
- admin_request: 0,
758
- env_edit_via_glob: 0,
759
- residual_fill: 0,
760
- env_restart_broadened: 0,
761
- },
762
- parity: null,
763
- revision: null,
764
- };
765
- }
766
-
767
- // options: { dryRun, verifyOnly, extraProcessNames, beforeVerify (test hook) }
768
- // Statuses: 'migrated' | 'dry-run' | 'already-migrated' | 'fresh' | 'verified' |
769
- // 'not-migrated' (verifyOnly before the migration ran). Throws MigrationParityError when
770
- // parity fails (the transaction is rolled back; a verify-only run changed nothing anyway).
771
- function runMigration(options = {}) {
772
- const migrated = isMigrated();
773
-
774
- if (options.verifyOnly) {
775
- if (!migrated) return newReport('not-migrated');
776
- const report = newReport('verified');
777
- const parity = verifyParity(buildContext(options));
778
- report.parity = {
779
- cells: parity.cells,
780
- diffs: parity.diffs,
781
- tolerated: parity.tolerated.length,
782
- };
783
- if (parity.diffs.length > 0) throw new MigrationParityError(parity.diffs, report);
784
- return report;
785
- }
786
-
787
- if (migrated) return newReport('already-migrated');
788
-
789
- const userCount = db.prepare('SELECT COUNT(*) AS c FROM users').get().c;
790
- if (userCount === 0) {
791
- // Nothing to preserve: a fresh install starts on v2 directly.
792
- const report = newReport('fresh');
793
- if (options.dryRun) {
794
- report.dryRun = true;
795
- return report;
796
- }
797
- setSetting(MIGRATED_KEY, String(Date.now()));
798
- return report;
799
- }
800
-
801
- const report = newReport(options.dryRun ? 'dry-run' : 'migrated');
802
- report.dryRun = !!options.dryRun;
803
- report.users = userCount;
804
- if (!options.dryRun) report.backupPath = backupDatabase();
805
-
806
- const ctx = buildContext(options);
807
- try {
808
- db.transaction(() => applyMigration(ctx, options, report))();
809
- } catch (err) {
810
- if (err instanceof DryRunAbort) return report; // rolled back by the throw
811
- throw err;
812
- }
813
- return report;
814
- }
815
-
816
- function formatDiffs(diffs, limit = 50) {
817
- const lines = diffs
818
- .slice(0, limit)
819
- .map(
820
- (d) =>
821
- ` ${d.email || d.userId}: ${d.description} — legacy ${d.old ? 'ALLOWED' : 'denied'}, v2 ${d.neu ? 'ALLOWED' : 'denied'}`,
822
- );
823
- if (diffs.length > limit) lines.push(` ... and ${diffs.length - limit} more`);
824
- return lines.join('\n');
825
- }
826
-
827
- function formatReport(report) {
828
- const lines = [`Status: ${report.status}${report.dryRun ? ' (nothing written)' : ''}`];
829
- if (report.backupPath) lines.push(`Backup: ${report.backupPath}`);
830
- if (report.status === 'not-migrated') {
831
- lines.push('The migration has not been applied to this database yet; nothing to verify.');
832
- return lines.join('\n');
833
- }
834
- if (['already-migrated', 'fresh'].includes(report.status)) return lines.join('\n');
835
- if (report.users) lines.push(`Users: ${report.users} (${report.rootUsers} promoted to root)`);
836
- if (report.groupTeams.length > 0) {
837
- lines.push(`Legacy groups -> teams (${report.groupTeams.length}):`);
838
- for (const t of report.groupTeams) {
839
- lines.push(` "${t.group}" -> team "${t.team}", ${t.members} member(s), ${t.rules} rule(s)`);
840
- }
841
- }
842
- if (report.residualTeams.length > 0) {
843
- lines.push(`Generated residual teams (${report.residualTeams.length}):`);
844
- for (const t of report.residualTeams) {
845
- lines.push(` "${t.team}": ${t.members.join(', ')} (${t.rules} rule(s))`);
846
- }
847
- }
848
- if (report.accessTagsCopied) lines.push(`Access tags copied: ${report.accessTagsCopied}`);
849
- const items = Object.entries(report.reviewItems).filter(([, n]) => n > 0);
850
- if (items.length > 0)
851
- lines.push(`Review items: ${items.map(([k, n]) => `${k}=${n}`).join(', ')}`);
852
- if (report.parity) {
853
- lines.push(
854
- `Parity: ${report.parity.cells} cells compared, ${report.parity.diffs.length} unflagged difference(s), ${report.parity.tolerated} tolerated`,
855
- );
856
- if (report.parity.diffs.length > 0) lines.push(formatDiffs(report.parity.diffs));
857
- }
858
- return lines.join('\n');
859
- }
860
-
861
- module.exports = {
862
- runMigration,
863
- verifyParity,
864
- buildContext,
865
- isMigrated,
866
- formatReport,
867
- formatDiffs,
868
- globToMatcher,
869
- MigrationParityError,
870
- MIGRATED_KEY,
871
- };
1
+ // Legacy roles/groups/capabilities/tags -> teams/policies/rules/access tags (permissions v2,
2
+ // see .claude/plans/permissions-v2-implementation.md §7).
3
+ //
4
+ // runMigration() is idempotent (guarded by settings.authz_migrated_at), transactional, and
5
+ // drives itself off a frozen copy of the old authorization logic (legacy-oracle.js):
6
+ // 1. users.is_root := 1 for role='super_admin'
7
+ // 2. every legacy group -> one team + one generated policy ("<group> access")
8
+ // 3. tags matched by a group tag rule are copied into instance_auth_tags (access tags)
9
+ // 4. users the generated teams don't fully cover (zero-group admins, admin capability
10
+ // flags, admins' no-service env files) get explicit rules through generated
11
+ // "Legacy · ..." teams, grouped by identical rule signature
12
+ // 5/6. review items: admin_request, env_edit_via_glob (+ residual_fill / env_restart_broadened
13
+ // when something unusual had to be filled or tolerated)
14
+ // 7. parity verification over the §7.4 domain (old oracle vs. the real v2 engine)
15
+ // 8. settings.authz_migrated_at, revision bump, `migration.applied` audit event
16
+ // Any unflagged parity difference rolls the whole thing back and throws a
17
+ // MigrationParityError; the startup wrapper (authz/bootstrap.js) turns that into exit(1),
18
+ // tests and the CLI just catch it. A pre-migration backup (VACUUM INTO) is taken first.
19
+ //
20
+ // Everything here goes through `engine.can` / `engine.buildSubject` (via the module object,
21
+ // so tests can wrap them) — parity must exercise the real engine, not a reimplementation.
22
+
23
+ const path = require('path');
24
+ const { db, getSetting, setSetting } = require('../db');
25
+ const store = require('../authz-store');
26
+ const audit = require('../audit');
27
+ const engine = require('./engine');
28
+ const { validateRule } = require('./scope');
29
+ const { createLegacyOracle } = require('./legacy-oracle');
30
+
31
+ const MIGRATED_KEY = 'authz_migrated_at';
32
+ const SYSTEM_ACTOR = 'authz-migration';
33
+ // An instance id that cannot exist: `can(servers.create, {instanceId: PROBE})` is true only
34
+ // for an `all` rule (the "create over all servers" semantics routes/instances.js uses).
35
+ const PROBE_INSTANCE = '__pulse_authz_probe__';
36
+ const MAX_DOMAIN_NAMES = 400;
37
+
38
+ const ENV_ACTIONS = ['env.view', 'env.edit', 'env.restore', 'env.reveal'];
39
+ const MANAGE_ACTIONS = [
40
+ 'servers.update',
41
+ 'servers.delete',
42
+ 'servers.tags.manage',
43
+ 'servers.agent.update',
44
+ 'env.setup',
45
+ ];
46
+ // §7.3: legacy capability flag -> org actions.
47
+ const ORG_FLAG_ACTIONS = {
48
+ manageTeam: ['people.view', 'people.invite', 'people.remove'],
49
+ assignGroupMembers: [
50
+ 'teams.view',
51
+ 'teams.create',
52
+ 'teams.update',
53
+ 'teams.delete',
54
+ 'teams.members.manage',
55
+ 'teams.policies.manage',
56
+ 'policies.view',
57
+ 'policies.create',
58
+ 'policies.update',
59
+ 'policies.delete',
60
+ ],
61
+ };
62
+ // No legacy concept existed, so nobody may gain it through migration.
63
+ const NEVER_GRANTED_ORG_ACTIONS = ['audit.view'];
64
+
65
+ class MigrationParityError extends Error {
66
+ constructor(diffs, report) {
67
+ super(`authz migration parity check failed: ${diffs.length} unflagged difference(s)`);
68
+ this.name = 'MigrationParityError';
69
+ this.code = 'AUTHZ_MIGRATION_PARITY';
70
+ this.diffs = diffs;
71
+ this.report = report;
72
+ }
73
+ }
74
+
75
+ // Internal: thrown inside the transaction to roll a dry run back.
76
+ class DryRunAbort extends Error {
77
+ constructor(report) {
78
+ super('dry run');
79
+ this.report = report;
80
+ }
81
+ }
82
+
83
+ function isMigrated() {
84
+ return getSetting(MIGRATED_KEY) !== null;
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------------------
88
+ // Rule construction helpers
89
+ // ---------------------------------------------------------------------------------------
90
+
91
+ function unique(list) {
92
+ return [...new Set(list)];
93
+ }
94
+
95
+ function uniqueName(base, used) {
96
+ const clean = (base || '').trim() || 'Migrated';
97
+ let candidate = clean;
98
+ for (let n = 2; used.has(candidate.toLowerCase()); n++) candidate = `${clean} (${n})`;
99
+ used.add(candidate.toLowerCase());
100
+ return candidate;
101
+ }
102
+
103
+ // §7.2: x* -> startsWith, *x -> endsWith, *x* -> contains, no wildcard -> exact, else glob.
104
+ function globToMatcher(glob) {
105
+ if (!/[*?]/.test(glob)) return { op: 'exact', value: glob };
106
+ let m = /^([^*?]+)\*$/.exec(glob);
107
+ if (m) return { op: 'startsWith', value: m[1] };
108
+ m = /^\*([^*?]+)$/.exec(glob);
109
+ if (m) return { op: 'endsWith', value: m[1] };
110
+ m = /^\*([^*?]+)\*$/.exec(glob);
111
+ if (m) return { op: 'contains', value: m[1] };
112
+ return { op: 'glob', value: glob };
113
+ }
114
+
115
+ function matchersFromGlobs(globs) {
116
+ const seen = new Set();
117
+ const out = [];
118
+ for (const g of globs) {
119
+ const m = globToMatcher(g);
120
+ const key = `${m.op}:${m.value}`;
121
+ if (!seen.has(key)) {
122
+ seen.add(key);
123
+ out.push(m);
124
+ }
125
+ }
126
+ return out;
127
+ }
128
+
129
+ // A group's instance set expressed as server scopes: the explicit ids as one `ids` scope
130
+ // plus every tag rule as its own `tags/any/[tag]` scope, so rule union == the old
131
+ // "group_instances UNION tag matches" semantics.
132
+ function serverScopesForGroups(oracle, groupIds) {
133
+ const ids = [];
134
+ const tags = [];
135
+ for (const groupId of groupIds) {
136
+ ids.push(...(oracle.groupInstances.get(groupId) || []));
137
+ tags.push(...(oracle.groupTags.get(groupId) || []));
138
+ }
139
+ const scopes = [];
140
+ if (ids.length > 0) scopes.push({ type: 'ids', ids: unique(ids) });
141
+ for (const tag of unique(tags)) scopes.push({ type: 'tags', tags: [tag], match: 'any' });
142
+ return scopes;
143
+ }
144
+
145
+ // §7.2 step 2: the rules generated for one legacy group.
146
+ function rulesForGroup(oracle, group) {
147
+ const scopes = serverScopesForGroups(oracle, [group.id]);
148
+ const matchers = matchersFromGlobs(unique(oracle.groupProcesses.get(group.id) || []));
149
+ const processServices = matchers.length > 0 ? { matchers } : null;
150
+ const allowlist = unique(oracle.groupEnvFiles.get(group.id) || []);
151
+ const rules = [];
152
+
153
+ for (const servers of scopes) {
154
+ rules.push({ action: 'servers.view', scope: { servers } });
155
+ for (const action of ['metrics.view', 'logs.view']) {
156
+ rules.push({
157
+ action,
158
+ scope: processServices ? { servers, services: processServices } : { servers },
159
+ });
160
+ }
161
+ if (allowlist.length > 0) {
162
+ for (const action of ENV_ACTIONS) {
163
+ rules.push({ action, scope: { servers, envFiles: { ids: allowlist } } });
164
+ }
165
+ } else {
166
+ // The old rule required a linked service for non-admins, hence an explicit `*` glob
167
+ // when the group has no process restriction (a matcher-less rule would also match
168
+ // no-service files, which only admins could touch).
169
+ const services = processServices || { matchers: [{ op: 'glob', value: '*' }] };
170
+ for (const action of ENV_ACTIONS) rules.push({ action, scope: { servers, services } });
171
+ rules.push({ action: 'service.restart', scope: { servers, services } });
172
+ }
173
+ }
174
+
175
+ if (allowlist.length > 0) {
176
+ // service.restart has no env-file narrowing, so pin it to each allowlisted file's own
177
+ // instance + service name (still only where the group actually grants that instance).
178
+ const byInstance = new Map();
179
+ for (const file of oracle.envFiles) {
180
+ if (!allowlist.includes(file.id) || !file.service_name) continue;
181
+ if (oracle.getGroupIdsGrantingInstance([group.id], file.instance_id).length === 0) continue;
182
+ if (!byInstance.has(file.instance_id)) byInstance.set(file.instance_id, new Set());
183
+ byInstance.get(file.instance_id).add(file.service_name);
184
+ }
185
+ for (const [instanceId, names] of byInstance) {
186
+ rules.push({
187
+ action: 'service.restart',
188
+ scope: {
189
+ servers: { type: 'ids', ids: [instanceId] },
190
+ services: { matchers: [...names].map((value) => ({ op: 'exact', value })) },
191
+ },
192
+ });
193
+ }
194
+ }
195
+ return rules;
196
+ }
197
+
198
+ // §7.3 structured residual: what a group-derived team can never express for this user.
199
+ function structuredRulesForUser(oracle, user) {
200
+ const rules = [];
201
+ const allowed = oracle.getAllowedInstanceIds(user);
202
+ const all = { servers: { type: 'all' } };
203
+
204
+ // Zero-group admins were unrestricted — including servers registered tomorrow — so this
205
+ // must be an `all` rule, not a snapshot of today's instances.
206
+ if (allowed === null) {
207
+ for (const action of ['servers.view', 'metrics.view', 'logs.view']) {
208
+ rules.push({ action, scope: all });
209
+ }
210
+ for (const action of ENV_ACTIONS) rules.push({ action, scope: all });
211
+ rules.push({ action: 'service.restart', scope: all });
212
+ }
213
+
214
+ if (oracle.canManageInstances(user)) {
215
+ rules.push({ action: 'servers.create', scope: all });
216
+ const scopes =
217
+ allowed === null
218
+ ? [all.servers]
219
+ : serverScopesForGroups(oracle, oracle.groupMembers.get(user.id) || []);
220
+ for (const servers of scopes) {
221
+ for (const action of MANAGE_ACTIONS) rules.push({ action, scope: { servers } });
222
+ }
223
+ }
224
+ return rules;
225
+ }
226
+
227
+ function assertValid(rule) {
228
+ const result = validateRule(rule, { fromMigration: true });
229
+ if (!result.ok) {
230
+ throw new Error(`migration generated an invalid rule ${JSON.stringify(rule)}: ${result.error}`);
231
+ }
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------------------
235
+ // Parity domain + evaluation (shared by the residual fill and the verification)
236
+ // ---------------------------------------------------------------------------------------
237
+
238
+ // Strings that would distinguish glob semantics from matcher semantics.
239
+ function witnessesForGlob(glob) {
240
+ const variants = [
241
+ glob.replace(/\*/g, '').replace(/\?/g, 'a'),
242
+ glob.replace(/[*?]/g, 'x'),
243
+ glob.replace(/\*/g, 'xx').replace(/\?/g, 'x'),
244
+ ];
245
+ const out = new Set();
246
+ for (const v of variants) {
247
+ if (!v) continue;
248
+ out.add(v);
249
+ out.add(`${v}x`);
250
+ out.add(`x${v}`);
251
+ out.add(v.toUpperCase());
252
+ if (v.length > 1) out.add(v.slice(0, -1));
253
+ }
254
+ return out;
255
+ }
256
+
257
+ function buildDomain(oracle, extraProcessNames = []) {
258
+ const names = new Set(['pulse-no-such-process']);
259
+ for (const n of extraProcessNames) if (n) names.add(String(n));
260
+ for (const file of oracle.envFiles) if (file.service_name) names.add(file.service_name);
261
+ for (const globs of oracle.groupProcesses.values()) {
262
+ for (const glob of globs) for (const w of witnessesForGlob(glob)) names.add(w);
263
+ }
264
+ return {
265
+ instanceIds: oracle.instanceIds,
266
+ envFiles: oracle.envFiles,
267
+ names: [...names].filter(Boolean).slice(0, MAX_DOMAIN_NAMES),
268
+ };
269
+ }
270
+
271
+ // One user x whole domain: old verdict (oracle) next to the new verdict (real engine).
272
+ function evaluateUser(ctx, user, subject) {
273
+ const { oracle, domain } = ctx;
274
+ const can = (action, resource) => !!engine.can(subject, action, resource);
275
+ const cells = [];
276
+ const old = {
277
+ manageInstances: !!oracle.canManageInstances(user),
278
+ manageTeam: !!oracle.canManageTeam(user),
279
+ assignGroupMembers: !!oracle.canAssignGroupMembers(user),
280
+ allowed: oracle.getAllowedInstanceIds(user),
281
+ };
282
+
283
+ for (const [flag, actions] of Object.entries(ORG_FLAG_ACTIONS)) {
284
+ for (const action of actions) {
285
+ cells.push({ kind: 'org', action, old: old[flag], neu: can(action) });
286
+ }
287
+ }
288
+ for (const action of NEVER_GRANTED_ORG_ACTIONS) {
289
+ cells.push({ kind: 'org', action, old: false, neu: can(action) });
290
+ }
291
+ cells.push({
292
+ kind: 'create',
293
+ action: 'servers.create',
294
+ old: old.manageInstances,
295
+ neu: can('servers.create', { instanceId: PROBE_INSTANCE }),
296
+ });
297
+
298
+ for (const instanceId of domain.instanceIds) {
299
+ const visibleOld = old.allowed === null || old.allowed.has(instanceId);
300
+ const visibleNew = can('servers.view', { instanceId });
301
+ cells.push({
302
+ kind: 'view',
303
+ action: 'servers.view',
304
+ instanceId,
305
+ old: visibleOld,
306
+ neu: visibleNew,
307
+ });
308
+ for (const action of MANAGE_ACTIONS) {
309
+ cells.push({
310
+ kind: 'manage',
311
+ action,
312
+ instanceId,
313
+ old: old.manageInstances && visibleOld,
314
+ neu: can(action, { instanceId }),
315
+ });
316
+ }
317
+ if (visibleOld || visibleNew) {
318
+ const patterns = oracle.getAllowedProcessNames(user, instanceId);
319
+ for (const name of domain.names) {
320
+ const matchOld = visibleOld && (!patterns || oracle.matchesAnyPattern(name, patterns));
321
+ for (const action of ['metrics.view', 'logs.view']) {
322
+ cells.push({
323
+ kind: 'proc',
324
+ action,
325
+ instanceId,
326
+ name,
327
+ old: matchOld,
328
+ neu: visibleNew && can(action, { instanceId, serviceName: name }),
329
+ });
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ for (const file of domain.envFiles) {
336
+ const accessOld = !!oracle.canAccessEnvFile(user, file);
337
+ const serviceName = file.service_name || undefined;
338
+ for (const action of ENV_ACTIONS) {
339
+ cells.push({
340
+ kind: 'env',
341
+ action,
342
+ instanceId: file.instance_id,
343
+ envFileId: file.id,
344
+ noService: !file.service_name,
345
+ old: accessOld,
346
+ neu: can(action, { instanceId: file.instance_id, serviceName, envFileId: file.id }),
347
+ });
348
+ }
349
+ cells.push({
350
+ kind: 'restart',
351
+ action: 'service.restart',
352
+ instanceId: file.instance_id,
353
+ envFileId: file.id,
354
+ name: file.service_name || null,
355
+ old: accessOld && !!file.service_name,
356
+ neu:
357
+ !!file.service_name &&
358
+ can('service.restart', { instanceId: file.instance_id, serviceName }),
359
+ });
360
+ }
361
+ return cells;
362
+ }
363
+
364
+ function describeCell(cell) {
365
+ const where = cell.envFileId
366
+ ? ` env-file ${cell.envFileId} (instance ${cell.instanceId})`
367
+ : cell.instanceId
368
+ ? ` instance ${cell.instanceId}`
369
+ : '';
370
+ const name = cell.kind === 'proc' ? ` process "${cell.name}"` : '';
371
+ return `${cell.action}${where}${name}`;
372
+ }
373
+
374
+ // §7.2 step 4: old-yes/new-no cells -> explicit rules (the safety net behind the structured
375
+ // rules above). Never converts new-yes/old-no — that is a parity failure, not something to
376
+ // "fix" by removing access.
377
+ function rulesFromLostCells(cells, domain) {
378
+ const lost = cells.filter((c) => c.old && !c.neu);
379
+ const rules = [];
380
+ const byKey = (list, keyFn) => {
381
+ const map = new Map();
382
+ for (const item of list) {
383
+ const key = keyFn(item);
384
+ if (!map.has(key)) map.set(key, []);
385
+ map.get(key).push(item);
386
+ }
387
+ return map;
388
+ };
389
+
390
+ for (const c of lost.filter((x) => x.kind === 'org')) {
391
+ rules.push({ action: c.action, scope: null });
392
+ }
393
+ if (lost.some((x) => x.kind === 'create')) {
394
+ rules.push({ action: 'servers.create', scope: { servers: { type: 'all' } } });
395
+ }
396
+ for (const [action, group] of byKey(
397
+ lost.filter((x) => x.kind === 'view' || x.kind === 'manage'),
398
+ (x) => x.action,
399
+ )) {
400
+ rules.push({
401
+ action,
402
+ scope: { servers: { type: 'ids', ids: unique(group.map((x) => x.instanceId)) } },
403
+ });
404
+ }
405
+ for (const [, group] of byKey(
406
+ lost.filter((x) => x.kind === 'proc'),
407
+ (x) => `${x.action}\u0000${x.instanceId}`,
408
+ )) {
409
+ const servers = { type: 'ids', ids: [group[0].instanceId] };
410
+ const names = unique(group.map((x) => x.name));
411
+ rules.push({
412
+ action: group[0].action,
413
+ scope:
414
+ names.length >= domain.names.length
415
+ ? { servers }
416
+ : { servers, services: { matchers: names.map((value) => ({ op: 'exact', value })) } },
417
+ });
418
+ }
419
+ for (const [, group] of byKey(
420
+ lost.filter((x) => x.kind === 'env'),
421
+ (x) => `${x.action}\u0000${x.instanceId}`,
422
+ )) {
423
+ rules.push({
424
+ action: group[0].action,
425
+ scope: {
426
+ servers: { type: 'ids', ids: [group[0].instanceId] },
427
+ envFiles: { ids: unique(group.map((x) => x.envFileId)) },
428
+ },
429
+ });
430
+ }
431
+ for (const [, group] of byKey(
432
+ lost.filter((x) => x.kind === 'restart'),
433
+ (x) => x.instanceId,
434
+ )) {
435
+ rules.push({
436
+ action: 'service.restart',
437
+ scope: {
438
+ servers: { type: 'ids', ids: [group[0].instanceId] },
439
+ services: {
440
+ matchers: unique(group.map((x) => x.name)).map((value) => ({ op: 'exact', value })),
441
+ },
442
+ },
443
+ });
444
+ }
445
+
446
+ // What the fill covered beyond the two expected categories (org flags, admins' no-service
447
+ // env files) deserves a human look.
448
+ const unexpected = lost.filter((c) => !(c.kind === 'org' || (c.kind === 'env' && c.noService)));
449
+ return { rules, unexpected };
450
+ }
451
+
452
+ function ruleSignature(rules) {
453
+ return JSON.stringify(rules.map((r) => JSON.stringify([r.action, r.scope])).sort());
454
+ }
455
+
456
+ function describeRuleSet(rules) {
457
+ const actions = new Set(rules.map((r) => r.action));
458
+ const parts = [];
459
+ const hasAllServers = rules.some(
460
+ (r) => r.action === 'servers.view' && r.scope && r.scope.servers.type === 'all',
461
+ );
462
+ if (hasAllServers) parts.push('all servers');
463
+ if (actions.has('servers.create')) parts.push('server admin');
464
+ if (actions.has('people.invite')) parts.push('people');
465
+ if (actions.has('teams.create')) parts.push('teams');
466
+ if (rules.some((r) => r.action === 'env.view' && r.scope && r.scope.envFiles)) {
467
+ parts.push('env files');
468
+ }
469
+ return parts.length > 0 ? parts.join(', ') : 'access';
470
+ }
471
+
472
+ // ---------------------------------------------------------------------------------------
473
+ // Parity verification
474
+ // ---------------------------------------------------------------------------------------
475
+
476
+ function buildContext({ extraProcessNames = [] } = {}) {
477
+ const oracle = createLegacyOracle(db);
478
+ return { oracle, domain: buildDomain(oracle, extraProcessNames) };
479
+ }
480
+
481
+ // Compares the legacy oracle against the engine for every non-root user. Returns
482
+ // { cells, diffs, tolerated }. `diffs` are fatal; `tolerated` are access differences the
483
+ // new model cannot express exactly and that are surfaced as review items instead.
484
+ function verifyParity(ctx) {
485
+ const { oracle } = ctx;
486
+ const diffs = [];
487
+ const tolerated = [];
488
+ let cellCount = 0;
489
+ const rows = db.prepare('SELECT * FROM users ORDER BY created_at ASC, id ASC').all();
490
+
491
+ for (const row of rows) {
492
+ if (row.role === 'super_admin' && !row.is_root) {
493
+ diffs.push({
494
+ userId: row.id,
495
+ email: row.email,
496
+ kind: 'root',
497
+ old: true,
498
+ neu: false,
499
+ description: 'legacy super_admin is not is_root',
500
+ });
501
+ }
502
+ if (row.is_root) continue; // root bypasses every check by design
503
+ const subject = engine.buildSubject(row, store);
504
+ const cells = evaluateUser(ctx, row, subject);
505
+ cellCount += cells.length;
506
+ for (const cell of cells) {
507
+ if (cell.old === cell.neu) continue;
508
+ const diff = {
509
+ userId: row.id,
510
+ email: row.email,
511
+ kind: cell.kind,
512
+ action: cell.action,
513
+ instanceId: cell.instanceId || null,
514
+ envFileId: cell.envFileId || null,
515
+ name: cell.name || null,
516
+ old: cell.old,
517
+ neu: cell.neu,
518
+ description: describeCell(cell),
519
+ };
520
+ // service.restart cannot be narrowed to one env file, so an allowlisted file whose
521
+ // instance + service name is shared with another file the user may use broadens to
522
+ // that sibling. Everything else is fatal.
523
+ if (cell.kind === 'restart' && !cell.old && cell.neu) {
524
+ const sibling = oracle.envFiles.find(
525
+ (f) =>
526
+ f.id !== cell.envFileId &&
527
+ f.instance_id === cell.instanceId &&
528
+ f.service_name === cell.name &&
529
+ oracle.canAccessEnvFile(row, f),
530
+ );
531
+ if (sibling) {
532
+ tolerated.push({ ...diff, reason: 'env_restart_broadened' });
533
+ continue;
534
+ }
535
+ }
536
+ diffs.push(diff);
537
+ }
538
+ }
539
+ return { cells: cellCount, diffs, tolerated };
540
+ }
541
+
542
+ // ---------------------------------------------------------------------------------------
543
+ // The migration proper
544
+ // ---------------------------------------------------------------------------------------
545
+
546
+ function backupDatabase() {
547
+ if (db.memory || !db.name) return null;
548
+ const file = path.join(path.dirname(db.name), `pulse.pre-authz-${Date.now()}.db`);
549
+ db.exec(`VACUUM INTO '${file.replace(/'/g, "''")}'`);
550
+ return file;
551
+ }
552
+
553
+ function applyMigration(ctx, options, report) {
554
+ const { oracle } = ctx;
555
+ const rootRow = db
556
+ .prepare("SELECT id FROM users WHERE role = 'super_admin' ORDER BY created_at ASC, id ASC")
557
+ .get();
558
+ const anyRow = db.prepare('SELECT id FROM users ORDER BY created_at ASC, id ASC').get();
559
+ const createdBy = (rootRow || anyRow).id;
560
+
561
+ // 1. root
562
+ report.rootUsers = db
563
+ .prepare("UPDATE users SET is_root = 1 WHERE role = 'super_admin'")
564
+ .run().changes;
565
+
566
+ // 2. groups -> teams + policies
567
+ const teamNames = new Set(store.listTeams().map((t) => t.name.toLowerCase()));
568
+ const policyNames = new Set(store.listPolicies().map((p) => p.name.toLowerCase()));
569
+ for (const group of oracle.groups) {
570
+ const team = store.createTeam(
571
+ {
572
+ name: uniqueName(group.name, teamNames),
573
+ description: `Migrated from legacy group "${group.name}"`,
574
+ },
575
+ createdBy,
576
+ );
577
+ const memberIds = unique(
578
+ [...oracle.users.keys()].filter((id) =>
579
+ (oracle.groupMembers.get(id) || []).includes(group.id),
580
+ ),
581
+ );
582
+ for (const userId of memberIds) store.addTeamMember(team.id, userId, SYSTEM_ACTOR);
583
+ const policy = store.createPolicy(
584
+ {
585
+ name: uniqueName(`${team.name} access`, policyNames),
586
+ description: `Generated from legacy group "${group.name}" (instances, tags, process restriction, env-file allowlist)`,
587
+ },
588
+ null,
589
+ );
590
+ const rules = rulesForGroup(oracle, group);
591
+ for (const rule of rules) {
592
+ assertValid(rule);
593
+ store.addPolicyRule(policy.id, rule);
594
+ }
595
+ store.attachPolicy(team.id, policy.id, SYSTEM_ACTOR);
596
+ report.groupTeams.push({
597
+ group: group.name,
598
+ team: team.name,
599
+ policy: policy.name,
600
+ members: memberIds.length,
601
+ rules: rules.length,
602
+ });
603
+ }
604
+
605
+ // 3. access tags: every tag a group tag rule could match, on every instance carrying it
606
+ const copyTag = db.prepare(
607
+ 'INSERT OR IGNORE INTO instance_auth_tags (instance_id, tag) SELECT DISTINCT instance_id, tag FROM instance_tags WHERE tag = ?',
608
+ );
609
+ for (const tag of unique([...oracle.groupTags.values()].flat())) {
610
+ report.accessTagsCopied += copyTag.run(tag).changes;
611
+ }
612
+
613
+ // 4. residual fill, per non-root user
614
+ const userRows = db.prepare('SELECT * FROM users ORDER BY created_at ASC, id ASC').all();
615
+ const plans = new Map(); // signature -> { rules, users: [row], descSource }
616
+ const fillNotes = [];
617
+ for (const row of userRows) {
618
+ if (row.is_root) continue;
619
+ const structured = structuredRulesForUser(oracle, row);
620
+ const subject = engine.buildSubject(row, store);
621
+ subject.rules.push(...structured.map((r) => ({ ...r, teamId: null, policyId: null })));
622
+ const cells = evaluateUser(ctx, row, subject);
623
+ const fill = rulesFromLostCells(cells, ctx.domain);
624
+ const rules = [...structured, ...fill.rules];
625
+ if (fill.unexpected.length > 0) {
626
+ fillNotes.push({
627
+ userId: row.id,
628
+ email: row.email,
629
+ cells: fill.unexpected.length,
630
+ sample: fill.unexpected.slice(0, 5).map(describeCell),
631
+ });
632
+ }
633
+ if (rules.length === 0) continue;
634
+ for (const rule of rules) assertValid(rule);
635
+ const signature = ruleSignature(rules);
636
+ if (!plans.has(signature)) plans.set(signature, { rules, users: [] });
637
+ plans.get(signature).users.push(row);
638
+ }
639
+ let n = 0;
640
+ for (const plan of plans.values()) {
641
+ n += 1;
642
+ const label = `Legacy · ${describeRuleSet(plan.rules)} · ${n}`;
643
+ const team = store.createTeam(
644
+ {
645
+ name: uniqueName(label, teamNames),
646
+ description: 'Generated by the permissions migration to preserve existing access exactly',
647
+ },
648
+ createdBy,
649
+ );
650
+ const policy = store.createPolicy(
651
+ {
652
+ name: uniqueName(label, policyNames),
653
+ description: 'Generated by the permissions migration (legacy role/capability residual)',
654
+ },
655
+ null,
656
+ );
657
+ for (const rule of plan.rules) store.addPolicyRule(policy.id, rule);
658
+ store.attachPolicy(team.id, policy.id, SYSTEM_ACTOR);
659
+ for (const user of plan.users) store.addTeamMember(team.id, user.id, SYSTEM_ACTOR);
660
+ report.residualTeams.push({
661
+ team: team.name,
662
+ policy: policy.name,
663
+ members: plan.users.map((u) => u.email || u.id),
664
+ rules: plan.rules.length,
665
+ });
666
+ }
667
+
668
+ // 5. admin-request flow -> review items
669
+ for (const row of userRows) {
670
+ if (!row.admin_requested_at) continue;
671
+ store.createReviewItem({
672
+ kind: 'admin_request',
673
+ userId: row.id,
674
+ detail: `Requested admin access on ${new Date(row.admin_requested_at).toISOString()}. The approval flow no longer exists; put this person in a team to grant access.`,
675
+ });
676
+ report.reviewItems.admin_request += 1;
677
+ }
678
+
679
+ // 6. viewers who could edit env files through a group's process globs
680
+ for (const row of userRows) {
681
+ if (row.role !== 'viewer' || row.is_root) continue;
682
+ for (const file of oracle.envFiles) {
683
+ if (!oracle.canAccessEnvFile(row, file)) continue;
684
+ store.createReviewItem({
685
+ kind: 'env_edit_via_glob',
686
+ userId: row.id,
687
+ instanceId: file.instance_id,
688
+ envFileId: file.id,
689
+ detail: `Viewer could edit "${file.label}" (${file.path}) through a group's service access. Migration preserved env view/edit/restore/reveal and restart; review whether that is intended.`,
690
+ });
691
+ report.reviewItems.env_edit_via_glob += 1;
692
+ }
693
+ }
694
+ for (const note of fillNotes) {
695
+ store.createReviewItem({
696
+ kind: 'residual_fill',
697
+ userId: note.userId,
698
+ detail: `Migration had to add ${note.cells} explicit permission(s) beyond the standard mapping: ${note.sample.join('; ')}`,
699
+ });
700
+ report.reviewItems.residual_fill += 1;
701
+ }
702
+
703
+ if (typeof options.beforeVerify === 'function') options.beforeVerify({ db, store, engine });
704
+
705
+ // 7. parity
706
+ const parity = verifyParity(ctx);
707
+ report.parity = {
708
+ cells: parity.cells,
709
+ diffs: parity.diffs,
710
+ tolerated: parity.tolerated.length,
711
+ };
712
+ if (parity.diffs.length > 0) throw new MigrationParityError(parity.diffs, report);
713
+ for (const t of parity.tolerated) {
714
+ store.createReviewItem({
715
+ kind: 'env_restart_broadened',
716
+ userId: t.userId,
717
+ instanceId: t.instanceId,
718
+ envFileId: t.envFileId,
719
+ detail: `Restarting "${t.name}" is now also allowed from env file ${t.envFileId}, which the user could not previously restart: service restarts cannot be limited to a single env file.`,
720
+ });
721
+ report.reviewItems.env_restart_broadened += 1;
722
+ }
723
+
724
+ if (options.dryRun) throw new DryRunAbort(report);
725
+
726
+ // 8. finish
727
+ setSetting(MIGRATED_KEY, String(Date.now()));
728
+ report.revision = store.bumpAuthzRevision();
729
+ audit.record({
730
+ action: 'migration.applied',
731
+ targetType: 'authz',
732
+ outcome: 'succeeded',
733
+ summary: `Migrated ${oracle.groups.length} group(s) and ${userRows.length} user(s) to teams and policies`,
734
+ metadata: {
735
+ groupTeams: report.groupTeams.length,
736
+ residualTeams: report.residualTeams.length,
737
+ rootUsers: report.rootUsers,
738
+ accessTagsCopied: report.accessTagsCopied,
739
+ reviewItems: report.reviewItems,
740
+ parityCells: report.parity.cells,
741
+ backup: report.backupPath,
742
+ },
743
+ });
744
+ }
745
+
746
+ function newReport(status) {
747
+ return {
748
+ status,
749
+ dryRun: false,
750
+ backupPath: null,
751
+ users: 0,
752
+ rootUsers: 0,
753
+ groupTeams: [],
754
+ residualTeams: [],
755
+ accessTagsCopied: 0,
756
+ reviewItems: {
757
+ admin_request: 0,
758
+ env_edit_via_glob: 0,
759
+ residual_fill: 0,
760
+ env_restart_broadened: 0,
761
+ },
762
+ parity: null,
763
+ revision: null,
764
+ };
765
+ }
766
+
767
+ // options: { dryRun, verifyOnly, extraProcessNames, beforeVerify (test hook) }
768
+ // Statuses: 'migrated' | 'dry-run' | 'already-migrated' | 'fresh' | 'verified' |
769
+ // 'not-migrated' (verifyOnly before the migration ran). Throws MigrationParityError when
770
+ // parity fails (the transaction is rolled back; a verify-only run changed nothing anyway).
771
+ function runMigration(options = {}) {
772
+ const migrated = isMigrated();
773
+
774
+ if (options.verifyOnly) {
775
+ if (!migrated) return newReport('not-migrated');
776
+ const report = newReport('verified');
777
+ const parity = verifyParity(buildContext(options));
778
+ report.parity = {
779
+ cells: parity.cells,
780
+ diffs: parity.diffs,
781
+ tolerated: parity.tolerated.length,
782
+ };
783
+ if (parity.diffs.length > 0) throw new MigrationParityError(parity.diffs, report);
784
+ return report;
785
+ }
786
+
787
+ if (migrated) return newReport('already-migrated');
788
+
789
+ const userCount = db.prepare('SELECT COUNT(*) AS c FROM users').get().c;
790
+ if (userCount === 0) {
791
+ // Nothing to preserve: a fresh install starts on v2 directly.
792
+ const report = newReport('fresh');
793
+ if (options.dryRun) {
794
+ report.dryRun = true;
795
+ return report;
796
+ }
797
+ setSetting(MIGRATED_KEY, String(Date.now()));
798
+ return report;
799
+ }
800
+
801
+ const report = newReport(options.dryRun ? 'dry-run' : 'migrated');
802
+ report.dryRun = !!options.dryRun;
803
+ report.users = userCount;
804
+ if (!options.dryRun) report.backupPath = backupDatabase();
805
+
806
+ const ctx = buildContext(options);
807
+ try {
808
+ db.transaction(() => applyMigration(ctx, options, report))();
809
+ } catch (err) {
810
+ if (err instanceof DryRunAbort) return report; // rolled back by the throw
811
+ throw err;
812
+ }
813
+ return report;
814
+ }
815
+
816
+ function formatDiffs(diffs, limit = 50) {
817
+ const lines = diffs
818
+ .slice(0, limit)
819
+ .map(
820
+ (d) =>
821
+ ` ${d.email || d.userId}: ${d.description} — legacy ${d.old ? 'ALLOWED' : 'denied'}, v2 ${d.neu ? 'ALLOWED' : 'denied'}`,
822
+ );
823
+ if (diffs.length > limit) lines.push(` ... and ${diffs.length - limit} more`);
824
+ return lines.join('\n');
825
+ }
826
+
827
+ function formatReport(report) {
828
+ const lines = [`Status: ${report.status}${report.dryRun ? ' (nothing written)' : ''}`];
829
+ if (report.backupPath) lines.push(`Backup: ${report.backupPath}`);
830
+ if (report.status === 'not-migrated') {
831
+ lines.push('The migration has not been applied to this database yet; nothing to verify.');
832
+ return lines.join('\n');
833
+ }
834
+ if (['already-migrated', 'fresh'].includes(report.status)) return lines.join('\n');
835
+ if (report.users) lines.push(`Users: ${report.users} (${report.rootUsers} promoted to root)`);
836
+ if (report.groupTeams.length > 0) {
837
+ lines.push(`Legacy groups -> teams (${report.groupTeams.length}):`);
838
+ for (const t of report.groupTeams) {
839
+ lines.push(` "${t.group}" -> team "${t.team}", ${t.members} member(s), ${t.rules} rule(s)`);
840
+ }
841
+ }
842
+ if (report.residualTeams.length > 0) {
843
+ lines.push(`Generated residual teams (${report.residualTeams.length}):`);
844
+ for (const t of report.residualTeams) {
845
+ lines.push(` "${t.team}": ${t.members.join(', ')} (${t.rules} rule(s))`);
846
+ }
847
+ }
848
+ if (report.accessTagsCopied) lines.push(`Access tags copied: ${report.accessTagsCopied}`);
849
+ const items = Object.entries(report.reviewItems).filter(([, n]) => n > 0);
850
+ if (items.length > 0)
851
+ lines.push(`Review items: ${items.map(([k, n]) => `${k}=${n}`).join(', ')}`);
852
+ if (report.parity) {
853
+ lines.push(
854
+ `Parity: ${report.parity.cells} cells compared, ${report.parity.diffs.length} unflagged difference(s), ${report.parity.tolerated} tolerated`,
855
+ );
856
+ if (report.parity.diffs.length > 0) lines.push(formatDiffs(report.parity.diffs));
857
+ }
858
+ return lines.join('\n');
859
+ }
860
+
861
+ module.exports = {
862
+ runMigration,
863
+ verifyParity,
864
+ buildContext,
865
+ isMigrated,
866
+ formatReport,
867
+ formatDiffs,
868
+ globToMatcher,
869
+ MigrationParityError,
870
+ MIGRATED_KEY,
871
+ };