taurusdb-core 0.3.0 → 0.5.0-rc.1

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -1
  3. package/dist/audit/jsonl-writer.d.ts +47 -0
  4. package/dist/audit/jsonl-writer.js +124 -0
  5. package/dist/auth/sql-profile-loader/env-source.js +10 -0
  6. package/dist/auth/sql-profile-loader/parsing.js +11 -2
  7. package/dist/auth/sql-profile-loader/runtime-override.js +10 -2
  8. package/dist/auth/sql-profile-loader/types.d.ts +5 -0
  9. package/dist/capability/probe.js +3 -1
  10. package/dist/cloud/auth.d.ts +8 -0
  11. package/dist/cloud/auth.js +61 -3
  12. package/dist/cloud/csms.d.ts +7 -0
  13. package/dist/cloud/csms.js +60 -0
  14. package/dist/cloud/keychain.d.ts +28 -0
  15. package/dist/cloud/keychain.js +200 -0
  16. package/dist/cloud/kms.d.ts +7 -0
  17. package/dist/cloud/kms.js +86 -0
  18. package/dist/config/env.js +20 -0
  19. package/dist/config/schema.d.ts +88 -0
  20. package/dist/config/schema.js +21 -0
  21. package/dist/context/datasource-resolver.js +7 -0
  22. package/dist/context/session-context.d.ts +7 -0
  23. package/dist/diagnostics/metrics-source.d.ts +3 -0
  24. package/dist/diagnostics/metrics-source.js +7 -2
  25. package/dist/diagnostics/replication-lag.d.ts +4 -0
  26. package/dist/diagnostics/replication-lag.js +138 -0
  27. package/dist/diagnostics/slow-sql-source/das-source.d.ts +3 -0
  28. package/dist/diagnostics/slow-sql-source/das-source.js +3 -0
  29. package/dist/diagnostics/slow-sql-source/factory.js +9 -2
  30. package/dist/diagnostics/slow-sql-source/taurus-api-source.d.ts +3 -0
  31. package/dist/diagnostics/slow-sql-source/taurus-api-source.js +3 -0
  32. package/dist/diagnostics/types.d.ts +5 -1
  33. package/dist/diagnostics/types.js +7 -7
  34. package/dist/engine/runtime.d.ts +2 -2
  35. package/dist/engine/runtime.js +8 -14
  36. package/dist/engine/types.d.ts +3 -2
  37. package/dist/engine.d.ts +4 -3
  38. package/dist/engine.js +44 -2
  39. package/dist/executor/bounded-sql.d.ts +1 -0
  40. package/dist/executor/bounded-sql.js +10 -0
  41. package/dist/executor/concurrency-limiter.d.ts +15 -0
  42. package/dist/executor/concurrency-limiter.js +67 -0
  43. package/dist/executor/connection-pool.d.ts +3 -2
  44. package/dist/executor/connection-pool.js +36 -24
  45. package/dist/executor/sql-executor.d.ts +3 -0
  46. package/dist/executor/sql-executor.js +52 -9
  47. package/dist/executor/types.d.ts +5 -1
  48. package/dist/index.d.ts +13 -4
  49. package/dist/index.js +7 -1
  50. package/dist/safety/confirmation-store.d.ts +30 -7
  51. package/dist/safety/confirmation-store.js +154 -30
  52. package/dist/safety/guardrail.d.ts +3 -0
  53. package/dist/safety/guardrail.js +16 -6
  54. package/dist/safety/redaction.d.ts +6 -0
  55. package/dist/safety/redaction.js +47 -6
  56. package/dist/safety/sql-classifier.d.ts +1 -0
  57. package/dist/safety/sql-classifier.js +1 -0
  58. package/dist/safety/sql-validator.d.ts +1 -0
  59. package/dist/safety/sql-validator.js +24 -0
  60. package/dist/schema/adapters/mysql.js +3 -1
  61. package/dist/taurus/flashback.js +4 -10
  62. package/dist/taurus/recycle-bin.js +2 -8
  63. package/dist/utils/formatter.d.ts +6 -2
  64. package/dist/utils/formatter.js +7 -3
  65. package/dist/utils/logger.js +8 -0
  66. package/dist/utils/mysql-identifier.d.ts +1 -0
  67. package/dist/utils/mysql-identifier.js +9 -0
  68. package/package.json +14 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TaurusDB MCP contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -4,7 +4,7 @@ Shared TaurusDB data-plane engine for:
