@geek-fun/serverlessinsight 0.6.0 → 0.6.2

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
@@ -37,6 +37,7 @@ Whether you're building on AWS, Alibaba Cloud, Huawei Cloud, or other providers,
37
37
  - 🏠 **Local Testing** - Run and debug serverless functions locally
38
38
  - 🔄 **Template Generation** - Generate provider-specific IaC templates
39
39
  - 🌐 **API Gateway Integration** - Configure HTTP endpoints for your functions
40
+ - 🌐 **Custom Domain Binding** - Automatic domain binding with DNS verification for OSS and API Gateway
40
41
  - 💾 **Resource Management** - Manage storage, databases, and other cloud resources
41
42
  - 🔐 **Security First** - Built-in validation and security best practices
42
43
  - 📊 **Comprehensive Logging** - Debug and monitor your applications
@@ -143,10 +144,10 @@ For more examples, check out the [samples](./samples) directory:
143
144
 
144
145
  - [API Gateway Example](./samples/aliyun-poc-api.yml) - Deploy functions with HTTP endpoints
145
146
  - [Storage Example](./samples/aliyun-poc-bucket.yml) - Configure OSS buckets
147
+ - [Custom Domain Example](./samples/aliyun-poc-domain.yml) - Configure OSS static website with custom domain binding
146
148
  - [Database Example](./samples/aliyun-poc-rds.yml) - Set up RDS databases
147
149
  - [Table Store Example](./samples/aliyun-poc-table.yml) - Configure OTS table storage
148
150
  - [Elasticsearch Example](./samples/aliyun-poc-es.yml) - Deploy Elasticsearch Serverless
149
- - [Custom Domain Example](./samples/aliyun-poc-domain.yml) - Configure custom domains
150
151
  - [GPU Functions Example](./samples/aliyun-poc-fc-gpu.yml) - Deploy GPU-enabled functions
151
152
  - [Huawei Cloud Example](./samples/huawei-poc-fc.yml) - Deploy to Huawei Cloud FunctionGraph
152
153
 
@@ -249,6 +250,98 @@ This architecture enables:
249
250
 
250
251
  ---
251
252
 
253
+ ## 🌐 Custom Domain Binding
254
+
255
+ ServerlessInsight provides automatic custom domain binding for OSS buckets and API Gateway with built-in DNS verification.
256
+
257
+ ### OSS Custom Domain Binding
258
+
259
+ When you configure a custom domain for an OSS bucket (static website hosting), ServerlessInsight automatically:
260
+
261
+ 1. **Binds the domain** to your OSS bucket
262
+ 2. **Creates DNS CNAME records** pointing to the correct OSS endpoint
263
+ 3. **Handles domain ownership verification** via DNS TXT records when required by the cloud provider
264
+ 4. **Manages retry logic** with DNS propagation polling for reliable binding
265
+
266
+ ```yaml
267
+ buckets:
268
+ my_website:
269
+ name: my-website-bucket
270
+ security:
271
+ acl: PUBLIC_READ
272
+ website:
273
+ code: ./dist
274
+ domain: www.example.com # Custom domain binding
275
+ index: index.html
276
+ error_page: 404.html
277
+ ```
278
+
279
+ ### Domain Ownership Verification Flow
280
+
281
+ When binding a custom domain that requires ownership verification:
282
+
283
+ ```
284
+ ┌─────────────────────────────────────────────────────────────────┐
285
+ │ OSS Custom Domain Binding │
286
+ └─────────────────────────────────────────────────────────────────┘
287
+ │
288
+ ▼
289
+ ┌───────────────────────┐
290
+ │ PutCname (Attempt) │
291
+ └───────────────────────┘
292
+ │
293
+ ┌───────────────────┴───────────────────┐
294
+ │ │
295
+ ▼ ▼
296
+ ┌───────────────┐ ┌─────────────────┐
297
+ │ Success │ │ NeedVerifyDomain│
298
+ └───────────────┘ │ Ownership │
299
+ └─────────────────┘
300
+ │
301
+ ▼
302
+ ┌─────────────────────────┐
303
+ │ CreateCnameToken API │
304
+ │ (Get TXT record value) │
305
+ └─────────────────────────┘
306
+ │
307
+ ▼
308
+ ┌─────────────────────────┐
309
+ │ Check existing TXT │
310
+ │ records (avoid dupes) │
311
+ └─────────────────────────┘
312
+ │
313
+ ▼
314
+ ┌─────────────────────────┐
315
+ │ Add DNS TXT Record │
316
+ │ (_dnsauth.domain) │
317
+ └─────────────────────────┘
318
+ │
319
+ ▼
320
+ ┌─────────────────────────┐
321
+ │ Poll DNS Propagation │
322
+ │ (up to 10 × 1 min) │
323
+ └─────────────────────────┘
324
+ │
325
+ ▼
326
+ ┌─────────────────────────┐
327
+ │ Retry PutCname │
328
+ │ (up to 5 × 30 sec) │
329
+ └─────────────────────────┘
330
+ ```
331
+
332
+ ### Supported Domain Types
333
+
334
+ For OSS static website hosting, ServerlessInsight supports:
335
+
336
+ | Domain Type | CNAME Target | Use Case |
337
+ | ----------------- | -------------------------------- | ---------------------------------------------- |
338
+ | Root domain (`@`) | `bucket.region.taihangcda.cn` | Bypasses DNS CNAME restriction on root domains |
339
+ | Subdomain (`www`) | `bucket.oss-region.aliyuncs.com` | Standard OSS endpoint |
340
+
341
+ For detailed configuration, see [OSS Custom Domain Binding Guide](./docs/oss-custom-domain-binding.md).
342
+
343
+ ---
344
+
252
345
  ## 🗄️ State Management
