@geek-fun/serverlessinsight 0.7.6 → 0.7.8

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 (35) hide show
  1. package/README.md +155 -409
  2. package/dist/package.json +2 -1
  3. package/dist/src/common/aliyunClient/ossOperations.js +41 -0
  4. package/dist/src/common/aliyunClient/ramOperations.js +161 -7
  5. package/dist/src/common/iamStatements.js +48 -0
  6. package/dist/src/common/tencentClient/camOperations.js +317 -0
  7. package/dist/src/common/tencentClient/cosOperations.js +67 -0
  8. package/dist/src/common/tencentClient/index.js +18 -0
  9. package/dist/src/common/tencentClient/scfOperations.js +2 -0
  10. package/dist/src/common/volcengineClient/iamOperations.js +133 -47
  11. package/dist/src/common/volcengineClient/tosOperations.js +79 -0
  12. package/dist/src/lang/en.js +24 -0
  13. package/dist/src/lang/zh-CN.js +24 -0
  14. package/dist/src/parser/bucketParser.js +31 -0
  15. package/dist/src/parser/functionParser.js +34 -0
  16. package/dist/src/stack/aliyunStack/fc3Planner.js +2 -1
  17. package/dist/src/stack/aliyunStack/fc3Resource.js +72 -14
  18. package/dist/src/stack/aliyunStack/ossResource.js +63 -0
  19. package/dist/src/stack/aliyunStack/ossTypes.js +9 -0
  20. package/dist/src/stack/localStack/aliyunFc.js +6 -1
  21. package/dist/src/stack/scfStack/cosResource.js +58 -0
  22. package/dist/src/stack/scfStack/cosTypes.js +9 -0
  23. package/dist/src/stack/scfStack/scfPlanner.js +1 -1
  24. package/dist/src/stack/scfStack/scfResource.js +195 -22
  25. package/dist/src/stack/scfStack/scfTypes.js +6 -4
  26. package/dist/src/stack/volcengineStack/tosResource.js +56 -0
  27. package/dist/src/stack/volcengineStack/tosTypes.js +9 -0
  28. package/dist/src/stack/volcengineStack/vefaasPlanner.js +2 -1
  29. package/dist/src/stack/volcengineStack/vefaasResource.js +46 -5
  30. package/dist/src/types/domains/state.js +2 -0
  31. package/dist/src/validator/bucketSchema.js +45 -0
  32. package/dist/src/validator/functionSchema.js +43 -0
  33. package/dist/tsconfig.tsbuildinfo +1 -1
  34. package/package.json +2 -1
  35. package/samples/aliyun-poc-api-cdn.yml +75 -0
@@ -772,6 +772,47 @@ const parseXmlResponse = (xml, tagName) => {
772
772
  unbindCustomDomain,
773
773
  createCnameToken,
774
774
  getBucketCnameEndpoint,
775
+ putBucketPolicy: async (bucketName, policy) => {
776
+ useBucket(bucketName);
777
+ await ossClient.putBucketPolicy(bucketName, policy);
778
+ logger_1.logger.info(lang_1.lang.__('OSS_BUCKET_POLICY_SET', { bucketName }));
779
+ },
780
+ getBucketPolicy: async (bucketName) => {
781
+ useBucket(bucketName);
782
+ try {
783
+ const result = (await ossClient.getBucketPolicy(bucketName));
784
+ return result.policy
785
+ ? typeof result.policy === 'string'
786
+ ? JSON.parse(result.policy)
787
+ : result.policy
788
+ : null;
789
+ }
790
+ catch (error) {
791
+ if (error &&
792
+ typeof error === 'object' &&
793
+ 'code' in error &&
794
+ error.code === 'NoSuchBucketPolicy') {
795
+ return null;
796
+ }
797
+ throw error;
798
+ }
799
+ },
800
+ deleteBucketPolicy: async (bucketName) => {
801
+ useBucket(bucketName);
802
+ try {
803
+ await ossClient.deleteBucketPolicy(bucketName);
804
+ logger_1.logger.info(lang_1.lang.__('OSS_BUCKET_POLICY_DELETED', { bucketName }));
805
+ }
806
+ catch (error) {
807
+ if (error &&
808
+ typeof error === 'object' &&
809
+ 'code' in error &&
810
+ error.code === 'NoSuchBucketPolicy') {
811
+ return;
812
+ }
813
+ throw error;
814
+ }
815
+ },
775
816
  };
