@revoengine/cli 1.0.15 → 1.0.16

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 (49) hide show
  1. package/README.md +45 -9
  2. package/dist/src/cli.js +5 -1
  3. package/dist/src/client.d.ts +25 -3
  4. package/dist/src/client.js +67 -2
  5. package/dist/src/commands/component.js +1 -0
  6. package/dist/src/commands/index.d.ts +1 -0
  7. package/dist/src/commands/index.js +1 -0
  8. package/dist/src/commands/migrate.js +12 -2
  9. package/dist/src/commands/service-accounts.d.ts +2 -0
  10. package/dist/src/commands/service-accounts.js +149 -0
  11. package/dist/src/commands/terminal-browser.d.ts +29 -2
  12. package/dist/src/commands/terminal-browser.js +144 -35
  13. package/dist/src/commands/terminal-file.d.ts +21 -0
  14. package/dist/src/commands/terminal-file.js +160 -0
  15. package/dist/src/commands/terminal-operational-log.js +2 -2
  16. package/dist/src/commands/terminal-policy.d.ts +5 -2
  17. package/dist/src/commands/terminal-policy.js +10 -4
  18. package/dist/src/commands/terminal-reconnect-grace.js +1 -1
  19. package/dist/src/commands/terminal-sandbox.js +7 -0
  20. package/dist/src/commands/terminal-secure-browser.d.ts +1 -0
  21. package/dist/src/commands/terminal-secure-browser.js +2 -1
  22. package/dist/src/commands/terminal-service.js +4 -4
  23. package/dist/src/commands/terminal.d.ts +12 -0
  24. package/dist/src/commands/terminal.js +134 -45
  25. package/dist/src/component-lock.d.ts +4 -0
  26. package/dist/src/component-lock.js +21 -2
  27. package/dist/src/metadata-backfill.js +50 -1
  28. package/dist/src/migration.d.ts +10 -2
  29. package/dist/src/migration.js +159 -68
  30. package/dist/src/resource-inventory.d.ts +3 -2
  31. package/dist/src/resource-inventory.js +6 -1
  32. package/dist/src/resource-syncs/account-principal.d.ts +22 -0
  33. package/dist/src/resource-syncs/account-principal.js +86 -0
  34. package/dist/src/resource-syncs/group-sync.d.ts +10 -0
  35. package/dist/src/resource-syncs/group-sync.js +92 -20
  36. package/dist/src/resource-syncs/identity-migration.d.ts +19 -0
  37. package/dist/src/resource-syncs/identity-migration.js +108 -0
  38. package/dist/src/resource-syncs/job-template-sync.d.ts +4 -0
  39. package/dist/src/resource-syncs/job-template-sync.js +55 -12
  40. package/dist/src/resource-syncs/service-account-sync.d.ts +98 -0
  41. package/dist/src/resource-syncs/service-account-sync.js +620 -0
  42. package/dist/src/sync-output.js +3 -0
  43. package/dist/src/tracked-resources.d.ts +1 -1
  44. package/dist/src/tracked-resources.js +5 -1
  45. package/dist/src/types.d.ts +12 -0
  46. package/dist/src/ui.js +4 -1
  47. package/dist/src/workspace-diff.d.ts +1 -0
  48. package/dist/src/workspace-diff.js +4 -1
  49. package/package.json +2 -2
