@geek-fun/serverlessinsight 0.8.5 → 0.8.7

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 (39) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -2
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -3
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +19 -183
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -2
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +11 -72
  6. package/AGENTS.md +29 -0
  7. package/README.md +0 -12
  8. package/README.zh-CN.md +146 -286
  9. package/dist/package.json +1 -1
  10. package/dist/src/commands/deploy.js +4 -6
  11. package/dist/src/common/aliyunClient/ramOperations.js +104 -15
  12. package/dist/src/common/iacHelper.js +3 -1
  13. package/dist/src/common/iamStatements.js +21 -1
  14. package/dist/src/common/nameBuilder.js +12 -1
  15. package/dist/src/common/stateBackend/remoteStateBackend.js +1 -3
  16. package/dist/src/common/stateBackend/saasStateBackend.js +26 -5
  17. package/dist/src/common/stateManager.js +8 -4
  18. package/dist/src/common/tencentClient/camOperations.js +24 -12
  19. package/dist/src/common/volcengineClient/iamOperations.js +15 -11
  20. package/dist/src/lang/en.js +7 -0
  21. package/dist/src/lang/zh-CN.js +6 -0
  22. package/dist/src/stack/aliyunStack/apigwExecutor.js +5 -5
  23. package/dist/src/stack/aliyunStack/apigwResource.js +10 -8
  24. package/dist/src/stack/aliyunStack/apigwTypes.js +20 -5
  25. package/dist/src/stack/aliyunStack/deployer.js +33 -3
  26. package/dist/src/stack/aliyunStack/fc3Resource.js +172 -18
  27. package/dist/src/stack/aliyunStack/sharedLogProject.js +22 -5
  28. package/dist/src/stack/scfStack/scfPlanner.js +1 -1
  29. package/dist/src/stack/scfStack/scfResource.js +72 -10
  30. package/dist/src/stack/scfStack/sharedLogset.js +9 -1
  31. package/dist/src/stack/volcengineStack/apigwPlanner.js +5 -1
  32. package/dist/src/stack/volcengineStack/apigwResource.js +52 -30
  33. package/dist/src/stack/volcengineStack/apigwTypes.js +18 -7
  34. package/dist/src/stack/volcengineStack/sharedLogProject.js +9 -3
  35. package/dist/src/stack/volcengineStack/vefaasPlanner.js +5 -4
  36. package/dist/src/stack/volcengineStack/vefaasResource.js +74 -10
  37. package/dist/src/stack/volcengineStack/vefaasTypes.js +61 -7
  38. package/dist/src/validator/semanticValidation.js +41 -0
  39. package/package.json +1 -1
@@ -33,11 +33,12 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.createRamOperations = void 0;
36
+ exports.createRamOperations = exports.buildFc3ExecutionPolicyDocument = void 0;
37
37
  const ram = __importStar(require("@alicloud/ram20150501"));
38
38
  const lang_1 = require("../../lang");
39
39
  const logger_1 = require("../logger");
40
40
  const iamStatements_1 = require("../iamStatements");
