@lightdash-tools/common 0.8.0 → 0.11.0

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 (49) hide show
  1. package/dist/audit.d.ts +29 -8
  2. package/dist/audit.js +53 -9
  3. package/dist/audit.test.js +51 -24
  4. package/dist/env.d.ts +1 -1
  5. package/dist/env.js +2 -2
  6. package/dist/operations/ai-agents.js +108 -40
  7. package/dist/operations/cli-content.js +6 -8
  8. package/dist/operations/client-coverage.d.ts +7 -0
  9. package/dist/operations/client-coverage.js +13 -4
  10. package/dist/operations/content-developer.js +19 -5
  11. package/dist/operations/content-governance.js +1 -1
  12. package/dist/operations/content-reader.js +19 -4
  13. package/dist/operations/data-analyst.d.ts +5 -0
  14. package/dist/operations/data-analyst.js +23 -0
  15. package/dist/operations/index.d.ts +2 -1
  16. package/dist/operations/index.js +4 -1
  17. package/dist/operations/organization-audit.js +1 -1
  18. package/dist/operations/registry.d.ts +5 -5
  19. package/dist/operations/registry.js +35 -9
  20. package/dist/operations/registry.test.js +23 -45
  21. package/dist/operations/semantic-layer.js +8 -7
  22. package/dist/operations/types.d.ts +10 -6
  23. package/dist/operations/types.js +23 -14
  24. package/dist/operations/types.test.js +14 -5
  25. package/dist/operations/users.js +3 -5
  26. package/dist/safety.d.ts +3 -2
  27. package/dist/safety.js +11 -3
  28. package/dist/safety.test.js +29 -6
  29. package/package.json +1 -1
  30. package/src/audit.test.ts +70 -30
  31. package/src/audit.ts +78 -11
  32. package/src/env.ts +1 -1
  33. package/src/operations/ai-agents.ts +113 -41
  34. package/src/operations/cli-content.ts +7 -10
  35. package/src/operations/client-coverage.ts +14 -5
  36. package/src/operations/content-developer.ts +23 -7
  37. package/src/operations/content-governance.ts +3 -3
  38. package/src/operations/content-reader.ts +23 -7
  39. package/src/operations/data-analyst.ts +27 -0
  40. package/src/operations/index.ts +3 -1
  41. package/src/operations/organization-audit.ts +2 -2
  42. package/src/operations/registry.test.ts +31 -52
  43. package/src/operations/registry.ts +42 -12
  44. package/src/operations/semantic-layer.ts +9 -8
  45. package/src/operations/types.test.ts +34 -6
  46. package/src/operations/types.ts +41 -31
  47. package/src/operations/users.ts +4 -7
  48. package/src/safety.test.ts +32 -6
  49. package/src/safety.ts +15 -4
@@ -6,7 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.SEMANTIC_LAYER_OPERATIONS = void 0;
7
7
  const safety_1 = require("../safety");
8
8
  const types_1 = require("./types");
9
- const PROFILE_SEMANTIC = 'semantic-discovery';
9
+ const PROFILE_SEMANTIC = 'semantic-layer';
10
+ const PROFILE_DATA_ANALYST = 'data-analyst';
10
11
  const API_V1 = '/api/v1';