253
346
 
254
347
  ServerlessInsight uses a state-based deployment model that tracks all deployed resources in a local state file (`.serverlessinsight/state-{app}-{service}.json` in the project directory). This enables:
package/README.zh-CN.md CHANGED
@@ -37,6 +37,7 @@ ServerlessInsight 是一个强大的 Serverless 框架,用于跨多个云服
37
37
  - 🏠 **本地测试** - 在本地运行和调试 Serverless 函数
38
38
  - 🔄 **模板生成** - 生成特定云服务商的 IaC 模板
39
39
  - 🌐 **API 网关集成** - 为您的函数配置 HTTP 端点
40
+ - 🌐 **自定义域名绑定** - 支持 OSS 和 API 网关的自动域名绑定与 DNS 验证
40
41
  - 💾 **资源管理** - 管理存储、数据库和其他云资源
41
42
  - 🔐 **安全优先** - 内置验证和安全最佳实践
42
43
  - 📊 **全面的日志记录** - 调试和监控您的应用
@@ -143,10 +144,10 @@ events:
143
144
 
144
145
  - [API 网关示例](./samples/aliyun-poc-api.yml) - 部署带 HTTP 端点的函数
145
146
  - [存储示例](./samples/aliyun-poc-bucket.yml) - 配置 OSS 存储桶
147
+ - [自定义域名示例](./samples/aliyun-poc-domain.yml) - 配置 OSS 静态网站托管与自定义域名绑定
146
148
  - [数据库示例](./samples/aliyun-poc-rds.yml) - 设置 RDS 数据库
147
149
  - [表格存储示例](./samples/aliyun-poc-table.yml) - 配置 OTS 表格存储
148
150
  - [Elasticsearch 示例](./samples/aliyun-poc-es.yml) - 部署 Elasticsearch Serverless
149
- - [自定义域名示例](./samples/aliyun-poc-domain.yml) - 配置自定义域名
150
151
  - [GPU 函数示例](./samples/aliyun-poc-fc-gpu.yml) - 部署支持 GPU 的函数
151
152
  - [华为云示例](./samples/huawei-poc-fc.yml) - 部署到华为云 FunctionGraph
152
153
 
@@ -176,6 +177,98 @@ npm run lint:check
176
177
 
177
178
  ---
178
179
 