41
+ const nameBuilder_1 = require("../nameBuilder");
41
42
  const buildAssumeRolePolicy = (trustedServices) => JSON.stringify({
42
43
  Version: '1',
43
44
  Statement: [
@@ -109,18 +110,24 @@ const mapToAliyunStatement = (stmt) => {
109
110
  }
110
111
  return result;
111
112
  };
112
- const buildExecutionPolicy = (customStatements) => {
113
- const merged = (0, iamStatements_1.mergePolicyStatements)(FC_EXECUTION_STATEMENTS, customStatements, mapToAliyunStatement);
113
+ /** @public Exec policy document from a derived baseline; falls back to the static FC_EXECUTION_STATEMENTS when omitted. */
114
+ const buildFc3ExecutionPolicyDocument = (executionStatements, customStatements) => {
115
+ const nativeBaseline = executionStatements
116
+ ? executionStatements.map(mapToAliyunStatement)
117
+ : FC_EXECUTION_STATEMENTS;
118
+ const merged = (0, iamStatements_1.mergePolicyStatements)(nativeBaseline, customStatements, mapToAliyunStatement);
114
119
  return (0, iamStatements_1.buildPolicyDocument)(merged, { version: '1' });
115
120
  };
121
+ exports.buildFc3ExecutionPolicyDocument = buildFc3ExecutionPolicyDocument;
122
+ const buildExecutionPolicy = (executionStatements, customStatements) => (0, exports.buildFc3ExecutionPolicyDocument)(executionStatements, customStatements);
116
123
  /* istanbul ignore next */ const createRamOperations = (ramClient) => {
117
- const attachRolePolicyForFc = async (roleName, customStatements) => {
118
- const policyName = `${roleName}-policy`;
124
+ const attachRolePolicyForFc = async (roleName, customStatements, executionStatements) => {
125
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
119
126
  // Create policy
120
127
  try {
121
128
  const createPolicyRequest = new ram.CreatePolicyRequest({
122
129
  policyName,
123
- policyDocument: buildExecutionPolicy(customStatements),
130
+ policyDocument: buildExecutionPolicy(executionStatements, customStatements),
124
131
  description: `FC execution policy for ${roleName}`,
125
132
  });
126
133
  await ramClient.createPolicy(createPolicyRequest);
@@ -215,8 +222,88 @@ const buildExecutionPolicy = (customStatements) => {
215
222
  return [];
216
223
  }
217
224
  };
225
+ const updateExecutionPolicyDocumentFn = async (roleName, policyDocument) => {
226
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
227
+ const ensureAttached = async () => {
228
+ try {
229
+ await ramClient.attachPolicyToRole(new ram.AttachPolicyToRoleRequest({ policyType: 'Custom', policyName, roleName }));
230
+ }
231
+ catch (error) {
232
+ if (!(error &&
233
+ typeof error === 'object' &&
234
+ 'code' in error &&
235
+ error.code === 'EntityAlreadyExists.Role.Policy')) {
236
+ throw error;
237
+ }
238
+ }
239
+ };
240
+ let currentDocument;
241
+ try {
242
+ const getPolicyResponse = await ramClient.getPolicy(new ram.GetPolicyRequest({ policyName, policyType: 'Custom' }));
243
+ const defaultVersionId = getPolicyResponse.body?.policy?.defaultVersion;
244
+ if (defaultVersionId) {
245
+ const versionResponse = await ramClient.getPolicyVersion(new ram.GetPolicyVersionRequest({
246
+ policyName,
247
+ policyType: 'Custom',
248
+ versionId: defaultVersionId,
249
+ }));
250
+ currentDocument = versionResponse.body?.policyVersion?.policyDocument;
251
+ }
252
+ }
253
+ catch (error) {
254
+ if (!(error &&
255
+ typeof error === 'object' &&
256
+ 'code' in error &&
257
+ error.code === 'EntityNotExist.Policy')) {
258
+ throw error;
259
+ }
260
+ try {
261
+ await ramClient.createPolicy(new ram.CreatePolicyRequest({
262
+ policyName,
263
+ policyDocument,
264
+ description: `FC execution policy for ${roleName}`,
265
+ }));
266
+ }
267
+ catch (error2) {
268
+ if (!(error2 &&
269
+ typeof error2 === 'object' &&
270
+ 'code' in error2 &&
271
+ error2.code === 'EntityAlreadyExists.Policy')) {
272
+ throw error2;
273
+ }
274
+ }
275
+ await ensureAttached();
276
+ return;
277
+ }
278
+ if (currentDocument === policyDocument) {
279
+ return;
280
+ }
281
+ try {
282
+ const listResponse = await ramClient.listPolicyVersions(new ram.ListPolicyVersionsRequest({ policyName, policyType: 'Custom' }));
283
+ const versions = listResponse.body?.policyVersions?.policyVersion ?? [];
284
+ const keepBeforeCreate = 4;
285
+ const toDelete = versions
286
+ .filter((v) => !v.isDefaultVersion)
287
+ .sort((a, b) => (a.createDate ?? '').localeCompare(b.createDate ?? ''))
288
+ .slice(0, Math.max(0, versions.length - keepBeforeCreate));
289
+ for (const version of toDelete) {
290
+ if (version.versionId) {
291
+ await ramClient.deletePolicyVersion(new ram.DeletePolicyVersionRequest({ policyName, versionId: version.versionId }));
292
+ }
293
+ }
294
+ }
295
+ catch (error) {
296
+ logger_1.logger.warn(lang_1.lang.__('RAM_POLICY_VERSION_PRUNE_FAILED', { policyName, error: String(error) }));
297
+ }
298
+ await ramClient.createPolicyVersion(new ram.CreatePolicyVersionRequest({
299
+ policyName,
300
+ policyDocument,
301
+ setAsDefault: true,
302
+ }));
303
+ await ensureAttached();
304
+ };
218
305
  return {
219
- createRole: async (roleName, trustedServices, description, customStatements, managedPolicies) => {
306
+ createRole: async (roleName, trustedServices, description, customStatements, managedPolicies, executionStatements) => {
220
307
  const assumeRolePolicy = buildAssumeRolePolicy(trustedServices);
221
308
  try {
222
309
  const request = new ram.CreateRoleRequest({
@@ -235,7 +322,7 @@ const buildExecutionPolicy = (customStatements) => {
235
322
  maxSessionDuration: response.body?.role?.maxSessionDuration,
236
323
  assumeRolePolicyDocument: assumeRolePolicy,
237
324
  };
238
- const policyName = await attachRolePolicyForFc(roleName, customStatements);
325
+ const policyName = await attachRolePolicyForFc(roleName, customStatements, executionStatements);
239
326
  if (managedPolicies && managedPolicies.length > 0) {
240
327
  await attachManagedPoliciesFn(roleName, managedPolicies);
241
328
  }
@@ -255,7 +342,8 @@ const buildExecutionPolicy = (customStatements) => {
255
342
  newAssumeRolePolicyDocument: assumeRolePolicy,
256
343
  });
257
344
  await ramClient.updateRole(updateRequest);
258
- const policyName = await attachRolePolicyForFc(roleName, customStatements);
345
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
346
+ await updateExecutionPolicyDocumentFn(roleName, (0, exports.buildFc3ExecutionPolicyDocument)(executionStatements, customStatements));
259
347
  if (managedPolicies && managedPolicies.length > 0) {
260
348
  await attachManagedPoliciesFn(roleName, managedPolicies);
261
349
  }
@@ -297,7 +385,7 @@ const buildExecutionPolicy = (customStatements) => {
297
385
  updateDate: getResponse.body?.role?.updateDate,
298
386
  maxSessionDuration: getResponse.body?.role?.maxSessionDuration,
299
387
  assumeRolePolicyDocument: assumeRolePolicy,
300
- policyName: `${roleName}-policy`,
388
+ policyName: (0, nameBuilder_1.buildRolePolicyName)(roleName),
301
389
  };
302
390
  const updateRequest = new ram.UpdateRoleRequest({
303
391
  roleName,
@@ -317,8 +405,8 @@ const buildExecutionPolicy = (customStatements) => {
317
405
  throw error;
318
406
  }
319
407
  },
320
- updateRolePolicy: async (roleName, customStatements) => {
321
- const policyName = `${roleName}-policy`;
408
+ updateRolePolicy: async (roleName, customStatements, executionStatements) => {
409
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
322
410
  try {
323
411
  await ramClient.detachPolicyFromRole(new ram.DetachPolicyFromRoleRequest({ policyType: 'Custom', policyName, roleName }));
324
412
  }
@@ -334,7 +422,7 @@ const buildExecutionPolicy = (customStatements) => {
334
422
  try {
335
423
  await ramClient.createPolicy(new ram.CreatePolicyRequest({
336
424
  policyName,
337
- policyDocument: buildExecutionPolicy(customStatements),
425
+ policyDocument: buildExecutionPolicy(executionStatements, customStatements),
338
426
  description: `FC execution policy for ${roleName}`,
339
427
  }));
340
428
  }
@@ -362,6 +450,7 @@ const buildExecutionPolicy = (customStatements) => {
362
450
  throw error;
363
451
  }
364
452
  },
453
+ updateExecutionPolicyDocument: updateExecutionPolicyDocumentFn,
365
454
  getRole: async (roleName) => {
366
455
  try {
367
456
  const request = new ram.GetRoleRequest({
@@ -380,7 +469,7 @@ const buildExecutionPolicy = (customStatements) => {
380
469
  updateDate: response.body.role.updateDate,
381
470
  maxSessionDuration: response.body.role.maxSessionDuration,
382
471
  assumeRolePolicyDocument: response.body.role.assumeRolePolicyDocument,
383
- policyName: `${roleName}-policy`,
472
+ policyName: (0, nameBuilder_1.buildRolePolicyName)(roleName),
384
473
  };
385
474
  }
386
475
  catch (error) {
@@ -394,7 +483,7 @@ const buildExecutionPolicy = (customStatements) => {
394
483
  }
395
484
  },
396
485
  deleteRole: async (roleName, managedPolicies) => {
397
- const policyName = `${roleName}-policy`;
486
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
398
487
  if (managedPolicies && managedPolicies.length > 0) {
399
488
  await detachManagedPoliciesFn(roleName, managedPolicies);
400
489
  }
@@ -98,7 +98,9 @@ const getIacDefinition = (iac, rawValue) => {
98
98
  if (matchFn?.length) {
99
99
  return iac.functions?.find((fc) => fc.key === matchFn[1]);
100
100
  }
101
- return iac.functions?.find((fc) => fc.key === rawValue);
101
+ // Bare values are the function's deployed NAME, never its key — resolving by
102
+ // key here would reintroduce the issue #227 trust-policy incident.
103
+ return iac.functions?.find((fc) => fc.name === rawValue);
102
104
  };
103
105
  exports.getIacDefinition = getIacDefinition;
104
106
  /* istanbul ignore next */
@@ -3,7 +3,7 @@
3
3
  // These functions operate on raw statement arrays and never import
4
4
  // provider-specific modules — consumers supply their own map functions.
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.buildPolicyDocument = exports.parseBuiltInStatements = exports.mergePolicyStatements = void 0;
6
+ exports.buildPolicyDocument = exports.parseBuiltInStatements = exports.unionPolicyStatements = exports.mergePolicyStatements = void 0;
7
7
  /**
8
8
  * Merge built-in native statements with optional custom user statements.
9
9
  * Returns a NEW array — the input arrays are never mutated.
@@ -21,6 +21,26 @@ const mergePolicyStatements = (nativeBuiltIn, custom, mapFn) => {
21
21
  return [...nativeBuiltIn, ...mappedCustom];
22
22
  };
23
23
  exports.mergePolicyStatements = mergePolicyStatements;
24
+ /**
25
+ * Union statement lists (e.g. the derived baselines of several functions
26
+ * sharing one legacy role), deduplicating identical statements. Returns a NEW
27
+ * array — the inputs are never mutated.
28
+ */
29
+ const unionPolicyStatements = (statementLists) => {
30
+ const seen = new Set();
31
+ const merged = [];
32
+ for (const list of statementLists) {
33
+ for (const statement of list) {
34
+ const fingerprint = JSON.stringify(statement);
35
+ if (seen.has(fingerprint))
36
+ continue;
37
+ seen.add(fingerprint);
38
+ merged.push(statement);
39
+ }
40
+ }
41
+ return merged;
42
+ };
43
+ exports.unionPolicyStatements = unionPolicyStatements;
24
44
  /**
25
45
  * Parse a provider's built-in policy JSON string into its raw Statement array.
26
46
  * Returns an empty array when the JSON is invalid or has no Statement field.
@@ -16,7 +16,7 @@
16
16
  * deploy set are additionally rejected up-front by semantic validation.
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
19
+ exports.buildRolePolicyName = exports.buildFunctionRoleName = exports.CONSTRAINT_NAME_LIMITS = exports.buildConstrainedName = exports.stableHash = exports.DEFAULT_HASH_LENGTH = void 0;
20
20
  const FNV_OFFSET_BASIS = 0x811c9dc5;
21
21
  const FNV_PRIME = 0x01000193;
22
22
  const SANITISERS = {
@@ -77,4 +77,15 @@ exports.CONSTRAINT_NAME_LIMITS = {
77
77
  ALIYUN_CREATE_API_NAME: 50,
78
78
  ALIYUN_API_GROUP_NAME: 50,
79
79
  VOLCENGINE_ROUTE_NAME: 63,
80
+ FUNCTION_ROLE_NAME: 64,
80
81
  };
82
+ /** Single source of truth for per-function execution role names across all providers. */
83
+ const buildFunctionRoleName = (serviceName, stage, fnKey) => (0, exports.buildConstrainedName)({
84
+ parts: [serviceName, stage, fnKey, 'role'],
85
+ maxLength: exports.CONSTRAINT_NAME_LIMITS.FUNCTION_ROLE_NAME,
86
+ charset: 'hyphen',
87
+ });
88
+ exports.buildFunctionRoleName = buildFunctionRoleName;
89
+ /** Single source of truth for the execution policy name attached to a role. */
90
+ const buildRolePolicyName = (roleName) => `${roleName}-policy`;
91
+ exports.buildRolePolicyName = buildRolePolicyName;
@@ -84,12 +84,11 @@ const createRemoteStateBackend = (adapter, config) => {
84
84
  app,
85
85
  service,
86
86
  stages: {},
87
- resources: {},
88
87
  };
89
88
  try {
90
89
  const raw = await adapter.read(config.key);
91
90
  if (raw)
92
- existing = raw;
91
+ existing = (0, stateManager_1.toPersistedState)(raw);
93
92
  }
94
93
  catch {
95
94
  // noop
@@ -107,7 +106,6 @@ const createRemoteStateBackend = (adapter, config) => {
107
106
  shared: state.stages?.[stage]?.shared ?? existing.stages?.[stage]?.shared ?? {},
108
107
  },
109
108
  },
110
- resources: state.resources,
111
109
  };
112
110
  await adapter.write(config.key, stateToSave);
113
111
  },
@@ -98,9 +98,19 @@ const createSaasStateBackend = (context) => {
98
98
  await ensureProvisioned(provider, stage);
99
99
  try {
100
100
  const state = await client.get(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/current?stage=${encodeURIComponent(stage)}`);
101
+ const migrated = (0, stateManager_1.migrateState)(state.stateJson);
102
+ // Legacy Console states hold fresh resources only in the top-level
103
+ // field (pre-stage-syncing saves) — prefer the stage store, fall back.
104
+ const stageResources = migrated.stages?.[stage]?.resources;
105
+ const resources = stageResources && Object.keys(stageResources).length > 0
106
+ ? stageResources
107
+ : migrated.resources && Object.keys(migrated.resources).length > 0
108
+ ? migrated.resources
109
+ : {};
101
110
  // Attach console metadata so subsequent deploys have the UUIDs
102
111
  return {
103
- ...(0, stateManager_1.migrateState)(state.stateJson),
112
+ ...migrated,
113
+ resources,
104
114
  orgId,
105
115
  appId: resolvedAppId,
106
116
  serviceId: resolvedServiceId,
@@ -119,15 +129,26 @@ const createSaasStateBackend = (context) => {
119
129
  saveState: async (state, app, service, stage) => {
120
130
  // If not provisioned yet, use the state's provider for provisioning
121
131
  await ensureProvisioned(state.provider, stage);
122
- // The backend persists the full state file under state_json — send the whole
123
- // StateFile (not just resources) so loadState round-trips it unchanged.
132
+ // Sync the runtime projection into the stage store before stripping, so
133
+ // stages[stage].resources carries the fresh working set (mirrors the fs
134
+ // and remote backends' save contract)
135
+ const stateJson = (0, stateManager_1.toPersistedState)({
136
+ ...state,
137
+ stages: {
138
+ ...state.stages,
139
+ [stage]: {
140
+ ...state.stages?.[stage],
141
+ resources: state.resources,
142
+ },
143
+ },
144
+ });
124
145
  const body = {
125
146
  appName: app,
126
147
  serviceName: service,
127
148
  provider: state.provider,
128
149
  stage,
129
- stateJson: state,
130
- contentHash: node_crypto_1.default.createHash('sha256').update(JSON.stringify(state)).digest('hex'),
150
+ stateJson,
151
+ contentHash: node_crypto_1.default.createHash('sha256').update(JSON.stringify(stateJson)).digest('hex'),
131
152
  resourceCount: Object.keys(state.resources).length,
132
153
  };
133
154
  await client.post(`/api/v1/apps/${resolvedAppId}/services/${resolvedServiceId}/state/sync`, body);
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getRoleArnFromState = exports.removeSharedResource = exports.setSharedResource = exports.getSharedResource = exports.getAllSharedResources = exports.getAllResources = exports.removeResource = exports.setResource = exports.getResource = exports.saveStateWithLock = exports.saveState = exports.loadState = exports.migrateState = exports.clearStateMigrations = exports.registerStateMigration = exports.ensureStateDir = exports.getStatePath = void 0;
6
+ exports.getRoleArnFromState = exports.removeSharedResource = exports.setSharedResource = exports.getSharedResource = exports.getAllSharedResources = exports.getAllResources = exports.removeResource = exports.setResource = exports.getResource = exports.saveStateWithLock = exports.saveState = exports.loadState = exports.toPersistedState = exports.migrateState = exports.clearStateMigrations = exports.registerStateMigration = exports.ensureStateDir = exports.getStatePath = void 0;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const node_crypto_1 = __importDefault(require("node:crypto"));
@@ -90,6 +90,12 @@ const migrateState = (raw) => {
90
90
  return migrated;
91
91
  };
92
92
  exports.migrateState = migrateState;
93
+ /** Strip the runtime-only `resources` projection — `stages` is the authoritative store (issue #225). */
94
+ const toPersistedState = (state) => {
95
+ const { resources: _projection, ...persisted } = state;
96
+ return persisted;
97
+ };
98
+ exports.toPersistedState = toPersistedState;
93
99
  /**
94
100
  * Load state file, scoped to the given stage.
95
101
  * The returned StateFile has `resources` populated from `stages[stage].resources`.
@@ -150,12 +156,11 @@ const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
150
156
  app,
151
157
  service,
152
158
  stages: {},
153
- resources: {},
154
159
  };
155
160
  try {
156
161
  if (node_fs_1.default.existsSync(statePath)) {
157
162
  const content = node_fs_1.default.readFileSync(statePath, 'utf-8');
158
- existing = JSON.parse(content);
163
+ existing = (0, exports.toPersistedState)(JSON.parse(content));
159
164
  }
160
165
  }
161
166
  catch {
@@ -177,7 +182,6 @@ const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
177
182
  shared: state.stages?.[stage]?.shared ?? existing.stages?.[stage]?.shared ?? {},
178
183
  },
179
184
  },
180
- resources: state.resources,
181
185
  };
182
186
  // Atomic write: back up the previous state, then write tmp + fsync + rename
183
187
  try {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createCamOperations = void 0;
4
4
  const iamStatements_1 = require("../iamStatements");
5
+ const nameBuilder_1 = require("../nameBuilder");
5
6
  const logger_1 = require("../logger");
6
7
  const lang_1 = require("../../lang");
7
8
  // SCF built-in execution policy (same idea as Aliyun's FC_EXECUTION_POLICY)
@@ -37,8 +38,9 @@ const mapToCamStatement = (stmt) => {
37
38
  }
38
39
  return result;
39
40
  };
40
- const buildExecutionPolicy = (customStatements) => {
41
- const merged = (0, iamStatements_1.mergePolicyStatements)(SCF_EXECUTION_STATEMENTS, customStatements, mapToCamStatement);
41
+ const buildExecutionPolicy = (customStatements, executionStatements) => {
42
+ const baseline = executionStatements?.map(mapToCamStatement) ?? SCF_EXECUTION_STATEMENTS;
43
+ const merged = (0, iamStatements_1.mergePolicyStatements)(baseline, customStatements, mapToCamStatement);
42
44
  return (0, iamStatements_1.buildPolicyDocument)(merged, { version: '2.0' });
43
45
  };
44
46
  const buildAssumeRolePolicy = (trustedServices) => JSON.stringify({
@@ -104,7 +106,17 @@ const createCamOperations = (camClient) => {
104
106
  }
105
107
  };
106
108
  return {
107
- createRole: async (roleName, trustedServices, description, customStatements, managedPolicies) => {
109
+ getOwnerUin: async () => {
110
+ try {
111
+ const response = await camClient.GetUserAppId(undefined);
112
+ return response.OwnerUin ?? response.Uin ?? undefined;
113
+ }
114
+ catch (error) {
115
+ logger_1.logger.warn(lang_1.lang.__('TENCENT_UIN_FETCH_FAILED', { error: String(error) }));
116
+ return undefined;
117
+ }
118
+ },
119
+ createRole: async (roleName, trustedServices, description, customStatements, managedPolicies, executionStatements) => {
108
120
  const assumeRolePolicy = buildAssumeRolePolicy(trustedServices);
109
121
  try {
110
122
  const response = await camClient.CreateRole({
@@ -129,11 +141,11 @@ const createCamOperations = (camClient) => {
129
141
  roleArn,
130
142
  };
131
143
  // Attach inline policy with built-in + custom statements
132
- const policyName = `${roleName}-policy`;
144
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
133
145
  try {
134
146
  await camClient.CreatePolicy({
135
147
  PolicyName: policyName,
136
- PolicyDocument: buildExecutionPolicy(customStatements),
148
+ PolicyDocument: buildExecutionPolicy(customStatements, executionStatements),
137
149
  Description: `SCF execution policy for ${roleName}`,
138
150
  });
139
151
  await attachPolicy(roleName, policyName);
@@ -170,12 +182,12 @@ const createCamOperations = (camClient) => {
170
182
  try {
171
183
  const getResponse = await camClient.GetRole({ RoleName: roleName });
172
184
  const roleData = getResponse.RoleInfo;
173
- const policyName = `${roleName}-policy`;
185
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
174
186
  // Re-attach built-in policy (idempotent)
175
187
  try {
176
188
  await camClient.CreatePolicy({
177
189
  PolicyName: policyName,
178
- PolicyDocument: buildExecutionPolicy(customStatements),
190
+ PolicyDocument: buildExecutionPolicy(customStatements, executionStatements),
179
191
  Description: `SCF execution policy for ${roleName}`,
180
192
  });
181
193
  await attachPolicy(roleName, policyName);
@@ -219,7 +231,7 @@ const createCamOperations = (camClient) => {
219
231
  roleId: roleData.RoleId,
220
232
  roleArn: roleData.RoleArn,
221
233
  description: roleData.Description,
222
- policyName: `${roleName}-policy`,
234
+ policyName: (0, nameBuilder_1.buildRolePolicyName)(roleName),
223
235
  };
224
236
  }
225
237
  catch (error) {
@@ -232,7 +244,7 @@ const createCamOperations = (camClient) => {
232
244
  }
233
245
  },
234
246
  deleteRole: async (roleName, managedPolicies) => {
235
- const policyName = `${roleName}-policy`;
247
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
236
248
  // Detach managed policies first (don't delete them)
237
249
  if (managedPolicies && managedPolicies.length > 0) {
238
250
  for (const policyArn of managedPolicies) {
@@ -256,8 +268,8 @@ const createCamOperations = (camClient) => {
256
268
  throw error;
257
269
  }
258
270
  },
259
- updateRolePolicy: async (roleName, customStatements) => {
260
- const policyName = `${roleName}-policy`;
271
+ updateRolePolicy: async (roleName, customStatements, executionStatements) => {
272
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
261
273
  // Detach + delete old
262
274
  await detachPolicy(roleName, policyName);
263
275
  await deletePolicyByName(camClient, policyName);
@@ -265,7 +277,7 @@ const createCamOperations = (camClient) => {
265
277
  try {
266
278
  await camClient.CreatePolicy({
267
279
  PolicyName: policyName,
268
- PolicyDocument: buildExecutionPolicy(customStatements),
280
+ PolicyDocument: buildExecutionPolicy(customStatements, executionStatements),
269
281
  Description: `SCF execution policy for ${roleName}`,
270
282
  });
271
283
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createIamOperations = void 0;
4
4
  const iamStatements_1 = require("../iamStatements");
5
+ const nameBuilder_1 = require("../nameBuilder");
5
6
  const logger_1 = require("../logger");
6
7
  const lang_1 = require("../../lang");
7
8
  const DEFAULT_TRUST_POLICY_SERVICES = ['vefaas'];
@@ -54,8 +55,11 @@ const mapToVolcengineStatement = (stmt) => {
54
55
  }
55
56
  return result;
56
57
  };
57
- const buildExecutionPolicy = (customStatements) => {
58
- const merged = (0, iamStatements_1.mergePolicyStatements)(VEFAAS_EXECUTION_STATEMENTS, customStatements, mapToVolcengineStatement);
58
+ const buildExecutionPolicy = (baseline, customStatements) => {
59
+ const nativeBaseline = baseline
60
+ ? baseline.map(mapToVolcengineStatement)
61
+ : VEFAAS_EXECUTION_STATEMENTS;
62
+ const merged = (0, iamStatements_1.mergePolicyStatements)(nativeBaseline, customStatements, mapToVolcengineStatement);
59
63
  return (0, iamStatements_1.buildPolicyDocument)(merged);
60
64
  };
61
65
  // TagResources expects flat numbered query params (ResourceIds.1, Tags.1.Key, ...).
@@ -69,8 +73,8 @@ const buildTagResourceQuery = (roleName, tags) => {
69
73
  }, { ResourceType: 'role', 'ResourceIds.1': roleName });
70
74
  };
71
75
  const createIamOperations = (iamClient) => {
72
- const createAndAttachPolicy = async (roleName, customStatements) => {
73
- const policyName = `${roleName}-policy`;
76
+ const createAndAttachPolicy = async (roleName, baseline, customStatements) => {
77
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
74
78
  try {
75
79
  await iamClient.fetchOpenAPI({
76
80
  Action: 'CreatePolicy',
@@ -79,7 +83,7 @@ const createIamOperations = (iamClient) => {
79
83
  headers: { 'content-type': 'application/json' },
80
84
  query: {
81
85
  PolicyName: policyName,
82
- PolicyDocument: buildExecutionPolicy(customStatements),
86
+ PolicyDocument: buildExecutionPolicy(baseline, customStatements),
83
87
  Description: `veFaaS execution policy for ${roleName}`,
84
88
  },
85
89
  });
@@ -136,7 +140,7 @@ const createIamOperations = (iamClient) => {
136
140
  return policyName;
137
141
  };
138
142
  const detachAndDeletePolicy = async (roleName) => {
139
- const policyName = `${roleName}-policy`;
143
+ const policyName = (0, nameBuilder_1.buildRolePolicyName)(roleName);
140
144
  try {
141
145
  await iamClient.fetchOpenAPI({
142
146
  Action: 'DetachRolePolicy',
@@ -261,7 +265,7 @@ const createIamOperations = (iamClient) => {
261
265
  });
262
266
  const data = (response.Result || {});
263
267
  const roleData = (data.Role || {});
264
- const policyName = await createAndAttachPolicy(roleName, customStatements);
268
+ const policyName = await createAndAttachPolicy(roleName, config.executionStatements, customStatements);
265
269
  if (config.managedPolicies && config.managedPolicies.length > 0) {
266
270
  for (const policyArn of config.managedPolicies) {
267
271
  await attachRolePolicyImpl(roleName, policyArn, 'System');
@@ -302,7 +306,7 @@ const createIamOperations = (iamClient) => {
302
306
  TrustPolicyDocument: trustPolicyDocument,
303
307
  },
304
308
  });
305
- const policyName = await createAndAttachPolicy(roleName);
309
+ const policyName = await createAndAttachPolicy(roleName, config.executionStatements, config.customStatements);
306
310
  if (config.managedPolicies && config.managedPolicies.length > 0) {
307
311
  for (const policyArn of config.managedPolicies) {
308
312
  await attachRolePolicyImpl(roleName, policyArn, 'System');
@@ -355,7 +359,7 @@ const createIamOperations = (iamClient) => {
355
359
  createdTime: roleData.CreateTime,
356
360
  maxSessionDuration: roleData.MaxSessionDuration,
357
361
  trustPolicyDocument: roleData.TrustPolicyDocument,
358
- policyName: `${roleName}-policy`,
362
+ policyName: (0, nameBuilder_1.buildRolePolicyName)(roleName),
359
363
  };
360
364
  }
361
365
  catch (error) {
@@ -425,9 +429,9 @@ const createIamOperations = (iamClient) => {
425
429
  detachRolePolicy: async (roleName, policyName) => {
426
430
  await detachRolePolicyImpl(roleName, policyName);
427
431
  },
428
- updateRolePolicy: async (roleName, customStatements) => {
432
+ updateRolePolicy: async (roleName, baseline, customStatements) => {
429
433
  await detachAndDeletePolicy(roleName);
430
- await createAndAttachPolicy(roleName, customStatements);
434
+ await createAndAttachPolicy(roleName, baseline, customStatements);
431
435
  logger_1.logger.info(lang_1.lang.__('IAM_ROLE_POLICY_UPDATED', { roleName }));
432
436
  },
433
437
  listAttachedRolePolicies: async (roleName) => {
@@ -413,6 +413,10 @@ exports.en = {
413
413
  SEMANTIC_DUPLICATE_GENERATED_API_NAME: 'Generated API Gateway apiName "{{apiName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
414
414
  SEMANTIC_DUPLICATE_ROUTE_NAME: 'Generated API Gateway route name "{{routeName}}" collides between "{{firstPath}}" and "{{secondPath}}" in this deployment; shorten the event name or differentiate trigger method/path',
415
415
  SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: 'Trigger backend "{{reference}}" in event "{{eventKey}}" does not match any function definition in the configuration',
416
+ SEMANTIC_BACKEND_BARE_KEY: 'Trigger backend "{{backend}}" in event "{{eventKey}}" matches function key "{{key}}", but bare backend values must be deployed function names. For template functions use the reference form "${functions.{{key}}}"',
417
+ SEMANTIC_BACKEND_BARE_NAME: 'Trigger backend "{{backend}}" in event "{{eventKey}}" resolves to template function "{{key}}" by name; prefer the reference form "${functions.{{key}}}"',
418
+ EXTERNAL_FUNCTION_NOT_FOUND_VOLCENGINE: 'Backend "{{backendRef}}" is not defined in this template and no deployed veFaaS function with that name exists in the provider. External backends must exist in the same account and region',
419
+ EXTERNAL_FUNCTION_BACKEND: 'Backend "{{backendRef}}" is not defined in this template; treating it as an external deployed function name',
416
420
  // Show command messages
417
421
  LOADING_STATE_FOR: 'Loading state for app: {{app}}, service: {{service}}, stage: {{stage}}...',
418
422
  NO_RESOURCES_FOUND: 'No resources found in state.',
@@ -492,6 +496,8 @@ exports.en = {
492
496
  RAM_ROLE_DRIFT_RECOVERY_FAILED: 'Failed to recover from RAM role state drift for "{{roleName}}": {{error}}. ' +
493
497
  'The role existed in the cloud but recovery operations failed. ' +
494
498
  'To fix: manually verify the role in the cloud console, remove it from state, and redeploy.',
499
+ RAM_POLICY_VERSION_PRUNE_FAILED: 'Failed to prune old policy versions for "{{policyName}}": {{error}}. ' +
500
+ 'The policy may exceed the version limit on the next update.',
495
501
  // Certificate messages
496
502
  CERT_INVALID_CONFIGURATION: 'Certificate "{{name}}" must have either (certificate_body + private_key) or certificate_id, but not both',
497
503
  CERT_FILE_NOT_FOUND: 'Certificate file not found: {{filePath}}',
@@ -648,6 +654,7 @@ exports.en = {
648
654
  TENCENT_CAM_ROLE_DELETED: 'Tencent CAM role {{roleName}} deleted',
649
655
  TENCENT_CAM_ROLE_NOT_FOUND: 'Tencent CAM role {{roleName}} not found in cloud provider',
650
656
  TENCENT_CAM_ROLE_ALREADY_EXISTS: 'Tencent CAM role {{roleName}} already exists',
657
+ TENCENT_UIN_FETCH_FAILED: 'Failed to fetch the Tencent UIN; function invoke permissions fall back to a wildcard resource: {{error}}',
651
658
  TENCENT_CAM_ROLE_DRIFT_RECOVERY_FAILED: 'Tencent CAM role drift recovery failed for {{roleName}}: {{error}}',
652
659
  TENCENT_CAM_POLICY_ALREADY_ATTACHED: 'Policy already attached to CAM role {{roleName}}',
653
660
  TENCENT_CAM_POLICY_ALREADY_EXISTS: 'Tencent CAM policy already exists',
@@ -410,6 +410,10 @@ exports.zhCN = {
410
410
  SEMANTIC_DUPLICATE_GENERATED_API_NAME: '生成的 API Gateway apiName "{{apiName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
411
411
  SEMANTIC_DUPLICATE_ROUTE_NAME: '生成的 API Gateway route name "{{routeName}}" 在 "{{firstPath}}" 与 "{{secondPath}}" 之间发生冲突;请缩短事件名称或区分触发器的 method/path',
412
412
  SEMANTIC_UNRESOLVED_FUNCTION_BACKEND: '事件 "{{eventKey}}" 的触发器后端 "{{reference}}" 未匹配到配置中的任何函数定义',
413
+ SEMANTIC_BACKEND_BARE_KEY: '事件 "{{eventKey}}" 的触发器后端 "{{backend}}" 匹配的是函数 key "{{key}}",但裸值必须是已部署函数名。模板函数请使用引用形式 "${functions.{{key}}}"',
414
+ SEMANTIC_BACKEND_BARE_NAME: '事件 "{{eventKey}}" 的触发器后端 "{{backend}}" 按名称解析为模板函数 "{{key}}",建议使用引用形式 "${functions.{{key}}}"',
415
+ EXTERNAL_FUNCTION_NOT_FOUND_VOLCENGINE: '后端 "{{backendRef}}" 未在本模板中定义,且提供商中不存在同名已部署 veFaaS 函数。外部后端必须位于同一账号和区域',
416
+ EXTERNAL_FUNCTION_BACKEND: '后端 "{{backendRef}}" 未在当前模板中定义,将按外部已部署函数名处理',
413
417
  // Show command messages
414
418
  LOADING_STATE_FOR: '正在加载应用 {{app}}、服务 {{service}}、阶段 {{stage}} 的状态...',
415
419
  NO_RESOURCES_FOUND: '状态中未找到资源。',
@@ -488,6 +492,7 @@ exports.zhCN = {
488
492
  RAM_ROLE_DRIFT_RECOVERY_FAILED: 'RAM 角色 "{{roleName}}" 状态漂移恢复失败:{{error}}。' +
489
493
  '角色在云端存在但恢复操作失败。' +
490
494
  '修复方法:在云控制台手动确认角色状态,从状态中移除该角色并重新部署。',
495
+ RAM_POLICY_VERSION_PRUNE_FAILED: '策略 "{{policyName}}" 旧版本清理失败:{{error}}。' + '下次更新时策略版本数可能超出上限。',
491
496
  // 证书消息
492
497
  CERT_INVALID_CONFIGURATION: '证书 "{{name}}" 必须具有 (certificate_body + private_key) 或 certificate_id,但不能同时存在',
493
498
  CERT_FILE_NOT_FOUND: '未找到证书文件: {{filePath}}',
@@ -642,6 +647,7 @@ exports.zhCN = {
642
647
  TENCENT_CAM_ROLE_DELETED: '腾讯云 CAM 角色 {{roleName}} 删除成功',
643
648
  TENCENT_CAM_ROLE_NOT_FOUND: '腾讯云 CAM 角色 {{roleName}} 在云服务商中未找到',
644
649
  TENCENT_CAM_ROLE_ALREADY_EXISTS: '腾讯云 CAM 角色 {{roleName}} 已存在',
650
+ TENCENT_UIN_FETCH_FAILED: '获取腾讯云 UIN 失败,函数调用权限将回退为资源通配: {{error}}',
645
651
  TENCENT_CAM_ROLE_DRIFT_RECOVERY_FAILED: '腾讯云 CAM 角色 {{roleName}} 状态漂移恢复失败:{{error}}',
646
652
  TENCENT_CAM_POLICY_ALREADY_ATTACHED: 'CAM 角色 {{roleName}} 已附加该策略',
647
653
  TENCENT_CAM_POLICY_ALREADY_EXISTS: '腾讯云 CAM 策略已存在',