@cloudbase/manager-node 5.10.7 → 5.10.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## [5.10.7] 2026-11-30
2
+
3
+ - [Fixed] deps: remove the legacy COS request chain
4
+
1
5
  ## [5.10.6] 2026-11-25
2
6
 
3
7
  - [Added] storage: 新增 TUS 大文件断点续传上传 uploadObjectResumable
@@ -1,7 +1,3 @@
1
- ## [5.10.6] 2026-11-25
1
+ ## [5.10.7] 2026-11-30
2
2
 
3
- - [Added] [TODO: translate] storage: 新增 TUS 大文件断点续传上传 uploadObjectResumable
4
- - [Added] [TODO: translate] database: 优化 PostgreSQL 迁移请求负载
5
- - [Added] [TODO: translate] monitor: 新增 PostgreSQL 监控指标类型与查询用例
6
- - [Fixed] [TODO: translate] function: CBF 代码包 PutUrl 上传补充 Content-Length 请求头修复 403 报错
7
- - [Fixed] [TODO: translate] error-docs: 补齐 8 个数据面错误码 + 自造码锚点契约测试
3
+ - [Fixed] [TODO: translate] deps: remove the legacy COS request chain
@@ -330,6 +330,30 @@ class CloudRunService {
330
330
  ServerName: params.serverName // 要删除的服务名称
331
331
  });
332
332
  }
333
+ /**
334
+ * 两段式部署阶段 A:获取代码包上传信息。
335
+ *
336
+ * UploadUrl / UploadHeaders 由服务端签发,调用方自行 PUT 代码 zip,再把
337
+ * PackageName / PackageVersion 通过 deploy({ packageInfo }) 传回来触发部署。
338
+ * 本方法不读取本地文件,也不代替调用方发起上传。
339
+ */
340
+ async getPackageUploadInfo(params) {
341
+ var _a, _b;
342
+ const serverName = (_a = params.serverName) === null || _a === void 0 ? void 0 : _a.trim();
343
+ if (!serverName) {
344
+ (0, error_1.throwInvalidParam)('Missing required parameters: serverName');
345
+ }
346
+ // @preLazy 保证环境已初始化,但 EnvId 仍可能因异常配置为空;空 EnvId 会发出无效请求。
347
+ const envConfig = this.environment.lazyEnvironmentConfig;
348
+ const envId = (_b = envConfig === null || envConfig === void 0 ? void 0 : envConfig.EnvId) === null || _b === void 0 ? void 0 : _b.trim();
349
+ if (!envId) {
350
+ (0, error_1.throwEnvironmentNotInitialized)('Missing environment EnvId: initialize CloudBase before requesting upload info');
351
+ }
352
+ return this.tcbService.request('DescribeCloudBaseBuildService', {
353
+ EnvId: envId,
354
+ ServiceName: serverName
355
+ });
356
+ }
333
357
  /**
334
358
  * 本地代码部署云托管服务
335
359
  * @param {Object} params 部署参数
@@ -355,13 +379,17 @@ class CloudRunService {
355
379
  */