180
+ ## 🌐 自定义域名绑定
181
+
182
+ ServerlessInsight 为 OSS 存储桶和 API 网关提供自动化的自定义域名绑定,内置 DNS 验证功能。
183
+
184
+ ### OSS 自定义域名绑定
185
+
186
+ 当您为 OSS 存储桶(静态网站托管)配置自定义域名时,ServerlessInsight 会自动:
187
+
188
+ 1. **绑定域名**到您的 OSS 存储桶
189
+ 2. **创建 DNS CNAME 记录**,指向正确的 OSS Endpoint
190
+ 3. **处理域名所有权验证**,通过 DNS TXT 记录完成云服务商要求的验证
191
+ 4. **管理重试逻辑**,通过 DNS 传播轮询确保绑定可靠
192
+
193
+ ```yaml
194
+ buckets:
195
+ my_website:
196
+ name: my-website-bucket
197
+ security:
198
+ acl: PUBLIC_READ
199
+ website:
200
+ code: ./dist
201
+ domain: www.example.com # 自定义域名绑定
202
+ index: index.html
203
+ error_page: 404.html
204
+ ```
205
+
206
+ ### 域名所有权验证流程
207
+
208
+ 当绑定需要所有权验证的自定义域名时:
209
+
210
+ ```
211
+ ┌─────────────────────────────────────────────────────────────────┐
212
+ │ OSS 自定义域名绑定流程 │
213
+ └─────────────────────────────────────────────────────────────────┘
214
+ │
215
+ ▼
216
+ ┌───────────────────────┐
217
+ │ PutCname (首次尝试) │
218
+ └───────────────────────┘
219
+ │
220
+ ┌───────────────────┴───────────────────┐
221
+ │ │
222
+ ▼ ▼
223
+ ┌───────────────┐ ┌─────────────────┐
224
+ │ 绑定成功 │ │ 需要域名所有权 │
225
+ └───────────────┘ │ 验证 │
226
+ └─────────────────┘
227
+ │
228
+ ▼
229
+ ┌─────────────────────────┐
230
+ │ CreateCnameToken API │
231
+ │ (获取 TXT 记录值) │
232
+ └─────────────────────────┘
233
+ │
234
+ ▼
235
+ ┌─────────────────────────┐
236
+ │ 检查现有 TXT 记录 │
237
+ │ (避免重复创建) │
238
+ └─────────────────────────┘
239
+ │
240
+ ▼
241
+ ┌─────────────────────────┐
242
+ │ 添加 DNS TXT 记录 │
243
+ │ (_dnsauth.domain) │
244
+ └─────────────────────────┘
245
+ │
246
+ ▼
247
+ ┌─────────────────────────┐
248
+ │ 轮询 DNS 传播状态 │
249
+ │ (最多 10 次 × 1 分钟) │
250
+ └─────────────────────────┘
251
+ │
252
+ ▼
253
+ ┌─────────────────────────┐
254
+ │ 重试 PutCname │
255
+ │ (最多 5 次 × 30 秒) │
256
+ └─────────────────────────┘
257
+ ```
258
+
259
+ ### 支持的域名类型
260
+
261
+ 对于 OSS 静态网站托管,ServerlessInsight 支持:
262
+
263
+ | 域名类型 | CNAME 目标 | 使用场景 |
264
+ | -------------- | -------------------------------- | --------------------------- |
265
+ | 根域名 (`@`) | `bucket.region.taihangcda.cn` | 绕过根域名的 DNS CNAME 限制 |
266
+ | 子域名 (`www`) | `bucket.oss-region.aliyuncs.com` | 标准 OSS Endpoint |
267
+
268
+ 详细配置请参考 [OSS 自定义域名绑定指南](./docs/oss-custom-domain-binding.md)。
269
+
270
+ ---
271
+
179
272
  ## 📘 文档
180
273
 
181
274
  完整文档请访问 [serverlessinsight.geekfun.club](https://serverlessinsight.geekfun.club)
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geek-fun/serverlessinsight",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Full life cycle cross providers serverless application management for your fast-growing business.",
5
5
  "homepage": "https://serverlessinsight.geekfun.club",
6
6
  "main": "dist/src/index.js",
@@ -43,10 +43,10 @@ const stateManager_1 = require("../stateManager");
43
43
  const sidUtils_1 = require("../sidUtils");
44
44
  const domainUtils_1 = require("../domainUtils");
45
45
  const constants_1 = require("../constants");
46
+ const retryUtils_1 = require("../retryUtils");
46
47
  const removeUndefined = (obj) => {
47
48
  return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== undefined));
48
49
  };
49
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
50
50
  const isNetworkTimeoutError = (error) => {
51
51
  if (!error || typeof error !== 'object')
52
52
  return false;
@@ -103,7 +103,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
103
103
  attempt: String(attempt),
104
104
  max: String(maxAttempts),
105
105
  }));