11
12
  const listProjects = (0, types_1.defineOperation)({
12
13
  id: 'semantic.projects.list',
@@ -34,7 +35,7 @@ const getProject = (0, types_1.defineOperation)({
34
35
  taskSupport: { exposed: true, taskEligible: false },
35
36
  },
36
37
  cli: { commandPath: 'projects get' },
37
- profiles: [PROFILE_SEMANTIC, 'content-reader', 'content-developer'],
38
+ profiles: [PROFILE_SEMANTIC, 'content-reader', 'content-developer', PROFILE_DATA_ANALYST],
38
39
  });
39
40
  const listExplores = (0, types_1.defineOperation)({
40
41
  id: 'semantic.explores.list',
@@ -48,7 +49,7 @@ const listExplores = (0, types_1.defineOperation)({
48
49
  taskSupport: { exposed: true, taskEligible: false },
49
50
  },
50
51
  cli: { commandPath: 'projects explores list' },
51
- profiles: [PROFILE_SEMANTIC],
52
+ profiles: [PROFILE_SEMANTIC, PROFILE_DATA_ANALYST],
52
53
  });
53
54
  const getExplore = (0, types_1.defineOperation)({
54
55
  id: 'semantic.explores.get',
@@ -62,7 +63,7 @@ const getExplore = (0, types_1.defineOperation)({
62
63
  taskSupport: { exposed: true, taskEligible: false },
63
64
  },
64
65
  cli: { commandPath: 'projects explores get' },
65
- profiles: [PROFILE_SEMANTIC],
66
+ profiles: [PROFILE_SEMANTIC, PROFILE_DATA_ANALYST],
66
67
  });
67
68
  const listDimensions = (0, types_1.defineOperation)({
68
69
  id: 'semantic.explores.list_dimensions',
@@ -76,7 +77,7 @@ const listDimensions = (0, types_1.defineOperation)({
76
77
  taskSupport: { exposed: true, taskEligible: false },
77
78
  },
78
79
  cli: { commandPath: 'projects explores dimensions' },
79
- profiles: [PROFILE_SEMANTIC],
80
+ profiles: [PROFILE_SEMANTIC, PROFILE_DATA_ANALYST],
80
81
  });
81
82
  const getFieldLineage = (0, types_1.defineOperation)({
82
83
  id: 'semantic.explores.get_field_lineage',
@@ -104,7 +105,7 @@ const listMetrics = (0, types_1.defineOperation)({
104
105
  taskSupport: { exposed: true, taskEligible: false },
105
106
  },
106
107
  cli: { commandPath: 'metrics list' },
107
- profiles: [PROFILE_SEMANTIC],
108
+ profiles: [PROFILE_SEMANTIC, PROFILE_DATA_ANALYST],
108
109
  });
109
110
  const getMetric = (0, types_1.defineOperation)({
110
111
  id: 'semantic.metrics.get',
@@ -138,7 +139,7 @@ const compileQuery = (0, types_1.defineOperation)({
138
139
  taskSupport: { exposed: true, taskEligible: false },
139
140
  },
140
141
  cli: { commandPath: 'query compile' },
141
- profiles: [PROFILE_SEMANTIC],
142
+ profiles: [PROFILE_SEMANTIC, PROFILE_DATA_ANALYST],
142
143
  });
143
144
  /** Semantic-layer operations registered in the shared operation catalog. */
144
145
  exports.SEMANTIC_LAYER_OPERATIONS = [
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Shared typed operation catalog (ADR-0013).
2
+ * Shared typed operation catalog (ADR-0013 / ADR-0006).
3
3
  * Single source of truth for HTTP, CLI, and MCP exposure of Lightdash API operations.
4
4
  */
5
5
  import type { SafetyImpact, ToolAnnotations } from '../safety';
@@ -8,10 +8,10 @@ export type { SafetyImpact };
8
8
  export type AgentExposure = 'agent' | 'client-only';
9
9
  /** HTTP verbs supported by registered operations. */
10
10
  export type HttpMethod = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
11
- /**
12
- * Capability profiles group operations for selective exposure (CLI profiles, MCP subsets).
13
- */
14
- export type CapabilityProfile = 'content-developer' | 'content-governance' | 'content-reader' | 'conversations' | 'core-lifecycle' | 'discovery-readonly' | 'evaluations' | 'org-audit-readonly' | 'semantic-discovery';
11
+ /** Runtime list of every MCP serving profile id (ADR-0006; fixed mounts / stdio). */
12
+ export declare const PROFILE_IDS: readonly ["ai-agent-ops", "content-developer", "content-governance", "content-reader", "data-analyst", "organization-audit", "semantic-layer"];
13
+ /** MCP serving profile ids aligned to fixed HTTP mounts / stdio subcommands (ADR-0006). */
14
+ export type ProfileId = (typeof PROFILE_IDS)[number];
15
15
  /**
16
16
  * MCP response sensitivity class (ADR-0011).
17
17
  * Documents which redaction class handlers must apply; does not auto-redact.
@@ -62,7 +62,11 @@ export type OperationDescriptor = {
62
62
  * Defaults to `none` when omitted from `defineOperation` input.
63
63
  */
64
64
  sensitivity: SensitivityClass;
65
- profiles: readonly CapabilityProfile[];
65
+ /**
66
+ * MCP mounts that expose this op when `mcp.taskSupport.exposed` is true (ADR-0006).
67
+ * Empty when the op is not MCP-exposed (CLI-only / reserved / client-only).
68
+ */
69
+ profiles: readonly ProfileId[];
66
70
  /** `agent` (default) = may appear on MCP and/or CLI; `client-only` = typed client only. */
67
71
  agentExposure: AgentExposure;
68
72
  /** Present when the operation is registered (or reserved) as an MCP tool. */
@@ -1,21 +1,22 @@
1
1
  "use strict";
2
2
  /**
3
- * Shared typed operation catalog (ADR-0013).
3
+ * Shared typed operation catalog (ADR-0013 / ADR-0006).
4
4
  * Single source of truth for HTTP, CLI, and MCP exposure of Lightdash API operations.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.PROFILE_IDS = void 0;
7
8
  exports.defineOperation = defineOperation;
8
- const VALID_PROFILES = new Set([
9
+ /** Runtime list of every MCP serving profile id (ADR-0006; fixed mounts / stdio). */
10
+ exports.PROFILE_IDS = [
11
+ 'ai-agent-ops',
9
12
  'content-developer',
10
13
  'content-governance',
11
14
  'content-reader',
12
- 'conversations',
13
- 'core-lifecycle',
14
- 'discovery-readonly',
15
- 'evaluations',
16
- 'org-audit-readonly',
17
- 'semantic-discovery',
18
- ]);
15
+ 'data-analyst',
16
+ 'organization-audit',
17
+ 'semantic-layer',
18
+ ];
19
+ const VALID_PROFILES = new Set(exports.PROFILE_IDS);
19
20
  const VALID_SENSITIVITY = new Set([
20
21
  'none',
21
22
  'pii.email',
@@ -44,15 +45,23 @@ function validateIdempotentHint(annotations, impact, id) {
44
45
  throw new Error(`Operation '${id}': destructive operations must not set mcp.annotations.idempotentHint = true`);
45
46
  }
46
47
  }
47
- function validateProfiles(id, profiles) {
48
- if (profiles.length === 0) {
49
- throw new Error(`Operation '${id}' must declare at least one capability profile`);
48
+ function validateProfiles(input) {
49
+ const { id, profiles, mcp } = input;
50
+ const mcpExposed = (mcp === null || mcp === void 0 ? void 0 : mcp.taskSupport.exposed) === true;
51
+ if (mcpExposed && profiles.length === 0) {
52
+ throw new Error(`Operation '${id}' must declare at least one profile when mcp.taskSupport.exposed is true`);
53
+ }
54
+ if (new Set(profiles).size !== profiles.length) {
55
+ throw new Error(`Operation '${id}' has duplicate profiles: ${profiles.join(', ')}`);
50
56
  }
51
57
  for (const profile of profiles) {
52
58
  if (!VALID_PROFILES.has(profile)) {
53
- throw new Error(`Operation '${id}' has unknown capability profile '${profile}'`);
59
+ throw new Error(`Operation '${id}' has unknown profile '${profile}'`);
54
60
  }
55
61
  }
62
+ if (!mcpExposed && profiles.length > 0) {
63
+ throw new Error(`Operation '${id}' must use empty profiles when not MCP-exposed (got ${profiles.join(', ')})`);
64
+ }
56
65
  }
57
66
  function validateClientOnlyOperation(input) {
58
67
  var _a;
@@ -88,7 +97,7 @@ function defineOperation(input) {
88
97
  if (!VALID_SENSITIVITY.has(sensitivity)) {
89
98
  throw new Error(`Operation '${input.id}' has unknown sensitivity '${String(sensitivity)}'`);
90
99
  }
91
- validateProfiles(input.id, input.profiles);
100
+ validateProfiles(input);
92
101
  const agentExposure = (_b = input.agentExposure) !== null && _b !== void 0 ? _b : 'agent';
93
102
  if (agentExposure === 'client-only') {
94
103
  return validateClientOnlyOperation(Object.assign(Object.assign({}, input), { sensitivity }));
@@ -31,7 +31,7 @@ const baseDescriptor = {
31
31
  },
32
32
  cli: { commandPath: 'test op' },
33
33
  agentExposure: 'agent',
34
- profiles: ['discovery-readonly'],
34
+ profiles: ['semantic-layer'],
35
35
  };
36
36
  (0, vitest_1.describe)('defineOperation', () => {
37
37
  (0, vitest_1.it)('accepts a valid read descriptor', () => {
@@ -53,19 +53,28 @@ const baseDescriptor = {
53
53
  (0, vitest_1.it)('allows agent ops with cli only', () => {
54
54
  const { mcp: _mcp } = baseDescriptor, rest = __rest(baseDescriptor, ["mcp"]);
55
55
  void _mcp;
56
- (0, vitest_1.expect)((0, types_1.defineOperation)(rest).mcp).toBeUndefined();
56
+ (0, vitest_1.expect)((0, types_1.defineOperation)(Object.assign(Object.assign({}, rest), { profiles: [] })).mcp).toBeUndefined();
57
57
  });
58
58
  (0, vitest_1.it)('rejects agent ops with neither mcp nor cli', () => {
59
59
  const { mcp: _mcp, cli: _cli } = baseDescriptor, rest = __rest(baseDescriptor, ["mcp", "cli"]);
60
60
  void _mcp;
61
61
  void _cli;
62
- (0, vitest_1.expect)(() => (0, types_1.defineOperation)(rest)).toThrow(/require mcp and\/or cli/);
62
+ (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, rest), { profiles: [] }))).toThrow(/require mcp and\/or cli/);
63
63
  });
64
64
  (0, vitest_1.it)('rejects empty id', () => {
65
65
  (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, baseDescriptor), { id: ' ' }))).toThrow(/id/);
66
66
  });
67
67
  (0, vitest_1.it)('rejects unknown profile', () => {
68
- (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, baseDescriptor), { profiles: ['unknown-profile'] }))).toThrow(/unknown capability profile/);
68
+ (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, baseDescriptor), { profiles: ['unknown-profile'] }))).toThrow(/unknown profile/);
69
+ });
70
+ (0, vitest_1.it)('rejects empty profiles when MCP-exposed', () => {
71
+ (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, baseDescriptor), { profiles: [] }))).toThrow(/at least one profile/);
72
+ });
73
+ (0, vitest_1.it)('rejects duplicate profiles', () => {
74
+ (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, baseDescriptor), { profiles: ['semantic-layer', 'semantic-layer'] }))).toThrow(/duplicate profiles/);
75
+ });
76
+ (0, vitest_1.it)('rejects non-empty profiles when not MCP-exposed', () => {
77
+ (0, vitest_1.expect)(() => (0, types_1.defineOperation)(Object.assign(Object.assign({}, baseDescriptor), { mcp: Object.assign(Object.assign({}, baseDescriptor.mcp), { taskSupport: { exposed: false, taskEligible: false } }), profiles: ['semantic-layer'] }))).toThrow(/empty profiles/);
69
78
  });