@@ -0,0 +1,620 @@
1
+ import path from 'node:path';
2
+ import { readPortableOwner, resolvePortableOwner, ownerIsAvailable } from "./account-principal.js";
3
+ import { describeFieldChanges } from "../diff-details.js";
4
+ import { hashStable, readComponentLock, writeComponentLock, } from "../component-lock.js";
5
+ import { readConfiguredResourceMetadataStableKey, sanitizeUserMetadata, } from "../resource-metadata.js";
6
+ import { readJsonFile, sanitizeSegment } from "../utils.js";
7
+ import { findManifestFiles, isRecord, localTargetPath, mapWithConcurrency, removeRelocatedManifest, requireProjectLayout, stableKeySuffix, toPortableRelativePath, unwrapData, writePulledManifest, } from "./util.js";
8
+ function exactKey(value) { return value; }
9
+ export const SERVICE_ACCOUNTS_DIRECTORY = 'ServiceAccounts';
10
+ export const SERVICE_ACCOUNT_MANIFEST_FILE = 'service-account.json';
11
+ function serviceAccountIdOf(record) {
12
+ return String(record.userId || '');
13
+ }
14
+ export async function serviceAccountManifestFromRecord(client, record, stableKeyName) {
15
+ const stableKey = readConfiguredResourceMetadataStableKey(record, stableKeyName);
16
+ if (!stableKey) {
17
+ return null;
18
+ }
19
+ return {
20
+ kind: 'service-account',
21
+ stableKey,
22
+ name: String(record.name || ''),
23
+ metadata: { [stableKeyName]: stableKey },
24
+ owner: await readPortableOwner(client, record, stableKeyName),
25
+ };
26
+ }
27
+ export function hashPortableServiceAccount(manifest) {
28
+ return hashStable({ kind: manifest.kind, stableKey: manifest.stableKey, name: manifest.name, metadata: manifest.metadata,
29
+ ...(['group', 'service-account'].includes(manifest.owner.type) ? { owner: manifest.owner } : {}) });
30
+ }
31
+ function serviceAccountHint(value) {
32
+ return String(value.name || '').trim().toLowerCase();
33
+ }
34
+ function diffServiceAccounts(desired, target) {
35
+ return { changedFields: ['name', 'metadata', 'owner'].filter((field) => {
36
+ if (field === 'owner' && !['group', 'service-account'].includes(desired.owner.type)) {
37
+ return false;
38
+ }
39
+ return hashStable(desired[field]) !== hashStable(target[field]);
40
+ }) };
41
+ }
42
+ function comparableManifest(desired, target) {
43
+ return ['group', 'service-account'].includes(desired.owner.type) ? target : { ...target, owner: desired.owner };
44
+ }
45
+ export function serviceAccountManifestPath(workspaceRoot, manifest) {
46
+ return path.join(workspaceRoot, SERVICE_ACCOUNTS_DIRECTORY, `${sanitizeSegment(manifest.name)}-${stableKeySuffix(manifest.stableKey)}`, SERVICE_ACCOUNT_MANIFEST_FILE);
47
+ }
48
+ function portablePathIdentity(filePath) {
49
+ return path.resolve(filePath)
50
+ .normalize('NFC')
51
+ .split(path.sep)
52
+ .map((segment) => segment.replace(/[. ]+$/g, '').toLowerCase())
53
+ .join(path.sep);
54
+ }
55
+ export function readWorkspaceServiceAccounts(cwd) {
56
+ const { workspaceRoot } = requireProjectLayout(cwd, 'Service-account');
57
+ return findManifestFiles(path.join(workspaceRoot, SERVICE_ACCOUNTS_DIRECTORY), SERVICE_ACCOUNT_MANIFEST_FILE)
58
+ .map((manifestPath) => ({
59
+ manifestPath,
60
+ manifest: readJsonFile(manifestPath),
61
+ }));
62
+ }
63
+ async function loadRemoteServiceAccounts(client) {
64
+ const { serviceAccounts } = await client.listAllServiceAccounts();
65
+ return mapWithConcurrency(serviceAccounts, async (summary) => {
66
+ const id = serviceAccountIdOf(summary);
67
+ return id ? unwrapData(await client.getServiceAccount(id)) : summary;
68
+ });
69
+ }
70
+ function validateManifest(manifest, stableKeyName) {
71
+ const errors = [];
72
+ if (!isRecord(manifest)) {
73
+ return ['manifest must be a JSON object'];
74
+ }
75
+ if (manifest.kind !== 'service-account'
76
+ || typeof manifest.stableKey !== 'string'
77
+ || !manifest.stableKey.trim()
78
+ || typeof manifest.name !== 'string'
79
+ || !manifest.name.trim()
80
+ || !isRecord(manifest.metadata)) {
81
+ errors.push('manifest must contain kind, stableKey, name and metadata');
82
+ }
83
+ if (!isRecord(manifest.owner) || !['group', 'service-account', 'manual-user', 'unresolved'].includes(String(manifest.owner.type))) {
84
+ errors.push('owner must contain a portable owner policy');
85
+ }
86
+ else if (['group', 'service-account'].includes(String(manifest.owner.type))
87
+ && (typeof manifest.owner.stableKey !== 'string' || !manifest.owner.stableKey.trim())) {
88
+ errors.push('portable owner requires stableKey');
89
+ }
90
+ if (isRecord(manifest.owner) && Object.keys(manifest.owner).some((key) => !['type', 'stableKey', 'reason'].includes(key))) {
91
+ errors.push('owner contains unsupported fields');
92
+ }
93
+ if (Object.keys(manifest).some((key) => !['kind', 'stableKey', 'name', 'metadata', 'owner'].includes(key))) {
94
+ errors.push('manifest contains unsupported account fields');
95
+ }
96
+ if (!isRecord(manifest.metadata) || Object.keys(manifest.metadata).length !== 1
97
+ || manifest.metadata[stableKeyName] !== manifest.stableKey) {
98
+ errors.push('metadata must contain only the configured stableKey');
99
+ }
100
+ return errors;
101
+ }
102
+ function emptyPlanCounts() {
103
+ return {
104
+ clean: 0,
105
+ create: 0,
106
+ 'safe-update': 0,
107
+ 'remote-changed': 0,
108
+ conflict: 0,
109
+ 'missing-lock': 0,
110
+ orphan: 0,
111
+ collision: 0,
112
+ skipped: 0,
113
+ delete: 0,
114
+ 'manual-owner': 0,
115
+ };
116
+ }
117
+ export async function buildServiceAccountsPlan(input) {
118
+ const localEntries = readWorkspaceServiceAccounts(input.cwd).filter((entry) => !input.onlyStableKeys || input.onlyStableKeys.includes(entry.manifest.stableKey));
119
+ const records = await loadRemoteServiceAccounts(input.client);
120
+ const identities = !input.projectedIdentities && !input.onlyStableKeys
121
+ ? await (await import("./identity-migration.js")).planIdentityMigration({ ...input, resources: ['service-account'] }) : undefined;
122
+ const projectedIdentities = input.projectedIdentities || identities?.projection;
123
+ const { projectRoot } = requireProjectLayout(input.cwd, 'Service-account');
124
+ const lock = readComponentLock(projectRoot);
125
+ const lockByNormalizedKey = new Map(Object.values(lock.serviceAccounts)
126
+ .map((entry) => [exactKey(entry.stableKey), entry]));
127
+ const blockers = [...(identities?.blockers || [])];
128
+ const items = [];
129
+ const localByKey = new Map();
130
+ for (const entry of localEntries) {
131
+ const errors = validateManifest(entry.manifest, input.stableKeyName);
132
+ if (errors.length > 0) {
133
+ blockers.push(`Invalid service-account manifest ${path.relative(projectRoot, entry.manifestPath)}: ${errors.join('; ')}.`);
134
+ const invalidName = isRecord(entry.manifest) && typeof entry.manifest.name === 'string' && entry.manifest.name
135
+ ? entry.manifest.name
136
+ : path.basename(path.dirname(entry.manifestPath));
137
+ items.push({
138
+ status: 'conflict',
139
+ name: invalidName,
140
+ reason: 'invalid service-account manifest',
141
+ });
142
+ continue;
143
+ }
144
+ const normalized = exactKey(entry.manifest.stableKey || '');
145
+ localByKey.set(normalized, [...(localByKey.get(normalized) || []), entry]);
146
+ }
147
+ const remoteByKey = new Map();
148
+ const unmanaged = [];
149
+ for (const record of records) {
150
+ const manifest = await serviceAccountManifestFromRecord(input.client, record, input.stableKeyName);
151
+ if (!manifest) {
152
+ unmanaged.push(record);
153
+ continue;
154
+ }
155
+ const normalized = exactKey(manifest.stableKey);
156
+ remoteByKey.set(normalized, [...(remoteByKey.get(normalized) || []), {
157
+ record,
158
+ manifest,
159
+ hash: hashPortableServiceAccount(manifest),
160
+ }]);
161
+ }
162
+ const consumedRemoteKeys = new Set();
163
+ const consumedUnmanaged = new Set();
164
+ for (const [normalized, entries] of localByKey) {
165
+ if (entries.length > 1) {
166
+ const stableKey = entries[0].manifest.stableKey;
167
+ blockers.push(`Duplicate desired service-account stableKey "${stableKey}".`);
168
+ items.push({ status: 'collision', stableKey, name: entries[0].manifest.name, reason: 'duplicate desired stableKey' });
169
+ continue;
170
+ }
171
+ const desired = entries[0].manifest;
172
+ const desiredHash = hashPortableServiceAccount(desired);
173
+ const matches = remoteByKey.get(normalized) || [];
174
+ if (matches.length > 1) {
175
+ blockers.push(`Duplicate target service-account stableKey "${desired.stableKey}".`);
176
+ consumedRemoteKeys.add(normalized);
177
+ items.push({ status: 'collision', stableKey: desired.stableKey, name: desired.name, reason: 'duplicate target stableKey', desiredHash });
178
+ continue;
179
+ }
180
+ if (desired.owner.type === 'group' || desired.owner.type === 'service-account') {
181
+ if (!await ownerIsAvailable(input.client, desired.owner, input.stableKeyName, projectedIdentities)) {
182
+ blockers.push(`Service account "${desired.stableKey}" owner "${desired.owner.stableKey}" is missing or ambiguous.`);
183
+ items.push({ status: 'conflict', stableKey: desired.stableKey, name: desired.name, desiredHash, reason: 'owner is missing or ambiguous' });
184
+ continue;
185
+ }
186
+ }
187
+ else if (matches.length === 0) {
188
+ items.push({ status: 'manual-owner', stableKey: desired.stableKey, name: desired.name, desiredHash,
189
+ reason: 'manual: create the account with a target owner and the exact stableKey, then rerun' });
190
+ continue;
191
+ }
192
+ const collisions = records.filter((record) => serviceAccountHint(record) === serviceAccountHint(desired)
193
+ && readConfiguredResourceMetadataStableKey(record, input.stableKeyName) !== desired.stableKey);
194
+ if (collisions.length > 0) {
195
+ blockers.push(`Service account "${desired.stableKey}" conflicts with another target account name.`);
196
+ items.push({ status: 'collision', stableKey: desired.stableKey, name: desired.name, desiredHash, reason: 'target name collision' });
197
+ continue;
198
+ }
199
+ if (matches.length === 0) {
200
+ const hinted = unmanaged.filter((record) => serviceAccountHint(record) === serviceAccountHint(desired));
201
+ if (hinted.length > 0) {
202
+ hinted.forEach((record) => consumedUnmanaged.add(record));
203
+ const reason = `target service-account matching name is missing ${input.stableKeyName}`;
204
+ blockers.push(`Cannot create "${desired.stableKey}": ${reason}.`);
205
+ items.push({ status: 'conflict', stableKey: desired.stableKey, name: desired.name, reason, desiredHash });
206
+ }
207
+ else {
208
+ items.push({ status: 'create', stableKey: desired.stableKey, name: desired.name, desiredHash });
209
+ }
210
+ continue;
211
+ }
212
+ consumedRemoteKeys.add(normalized);
213
+ const target = matches[0];
214
+ target.manifest = comparableManifest(desired, target.manifest);
215
+ target.hash = hashPortableServiceAccount(target.manifest);
216
+ const diff = diffServiceAccounts(desired, target.manifest);
217
+ const common = {
218
+ stableKey: desired.stableKey,
219
+ name: desired.name,
220
+ desiredHash,
221
+ currentHash: target.hash,
222
+ ...(diff.changedFields.length > 0 ? { changedFields: diff.changedFields, fieldChanges: describeFieldChanges(desired, target.manifest, diff.changedFields) } : {}),
223
+ };
224
+ if (desiredHash === target.hash) {
225
+ items.push({ status: 'clean', ...common });
226
+ continue;
227
+ }
228
+ const baselineHash = lockByNormalizedKey.get(normalized)?.environments[input.envName]?.remoteHash;
229
+ if (!baselineHash) {
230
+ items.push({ status: 'missing-lock', ...common, reason: `missing ${input.envName} lock baseline` });
231
+ }
232
+ else if (target.hash === baselineHash) {
233
+ items.push({ status: 'safe-update', ...common, baselineHash });
234
+ }
235
+ else if (desiredHash === baselineHash) {
236
+ items.push({ status: 'remote-changed', ...common, baselineHash, reason: 'target changed since lock baseline' });
237
+ }
238
+ else {
239
+ items.push({ status: 'conflict', ...common, baselineHash, reason: 'desired and target changed since lock baseline' });
240
+ }
241
+ }
242
+ for (const [normalized, matches] of remoteByKey) {
243
+ if (consumedRemoteKeys.has(normalized) || localByKey.has(normalized)) {
244
+ continue;
245
+ }
246
+ if (matches.length > 1) {
247
+ const stableKey = matches[0].manifest.stableKey;
248
+ blockers.push(`Duplicate target service-account stableKey "${stableKey}".`);
249
+ items.push({ status: 'collision', stableKey, name: matches[0].manifest.name, reason: 'duplicate target stableKey' });
250
+ continue;
251
+ }
252
+ const target = matches[0];
253
+ items.push({ status: 'orphan', stableKey: target.manifest.stableKey, name: target.manifest.name, currentHash: target.hash, reason: 'target-only service-account' });
254
+ }
255
+ for (const record of unmanaged) {
256
+ if (consumedUnmanaged.has(record)) {
257
+ continue;
258
+ }
259
+ items.push({ status: 'skipped', name: String(record.name || 'unknown'), reason: `missing ${input.stableKeyName}; unmanaged` });
260
+ }
261
+ const rank = {
262
+ create: 0,
263
+ 'safe-update': 1,
264
+ 'remote-changed': 2,
265
+ conflict: 3,
266
+ 'missing-lock': 4,
267
+ clean: 5,
268
+ orphan: 6,
269
+ collision: 7,
270
+ skipped: 8,
271
+ delete: 9,
272
+ 'manual-owner': 10,
273
+ };
274
+ items.sort((left, right) => rank[left.status] - rank[right.status]
275
+ || (left.stableKey || left.name).localeCompare(right.stableKey || right.name));
276
+ const counts = emptyPlanCounts();
277
+ for (const item of items)
278
+ counts[item.status] += 1;
279
+ return {
280
+ resourceType: 'service-account',
281
+ env: input.envName,
282
+ counts,
283
+ blockers: [...new Set(blockers)].sort((left, right) => left.localeCompare(right)),
284
+ items,
285
+ exclusions: ['Secrets and API keys are target-local; configure them separately after create', 'Only stableKey metadata is portable; other account metadata is target-local'],
286
+ };
287
+ }
288
+ export async function pullServiceAccountsToWorkspace(input) {
289
+ const { projectRoot, workspaceRoot } = requireProjectLayout(input.cwd, 'Service-account');
290
+ const records = await loadRemoteServiceAccounts(input.client);
291
+ const skipped = [];
292
+ const managed = [];
293
+ const normalizedKeys = new Set();
294
+ for (const record of records) {
295
+ const manifest = await serviceAccountManifestFromRecord(input.client, record, input.stableKeyName);
296
+ if (!manifest) {
297
+ const name = String(record.name || serviceAccountIdOf(record) || 'unknown');
298
+ skipped.push({ name, targetPath: name, reason: `missing ${input.stableKeyName}; unmanaged` });
299
+ continue;
300
+ }
301
+ const errors = validateManifest(manifest, input.stableKeyName);
302
+ if (errors.length > 0) {
303
+ throw new Error(`Invalid source service account: ${errors.join('; ')}.`);
304
+ }
305
+ const normalized = exactKey(manifest.stableKey);
306
+ if (normalizedKeys.has(normalized)) {
307
+ throw new Error(`Duplicate service-account stableKey "${manifest.stableKey}" on ${input.envName}; no files were changed.`);
308
+ }
309
+ normalizedKeys.add(normalized);
310
+ managed.push(manifest);
311
+ }
312
+ managed.sort((left, right) => left.stableKey.localeCompare(right.stableKey));
313
+ const lock = readComponentLock(projectRoot);
314
+ const existingByStableKey = new Map();
315
+ const existingByPath = new Map();
316
+ for (const entry of readWorkspaceServiceAccounts(input.cwd)) {
317
+ const errors = validateManifest(entry.manifest, input.stableKeyName);
318
+ if (errors.length > 0) {
319
+ throw new Error(`Cannot pull over invalid service-account manifest ${path.relative(projectRoot, entry.manifestPath)}: ${errors.join('; ')}.`);
320
+ }
321
+ const normalized = exactKey(entry.manifest.stableKey || '');
322
+ if (existingByStableKey.has(normalized)) {
323
+ throw new Error(`Duplicate local service-account stableKey "${entry.manifest.stableKey}"; no files were changed.`);
324
+ }
325
+ existingByStableKey.set(normalized, entry);
326
+ const pathIdentity = portablePathIdentity(entry.manifestPath);
327
+ existingByPath.set(pathIdentity, [...(existingByPath.get(pathIdentity) || []), entry]);
328
+ }
329
+ const writes = [];
330
+ const outputPaths = new Set();
331
+ for (const manifest of managed) {
332
+ const hash = hashPortableServiceAccount(manifest);
333
+ const normalized = exactKey(manifest.stableKey);
334
+ const existing = existingByStableKey.get(normalized);
335
+ if (existing && !input.force) {
336
+ const localHash = hashPortableServiceAccount(existing.manifest);
337
+ const lockEntry = Object.values(lock.serviceAccounts)
338
+ .find((entry) => exactKey(entry.stableKey) === normalized);
339
+ if (localHash !== hash && (!lockEntry || localHash !== lockEntry.sourceHash)) {
340
+ throw new Error(`Cannot pull service-account "${manifest.stableKey}": local manifest changed since the lock baseline. Re-run with --force.`);
341
+ }
342
+ }
343
+ const filePath = serviceAccountManifestPath(workspaceRoot, manifest);
344
+ const pathIdentity = portablePathIdentity(filePath);
345
+ if (outputPaths.has(pathIdentity)) {
346
+ throw new Error(`Multiple service-accounts resolve to workspace path "${path.relative(projectRoot, filePath)}"; no files were changed.`);
347
+ }
348
+ const pathOwner = (existingByPath.get(pathIdentity) || [])
349
+ .find((entry) => exactKey(entry.manifest.stableKey) !== normalized);
350
+ if (pathOwner) {
351
+ throw new Error(`Service-account workspace path "${path.relative(projectRoot, filePath)}" is occupied by different stableKey "${pathOwner.manifest.stableKey}"; no files were changed.`);
352
+ }
353
+ outputPaths.add(pathIdentity);
354
+ writes.push({
355
+ filePath,
356
+ ...(existing && existing.manifestPath !== filePath ? { previousPath: existing.manifestPath } : {}),
357
+ manifest,
358
+ hash,
359
+ });
360
+ }
361
+ const sourceStableKeys = new Set(managed.map((manifest) => exactKey(manifest.stableKey)));
362
+ const pruned = input.pruneOrphans === true
363
+ ? [...existingByStableKey.entries()]
364
+ .filter(([normalized]) => !sourceStableKeys.has(normalized))
365
+ .map(([, entry]) => ({
366
+ stableKey: entry.manifest.stableKey,
367
+ targetPath: localTargetPath(input.cwd, entry.manifestPath),
368
+ manifestPath: entry.manifestPath,
369
+ }))
370
+ .sort((left, right) => right.manifestPath.length - left.manifestPath.length
371
+ || left.stableKey.localeCompare(right.stableKey))
372
+ : [];
373
+ const serviceAccountsRoot = path.join(workspaceRoot, SERVICE_ACCOUNTS_DIRECTORY);
374
+ let lockChanged = false;
375
+ for (const write of writes) {
376
+ writePulledManifest({
377
+ filePath: write.filePath,
378
+ manifest: write.manifest,
379
+ previousPath: write.previousPath,
380
+ root: serviceAccountsRoot,
381
+ force: input.force,
382
+ });
383
+ const normalized = exactKey(write.manifest.stableKey);
384
+ const previousPair = Object.entries(lock.serviceAccounts)
385
+ .find(([, entry]) => exactKey(entry.stableKey) === normalized);
386
+ const previous = previousPair?.[1];
387
+ if (previousPair && previousPair[0] !== write.manifest.stableKey) {
388
+ delete lock.serviceAccounts[previousPair[0]];
389
+ lockChanged = true;
390
+ }
391
+ const previousBaseline = previous?.environments[input.envName];
392
+ const entry = {
393
+ stableKey: write.manifest.stableKey,
394
+ path: toPortableRelativePath(projectRoot, write.filePath),
395
+ sourceHash: write.hash,
396
+ environments: {
397
+ ...(previous?.environments || {}),
398
+ [input.envName]: previousBaseline?.remoteHash === write.hash
399
+ ? previousBaseline
400
+ : { remoteHash: write.hash, syncedAt: new Date().toISOString() },
401
+ },
402
+ };
403
+ if (!previous || hashStable(previous) !== hashStable(entry)) {
404
+ lockChanged = true;
405
+ }
406
+ lock.serviceAccounts[write.manifest.stableKey] = entry;
407
+ }
408
+ for (const removed of pruned) {
409
+ removeRelocatedManifest(removed.manifestPath, serviceAccountsRoot);
410
+ const normalized = exactKey(removed.stableKey);
411
+ const lockKey = Object.keys(lock.serviceAccounts)
412
+ .find((stableKey) => exactKey(stableKey) === normalized);
413
+ if (lockKey) {
414
+ delete lock.serviceAccounts[lockKey];
415
+ }
416
+ lockChanged = true;
417
+ }
418
+ if (lockChanged) {
419
+ writeComponentLock(projectRoot, lock);
420
+ }
421
+ return {
422
+ pulled: writes.map((write) => ({
423
+ manifest: write.manifest,
424
+ targetPath: localTargetPath(input.cwd, write.filePath),
425
+ })),
426
+ pruned: pruned.map(({ stableKey, targetPath }) => ({ stableKey, targetPath })),
427
+ skipped,
428
+ };
429
+ }
430
+ async function buildCreatePayload(client, manifest, stableKeyName) {
431
+ return { name: manifest.name, metadata: manifest.metadata, ...await resolvePortableOwner(client, manifest.owner, stableKeyName) };
432
+ }
433
+ async function buildBaseUpdatePayload(client, manifest, target, stableKeyName) {
434
+ if (!Number.isInteger(target.version)) {
435
+ throw new Error('target service-account version is required');
436
+ }
437
+ return { name: manifest.name, metadata: { ...sanitizeUserMetadata(target.metadata), ...manifest.metadata }, version: target.version,
438
+ ...(['group', 'service-account'].includes(manifest.owner.type) ? await resolvePortableOwner(client, manifest.owner, stableKeyName) : {}) };
439
+ }
440
+ function updateEnvironmentBaseline(input) {
441
+ const { projectRoot } = requireProjectLayout(input.cwd, 'Service-account');
442
+ const lock = readComponentLock(projectRoot);
443
+ const normalized = exactKey(input.stableKey);
444
+ const localMatches = readWorkspaceServiceAccounts(input.cwd)
445
+ .filter(({ manifest }) => typeof manifest.stableKey === 'string'
446
+ && exactKey(manifest.stableKey) === normalized);
447
+ if (localMatches.length !== 1) {
448
+ throw new Error(`Cannot update lock baseline for "${input.stableKey}": expected one local service-account manifest, found ${localMatches.length}.`);
449
+ }
450
+ const local = localMatches[0];
451
+ const pair = Object.entries(lock.serviceAccounts)
452
+ .find(([, entry]) => exactKey(entry.stableKey) === normalized);
453
+ const lockKey = pair?.[0] || local.manifest.stableKey;
454
+ const entry = pair?.[1];
455
+ const existingBaseline = entry?.environments[input.envName];
456
+ const nextEntry = {
457
+ stableKey: local.manifest.stableKey,
458
+ path: toPortableRelativePath(projectRoot, local.manifestPath),
459
+ sourceHash: hashPortableServiceAccount(local.manifest),
460
+ environments: {
461
+ ...(entry?.environments || {}),
462
+ [input.envName]: existingBaseline?.remoteHash === input.remoteHash
463
+ ? existingBaseline
464
+ : { remoteHash: input.remoteHash, syncedAt: new Date().toISOString() },
465
+ },
466
+ };
467
+ if (entry && hashStable(entry) === hashStable(nextEntry)) {
468
+ return;
469
+ }
470
+ if (lockKey !== local.manifest.stableKey) {
471
+ delete lock.serviceAccounts[lockKey];
472
+ }
473
+ lock.serviceAccounts[local.manifest.stableKey] = nextEntry;
474
+ writeComponentLock(projectRoot, lock);
475
+ }
476
+ function localManifestByStableKey(cwd) {
477
+ return new Map(readWorkspaceServiceAccounts(cwd).map((entry) => [
478
+ exactKey(entry.manifest.stableKey),
479
+ entry,
480
+ ]));
481
+ }
482
+ async function liveTargetByStableKey(client, stableKeyName, stableKey) {
483
+ const normalized = exactKey(stableKey);
484
+ const records = await loadRemoteServiceAccounts(client);
485
+ return records.filter((record) => {
486
+ const value = readConfiguredResourceMetadataStableKey(record, stableKeyName);
487
+ return value ? exactKey(value) === normalized : false;
488
+ });
489
+ }
490
+ async function assertCreateStillSafe(client, stableKeyName, desired) {
491
+ const normalized = exactKey(desired.stableKey);
492
+ const records = await loadRemoteServiceAccounts(client);
493
+ for (const record of records) {
494
+ const key = readConfiguredResourceMetadataStableKey(record, stableKeyName);
495
+ if (key && exactKey(key) === normalized) {
496
+ throw new Error('matching stableKey appeared after planning');
497
+ }
498
+ if (key !== desired.stableKey && serviceAccountHint(record) === serviceAccountHint(desired)) {
499
+ throw new Error(`target service-account matching name appeared without ${stableKeyName} after planning`);
500
+ }
501
+ }
502
+ }
503
+ export async function pushServiceAccounts(input) {
504
+ const plan = await buildServiceAccountsPlan(input);
505
+ if (plan.blockers.length > 0) {
506
+ throw new Error(`Service-account push blocked: ${plan.blockers.join(' ')}`);
507
+ }
508
+ const contentBlockers = plan.items.filter((item) => ['missing-lock', 'remote-changed', 'conflict'].includes(item.status));
509
+ if (contentBlockers.length > 0 && !input.force) {
510
+ const statuses = [...new Set(contentBlockers.map((item) => item.status))].sort().join(', ');
511
+ throw new Error(`Service-account push blocked by ${statuses}; review the plan and re-run with --force only to adopt or overwrite reviewed content drift.`);
512
+ }
513
+ if (plan.items.some((item) => item.status === 'collision')) {
514
+ throw new Error('Service-account push blocked by stableKey collision; --force cannot bypass identity ambiguity.');
515
+ }
516
+ const localByKey = localManifestByStableKey(input.cwd);
517
+ const results = [];
518
+ for (const item of plan.items.filter((candidate) => candidate.status === 'clean')) {
519
+ if (!item.stableKey || !item.currentHash) {
520
+ continue;
521
+ }
522
+ const local = localByKey.get(exactKey(item.stableKey));
523
+ updateEnvironmentBaseline({ cwd: input.cwd, envName: input.envName, stableKey: item.stableKey, remoteHash: item.currentHash });
524
+ results.push({
525
+ stableKey: item.stableKey,
526
+ action: 'noop',
527
+ status: 'skipped',
528
+ targetPath: local ? localTargetPath(input.cwd, local.manifestPath) : item.stableKey,
529
+ reason: 'No local changes; target-local secrets are preserved',
530
+ credentials: { stableKey: item.stableKey, environment: input.envName, policy: 'target-local', status: 'preserved-target-local' },
531
+ });
532
+ }
533
+ const identities = !input.onlyStableKeys
534
+ ? await (await import("./identity-migration.js")).planIdentityMigration({ ...input, resources: ['service-account'] }) : undefined;
535
+ const order = new Map((identities?.ordered || []).map((node, index) => [node.stableKey, index]));
536
+ const writeItems = plan.items.filter((item) => item.status === 'create')
537
+ .concat(plan.items.filter((item) => ['safe-update', 'missing-lock', 'remote-changed', 'conflict'].includes(item.status)));
538
+ writeItems.sort((left, right) => (order.get(left.stableKey || '') ?? 0) - (order.get(right.stableKey || '') ?? 0));
539
+ for (const item of writeItems) {
540
+ const stableKey = item.stableKey || '';
541
+ const local = localByKey.get(exactKey(stableKey));
542
+ if (!local) {
543
+ results.push({ stableKey, action: item.status === 'create' ? 'create' : 'update', status: 'failed', targetPath: stableKey, error: 'desired manifest disappeared after planning' });
544
+ continue;
545
+ }
546
+ const targetPath = localTargetPath(input.cwd, local.manifestPath);
547
+ const liveDesiredHash = hashPortableServiceAccount(local.manifest);
548
+ if (liveDesiredHash !== item.desiredHash) {
549
+ results.push({ stableKey, action: item.status === 'create' ? 'create' : 'update', status: 'failed', targetPath, error: 'desired manifest changed after planning' });
550
+ continue;
551
+ }
552
+ if (item.status === 'create') {
553
+ try {
554
+ await assertCreateStillSafe(input.client, input.stableKeyName, local.manifest);
555
+ const created = unwrapData(await input.client.createServiceAccount(await buildCreatePayload(input.client, local.manifest, input.stableKeyName)));
556
+ const createdId = serviceAccountIdOf(created);
557
+ if (!createdId) {
558
+ throw new Error('create response did not include userId');
559
+ }
560
+ const verified = unwrapData(await input.client.getServiceAccount(createdId));
561
+ const rawVerifiedManifest = await serviceAccountManifestFromRecord(input.client, verified, input.stableKeyName);
562
+ const verifiedManifest = rawVerifiedManifest ? comparableManifest(local.manifest, rawVerifiedManifest) : null;
563
+ if (!verifiedManifest || hashPortableServiceAccount(verifiedManifest) !== liveDesiredHash) {
564
+ throw new Error('created service-account did not match desired portable hash');
565
+ }
566
+ updateEnvironmentBaseline({ cwd: input.cwd, envName: input.envName, stableKey, remoteHash: liveDesiredHash });
567
+ results.push({ stableKey, action: 'create', status: 'deployed', targetPath, reason: 'Created; secrets are target-local and require separate configuration', credentials: { stableKey, environment: input.envName, policy: 'target-local', status: 'configure-manually' } });
568
+ }
569
+ catch (error) {
570
+ results.push({ stableKey, action: 'create', status: 'failed', targetPath, error: error instanceof Error ? error.message : String(error) });
571
+ }
572
+ continue;
573
+ }
574
+ try {
575
+ const matches = await liveTargetByStableKey(input.client, input.stableKeyName, stableKey);
576
+ if (matches.length !== 1) {
577
+ throw new Error(`expected one live target match, found ${matches.length}`);
578
+ }
579
+ const targetId = serviceAccountIdOf(matches[0]);
580
+ if (!targetId) {
581
+ throw new Error('live target did not include userId');
582
+ }
583
+ let target = unwrapData(await input.client.getServiceAccount(targetId));
584
+ let targetManifest = await serviceAccountManifestFromRecord(input.client, target, input.stableKeyName);
585
+ if (targetManifest) {
586
+ targetManifest = comparableManifest(local.manifest, targetManifest);
587
+ }
588
+ if (!targetManifest || hashPortableServiceAccount(targetManifest) !== item.currentHash) {
589
+ throw new Error('target changed after planning');
590
+ }
591
+ const diff = diffServiceAccounts(local.manifest, targetManifest);
592
+ if (diff.changedFields.length > 0) {
593
+ await input.client.updateServiceAccount(targetId, await buildBaseUpdatePayload(input.client, local.manifest, target, input.stableKeyName));
594
+ target = unwrapData(await input.client.getServiceAccount(targetId));
595
+ targetManifest = await serviceAccountManifestFromRecord(input.client, target, input.stableKeyName);
596
+ if (!targetManifest) {
597
+ throw new Error(`updated target is missing ${input.stableKeyName}`);
598
+ }
599
+ }
600
+ const verified = unwrapData(await input.client.getServiceAccount(targetId));
601
+ const rawVerifiedManifest = await serviceAccountManifestFromRecord(input.client, verified, input.stableKeyName);
602
+ const verifiedManifest = rawVerifiedManifest ? comparableManifest(local.manifest, rawVerifiedManifest) : null;
603
+ if (!verifiedManifest || hashPortableServiceAccount(verifiedManifest) !== liveDesiredHash) {
604
+ throw new Error('updated service-account did not match desired portable hash');
605
+ }
606
+ updateEnvironmentBaseline({ cwd: input.cwd, envName: input.envName, stableKey, remoteHash: liveDesiredHash });
607
+ results.push({ stableKey, action: 'update', status: 'deployed', targetPath, reason: 'Target-local secrets preserved', credentials: { stableKey, environment: input.envName, policy: 'target-local', status: 'preserved-target-local' } });
608
+ }
609
+ catch (error) {
610
+ results.push({ stableKey, action: 'update', status: 'failed', targetPath, error: error instanceof Error ? error.message : String(error) });
611
+ }
612
+ }
613
+ for (const item of plan.items.filter((candidate) => candidate.status === 'orphan')) {
614
+ results.push({ stableKey: item.stableKey || item.name, action: 'orphan', status: 'skipped', targetPath: item.stableKey || item.name, reason: 'target-only orphan' });
615
+ }
616
+ for (const item of plan.items.filter((candidate) => candidate.status === 'skipped' || candidate.status === 'manual-owner')) {
617
+ results.push({ stableKey: item.stableKey || item.name, action: 'skipped', status: 'skipped', targetPath: item.stableKey || item.name, reason: item.reason || 'unmanaged' });
618
+ }
619
+ return { plan, results };
620
+ }
@@ -199,6 +199,9 @@ const DIFF_KIND_STYLE = {
199
199
  };