106
- await sleep(delayMs);
106
+ await (0, retryUtils_1.sleep)(delayMs);
107
107
  const propagated = await checkPropagation();
108
108
  if (propagated) {
109
109
  logger_1.logger.info(lang_1.lang.__('APIGW_DNS_VERIFIED', { minutes: String(attempt) }));
@@ -135,7 +135,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
135
135
  return true;
136
136
  }
137
137
  if (attempt < constants_1.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS) {
138
- await sleep(constants_1.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS);
138
+ await (0, retryUtils_1.sleep)(constants_1.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS);
139
139
  }
140
140
  }
141
141
  logger_1.logger.warn(lang_1.lang.__('APIGW_PUBLIC_DNS_TIMEOUT', { domain: domainName }));
@@ -706,7 +706,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
706
706
  attempt: String(attempt),
707
707
  max: String(constants_1.APIGW_DOMAIN_BIND_MAX_RETRIES),
708
708
  }));
709
- await sleep(constants_1.APIGW_DOMAIN_BIND_RETRY_DELAY_MS);
709
+ await (0, retryUtils_1.sleep)(constants_1.APIGW_DOMAIN_BIND_RETRY_DELAY_MS);
710
710
  try {
711
711
  await apigwClient.setDomain(setDomainRequest);
712
712
  await setCertificate();
@@ -756,7 +756,7 @@ const createApigwOperations = (apigwClient, dnsClient, _context) => {
756
756
  attempt: String(attempt),
757
757
  max: String(constants_1.APIGW_DOMAIN_BIND_MAX_RETRIES),
758
758
  }));