70
79
  (0, vitest_1.it)('allows read operation with idempotentHint false (transient execution)', () => {
71
80
  var _a;
@@ -83,7 +92,7 @@ const baseDescriptor = {
83
92
  authorization: { safetyImpact: 'write-destructive' },
84
93
  agentExposure: 'client-only',
85
94
  bannedMcpToolName: 'delete_test',
86
- profiles: ['discovery-readonly'],
95
+ profiles: [],
87
96
  });
88
97
  (0, vitest_1.expect)(op.agentExposure).toBe('client-only');
89
98
  (0, vitest_1.expect)(op.bannedMcpToolName).toBe('delete_test');
@@ -6,8 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.USER_OPERATIONS = void 0;
7
7
  const safety_1 = require("../safety");
8
8
  const types_1 = require("./types");
9
- const PROFILE_DISCOVERY = 'discovery-readonly';
10
- const PROFILE_CORE_LIFECYCLE = 'core-lifecycle';
11
9
  const API_V1 = '/api/v1';
12
10
  const MEMBERS_PATH = `${API_V1}/org/users`;
13
11
  const MEMBER_PATH = `${MEMBERS_PATH}/{userUuid}`;
@@ -24,7 +22,7 @@ const membersList = (0, types_1.defineOperation)({
24
22
  taskSupport: { exposed: false, taskEligible: false },
25
23
  },
26
24
  cli: { commandPath: 'users list' },
27
- profiles: [PROFILE_DISCOVERY],
25
+ profiles: [],
28
26
  });