4
4
 
5
5
  - schema discovery
6
6
  - readonly and mutation SQL execution
7
- - SQL guardrails and confirmation flow
7
+ - SQL guardrails and external operator-signed approval flow
8
8
  - TaurusDB capability detection
9
9
  - diagnostics workflows
10
10
 
@@ -19,3 +19,5 @@ npm install taurusdb-core
19
19
  - Requires Node.js `>= 20`
20
20
  - This is the shared engine package
21
21
  - Most end users should install `taurusdb-mcp` instead
22
+ - TLS verification, least-privilege credentials, bounded results, and JSONL
23
+ auditing are enabled as production safety controls
@@ -0,0 +1,47 @@
1
+ export type AuditDecision = "allowed" | "blocked" | "approval_required" | "approval_denied" | "failed";
2
+ export interface AuditEvent {
3
+ timestamp: string;
4
+ task_id: string;
5
+ tool: string;
6
+ actor: string;
7
+ datasource?: string;
8
+ database?: string;
9
+ host?: string;
10
+ port?: number;
11
+ project_id?: string;
12
+ instance_id?: string;
13
+ node_id?: string;
14
+ sql_hash?: string;
15
+ raw_sql?: string;
16
+ decision: AuditDecision;
17
+ outcome: "success" | "error";
18
+ error_code?: string;
19
+ duration_ms: number;
20
+ }
21
+ export interface AuditWriter {
22
+ write(event: AuditEvent): Promise<void>;
23
+ close(): Promise<void>;
24
+ }
25
+ export interface JsonlAuditWriterOptions {
26
+ logPath: string;
27
+ syncWrites?: boolean;
28
+ maxBytes?: number;
29
+ maxFiles?: number;
30
+ }
31
+ export declare class JsonlAuditWriter implements AuditWriter {
32
+ private handle;
33
+ private readonly logPath;
34
+ private readonly syncWrites;
35
+ private readonly maxBytes;
36
+ private readonly maxFiles;
37
+ private currentBytes;
38
+ private pending;
39
+ private closed;
40
+ private constructor();
41
+ static create(options: JsonlAuditWriterOptions): Promise<JsonlAuditWriter>;
42
+ private rotate;
43
+ private writeLine;
44
+ write(event: AuditEvent): Promise<void>;
45
+ close(): Promise<void>;
46
+ }
47
+ export declare function createJsonlAuditWriter(options: JsonlAuditWriterOptions): Promise<JsonlAuditWriter>;
@@ -0,0 +1,124 @@
1
+ import { constants } from "node:fs";
2
+ import { mkdir, open, rename, rm, } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ function expandHome(input) {
6
+ if (input === "~") {
7
+ return os.homedir();
8
+ }
9
+ return input.startsWith("~/") ? path.join(os.homedir(), input.slice(2)) : input;
10
+ }
11
+ export class JsonlAuditWriter {
12
+ handle;
13
+ logPath;
14
+ syncWrites;
15
+ maxBytes;
16
+ maxFiles;
17
+ currentBytes;
18
+ pending = Promise.resolve();
19
+ closed = false;
20
+ constructor(opened, logPath, syncWrites, maxBytes, maxFiles) {
21
+ this.handle = opened.handle;
22
+ this.currentBytes = opened.size;
23
+ this.logPath = logPath;
24
+ this.syncWrites = syncWrites;
25
+ this.maxBytes = maxBytes;
26
+ this.maxFiles = maxFiles;
27
+ }
28
+ static async create(options) {
29
+ const logPath = path.resolve(expandHome(options.logPath));
30
+ await mkdir(path.dirname(logPath), { recursive: true, mode: 0o700 });
31
+ const opened = await openAuditFile(logPath);
32
+ const maxBytes = options.maxBytes ?? 104857600;
33
+ const maxFiles = options.maxFiles ?? 10;
34
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
35
+ await opened.handle.close();
36
+ throw new Error("Audit maxBytes must be a positive safe integer.");
37
+ }
38
+ if (!Number.isSafeInteger(maxFiles) || maxFiles <= 0 || maxFiles > 100) {
39
+ await opened.handle.close();
40
+ throw new Error("Audit maxFiles must be an integer between 1 and 100.");
41
+ }
42
+ return new JsonlAuditWriter(opened, logPath, options.syncWrites ?? true, maxBytes, maxFiles);
43
+ }
44
+ async rotate() {
45
+ if (this.syncWrites) {
46
+ await this.handle.sync();
47
+ }
48
+ await this.handle.close();
49
+ try {
50
+ await rm(`${this.logPath}.${this.maxFiles}`, { force: true });
51
+ for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
52
+ const source = `${this.logPath}.${index}`;
53
+ const destination = `${this.logPath}.${index + 1}`;
54
+ try {
55
+ await rm(destination, { force: true });
56
+ await rename(source, destination);
57
+ }
58
+ catch (error) {
59
+ if (error.code !== "ENOENT") {
60
+ throw error;
61
+ }
62
+ }
63
+ }
64
+ await rm(`${this.logPath}.1`, { force: true });
65
+ await rename(this.logPath, `${this.logPath}.1`);
66
+ const opened = await openAuditFile(this.logPath);
67
+ this.handle = opened.handle;
68
+ this.currentBytes = opened.size;
69
+ }
70
+ catch (error) {
71
+ const reopened = await openAuditFile(this.logPath);
72
+ this.handle = reopened.handle;
73
+ this.currentBytes = reopened.size;
74
+ throw error;
75
+ }
76
+ }
77
+ async writeLine(line) {
78
+ const lineBytes = Buffer.byteLength(line, "utf8");
79
+ if (this.currentBytes > 0 && this.currentBytes + lineBytes > this.maxBytes) {
80
+ await this.rotate();
81
+ }
82
+ await this.handle.write(line, undefined, "utf8");
83
+ this.currentBytes += lineBytes;
84
+ if (this.syncWrites) {
85
+ await this.handle.sync();
86
+ }
87
+ }
88
+ write(event) {
89
+ if (this.closed) {
90
+ return Promise.reject(new Error("Audit writer is closed."));
91
+ }
92
+ const line = `${JSON.stringify(event)}\n`;
93
+ const next = this.pending.then(() => this.writeLine(line));
94
+ this.pending = next.catch(() => undefined);
95
+ return next;
96
+ }
97
+ async close() {
98
+ if (this.closed) {
99
+ return;
100
+ }
101
+ this.closed = true;
102
+ await this.pending;
103
+ await this.handle.close();
104
+ }
105
+ }
106
+ async function openAuditFile(logPath) {
107
+ const noFollow = typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0;
108
+ const handle = await open(logPath, constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | noFollow, 0o600);
109
+ try {
110
+ const fileStat = await handle.stat();
111
+ if (!fileStat.isFile()) {
112
+ throw new Error("Audit log target must be a regular file.");
113
+ }
114
+ await handle.chmod(0o600);
115
+ return { handle, size: fileStat.size };
116
+ }
117
+ catch (error) {
118
+ await handle.close();
119
+ throw error;
120
+ }
121
+ }
122
+ export function createJsonlAuditWriter(options) {
123
+ return JsonlAuditWriter.create(options);
124
+ }
@@ -60,6 +60,13 @@ export function parseEnvProfile(env) {
60
60
  if (!passwordRef) {
61
61
  throw new Error("Missing SQL password in environment. Set TAURUSDB_SQL_PASSWORD or include it in DSN.");
62
62
  }
63
+ const mutationUsername = asString(env.TAURUSDB_SQL_MUTATION_USER);
64
+ const mutationPasswordRef = Object.hasOwn(env, "TAURUSDB_SQL_MUTATION_PASSWORD")
65
+ ? parseCredentialRef(env.TAURUSDB_SQL_MUTATION_PASSWORD, "TAURUSDB_SQL_MUTATION_PASSWORD")
66
+ : undefined;
67
+ if ((mutationUsername && !mutationPasswordRef) || (!mutationUsername && mutationPasswordRef)) {
68
+ throw new Error("Mutation credentials require both TAURUSDB_SQL_MUTATION_USER and TAURUSDB_SQL_MUTATION_PASSWORD.");
69
+ }
63
70
  const poolSize = asInteger(env.TAURUSDB_SQL_POOL_SIZE);
64
71
  if (poolSize !== undefined && poolSize <= 0) {
65
72
  throw new Error("Invalid TAURUSDB_SQL_POOL_SIZE: must be positive.");
@@ -74,6 +81,9 @@ export function parseEnvProfile(env) {
74
81
  username,
75
82
  password: passwordRef,
76
83
  },
84
+ mutationUser: mutationUsername && mutationPasswordRef
85
+ ? { username: mutationUsername, password: mutationPasswordRef }
86
+ : undefined,
77
87
  poolSize,
78
88
  });