356
380
  async deploy(params) {
357
381
  var _a, _b, _c;
358
- const { serverName, targetPath = process.cwd(), serverConfig, vpcInfo, imageUrl } = params;
382
+ const { serverName, targetPath, serverConfig, vpcInfo, imageUrl, packageInfo, serverType } = params;
383
+ const localPath = targetPath !== null && targetPath !== void 0 ? targetPath : process.cwd();
359
384
  /**
360
385
  * 参数校验和默认值设置
361
386
  */
362
387
  if (!serverName) {
363
388
  (0, error_1.throwInvalidParam)('Missing required parameters: serviceName');
364
389
  }
390
+ if (packageInfo && (!packageInfo.PackageName || !packageInfo.PackageVersion)) {
391
+ (0, error_1.throwInvalidParam)('packageInfo requires PackageName and PackageVersion');
392
+ }
365
393
  // 获取当前环境配置(包含EnvId)
366
394
  const envConfig = this.environment.lazyEnvironmentConfig;
367
395
  /**
@@ -375,6 +403,14 @@ class CloudRunService {
375
403
  ImageUrl: imageUrl
376
404
  };
377
405
  }
406
+ else if (packageInfo) {
407
+ // 两段式部署阶段 B:代码包已由调用方上传,这里只认服务端签发的包名。
408
+ deployInfo = {
409
+ DeployType: 'package',
410
+ PackageName: packageInfo.PackageName,
411
+ PackageVersion: packageInfo.PackageVersion
412
+ };
413
+ }
378
414
  else {
379
415
  // 代码包部署模式:获取上传信息 → 打包 → 上传
380
416
  const { UploadUrl: uploadUrl, UploadHeaders: uploadHeaders, PackageName: packageName, PackageVersion: packageVersion } = await this.tcbService.request('DescribeCloudBaseBuildService', {
@@ -389,7 +425,7 @@ class CloudRunService {
389
425
  /**
390
426
  * 上传部署包
391
427
  */
392
- const zipFile = await codeToZip(targetPath, { installDependency: (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.InstallDependency) !== undefined ? serverConfig.InstallDependency : true });
428
+ const zipFile = await codeToZip(localPath, { installDependency: (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.InstallDependency) !== undefined ? serverConfig.InstallDependency : true });
393
429
  await (0, utils_1.upload)({
394
430
  url: uploadUrl,
395
431
  file: zipFile,
@@ -422,16 +458,24 @@ class CloudRunService {
422
458
  });
423
459
  }
424
460
  else {
425
- // 创建
461
+ // 创建:两段式部署无法从本地目录判断服务类型,必须由调用方显式给出。
462
+ // 只在新建路径校验;更新路径的服务类型来自远端 Tag,不看 serverType 入参。
463
+ if (packageInfo && !serverType) {
464
+ (0, error_1.throwInvalidParam)('Two-phase deploy requires serverType for new services');
465
+ }
426
466
  /**
427
467
  * 判断是容器还是函数型(镜像部署固定为 container)
428
468
  */
429
- let type = imageUrl ? 'container' : 'function';
430
- if (!imageUrl && (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.Dockerfile)) {
431
- type = 'container';
432
- }
433
- else if (!imageUrl) {
434
- if (await (0, fs_extra_1.pathExists)(path_1.default.join(targetPath, 'Dockerfile'))) {
469
+ // 镜像部署固定为 container;serverType 只在非镜像部署时生效,
470
+ // 避免 type=function 与 DeployType=image 同时出现。
471
+ let type = imageUrl
472
+ ? 'container'
473
+ : (serverType !== null && serverType !== void 0 ? serverType : 'function');
474
+ if (!serverType && !imageUrl) {
475
+ if (serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.Dockerfile) {
476
+ type = 'container';
477
+ }
478
+ else if (targetPath && await (0, fs_extra_1.pathExists)(path_1.default.join(localPath, 'Dockerfile'))) {
435
479
  type = 'container';
436
480
  }
437
481
  }
@@ -571,6 +615,9 @@ __decorate([
571
615
  __decorate([
572
616
  (0, utils_1.preLazy)()
573
617
  ], CloudRunService.prototype, "delete", null);
618
+ __decorate([
619
+ (0, utils_1.preLazy)()
620
+ ], CloudRunService.prototype, "getPackageUploadInfo", null);
574
621
  __decorate([
575
622
  (0, utils_1.preLazy)()
576
623
  ], CloudRunService.prototype, "deploy", null);
package/lib/docs/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DocsService = void 0;
4
+ exports.isHtmlBody = isHtmlBody;
5
+ exports.isNotFoundPage = isNotFoundPage;
6
+ exports.normalizeDocPath = normalizeDocPath;
4
7
  const http_request_1 = require("../utils/http-request");
5
8
  const error_1 = require("../error");
6
9
  const DOCS_BASE_URL = 'https://docs.cloudbase.net';
@@ -16,6 +19,85 @@ const ALGOLIA_SEARCH_PARAMS = 'attributesToRetrieve=["hierarchy.lvl0","hierarchy
16
19
  '&hitsPerPage=20' +
17
20
  '&clickAnalytics=false' +
18
21
  '&facetFilters=["language:zh-Hans",["docusaurus_tag:default","docusaurus_tag:docs-default-current"]]';
22
+ // HTTP 200 也可能是 HTML:站点对任意未知路径回兜底页,状态码与 content-type 都不能单独作判据
23
+ const HTML_BODY_PREFIX = /^<!doctype html|^<html[\s>]/i;
24
+ const CANONICAL_LINK_TAG = /<link[^>]+rel=["']canonical["'][^>]*>/i;
25
+ // 兜底页正文里的固定文案,canonical 之外的第二道保险(站点改版时两者至少活一个)
26
+ const NOT_FOUND_COPY = '这个页面走丢了';
27
+ function isHtmlBody(text) {
28
+ return HTML_BODY_PREFIX.test(text.trimStart());
29
+ }
30
+ /** 404 兜底页的特征:canonical 指向 404.html(或正文含「这个页面走丢了」) */
31
+ function isNotFoundPage(html) {
32
+ var _a;
33
+ const canonical = (_a = html.match(CANONICAL_LINK_TAG)) === null || _a === void 0 ? void 0 : _a[0];
34
+ if (canonical && /\/404\.html/i.test(canonical)) {
35
+ return true;
36
+ }
37
+ return html.includes(NOT_FOUND_COPY);
38
+ }
39
+ /**
40
+ * 将文档路径归一化为 markdown 源文件路径(`{path}.md`)
41
+ *
42
+ * 文档站按 `{path}.md` 直接给出 markdown 源文件,不再提供 `{path}/index.md`;
43
+ * 且 CDN 对缺失路径返回 HTTP 200 + 404 兜底页面(而非 404 状态码),
44
+ * 因此路径拼接错误不会触发网络错误,只会静默把整页 HTML 当文档正文返回。
45
+ *
46
+ * 这里只做形态归一,不判断文档是否存在(那要靠响应体,见 `isNotFoundPage`):
47
+ * - 文档站完整 URL → 只留 pathname(`/en/` 是真实语言站,原样保留)
48
+ * - 旧写法 `<path>/index.md`、`<path>/index` → 还原成 `<path>.md`
49
+ * - 非文档站的完整 URL → 原样透传(既有行为,调用方可能指向别的源)
50
+ */
51
+ function normalizeDocPath(docPath) {
52
+ const trimmed = docPath.trim();
53
+ let path = trimmed;
54
+ if (/^https?:\/\//i.test(trimmed)) {
55
+ let parsed;
56
+ try {
57
+ parsed = new URL(trimmed);
58
+ }
59
+ catch (_a) {
60
+ return trimmed;
61
+ }
62
+ // 只认官方网站的 hostname。用 URL API 判断而不是正则:
63
+ // `docs.cloudbase.net@evil.com` 的 hostname 是 evil.com,正则容易看走眼
64
+ if (parsed.hostname.toLowerCase() !== 'docs.cloudbase.net') {
65
+ return trimmed;
66
+ }
67
+ // 只剥 scheme + authority,路径保留原样。不能取 parsed.pathname:
68
+ // URL 解析器会提前把 `.%2e` 这类点段归一化掉,抹掉待校验的痕迹
69
+ path = trimmed.replace(/^https?:\/\/[^/?#]+/i, '');
70
+ }
71
+ // 查询串与锚点对取源文件无用,留着会让 `.md` 拼到锚点后面
72
+ path = path
73
+ .replace(/[?#].*$/, '')
74
+ .replace(/\\/g, '/')
75
+ .replace(/^\/+|\/+$/g, '');
76
+ // 解码到稳定再按路径段校验:%2e / %2f / 反斜杠 / 多轮编码都是同一类绕过
77
+ let decoded = path;
78
+ for (let i = 0; i < 3; i++) {
79
+ let next;
80
+ try {
81
+ next = decodeURIComponent(decoded);
82
+ }
83
+ catch (_b) {
84
+ (0, error_1.throwApiError)(`文档路径含非法编码: "${docPath}"`);
85
+ }
86
+ if (next === decoded) {
87
+ break;
88
+ }
89
+ decoded = next;
90
+ }
91
+ if (decoded.split('/').some(segment => segment === '.' || segment === '..')) {
92
+ (0, error_1.throwApiError)(`文档路径含上级目录跳转: "${docPath}"`);
93
+ }
94
+ // 旧写法(category.json 里有 14 条以 /index 结尾的页面 URL)
95
+ path = path.replace(/\/index(\.mdx?)?$/i, '');
96
+ if (/\.mdx?$/i.test(path)) {
97
+ return path;
98
+ }
99
+ return path ? `${path}.md` : 'index.md';
100
+ }
19
101
  class DocsService {
20
102
  async listModules() {
21
103
  const category = await this.getCategory();
@@ -105,7 +187,9 @@ class DocsService {
105
187
  return new URL(`${parsed.pathname}${parsed.search}${parsed.hash}`, DOCS_BASE_URL).toString();
106
188
  }
107
189
  async readDoc(docPath) {
108
- const normalizedPath = docPath.endsWith('.md') ? docPath : `${docPath}/index.md`;
190
+ const normalizedPath = normalizeDocPath(docPath);
191
+ // 请求目标只由 DOCS_BASE_URL 决定:归一化后仍走 resolveDocsRequestUrl,
192
+ // 丢弃入参带来的 scheme / host / port,调用方无论如何都选不了主机。
109
193
  const url = this.resolveDocsRequestUrl(normalizedPath);
110
194
  const res = await (0, http_request_1.fetchStream)(url, {
111
195
  redirect: 'manual',
@@ -121,6 +205,14 @@ class DocsService {
121
205
  if (text.charCodeAt(0) === 0xFEFF) {
122
206
  text = text.slice(1);
123
207
  }
208
+ // 站点对未知路径回 200 + HTML 兜底页,HTTP 层看不出失败,只能判响应体
209
+ if (isHtmlBody(text)) {
210
+ if (isNotFoundPage(text)) {
211
+ (0, error_1.throwNotFound)(`该路径没有 Markdown 源文件: "${docPath}"(${url} 返回 404 兜底页面)—— 路径可能拼错,` +
212
+ '也可能该页面(如 http-api 下由 OpenAPI 生成的页)本来就不提供 md');
213
+ }
214
+ (0, error_1.throwApiError)(`文档站返回 HTML 而非 Markdown: "${docPath}"(${url})`);
215
+ }
124
216
  return text;
125
217
  }
126
218
  async searchDocs(query) {
@@ -0,0 +1,235 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AUTHZ_ENGINE = void 0;
4
+ exports.authzEngineDetailOf = authzEngineDetailOf;
5
+ exports.authzEngineOf = authzEngineOf;
6
+ exports.deriveEnvCapabilities = deriveEnvCapabilities;
7
+ exports.postgresProvisionState = postgresProvisionState;
8
+ function asArray(value) {
9
+ return Array.isArray(value) ? value : undefined;
10
+ }
11
+ /** 取对象形态(排除数组与 null);非对象一律 undefined */
12
+ function asRecord(value) {
13
+ return value && typeof value === 'object' && !Array.isArray(value)
14
+ ? value
15
+ : undefined;
16
+ }
17
+ /**
18
+ * PG 是否已开通:PostgreSQL[] 非空,或 Meta 里 postgresql/postgre_sql=enable。
19
+ * 两个信号都在才敢下「没有」的结论(Meta[] 为空是正常值)。
20
+ */
21
+ function postgresProvisioned(source) {
22
+ const instances = asArray(source.PostgreSQL);
23
+ if (instances && instances.length > 0)
24
+ return true;
25
+ const meta = asArray(source.Meta);
26
+ return Boolean(meta === null || meta === void 0 ? void 0 : meta.some(item => ((item === null || item === void 0 ? void 0 : item.Key) === 'postgresql' || (item === null || item === void 0 ? void 0 : item.Key) === 'postgre_sql') &&
27
+ (item === null || item === void 0 ? void 0 : item.Value) === 'enable'));
28
+ }
29
+ function documentdbOf(source) {
30
+ const instances = asArray(source.PostgreSQL) || [];
31
+ const values = instances
32
+ .map(instance => instance === null || instance === void 0 ? void 0 : instance.DocumentExt)
33
+ .filter((value) => typeof value === 'boolean');
34
+ return values.length > 0 ? values.includes(true) : undefined;
35
+ }
36
+ /**
37
+ * 是否至少有一条「真实可用的桶」记录。
38
+ *
39
+ * Storages[] 里两种形态都算真实存储:
40
+ * - 环境自有桶:`Bucket` 非空;
41
+ * - 共享桶:`Bucket` 为空,`ExternalStorage.Enabled = true`。
42
+ * 既没有桶名、也没开共享的空壳记录不算 —— 用数组非空判「有存储」会被这种记录骗过。
43
+ */
44
+ function hasRealStorageBucket(source) {
45
+ const storages = asArray(source.Storages) || [];
46
+ return storages.some(storage => {
47
+ var _a;
48
+ const bucket = storage === null || storage === void 0 ? void 0 : storage.Bucket;
49
+ if (typeof bucket === 'string' && bucket.length > 0)
50
+ return true;
51
+ return ((_a = asRecord(storage === null || storage === void 0 ? void 0 : storage.ExternalStorage)) === null || _a === void 0 ? void 0 : _a.Enabled) === true;
52
+ });
53
+ }
54
+ /**
55
+ * 鉴权引擎取值:`Meta[].authz_engine` 的原值,也是 `AuthzProfile.engine` 的取值域。
56
+ *
57
+ * 常量而非散落字符串:能力派生与 permission 共用同一份,避免后续扩枚举时漏改一处。
58
+ */
59
+ exports.AUTHZ_ENGINE = {
60
+ OPA: 'opa',
61
+ AUTHPOLICY: 'authpolicy'
62
+ };
63
+ /**
64
+ * 网关鉴权引擎的判定值与原始值,二者取自同一次查找,保证配对
65
+ * (不会出现「首个条目写坏 → 生效值是后面那条」时错位)。
66
+ *
67
+ * - `engine`:只认文档枚举 opa / authpolicy,取第一个能判定的值;
68
+ * - `raw`:与 engine 配对的那条 Meta 原始取值;没有能判定的值时回落到
69
+ * 首条 key 匹配的原始值,便于排查「值写错了」而不是「字段没有」。
70
+ *
71
+ * 模块内导出供 PermissionService 复用(不进 CloudBase 命名空间),
72
+ * 保证 Gateway 能力与鉴权短路读的是同一个结论。
73
+ */
74
+ function authzEngineDetailOf(source) {
75
+ const meta = asArray(source === null || source === void 0 ? void 0 : source.Meta) || [];
76
+ let firstValue;
77
+ for (const item of meta) {
78
+ if ((item === null || item === void 0 ? void 0 : item.Key) !== 'authz_engine')
79
+ continue;
80
+ const value = item.Value;
81
+ if (typeof value !== 'string')
82
+ continue;
83
+ if (firstValue === undefined)
84
+ firstValue = value;
85
+ const normalized = value.toLowerCase();
86
+ if (normalized === exports.AUTHZ_ENGINE.OPA || normalized === exports.AUTHZ_ENGINE.AUTHPOLICY) {
87
+ return { engine: normalized, raw: value };
88
+ }
89
+ }
90
+ return firstValue === undefined ? {} : { raw: firstValue };
91
+ }
92
+ /** 网关鉴权引擎判定值;Gateway 能力与 Permission 共用同一口径 */
93
+ function authzEngineOf(source) {
94
+ return authzEngineDetailOf(source).engine;
95
+ }
96
+ /** PG 实例名:Databases[] 里同名条目是 PG 的投影,不是老文档型租户 */
97
+ function postgresInstanceNames(source) {
98
+ const instances = asArray(source.PostgreSQL) || [];
99
+ return new Set(instances
100
+ .map(instance => instance === null || instance === void 0 ? void 0 : instance.InstanceName)
101
+ .filter((name) => typeof name === 'string' && name.length > 0));
102
+ }
103
+ /**
104
+ * 认证代际:Auth.AuthKind 现有两个确定值 —— pg-auth(v2)、supabase-auth(v3)。
105
+ * 其余(空串 / 未知)分不出传统认证,留给后端补齐,不猜。
106
+ */
107
+ function authGenerationOf(source) {
108
+ var _a;
109
+ const authKind = (_a = asRecord(source.Auth)) === null || _a === void 0 ? void 0 : _a.AuthKind;
110
+ if (authKind === 'pg-auth')
111
+ return 'v2';
112
+ if (authKind === 'supabase-auth')
113
+ return 'v3';
114
+ return undefined;
115
+ }
116
+ /**
117
+ * 由一次 DescribeEnvInfo 的返回派生能力字段。纯函数:无 IO、无缓存、不修改入参。
118
+ *
119
+ * 不新增单数顶层字段:结论挂在**现有字段**上 ——
120
+ * `Databases[]` / `Storages[]` / `Functions[]` 各条补齐同一个环境级 `Version`,
121
+ * `Auth` 对象补 `Version`。
122
+ * `Log` 用 `LogServices[]` / `CustomLogServices[]` 表达,`Hosting` 用
123
+ * `StaticStorages[].DomainType`,`CloudRun` 用 `ArchitectureType`,`Gateway` 用
124
+ * `Meta[].authz_engine` —— 这些已有字段不再派生。
125
+ *
126
+ * 返回的是 `EnvInfo` 的增量,直接 `Object.assign({}, envInfo, deriveEnvCapabilities(envInfo))`
127
+ * 即得到最终形态;接口上线后 `Version` 由后端返回,本函数删除即可。
128
+ *
129
+ * `source` 允许为 null / undefined(上游或消费方可能把整个对象传成 null,比如
130
+ * CLI / MCP 从 JSON 里取字段),此时按「什么都读不到」处理,返回空对象而不是抛错。
131
+ */
132
+ function deriveEnvCapabilities(source) {
133
+ const fields = {};
134
+ if (!source)
135
+ return fields;
136
+ // 三态:true / false / 'unknown'(两个信号源都在才敢下 false)
137
+ const pgState = postgresProvisionState(source);
138
+ // Databases:环境级代际,逐条补 Version
139
+ const databases = asArray(source.Databases);
140
+ if (databases) {
141
+ const version = databaseVersionOf(source, pgState);
142
+ fields.Databases = version
143
+ ? databases.map(item => (Object.assign(Object.assign({}, item), { Version: version })))
144
+ : databases;
145
+ }
146
+ // Storages:代际跟随 PG,逐条补 Version
147
+ const storages = asArray(source.Storages);
148
+ if (storages) {
149
+ const version = storageVersionOf(source, pgState);
150
+ fields.Storages = version
151
+ ? storages.map(item => (Object.assign(Object.assign({}, item), { Version: version })))
152
+ : storages;
153
+ }
154
+ // Functions:环境级代际,逐条补 Version
155
+ const functions = asArray(source.Functions);
156
+ if (functions) {
157
+ const version = functionVersionOf(source);
158
+ fields.Functions = version
159
+ ? functions.map(fn => (Object.assign(Object.assign({}, fn), { Version: version })))
160
+ : functions;
161
+ }
162
+ // Auth:在现有对象上补 Version
163
+ const authGeneration = authGenerationOf(source);
164
+ if (authGeneration) {
165
+ fields.Auth = Object.assign(Object.assign({}, asRecord(source.Auth)), { Version: `auth_${authGeneration}` });
166
+ }
167
+ return fields;
168
+ }
169
+ /**
170
+ * 数据库代际:pgdoc → `database_v2`;有真实老租户 → `database`。
171
+ * 两者并存时取新代(单值只能表达一态)。
172
+ */
173
+ function databaseVersionOf(source, pgState) {
174
+ if (pgState === true && documentdbOf(source) === true)
175
+ return 'database_v2';
176
+ const projected = postgresInstanceNames(source);
177
+ const databases = asArray(source.Databases) || [];
178
+ const hasTenant = databases.some(item => Boolean(item === null || item === void 0 ? void 0 : item.InstanceId) &&
179
+ (item === null || item === void 0 ? void 0 : item.Status) === 'RUNNING' &&
180
+ !projected.has(String(item.InstanceId)));
181
+ return hasTenant ? 'database' : undefined;
182
+ }
183
+ /**
184
+ * 存储代际跟随 PG(接口没有独立字段):PG 环境 → `storage_v2`;
185
+ * 非 PG 环境且有一条真实可用的桶 → `storage`;PG 状态读不到 → 不判定,
186
+ * 不把「不知道」压成「非 PG」。
187
+ */
188
+ function storageVersionOf(source, pgState) {
189
+ if (pgState === true)
190
+ return 'storage_v2';
191
+ if (pgState === false && hasRealStorageBucket(source))
192
+ return 'storage';
193
+ return undefined;
194
+ }
195
+ /**
196
+ * 云函数代际:一个环境只有一种后端,取环境级单值。
197
+ *
198
+ * 全部 `cbf` → `function_v2`,全部 `scf` → `function`;任一 `Backend` 缺失、
199
+ * 非字符串、未知值,或 cbf 与非 cbf 同时出现(理论不发生,防御性处理)→ 不判定。
200
+ * 与 databaseVersionOf / storageVersionOf 同形态:读不到就不出现,不默认成某一代。
201
+ */
202
+ function functionVersionOf(source) {
203
+ const functions = asArray(source.Functions);
204
+ if (!functions || functions.length === 0)
205
+ return undefined;
206
+ const backends = new Set();
207
+ for (const fn of functions) {
208
+ const backend = fn === null || fn === void 0 ? void 0 : fn.Backend;
209
+ if (backend !== 'cbf' && backend !== 'scf')
210
+ return undefined;
211
+ backends.add(backend);
212
+ }
213
+ if (backends.size !== 1)
214
+ return undefined;
215
+ return backends.has('cbf') ? 'function_v2' : 'function';
216
+ }
217
+ /**
218
+ * PG 开通状态的三态判定:true / false / 'unknown'。
219
+ *
220
+ * 两个信号源(PostgreSQL[] 与 Meta[])都在才敢下 false;任何一个缺失都算读不到,
221
+ * 因为 Meta[] 为空是正常值、PostgreSQL 也可能因裁剪而不返回。守卫用它区分
222
+ * 「确定不是 PG」与「读不到」,避免把未知压成 false 后误拦或误放。
223
+ *
224
+ * `source` 为 null / undefined 时同样返回 'unknown':调用方常常是 `any` 进来的一手
225
+ * 响应字段,不能假设类型上的「非空」在运行时成立。
226
+ */
227
+ function postgresProvisionState(source) {
228
+ if (!source)
229
+ return 'unknown';
230
+ if (postgresProvisioned(source))
231
+ return true;
232
+ const hasInstances = Array.isArray(source.PostgreSQL);
233
+ const hasMeta = Array.isArray(source.Meta);
234
+ return hasInstances && hasMeta ? false : 'unknown';
235
+ }
package/lib/env/index.js CHANGED
@@ -10,6 +10,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.EnvService = void 0;
13
+ exports.toEnvInfo = toEnvInfo;
13
14
  const cos_nodejs_sdk_v5_1 = __importDefault(require("cos-nodejs-sdk-v5"));
14
15
  const util_1 = __importDefault(require("util"));
15
16
  const http_request_1 = require("../utils/http-request");
@@ -20,7 +21,42 @@ const constant_1 = require("../constant");
20
21
  const storage_config_1 = require("../utils/storage-config");
21
22
  const billing_1 = require("../billing");
22
23
  const uuid_1 = require("uuid");
23
- const postgresql_1 = require("./postgresql");
24
+ const capabilities_1 = require("./capabilities");
25
+ /**
26
+ * 只接受普通对象:数组 / null / 原始值 / 类实例 / Date / Map 都视为形状异常。
27
+ *
28
+ * 原型必须是 `Object.prototype` 或 null —— 否则后面 `{ ...envBaseInfo }` 只拷贝自有
29
+ * 可枚举属性,原型上的 getter 字段会被静默丢掉,而 `as EnvBaseInfo` 又把类型风险盖住。
30
+ */
31
+ function isPlainObject(value) {
32
+ if (!value || typeof value !== 'object' || Array.isArray(value))
33
+ return false;
34
+ const proto = Object.getPrototypeOf(value);
35
+ return proto === Object.prototype || proto === null;
36
+ }
37
+ /**
38
+ * DescribeEnvInfo 响应 → 对外 EnvInfo(纯函数,无 IO)。
39
+ *
40
+ * - `EnvInfo` / `EnvBaseInfo` 缺失或形状不对 ⇒ 接口异常,直接报错,不返回「字段全默认」的假结果;
41
+ * - 展开范围仅限 EnvBaseInfo(未进类型的上游字段运行时透传,语义见 `getEnvInfo` 返回类型);
42
+ * - 数组字段做 `Array.isArray` 兜底,避免非数组值流到下游 `.map/.filter`。
43
+ */
44
+ function toEnvInfo(response, envId) {
45
+ if (!isPlainObject(response === null || response === void 0 ? void 0 : response.EnvInfo)) {
46
+ (0, error_1.throwApiError)(`获取环境 ${envId} 信息失败:DescribeEnvInfo 未返回 EnvInfo`);
47
+ }
48
+ if (!isPlainObject(response.EnvInfo.EnvBaseInfo)) {
49
+ (0, error_1.throwApiError)(`获取环境 ${envId} 信息失败:DescribeEnvInfo 未返回 EnvBaseInfo`);
50
+ }
51
+ const envBaseInfo = response.EnvInfo.EnvBaseInfo;
52
+ // 顶层可选字段「没有」时不写入属性:无条件赋值会让 `'BillingInfo' in envInfo` 恒为 true,
53
+ // 调用方无法区分「上游没返回」与「返回了 undefined」。上游用 null 表示没有的同样规范化掉 ——
54
+ // 只判 undefined 会把 null 透传下去,与类型(非空对象)和调用方的判空口径都对不上。
55
+ const { BillingInfo, UserInfo } = response.EnvInfo;
56
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, envBaseInfo), { PackageId: envBaseInfo.PackageId || '', PackageName: envBaseInfo.PackageName || '', LogServices: Array.isArray(envBaseInfo.LogServices) ? envBaseInfo.LogServices : [], CustomLogServices: Array.isArray(envBaseInfo.CustomLogServices)
57
+ ? envBaseInfo.CustomLogServices
58
+ : [], Region: envBaseInfo.Region || '' }), (BillingInfo === undefined || BillingInfo === null ? {} : { BillingInfo })), (UserInfo === undefined || UserInfo === null ? {} : { UserInfo }));
59
+ }
24
60
  class EnvService {
25
61
  constructor(environment) {
26
62
  this.environment = environment;
@@ -140,52 +176,22 @@ class EnvService {
140
176
  }
141
177
  /**
142
178
  * 获取环境信息
143
- * @returns {Promise<IEnvInfoRes>}
179
+ *
180
+ * 返回的 `EnvInfo` 除声明字段外,还会带上 `EnvBaseInfo` 里尚未进类型的上游字段
181
+ * (运行时展开透传,供 CLI `env detail --json` 等直接展示)。这条「可能多出未知键」
182
+ * 的语义写在返回类型上,`EnvInfo` 本身保持闭合,调用方按需 `Record<string, unknown>`
183
+ * 读取。
184
+ *
185
+ * @returns {Promise<{ EnvInfo: EnvInfo & Record<string, unknown>; RequestId: string }>}
144
186
  */
145
187
  async getEnvInfo() {
146
- var _a, _b;
147
188
  // 使用 DescribeEnvInfo 进行单环境查询
148
189
  const params = {
149
190
  EnvId: this.envId
150
191
  };
151
192
  const response = await this.describeEnvInfo(params);
152
- const envBaseInfo = (_a = response === null || response === void 0 ? void 0 : response.EnvInfo) === null || _a === void 0 ? void 0 : _a.EnvBaseInfo;
153
- // 将 EnvBaseInfo 完整映射到 EnvInfo 类型,避免新增字段被丢弃
154
- // UserInfo 位于 response.EnvInfo 顶层(非 EnvBaseInfo),单独映射
155
- const envInfo = {
156
- EnvId: envBaseInfo.EnvId,
157
- Alias: envBaseInfo.Alias,
158
- Status: envBaseInfo.Status,
159
- Databases: envBaseInfo.Databases,
160
- Storages: envBaseInfo.Storages,
161
- Functions: envBaseInfo.Functions,
162
- PackageId: envBaseInfo.PackageId || '',
163
- PackageName: envBaseInfo.PackageName || '',
164
- LogServices: envBaseInfo.LogServices || [],
165
- CustomLogServices: envBaseInfo.CustomLogServices || [],
166
- Region: envBaseInfo.Region || '',
167
- Source: envBaseInfo.Source,
168
- CreateTime: envBaseInfo.CreateTime,
169
- UpdateTime: envBaseInfo.UpdateTime,
170
- StaticStorages: envBaseInfo.StaticStorages,
171
- IsAutoDegrade: envBaseInfo.IsAutoDegrade,
172
- EnvChannel: envBaseInfo.EnvChannel,
173
- PayMode: envBaseInfo.PayMode,
174
- IsDefault: envBaseInfo.IsDefault,
175
- Tags: envBaseInfo.Tags,
176
- EnvType: envBaseInfo.EnvType,
177
- IsDauPackage: envBaseInfo.IsDauPackage,
178
- PackageType: envBaseInfo.PackageType,
179
- ArchitectureType: envBaseInfo.ArchitectureType,
180
- Recycle: envBaseInfo.Recycle,
181
- EnvPreferences: envBaseInfo.EnvPreferences,
182
- Meta: envBaseInfo.Meta,
183
- PostgreSQL: envBaseInfo.PostgreSQL,
184
- EnvStatus: envBaseInfo.EnvStatus,
185
- UserInfo: (_b = response === null || response === void 0 ? void 0 : response.EnvInfo) === null || _b === void 0 ? void 0 : _b.UserInfo
186
- };
187
193
  return {
188
- EnvInfo: envInfo,
194
+ EnvInfo: toEnvInfo(response, this.envId),
189
195
  RequestId: response.RequestId || ''
190
196
  };
191
197
  }
@@ -208,15 +214,21 @@ class EnvService {
208
214
  return this.cloudService.request('DescribeEnvInfo', params);
209
215
  }
210
216
  /**
211
- * 判断当前环境是否为 PostgreSQL 环境
212
- * PostgreSQL 字段为数组且长度 > 0 时视为 PG 环境
217
+ * 判断当前环境是否为 PostgreSQL 环境(布尔签名保持不变)
218
+ * 走能力结论:读不到 PG 字段时返回 false,不抛错 —— permission 依赖布尔值。
213
219
  *
214
220
  * @returns 是否为 PG 环境
215
221
  */
216
222
  async isPostgresqlEnv() {
217
- var _a;
218
- const response = await this.describeEnvInfo({ EnvId: this.envId });
219
- return (0, postgresql_1.isPostgresqlBaseInfo)((_a = response === null || response === void 0 ? void 0 : response.EnvInfo) === null || _a === void 0 ? void 0 : _a.EnvBaseInfo);
223
+ return (await this.isPostgresqlEnvStrict()) === true;
224
+ }
225
+ /**
226
+ * 严格版 PG 判定:读不到时返回 'unknown' 而不是压成 false。
227
+ * 与 isPostgresqlEnv 共用同一次 DescribeEnvInfo,不额外发请求。
228
+ */
229
+ async isPostgresqlEnvStrict() {
230
+ const { EnvInfo } = await this.getEnvInfo();
231
+ return (0, capabilities_1.postgresProvisionState)(EnvInfo);
220
232
  }
221
233
  /**
222
234
  * 修改环境名称
@@ -1,14 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isPostgresqlBaseInfo = isPostgresqlBaseInfo;
4
+ const capabilities_1 = require("./capabilities");
4
5
  /**
5
- * 判断环境基础信息是否属于 PostgreSQL 环境
6
- * PostgreSQL 字段为数组且长度 > 0 时视为 PG 环境。
6
+ * 判断环境基础信息是否属于 PostgreSQL 环境。
7
7
  *
8
- * 抽成纯函数供 EnvService 与 PermissionService 共用,避免两处各写一份判断而漂移。
9
- * 放在独立叶子模块中(只依赖类型),避免 permission 反向 import 整个 env 造成循环依赖。
8
+ * 判定口径与 `deriveEnvCapabilities()` 完全一致(`PostgreSQL[]` 非空,或 Meta 里
9
+ * postgresql/postgre_sql = enable),避免 permission 与 env 两处各写一份而漂移:
10
+ * 旧实现只看 `PostgreSQL[]`,Meta 已标记 enable 但数组被裁剪的环境会被判成非 PG。
11
+ *
12
+ * 读不到(两个信号源都缺失)时返回 false —— 调用方要区分未知请直接用
13
+ * `postgresProvisionState()`。依赖的 capabilities 是纯叶子模块(只 import 类型),
14
+ * 不会把整个 env 模块拉进 permission 造成循环依赖。
10
15
  */
11
16
  function isPostgresqlBaseInfo(baseInfo) {
12
- const postgresql = baseInfo === null || baseInfo === void 0 ? void 0 : baseInfo.PostgreSQL;
13
- return Array.isArray(postgresql) && postgresql.length > 0;
17
+ return (0, capabilities_1.postgresProvisionState)(baseInfo) === true;
14
18
  }
@@ -26,5 +26,10 @@ exports.ERROR_TYPES = {
26
26
  * 声明式部署(`tcb deploy`)不执行构建,产物必须由用户先产出;
27
27
  * 这个码让 CLI 侧能稳定映射到非零退出码并给出「先构建」的引导。
28
28
  */
29
- buildOutputNotFound: { code: 'BUILD_OUTPUT_NOT_FOUND' }
29
+ buildOutputNotFound: { code: 'BUILD_OUTPUT_NOT_FOUND' },
30
+ /**
31
+ * 环境未完成初始化(EnvId 等环境配置缺失)。
32
+ * 与「调用方传入参数非法」区分,便于上层按配置问题给出初始化指引。
33
+ */
34
+ environmentNotInitialized: { code: 'ENVIRONMENT_NOT_INITIALIZED' }
30
35
  };
package/lib/error.js CHANGED
@@ -6,6 +6,7 @@ exports.isValidErrorCode = isValidErrorCode;
6
6
  exports.isErrorSource = isErrorSource;
7
7
  exports.errorSourceOf = errorSourceOf;
8
8
  exports.throwInvalidParam = throwInvalidParam;
9
+ exports.throwEnvironmentNotInitialized = throwEnvironmentNotInitialized;
9
10
  exports.throwNotFound = throwNotFound;
10
11
  exports.throwNetError = throwNetError;
11
12
  exports.throwApiError = throwApiError;
@@ -216,6 +217,10 @@ function errorSourceOf(e) {
216
217
  function throwInvalidParam(message) {
217
218
  throw new CloudBaseError(message, { type: error_types_1.ERROR_TYPES.invalidParam });
218
219
  }
220
+ /** 环境未初始化:EnvId 等环境配置缺失,不属于调用方参数非法。 */
221
+ function throwEnvironmentNotInitialized(message) {
222
+ throw new CloudBaseError(message, { type: error_types_1.ERROR_TYPES.environmentNotInitialized });
223
+ }
219
224
  /**
220
225
  * 资源不存在错误:统一 code = NOT_FOUND + source = manager-node。
221
226
  * 用于替换 `throw new Error('xxx 不存在')` 类错误。
package/lib/index.js CHANGED
@@ -6,6 +6,7 @@ const docs_1 = require("./docs");
6
6
  const projectValidator_1 = require("./projectValidator");
7
7
  const DeployOrchestrator_1 = require("./deploy/DeployOrchestrator");
8
8
  const framework_1 = require("./deploy/framework");
9
+ const capabilities_1 = require("./env/capabilities");
9
10
  class CloudBase {
10
11
  /**
11
12
  * init 初始化 为单例
@@ -207,5 +208,14 @@ class CloudBase {
207
208
  CloudBase.resolveHostingBuildCommand = framework_1.resolveBuildCommand;
208
209
  CloudBase.resolveHostingOutputDir = framework_1.resolveHostingOutputDir;
209
210
  CloudBase.buildHosting = framework_1.buildHostingItem;
211
+ /**
212
+ * 环境能力派生(iWiki 4057912034)。判断只在 manager-node 一处实现,
213
+ * CLI / MCP 复用同一份结论;结果不写进 DescribeEnvInfo 的响应。
214
+ *
215
+ * 返回的是 `EnvInfo` 的增量,字段名与将来接口返回一致(大驼峰)。
216
+ * 均为纯函数,输入可以是 getEnvInfo() 的 EnvInfo 或裸 EnvBaseInfo。
217
+ */
218
+ CloudBase.deriveEnvCapabilities = capabilities_1.deriveEnvCapabilities;
219
+ CloudBase.postgresProvisionState = capabilities_1.postgresProvisionState;
210
220
  })(CloudBase || (CloudBase = {}));
211
221
  module.exports = CloudBase;
@@ -8,6 +8,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.PermissionService = void 0;
10
10
  const postgresql_1 = require("../env/postgresql");
11
+ const capabilities_1 = require("../env/capabilities");
11
12
  const utils_1 = require("../utils");
12
13
  const error_1 = require("../error");
13
14
  const PERMISSION_BY_RESOURCE = {
@@ -308,22 +309,35 @@ class PermissionService {
308
309
  /**
309
310
  * 查询环境实际生效的鉴权引擎
310
311
  *
311
- * 只发一次 DescribeEnvInfo,同时产出 PostgreSQL 与 Meta.authz_engine 两个结论,
312
- * 调用方无需自行解析环境 Meta。
312
+ * 两个信号,任一成立即为新网关(opa):
313
+ * - **环境类型兜底**:PG 环境没有旧网关策略,一律视为 opa(`isPostgresqlBaseInfo`);
314
+ * - `Meta[].authz_engine = opa`:非 PG 环境显式切到 OPA。
313
315
  *
314
- * 注意:不做缓存 —— 引擎由环境 Meta 的 authz_engine 决定,可能在运行期被切换,
316
+ * 为什么不能只读 `authz_engine`(数据面源码为证):
317
+ * - `tcblinker/apis/httpapi/middlewares/authpolicy.go:95`:PG 环境的旧网关策略被**无条件跳过**
318
+ * (`SkippedReason=postgresql`),与 `authz_engine` 取值无关;
319
+ * - `tcblinker/internal/tcb/envinfo/envinfo.go:573 GetAuthzEngine()`:只读 `meta[authz_engine]`,
320
+ * 缺省/未知值一律回落 `authpolicy`;
321
+ * - `tcbserver/profileserver/action/envconfig.go:150/174`:只有写 `authz.user.rego` 时才联动写
322
+ * `authz_engine=opa`,新建环境(含 PG)没有这个 Meta 项。
323
+ *
324
+ * 所以「策略记录为空」不等于「旧网关生效」:PG 环境一条策略都没写过时,旧策略照样不生效。
325
+ * 若只读后者会把它误判成 authpolicy,把 Agent 引向已退役的旧命令。
326
+ * 等后端提供独立的「当前生效鉴权引擎」字段后,再以该字段为唯一来源。
327
+ *
328
+ * 注意:不做缓存 —— 引擎由环境类型与 Meta 决定,可能在运行期被切换,
315
329
  * 缓存会让切换后的查询拿到过期结论。
316
330
  */
317
331
  async describeAuthzProfile() {
318
- var _a;
319
332
  const baseInfo = await this.getEnvBaseInfo();
333
+ // 引擎值与原始值来自同一次查找,保证两者配对(不会「首个条目写坏 → 生效值是后面那条」时错位)
334
+ const { engine: engineFromMeta, raw: authzEngineMeta } = (0, capabilities_1.authzEngineDetailOf)(baseInfo);
320
335
  const isPostgresql = (0, postgresql_1.isPostgresqlBaseInfo)(baseInfo);
321
- const authzEngineMeta = Array.isArray(baseInfo === null || baseInfo === void 0 ? void 0 : baseInfo.Meta)
322
- ? (_a = baseInfo.Meta.find(tag => tag.Key === 'authz_engine')) === null || _a === void 0 ? void 0 : _a.Value
323
- : undefined;
324
336
  return {
325
- // PG 环境不存在旧网关策略,统一视为 opa,避免与短路行为自相矛盾
326
- engine: isPostgresql || authzEngineMeta === 'opa' ? 'opa' : 'authpolicy',
337
+ // PG 兜底优先:PG 环境不存在旧网关策略,避免与短路行为自相矛盾
338
+ engine: isPostgresql || engineFromMeta === capabilities_1.AUTHZ_ENGINE.OPA
339
+ ? capabilities_1.AUTHZ_ENGINE.OPA
340
+ : capabilities_1.AUTHZ_ENGINE.AUTHPOLICY,
327
341
  isPostgresql,
328
342
  authzEngineMeta
329
343
  };
@@ -331,7 +345,7 @@ class PermissionService {
331
345
  /**
332
346
  * 拉取环境下的所有用户自定义的网关鉴权策略列表
333
347
  *
334
- * 以下两种环境不会发起请求,直接按空列表处理,并在返回值顶层给出 SkippedReason:
348
+ * 以下两种情况不发起请求,直接按空列表处理,并在返回值顶层给出 SkippedReason:
335
349
  * - PG 环境:无存量网关策略(postgresql_env)
336
350
  * - authz_engine 为 opa:网关策略不生效(opa_authz_engine)
337
351
  *
@@ -346,7 +360,7 @@ class PermissionService {
346
360
  const profile = await this.describeAuthzProfile();
347
361
  const skippedReason = profile.isPostgresql
348
362
  ? 'postgresql_env'
349
- : profile.engine === 'opa'
363
+ : profile.engine === capabilities_1.AUTHZ_ENGINE.OPA
350
364
  ? 'opa_authz_engine'
351
365
  : undefined;
352
366
  if (skippedReason) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudbase/manager-node",
3
- "version": "5.10.7",
3
+ "version": "5.10.8",
4
4
  "description": "The node manage service api for cloudbase.",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
@@ -140,6 +140,25 @@ export declare class CloudRunService {
140
140
  delete(params: {
141
141
  serverName: string;
142
142
  }): Promise<IResponseInfo>;
143
+ /**
144
+ * 两段式部署阶段 A:获取代码包上传信息。
145
+ *
146
+ * UploadUrl / UploadHeaders 由服务端签发,调用方自行 PUT 代码 zip,再把
147
+ * PackageName / PackageVersion 通过 deploy({ packageInfo }) 传回来触发部署。
148
+ * 本方法不读取本地文件,也不代替调用方发起上传。
149
+ */
150
+ getPackageUploadInfo(params: {
151
+ serverName: string;
152
+ }): Promise<{
153
+ UploadUrl: string;
154
+ UploadHeaders: Array<{
155
+ Key: string;
156
+ Value: string;
157
+ }>;
158
+ PackageName: string;
159
+ PackageVersion: string;
160
+ RequestId?: string;
161
+ }>;
143
162
  /**
144
163
  * 本地代码部署云托管服务
145
164
  * @param {Object} params 部署参数
@@ -165,12 +184,23 @@ export declare class CloudRunService {
165
184
  */
166
185
  deploy(params: {
167
186
  serverName: string;
168
- targetPath: string;
187
+ /** 本地项目目录;两段式部署(packageInfo)或镜像部署时可省略 */
188
+ targetPath?: string;
169
189
  deployInfo: {
170
190
  ReleaseType: ReleaseTypeEnum;
171
191
  };
172
192
  /** 镜像地址,传入时走镜像部署模式,无需上传代码包 */
173
193
  imageUrl?: string;
194
+ /**
195
+ * 已上传到云端的代码包(两段式部署阶段 B)。传入时跳过取地址、本地打包与上传,
196
+ * 直接用服务端签发的包名触发部署;服务配置、Items、VpcInfo 与源码部署共用同一套逻辑。
197
+ */
198
+ packageInfo?: {
199
+ PackageName: string;
200
+ PackageVersion: string;
201
+ };
202
+ /** 无本地目录时指定服务类型;两段式部署且未提供 targetPath 时必填 */
203
+ serverType?: CloudrunServerType;
174
204
  vpcInfo?: ICreateVpcInfo;
175
205
  serverConfig?: Partial<Pick<ICloudrunServerBaseConfig, 'OpenAccessTypes' | 'Cpu' | 'Mem' | 'MinNum' | 'MaxNum' | 'PolicyDetails' | 'CustomLogs' | 'EnvParams' | 'Port' | 'Dockerfile' | 'BuildDir' | 'InternalAccess' | 'InternalDomain' | 'EntryPoint' | 'Cmd' | 'InstallDependency' | 'OperationMode' | 'SessionAffinity' | 'LogType' | 'LogSetId' | 'LogTopicId' | 'LogParseType' | 'Tag' | 'TimerScale' | 'VpcConf' | 'VolumesConf' | 'PublicNetConf'>>;
176
206
  }): Promise<IResponseInfo>;
@@ -1,4 +1,20 @@
1
1
  import { SearchResult, ModuleDocs } from './types';
2
+ export declare function isHtmlBody(text: string): boolean;
3
+ /** 404 兜底页的特征:canonical 指向 404.html(或正文含「这个页面走丢了」) */
4
+ export declare function isNotFoundPage(html: string): boolean;
5
+ /**
6
+ * 将文档路径归一化为 markdown 源文件路径(`{path}.md`)
7
+ *
8
+ * 文档站按 `{path}.md` 直接给出 markdown 源文件,不再提供 `{path}/index.md`;
9
+ * 且 CDN 对缺失路径返回 HTTP 200 + 404 兜底页面(而非 404 状态码),
10
+ * 因此路径拼接错误不会触发网络错误,只会静默把整页 HTML 当文档正文返回。
11
+ *
12
+ * 这里只做形态归一,不判断文档是否存在(那要靠响应体,见 `isNotFoundPage`):
13
+ * - 文档站完整 URL → 只留 pathname(`/en/` 是真实语言站,原样保留)
14
+ * - 旧写法 `<path>/index.md`、`<path>/index` → 还原成 `<path>.md`
15
+ * - 非文档站的完整 URL → 原样透传(既有行为,调用方可能指向别的源)
16
+ */
17
+ export declare function normalizeDocPath(docPath: string): string;
2
18
  export declare class DocsService {
3
19
  listModules(): Promise<string[]>;
4
20
  /**
@@ -0,0 +1,81 @@
1
+ import { EnvInfo } from '../interfaces/tcb.interface';
2
+ /**
3
+ * 环境能力派生(中间态)。
4
+ *
5
+ * 输出形状 = `EnvInfo` 的增量:每个资源一个对象,代际用 `Version` 表达,
6
+ * 其余为明细字段(`Auth{Version,TenantType}` / `Storage{Version,DomainType,SharedBucket}` …)。
7
+ * DescribeEnvInfo 定稿后这些字段由接口直接返回,本文件整体删除,消费方无需改动。
8
+ *
9
+ * 判定规则(全部读 DescribeEnvInfo 现有字段):
10
+ * - `Database.Version`:pgdoc → database_v2;老文档型 → database(两者并存时取新代)
11
+ * - `Auth.Version`:Auth.AuthKind = pg-auth → auth_v2 / supabase-auth → auth_v3
12
+ * - `Storage.Version`:代际跟随 PG(storage_v2 / storage),互斥;PG 状态读不到时不给
13
+ * - `Hosting`:StaticStorages[] 非空;明细 DomainType
14
+ * - `Function.Version`:Functions[].Backend 全 cbf → function_v2,全 scf → function;
15
+ * 任一缺失 / 未知值或混合出现时不判定
16
+ * - `CloudRun.ArchitectureType`:EnvInfo.ArchitectureType
17
+ * - `Gateway.AuthzEngine`:Meta 有 authz_engine;遍历全部候选取第一个能判定的
18
+ * - `Log.Custom`:LogServices[] 或 CustomLogServices[] 非空
19
+ *
20
+ * 三条硬规则:
21
+ * - 读不到就不出现,不默认成某一代;
22
+ * - 每项由对应资源自己的字段判定,不从别的字段反推;唯一例外是存储代际;
23
+ * - 字段出现即表示该资源存在;枚举值沿用云 API 的大写形式。
24
+ */
25
+ /** 输入既可以是 getEnvInfo() 组装后的 EnvInfo,也可以是裸 EnvBaseInfo 快照 */
26
+ export type EnvCapabilitySource = Partial<EnvInfo>;
27
+ /**
28
+ * 鉴权引擎取值:`Meta[].authz_engine` 的原值,也是 `AuthzProfile.engine` 的取值域。
29
+ *
30
+ * 常量而非散落字符串:能力派生与 permission 共用同一份,避免后续扩枚举时漏改一处。
31
+ */
32
+ export declare const AUTHZ_ENGINE: {
33
+ readonly OPA: "opa";
34
+ readonly AUTHPOLICY: "authpolicy";
35
+ };
36
+ export type AuthzEngine = (typeof AUTHZ_ENGINE)[keyof typeof AUTHZ_ENGINE];
37
+ /**
38
+ * 网关鉴权引擎的判定值与原始值,二者取自同一次查找,保证配对
39
+ * (不会出现「首个条目写坏 → 生效值是后面那条」时错位)。
40
+ *
41
+ * - `engine`:只认文档枚举 opa / authpolicy,取第一个能判定的值;
42
+ * - `raw`:与 engine 配对的那条 Meta 原始取值;没有能判定的值时回落到
43
+ * 首条 key 匹配的原始值,便于排查「值写错了」而不是「字段没有」。
44
+ *
45
+ * 模块内导出供 PermissionService 复用(不进 CloudBase 命名空间),
46
+ * 保证 Gateway 能力与鉴权短路读的是同一个结论。
47
+ */
48
+ export declare function authzEngineDetailOf(source?: EnvCapabilitySource | null): {
49
+ engine?: AuthzEngine;
50
+ raw?: string;
51
+ };
52
+ /** 网关鉴权引擎判定值;Gateway 能力与 Permission 共用同一口径 */
53
+ export declare function authzEngineOf(source?: EnvCapabilitySource | null): AuthzEngine | undefined;
54
+ /**
55
+ * 由一次 DescribeEnvInfo 的返回派生能力字段。纯函数:无 IO、无缓存、不修改入参。
56
+ *
57
+ * 不新增单数顶层字段:结论挂在**现有字段**上 ——
58
+ * `Databases[]` / `Storages[]` / `Functions[]` 各条补齐同一个环境级 `Version`,
59
+ * `Auth` 对象补 `Version`。
60
+ * `Log` 用 `LogServices[]` / `CustomLogServices[]` 表达,`Hosting` 用
61
+ * `StaticStorages[].DomainType`,`CloudRun` 用 `ArchitectureType`,`Gateway` 用
62
+ * `Meta[].authz_engine` —— 这些已有字段不再派生。
63
+ *
64
+ * 返回的是 `EnvInfo` 的增量,直接 `Object.assign({}, envInfo, deriveEnvCapabilities(envInfo))`
65
+ * 即得到最终形态;接口上线后 `Version` 由后端返回,本函数删除即可。
66
+ *
67
+ * `source` 允许为 null / undefined(上游或消费方可能把整个对象传成 null,比如
68
+ * CLI / MCP 从 JSON 里取字段),此时按「什么都读不到」处理,返回空对象而不是抛错。
69
+ */
70
+ export declare function deriveEnvCapabilities(source?: EnvCapabilitySource | null): Partial<EnvInfo>;
71
+ /**
72
+ * PG 开通状态的三态判定:true / false / 'unknown'。
73
+ *
74
+ * 两个信号源(PostgreSQL[] 与 Meta[])都在才敢下 false;任何一个缺失都算读不到,
75
+ * 因为 Meta[] 为空是正常值、PostgreSQL 也可能因裁剪而不返回。守卫用它区分
76
+ * 「确定不是 PG」与「读不到」,避免把未知压成 false 后误拦或误放。
77
+ *
78
+ * `source` 为 null / undefined 时同样返回 'unknown':调用方常常是 `any` 进来的一手
79
+ * 响应字段,不能假设类型上的「非空」在运行时成立。
80
+ */
81
+ export declare function postgresProvisionState(source?: EnvCapabilitySource | null): boolean | 'unknown';
@@ -551,6 +551,14 @@ interface IDescribeApiKeyListRes {
551
551
  /** 总数 */
552
552
  Total?: number;
553
553
  }
554
+ /**
555
+ * DescribeEnvInfo 响应 → 对外 EnvInfo(纯函数,无 IO)。
556
+ *
557
+ * - `EnvInfo` / `EnvBaseInfo` 缺失或形状不对 ⇒ 接口异常,直接报错,不返回「字段全默认」的假结果;
558
+ * - 展开范围仅限 EnvBaseInfo(未进类型的上游字段运行时透传,语义见 `getEnvInfo` 返回类型);
559
+ * - 数组字段做 `Array.isArray` 兜底,避免非数组值流到下游 `.map/.filter`。
560
+ */
561
+ export declare function toEnvInfo(response: Partial<DescribeEnvInfoResponse> | undefined, envId: string): EnvInfo & Record<string, unknown>;
554
562
  export declare class EnvService {
555
563
  private environment;
556
564
  private envId;
@@ -618,10 +626,16 @@ export declare class EnvService {
618
626
  destroyEnvWithParams(params: DestroyEnvParams): Promise<IResponseInfo>;
619
627
  /**
620
628
  * 获取环境信息
621
- * @returns {Promise<IEnvInfoRes>}
629
+ *
630
+ * 返回的 `EnvInfo` 除声明字段外,还会带上 `EnvBaseInfo` 里尚未进类型的上游字段
631
+ * (运行时展开透传,供 CLI `env detail --json` 等直接展示)。这条「可能多出未知键」
632
+ * 的语义写在返回类型上,`EnvInfo` 本身保持闭合,调用方按需 `Record<string, unknown>`
633
+ * 读取。
634
+ *
635
+ * @returns {Promise<{ EnvInfo: EnvInfo & Record<string, unknown>; RequestId: string }>}
622
636
  */
623
637
  getEnvInfo(): Promise<{
624
- EnvInfo: EnvInfo;
638
+ EnvInfo: EnvInfo & Record<string, unknown>;
625
639
  RequestId: string;
626
640
  }>;
627
641
  /**
@@ -643,12 +657,17 @@ export declare class EnvService {
643
657
  */
644
658
  describeEnvInfo(params: DescribeEnvInfoParams): Promise<DescribeEnvInfoResponse>;
645
659
  /**
646
- * 判断当前环境是否为 PostgreSQL 环境
647
- * PostgreSQL 字段为数组且长度 > 0 时视为 PG 环境
660
+ * 判断当前环境是否为 PostgreSQL 环境(布尔签名保持不变)
661
+ * 走能力结论:读不到 PG 字段时返回 false,不抛错 —— permission 依赖布尔值。
648
662
  *
649
663
  * @returns 是否为 PG 环境
650
664
  */
651
665
  isPostgresqlEnv(): Promise<boolean>;
666
+ /**
667
+ * 严格版 PG 判定:读不到时返回 'unknown' 而不是压成 false。
668
+ * 与 isPostgresqlEnv 共用同一次 DescribeEnvInfo,不额外发请求。
669
+ */
670
+ isPostgresqlEnvStrict(): Promise<boolean | 'unknown'>;
652
671
  /**
653
672
  * 修改环境名称
654
673
  * @param {string} alias 环境名称
@@ -1,9 +1,13 @@
1
1
  import { EnvBaseInfo } from '../interfaces/tcb.interface';
2
2
  /**
3
- * 判断环境基础信息是否属于 PostgreSQL 环境
4
- * PostgreSQL 字段为数组且长度 > 0 时视为 PG 环境。
3
+ * 判断环境基础信息是否属于 PostgreSQL 环境。
5
4
  *
6
- * 抽成纯函数供 EnvService 与 PermissionService 共用,避免两处各写一份判断而漂移。
7
- * 放在独立叶子模块中(只依赖类型),避免 permission 反向 import 整个 env 造成循环依赖。
5
+ * 判定口径与 `deriveEnvCapabilities()` 完全一致(`PostgreSQL[]` 非空,或 Meta 里
6
+ * postgresql/postgre_sql = enable),避免 permission 与 env 两处各写一份而漂移:
7
+ * 旧实现只看 `PostgreSQL[]`,Meta 已标记 enable 但数组被裁剪的环境会被判成非 PG。
8
+ *
9
+ * 读不到(两个信号源都缺失)时返回 false —— 调用方要区分未知请直接用
10
+ * `postgresProvisionState()`。依赖的 capabilities 是纯叶子模块(只 import 类型),
11
+ * 不会把整个 env 模块拉进 permission 造成循环依赖。
8
12
  */
9
13
  export declare function isPostgresqlBaseInfo(baseInfo?: EnvBaseInfo): boolean;
@@ -42,6 +42,13 @@ export declare const ERROR_TYPES: {
42
42
  readonly buildOutputNotFound: {
43
43
  readonly code: "BUILD_OUTPUT_NOT_FOUND";
44
44
  };
45
+ /**
46
+ * 环境未完成初始化(EnvId 等环境配置缺失)。
47
+ * 与「调用方传入参数非法」区分,便于上层按配置问题给出初始化指引。
48
+ */
49
+ readonly environmentNotInitialized: {
50
+ readonly code: "ENVIRONMENT_NOT_INITIALIZED";
51
+ };
45
52
  };
46
53
  export type ErrorTypeName = keyof typeof ERROR_TYPES;
47
54
  export type ErrorType = (typeof ERROR_TYPES)[ErrorTypeName];
package/types/error.d.ts CHANGED
@@ -137,6 +137,8 @@ export declare function errorSourceOf(e: unknown): ErrorSource;
137
137
  * 带上稳定 code(CLI 据此映射 exitCode=3)与来源标识,而非裸 Error 兜底。
138
138
  */
139
139
  export declare function throwInvalidParam(message: string): never;
140
+ /** 环境未初始化:EnvId 等环境配置缺失,不属于调用方参数非法。 */
141
+ export declare function throwEnvironmentNotInitialized(message: string): never;
140
142
  /**
141
143
  * 资源不存在错误:统一 code = NOT_FOUND + source = manager-node。
142
144
  * 用于替换 `throw new Error('xxx 不存在')` 类错误。
package/types/index.d.ts CHANGED
@@ -27,6 +27,7 @@ import { PlatformService } from './platform';
27
27
  import { ProjectValidator } from './projectValidator';
28
28
  import { DeployOrchestrator } from './deploy/DeployOrchestrator';
29
29
  import { resolveBuildCommand as frameworkResolveBuildCommand, resolveHostingOutputDir as frameworkResolveHostingOutputDir, buildHostingItem as frameworkBuildHostingItem } from './deploy/framework';
30
+ import { deriveEnvCapabilities as envDeriveCapabilities, postgresProvisionState as envPostgresProvisionState } from './env/capabilities';
30
31
  interface CloudBaseConfig {
31
32
  secretId?: string;
32
33
  secretKey?: string;
@@ -141,5 +142,14 @@ declare namespace CloudBase {
141
142
  const resolveHostingBuildCommand: typeof frameworkResolveBuildCommand;
142
143
  const resolveHostingOutputDir: typeof frameworkResolveHostingOutputDir;
143
144
  const buildHosting: typeof frameworkBuildHostingItem;
145
+ /**
146
+ * 环境能力派生(iWiki 4057912034)。判断只在 manager-node 一处实现,
147
+ * CLI / MCP 复用同一份结论;结果不写进 DescribeEnvInfo 的响应。
148
+ *
149
+ * 返回的是 `EnvInfo` 的增量,字段名与将来接口返回一致(大驼峰)。
150
+ * 均为纯函数,输入可以是 getEnvInfo() 的 EnvInfo 或裸 EnvBaseInfo。
151
+ */
152
+ const deriveEnvCapabilities: typeof envDeriveCapabilities;
153
+ const postgresProvisionState: typeof envPostgresProvisionState;
144
154
  }
145
155
  export = CloudBase;
@@ -151,17 +151,30 @@ export interface EnvInfo {
151
151
  PostgreSQL?: PostgreSQLInfo[] | Record<string, any>;
152
152
  EnvStatus?: string;
153
153
  UserInfo?: AccountInfoInner;
154
+ BillingInfo?: EnvBillingInfoItem;
155
+ Auth?: EnvAuthCapability;
156
+ }
157
+ /**
158
+ * 身份认证能力:来源 Auth.AuthKind。
159
+ * 不新增单数顶层字段,结论直接挂在现有的 Auth 对象上。
160
+ */
161
+ export interface EnvAuthCapability {
162
+ AuthKind?: string;
163
+ Status?: number;
164
+ Version?: 'auth_v2' | 'auth_v3';
154
165
  }
155
166
  export interface FunctionInfo {
156
167
  Namespace?: string;
157
168
  Region?: string;
158
169
  Backend?: string;
170
+ Version?: 'function' | 'function_v2';
159
171
  }
160
172
  export interface DatabasesInfo {
161
173
  InstanceId?: string;
162
174
  Status?: string;
163
175
  Region?: string;
164
176
  UpdateTime?: string;
177
+ Version?: 'database' | 'database_v2';
165
178
  }
166
179
  export interface ExternalStorage {
167
180
  BucketName?: string;
@@ -181,6 +194,7 @@ export interface StorageInfo {
181
194
  ExternalStorage?: ExternalStorage;
182
195
  CustomDomain?: string;
183
196
  Status?: string;
197
+ Version?: 'storage' | 'storage_v2';
184
198
  }
185
199
  export interface StaticStorageInfo {
186
200
  StaticDomain?: string;
@@ -209,6 +223,8 @@ export interface PostgreSQLInfo {
209
223
  Status?: number;
210
224
  Region?: string;
211
225
  Version?: string;
226
+ DocumentExt?: boolean;
227
+ TenantType?: string;
212
228
  }
213
229
  export interface VoucherUseHistory {
214
230
  VoucherId?: string;
@@ -629,6 +645,10 @@ export interface EnvBaseInfo {
629
645
  Value: string;
630
646
  }>;
631
647
  PostgreSQL?: PostgreSQLInfo[] | Record<string, any>;
648
+ Auth?: {
649
+ AuthKind?: string;
650
+ Status?: number;
651
+ };
632
652
  EnvStatus?: string;
633
653
  }
634
654
  export interface AccountInfoInner {
@@ -40,17 +40,30 @@ export declare class PermissionService {
40
40
  /**
41
41
  * 查询环境实际生效的鉴权引擎
42
42
  *
43
- * 只发一次 DescribeEnvInfo,同时产出 PostgreSQL 与 Meta.authz_engine 两个结论,
44
- * 调用方无需自行解析环境 Meta。
43
+ * 两个信号,任一成立即为新网关(opa):
44
+ * - **环境类型兜底**:PG 环境没有旧网关策略,一律视为 opa(`isPostgresqlBaseInfo`);
45
+ * - `Meta[].authz_engine = opa`:非 PG 环境显式切到 OPA。
45
46
  *
46
- * 注意:不做缓存 —— 引擎由环境 Meta 的 authz_engine 决定,可能在运行期被切换,
47
+ * 为什么不能只读 `authz_engine`(数据面源码为证):
48
+ * - `tcblinker/apis/httpapi/middlewares/authpolicy.go:95`:PG 环境的旧网关策略被**无条件跳过**
49
+ * (`SkippedReason=postgresql`),与 `authz_engine` 取值无关;
50
+ * - `tcblinker/internal/tcb/envinfo/envinfo.go:573 GetAuthzEngine()`:只读 `meta[authz_engine]`,
51
+ * 缺省/未知值一律回落 `authpolicy`;
52
+ * - `tcbserver/profileserver/action/envconfig.go:150/174`:只有写 `authz.user.rego` 时才联动写
53
+ * `authz_engine=opa`,新建环境(含 PG)没有这个 Meta 项。
54
+ *
55
+ * 所以「策略记录为空」不等于「旧网关生效」:PG 环境一条策略都没写过时,旧策略照样不生效。
56
+ * 若只读后者会把它误判成 authpolicy,把 Agent 引向已退役的旧命令。
57
+ * 等后端提供独立的「当前生效鉴权引擎」字段后,再以该字段为唯一来源。
58
+ *
59
+ * 注意:不做缓存 —— 引擎由环境类型与 Meta 决定,可能在运行期被切换,
47
60
  * 缓存会让切换后的查询拿到过期结论。
48
61
  */
49
62
  describeAuthzProfile(): Promise<AuthzProfile>;
50
63
  /**
51
64
  * 拉取环境下的所有用户自定义的网关鉴权策略列表
52
65
  *
53
- * 以下两种环境不会发起请求,直接按空列表处理,并在返回值顶层给出 SkippedReason:
66
+ * 以下两种情况不发起请求,直接按空列表处理,并在返回值顶层给出 SkippedReason:
54
67
  * - PG 环境:无存量网关策略(postgresql_env)
55
68
  * - authz_engine 为 opa:网关策略不生效(opa_authz_engine)
56
69
  *
@@ -174,13 +174,14 @@ export interface ModifyEnvAuthzConfigResp {
174
174
  export interface ClearEnvAuthzConfigOptions {
175
175
  key: 'authz.user.rego';
176
176
  }
177
- /** 网关鉴权引擎 */
178
- export type AuthzEngine = 'authpolicy' | 'opa';
177
+ /** 网关鉴权引擎(取值域与能力派生层共用,见 env/capabilities 的 AUTHZ_ENGINE) */
178
+ export type { AuthzEngine } from '../env/capabilities';
179
+ import type { AuthzEngine } from '../env/capabilities';
179
180
  export interface AuthzProfile {
180
- /** 实际生效的鉴权引擎(PG 环境一律视为 opa) */
181
+ /** 实际生效的鉴权引擎:PG 环境一律 opa;非 PG 环境看 Meta[].authz_engine(缺省 / 非法值视为 authpolicy) */
181
182
  engine: AuthzEngine;
182
- /** 是否为 PostgreSQL 环境 */
183
+ /** 是否为 PostgreSQL 环境(同时作为「旧网关策略不生效」的环境类型兜底) */
183
184
  isPostgresql: boolean;
184
- /** Meta 中 authz_engine 的原始取值,便于排查 */
185
+ /** 与 engine 配对的那条 Meta 原始取值(未归一化),便于排查;没有任何能判定的值时为首条 key 匹配值 */
185
186
  authzEngineMeta?: string;
186
187
  }