759
- await sleep(constants_1.APIGW_DOMAIN_BIND_RETRY_DELAY_MS);
759
+ await (0, retryUtils_1.sleep)(constants_1.APIGW_DOMAIN_BIND_RETRY_DELAY_MS);
760
760
  try {
761
761
  await apigwClient.setDomain(setDomainRequest);
762
762
  await setCertificate();
@@ -10,10 +10,32 @@ const bucketTypes_1 = require("../../stack/bucketTypes");
10
10
  const logger_1 = require("../logger");
11
11
  const lang_1 = require("../../lang");
12
12
  const domainUtils_1 = require("../domainUtils");
13
+ const retryUtils_1 = require("../retryUtils");
14
+ const constants_1 = require("../constants");
13
15
  const ossRequest = (ossClient, params) => {
14
16
  return ossClient.request(params);
15
17
  };
16
18
  const escapeXmlText = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
19
+ const toCamelCase = (str) => str.charAt(0).toLowerCase() + str.slice(1);
20
+ const parseXmlResponse = (xml, tagName) => {
21
+ try {
22
+ const containerRegex = new RegExp(`<${tagName}>([\\s\\S]*?)<\\/${tagName}>`);
23
+ const containerMatch = containerRegex.exec(xml);
24
+ if (!containerMatch)
25
+ return null;
26
+ const innerXml = containerMatch[1];
27
+ const result = {};
28
+ const childRegex = /<(\w+)>([^<]*)<\/\1>/g;
29
+ let match;
30
+ while ((match = childRegex.exec(innerXml)) !== null) {
31
+ result[toCamelCase(match[1])] = match[2].trim();
32
+ }
33
+ return Object.keys(result).length > 0 ? result : null;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ };
17
39
  const createOssOperations = (ossClient, region, dnsOps) => {
18
40
  const useBucket = (bucketName) => {
19
41
  ossClient.useBucket(bucketName);
@@ -31,6 +53,37 @@ const createOssOperations = (ossClient, region, dnsOps) => {
31
53
  <Force>true</Force>
32
54
  </CertificateConfiguration>`;
33
55
  };
56
+ const createCnameToken = async (bucketName, domain) => {
57
+ useBucket(bucketName);
58
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
59
+ <BucketCnameConfiguration>
60
+ <Cname>
61
+ <Domain>${escapeXmlText(domain)}</Domain>
62
+ </Cname>
63
+ </BucketCnameConfiguration>`;
64
+ const params = {
65
+ method: 'POST',
66
+ bucket: bucketName,
67
+ subres: { cname: '', comp: 'token' },
68
+ headers: {
69
+ 'Content-Type': 'application/xml',
70
+ },
71
+ content: xml,
72
+ successStatuses: [200],
73
+ };
74
+ const response = await ossRequest(ossClient, params);
75
+ const responseXml = response.data || '';
76
+ const parsed = parseXmlResponse(responseXml, 'CnameToken');
77
+ if (!parsed || !parsed.token) {
78
+ throw new Error(lang_1.lang.__('OSS_CNAME_TOKEN_CREATE_FAILED', { domain }));
79
+ }
80
+ return {
81
+ bucket: bucketName,
82
+ cname: domain,
83
+ token: parsed.token,
84
+ expireTime: parsed.expireTime || '',
85
+ };
86
+ };
34
87
  const putBucketCname = async (bucketName, domain, certificate) => {
35
88
  useBucket(bucketName);
36
89
  const certXml = buildCertificateXml(certificate);
@@ -54,24 +107,24 @@ const createOssOperations = (ossClient, region, dnsOps) => {
54
107
  };
55
108
  await ossClient.request(params);
56
109
  logger_1.logger.info(lang_1.lang.__('OSS_BUCKET_CNAME_BOUND', { domain }));
57
- return true;
110
+ return { success: true, needVerification: false };
58
111
  }
59
112
  catch (error) {
60
113
  const err = error;
61
114
  if (err.code === 'CnameAlreadyExists' || err.status === 409) {
62
115
  logger_1.logger.info(lang_1.lang.__('OSS_BUCKET_CNAME_EXISTS', { domain }));
63
- return true;
116
+ return { success: true, needVerification: false };
64
117
  }
65
118
  if (err.code === 'NeedVerifyDomainOwnership') {
66
119
  logger_1.logger.warn(lang_1.lang.__('OSS_BUCKET_CNAME_NEED_VERIFY', { domain }));
67
- return false;
120
+ return { success: false, needVerification: true };
68
121
  }
69
122
  if (certificate) {
70
123
  // eslint-disable-next-line preserve-caught-error
71
124
  throw new Error(lang_1.lang.__('OSS_BUCKET_CNAME_BIND_FAILED', { error: String(error) }));
72
125
  }
73
126
  logger_1.logger.warn(lang_1.lang.__('OSS_BUCKET_CNAME_BIND_FAILED', { error: String(error) }));
74
- return false;
127
+ return { success: false, needVerification: false };
75
128
  }
76
129
  };
77
130
  const deleteBucketCname = async (bucketName, domain) => {
@@ -172,15 +225,166 @@ const createOssOperations = (ossClient, region, dnsOps) => {
172
225
  const mainDomain = (0, domainUtils_1.extractMainDomain)(domain);
173
226
  const hostRecord = (0, domainUtils_1.extractHostRecord)(domain, mainDomain);
174
227
  const ossEndpoint = getOssEndpoint(bucketName);
175
- const bucketCnameBound = await putBucketCname(bucketName, domain, certificate);
228
+ let cnameResult = await putBucketCname(bucketName, domain, certificate);
229
+ let txtRecordId;
230
+ if (cnameResult.needVerification) {
231
+ const verificationResult = await handleDomainOwnershipVerification(bucketName, domain, certificate);
232
+ cnameResult = verificationResult;
233
+ txtRecordId = verificationResult.txtRecordId;
234
+ }
235
+ const bucketCnameBound = cnameResult.success;
176
236
  if (certificate && bucketCnameBound) {
177
237
  logger_1.logger.info(lang_1.lang.__('OSS_BUCKET_CERT_BOUND', { domain }));
178
238
  }
179
239
  await addCorsRuleForDomain(bucketName, domain);
180
240
  if (!dnsOps) {
181
241
  logger_1.logger.warn(lang_1.lang.__('OSS_DNS_MANUAL_CONFIG_REQUIRED', { domain, cname: ossEndpoint }));
182
- return { domain, cname: ossEndpoint, bucketCnameBound };
242
+ return { domain, cname: ossEndpoint, bucketCnameBound, txtRecordId };
243
+ }
244
+ const result = await createOrFindDnsCnameRecord(domain, mainDomain, hostRecord, ossEndpoint, bucketCnameBound);
245
+ return { ...result, txtRecordId };
246
+ };
247
+ const logOssVerificationInstructions = (domain, fullTxtRecord, token) => {
248
+ const mainDomain = (0, domainUtils_1.extractMainDomain)(domain);
249
+ const separator = '='.repeat(80);
250
+ logger_1.logger.error(`\n${separator}\n${lang_1.lang.__('OSS_VERIFICATION_HEADER')}\n${separator}\n${lang_1.lang.__('OSS_VERIFICATION_DOMAIN', { domain })}\n\n${lang_1.lang.__('OSS_VERIFICATION_INSTRUCTIONS')}\n\n${lang_1.lang.__('OSS_VERIFICATION_RECORD_NAME', { name: `${fullTxtRecord}.${mainDomain}` })}\n${lang_1.lang.__('OSS_VERIFICATION_RECORD_TYPE')}\n${lang_1.lang.__('OSS_VERIFICATION_RECORD_VALUE', { value: token })}`);
251
+ logger_1.logger.error(`\n${separator}\n${lang_1.lang.__('OSS_VERIFICATION_NEXT_STEPS')}\n${lang_1.lang.__('OSS_VERIFICATION_STEP1')}\n${lang_1.lang.__('OSS_VERIFICATION_STEP2')}\n${separator}\n`);
252
+ };
253
+ const handleDomainOwnershipVerification = async (bucketName, domain, certificate) => {
254
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_CREATING_VERIFICATION_TOKEN', { domain }));
255
+ const tokenInfo = await createCnameToken(bucketName, domain);
256
+ const txtRecordName = '_dnsauth';
257
+ const hostRecord = (0, domainUtils_1.extractHostRecord)(domain, (0, domainUtils_1.extractMainDomain)(domain));
258
+ const fullTxtRecord = hostRecord ? `${txtRecordName}.${hostRecord}` : txtRecordName;
259
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_VERIFICATION_TOKEN_CREATED', {
260
+ domain,
261
+ txtRecord: fullTxtRecord,
262
+ token: tokenInfo.token,
263
+ }));
264
+ const txtResult = await addVerificationTxtRecord((0, domainUtils_1.extractMainDomain)(domain), fullTxtRecord, tokenInfo.token);
265
+ if (txtResult.success) {
266
+ await pollTxtDnsPropagation((0, domainUtils_1.extractMainDomain)(domain), fullTxtRecord, tokenInfo.token);
267
+ const retryResult = await retryCnameBindingAfterVerification(bucketName, domain, certificate);
268
+ return { ...retryResult, txtRecordId: txtResult.recordId };
183
269
  }
270
+ logOssVerificationInstructions(domain, fullTxtRecord, tokenInfo.token);
271
+ throw new Error(lang_1.lang.__('OSS_CNAME_MANUAL_VERIFICATION_REQUIRED', {
272
+ domain,
273
+ txtRecord: `${fullTxtRecord}.${(0, domainUtils_1.extractMainDomain)(domain)}`,
274
+ token: tokenInfo.token,
275
+ }));
276
+ };
277
+ const addVerificationTxtRecord = async (mainDomain, fullTxtRecord, token) => {
278
+ if (!dnsOps)
279
+ return { success: false };
280
+ try {
281
+ const existingRecords = await dnsOps.describeDomainRecords(mainDomain, fullTxtRecord);
282
+ const existingRecord = existingRecords.find((record) => record.rr === fullTxtRecord && record.type === 'TXT' && record.value === token);
283
+ if (existingRecord) {
284
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_TXT_RECORD_ALREADY_EXISTS', {
285
+ txtRecord: `${fullTxtRecord}.${mainDomain}`,
286
+ }));
287
+ return { success: true, recordId: existingRecord.recordId };
288
+ }
289
+ const recordId = await dnsOps.addDomainRecord({
290
+ domainName: mainDomain,
291
+ rr: fullTxtRecord,
292
+ type: 'TXT',
293
+ value: token,
294
+ ttl: 600,
295
+ });
296
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_TXT_RECORD_CREATED', {
297
+ txtRecord: `${fullTxtRecord}.${mainDomain}`,
298
+ }));
299
+ return { success: true, recordId };
300
+ }
301
+ catch (error) {
302
+ logger_1.logger.warn(lang_1.lang.__('OSS_CNAME_TXT_RECORD_CREATE_FAILED', {
303
+ txtRecord: `${fullTxtRecord}.${mainDomain}`,
304
+ error: String(error),
305
+ }));
306
+ return { success: false };
307
+ }
308
+ };
309
+ const pollTxtDnsPropagation = async (mainDomain, fullTxtRecord, token) => {
310
+ if (!dnsOps)
311
+ return false;
312
+ const checkPropagation = async () => {
313
+ try {
314
+ const currentRecords = await dnsOps.describeDomainRecords(mainDomain, fullTxtRecord);
315
+ return currentRecords.some((record) => record.rr === fullTxtRecord &&
316
+ record.type === 'TXT' &&
317
+ record.value === token &&
318
+ record.status === 'ENABLE');
319
+ }
320
+ catch (checkError) {
321
+ logger_1.logger.warn(lang_1.lang.__('OSS_CNAME_DNS_CHECK_FAILED', { error: String(checkError) }));
322
+ return false;
323
+ }
324
+ };
325
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_DNS_PROPAGATION_WAITING', { domain: mainDomain }));
326
+ for (let attempt = 1; attempt <= constants_1.DNS_PROPAGATION_MAX_ATTEMPTS; attempt++) {
327
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_DNS_PROPAGATION_CHECK', {
328
+ attempt: String(attempt),
329
+ max: String(constants_1.DNS_PROPAGATION_MAX_ATTEMPTS),
330
+ }));
331
+ await (0, retryUtils_1.sleep)(constants_1.DNS_PROPAGATION_DELAY_MS);
332
+ const propagated = await checkPropagation();
333
+ if (propagated) {
334
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_DNS_PROPAGATION_VERIFIED', {
335
+ domain: mainDomain,
336
+ minutes: String(attempt),
337
+ }));
338
+ return true;
339
+ }
340
+ }
341
+ logger_1.logger.warn(lang_1.lang.__('OSS_CNAME_DNS_PROPAGATION_TIMEOUT', {
342
+ max: String(constants_1.DNS_PROPAGATION_MAX_ATTEMPTS),
343
+ }));
344
+ return false;
345
+ };
346
+ const retryCnameBindingAfterVerification = async (bucketName, domain, certificate) => {
347
+ logger_1.logger.info(lang_1.lang.__('OSS_CNAME_WAITING_FOR_VERIFICATION', { domain }));
348
+ for (let attempt = 1; attempt <= constants_1.DOMAIN_BIND_MAX_RETRIES; attempt++) {
349
+ if (attempt > 1) {
350
+ logger_1.logger.info(lang_1.lang.__('RETRY_ATTEMPT', {
351
+ operation: 'domain binding',
352
+ attempt: String(attempt),
353
+ max: String(constants_1.DOMAIN_BIND_MAX_RETRIES),
354
+ }));
355
+ }
356
+ await (0, retryUtils_1.sleep)(constants_1.DOMAIN_BIND_RETRY_DELAY_MS);
357
+ try {
358
+ const cnameResult = await putBucketCname(bucketName, domain, certificate);
359
+ if (cnameResult.success) {
360
+ return cnameResult;
361
+ }
362
+ if (!cnameResult.needVerification) {
363
+ return cnameResult;
364
+ }
365
+ }
366
+ catch (error) {
367
+ if (attempt === constants_1.DOMAIN_BIND_MAX_RETRIES) {
368
+ throw error;
369
+ }
370
+ logger_1.logger.warn(lang_1.lang.__('RETRY_ATTEMPT_FAILED', {
371
+ operation: 'domain binding',
372
+ attempt: String(attempt),
373
+ max: String(constants_1.DOMAIN_BIND_MAX_RETRIES),
374
+ error: String(error),
375
+ }));
376
+ }
377
+ }
378
+ const hostRecord = (0, domainUtils_1.extractHostRecord)(domain, (0, domainUtils_1.extractMainDomain)(domain));
379
+ const txtRecordName = '_dnsauth';
380
+ const fullTxtRecord = hostRecord ? `${txtRecordName}.${hostRecord}` : txtRecordName;
381
+ logger_1.logger.warn(lang_1.lang.__('OSS_CNAME_VERIFICATION_RETRY_FAILED', {
382
+ domain,
383
+ txtRecord: `${fullTxtRecord}.${(0, domainUtils_1.extractMainDomain)(domain)}`,
384
+ }));
385
+ return { success: false, needVerification: true };
386
+ };
387
+ const createOrFindDnsCnameRecord = async (domain, mainDomain, hostRecord, ossEndpoint, bucketCnameBound) => {
184
388
  try {
185
389
  const existingRecords = await dnsOps.describeDomainRecords(mainDomain, hostRecord);
186
390
  const existingRecord = existingRecords.find((record) => record.rr === hostRecord && record.type === 'CNAME' && record.value === ossEndpoint);
@@ -237,18 +441,28 @@ const createOssOperations = (ossClient, region, dnsOps) => {
237
441
  }));