79
89
  }
@@ -1,4 +1,4 @@
1
- const CREDENTIAL_URI_PREFIXES = ["aws-sm:", "hw-kms:", "uri:"];
1
+ const CREDENTIAL_URI_PREFIXES = ["aws-sm:", "hw-csms:", "hw-kms:", "hw-kms-file:", "uri:"];
2
2
  const SENSITIVE_KEY_PATTERN = /(password|secret|token|credential|apikey|api_key)/i;
3
3
  export function isObject(value) {
4
4
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -190,11 +190,13 @@ export function parseProfileRecord(name, value, context) {
190
190
  throw new Error(`Invalid datasource profile ${name} in ${context}: port must be positive.`);
191
191
  }
192
192
  const database = asString(value.database);
193
+ const instanceId = asString(value.instanceId ?? value.instance_id);
194
+ const nodeId = asString(value.nodeId ?? value.node_id);
193
195
  const poolSize = asInteger(value.poolSize);
194
196
  if (poolSize !== undefined && poolSize <= 0) {
195
197
  throw new Error(`Invalid datasource profile ${name} in ${context}: poolSize must be positive.`);
196
198
  }
197
- // Backward compatibility for older profile field names. New configs should use `user`.
199
+ // `user` is the read-only credential. Keep older read-only aliases for compatibility.
198
200
  const userRaw = value.user ??
199
201
  value.readonlyUser ??
200
202
  value.readonly ??
@@ -203,6 +205,10 @@ export function parseProfileRecord(name, value, context) {
203
205
  throw new Error(`Invalid datasource profile ${name} in ${context}: missing user.`);
204
206
  }
205
207
  const user = parseUserCredential(userRaw, `${context}.${name}.user`);
208
+ const mutationUserRaw = value.mutationUser ?? value.writeUser ?? value.rwUser;
209
+ const mutationUser = mutationUserRaw === undefined
210
+ ? undefined
211
+ : parseUserCredential(mutationUserRaw, `${context}.${name}.mutationUser`);
206
212
  const tls = parseTlsOptions(value.tls, `${context}.${name}.tls`);
207
213
  return withRedactedToString({
208
214
  name,
@@ -210,7 +216,10 @@ export function parseProfileRecord(name, value, context) {
210
216
  host,
211
217
  port,
212
218
  database,
219
+ instanceId,
220
+ nodeId,
213
221
  user,
222
+ mutationUser,
214
223
  tls,
215
224
  poolSize,
216
225
  });
@@ -8,6 +8,8 @@ export function applyRuntimeTarget(profile, target) {
8
8
  host: target.host ?? profile.host,
9
9
  port: target.port ?? profile.port,
10
10
  database: target.database ?? profile.database,
11
+ instanceId: target.instanceId ?? profile.instanceId,
12
+ nodeId: target.nodeId ?? profile.nodeId,
11
13
  user: target.user ?? profile.user,
12
14
  });
13
15
  }
