@revoengine/cli 1.0.18 → 1.0.20

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.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # @revoengine/cli
2
2
 
3
+ Development and GitLab CI use Node.js 24.21.0. Run `nvm use` in this repository to select the checked-in `.nvmrc`.
4
+
3
5
  Official command-line interface for moving RevoEngine configuration between an instance, a Git repository, and another instance.
4
6
 
5
7
  The CLI has three main capabilities:
@@ -510,7 +512,9 @@ revo request GET /api/component/list
510
512
  revo request POST /api/component '{"name":"Customer Card"}'
511
513
 
512
514
  # Debug a local component in the sandbox
513
- revo component debug <componentId> --stream
515
+ revo component debug <componentId> --read-only=true --stream
516
+ # Full execution requires a component execution role:
517
+ revo component debug <componentId> --read-only=false
514
518
  ```
515
519
 
516
520
  Use low-level `request` carefully; it bypasses the higher-level migration planner.
@@ -560,12 +564,36 @@ The same family is included in `revo pull --all`, repository `diff`/`plan`/`depl
560
564
  Select it alone with `--resources service-account`. Named profiles (`--project`/`--env`), URL/token environment variables,
561
565
  and the ordinary authenticated runtime work through the existing config resolution. `--force` retains the existing drift policy.
562
566
 
563
- The portable manifest contains the Stable Key, name, and Stable Key of a Group or Service Account owner.
567
+ The portable manifest contains the Stable Key, name, and a single Group, Service Account or built-in System management principal. The manifest field `owner` remains the portable dependency policy; Platform 1.6.4 writes it as a restricted management `access` ACL, with target UUIDs and no legacy `ownerId`/`ownerType` fields.
564
568
  Group USER owners and Job Template `triggerUser` references to Service Accounts are resolved to target `userId` at write time.
569
+ Use `owner: { "type": "system" }` for a Group or Service Account managed by the physical built-in System account. The CLI reads the target account with UUID `00000000-0000-0000-0000-000000000000` and verifies `serviceAccount: true` and active state before any dependent write; an unmigrated instance is blocked. System itself is never exported as a managed account, assigned a Stable Key, updated or pruned. An ordinary account named System remains managed through its own Stable Key.
565
570
  Human principals are reported for manual configuration; an account with a human owner needs a target account with the exact Stable Key before it can be adopted.
566
571
  A missing or circular owner dependency blocks writes. Groups and accounts are created in dependency order before their consumers.
567
572
 
568
573
  API keys and secrets cannot be exported. Every newly created Service Account is active and has platform access but has no migrated credentials.
569
574
  The push result contains `credentials: { stableKey, environment, policy: "target-local", status: "configure-manually" }`.
570
575
  Existing target secrets remain local and are never compared, copied, rotated, or exposed in manifests, plans, lock files, or HTTP trace.
571
- Memberships, ACL, other account metadata, and `metadataAdvanced` remain outside this sync contract.
576
+ Execution memberships, unrestricted or multiple-principal management ACLs, other account metadata, and `metadataAdvanced` remain target-local. Existing self access is preserved when a portable management principal changes; name/metadata updates omit the ACL. Complex target ACLs cannot be replaced through the single-principal manifest, including with `--force`.
577
+
578
+
579
+ ## Runtime execution policies
580
+
581
+ Endpoint `execution` still identifies its Component. The separate optional `executionPolicy` selects runtime authority and, for Endpoints, the account exposed through `api.currentUser`:
582
+
583
+ ```json
584
+ {
585
+ "executionPolicy": {
586
+ "mode": "SERVICE_ACCOUNT",
587
+ "serviceAccount": { "kind": "system" },
588
+ "currentUser": "CALLER"
589
+ }
590
+ }
591
+ ```
592
+
593
+ A normal Service Account uses `serviceAccount: { "kind": "service-account", "stableKey": "Ops/Robot#abc12345" }`. The target account must be active and have platform access. Plans include accounts created earlier in a multi-resource migration; writes resolve fresh target IDs and account state. The manifest and lock contain portable references, never source account UUIDs.
594
+
595
+ Both Endpoints and Job Templates accept `mode: "INHERIT"`, `"CALLER"` or `"SERVICE_ACCOUNT"`. Non-Service Account modes omit `serviceAccount`. Endpoint `currentUser` independently accepts `"INHERIT"`, `"CALLER"` or `"EXECUTION_ACCOUNT"`. Job Templates expose the executor through `api.currentUser` and record the initiator separately; unattended jobs require a Service Account. Set instance defaults in **Settings > Endpoints**. Instance settings are target-local and are not copied by resource migration.
596
+
597
+ Job Template manifests retain the legacy `executionPrincipal` reference for existing definitions, including `{ "kind": "system" }`. Use either this field or `executionPolicy`, never both. Writing an explicit policy clears the legacy `triggerUser` alias. Definitions without either field retain target-local execution configuration. An explicit policy pointing to a human or an unkeyed ordinary account cannot be exported as a portable definition.
598
+
599
+ Selecting System or another instance administrator execution account approves the current instance Component and library code. Later source changes require administrator approval; ordinary editors cannot replace approved code silently. Authority selection preserves the caller in the audit trail.
@@ -1,3 +1,4 @@
1
+ import type { RuntimeExecutionPolicy } from './types.ts';
1
2
  import { RequestQueue } from './request-queue.ts';