200
200
  export function printWorkspaceDiff(println, diff) {
201
201
  println(`${paint('Workspace diff', ANSI.bold)} for ${paint(diff.to, ANSI.bold + ANSI.cyan)}`);
202
+ for (const notice of diff.notices || []) {
203
+ println(`Notice: ${notice}`);
204
+ }
202
205
  if (diff.changes.length === 0) {
203
206
  println(paint('No differences.', ANSI.green));
204
207
  return;
@@ -1,5 +1,5 @@
1
1
  export declare const TRACK_ALL_RESOURCES = "all";
2
- export declare const TRACKABLE_RESOURCE_TYPES: readonly ["component", "endpoint", "group", "role-group", "job-template", "schedule", "event", "database-table", "database-view"];
2
+ export declare const TRACKABLE_RESOURCE_TYPES: readonly ["component", "endpoint", "group", "role-group", "job-template", "schedule", "event", "database-table", "database-view", "service-account"];
3
3
  export type TrackableResourceType = typeof TRACKABLE_RESOURCE_TYPES[number];
4
4
  export type TrackedResource = typeof TRACK_ALL_RESOURCES | TrackableResourceType;
5
5
  export declare function normalizeTrackedResources(value: string | string[] | null | undefined): TrackedResource[];
@@ -1,6 +1,10 @@
1
1
  export const TRACK_ALL_RESOURCES = 'all';
2
- export const TRACKABLE_RESOURCE_TYPES = ['component', 'endpoint', 'group', 'role-group', 'job-template', 'schedule', 'event', 'database-table', 'database-view'];
2
+ export const TRACKABLE_RESOURCE_TYPES = ['component', 'endpoint', 'group', 'role-group', 'job-template', 'schedule', 'event', 'database-table', 'database-view', 'service-account'];
3
3
  const RESOURCE_ALIASES = {
4
+ 'service-account': 'service-account',
5
+ 'service-accounts': 'service-account',
6
+ serviceaccount: 'service-account',
7
+ serviceaccounts: 'service-account',
4
8
  all: TRACK_ALL_RESOURCES,
5
9
  '*': TRACK_ALL_RESOURCES,
6
10
  component: 'component',
@@ -159,6 +159,18 @@ export type EndpointRecord = {
159
159
  deletedBy?: string | null;
160
160
  [key: string]: unknown;
161
161
  };
162
+ export type ServiceAccountRecord = {
163
+ category?: string | null;
164
+ userId?: string;
165
+ name?: string;
166
+ serviceAccount?: boolean;
167
+ ownerId?: string;
168
+ ownerType?: string;
169
+ version?: number;
170
+ deletedAt?: string | null;
171
+ metadata?: Record<string, unknown>;
172
+ [key: string]: unknown;
173
+ };
162
174
  export type RoleGroupRecord = {
163
175
  roleGroupId?: string;
164
176
  id?: string;