29
27
  const membersGet = (0, types_1.defineOperation)({
30
28
  id: 'users.members.get',
@@ -38,7 +36,7 @@ const membersGet = (0, types_1.defineOperation)({
38
36
  taskSupport: { exposed: false, taskEligible: false },
39
37
  },
40
38
  cli: { commandPath: 'users get' },
41
- profiles: [PROFILE_DISCOVERY],
39
+ profiles: [],
42
40
  });
43
41
  const membersDelete = (0, types_1.defineOperation)({
44
42
  id: 'users.members.delete',
@@ -48,7 +46,7 @@ const membersDelete = (0, types_1.defineOperation)({
48
46
  sensitivity: 'none',
49
47
  agentExposure: 'client-only',
50
48
  bannedMcpToolName: 'delete_member',
51
- profiles: [PROFILE_CORE_LIFECYCLE],
49
+ profiles: [],
52
50
  });
53
51
  /** Organization member operations registered in the shared operation catalog. */
54
52
  exports.USER_OPERATIONS = [
package/dist/safety.d.ts CHANGED
@@ -62,11 +62,12 @@ export declare function isOperationAllowed(mode: SafetyMode | string, policy: Op
62
62
  */
63
63
  export declare function getSafetyModeFromEnv(): SafetyMode;
64
64
  /**
65
- * Parses allowed project UUIDs from the LIGHTDASH_TOOLS_ALLOWED_PROJECTS environment
65
+ * Parses allowed project UUIDs from the LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS environment
66
66
  * variable (comma-separated). Returns an empty array when the variable is unset, meaning
67
67
  * all projects are allowed.
68
68
  *
69
- * Note: CLI/MCP flags (--allowed-projects) always take priority over this env var.
69
+ * Throws if the removed name LIGHTDASH_TOOLS_ALLOWED_PROJECTS is still set.
70
+ * Note: CLI `--projects` takes priority over this env var.
70
71
  */
71
72
  export declare function getAllowedProjectUuidsFromEnv(): string[];
72
73
  /**
package/dist/safety.js CHANGED
@@ -10,6 +10,8 @@ exports.areAllProjectsAllowed = areAllProjectsAllowed;
10
10
  exports.extractProjectUuids = extractProjectUuids;
11
11
  const extract_yaml_project_1 = require("./agentops/extract-yaml-project");
12
12
  const env_1 = require("./env");
13
+ /** Removed allowlist env — fail closed if still set. */
14
+ const ENV_ALLOWED_PROJECTS_REMOVED = 'LIGHTDASH_TOOLS_ALLOWED_PROJECTS';
13
15
  /**
14
16
  * Hierarchical safety modes for Lightdash AI tools and CLI.
15
17
  */
@@ -120,15 +122,21 @@ function getSafetyModeFromEnv() {
120
122
  return SafetyMode.READ_ONLY;
121
123
  }
122
124
  /**
123
- * Parses allowed project UUIDs from the LIGHTDASH_TOOLS_ALLOWED_PROJECTS environment
125
+ * Parses allowed project UUIDs from the LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS environment
124
126
  * variable (comma-separated). Returns an empty array when the variable is unset, meaning
125
127
  * all projects are allowed.
126
128
  *
127
- * Note: CLI/MCP flags (--allowed-projects) always take priority over this env var.
129
+ * Throws if the removed name LIGHTDASH_TOOLS_ALLOWED_PROJECTS is still set.
130
+ * Note: CLI `--projects` takes priority over this env var.
128
131
  */
129
132
  function getAllowedProjectUuidsFromEnv() {
130
133
  var _a;
131
- const raw = (_a = process.env[env_1.ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECTS]) !== null && _a !== void 0 ? _a : '';
134
+ const legacy = process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
135
+ if (legacy !== undefined && legacy.trim() !== '') {
136
+ throw new Error(`${ENV_ALLOWED_PROJECTS_REMOVED} is no longer supported. ` +
137
+ `Use ${env_1.ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS} instead.`);
138
+ }
139
+ const raw = (_a = process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS) !== null && _a !== void 0 ? _a : '';
132
140
  return raw
133
141
  .split(',')
134
142
  .map((s) => s.trim())
@@ -159,30 +159,53 @@ function policy(impact) {
159
159
  });
160
160
  });
161
161
  (0, vitest_1.describe)('getAllowedProjectUuidsFromEnv', () => {
162
- const originalEnv = process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
162
+ const originalEnv = process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS;
163
+ const originalLegacy = process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
163
164
  (0, vitest_1.afterEach)(() => {
164
- process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = originalEnv;
165
+ if (originalEnv === undefined) {
166
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS;
167
+ }
168
+ else {
169
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS = originalEnv;
170
+ }
171
+ if (originalLegacy === undefined) {
172
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
173
+ }
174
+ else {
175
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = originalLegacy;
176
+ }
165
177
  });
166
178
  (0, vitest_1.it)('should return empty array when env is not set', () => {
179
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS;
167
180
  delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
168
181
  (0, vitest_1.expect)((0, safety_1.getAllowedProjectUuidsFromEnv)()).toEqual([]);
169
182
  });
170
183
  (0, vitest_1.it)('should parse a single UUID', () => {
171
- process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = 'uuid-a';
184
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
185
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS = 'uuid-a';
172
186
  (0, vitest_1.expect)((0, safety_1.getAllowedProjectUuidsFromEnv)()).toEqual(['uuid-a']);
173
187
  });
174
188
  (0, vitest_1.it)('should parse comma-separated UUIDs', () => {
175
- process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = 'uuid-a,uuid-b,uuid-c';
189
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
190
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS = 'uuid-a,uuid-b,uuid-c';
176
191
  (0, vitest_1.expect)((0, safety_1.getAllowedProjectUuidsFromEnv)()).toEqual(['uuid-a', 'uuid-b', 'uuid-c']);
177
192
  });
178
193
  (0, vitest_1.it)('should trim whitespace around UUIDs', () => {
179
- process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = ' uuid-a , uuid-b ';
194
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
195
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS = ' uuid-a , uuid-b ';
180
196
  (0, vitest_1.expect)((0, safety_1.getAllowedProjectUuidsFromEnv)()).toEqual(['uuid-a', 'uuid-b']);
181
197
  });
182
198
  (0, vitest_1.it)('should filter out empty entries', () => {
183
- process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = 'uuid-a,,uuid-b';
199
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS;
200
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS = 'uuid-a,,uuid-b';
184
201
  (0, vitest_1.expect)((0, safety_1.getAllowedProjectUuidsFromEnv)()).toEqual(['uuid-a', 'uuid-b']);
185
202
  });
203
+ (0, vitest_1.it)('should reject removed LIGHTDASH_TOOLS_ALLOWED_PROJECTS', () => {
204
+ delete process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS;
205
+ process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS = 'uuid-a';
206
+ (0, vitest_1.expect)(() => (0, safety_1.getAllowedProjectUuidsFromEnv)()).toThrow(/LIGHTDASH_TOOLS_ALLOWED_PROJECTS is no longer supported/);
207
+ (0, vitest_1.expect)(() => (0, safety_1.getAllowedProjectUuidsFromEnv)()).toThrow(/LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS/);
208
+ });
186
209
  });
187
210
  (0, vitest_1.describe)('isProjectAllowed', () => {
188
211
  (0, vitest_1.it)('should allow all projects when allowlist is empty', () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/common",
3
- "version": "0.8.0",
3
+ "version": "0.11.0",
4
4
  "description": "Shared utilities and types for Lightdash AI.",
5
5
  "keywords": [],
6
6
  "repository": {
package/src/audit.test.ts CHANGED
@@ -4,7 +4,14 @@ import { join } from 'node:path';
4
4
 
5
5
  import { afterEach, describe, expect, it, vi } from 'vitest';
6
6
 
7
- import { closeAuditLog, getSessionId, initAuditLog, logAuditEntry } from './audit';
7
+ import {
8
+ auditSeverityForStatus,
9
+ buildAuditLogEntry,
10
+ closeAuditLog,
11
+ getSessionId,
12
+ initAuditLog,
13
+ logAuditEntry,
14
+ } from './audit';
8
15
 
9
16
  describe('audit', () => {
10
17
  const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
@@ -20,39 +27,70 @@ describe('audit', () => {
20
27
  expect(getSessionId()).toBe(getSessionId());
21
28
  });
22
29
 
23
- it('initAuditLog announces stderr destination when no file path is given', () => {
24
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
30
+ it('auditSeverityForStatus maps statuses for Cloud Logging', () => {
31
+ expect(auditSeverityForStatus('success')).toBe('INFO');
32
+ expect(auditSeverityForStatus('deletion_succeeded')).toBe('NOTICE');
33
+ expect(auditSeverityForStatus('blocked')).toBe('WARNING');
34
+ expect(auditSeverityForStatus('error')).toBe('ERROR');
35
+ });
36
+
37
+ it('buildAuditLogEntry derives channel, severity, and message', () => {
38
+ const entry = buildAuditLogEntry({
39
+ tool: 'demo_tool',
40
+ status: 'blocked',
41
+ startMs: Date.now() - 5,
42
+ projectUuids: [],
43
+ profileId: 'semantic-layer',
44
+ });
45
+ expect(entry.channel).toBe('audit');
46
+ expect(entry.severity).toBe('WARNING');
47
+ expect(entry.message).toBe('demo_tool blocked');
48
+ expect(entry.projectUuids).toBeUndefined();
49
+ expect(entry.profileId).toBe('semantic-layer');
50
+ expect(entry.sessionId).toBe(getSessionId());
51
+ });
52
+
53
+ it('initAuditLog announces stderr destination on stdout when no file path is given', () => {
54
+ const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
25
55
  try {
26
56
  initAuditLog();
27
- expect(consoleErrorSpy).toHaveBeenCalledWith(
57
+ expect(consoleLogSpy).toHaveBeenCalledWith(
28
58
  expect.stringContaining('[audit] Writing to stderr'),
29
59
  );
30
60
  } finally {
31
- consoleErrorSpy.mockRestore();
61
+ consoleLogSpy.mockRestore();
32
62
  }
33
63
  });
34
64
 
35
- it('logAuditEntry writes NDJSON to stderr by default', () => {
65
+ it('logAuditEntry writes pure JSON NDJSON to stderr (Cloud Logging–parseable)', () => {
36
66
  initAuditLog();
37
67
 
38
- logAuditEntry({
39
- timestamp: '2026-01-01T00:00:00.000Z',
40
- sessionId: getSessionId(),
41
- tool: 'test_tool',
42
- tokenHash: 'abc123',
43
- subject: 'user-uuid',
44
- status: 'success',
45
- durationMs: 12,
46
- });
68
+ logAuditEntry(
69
+ buildAuditLogEntry({
70
+ tool: 'test_tool',
71
+ status: 'success',
72
+ startMs: Date.now() - 12,
73
+ tokenHash: 'abc123',
74
+ subject: 'user-uuid',
75
+ clientSessionId: 'mcp-session-1',
76
+ profileId: 'semantic-layer',
77
+ }),
78
+ );
47
79
 
48
80
  const auditLine = stderrSpy.mock.calls
49
81
  .map(([chunk]) => String(chunk))
50
82
  .find((line) => line.includes('"tool":"test_tool"'));
51
83
  expect(auditLine).toBeDefined();
52
- expect(auditLine).toContain('[audit]');
53
- expect(auditLine).toContain('"status":"success"');
54
- expect(auditLine).toContain('"tokenHash":"abc123"');
55
- expect(auditLine).toContain('"subject":"user-uuid"');
84
+ expect(auditLine).not.toContain('[audit]');
85
+ const parsed = JSON.parse(auditLine!.trim()) as Record<string, unknown>;
86
+ expect(parsed.channel).toBe('audit');
87
+ expect(parsed.severity).toBe('INFO');
88
+ expect(parsed.message).toBe('test_tool success');
89
+ expect(parsed.status).toBe('success');
90
+ expect(parsed.tokenHash).toBe('abc123');
91
+ expect(parsed.subject).toBe('user-uuid');
92
+ expect(parsed.clientSessionId).toBe('mcp-session-1');
93
+ expect(parsed.profileId).toBe('semantic-layer');
56
94
  });
57
95
 
58
96
  it('logAuditEntry appends to a file when initAuditLog receives a path', async () => {
@@ -62,23 +100,25 @@ describe('audit', () => {
62
100
  try {
63
101
  initAuditLog(filePath);
64
102
 
65
- logAuditEntry({
66
- timestamp: '2026-01-01T00:00:00.000Z',
67
- sessionId: getSessionId(),
68
- tool: 'file_tool',
69
- projectUuids: ['uuid-a'],
70
- status: 'blocked',
71
- durationMs: 3,
72
- });
103
+ logAuditEntry(
104
+ buildAuditLogEntry({
105
+ tool: 'file_tool',
106
+ status: 'blocked',
107
+ startMs: Date.now() - 3,
108
+ projectUuids: ['uuid-a'],
109
+ }),
110
+ );
73
111
 
74
112
  await closeAuditLog();
75
113
 
76
114
  // filePath is a temp path from mkdtempSync in this test only
77
115
  // eslint-disable-next-line security/detect-non-literal-fs-filename
78
116
  const contents = readFileSync(filePath, 'utf8');
79
- expect(contents).toContain('"tool":"file_tool"');
80
- expect(contents).toContain('"projectUuids":["uuid-a"]');
81
- expect(contents).toContain('"status":"blocked"');
117
+ const parsed = JSON.parse(contents.trim()) as Record<string, unknown>;
118
+ expect(parsed.channel).toBe('audit');
119
+ expect(parsed.tool).toBe('file_tool');
120
+ expect(parsed.projectUuids).toEqual(['uuid-a']);
121
+ expect(parsed.status).toBe('blocked');
82
122
  } finally {
83
123
  await closeAuditLog();
84
124
  rmSync(dir, { recursive: true, force: true });