pulse-hub 0.0.0-stage → 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 (84) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/LICENSE +5 -0
  3. package/README.md +86 -2
  4. package/backend/.env.example +52 -0
  5. package/backend/agent-package.json +9 -0
  6. package/backend/agent.config.example.json +6 -0
  7. package/backend/agent.js +372 -0
  8. package/backend/authz-migrate.js +76 -0
  9. package/backend/cli.js +1021 -0
  10. package/backend/config.js +120 -0
  11. package/backend/emails/env-backup.html +52 -0
  12. package/backend/emails/invite.html +53 -0
  13. package/backend/install-agent.sh +181 -0
  14. package/backend/lib/agent-rpc.js +72 -0
  15. package/backend/lib/async-route.js +17 -0
  16. package/backend/lib/audit.js +134 -0
  17. package/backend/lib/auth-google.js +78 -0
  18. package/backend/lib/authz/bootstrap.js +35 -0
  19. package/backend/lib/authz/catalog.js +291 -0
  20. package/backend/lib/authz/delegation.js +104 -0
  21. package/backend/lib/authz/effective.js +104 -0
  22. package/backend/lib/authz/engine.js +251 -0
  23. package/backend/lib/authz/index.js +134 -0
  24. package/backend/lib/authz/legacy-oracle.js +195 -0
  25. package/backend/lib/authz/migrate.js +871 -0
  26. package/backend/lib/authz/mutate.js +87 -0
  27. package/backend/lib/authz/preview.js +327 -0
  28. package/backend/lib/authz/scope.js +282 -0
  29. package/backend/lib/authz/templates.js +103 -0
  30. package/backend/lib/authz-store.js +535 -0
  31. package/backend/lib/bundle-version.js +71 -0
  32. package/backend/lib/config-check.js +100 -0
  33. package/backend/lib/crypto-helpers.js +15 -0
  34. package/backend/lib/db.js +984 -0
  35. package/backend/lib/env-backup.js +306 -0
  36. package/backend/lib/env-crypto.js +52 -0
  37. package/backend/lib/env-files.js +235 -0
  38. package/backend/lib/env-mask.js +131 -0
  39. package/backend/lib/gmail-send.js +234 -0
  40. package/backend/lib/http-helpers.js +48 -0
  41. package/backend/lib/instance-registry.js +34 -0
  42. package/backend/lib/invite-helpers.js +83 -0
  43. package/backend/lib/invites.js +160 -0
  44. package/backend/lib/jwt.js +59 -0
  45. package/backend/lib/logs.js +244 -0
  46. package/backend/lib/metrics.js +249 -0
  47. package/backend/lib/migrate-legacy.js +106 -0
  48. package/backend/lib/paths.js +17 -0
  49. package/backend/lib/relay-state.js +564 -0
  50. package/backend/lib/self-update.js +68 -0
  51. package/backend/lib/session.js +48 -0
  52. package/backend/lib/sqlite.js +197 -0
  53. package/backend/lib/static-files.js +86 -0
  54. package/backend/middleware/authz.js +65 -0
  55. package/backend/middleware/session-gate.js +38 -0
  56. package/backend/public/assets/favicon.ico +0 -0
  57. package/backend/public/assets/favicon.svg +6 -0
  58. package/backend/public/assets/index.css +1 -0
  59. package/backend/public/assets/index.js +111 -0
  60. package/backend/public/assets/inter-cyrillic-ext-wght-normal.woff2 +0 -0
  61. package/backend/public/assets/inter-cyrillic-wght-normal.woff2 +0 -0
  62. package/backend/public/assets/inter-greek-ext-wght-normal.woff2 +0 -0
  63. package/backend/public/assets/inter-greek-wght-normal.woff2 +0 -0
  64. package/backend/public/assets/inter-latin-ext-wght-normal.woff2 +0 -0
  65. package/backend/public/assets/inter-latin-wght-normal.woff2 +0 -0
  66. package/backend/public/assets/inter-vietnamese-wght-normal.woff2 +0 -0
  67. package/backend/public/index.html +25 -0
  68. package/backend/routes/access.js +123 -0
  69. package/backend/routes/audit.js +41 -0
  70. package/backend/routes/auth.js +207 -0
  71. package/backend/routes/env-files.js +943 -0
  72. package/backend/routes/instances.js +555 -0
  73. package/backend/routes/invites-public.js +91 -0
  74. package/backend/routes/invites.js +121 -0
  75. package/backend/routes/logs.js +68 -0
  76. package/backend/routes/metrics.js +76 -0
  77. package/backend/routes/policies.js +240 -0
  78. package/backend/routes/static.js +100 -0
  79. package/backend/routes/teams.js +221 -0
  80. package/backend/routes/users.js +100 -0
  81. package/backend/seed-admins.js +68 -0
  82. package/backend/server.js +106 -0
  83. package/backend/ws/agent-relay.js +159 -0
  84. package/package.json +95 -4