238
442
  }
239
443
  };
240
- const unbindCustomDomain = async (bucketName, domain, dnsRecordId) => {
444
+ const unbindCustomDomain = async (bucketName, domain, dnsRecordId, txtRecordId) => {
241
445
  await removeCorsRuleForDomain(bucketName, domain);
242
446
  await deleteBucketCname(bucketName, domain);
243
- if (!dnsOps || !dnsRecordId || dnsRecordId === 'existing') {
244
- return;
245
- }
246
- try {
247
- await dnsOps.deleteDomainRecord(dnsRecordId);
248
- logger_1.logger.info(lang_1.lang.__('OSS_DNS_CNAME_DELETED', { domain }));
249
- }
250
- catch (error) {
251
- logger_1.logger.warn(lang_1.lang.__('OSS_DNS_CNAME_DELETE_FAILED', { domain, error: String(error) }));
447
+ if (dnsOps) {
448
+ if (dnsRecordId && dnsRecordId !== 'existing') {
449
+ try {
450
+ await dnsOps.deleteDomainRecord(dnsRecordId);
451
+ logger_1.logger.info(lang_1.lang.__('OSS_DNS_CNAME_DELETED', { domain }));
452
+ }
453
+ catch (error) {
454
+ logger_1.logger.warn(lang_1.lang.__('OSS_DNS_CNAME_DELETE_FAILED', { domain, error: String(error) }));
455
+ }
456
+ }
457
+ if (txtRecordId) {
458
+ try {
459
+ await dnsOps.deleteDomainRecord(txtRecordId);
460
+ logger_1.logger.info(lang_1.lang.__('OSS_DNS_TXT_RECORD_DELETED', { domain }));
461
+ }
462
+ catch (error) {
463
+ logger_1.logger.warn(lang_1.lang.__('OSS_DNS_TXT_RECORD_DELETE_FAILED', { domain, error: String(error) }));
464
+ }
465
+ }
252
466
  }
253
467
  };
254
468
  return {
@@ -486,6 +700,7 @@ const createOssOperations = (ossClient, region, dnsOps) => {
486
700
  bindCustomDomain,
487
701
  unbindCustomDomain,
488
702
  getOssEndpoint,
703
+ createCnameToken,
489
704
  };
490
705
  };
491
706
  exports.createOssOperations = createOssOperations;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.warnInlinePem = exports.readPemContent = exports.isFilePath = void 0;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const logger_1 = require("./logger");
10
+ const lang_1 = require("../lang");
11
+ const isFilePath = (value) => {
12
+ if (value.startsWith('./') || value.startsWith('../'))
13
+ return true;
14
+ return /\.(pem|crt|key)$/.test(value);
15
+ };
16
+ exports.isFilePath = isFilePath;
17
+ const readPemContent = (value) => {
18
+ if (!(0, exports.isFilePath)(value))
19
+ return value;
20
+ const filePath = node_path_1.default.resolve(process.cwd(), value);
21
+ if (!node_fs_1.default.existsSync(filePath)) {
22
+ throw new Error(lang_1.lang.__('CERT_FILE_NOT_FOUND', { filePath }));
23
+ }
24
+ logger_1.logger.info(lang_1.lang.__('CERT_READING_FILE', { filePath }));
25
+ return node_fs_1.default.readFileSync(filePath, 'utf-8');
26
+ };
27
+ exports.readPemContent = readPemContent;
28
+ const warnInlinePem = (value) => {
29
+ if (typeof value === 'string' && (value.includes('BEGIN') || value.includes('PRIVATE KEY'))) {
30
+ logger_1.logger.warn(lang_1.lang.__('CERT_INLINE_PEM_WARNING'));
31
+ }
32
+ };
33
+ exports.warnInlinePem = warnInlinePem;