2
3
  import type { ComponentRecord, DatabaseSchemaRecord, DatabaseViewRecord, EndpointRecord, EventRecord, GroupRecord, JobTemplateRecord, RoleGroupRecord, ServiceAccountRecord, ScheduleRecord } from './types.ts';
3
4
  import type { TrackableResourceType } from './tracked-resources.ts';
@@ -123,6 +124,7 @@ export type DatabaseViewUpdatePayload = {
123
124
  });
124
125
  export type EndpointListRequest = ComponentListRequest;
125
126
  export type EndpointWritePayload = {
127
+ executionPolicy?: RuntimeExecutionPolicy;
126
128
  version: number;
127
129
  metadata: Record<string, unknown>;
128
130
  name?: string;
@@ -144,8 +146,31 @@ export type EndpointCreatePayload = Omit<EndpointWritePayload, 'version'> & {
144
146
  export type ServiceAccountWritePayload = {
145
147
  name?: string;
146
148
  metadata?: Record<string, unknown>;
147
- ownerId?: string;
148
- ownerType?: 'USER' | 'GROUP';
149
+ access?: {
150
+ restricted: boolean;
151
+ users?: Array<string | {
152
+ id: string;
153
+ } | {
154
+ mail: string;
155
+ }>;
156
+ groups?: Array<string | {
157
+ id: string;
158
+ } | {
159
+ name: string;
160
+ }>;
161
+ };
162
+ memberships?: {
163
+ groups?: Array<string | {
164
+ id: string;
165
+ } | {
166
+ name: string;
167
+ }>;
168
+ roleGroups?: Array<string | {
169
+ id: string;
170
+ } | {
171
+ name: string;
172
+ }>;
173
+ };
149
174
  version?: number;
150
175
  };
151
176
  export type RoleGroupListRequest = {
@@ -218,7 +243,8 @@ export type ScheduleCreatePayload = {
218
243
  targetConfig?: Record<string, unknown> | null;
219
244
  };
220
245
  export type JobTemplateUpdatePayload = {
221
- triggerUser?: string;
246
+ executionPolicy?: RuntimeExecutionPolicy;
247
+ triggerUser?: string | null;
222
248
  version: number;
223
249
  name?: string;
224
250
  category?: string | null;
@@ -230,7 +256,8 @@ export type JobTemplateUpdatePayload = {
230
256
  inputs?: unknown;
231
257
  };
232
258
  export type JobTemplateCreatePayload = {
233
- triggerUser?: string;
259
+ executionPolicy?: RuntimeExecutionPolicy;
260
+ triggerUser?: string | null;
234
261
  name: string;
235
262
  category?: string | null;
236
263
  desc?: string;
@@ -416,8 +443,6 @@ export declare class RevoClient {
416
443
  getServiceAccount(userId: string): Promise<ServiceAccountRecord>;
417
444
  createServiceAccount(body: ServiceAccountWritePayload & {
418
445
  name: string;
419
- ownerId: string;
420
- ownerType: 'USER' | 'GROUP';
421
446
  }): Promise<ServiceAccountRecord>;
422
447
  updateServiceAccount(userId: string, body: ServiceAccountWritePayload): Promise<ServiceAccountRecord>;
423
448
  listRoleGroups(options?: RoleGroupListRequest): Promise<unknown>;
@@ -1208,7 +1208,7 @@ export class RevoClient {
1208
1208
  throw new Error('Invalid account response.');
1209
1209
  }
1210
1210
  const record = {};
1211
- for (const field of ['userId', 'name', 'serviceAccount', 'ownerId', 'ownerType', 'version', 'deletedAt']) {
1211
+ for (const field of ['userId', 'name', 'serviceAccount', 'ownerId', 'ownerType', 'access', 'memberships', 'version', 'deletedAt', 'deletedBy', 'status', 'platformAccess']) {
1212
1212
  if (wrapper[field] !== undefined) {
1213
1213
  Object.assign(record, { [field]: wrapper[field] });
1214
1214
  }
@@ -1855,6 +1855,28 @@ function readLibraryDebugCode(cwd, type) {
1855
1855
  const filePath = path.join(cwd, '.revoengine', fileName);
1856
1856
  return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
1857
1857
  }
1858
+ function resolveDebugReadOnly(cwd, flag) {
1859
+ if (flag !== undefined) {
1860
+ if (flag === true || flag === 'true')
1861
+ return true;
1862
+ if (flag === false || flag === 'false')
1863
+ return false;
1864
+ throw new Error('--read-only must be true or false.');
1865
+ }
1866
+ const configPath = path.join(getProjectRoot(cwd) || cwd, '.revoengine', 'debug.json');
1867
+ if (!fs.existsSync(configPath))
1868
+ return true;
1869
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1870
+ if (typeof config.readOnly === 'boolean')
1871
+ return config.readOnly;
1872
+ if (typeof config.production === 'boolean') {
1873
+ const { production, ...rest } = config;
1874
+ const readOnly = !production;
1875
+ fs.writeFileSync(configPath, `${JSON.stringify({ ...rest, readOnly }, null, 2)}\n`);
1876
+ return readOnly;
1877
+ }
1878
+ return true;
1879
+ }
1858
1880
  function buildDebugPayload(cwd, component, input) {
1859
1881
  const type = normalizeComponentType(component);
1860
1882
  const base = {
@@ -1862,6 +1884,7 @@ function buildDebugPayload(cwd, component, input) {
1862
1884
  inputs: input.inputs,
1863
1885
  timeout: input.timeout,
1864
1886
  memory: input.memory,
1887
+ readOnly: input.readOnly,
1865
1888
  ...(input.extraLibs?.length ? { extraLibs: input.extraLibs } : {}),
1866
1889
  };
1867
1890
  if (!isDebugLibraryType(type)) {
@@ -1977,6 +2000,7 @@ async function debugSingleComponent(context, componentId) {
1977
2000
  const inputs = parseDebugInputs(context.args);
1978
2001
  const timeout = parseDebugNumber(context.args, ['timeout', 't'], 10, 600, 'Timeout');
1979
2002
  const memory = parseDebugNumber(context.args, ['memory', 'm'], 128, 1024, 'Memory');
2003
+ const readOnly = resolveDebugReadOnly(context.cwd, context.args['read-only']);
1980
2004
  const stream = readBoolFlag(context.args, ['stream']);
1981
2005
  const includeExtraLibs = context.args['extra-libs'] !== false
1982
2006
  && !readBoolFlag(context.args, ['no-extra-libs']);
@@ -1991,6 +2015,7 @@ async function debugSingleComponent(context, componentId) {
1991
2015
  inputs,
1992
2016
  timeout,
1993
2017
  memory,
2018
+ readOnly,
1994
2019
  extraLibs: extraLibs.map((entry) => entry.payload),
1995
2020
  });
1996
2021
  const endpoint = stream ? buildSandboxDebugStreamUrl(sandboxEndpoint) : buildSandboxDebugUrl(sandboxEndpoint);
@@ -47,6 +47,9 @@ export type GroupOwnerPolicy = {
47
47
  } | {
48
48
  type: 'service-account';
49
49
  stableKey: string;
50
+ } | {
51
+ type: 'system';
52
+ stableKey?: never;
50
53
  } | {
51
54
  type: 'manual-user';
52
55
  } | {
@@ -215,11 +215,13 @@ export function readComponentLock(projectRoot) {
215
215
  sourceHash: String(entry.sourceHash),
216
216
  ...((isRecord(entry.owner) && (entry.owner.type === 'group' || entry.owner.type === 'service-account') && typeof entry.owner.stableKey === 'string')
217
217
  ? { owner: { type: entry.owner.type, stableKey: entry.owner.stableKey } }
218
- : (isRecord(entry.owner) && entry.owner.type === 'manual-user')
219
- ? { owner: { type: 'manual-user' } }
220
- : (isRecord(entry.owner) && entry.owner.type === 'unresolved' && typeof entry.owner.reason === 'string')
221
- ? { owner: { type: 'unresolved', reason: entry.owner.reason } }
222
- : {}),
218
+ : (isRecord(entry.owner) && entry.owner.type === 'system')
219
+ ? { owner: { type: 'system' } }
220
+ : (isRecord(entry.owner) && entry.owner.type === 'manual-user')
221
+ ? { owner: { type: 'manual-user' } }
222
+ : (isRecord(entry.owner) && entry.owner.type === 'unresolved' && typeof entry.owner.reason === 'string')
223
+ ? { owner: { type: 'unresolved', reason: entry.owner.reason } }
224
+ : {}),
223
225
  environments: Object.fromEntries(Object.entries(entry.environments)
224
226
  .filter(([, baseline]) => typeof baseline.remoteHash === 'string' && typeof baseline.syncedAt === 'string')
225
227
  .map(([envName, baseline]) => [envName, {
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { readResourceInventory, resourceIdOf, unwrapResource, } from "./resource-inventory.js";
3
3
  import { isDatabaseBackupArtifact } from "./database-table-artifacts.js";
4
+ import { isBuiltinSystemAccount } from "./resource-syncs/account-principal.js";
4
5
  import { buildStableKey, buildResourceIdentityStableKeyValue, normalizeStableKeyValue, readConfiguredResourceMetadataStableKey, sanitizeUserMetadata, } from "./resource-metadata.js";
5
6
  import { shouldTrackResource } from "./tracked-resources.js";
6
7
  function isRecord(value) {
@@ -160,6 +161,8 @@ function endpointExclusionReason(endpoint) {
160
161
  return endpoint.deletedAt || endpoint.deletedBy ? 'deleted endpoint is excluded' : null;
161
162
  }
162
163
  function buildMetadataUpdatePayload(resource, stableKeyName, stableKey, resourceType) {
164
+ if (isBuiltinSystemAccount(resource))
165
+ throw new Error('The built-in System account cannot be managed by metadata backfill.');
163
166
  if (!Number.isInteger(resource.version)) {
164
167
  throw new Error(`${resourceType} version is required to update metadata`);
165
168
  }
@@ -487,6 +490,10 @@ export async function buildMetadataBackfillPlan(input) {
487
490
  }
488
491
  if (shouldTrackResource(trackedResources, 'service-account') && typeof client.listAllServiceAccounts === 'function') {
489
492
  for await (const { listedId, resource: account } of readResourceInventory(client, 'service-account')) {
493
+ if (isBuiltinSystemAccount(account)) {
494
+ items.push({ resourceType: 'service-account', resourceId: resourceIdOf(account) || listedId, name: String(account.name || 'System'), category: null, action: 'skip', metadataField: 'metadata', stableKeyName, reason: 'built-in System account is managed by the platform' });
495
+ continue;
496
+ }
490
497
  if (!listedId) {
491
498
  continue;
492
499
  }
@@ -982,6 +989,8 @@ export async function applyMetadataBackfillPlan(input) {
982
989
  }
983
990
  if (item.resourceType === 'service-account') {
984
991
  const account = await client.getServiceAccount(item.resourceId);
992
+ if (isBuiltinSystemAccount(account))
993
+ throw new Error('The built-in System account cannot be managed by metadata backfill.');
985
994
  const current = readConfiguredResourceMetadataStableKey(account, plan.stableKeyName);
986
995
  if (current && !plan.force) {
987
996
  results.push({ resourceType: item.resourceType, resourceId: item.resourceId, stableKey: current, action: 'skip' });
@@ -1065,6 +1065,7 @@ async function planWorkspace(input) {
1065
1065
  envName: environmentKey,
1066
1066
  stableKeyName,
1067
1067
  includeDependencyBlockers: input.sourceMode === 'workspace',
1068
+ projectedServiceAccounts: identities?.projection.serviceAccounts,
1068
1069
  ...(input.projectDependencies === true && components
1069
1070
  ? { projectedComponents: projectedComponentDependencies(components) }
1070
1071
  : {}),
@@ -526,7 +526,7 @@ export function ensureProjectDebugScaffolding(rootDir) {
526
526
  [path.join(rootDir, REVO_DEBUG_CONFIG_FILE), `${JSON.stringify({
527
527
  timeout: 10,
528
528
  memory: 128,
529
- production: false,
529
+ readOnly: true,
530
530
  }, null, 2)}\n`],
531
531
  [path.join(rootDir, REVO_PLAYGROUND_JS_FILE), ''],
532
532
  [path.join(rootDir, REVO_PLAYGROUND_TS_FILE), ''],
@@ -1,10 +1,18 @@
1
1
  import { type RevoClient } from '../client.ts';
2
2
  import type { GroupOwnerPolicy } from '../component-lock.ts';
3
- import type { ServiceAccountRecord } from '../types.ts';
3
+ import type { ServiceAccountRecord, RuntimeExecutionPolicy } from '../types.ts';
4
4
  export type ExecutionPrincipal = {
5
5
  kind: 'service-account';
6
6
  stableKey: string;
7
+ } | {
8
+ kind: 'system';
9
+ stableKey?: never;
7
10
  };
11
+ export declare const SYSTEM_ACCOUNT_ID = "00000000-0000-0000-0000-000000000000";
12
+ export declare function isBuiltinSystemAccount(account: ServiceAccountRecord): boolean;
13
+ export declare function resolveSystemAccount(client: RevoClient, requireExecutionAccess?: boolean): Promise<ServiceAccountRecord>;
14
+ export declare function ownerFromPrincipal(principal: ExecutionPrincipal): GroupOwnerPolicy;
15
+ export declare function resolveExecutionPrincipal(client: RevoClient, principal: ExecutionPrincipal, stableKeyName: string): Promise<string>;
8
16
  export type IdentityProjection = {
9
17
  serviceAccounts?: string[];
10
18
  groups?: string[];
@@ -20,3 +28,13 @@ export declare function resolvePortableOwner(client: RevoClient, owner: GroupOwn
20
28
  ownerId: string;
21
29
  }>;
22
30
  export declare function ownerIsAvailable(client: RevoClient, owner: GroupOwnerPolicy, stableKeyName: string, projection?: IdentityProjection): Promise<boolean>;
31
+ export type PortableExecutionPolicy = {
32
+ mode: 'INHERIT' | 'CALLER' | 'SERVICE_ACCOUNT';
33
+ serviceAccount?: ExecutionPrincipal;
34
+ currentUser?: 'INHERIT' | 'CALLER' | 'EXECUTION_ACCOUNT';
35
+ };
36
+ export declare function validExecutionPrincipal(value: unknown): value is ExecutionPrincipal;
37
+ export declare function validPortableExecutionPolicy(value: unknown, allowCurrentUser?: boolean): value is PortableExecutionPolicy;
38
+ export declare function portableExecutionPolicy(client: RevoClient, policy: RuntimeExecutionPolicy | null | undefined, stableKeyName: string): Promise<PortableExecutionPolicy | undefined>;
39
+ export declare function runtimeExecutionPolicyPayload(client: RevoClient, policy: PortableExecutionPolicy | undefined, stableKeyName: string): Promise<RuntimeExecutionPolicy | undefined>;
40
+ export declare function executionPrincipalAvailable(client: RevoClient, principal: ExecutionPrincipal, stableKeyName: string, projected?: string[], requireExecutionAccess?: boolean): Promise<boolean>;
@@ -1,6 +1,29 @@
1
1
  import { ApiError } from "../client.js";
2
2
  import { readConfiguredResourceMetadataStableKey } from "../resource-metadata.js";
3
3
  import { unwrapData } from "./util.js";
4
+ export const SYSTEM_ACCOUNT_ID = '00000000-0000-0000-0000-000000000000';
5
+ export function isBuiltinSystemAccount(account) {
6
+ return account.userId === SYSTEM_ACCOUNT_ID && account.serviceAccount === true;
7
+ }
8
+ export async function resolveSystemAccount(client, requireExecutionAccess = false) {
9
+ const account = await client.getAccount(SYSTEM_ACCOUNT_ID);
10
+ if (!isBuiltinSystemAccount(account) || account.deletedAt || account.deletedBy
11
+ || ![0, 'ACTIVE'].includes(account.status) || (requireExecutionAccess && account.platformAccess !== true)) {
12
+ throw new Error('The target built-in System account is unavailable; migrate the instance before using a System reference.');
13
+ }
14
+ return account;
15
+ }
16
+ export function ownerFromPrincipal(principal) {
17
+ return principal.kind === 'system' ? { type: 'system' } : { type: 'service-account', stableKey: principal.stableKey };
18
+ }
19
+ export async function resolveExecutionPrincipal(client, principal, stableKeyName) {
20
+ if (principal.kind === 'system')
21
+ return String((await resolveSystemAccount(client, true)).userId);
22
+ const matches = await serviceAccountMatches(client, principal.stableKey, stableKeyName);
23
+ if (matches.length !== 1 || !matches[0].userId)
24
+ throw new Error('Execution principal must resolve to exactly one target service account.');
25
+ return matches[0].userId;
26
+ }
4
27
  export async function accountPrincipal(client, userId, stableKeyName) {
5
28
  let account;
6
29
  try {
@@ -12,16 +35,18 @@ export async function accountPrincipal(client, userId, stableKeyName) {
12
35
  }
13
36
  throw error;
14
37
  }
15
- if (account.serviceAccount !== true || account.deletedAt) {
38
+ if (account.serviceAccount !== true || account.deletedAt || account.deletedBy) {
16
39
  return undefined;
17
40
  }
41
+ if (isBuiltinSystemAccount(account))
42
+ return { kind: 'system' };
18
43
  const stableKey = readConfiguredResourceMetadataStableKey(account, stableKeyName);
19
44
  return stableKey ? { kind: 'service-account', stableKey } : undefined;
20
45
  }
21
46
  export async function readPortableOwner(client, record, stableKeyName) {
22
47
  if (record.ownerType === 'USER' && record.ownerId) {
23
48
  const principal = await accountPrincipal(client, record.ownerId, stableKeyName);
24
- return principal ? { type: 'service-account', stableKey: principal.stableKey } : { type: 'manual-user' };
49
+ return principal ? ownerFromPrincipal(principal) : { type: 'manual-user' };
25
50
  }
26
51
  if (record.ownerType === 'GROUP' && record.ownerId) {
27
52
  const group = unwrapData(await client.getGroup(record.ownerId));
@@ -35,13 +60,16 @@ export async function serviceAccountMatches(client, stableKey, stableKeyName) {
35
60
  const matches = [];
36
61
  for (const summary of serviceAccounts) {
37
62
  const account = await client.getServiceAccount(String(summary.userId || ''));
38
- if (readConfiguredResourceMetadataStableKey(account, stableKeyName) === stableKey) {
63
+ if (!isBuiltinSystemAccount(account) && readConfiguredResourceMetadataStableKey(account, stableKeyName) === stableKey) {
39
64
  matches.push(account);
40
65
  }
41
66
  }
42
67
  return matches;
43
68
  }
44
69
  export async function resolvePortableOwner(client, owner, stableKeyName) {
70
+ if (owner.type === 'system') {
71
+ return { ownerType: 'USER', ownerId: String((await resolveSystemAccount(client)).userId) };
72
+ }
45
73
  if (owner.type === 'service-account') {
46
74
  const matches = await serviceAccountMatches(client, owner.stableKey, stableKeyName);
47
75
  if (matches.length !== 1 || !matches[0].userId) {
@@ -66,7 +94,7 @@ export async function resolvePortableOwner(client, owner, stableKeyName) {
66
94
  throw new Error('Owner requires manual target configuration.');
67
95
  }
68
96
  export async function ownerIsAvailable(client, owner, stableKeyName, projection) {
69
- if (owner.type !== 'group' && owner.type !== 'service-account') {
97
+ if (owner.type !== 'group' && owner.type !== 'service-account' && owner.type !== 'system') {
70
98
  return false;
71
99
  }
72
100
  try {
@@ -74,6 +102,8 @@ export async function ownerIsAvailable(client, owner, stableKeyName, projection)
74
102
  return true;
75
103
  }
76
104
  catch {
105
+ if (owner.type === 'system')
106
+ return false;
77
107
  // Projection cannot mask duplicate live identities.
78
108
  if (owner.type === 'service-account') {
79
109
  const matches = await serviceAccountMatches(client, owner.stableKey, stableKeyName);
@@ -84,3 +114,63 @@ export async function ownerIsAvailable(client, owner, stableKeyName, projection)
84
114
  return matches.length === 0 && (projection?.groups || []).includes(owner.stableKey);
85
115
  }
86
116
  }
117
+ export function validExecutionPrincipal(value) {
118
+ if (!value || typeof value !== 'object' || Array.isArray(value))
119
+ return false;
120
+ const principal = value;
121
+ return principal.kind === 'system' ? Object.keys(principal).length === 1
122
+ : principal.kind === 'service-account' && typeof principal.stableKey === 'string' && !!principal.stableKey.trim()
123
+ && Object.keys(principal).every(key => ['kind', 'stableKey'].includes(key));
124
+ }
125
+ export function validPortableExecutionPolicy(value, allowCurrentUser = false) {
126
+ if (!value || typeof value !== 'object' || Array.isArray(value))
127
+ return false;
128
+ const policy = value;
129
+ return ['INHERIT', 'CALLER', 'SERVICE_ACCOUNT'].includes(String(policy.mode))
130
+ && Object.keys(policy).every(key => ['mode', 'serviceAccount', ...(allowCurrentUser ? ['currentUser'] : [])].includes(key))
131
+ && (policy.mode === 'SERVICE_ACCOUNT' ? validExecutionPrincipal(policy.serviceAccount) : policy.serviceAccount === undefined)
132
+ && (policy.currentUser === undefined || allowCurrentUser && ['INHERIT', 'CALLER', 'EXECUTION_ACCOUNT'].includes(String(policy.currentUser)));
133
+ }
134
+ export async function portableExecutionPolicy(client, policy, stableKeyName) {
135
+ if (!policy)
136
+ return undefined;
137
+ if (!['INHERIT', 'CALLER', 'SERVICE_ACCOUNT'].includes(policy.mode))
138
+ throw new Error('Invalid saved runtime execution policy.');
139
+ const serviceAccount = policy.mode === 'SERVICE_ACCOUNT' && policy.serviceAccountUserId
140
+ ? await accountPrincipal(client, policy.serviceAccountUserId, stableKeyName) : undefined;
141
+ if (policy.mode === 'SERVICE_ACCOUNT' && !serviceAccount)
142
+ throw new Error('Execution account is human, unavailable, or missing a portable Stable Key.');
143
+ return { mode: policy.mode, ...(serviceAccount ? { serviceAccount } : {}), ...(policy.currentUser ? { currentUser: policy.currentUser } : {}) };
144
+ }
145
+ export async function runtimeExecutionPolicyPayload(client, policy, stableKeyName) {
146
+ if (!policy)
147
+ return undefined;
148
+ const userId = policy.mode === 'SERVICE_ACCOUNT' ? await resolveExecutionPrincipal(client, policy.serviceAccount, stableKeyName) : undefined;
149
+ if (userId && policy.serviceAccount.kind !== 'system') {
150
+ const target = await client.getAccount(userId);
151
+ if (target.deletedAt || target.deletedBy || ![0, 'ACTIVE'].includes(target.status) || target.platformAccess !== true) {
152
+ throw new Error('Execution service account must be active and have platform access.');
153
+ }
154
+ }
155
+ return { mode: policy.mode, ...(userId ? { serviceAccountUserId: userId } : {}), ...(policy.currentUser ? { currentUser: policy.currentUser } : {}) };
156
+ }
157
+ export async function executionPrincipalAvailable(client, principal, stableKeyName, projected = [], requireExecutionAccess = false) {
158
+ if (principal.kind === 'system') {
159
+ try {
160
+ await resolveSystemAccount(client, true);
161
+ return true;
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ const matches = await serviceAccountMatches(client, principal.stableKey, stableKeyName);
168
+ if (matches.length === 1) {
169
+ if (!requireExecutionAccess)
170
+ return true;
171
+ const target = await client.getAccount(String(matches[0].userId));
172
+ return target.serviceAccount === true && !target.deletedAt && !target.deletedBy
173
+ && [0, 'ACTIVE'].includes(target.status) && target.platformAccess === true;
174
+ }
175
+ return matches.length === 0 && projected.includes(principal.stableKey);
176
+ }
@@ -1,3 +1,4 @@
1
+ import { type PortableExecutionPolicy } from './account-principal.ts';
1
2
  import { type FieldChange } from '../diff-details.ts';
2
3
  import type { RevoClient } from '../client.ts';
3
4
  export declare const ENDPOINTS_DIRECTORY = "Endpoints";
@@ -25,6 +26,7 @@ export type EndpointManifest = {
25
26
  };
26
27
  options?: Record<string, unknown>;
27
28
  execution?: EndpointComponentBinding;
29
+ executionPolicy?: PortableExecutionPolicy;
28
30
  schema?: EndpointSchemaBinding;
29
31
  };
30
32
  export type EndpointPullResult = {
@@ -110,6 +112,7 @@ export declare function buildEndpointsPlan(input: {
110
112
  envName: string;
111
113
  stableKeyName: string;
112
114
  projectedComponents?: ProjectedEndpointComponentDependency[];
115
+ projectedServiceAccounts?: string[];
113
116
  includeDependencyBlockers?: boolean;
114
117
  }): Promise<EndpointPlan>;
115
118
  export declare function pushEndpoints(input: {
@@ -1,3 +1,4 @@
1
+ import { executionPrincipalAvailable, portableExecutionPolicy, runtimeExecutionPolicyPayload, validPortableExecutionPolicy } from "./account-principal.js";
1
2
  import path from 'node:path';
2
3
  import { describeFieldChanges } from "../diff-details.js";
3
4
  import { hashPortableComponentSource, hashStable, readComponentLock, writeComponentLock } from "../component-lock.js";
@@ -109,7 +110,7 @@ function disambiguateManifestPath(filePath, stableKey) {
109
110
  }
110
111
  const ENDPOINT_MANIFEST_FIELDS = new Set([
111
112
  'kind', 'stableKey', 'name', 'category', 'description', 'metadata', 'active', 'timeout',
112
- 'route', 'options', 'execution', 'schema',
113
+ 'route', 'options', 'execution', 'executionPolicy', 'schema',
113
114
  ]);
114
115
  const INSTANCE_LOCAL_SCHEMA_OPTION_FIELDS = new Set([
115
116
  'componentSchemaId', 'componentSchemaVersion', 'componentSchemaElement',
@@ -169,6 +170,8 @@ function validateManifest(manifest, stableKeyName) {
169
170
  && Object.keys(manifest.options).some((key) => INSTANCE_LOCAL_SCHEMA_OPTION_FIELDS.has(key))) {
170
171
  return false;
171
172
  }
173
+ if (manifest.executionPolicy !== undefined && !validPortableExecutionPolicy(manifest.executionPolicy, true))
174
+ return false;
172
175
  if (manifest.execution !== undefined && !hasValidBinding(manifest.execution)) {
173
176
  return false;
174
177
  }
@@ -190,6 +193,7 @@ export function hashPortableEndpoint(manifest) {
190
193
  route: canonicalValue(manifest.route),
191
194
  ...(manifest.options === undefined ? {} : { options: canonicalPortableOptions(manifest.options) }),
192
195
  ...(manifest.execution === undefined ? {} : { execution: canonicalValue(manifest.execution) }),
196
+ ...(manifest.executionPolicy === undefined ? {} : { executionPolicy: canonicalValue(manifest.executionPolicy) }),
193
197
  ...(manifest.schema === undefined ? {} : { schema: canonicalValue(manifest.schema) }),
194
198
  });
195
199
  }
@@ -308,6 +312,7 @@ async function manifestFromRecord(input) {
308
312
  }
309
313
  : undefined;
310
314
  const options = portableOptions(record);
315
+ const executionPolicy = input.includeExecutionPolicy === false ? undefined : await portableExecutionPolicy(input.client, record.executionPolicy, input.stableKeyName);
311
316
  const manifest = {
312
317
  kind: 'endpoint',
313
318
  stableKey: input.stableKey,
@@ -320,6 +325,7 @@ async function manifestFromRecord(input) {
320
325
  route: canonicalRoute(record),
321
326
  ...(options === undefined ? {} : { options }),
322
327
  ...(execution ? { execution } : {}),
328
+ ...(executionPolicy ? { executionPolicy } : {}),
323
329
  ...(schema ? { schema } : {}),
324
330
  };
325
331
  if (!validateManifest(manifest, input.stableKeyName)) {
@@ -504,6 +510,7 @@ function diffEndpoints(desired, current) {
504
510
  ['route.path', desired.route.path, current.route.path],
505
511
  ['options', canonicalPortableOptions(desired.options) ?? null, canonicalPortableOptions(current.options) ?? null],
506
512
  ['execution', canonicalValue(desired.execution ?? null), canonicalValue(current.execution ?? null)],
513
+ ...(desired.executionPolicy ? [['executionPolicy', canonicalValue(desired.executionPolicy), canonicalValue(current.executionPolicy ?? null)]] : []),
507
514
  ['schema', canonicalValue(desired.schema ?? null), canonicalValue(current.schema ?? null)],
508
515
  ];
509
516
  return fields
@@ -808,6 +815,7 @@ export async function buildEndpointsPlan(input) {
808
815
  }
809
816
  try {
810
817
  const manifest = await manifestFromRecord({
818
+ includeExecutionPolicy: (localByStableKey.get(stableKey) || []).some(entry => entry.manifest.executionPolicy !== undefined),
811
819
  client: input.client,
812
820
  record,
813
821
  stableKey,
@@ -934,6 +942,20 @@ export async function buildEndpointsPlan(input) {
934
942
  const dependencyBlockers = input.includeDependencyBlockers && dependency.blockers.length > 0
935
943
  ? { dependencyBlockers: [...dependency.blockers] }
936
944
  : {};
945
+ if (desired.executionPolicy) {
946
+ try {
947
+ const principal = desired.executionPolicy.serviceAccount;
948
+ if (principal && !await executionPrincipalAvailable(input.client, principal, input.stableKeyName, input.projectedServiceAccounts, true)) {
949
+ throw new Error('Execution service account is unavailable, inactive, lacks platform access, or is ambiguous.');
950
+ }
951
+ }
952
+ catch (error) {
953
+ const reason = error instanceof Error ? error.message : 'Execution principal is unavailable.';
954
+ blockers.push(`Endpoint "${desired.stableKey}": ${reason}`);
955
+ items.push({ status: 'conflict', stableKey: desired.stableKey, name: desired.name, reason });
956
+ continue;
957
+ }
958
+ }
937
959
  const desiredHash = hashPortableEndpoint(desired);
938
960
  if (ambiguousTargetKeys.has(stableKey) || targetIssueKeys.has(stableKey)) {
939
961
  continue;
@@ -1130,7 +1152,9 @@ async function resolveEndpointWritePayload(input) {
1130
1152
  throw new Error(`execution dependency "${input.manifest.execution?.stableKey}" has no target component id`);
1131
1153
  }
1132
1154
  const options = endpointWriteOptions(input.manifest, schema);
1155
+ const executionPolicy = await runtimeExecutionPolicyPayload(input.client, input.manifest.executionPolicy, input.stableKeyName);
1133
1156
  const common = {
1157
+ ...(executionPolicy ? { executionPolicy } : {}),
1134
1158
  name: input.manifest.name,
1135
1159
  category: input.manifest.category ?? null,
1136
1160
  desc: input.manifest.description ?? '',
@@ -1185,6 +1209,7 @@ async function verifyEndpointWrite(input) {
1185
1209
  const targetComponents = await loadRemoteComponents(input.client);
1186
1210
  const componentsById = new Map(targetComponents.map((component) => [componentIdOf(component), component]));
1187
1211
  const verifiedManifest = await manifestFromRecord({
1212
+ includeExecutionPolicy: input.desiredManifest.executionPolicy !== undefined,
1188
1213
  client: input.client,
1189
1214
  record: verified,
1190
1215
  stableKey: verifiedStableKey,
@@ -1316,6 +1341,7 @@ async function pushEndpointUpdate(input) {
1316
1341
  }
1317
1342
  const targetComponents = await loadRemoteComponents(input.client);
1318
1343
  const targetManifest = await manifestFromRecord({
1344
+ includeExecutionPolicy: prepared.manifest.executionPolicy !== undefined,
1319
1345
  client: input.client,
1320
1346
  record: target,
1321
1347
  stableKey: prepared.stableKey,
@@ -9,6 +9,9 @@ export type GroupManifest = {
9
9
  owner?: {
10
10
  type: 'service-account';
11
11
  stableKey: string;
12
+ } | {
13
+ type: 'system';
14
+ stableKey?: never;
12
15
  };
13
16
  stableKey: string;
14
17
  name: string;
@@ -47,7 +50,7 @@ export type GroupPlanItem = {
47
50
  currentHash?: string;
48
51
  baselineHash?: string;
49
52
  ownerStableKey?: string;
50
- ownerKind?: 'group' | 'service-account';
53
+ ownerKind?: 'group' | 'service-account' | 'system';
51
54
  manual?: string[];
52
55
  };
53
56
  export type GroupsPlan = {