776
817
  };
777
818
  exports.createOssOperations = createOssOperations;
@@ -37,6 +37,7 @@ exports.createRamOperations = 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
+ const iamStatements_1 = require("../iamStatements");
40
41
  const buildAssumeRolePolicy = (trustedServices) => JSON.stringify({
41
42
  Version: '1',
42
43
  Statement: [
@@ -92,14 +93,34 @@ const FC_EXECUTION_POLICY = JSON.stringify({
92
93
  },
93
94
  ],
94
95
  });
96
+ const FC_EXECUTION_STATEMENTS = (0, iamStatements_1.parseBuiltInStatements)(FC_EXECUTION_POLICY);
97
+ const extractPolicyNameFromArn = (arn) => {
98
+ const parts = arn.split('/');
99
+ return parts[parts.length - 1];
100
+ };
101
+ const mapToAliyunStatement = (stmt) => {
102
+ const result = {
103
+ Effect: stmt.effect,
104
+ Action: stmt.action,
105
+ Resource: stmt.resource,
106
+ };
107
+ if (stmt.sid) {
108
+ result.Sid = stmt.sid;
109
+ }
110
+ return result;
111
+ };
112
+ const buildExecutionPolicy = (customStatements) => {
113
+ const merged = (0, iamStatements_1.mergePolicyStatements)(FC_EXECUTION_STATEMENTS, customStatements, mapToAliyunStatement);
114
+ return (0, iamStatements_1.buildPolicyDocument)(merged, { version: '1' });
115
+ };
95
116
  /* istanbul ignore next */ const createRamOperations = (ramClient) => {
96
- const attachRolePolicyForFc = async (roleName) => {
117
+ const attachRolePolicyForFc = async (roleName, customStatements) => {
97
118
  const policyName = `${roleName}-policy`;
98
119
  // Create policy
99
120
  try {
100
121
  const createPolicyRequest = new ram.CreatePolicyRequest({
101
122
  policyName,
102
- policyDocument: FC_EXECUTION_POLICY,
123
+ policyDocument: buildExecutionPolicy(customStatements),
103
124
  description: `FC execution policy for ${roleName}`,
104
125
  });
105
126
  await ramClient.createPolicy(createPolicyRequest);
@@ -133,8 +154,69 @@ const FC_EXECUTION_POLICY = JSON.stringify({
133
154
  }
134
155
  return policyName;
135
156
  };
157
+ const attachManagedPoliciesFn = async (roleName, policies) => {
158
+ for (const policyArn of policies) {
159
+ try {
160
+ const attachRequest = new ram.AttachPolicyToRoleRequest({
161
+ policyType: 'System',
162
+ policyName: extractPolicyNameFromArn(policyArn),
163
+ roleName,
164
+ });
165
+ await ramClient.attachPolicyToRole(attachRequest);
166
+ }
167
+ catch (error) {
168
+ if (error &&
169
+ typeof error === 'object' &&
170
+ 'code' in error &&
171
+ error.code === 'EntityAlreadyExists.Role.Policy') {
172
+ // Already attached - idempotent
173
+ }
174
+ else {
175
+ throw error;
176
+ }
177
+ }
178
+ }
179
+ };
180
+ const detachManagedPoliciesFn = async (roleName, policies) => {
181
+ for (const policyArn of policies) {
182
+ try {
183
+ const detachRequest = new ram.DetachPolicyFromRoleRequest({
184
+ policyType: 'System',
185
+ policyName: extractPolicyNameFromArn(policyArn),
186
+ roleName,
187
+ });
188
+ await ramClient.detachPolicyFromRole(detachRequest);
189
+ }
190
+ catch (error) {
191
+ if (error &&
192
+ typeof error === 'object' &&
193
+ 'code' in error &&
194
+ error.code === 'EntityNotExist.Role.Policy') {
195
+ // Not attached - idempotent
196
+ }
197
+ else {
198
+ throw error;
199
+ }
200
+ }
201
+ }
202
+ };
203
+ const listAttachedRolePoliciesFn = async (roleName) => {
204
+ try {
205
+ const request = new ram.ListPoliciesForRoleRequest({ roleName });
206
+ const response = await ramClient.listPoliciesForRole(request);
207
+ if (!response?.body?.policies?.policy) {
208
+ return [];
209
+ }
210
+ return response.body.policies.policy
211
+ .filter((p) => p.policyType === 'System')
212
+ .map((p) => p.policyName ?? '');
213
+ }
214
+ catch {
215
+ return [];
216
+ }
217
+ };
136
218
  return {
137
- createRole: async (roleName, trustedServices, description) => {
219
+ createRole: async (roleName, trustedServices, description, customStatements, managedPolicies) => {
138
220
  const assumeRolePolicy = buildAssumeRolePolicy(trustedServices);
139
221
  try {
140
222
  const request = new ram.CreateRoleRequest({
@@ -153,8 +235,11 @@ const FC_EXECUTION_POLICY = JSON.stringify({
153
235
  maxSessionDuration: response.body?.role?.maxSessionDuration,
154
236
  assumeRolePolicyDocument: assumeRolePolicy,
155
237
  };
156
- const policyName = await attachRolePolicyForFc(roleName);
157
- return { ...roleInfo, policyName };
238
+ const policyName = await attachRolePolicyForFc(roleName, customStatements);
239
+ if (managedPolicies && managedPolicies.length > 0) {
240
+ await attachManagedPoliciesFn(roleName, managedPolicies);
241
+ }
242
+ return { ...roleInfo, policyName, managedPolicies };
158
243
  }
159
244
  catch (error) {
160
245
  if (error &&
@@ -170,7 +255,10 @@ const FC_EXECUTION_POLICY = JSON.stringify({
170
255
  newAssumeRolePolicyDocument: assumeRolePolicy,
171
256
  });
172
257
  await ramClient.updateRole(updateRequest);
173
- const policyName = await attachRolePolicyForFc(roleName);
258
+ const policyName = await attachRolePolicyForFc(roleName, customStatements);
259
+ if (managedPolicies && managedPolicies.length > 0) {
260
+ await attachManagedPoliciesFn(roleName, managedPolicies);
261
+ }
174
262
  return {
175
263
  roleName,
176
264
  roleId: getResponse.body?.role?.roleId,
@@ -181,6 +269,7 @@ const FC_EXECUTION_POLICY = JSON.stringify({
181
269
  maxSessionDuration: getResponse.body?.role?.maxSessionDuration,
182
270
  assumeRolePolicyDocument: assumeRolePolicy,
183
271
  policyName,
272
+ managedPolicies,
184
273
  };
185
274
  }
186
275
  catch (recoveryError) {
@@ -228,6 +317,51 @@ const FC_EXECUTION_POLICY = JSON.stringify({
228
317
  throw error;
229
318
  }
230
319
  },
320
+ updateRolePolicy: async (roleName, customStatements) => {
321
+ const policyName = `${roleName}-policy`;
322
+ try {
323
+ await ramClient.detachPolicyFromRole(new ram.DetachPolicyFromRoleRequest({ policyType: 'Custom', policyName, roleName }));
324
+ }
325
+ catch {
326
+ /* idempotent */
327
+ }
328
+ try {
329
+ await ramClient.deletePolicy(new ram.DeletePolicyRequest({ policyName }));
330
+ }
331
+ catch {
332
+ /* idempotent */
333
+ }
334
+ try {
335
+ await ramClient.createPolicy(new ram.CreatePolicyRequest({
336
+ policyName,
337
+ policyDocument: buildExecutionPolicy(customStatements),
338
+ description: `FC execution policy for ${roleName}`,
339
+ }));
340
+ }
341
+ catch (error) {
342
+ if (error &&
343
+ typeof error === 'object' &&
344
+ 'code' in error &&
345
+ error.code === 'EntityAlreadyExists.Policy') {
346
+ /* idempotent */
347
+ }
348
+ else
349
+ throw error;
350
+ }
351
+ try {
352
+ await ramClient.attachPolicyToRole(new ram.AttachPolicyToRoleRequest({ policyType: 'Custom', policyName, roleName }));
353
+ }
354
+ catch (error) {
355
+ if (error &&
356
+ typeof error === 'object' &&
357
+ 'code' in error &&
358
+ error.code === 'EntityAlreadyExists.Role.Policy') {
359
+ /* idempotent */
360
+ }
361
+ else
362
+ throw error;
363
+ }
364
+ },
231
365
  getRole: async (roleName) => {
232
366
  try {
233
367
  const request = new ram.GetRoleRequest({
@@ -259,8 +393,11 @@ const FC_EXECUTION_POLICY = JSON.stringify({
259
393
  throw error;
260
394
  }
261
395
  },
262
- deleteRole: async (roleName) => {
396
+ deleteRole: async (roleName, managedPolicies) => {
263
397
  const policyName = `${roleName}-policy`;
398
+ if (managedPolicies && managedPolicies.length > 0) {
399
+ await detachManagedPoliciesFn(roleName, managedPolicies);
400
+ }
264
401
  // Detach policy from role
265
402
  try {
266
403
  const detachRequest = new ram.DetachPolicyFromRoleRequest({
@@ -289,6 +426,23 @@ const FC_EXECUTION_POLICY = JSON.stringify({
289
426
  });
290
427
  await ramClient.deleteRole(request);
291
428
  },
429
+ attachManagedPolicies: attachManagedPoliciesFn,
430
+ detachManagedPolicies: detachManagedPoliciesFn,
431
+ listAttachedRolePolicies: listAttachedRolePoliciesFn,
432
+ updateManagedPolicies: async (roleName, desiredPolicies) => {
433
+ const desiredNames = desiredPolicies.map(extractPolicyNameFromArn);
434
+ const currentNames = await listAttachedRolePoliciesFn(roleName);
435
+ const currentSet = new Set(currentNames);
436
+ const desiredSet = new Set(desiredNames);
437
+ const toAttach = desiredPolicies.filter((p) => !currentSet.has(extractPolicyNameFromArn(p)));
438
+ const toDetach = currentNames.filter((n) => !desiredSet.has(n));
439
+ if (toAttach.length > 0) {
440
+ await attachManagedPoliciesFn(roleName, toAttach);
441
+ }
442
+ if (toDetach.length > 0) {
443
+ await detachManagedPoliciesFn(roleName, toDetach);
444
+ }
445
+ },
292
446
  };
293
447
  };
294
448
  exports.createRamOperations = createRamOperations;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ // Provider-agnostic IAM policy statement merge helpers.
3
+ // These functions operate on raw statement arrays and never import
4
+ // provider-specific modules — consumers supply their own map functions.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.buildPolicyDocument = exports.parseBuiltInStatements = exports.mergePolicyStatements = void 0;
7
+ /**
8
+ * Merge built-in native statements with optional custom user statements.
9
+ * Returns a NEW array — the input arrays are never mutated.
10
+ *
11
+ * @param nativeBuiltIn - The parsed Statement[] from the provider's built-in policy JSON.
12
+ * @param custom - Optional user custom statements in provider-agnostic format.
13
+ * @param mapFn - Converts an IamStatement into the native statement shape for the specific provider.
14
+ * @returns A new array with built-in statements first, then mapped custom statements.
15
+ */
16
+ const mergePolicyStatements = (nativeBuiltIn, custom, mapFn) => {
17
+ if (!custom || custom.length === 0) {
18
+ return nativeBuiltIn;
19
+ }
20
+ const mappedCustom = custom.map(mapFn);
21
+ return [...nativeBuiltIn, ...mappedCustom];
22
+ };
23
+ exports.mergePolicyStatements = mergePolicyStatements;
24
+ /**
25
+ * Parse a provider's built-in policy JSON string into its raw Statement array.
26
+ * Returns an empty array when the JSON is invalid or has no Statement field.
27
+ */
28
+ const parseBuiltInStatements = (policyJson) => {
29
+ const parsed = JSON.parse(policyJson);
30
+ const statement = parsed.Statement;
31
+ return Array.isArray(statement) ? statement : [];
32
+ };
33
+ exports.parseBuiltInStatements = parseBuiltInStatements;
34
+ /**
35
+ * Build a complete policy document JSON string from an array of statements.
36
+ *
37
+ * @param statements - The policy statements to include.
38
+ * @param providerOptions - Optional per-provider options such as version.
39
+ * @returns A JSON-stringified policy document.
40
+ */
41
+ const buildPolicyDocument = (statements, providerOptions) => {
42
+ const doc = { Statement: statements };
43
+ if (providerOptions?.version) {
44
+ doc.Version = providerOptions.version;
45
+ }
46
+ return JSON.stringify(doc);
47
+ };
48
+ exports.buildPolicyDocument = buildPolicyDocument;
@@ -0,0 +1,317 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCamOperations = void 0;
4
+ const iamStatements_1 = require("../iamStatements");
5
+ const logger_1 = require("../logger");
6
+ const lang_1 = require("../../lang");
7
+ // SCF built-in execution policy (same idea as Aliyun's FC_EXECUTION_POLICY)
8
+ const SCF_EXECUTION_POLICY = JSON.stringify({
9
+ Version: '2.0',
10
+ Statement: [
11
+ {
12
+ Effect: 'Allow',
13
+ Action: ['scf:InvokeFunction'],
14
+ Resource: '*',
15
+ },
16
+ {
17
+ Effect: 'Allow',
18
+ Action: ['cls:logset:putlog', 'cls:logset:create*', 'cls:logset:get*'],
19
+ Resource: '*',
20
+ },
21
+ {
22
+ Effect: 'Allow',
23
+ Action: ['cos:GetObject', 'cos:PutObject', 'cos:DeleteObject', 'cos:ListBucket'],
24
+ Resource: '*',
25
+ },
26
+ ],
27
+ });
28
+ const SCF_EXECUTION_STATEMENTS = (0, iamStatements_1.parseBuiltInStatements)(SCF_EXECUTION_POLICY);
29
+ const mapToCamStatement = (stmt) => {
30
+ const result = {
31
+ Effect: stmt.effect,
32
+ Action: stmt.action,
33
+ Resource: stmt.resource,
34
+ };
35
+ if (stmt.sid) {
36
+ result.Sid = stmt.sid;
37
+ }
38
+ return result;
39
+ };
40
+ const buildExecutionPolicy = (customStatements) => {
41
+ const merged = (0, iamStatements_1.mergePolicyStatements)(SCF_EXECUTION_STATEMENTS, customStatements, mapToCamStatement);
42
+ return (0, iamStatements_1.buildPolicyDocument)(merged, { version: '2.0' });
43
+ };
44
+ const buildAssumeRolePolicy = (trustedServices) => JSON.stringify({
45
+ Version: '2.0',
46
+ Statement: [
47
+ {
48
+ Effect: 'Allow',
49
+ Action: ['sts:AssumeRole'],
50
+ Principal: {
51
+ Service: trustedServices,
52
+ },
53
+ },
54
+ ],
55
+ });
56
+ // Try to delete a policy by name. Tencent CAM DeletePolicy requires a numeric
57
+ // PolicyId, so we first list policies to find the ID by name.
58
+ const deletePolicyByName = async (camClient, policyName) => {
59
+ try {
60
+ const listResp = await camClient.ListPolicies({ Keyword: policyName, Scope: 'Local' });
61
+ const found = listResp.List?.find((p) => p.PolicyName === policyName);
62
+ if (found?.PolicyId) {
63
+ await camClient.DeletePolicy({ PolicyId: [found.PolicyId] });
64
+ }
65
+ }
66
+ catch {
67
+ // Idempotent cleanup - best effort
68
+ }
69
+ };
70
+ const createCamOperations = (camClient) => {
71
+ const attachPolicy = async (roleName, policyName) => {
72
+ try {
73
+ await camClient.AttachRolePolicy({
74
+ PolicyName: policyName,
75
+ AttachRoleName: roleName,
76
+ });
77
+ }
78
+ catch (error) {
79
+ if (error && typeof error === 'object' && 'code' in error) {
80
+ const code = String(error.code);
81
+ if (code === 'InvalidParameter.AttachmentRoleAlreadyExist') {
82
+ return; // Already attached - idempotent
83
+ }
84
+ }
85
+ throw error;
86
+ }
87
+ };
88
+ const detachPolicy = async (roleName, policyName) => {
89
+ try {
90
+ await camClient.DetachRolePolicy({
91
+ PolicyName: policyName,
92
+ DetachRoleName: roleName,
93
+ });
94
+ }
95
+ catch (error) {
96
+ if (error && typeof error === 'object' && 'code' in error) {
97
+ const code = String(error.code);
98
+ if (code === 'ResourceNotFound.PolicyNotAttached' ||
99
+ code === 'ResourceNotFound.RoleNotExist') {
100
+ return; // Not found - idempotent
101
+ }
102
+ }
103
+ throw error;
104
+ }
105
+ };
106
+ return {
107
+ createRole: async (roleName, trustedServices, description, customStatements, managedPolicies) => {
108
+ const assumeRolePolicy = buildAssumeRolePolicy(trustedServices);
109
+ try {
110
+ const response = await camClient.CreateRole({
111
+ RoleName: roleName,
112
+ PolicyDocument: assumeRolePolicy,
113
+ Description: description ?? `ServerlessInsight SCF execution role for ${roleName}`,
114
+ });
115
+ // Build base role info; CreateRole only returns RoleId,
116
+ // so get full info (including RoleArn) via GetRole
117
+ const roleId = response.RoleId;
118
+ let roleArn;
119
+ try {
120
+ const getResp = await camClient.GetRole({ RoleName: roleName });
121
+ roleArn = getResp.RoleInfo?.RoleArn;
122
+ }
123
+ catch {
124
+ // optional enrichment
125
+ }
126
+ const roleInfo = {
127
+ roleName,
128
+ roleId,
129
+ roleArn,
130
+ };
131
+ // Attach inline policy with built-in + custom statements
132
+ const policyName = `${roleName}-policy`;
133
+ try {
134
+ await camClient.CreatePolicy({
135
+ PolicyName: policyName,
136
+ PolicyDocument: buildExecutionPolicy(customStatements),
137
+ Description: `SCF execution policy for ${roleName}`,
138
+ });
139
+ await attachPolicy(roleName, policyName);
140
+ }
141
+ catch (error) {
142
+ if (error && typeof error === 'object' && 'code' in error) {
143
+ const code = String(error.code);
144
+ if (code === 'InvalidParameter.PolicyAlreadyExist') {
145
+ // Policy already exists - reuse it
146
+ await attachPolicy(roleName, policyName);
147
+ }
148
+ else {
149
+ throw error;
150
+ }
151
+ }
152
+ else {
153
+ throw error;
154
+ }
155
+ }
156
+ // Attach managed policies
157
+ if (managedPolicies && managedPolicies.length > 0) {
158
+ for (const policyArn of managedPolicies) {
159
+ await attachPolicy(roleName, policyArn);
160
+ }
161
+ }
162
+ return { ...roleInfo, policyName };
163
+ }
164
+ catch (error) {
165
+ if (error && typeof error === 'object' && 'code' in error) {
166
+ const code = String(error.code);
167
+ if (code === 'InvalidParameter.RoleAlreadyExist') {
168
+ logger_1.logger.warn(lang_1.lang.__('TENCENT_CAM_ROLE_ALREADY_EXISTS', { roleName }));
169
+ // Try to get the role info
170
+ try {
171
+ const getResponse = await camClient.GetRole({ RoleName: roleName });
172
+ const roleData = getResponse.RoleInfo;
173
+ const policyName = `${roleName}-policy`;
174
+ // Re-attach built-in policy (idempotent)
175
+ try {
176
+ await camClient.CreatePolicy({
177
+ PolicyName: policyName,
178
+ PolicyDocument: buildExecutionPolicy(customStatements),
179
+ Description: `SCF execution policy for ${roleName}`,
180
+ });
181
+ await attachPolicy(roleName, policyName);
182
+ }
183
+ catch {
184
+ /* already exists */
185
+ }
186
+ // Re-attach managed policies
187
+ if (managedPolicies && managedPolicies.length > 0) {
188
+ for (const policyArn of managedPolicies) {
189
+ await attachPolicy(roleName, policyArn);
190
+ }
191
+ }
192
+ return {
193
+ roleName,
194
+ roleId: roleData?.RoleId,
195
+ roleArn: roleData?.RoleArn,
196
+ policyName,
197
+ };
198
+ }
199
+ catch (recoveryError) {
200
+ // eslint-disable-next-line preserve-caught-error
201
+ throw new Error(lang_1.lang.__('TENCENT_CAM_ROLE_DRIFT_RECOVERY_FAILED', {
202
+ roleName,
203
+ error: recoveryError instanceof Error ? recoveryError.message : String(recoveryError),
204
+ }));
205
+ }
206
+ }
207
+ }
208
+ throw error;
209
+ }
210
+ },
211
+ getRole: async (roleName) => {
212
+ try {
213
+ const response = await camClient.GetRole({ RoleName: roleName });
214
+ const roleData = response.RoleInfo;
215
+ if (!roleData)
216
+ return null;
217
+ return {
218
+ roleName: roleData.RoleName,
219
+ roleId: roleData.RoleId,
220
+ roleArn: roleData.RoleArn,
221
+ description: roleData.Description,
222
+ policyName: `${roleName}-policy`,
223
+ };
224
+ }
225
+ catch (error) {
226
+ if (error && typeof error === 'object' && 'code' in error) {
227
+ const code = String(error.code);
228
+ if (code === 'ResourceNotFound.RoleNotExist')
229
+ return null;
230
+ }
231
+ throw error;
232
+ }
233
+ },
234
+ deleteRole: async (roleName, managedPolicies) => {
235
+ const policyName = `${roleName}-policy`;
236
+ // Detach managed policies first (don't delete them)
237
+ if (managedPolicies && managedPolicies.length > 0) {
238
+ for (const policyArn of managedPolicies) {
239
+ await detachPolicy(roleName, policyArn);
240
+ }
241
+ }
242
+ // Detach and delete inline policy
243
+ await detachPolicy(roleName, policyName);
244
+ await deletePolicyByName(camClient, policyName);
245
+ // Delete role
246
+ try {
247
+ await camClient.DeleteRole({ RoleName: roleName });
248
+ logger_1.logger.info(lang_1.lang.__('TENCENT_CAM_ROLE_DELETED', { roleName }));
249
+ }
250
+ catch (error) {
251
+ if (error && typeof error === 'object' && 'code' in error) {
252
+ const code = String(error.code);
253
+ if (code === 'ResourceNotFound.RoleNotExist')
254
+ return;
255
+ }
256
+ throw error;
257
+ }
258
+ },
259
+ updateRolePolicy: async (roleName, customStatements) => {
260
+ const policyName = `${roleName}-policy`;
261
+ // Detach + delete old
262
+ await detachPolicy(roleName, policyName);
263
+ await deletePolicyByName(camClient, policyName);
264
+ // Create + attach new
265
+ try {
266
+ await camClient.CreatePolicy({
267
+ PolicyName: policyName,
268
+ PolicyDocument: buildExecutionPolicy(customStatements),
269
+ Description: `SCF execution policy for ${roleName}`,
270
+ });
271
+ }
272
+ catch (error) {
273
+ if (error && typeof error === 'object' && 'code' in error) {
274
+ const code = String(error.code);
275
+ if (code !== 'InvalidParameter.PolicyAlreadyExist')
276
+ throw error;
277
+ }
278
+ else {
279
+ throw error;
280
+ }
281
+ }
282
+ await attachPolicy(roleName, policyName);
283
+ },
284
+ updateManagedPolicies: async (roleName, desiredPolicies) => {
285
+ try {
286
+ const response = await camClient.ListAttachedRolePolicies({
287
+ RoleName: roleName,
288
+ Page: 1,
289
+ Rp: 200,
290
+ });
291
+ const currentPolicies = response.List ?? [];
292
+ const currentNames = currentPolicies.map((p) => p.PolicyName ?? '');
293
+ // Detach removed policies
294
+ for (const current of currentNames) {
295
+ if (current && !desiredPolicies.includes(current)) {
296
+ await detachPolicy(roleName, current);
297
+ }
298
+ }
299
+ // Attach new policies
300
+ for (const desired of desiredPolicies) {
301
+ if (!currentNames.includes(desired)) {
302
+ await attachPolicy(roleName, desired);
303
+ }
304
+ }
305
+ }
306
+ catch (error) {
307
+ if (error && typeof error === 'object' && 'code' in error) {
308
+ const code = String(error.code);
309
+ if (code === 'ResourceNotFound.RoleNotExist')
310
+ return;
311
+ }
312
+ throw error;
313
+ }
314
+ },
315
+ };
316
+ };
317
+ exports.createCamOperations = createCamOperations;