@lightdash-tools/common 0.8.0 → 0.9.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.
@@ -14,7 +14,7 @@ const PROFILE_CONTENT_DEVELOPER = 'content-developer';
14
14
  const API_V1 = '/api/v1';
15
15
  const API_V2 = '/api/v2';
16
16
  const WRITE_NONDESTRUCTIVE_IMPACT = 'write-nondestructive';
17
- const PREVIEW_DIFF_SUMMARY = 'Compute an in-memory diff and issue a single-use previewId (no upstream preview API)';
17
+ const PREVIEW_DIFF_SUMMARY = 'Compute an in-memory diff and issue an HMAC-signed previewToken (no upstream preview API)';
18
18
  const TILE_READ_SUMMARY = 'Read the current tile array (no per-tile REST route exists)';
19
19
  const op_preview_chart_changes = (0, types_1.defineOperation)({
20
20
  id: 'content-developer.preview.chart',
@@ -71,7 +71,7 @@ const op_preview_dashboard_changes = (0, types_1.defineOperation)({
71
71
  });
72
72
  const op_preview_content_move = (0, types_1.defineOperation)({
73
73
  id: 'content-developer.preview.content-move',
74
- summary: 'Preview a bulk content move into an existing space (MCP ledger only; issues a single-use previewId)',
74
+ summary: 'Preview a bulk content move into an existing space (issues an HMAC-signed previewToken)',
75
75
  http: { method: 'GET', path: `${API_V2}/content` },
76
76
  authorization: { safetyImpact: 'read' },
77
77
  sensitivity: 'none',
@@ -89,6 +89,19 @@ const op_preview_content_move = (0, types_1.defineOperation)({
89
89
  ],
90
90
  profiles: [PROFILE_CONTENT_DEVELOPER],
91
91
  });
92
+ const op_get_chart_as_code = (0, types_1.defineOperation)({
93
+ id: 'content-developer.charts.get-as-code',
94
+ summary: 'Get a chart in as-code (upsert) shape for cloning chartConfig/metricQuery before dashboard-scoped create',
95
+ http: { method: 'GET', path: `${API_V1}/projects/{projectUuid}/code/charts` },
96
+ authorization: { safetyImpact: 'read' },
97
+ sensitivity: 'none',
98
+ mcp: {
99
+ toolName: 'get_chart_as_code',
100
+ annotations: safety_1.READ_ONLY_DEFAULT,
101
+ taskSupport: { exposed: true, taskEligible: false },
102
+ },
103
+ profiles: [PROFILE_CONTENT_DEVELOPER],
104
+ });
92
105
  const op_validate_chart = (0, types_1.defineOperation)({
93
106
  id: 'content-developer.charts.validate',
94
107
  summary: "Validate a saved chart's fields against its underlying explore",
@@ -436,6 +449,7 @@ exports.CONTENT_DEVELOPER_OPERATIONS = [
436
449
  op_preview_chart_changes,
437
450
  op_preview_dashboard_changes,
438
451
  op_preview_content_move,
452
+ op_get_chart_as_code,
439
453
  op_validate_chart,
440
454
  op_validate_dashboard,
441
455
  op_confirm_preview,
@@ -128,6 +128,19 @@ const op_run_chart = (0, types_1.defineOperation)({
128
128
  },
129
129
  profiles: [PROFILE_CONTENT_READER],
130
130
  });
131
+ const op_export_chart_image = (0, types_1.defineOperation)({
132
+ id: 'content-reader.charts.export-image',
133
+ summary: 'Export a saved chart as a PNG image snapshot',
134
+ http: { method: 'POST', path: '/api/v1/saved/{chartUuid}/export' },
135
+ authorization: { safetyImpact: 'read' },
136
+ sensitivity: 'none',
137
+ mcp: {
138
+ toolName: 'export_chart_image',
139
+ annotations: safety_1.READ_ONLY_TRANSIENT,
140
+ taskSupport: { exposed: true, taskEligible: false },
141
+ },
142
+ profiles: [PROFILE_CONTENT_READER],
143
+ });
131
144
  const op_run_dashboard_tile = (0, types_1.defineOperation)({
132
145
  id: 'content-reader.dashboards.run-tile',
133
146
  summary: 'Execute a dashboard tile with bounded results',
@@ -143,7 +156,7 @@ const op_run_dashboard_tile = (0, types_1.defineOperation)({
143
156
  });
144
157
  const op_get_query_result = (0, types_1.defineOperation)({
145
158
  id: 'content-reader.query.result.get',
146
- summary: 'Get or poll a session-owned query result',
159
+ summary: 'Get or poll a query result by queryUuid',
147
160
  http: { method: 'GET', path: '/api/v2/projects/{projectUuid}/query/{queryUuid}' },
148
161
  authorization: { safetyImpact: 'read' },
149
162
  sensitivity: 'none',
@@ -156,7 +169,7 @@ const op_get_query_result = (0, types_1.defineOperation)({
156
169
  });
157
170
  const op_cancel_query = (0, types_1.defineOperation)({
158
171
  id: 'content-reader.query.cancel',
159
- summary: 'Cancel a running session-owned query',
172
+ summary: 'Cancel a running query by queryUuid',
160
173
  http: { method: 'POST', path: '/api/v2/projects/{projectUuid}/query/{queryUuid}/cancel' },
161
174
  authorization: { safetyImpact: 'read' },
162
175
  sensitivity: 'none',
@@ -177,6 +190,7 @@ exports.CONTENT_READER_OPERATIONS = [
177
190
  op_get_project_parameters,
178
191
  op_explain_content,
179
192
  op_run_chart,
193
+ op_export_chart_image,
180
194
  op_run_dashboard_tile,
181
195
  op_get_query_result,
182
196
  op_cancel_query,
@@ -32,6 +32,7 @@ const P0_OPERATION_IDS = [
32
32
  'ai-agents.project.evaluations.runs.list',
33
33
  ];
34
34
  const ALL_PROFILES = [
35
+ 'ai-agent-ops',
35
36
  'core-lifecycle',
36
37
  'evaluations',
37
38
  'conversations',
@@ -11,7 +11,7 @@ export type HttpMethod = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
11
11
  /**
12
12
  * Capability profiles group operations for selective exposure (CLI profiles, MCP subsets).
13
13
  */
14
- export type CapabilityProfile = 'content-developer' | 'content-governance' | 'content-reader' | 'conversations' | 'core-lifecycle' | 'discovery-readonly' | 'evaluations' | 'org-audit-readonly' | 'semantic-discovery';
14
+ export type CapabilityProfile = 'ai-agent-ops' | 'content-developer' | 'content-governance' | 'content-reader' | 'conversations' | 'core-lifecycle' | 'discovery-readonly' | 'evaluations' | 'org-audit-readonly' | 'semantic-discovery';
15
15
  /**
16
16
  * MCP response sensitivity class (ADR-0011).
17
17
  * Documents which redaction class handlers must apply; does not auto-redact.
@@ -6,6 +6,7 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.defineOperation = defineOperation;
8
8
  const VALID_PROFILES = new Set([
9
+ 'ai-agent-ops',
9
10
  'content-developer',
10
11
  'content-governance',
11
12
  'content-reader',
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.9.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
+ personaId: '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.personaId).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
+ personaId: '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.personaId).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 });
package/src/audit.ts CHANGED
@@ -1,13 +1,10 @@
1
1
  /**
2
2
  * Structured audit logger for Lightdash tool invocations (MCP and CLI).
3
3
  *
4
- * Each operation is recorded as a single NDJSON line containing:
5
- * timestamp, sessionId, tool/command name, projectUuids (if present), status, durationMs,
6
- * and optional OAuth attribution fields (tokenHash, subject) when available.
4
+ * Each operation is recorded as a single NDJSON line. On stderr the line is pure JSON
5
+ * (Cloud Logging–parseable); text prefixes prevent jsonPayload parsing on Cloud Run.
7
6
  *
8
- * Output destination:
9
- * - If LIGHTDASH_TOOLS_AUDIT_LOG is set to a file path, entries are appended to that file.
10
- * - Otherwise entries are written to stderr with an "[audit]" prefix.
7
+ * If LIGHTDASH_TOOLS_AUDIT_LOG is a file path, entries are appended there; otherwise stderr.
11
8
  */
12
9
 
13
10
  import { randomUUID } from 'node:crypto';
@@ -26,21 +23,41 @@ export type AuditStatus =
26
23
  | 'resource_changed'
27
24
  | 'success';
28
25
 
26
+ /** Cloud Logging LogSeverity-compatible strings for structured stderr JSON. */
27
+ export type AuditSeverity = 'ERROR' | 'INFO' | 'NOTICE' | 'WARNING';
28
+
29
29
  export type AuditLogEntry = {
30
+ /** Stable filter key for Cloud Logging (`jsonPayload.channel="audit"`). */
31
+ channel: 'audit';
32
+ severity: AuditSeverity;
33
+ message: string;
30
34
  timestamp: string;
35
+ /** Process-lifetime instance id (not the MCP client session). */
31
36
  sessionId: string;
32
- /** MCP tool name or CLI command name. */
33
37
  tool: string;
34
- /** Project UUIDs involved in the call, if any (covers both projectUuid and projectUuids[]). */
35
38
  projectUuids?: string[];
36
39
  /** SHA-256 hash of the OAuth bearer token (never the raw token). */
37
40
  tokenHash?: string;
38
41
  /** Lightdash user UUID when the call runs under OAuth bearer auth. */
39
42
  subject?: string;
43
+ clientSessionId?: string;
44
+ personaId?: string;
40
45
  status: AuditStatus;
41
46
  durationMs: number;
42
47
  };
43
48
 
49
+ export type BuildAuditLogEntryInput = {
50
+ tool: string;
51
+ status: AuditStatus;
52
+ /** Epoch ms when the operation started (`durationMs = now - startMs`). */
53
+ startMs: number;
54
+ projectUuids?: string[];
55
+ tokenHash?: string;
56
+ subject?: string;
57
+ clientSessionId?: string;
58
+ personaId?: string;
59
+ };
60
+
44
61
  /** Unique ID for the current process lifetime. Generated once at module load. */
45
62
  const SESSION_ID = randomUUID();
46
63
 
@@ -50,19 +67,67 @@ export function getSessionId(): string {
50
67
  return SESSION_ID;
51
68
  }
52
69
 
70
+ /** Map audit status to Cloud Logging severity. */
71
+ export function auditSeverityForStatus(status: AuditStatus): AuditSeverity {
72
+ switch (status) {
73
+ case 'success':
74
+ return 'INFO';
75
+ case 'deletion_succeeded':
76
+ case 'promotion_succeeded':
77
+ return 'NOTICE';
78
+ case 'blocked':
79
+ case 'confirmation_cancelled':
80
+ case 'confirmation_declined':
81
+ case 'confirmation_requested':
82
+ case 'resource_changed':
83
+ return 'WARNING';
84
+ case 'deletion_failed':
85
+ case 'error':
86
+ case 'promotion_failed':
87
+ return 'ERROR';
88
+ default: {
89
+ const _exhaustive: never = status;
90
+ return _exhaustive;
91
+ }
92
+ }
93
+ }
94
+
95
+ /** Assemble a full audit entry (shared by CLI and MCP). */
96
+ export function buildAuditLogEntry(input: BuildAuditLogEntryInput): AuditLogEntry {
97
+ const projectUuids =
98
+ input.projectUuids && input.projectUuids.length > 0 ? input.projectUuids : undefined;
99
+ return {
100
+ channel: 'audit',
101
+ severity: auditSeverityForStatus(input.status),
102
+ message: `${input.tool} ${input.status}`,
103
+ timestamp: new Date().toISOString(),
104
+ sessionId: SESSION_ID,
105
+ tool: input.tool,
106
+ projectUuids,
107
+ tokenHash: input.tokenHash,
108
+ subject: input.subject,
109
+ clientSessionId: input.clientSessionId,
110
+ personaId: input.personaId,
111
+ status: input.status,
112
+ durationMs: Date.now() - input.startMs,
113
+ };
114
+ }
115
+
53
116
  /**
54
117
  * Initialise the audit log. Call once at process startup.
55
118
  * If filePath is provided, entries are appended to that file; otherwise stderr is used.
119
+ * Startup banners go to stdout so they do not mix with structured audit JSON on stderr.
56
120
  */
57
121
  export function initAuditLog(filePath?: string): void {
58
122
  if (filePath) {
59
123
  _writeStream = createWriteStream(filePath, { flags: 'a' });
60
124
  _writeStream.on('error', (err) => {
125
+ // Diagnostic only — not an audit row.
61
126
  console.error('[audit] Failed to write to audit log file:', err);
62
127
  });
63
- console.error(`[audit] Writing to file: ${filePath} (session: ${SESSION_ID})`);
128
+ console.log(`[audit] Writing to file: ${filePath} (session: ${SESSION_ID})`);
64
129
  } else {
65
- console.error(`[audit] Writing to stderr (session: ${SESSION_ID})`);
130
+ console.log(`[audit] Writing to stderr (session: ${SESSION_ID})`);
66
131
  }
67
132
  }
68
133
 
@@ -72,7 +137,7 @@ export function logAuditEntry(entry: AuditLogEntry): void {
72
137
  if (_writeStream) {
73
138
  _writeStream.write(line);
74
139
  } else {
75
- process.stderr.write(`[audit] ${line}`);
140
+ process.stderr.write(line);
76
141
  }
77
142
  }
78
143
 
package/src/env.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  export const ENV_LIGHTDASH_TOOLS_DRY_RUN = 'LIGHTDASH_TOOLS_DRY_RUN';
8
8
  export const ENV_LIGHTDASH_TOOLS_AUDIT_LOG = 'LIGHTDASH_TOOLS_AUDIT_LOG';
9
9
  export const ENV_LIGHTDASH_TOOLS_SAFETY_MODE = 'LIGHTDASH_TOOLS_SAFETY_MODE';
10
- export const ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECTS = 'LIGHTDASH_TOOLS_ALLOWED_PROJECTS';
10
+ export const ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS = 'LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS';
11
11
 
12
12
  /** MCP HTTP server env vars (`LIGHTDASH_TOOLS_MCP_*` / `LIGHTDASH_TOOLS_OAUTH_*` per ADR-0009). */
13
13
  /** @deprecated Removed — auth is credential-inferred (ADR-0007). Kept for migration error messages. */