@@ -0,0 +1,87 @@
1
+ // Shared plumbing for access-changing routes: delegation guard, impact confirmation, and an
2
+ // atomic "mutation + audit + revision bump" transaction that emits the revision event only
3
+ // after commit (so open streams revalidate against committed data).
4
+ const { db } = require('../db');
5
+ const store = require('../authz-store');
6
+ const authz = require('./index');
7
+ const { canDelegate } = require('./delegation');
8
+ const previewLib = require('./preview');
9
+
10
+ class StaleRevisionError extends Error {}
11
+
12
+ // Runs fn() in one transaction, bumps the authorization revision inside it, then emits the
13
+ // revision event after commit. If `expectedRevision` is given and the stored revision has
14
+ // moved, aborts (nothing written) with StaleRevisionError.
15
+ function mutate(fn, { expectedRevision = null } = {}) {
16
+ let rev;
17
+ const out = db.transaction(() => {
18
+ if (expectedRevision !== null && store.getAuthzRevision() !== expectedRevision) {
19
+ throw new StaleRevisionError('stale');
20
+ }
21
+ const r = fn();
22
+ rev = store.bumpAuthzRevision();
23
+ return r;
24
+ })();
25
+ authz.authzEvents.emit('revision', rev);
26
+ return out;
27
+ }
28
+
29
+ function sendJson(res, status, body) {
30
+ res.writeHead(status, { 'Content-Type': 'application/json' });
31
+ res.end(JSON.stringify(body));
32
+ }
33
+
34
+ // Delegation guard (privilege-escalation check). Returns true to proceed; otherwise writes a
35
+ // 403 listing what the actor cannot grant.
36
+ function requireDelegable(req, res, change) {
37
+ const state = store.loadState();
38
+ const rules = previewLib.rulesToDelegate(state, change);
39
+ if (rules.length === 0) return true;
40
+ const r = canDelegate(req.authz.subject, rules);
41
+ if (r.ok) return true;
42
+ sendJson(res, 403, {
43
+ error: 'You cannot grant access you do not hold yourself.',
44
+ denied: r.denied.map((d) => d.rule || d),
45
+ });
46
+ return false;
47
+ }
48
+
49
+ // Impact confirmation. If the change would alter anyone's effective access, the request
50
+ // must carry confirmRevision equal to the current revision, else 409 with a fresh preview.
51
+ // Returns {proceed:true, expectedRevision} (expectedRevision null when nothing was affected).
52
+ function requireConfirmation(req, res, change, confirmRevision) {
53
+ const p = previewLib.preview(change, req.authz.subject);
54
+ if (p.counts.affected === 0) return { proceed: true, expectedRevision: null };
55
+ const given =
56
+ confirmRevision === undefined || confirmRevision === null ? null : Number(confirmRevision);
57
+ if (given === null) {
58
+ sendJson(res, 409, { code: 'CONFIRMATION_REQUIRED', preview: p });
59
+ return { proceed: false };
60
+ }
61
+ if (given !== p.revision) {
62
+ sendJson(res, 409, { code: 'STALE_PREVIEW', preview: p });
63
+ return { proceed: false };
64
+ }
65
+ return { proceed: true, expectedRevision: given };
66
+ }
67
+
68
+ // Maps a StaleRevisionError thrown by mutate() into the same 409 the pre-check produces.
69
+ function handleStale(res, e, change, req) {
70
+ if (e instanceof StaleRevisionError) {
71
+ sendJson(res, 409, {
72
+ code: 'STALE_PREVIEW',
73
+ preview: previewLib.preview(change, req.authz.subject),
74
+ });
75
+ return true;
76
+ }
77
+ return false;
78
+ }
79
+
80
+ module.exports = {
81
+ mutate,
82
+ sendJson,
83
+ requireDelegable,
84
+ requireConfirmation,
85
+ handleStale,
86
+ StaleRevisionError,
87
+ };
@@ -0,0 +1,327 @@
1
+ // Impact preview for access changes — runs the REAL scope-matching code over an in-memory
2
+ // copy of the whole authorization state (authz-store.loadState()) before and after a
3
+ // hypothetical change, and diffs each person's effective permission cells.
4
+ //
5
+ // Cell = (action, instanceId, service signature, env-file signature). Rules are unioned, so
6
+ // a narrower cell is dropped whenever an unrestricted cell exists for the same
7
+ // (action, instance). Root users bypass every check and are never part of a diff.
8
+ const { db } = require('../db');
9
+ const store = require('../authz-store');
10
+ const { getAction, ACTIONS } = require('./catalog');
11
+ const { serverMatches } = require('./scope');
12
+ const { canDelegate } = require('./delegation');
13
+
14
+ const CHANGE_KINDS = [
15
+ 'team.members.set',
16
+ 'team.policies.set',
17
+ 'policy.update',
18
+ 'policy.delete',
19
+ 'team.delete',
20
+ 'access-tags.set',
21
+ 'invite.create',
22
+ ];
23
+
24
+ function closureOf(action) {
25
+ const out = new Set([action]);
26
+ const walk = (a) => {
27
+ const def = getAction(a);
28
+ if (def && def.implies) {
29
+ def.implies.forEach((i) => {
30
+ if (!out.has(i)) {
31
+ out.add(i);
32
+ walk(i);
33
+ }
34
+ });
35
+ }
36
+ };
37
+ walk(action);
38
+ return out;
39
+ }
40
+
41
+ function sigOf(def, scope) {
42
+ if (def.scopeKind === 'org' || def.scopeKind === 'server') return '';
43
+ const svc =
44
+ scope && scope.services && scope.services.matchers.length > 0
45
+ ? JSON.stringify(scope.services.matchers.map((m) => `${m.op}:${m.value}`).sort())
46
+ : '*';
47
+ if (def.scopeKind === 'service') return `svc=${svc}`;
48
+ const env = scope && scope.envFiles ? JSON.stringify([...scope.envFiles.ids].sort()) : '*';
49
+ return `svc=${svc};env=${env}`;
50
+ }
51
+
52
+ function rulesForUser(state, userId) {
53
+ const teamIds = state.teamMembers.filter((m) => m.user_id === userId).map((m) => m.team_id);
54
+ const policyIds = new Set(
55
+ state.teamPolicies.filter((tp) => teamIds.includes(tp.team_id)).map((tp) => tp.policy_id),
56
+ );
57
+ return state.policyRules.filter((r) => policyIds.has(r.policy_id));
58
+ }
59
+
60
+ function cellsFor(state, rules) {
61
+ const tagsOf = new Map();
62
+ for (const t of state.instanceAuthTags) {
63
+ if (!tagsOf.has(t.instance_id)) tagsOf.set(t.instance_id, []);
64
+ tagsOf.get(t.instance_id).push(t.tag);
65
+ }
66
+ const authTagsOf = (id) => tagsOf.get(id) || [];
67
+ const cells = new Map();
68
+ const add = (action, instanceId, sig) => {
69
+ const key = `${action}\u0000${instanceId || ''}\u0000${sig}`;
70
+ cells.set(key, { action, instanceId: instanceId || null, sig });
71
+ };
72
+ for (const rule of rules) {
73
+ const def = getAction(rule.action);
74
+ if (!def) continue;
75
+ for (const action of closureOf(rule.action)) {
76
+ const adef = getAction(action);
77
+ if (adef.scopeKind === 'org') {
78
+ add(action, null, '');
79
+ continue;
80
+ }
81
+ if (!rule.scope || !rule.scope.servers) continue;
82
+ for (const instanceId of state.instances) {
83
+ if (serverMatches(rule.scope.servers, { id: instanceId }, authTagsOf)) {
84
+ add(action, instanceId, sigOf(adef, rule.scope));
85
+ }
86
+ }
87
+ }
88
+ }
89
+ // Union semantics: an unrestricted cell subsumes any narrower one for the same target.
90
+ const WIDE = ['svc=*', 'svc=*;env=*'];
91
+ for (const [key, c] of [...cells]) {
92
+ if (c.sig === '' || WIDE.includes(c.sig)) continue;
93
+ if (WIDE.some((s) => cells.has(`${c.action}\u0000${c.instanceId || ''}\u0000${s}`))) {
94
+ cells.delete(key);
95
+ }
96
+ }
97
+ return cells;
98
+ }
99
+
100
+ function effectiveMatrix(state, rootIds) {
101
+ const out = new Map();
102
+ for (const u of state.users) {
103
+ if (rootIds.has(u.id)) continue;
104
+ out.set(u.id, cellsFor(state, rulesForUser(state, u.id)));
105
+ }
106
+ return out;
107
+ }
108
+
109
+ function cloneState(state) {
110
+ return {
111
+ ...state,
112
+ teams: [...state.teams],
113
+ teamMembers: [...state.teamMembers],
114
+ policies: [...state.policies],
115
+ policyRules: [...state.policyRules],
116
+ teamPolicies: [...state.teamPolicies],
117
+ instances: [...state.instances],
118
+ instanceAuthTags: [...state.instanceAuthTags],
119
+ users: [...state.users],
120
+ };
121
+ }
122
+
123
+ // Pure: returns a new state with the change applied (never touches the DB).
124
+ function applyChange(state, change) {
125
+ const s = cloneState(state);
126
+ switch (change.kind) {
127
+ case 'team.members.set':
128
+ s.teamMembers = s.teamMembers.filter((m) => m.team_id !== change.teamId);
129
+ for (const userId of change.userIds || [])
130
+ s.teamMembers.push({ team_id: change.teamId, user_id: userId });
131
+ break;
132
+ case 'team.policies.set':
133
+ s.teamPolicies = s.teamPolicies.filter((tp) => tp.team_id !== change.teamId);
134
+ for (const policyId of change.policyIds || [])
135
+ s.teamPolicies.push({ team_id: change.teamId, policy_id: policyId });
136
+ break;
137
+ case 'policy.update':
138
+ s.policyRules = s.policyRules.filter((r) => r.policy_id !== change.policyId);
139
+ (change.rules || []).forEach((r, i) =>
140
+ s.policyRules.push({
141
+ id: `preview-${i}`,
142
+ policy_id: change.policyId,
143
+ action: r.action,
144
+ scope: r.scope || null,
145
+ }),
146
+ );
147
+ break;
148
+ case 'policy.delete':
149
+ s.policyRules = s.policyRules.filter((r) => r.policy_id !== change.policyId);
150
+ s.teamPolicies = s.teamPolicies.filter((tp) => tp.policy_id !== change.policyId);
151
+ s.policies = s.policies.filter((p) => p.id !== change.policyId);
152
+ break;
153
+ case 'team.delete':
154
+ s.teamMembers = s.teamMembers.filter((m) => m.team_id !== change.teamId);
155
+ s.teamPolicies = s.teamPolicies.filter((tp) => tp.team_id !== change.teamId);
156
+ s.teams = s.teams.filter((t) => t.id !== change.teamId);
157
+ break;
158
+ case 'access-tags.set':
159
+ s.instanceAuthTags = s.instanceAuthTags.filter((t) => t.instance_id !== change.instanceId);
160
+ for (const tag of change.tags || [])
161
+ s.instanceAuthTags.push({ instance_id: change.instanceId, tag });
162
+ break;
163
+ case 'invite.create': {
164
+ const id = `invite:${change.email}`;
165
+ s.users.push({ id, email: change.email });
166
+ for (const teamId of change.teamIds || [])
167
+ s.teamMembers.push({ team_id: teamId, user_id: id });
168
+ break;
169
+ }
170
+ default:
171
+ throw new Error(`Unknown change kind: ${change.kind}`);
172
+ }
173
+ return s;
174
+ }
175
+
176
+ function rulesOfPolicies(state, policyIds) {
177
+ const set = new Set(policyIds);
178
+ return state.policyRules
179
+ .filter((r) => set.has(r.policy_id))
180
+ .map((r) => ({ action: r.action, scope: r.scope }));
181
+ }
182
+
183
+ function ruleKey(r) {
184
+ return `${r.action}|${JSON.stringify(r.scope || null)}`;
185
+ }
186
+
187
+ // The rules a change would hand to people, which the actor must be able to delegate (a
188
+ // privilege-escalation guard — see delegation.js). Removing access is always allowed.
189
+ function rulesToDelegate(state, change) {
190
+ switch (change.kind) {
191
+ case 'team.members.set': {
192
+ const current = new Set(
193
+ state.teamMembers.filter((m) => m.team_id === change.teamId).map((m) => m.user_id),
194
+ );
195
+ const added = (change.userIds || []).some((id) => !current.has(id));
196
+ if (!added) return [];
197
+ const policyIds = state.teamPolicies
198
+ .filter((tp) => tp.team_id === change.teamId)
199
+ .map((tp) => tp.policy_id);
200
+ return rulesOfPolicies(state, policyIds);
201
+ }
202
+ case 'team.policies.set': {
203
+ const current = new Set(
204
+ state.teamPolicies.filter((tp) => tp.team_id === change.teamId).map((tp) => tp.policy_id),
205
+ );
206
+ return rulesOfPolicies(
207
+ state,
208
+ (change.policyIds || []).filter((id) => !current.has(id)),
209
+ );
210
+ }
211
+ case 'policy.update': {
212
+ const existing = new Set(
213
+ state.policyRules.filter((r) => r.policy_id === change.policyId).map(ruleKey),
214
+ );
215
+ return (change.rules || [])
216
+ .map((r) => ({ action: r.action, scope: r.scope || null }))
217
+ .filter((r) => !existing.has(ruleKey(r)));
218
+ }
219
+ case 'invite.create': {
220
+ const policyIds = state.teamPolicies
221
+ .filter((tp) => (change.teamIds || []).includes(tp.team_id))
222
+ .map((tp) => tp.policy_id);
223
+ return rulesOfPolicies(state, policyIds);
224
+ }
225
+ default:
226
+ return [];
227
+ }
228
+ }
229
+
230
+ function delegationErrors(actorSubject, state, change) {
231
+ const rules = rulesToDelegate(state, change);
232
+ if (rules.length === 0) return { ok: true, denied: [] };
233
+ const r = canDelegate(actorSubject, rules);
234
+ return r.ok ? { ok: true, denied: [] } : { ok: false, denied: r.denied };
235
+ }
236
+
237
+ function groupBy(cells) {
238
+ const byAction = new Map();
239
+ for (const c of cells) {
240
+ if (!byAction.has(c.action))
241
+ byAction.set(c.action, { instanceIds: new Set(), sigs: new Set() });
242
+ const g = byAction.get(c.action);
243
+ if (c.instanceId) g.instanceIds.add(c.instanceId);
244
+ if (c.sig) g.sigs.add(c.sig);
245
+ }
246
+ return [...byAction].map(([action, g]) => ({
247
+ action,
248
+ instanceIds: [...g.instanceIds],
249
+ detail: [...g.sigs].join(' · ') || null,
250
+ }));
251
+ }
252
+
253
+ function labelOf(state, userId) {
254
+ const u = state.users.find((x) => x.id === userId);
255
+ return u ? u.email || userId : userId;
256
+ }
257
+
258
+ // preview({change, actorSubject}) → PreviewResult
259
+ function preview(change, actorSubject) {
260
+ if (!CHANGE_KINDS.includes(change.kind)) throw new Error(`Unknown change kind: ${change.kind}`);
261
+ const before = store.loadState();
262
+ const rootIds = new Set(
263
+ db
264
+ .prepare('SELECT id FROM users WHERE is_root = 1')
265
+ .all()
266
+ .map((r) => r.id),
267
+ );
268
+ const after = applyChange(before, change);
269
+ const mBefore = effectiveMatrix(before, rootIds);
270
+ const mAfter = effectiveMatrix(after, rootIds);
271
+
272
+ const people = [];
273
+ let gaining = 0;
274
+ let losing = 0;
275
+ let powerful = false;
276
+ const sentences = [];
277
+ const label = (a) => (getAction(a) ? getAction(a).label : a);
278
+
279
+ for (const [userId, afterCells] of mAfter) {
280
+ const beforeCells = mBefore.get(userId) || new Map();
281
+ const gainCells = [...afterCells].filter(([k]) => !beforeCells.has(k)).map(([, c]) => c);
282
+ const lossCells = [...beforeCells].filter(([k]) => !afterCells.has(k)).map(([, c]) => c);
283
+ if (gainCells.length === 0 && lossCells.length === 0) continue;
284
+ const gains = groupBy(gainCells);
285
+ const losses = groupBy(lossCells);
286
+ if (gains.length) gaining++;
287
+ if (losses.length) losing++;
288
+ if (gains.some((g) => (getAction(g.action) || {}).powerful)) powerful = true;
289
+ const who = labelOf(after, userId);
290
+ people.push({ userId, label: who, gains, losses });
291
+ const part = (list) =>
292
+ list
293
+ .map(
294
+ (g) =>
295
+ `${label(g.action)}${g.instanceIds.length ? ` on ${g.instanceIds.length} server(s)` : ''}`,
296
+ )
297
+ .join(', ');
298
+ if (gains.length) sentences.push(`${who} would gain: ${part(gains)}.`);
299
+ if (losses.length) sentences.push(`${who} would lose: ${part(losses)}.`);
300
+ }
301
+
302
+ const deleg = actorSubject ? delegationErrors(actorSubject, before, change) : { ok: true };
303
+ const result = {
304
+ revision: store.getAuthzRevision(),
305
+ counts: { affected: people.length, gaining, losing },
306
+ people,
307
+ sentences,
308
+ powerful,
309
+ };
310
+ if (!deleg.ok) {
311
+ result.errors = deleg.denied.map(
312
+ (d) =>
313
+ `You cannot grant "${label((d.rule || {}).action)}" with that scope — you don't hold it.`,
314
+ );
315
+ }
316
+ return result;
317
+ }
318
+
319
+ module.exports = {
320
+ CHANGE_KINDS,
321
+ ACTIONS,
322
+ preview,
323
+ applyChange,
324
+ effectiveMatrix,
325
+ rulesToDelegate,
326
+ delegationErrors,
327
+ };
@@ -0,0 +1,282 @@
1
+ // Scope schema and matching logic
2
+ const { getAction } = require('./catalog');
3
+
4
+ // Convert glob pattern to RegExp (for migration, globs are marked with fromMigration:true)
5
+ function globToRegExp(glob) {
6
+ // Simple glob: * = .*, ? = .
7
+ // Escape all regex special chars except * and ?
8
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&');
9
+ const regexStr = escaped.replace(/\*/g, '.*').replace(/\?/g, '.');
10
+ return new RegExp(`^${regexStr}$`);
11
+ }
12
+
13
+ function compileMatcher(m) {
14
+ if (m.op === 'exact') {
15
+ return new RegExp(`^${m.value.replace(/[.+^${}()|[\]\\]/g, '\\$&')}$`);
16
+ } else if (m.op === 'startsWith') {
17
+ return new RegExp(`^${m.value.replace(/[.+^${}()|[\]\\]/g, '\\$&')}`);
18
+ } else if (m.op === 'endsWith') {
19
+ return new RegExp(`${m.value.replace(/[.+^${}()|[\]\\]/g, '\\$&')}$`);
20
+ } else if (m.op === 'contains') {
21
+ return new RegExp(m.value.replace(/[.+^${}()|[\]\\]/g, '\\$&'));
22
+ } else if (m.op === 'glob') {
23
+ return globToRegExp(m.value);
24
+ }
25
+ throw new Error(`Unknown matcher op: ${m.op}`);
26
+ }
27
+
28
+ function serviceMatches(matchers, serviceName) {
29
+ if (!matchers || matchers.length === 0) {
30
+ return true; // No service narrowing = all services
31
+ }
32
+ if (!serviceName) {
33
+ return false; // Service narrowing but no service name = no match
34
+ }
35
+ return matchers.some((m) => compileMatcher(m).test(serviceName));
36
+ }
37
+
38
+ function validateRule({ action, scope }, { fromMigration = false } = {}) {
39
+ const actionDef = getAction(action);
40
+ if (!actionDef) {
41
+ return { error: `Unknown action: ${action}` };
42
+ }
43
+
44
+ // Org actions must have null scope
45
+ if (actionDef.scopeKind === 'org') {
46
+ if (scope !== null) {
47
+ return { error: `Org action ${action} cannot have a scope` };
48
+ }
49
+ return { ok: true };
50
+ }
51
+
52
+ // Other actions must have a scope
53
+ if (scope === null) {
54
+ return { error: `Action ${action} requires a scope` };
55
+ }
56
+
57
+ // Validate server scope
58
+ if (!scope.servers) {
59
+ return { error: 'Scope must have a servers field' };
60
+ }
61
+
62
+ const { type } = scope.servers;
63
+ if (type === 'all') {
64
+ // OK
65
+ } else if (type === 'ids') {
66
+ if (!Array.isArray(scope.servers.ids) || scope.servers.ids.length === 0) {
67
+ return { error: 'servers.ids must be a non-empty array' };
68
+ }
69
+ } else if (type === 'tags') {
70
+ if (!Array.isArray(scope.servers.tags) || scope.servers.tags.length === 0) {
71
+ return { error: 'servers.tags must be a non-empty array' };
72
+ }
73
+ const match = scope.servers.match || 'all';
74
+ if (!['all', 'any'].includes(match)) {
75
+ return { error: 'servers.match must be "all" or "any"' };
76
+ }
77
+ } else {
78
+ return { error: `Unknown servers type: ${type}` };
79
+ }
80
+
81
+ // Stricter shape checks for rules created/changed through the API (the UI applies the same
82
+ // ones in policyModel.ts). Stored rules load leniently so older data keeps working.
83
+ // - An empty list is rejected: leave the field out to mean "all". (Empty `services` used to
84
+ // silently mean "all services" while empty `envFiles` meant "no files".)
85
+ // - Narrowing only goes on actions that can use it; elsewhere it was silently ignored.
86
+ if (!fromMigration) {
87
+ const kind = actionDef.scopeKind;
88
+ if (scope.services) {
89
+ if (kind !== 'service' && kind !== 'envfile') {
90
+ return { error: `Action ${action} can't be limited to specific services` };
91
+ }
92
+ if (!Array.isArray(scope.services.matchers) || scope.services.matchers.length === 0) {
93
+ return { error: 'services.matchers must be a non-empty array (omit services for all)' };
94
+ }
95
+ }
96
+ if (scope.envFiles) {
97
+ if (kind !== 'envfile') {
98
+ return { error: `Action ${action} can't be limited to specific env files` };
99
+ }
100
+ if (!Array.isArray(scope.envFiles.ids) || scope.envFiles.ids.length === 0) {
101
+ return { error: 'envFiles.ids must be a non-empty array (omit envFiles for all)' };
102
+ }
103
+ }
104
+ }
105
+
106
+ // Validate service matchers (optional)
107
+ if (scope.services) {
108
+ if (!Array.isArray(scope.services.matchers)) {
109
+ return { error: 'services.matchers must be an array' };
110
+ }
111
+ for (const m of scope.services.matchers) {
112
+ if (!m.op || !m.value) {
113
+ return { error: 'Each service matcher must have op and value' };
114
+ }
115
+ const validOps = ['exact', 'startsWith', 'endsWith', 'contains', 'glob'];
116
+ if (!validOps.includes(m.op)) {
117
+ return { error: `Unknown service matcher op: ${m.op}` };
118
+ }
119
+ // Only allow glob if fromMigration=true
120
+ if (m.op === 'glob' && !fromMigration) {
121
+ return { error: 'Glob matchers only allowed in migration' };
122
+ }
123
+ }
124
+ }
125
+
126
+ // Validate env-file ids (optional)
127
+ if (scope.envFiles) {
128
+ if (!Array.isArray(scope.envFiles.ids)) {
129
+ return { error: 'envFiles.ids must be an array' };
130
+ }
131
+ }
132
+
133
+ return { ok: true };
134
+ }
135
+
136
+ function serverMatches(serverScope, instance, authTagsOf) {
137
+ if (serverScope.type === 'all') {
138
+ return true;
139
+ }
140
+ if (serverScope.type === 'ids') {
141
+ return serverScope.ids.includes(instance.id);
142
+ }
143
+ if (serverScope.type === 'tags') {
144
+ const instanceTags = authTagsOf(instance.id);
145
+ const match = serverScope.match || 'all';
146
+ if (match === 'all') {
147
+ return serverScope.tags.every((t) => instanceTags.includes(t));
148
+ } else {
149
+ return serverScope.tags.some((t) => instanceTags.includes(t));
150
+ }
151
+ }
152
+ return false;
153
+ }
154
+
155
+ // Check if scopeA is a subset of scopeB
156
+ function scopeSubset(scopeA, scopeB) {
157
+ if (!scopeA || !scopeB) {
158
+ return scopeA === scopeB;
159
+ }
160
+
161
+ // Servers
162
+ const serverSubset = serverScopeSubset(scopeA.servers, scopeB.servers);
163
+ if (!serverSubset) return false;
164
+
165
+ // Services
166
+ const serviceSubset = serviceScopeSubset(scopeA.services, scopeB.services);
167
+ if (!serviceSubset) return false;
168
+
169
+ // Env files
170
+ const envSubset = envFileScopeSubset(scopeA.envFiles, scopeB.envFiles);
171
+ if (!envSubset) return false;
172
+
173
+ return true;
174
+ }
175
+
176
+ function serverScopeSubset(scopeA, scopeB) {
177
+ if (scopeB.type === 'all') return true; // Anything is subset of 'all'
178
+ if (scopeA.type === 'all') return false; // 'all' is not subset of specific
179
+
180
+ if (scopeA.type === 'ids' && scopeB.type === 'ids') {
181
+ return scopeA.ids.every((id) => scopeB.ids.includes(id));
182
+ }
183
+ if (scopeA.type === 'ids' && scopeB.type === 'tags') {
184
+ // ids subset of tags only if we can prove all current ids match the tags (point-in-time)
185
+ // This is evaluated at delegation time with current tag state
186
+ return false; // Conservative: requires runtime check in delegation
187
+ }
188
+ if (scopeA.type === 'tags' && scopeB.type === 'ids') {
189
+ return false; // tags not subset of ids
190
+ }
191
+ if (scopeA.type === 'tags' && scopeB.type === 'tags') {
192
+ const matchA = scopeA.match || 'all';
193
+ const matchB = scopeB.match || 'all';
194
+ if (matchA === 'all' && matchB === 'all') {
195
+ // Requiring MORE tags is narrower: A ⊆ B iff every tag B requires, A requires too.
196
+ return scopeB.tags.every((t) => scopeA.tags.includes(t));
197
+ }
198
+ if (matchA === 'any' && matchB === 'any') {
199
+ return scopeA.tags.every((t) => scopeB.tags.includes(t)); // subset of available tags
200
+ }
201
+ if (matchA === 'all' && matchB === 'any') {
202
+ return scopeA.tags.some((t) => scopeB.tags.includes(t)); // some overlap
203
+ }
204
+ return false; // 'any' subset of 'all' is false
205
+ }
206
+ return false;
207
+ }
208
+
209
+ function serviceScopeSubset(scopeA, scopeB) {
210
+ if (!scopeA && !scopeB) return true; // Both absent
211
+ if (!scopeB) return true; // B absent means no narrowing, A is subset
212
+ if (!scopeA) return false; // A absent but B present is not a subset
213
+
214
+ if (!scopeA.matchers || scopeA.matchers.length === 0) {
215
+ return !scopeB.matchers || scopeB.matchers.length === 0;
216
+ }
217
+
218
+ if (!scopeB.matchers || scopeB.matchers.length === 0) {
219
+ return false; // A has matchers but B doesn't
220
+ }
221
+
222
+ // Each matcher in A must be covered by some matcher in B
223
+ return scopeA.matchers.every((mA) => scopeB.matchers.some((mB) => matcherSubset(mA, mB)));
224
+ }
225
+
226
+ function matcherSubset(mA, mB) {
227
+ if (mB.op === 'exact' || mA.op === 'exact') {
228
+ if (mA.op === 'exact' && mB.op === 'exact') {
229
+ return mA.value === mB.value;
230
+ }
231
+ if (mA.op === 'exact' && mB.op !== 'exact') {
232
+ // exact(x) subset of pattern if pattern matches x
233
+ return compileMatcher(mB).test(mA.value);
234
+ }
235
+ return false;
236
+ }
237
+
238
+ if (mA.op === mB.op) {
239
+ // Same op: startsWith, endsWith, contains
240
+ // A is covered by B when everything A matches, B matches too: a LONGER prefix/suffix/
241
+ // substring is narrower (startsWith "api-v" ⊆ startsWith "api").
242
+ if (mA.op === 'startsWith') {
243
+ return mA.value.startsWith(mB.value);
244
+ }
245
+ if (mA.op === 'endsWith') {
246
+ return mA.value.endsWith(mB.value);
247
+ }
248
+ if (mA.op === 'contains') {
249
+ return mA.value.includes(mB.value);
250
+ }
251
+ if (mA.op === 'glob') {
252
+ return mA.value === mB.value; // Globs only equal to identical globs
253
+ }
254
+ }
255
+
256
+ return false;
257
+ }
258
+
259
+ function envFileScopeSubset(scopeA, scopeB) {
260
+ if (!scopeA && !scopeB) return true;
261
+ if (!scopeB) return true; // B absent = no env narrowing, subset
262
+ if (!scopeA) return false;
263
+
264
+ if (scopeA.ids && scopeB.ids) {
265
+ return scopeA.ids.every((id) => scopeB.ids.includes(id));
266
+ }
267
+
268
+ return scopeA.ids && !scopeB.ids ? true : false; // A specific, B not = subset
269
+ }
270
+
271
+ module.exports = {
272
+ compileMatcher,
273
+ serviceMatches,
274
+ serverMatches,
275
+ validateRule,
276
+ scopeSubset,
277
+ serverScopeSubset,
278
+ serviceScopeSubset,
279
+ matcherSubset,
280
+ envFileScopeSubset,
281
+ globToRegExp,
282
+ };