@@ -19,14 +21,19 @@ export class RuntimeOverrideProfileLoader {
19
21
  }
20
22
  setRuntimeTarget(name, target) {
21
23
  const current = this.runtimeTargets.get(name);
24
+ const targetChanged = (target.host !== undefined && target.host !== current?.host) ||
25
+ (target.instanceId !== undefined && target.instanceId !== current?.instanceId);
26
+ const user = target.user ?? (targetChanged ? undefined : current?.user);
22
27
  const next = {
23
28
  host: target.host ?? current?.host,
24
29
  port: target.port ?? current?.port,
25
30
  database: target.database ?? current?.database,
26
- user: target.user ?? current?.user,
27
31
  instanceId: target.instanceId ?? current?.instanceId,
28
32
  nodeId: target.nodeId ?? current?.nodeId,
29
33
  };
34
+ if (user) {
35
+ next.user = user;
36
+ }
30
37
  this.runtimeTargets.set(name, next);
31
38
  }
32
39
  clearRuntimeUser(name) {
@@ -44,7 +51,8 @@ export class RuntimeOverrideProfileLoader {
44
51
  this.runtimeTargets.clear();
45
52
  }
46
53
  getRuntimeTarget(name) {
47
- return this.runtimeTargets.get(name);
54
+ const target = this.runtimeTargets.get(name);
55
+ return target ? { ...target } : undefined;
48
56
  }
49
57
  async load() {
50
58
  const loaded = await this.base.load();
@@ -31,7 +31,12 @@ export interface DataSourceProfile {
31
31
  host?: string;
32
32
  port: number;
33
33
  database?: string;
34
+ instanceId?: string;
35
+ nodeId?: string;
36
+ /** Read-only credential used by discovery, diagnostics, and query tools. */
34
37
  user?: UserCredential;
38
+ /** Separate credential required for mutation tools. No fallback is allowed. */
39
+ mutationUser?: UserCredential;
35
40
  tls?: TlsOptions;
36
41
  poolSize?: number;
37
42
  toString(): string;
@@ -111,7 +111,9 @@ export class CapabilityProbeImpl {
111
111
  this.connectionPool = options.connectionPool;
112
112
  }
113
113
  async probe(ctx) {
114
- const session = await this.connectionPool.acquire(ctx.datasource, "ro");
114
+ const session = await this.connectionPool.acquire(ctx.datasource, "ro", {
115
+ database: ctx.database,
116
+ });
115
117
  try {
116
118
  const variables = await collectVariables(session);
117
119
  const kernelInfo = await detectKernelInfo(session, variables);
@@ -9,7 +9,15 @@ export interface HuaweiCloudAuthOptions {
9
9
  domainSuffix?: string;
10
10
  iamEndpoint?: string;
11
11
  language?: "en-us" | "zh-cn";
12
+ allowedEndpointHosts?: string[];
13
+ credentialProvider?: HuaweiCloudCredentialProvider;
12
14
  }
15
+ export interface HuaweiCloudCredentials {
16
+ accessKeyId: string;
17
+ secretAccessKey: string;
18
+ securityToken?: string;
19
+ }
20
+ export type HuaweiCloudCredentialProvider = () => Promise<HuaweiCloudCredentials>;
13
21
  export interface FetchHuaweiCloudOptions {
14
22
  url: string;
15
23
  method?: string;
@@ -1,7 +1,26 @@
1
1
  import { createHash, createHmac } from "node:crypto";
2
+ import { createSystemCredentialProvider } from "./keychain.js";
2
3
  function readString(value) {
3
4
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
4
5
  }
6
+ function validateHuaweiCloudUrl(url, auth) {
7
+ if (url.protocol !== "https:") {
8
+ throw new Error("Huawei Cloud API endpoints must use HTTPS.");
9
+ }
10
+ if (url.username || url.password) {
11
+ throw new Error("Huawei Cloud API endpoints must not contain credentials.");
12
+ }
13
+ const hostname = url.hostname.toLowerCase().replace(/\.$/, "");
14
+ const suffix = (readString(auth.domainSuffix) ?? "myhuaweicloud.com")
15
+ .toLowerCase()
16
+ .replace(/^\.+|\.+$/g, "");
17
+ const explicitHosts = new Set((auth.allowedEndpointHosts ?? []).map((host) => host.toLowerCase().replace(/\.$/, "")));
18
+ if (hostname !== suffix &&
19
+ !hostname.endsWith(`.${suffix}`) &&
20
+ !explicitHosts.has(hostname)) {
21
+ throw new Error(`Huawei Cloud API endpoint host is not allowed: ${hostname}.`);
22
+ }
23
+ }
5
24
  function sha256Hex(value) {
6
25
  return createHash("sha256").update(value, "utf8").digest("hex");
7
26
  }
@@ -87,6 +106,7 @@ export async function fetchHuaweiCloud(options) {
87
106
  const fetchImpl = options.fetchImpl ?? fetch;
88
107
  const method = options.method ?? "GET";
89
108
  const url = new URL(options.url);
109
+ validateHuaweiCloudUrl(url, options.auth);
90
110
  const body = options.body ?? "";
91
111
  const authToken = readString(options.auth.authToken);
92
112
  const headers = new Headers(options.headers);
@@ -98,9 +118,21 @@ export async function fetchHuaweiCloud(options) {
98
118
  body: options.body,
99
119
  });
100
120
  }
101
- const { accessKeyId, secretAccessKey } = requireAksk(options.auth);
121
+ const providerCredentials = (!readString(options.auth.accessKeyId) ||
122
+ !readString(options.auth.secretAccessKey)) &&
123
+ options.auth.credentialProvider
124
+ ? await options.auth.credentialProvider()
125
+ : undefined;
126
+ const resolvedAuth = {
127
+ ...options.auth,
128
+ accessKeyId: readString(options.auth.accessKeyId) ?? providerCredentials?.accessKeyId,
129
+ secretAccessKey: readString(options.auth.secretAccessKey) ??
130
+ providerCredentials?.secretAccessKey,
131
+ securityToken: readString(options.auth.securityToken) ?? providerCredentials?.securityToken,
132
+ };
133
+ const { accessKeyId, secretAccessKey } = requireAksk(resolvedAuth);
102
134
  const sdkDate = formatSdkDate(new Date());
103
- const headerMap = buildHeaderMap(headers, url, sdkDate, readString(options.auth.securityToken));
135
+ const headerMap = buildHeaderMap(headers, url, sdkDate, readString(resolvedAuth.securityToken));
104
136
  headerMap.set("authorization", buildAuthorization(method, url, headerMap, body, accessKeyId, secretAccessKey));
105
137
  return fetchImpl(url, {
106
138
  method,
@@ -169,6 +201,12 @@ export async function resolveHuaweiCloudProjectId(auth, fetchImpl) {
169
201
  throw new Error(`Unable to resolve project id for region ${region}. Set TAURUSDB_CLOUD_PROJECT_ID explicitly or restrict the account to a single visible project in that region.`);
170
202
  }
171
203
  export function getHuaweiCloudAuthFromConfig(config) {
204
+ const credentialProvider = config.cloud?.keychainService
205
+ ? createSystemCredentialProvider({
206
+ service: config.cloud.keychainService,
207
+ account: config.cloud.keychainAccount,
208
+ })
209
+ : undefined;
172
210
  return {
173
211
  region: config.cloud?.region,
174
212
  projectId: config.cloud?.projectId,
@@ -179,10 +217,30 @@ export function getHuaweiCloudAuthFromConfig(config) {
179
217
  domainSuffix: config.cloud?.domainSuffix,
180
218
  iamEndpoint: config.cloud?.iamEndpoint,
181
219
  language: config.cloud?.language,
220
+ allowedEndpointHosts: [
221
+ config.cloud?.apiEndpoint,
222
+ config.cloud?.iamEndpoint,
223
+ config.cloud?.kmsEndpoint,
224
+ config.cloud?.csmsEndpoint,
225
+ config.slowSqlSource?.taurusApi?.endpoint,
226
+ config.slowSqlSource?.das?.endpoint,
227
+ config.metricsSource?.ces?.endpoint,
228
+ ]
229
+ .filter((value) => Boolean(value))
230
+ .flatMap((value) => {
231
+ try {
232
+ return [new URL(value).hostname];
233
+ }
234
+ catch {
235
+ return [];
236
+ }
237
+ }),
238
+ credentialProvider,
182
239
  };
183
240
  }
184
241
  export function hasHuaweiCloudCredentialAuth(config) {
185
- return canAuthenticateHuaweiCloudRequests(getHuaweiCloudAuthFromConfig(config));
242
+ return Boolean(config.cloud?.keychainService ||
243
+ canAuthenticateHuaweiCloudRequests(getHuaweiCloudAuthFromConfig(config)));
186
244
  }
187
245
  export function inferHuaweiCloudRegionFromEndpoint(endpoint) {
188
246
  const normalized = readString(endpoint);
@@ -0,0 +1,7 @@
1
+ import type { UriSecretResolver } from "../auth/secret-resolver.js";
2
+ import type { Config } from "../config/index.js";
3
+ export type HuaweiCsmsSecretResolverOptions = {
4
+ config: Config;
5
+ fetchImpl?: typeof fetch;
6
+ };
7
+ export declare function createHuaweiCsmsSecretResolver(options: HuaweiCsmsSecretResolverOptions): UriSecretResolver;
@@ -0,0 +1,60 @@
1
+ import { fetchHuaweiCloud, getHuaweiCloudAuthFromConfig, resolveHuaweiCloudProjectId, } from "./auth.js";
2
+ function readString(value) {
3
+ return typeof value === "string" && value.length > 0 ? value : undefined;
4
+ }
5
+ function readSecretName(uri) {
6
+ if (!uri.startsWith("hw-csms:")) {
7
+ throw new Error(`Unsupported Huawei CSMS credential reference: ${uri}`);
8
+ }
9
+ const secretName = decodeURIComponent(uri.slice("hw-csms:".length).trim());
10
+ if (!secretName) {
11
+ throw new Error("Huawei CSMS credential reference is missing a secret name.");
12
+ }
13
+ return secretName;
14
+ }
15
+ function parseSecretString(payload) {
16
+ const record = payload && typeof payload === "object" && !Array.isArray(payload)
17
+ ? payload
18
+ : {};
19
+ const version = record.version && typeof record.version === "object" && !Array.isArray(record.version)
20
+ ? record.version
21
+ : {};
22
+ const secretString = readString(version.secret_string);
23
+ if (!secretString) {
24
+ throw new Error("Huawei CSMS response did not include version.secret_string.");
25
+ }
26
+ return secretString;
27
+ }
28
+ export function createHuaweiCsmsSecretResolver(options) {
29
+ const auth = getHuaweiCloudAuthFromConfig(options.config);
30
+ const endpoint = options.config.cloud.csmsEndpoint?.replace(/\/+$/g, "");
31
+ const fetchImpl = options.fetchImpl ?? fetch;
32
+ return async (uri) => {
33
+ if (!endpoint) {
34
+ throw new Error("Huawei CSMS endpoint is not configured. Set TAURUSDB_CLOUD_REGION or TAURUSDB_CLOUD_CSMS_ENDPOINT.");
35
+ }
36
+ const [secretName, projectId] = await Promise.all([
37
+ Promise.resolve(readSecretName(uri)),
38
+ resolveHuaweiCloudProjectId(auth, fetchImpl),
39
+ ]);
40
+ if (!projectId) {
41
+ throw new Error("Huawei CSMS request could not resolve a project id. Set TAURUSDB_CLOUD_PROJECT_ID or configure region plus Huawei Cloud credentials.");
42
+ }
43
+ const response = await fetchHuaweiCloud({
44
+ url: `${endpoint}/v1/${encodeURIComponent(projectId)}/secrets/${encodeURIComponent(secretName)}/versions/latest`,
45
+ headers: { "content-type": "application/json" },
46
+ auth,
47
+ fetchImpl,
48
+ });
49
+ const payload = (await response.json().catch(() => ({})));
50
+ if (!response.ok) {
51
+ const record = payload && typeof payload === "object" && !Array.isArray(payload)
52
+ ? payload
53
+ : {};
54
+ const code = readString(record.error_code) ?? readString(record.code);
55
+ const message = readString(record.error_msg) ?? readString(record.message);
56
+ throw new Error(`Huawei CSMS request failed with status ${response.status}${code ? ` (${code})` : ""}${message ? `: ${message}` : ""}.`);
57
+ }
58
+ return parseSecretString(payload);
59
+ };
60
+ }
@@ -0,0 +1,28 @@
1
+ import type { HuaweiCloudCredentialProvider } from "./auth.js";
2
+ export type MacOsKeychainCredentialProviderOptions = {
3
+ service: string;
4
+ account?: string;
5
+ platform?: NodeJS.Platform;
6
+ readPassword?: (service: string, account: string) => Promise<string | undefined>;
7
+ };
8
+ export type LinuxSecretServiceCredentialProviderOptions = {
9
+ service: string;
10
+ account?: string;
11
+ platform?: NodeJS.Platform;
12
+ readPassword?: (service: string, account: string, key: string) => Promise<string | undefined>;
13
+ };
14
+ export type WindowsCredentialManagerProviderOptions = {
15
+ service: string;
16
+ account?: string;
17
+ platform?: NodeJS.Platform;
18
+ readPassword?: (service: string, account: string, key: string) => Promise<string | undefined>;
19
+ };
20
+ export type SystemCredentialProviderOptions = {
21
+ service: string;
22
+ account?: string;
23
+ platform?: NodeJS.Platform;
24
+ };
25
+ export declare function createMacOsKeychainCredentialProvider(options: MacOsKeychainCredentialProviderOptions): HuaweiCloudCredentialProvider;
26
+ export declare function createLinuxSecretServiceCredentialProvider(options: LinuxSecretServiceCredentialProviderOptions): HuaweiCloudCredentialProvider;
27
+ export declare function createWindowsCredentialManagerProvider(options: WindowsCredentialManagerProviderOptions): HuaweiCloudCredentialProvider;
28
+ export declare function createSystemCredentialProvider(options: SystemCredentialProviderOptions): HuaweiCloudCredentialProvider;