@lightdash-tools/common 0.6.0 → 0.8.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 (120) hide show
  1. package/dist/agentops/extract-yaml-project.d.ts +7 -0
  2. package/dist/agentops/extract-yaml-project.js +42 -0
  3. package/dist/agentops/formatters.d.ts +5 -0
  4. package/dist/agentops/formatters.js +47 -0
  5. package/dist/agentops/snapshots.d.ts +32 -0
  6. package/dist/agentops/snapshots.js +34 -0
  7. package/dist/agentops/types.d.ts +224 -0
  8. package/dist/agentops/types.js +430 -0
  9. package/dist/argument-validation.d.ts +25 -0
  10. package/dist/argument-validation.js +217 -0
  11. package/dist/argument-validation.test.d.ts +1 -0
  12. package/dist/argument-validation.test.js +205 -0
  13. package/dist/audit.d.ts +9 -2
  14. package/dist/audit.js +17 -2
  15. package/dist/audit.test.d.ts +1 -0
  16. package/dist/audit.test.js +73 -0
  17. package/dist/env.d.ts +8 -0
  18. package/dist/env.js +9 -1
  19. package/dist/index.d.ts +7 -3
  20. package/dist/index.js +14 -2
  21. package/dist/input-validation.d.ts +35 -0
  22. package/dist/input-validation.js +87 -0
  23. package/dist/input-validation.test.js +93 -0
  24. package/dist/operations/agent-safe.d.ts +5 -0
  25. package/dist/operations/agent-safe.js +9 -0
  26. package/dist/operations/ai-agents.d.ts +6 -0
  27. package/dist/operations/ai-agents.js +427 -0
  28. package/dist/operations/cli-content.d.ts +5 -0
  29. package/dist/operations/cli-content.js +71 -0
  30. package/dist/operations/client-coverage.d.ts +113 -0
  31. package/dist/operations/client-coverage.js +130 -0
  32. package/dist/operations/client-coverage.test.d.ts +1 -0
  33. package/dist/operations/client-coverage.test.js +22 -0
  34. package/dist/operations/content-developer.d.ts +2 -0
  35. package/dist/operations/content-developer.js +457 -0
  36. package/dist/operations/content-governance.d.ts +7 -0
  37. package/dist/operations/content-governance.js +98 -0
  38. package/dist/operations/content-reader.d.ts +2 -0
  39. package/dist/operations/content-reader.js +183 -0
  40. package/dist/operations/index.d.ts +12 -0
  41. package/dist/operations/index.js +34 -0
  42. package/dist/operations/organization-audit.d.ts +2 -0
  43. package/dist/operations/organization-audit.js +273 -0
  44. package/dist/operations/parity.test.d.ts +1 -0
  45. package/dist/operations/parity.test.js +29 -0
  46. package/dist/operations/registry.d.ts +18 -0
  47. package/dist/operations/registry.js +110 -0
  48. package/dist/operations/registry.test.d.ts +1 -0
  49. package/dist/operations/registry.test.js +223 -0
  50. package/dist/operations/semantic-layer.d.ts +6 -0
  51. package/dist/operations/semantic-layer.js +154 -0
  52. package/dist/operations/types.d.ts +86 -0
  53. package/dist/operations/types.js +104 -0
  54. package/dist/operations/types.test.d.ts +1 -0
  55. package/dist/operations/types.test.js +92 -0
  56. package/dist/operations/users.d.ts +6 -0
  57. package/dist/operations/users.js +58 -0
  58. package/dist/safety.d.ts +32 -2
  59. package/dist/safety.js +62 -5
  60. package/dist/safety.test.js +217 -4
  61. package/dist/types/generated/openapi-types.d.ts +32623 -11194
  62. package/dist/types/index.d.ts +12 -0
  63. package/dist/types/index.js +29 -0
  64. package/dist/types/lightdash-api.d.ts +1 -1
  65. package/dist/types/v1/ai-agents.d.ts +112 -3
  66. package/dist/types/v1/charts.d.ts +5 -3
  67. package/dist/types/v1/dashboards.d.ts +13 -0
  68. package/dist/types/v1/index.d.ts +45 -8
  69. package/dist/types/v1/index.js +1 -1
  70. package/dist/types/v1/lightdash-api.d.ts +107 -16
  71. package/dist/types/v1/users.d.ts +4 -0
  72. package/dist/types/v2/content.d.ts +2 -0
  73. package/dist/types/v2/content.js +8 -0
  74. package/dist/types/v2/index.d.ts +11 -9
  75. package/dist/types/v2/index.js +1 -1
  76. package/package.json +17 -3
  77. package/src/agentops/extract-yaml-project.ts +42 -0
  78. package/src/agentops/formatters.ts +52 -0
  79. package/src/agentops/snapshots.ts +56 -0
  80. package/src/agentops/types.ts +599 -0
  81. package/src/argument-validation.test.ts +301 -0
  82. package/src/argument-validation.ts +258 -0
  83. package/src/audit.test.ts +87 -0
  84. package/src/audit.ts +32 -3
  85. package/src/env.ts +9 -0
  86. package/src/index.test.ts +1 -0
  87. package/src/index.ts +17 -6
  88. package/src/input-validation.test.ts +157 -1
  89. package/src/input-validation.ts +95 -0
  90. package/src/operations/agent-safe.ts +8 -0
  91. package/src/operations/ai-agents.ts +467 -0
  92. package/src/operations/cli-content.ts +79 -0
  93. package/src/operations/client-coverage.test.ts +23 -0
  94. package/src/operations/client-coverage.ts +147 -0
  95. package/src/operations/content-developer.ts +485 -0
  96. package/src/operations/content-governance.ts +110 -0
  97. package/src/operations/content-reader.ts +197 -0
  98. package/src/operations/index.ts +42 -0
  99. package/src/operations/organization-audit.ts +293 -0
  100. package/src/operations/parity.test.ts +33 -0
  101. package/src/operations/registry.test.ts +250 -0
  102. package/src/operations/registry.ts +128 -0
  103. package/src/operations/semantic-layer.ts +166 -0
  104. package/src/operations/types.test.ts +110 -0
  105. package/src/operations/types.ts +231 -0
  106. package/src/operations/users.ts +65 -0
  107. package/src/safety.test.ts +276 -4
  108. package/src/safety.ts +83 -4
  109. package/src/types/generated/openapi-types.ts +33701 -11813
  110. package/src/types/index.ts +13 -0
  111. package/src/types/lightdash-api.ts +39 -0
  112. package/src/types/v1/ai-agents.ts +133 -3
  113. package/src/types/v1/charts.ts +5 -3
  114. package/src/types/v1/dashboards.ts +19 -0
  115. package/src/types/v1/index.ts +51 -8
  116. package/src/types/v1/lightdash-api.ts +129 -20
  117. package/src/types/v1/users.ts +4 -0
  118. package/src/types/v2/content.ts +8 -0
  119. package/src/types/v2/index.ts +11 -9
  120. package/tsconfig.json +1 -0
@@ -0,0 +1,301 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import {
4
+ RESOURCE_ID_KEYS,
5
+ validateArguments,
6
+ validateResourceIdsInObject,
7
+ } from './argument-validation';
8
+
9
+ import type { ArgumentDescriptor } from './argument-validation';
10
+
11
+ const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000';
12
+
13
+ describe('argument-validation', () => {
14
+ describe('RESOURCE_ID_KEYS', () => {
15
+ it('contains all RFC Phase 0 identifier keys', () => {
16
+ expect([...RESOURCE_ID_KEYS].sort()).toEqual(
17
+ [
18
+ 'agentUuid',
19
+ 'artifactUuid',
20
+ 'chartUuid',
21
+ 'chartUuidOrSlug',
22
+ 'contentUuidOrSlug',
23
+ 'dashboardUuid',
24
+ 'dashboardUuidOrSlug',
25
+ 'evalUuid',
26
+ 'fingerprint',
27
+ 'groupUuid',
28
+ 'itemUuids',
29
+ 'mcpServerUuid',
30
+ 'messageUuid',
31
+ 'newSlug',
32
+ 'organizationUuid',
33
+ 'parentSpaceUuid',
34
+ 'project',
35
+ 'projectUuid',
36
+ 'projectUuids',
37
+ 'projects',
38
+ 'promptUuid',
39
+ 'roleUuid',
40
+ 'runUuid',
41
+ 'savedQueryUuid',
42
+ 'schedulerUuid',
43
+ 'slug',
44
+ 'sourceChartUuidOrSlug',
45
+ 'sourceDashboardUuid',
46
+ 'spaceUuid',
47
+ 'spaceUuids',
48
+ 'targetSpaceUuid',
49
+ 'threadUuid',
50
+ 'tileUuid',
51
+ 'toolCallId',
52
+ 'userUuid',
53
+ 'versionUuid',
54
+ 'versionUuidA',
55
+ 'versionUuidB',
56
+ ].sort(),
57
+ );
58
+ });
59
+ });
60
+
61
+ describe('validateArguments', () => {
62
+ it('validates uuid arguments', () => {
63
+ const descriptors: ArgumentDescriptor[] = [
64
+ { name: 'projectUuid', source: 'option', semanticType: 'uuid', required: true },
65
+ ];
66
+ expect(() => validateArguments({ projectUuid: VALID_UUID }, descriptors)).not.toThrow();
67
+ expect(() => validateArguments({ projectUuid: 'bad-uuid' }, descriptors)).toThrow(
68
+ 'Invalid UUID format',
69
+ );
70
+ });
71
+
72
+ it('validates slug arguments', () => {
73
+ const descriptors: ArgumentDescriptor[] = [
74
+ { name: 'slug', source: 'option', semanticType: 'slug' },
75
+ ];
76
+ expect(() => validateArguments({ slug: 'my-chart' }, descriptors)).not.toThrow();
77
+ expect(() => validateArguments({ slug: 'bad slug' }, descriptors)).toThrow(
78
+ 'Slug must contain only alphanumeric characters',
79
+ );
80
+ });
81
+
82
+ it('validates fingerprint arguments', () => {
83
+ const descriptors: ArgumentDescriptor[] = [
84
+ { name: 'fingerprint', source: 'body', semanticType: 'fingerprint' },
85
+ ];
86
+ expect(() => validateArguments({ fingerprint: 'abc123' }, descriptors)).not.toThrow();
87
+ expect(() => validateArguments({ fingerprint: '' }, descriptors)).toThrow(
88
+ 'Fingerprint must be between 1 and 512 characters',
89
+ );
90
+ });
91
+
92
+ it('throws when required argument is missing', () => {
93
+ const descriptors: ArgumentDescriptor[] = [
94
+ { name: 'projectUuid', source: 'option', semanticType: 'uuid', required: true },
95
+ ];
96
+ expect(() => validateArguments({}, descriptors)).toThrow(
97
+ "Required argument 'projectUuid' is missing",
98
+ );
99
+ });
100
+
101
+ it('skips optional missing arguments', () => {
102
+ const descriptors: ArgumentDescriptor[] = [
103
+ { name: 'slug', source: 'option', semanticType: 'slug' },
104
+ ];
105
+ expect(() => validateArguments({}, descriptors)).not.toThrow();
106
+ });
107
+
108
+ it('validates uuid arrays', () => {
109
+ const descriptors: ArgumentDescriptor[] = [
110
+ { name: 'projectUuid', source: 'body', semanticType: 'uuid' },
111
+ ];
112
+ expect(() =>
113
+ validateArguments({ projectUuid: [VALID_UUID, VALID_UUID] }, descriptors),
114
+ ).not.toThrow();
115
+ expect(() =>
116
+ validateArguments({ projectUuid: [VALID_UUID, 'not-uuid'] }, descriptors),
117
+ ).toThrow('Invalid UUID format');
118
+ });
119
+
120
+ it('validates free-text with control char rejection only', () => {
121
+ const descriptors: ArgumentDescriptor[] = [
122
+ { name: 'query', source: 'positional', semanticType: 'free-text' },
123
+ ];
124
+ expect(() => validateArguments({ query: 'what? growth%' }, descriptors)).not.toThrow();
125
+ expect(() => validateArguments({ query: 'bad\u0000' }, descriptors)).toThrow(
126
+ 'Input contains invalid control characters',
127
+ );
128
+ });
129
+
130
+ it('validates json string arguments', () => {
131
+ const descriptors: ArgumentDescriptor[] = [
132
+ { name: 'payload', source: 'body', semanticType: 'json' },
133
+ ];
134
+ expect(() => validateArguments({ payload: '{"a":1}' }, descriptors)).not.toThrow();
135
+ expect(() => validateArguments({ payload: 'not-json' }, descriptors)).toThrow(
136
+ "Argument 'payload' must be valid JSON",
137
+ );
138
+ });
139
+
140
+ it('validates boolean arguments', () => {
141
+ const descriptors: ArgumentDescriptor[] = [
142
+ { name: 'enabled', source: 'option', semanticType: 'boolean' },
143
+ ];
144
+ expect(() => validateArguments({ enabled: true }, descriptors)).not.toThrow();
145
+ expect(() => validateArguments({ enabled: 'true' }, descriptors)).toThrow(
146
+ "Argument 'enabled' must be a boolean",
147
+ );
148
+ });
149
+
150
+ it('validates number arguments', () => {
151
+ const descriptors: ArgumentDescriptor[] = [
152
+ { name: 'limit', source: 'option', semanticType: 'number' },
153
+ ];
154
+ expect(() => validateArguments({ limit: 10 }, descriptors)).not.toThrow();
155
+ expect(() => validateArguments({ limit: Number.NaN }, descriptors)).toThrow(
156
+ "Argument 'limit' must be a number",
157
+ );
158
+ });
159
+ });
160
+
161
+ describe('validateResourceIdsInObject', () => {
162
+ it('validates top-level resource id keys', () => {
163
+ expect(() =>
164
+ validateResourceIdsInObject({
165
+ projectUuid: VALID_UUID,
166
+ slug: 'my-chart',
167
+ }),
168
+ ).not.toThrow();
169
+ });
170
+
171
+ it('validates projectUuids / projects array entries as UUIDs', () => {
172
+ expect(() => validateResourceIdsInObject({ projectUuids: [VALID_UUID] })).not.toThrow();
173
+ expect(() => validateResourceIdsInObject({ projectUuids: [VALID_UUID, 'bad-uuid'] })).toThrow(
174
+ 'Invalid UUID format',
175
+ );
176
+ expect(() => validateResourceIdsInObject({ projects: ['bad-uuid'] })).toThrow(
177
+ 'Invalid UUID format',
178
+ );
179
+ });
180
+
181
+ it('validates nested resource id keys', () => {
182
+ expect(() =>
183
+ validateResourceIdsInObject({
184
+ filter: {
185
+ agentUuid: VALID_UUID,
186
+ nested: {
187
+ threadUuid: VALID_UUID,
188
+ },
189
+ },
190
+ }),
191
+ ).not.toThrow();
192
+ });
193
+
194
+ it('validates resource id keys inside arrays', () => {
195
+ expect(() =>
196
+ validateResourceIdsInObject([{ projectUuid: VALID_UUID }, { projectUuid: 'bad-uuid' }]),
197
+ ).toThrow('Invalid UUID format');
198
+ });
199
+
200
+ it('validates uuid keys with uuid rules', () => {
201
+ expect(() => validateResourceIdsInObject({ runUuid: 'not-a-uuid' })).toThrow(
202
+ 'Invalid UUID format',
203
+ );
204
+ });
205
+
206
+ it('validates slug key with slug rules', () => {
207
+ expect(() => validateResourceIdsInObject({ slug: 'bad slug' })).toThrow(
208
+ 'Slug must contain only alphanumeric characters',
209
+ );
210
+ });
211
+
212
+ it('accepts UUID or slug for dashboardUuid and chartUuid', () => {
213
+ expect(() => validateResourceIdsInObject({ dashboardUuid: 'sales-overview' })).not.toThrow();
214
+ expect(() => validateResourceIdsInObject({ dashboardUuid: VALID_UUID })).not.toThrow();
215
+ expect(() => validateResourceIdsInObject({ chartUuid: 'my-chart' })).not.toThrow();
216
+ expect(() => validateResourceIdsInObject({ dashboardUuid: 'bad?' })).toThrow(
217
+ 'Slug must contain only alphanumeric characters',
218
+ );
219
+ expect(() => validateResourceIdsInObject({ dashboardUuid: '..' })).toThrow(
220
+ 'Slug must not contain path traversal segments',
221
+ );
222
+ });
223
+
224
+ it('validates chartUuidOrSlug/dashboardUuidOrSlug and itemUuids/targetSpaceUuid', () => {
225
+ expect(() =>
226
+ validateResourceIdsInObject({
227
+ chartUuidOrSlug: 'my-chart',
228
+ dashboardUuidOrSlug: VALID_UUID,
229
+ itemUuids: [VALID_UUID],
230
+ targetSpaceUuid: VALID_UUID,
231
+ }),
232
+ ).not.toThrow();
233
+ expect(() => validateResourceIdsInObject({ itemUuids: [VALID_UUID, 'bad-uuid'] })).toThrow(
234
+ 'Invalid UUID format',
235
+ );
236
+ expect(() => validateResourceIdsInObject({ targetSpaceUuid: 'bad?' })).toThrow(
237
+ 'Invalid UUID format',
238
+ );
239
+ expect(() => validateResourceIdsInObject({ chartUuidOrSlug: 'bad?' })).toThrow(
240
+ 'Slug must contain only alphanumeric characters',
241
+ );
242
+ });
243
+
244
+ it('validates spaceUuids and parentSpaceUuid as UUIDs', () => {
245
+ expect(() =>
246
+ validateResourceIdsInObject({
247
+ spaceUuids: [VALID_UUID],
248
+ parentSpaceUuid: VALID_UUID,
249
+ }),
250
+ ).not.toThrow();
251
+ expect(() => validateResourceIdsInObject({ spaceUuids: ['bad?'] })).toThrow(
252
+ 'Invalid UUID format',
253
+ );
254
+ expect(() => validateResourceIdsInObject({ parentSpaceUuid: '..' })).toThrow(
255
+ 'Invalid UUID format',
256
+ );
257
+ });
258
+
259
+ it('validates fingerprint and toolCallId with fingerprint rules', () => {
260
+ expect(() =>
261
+ validateResourceIdsInObject({
262
+ fingerprint: 'fp-123',
263
+ toolCallId: 'call-abc',
264
+ }),
265
+ ).not.toThrow();
266
+ expect(() => validateResourceIdsInObject({ fingerprint: '' })).toThrow(
267
+ 'Fingerprint must be between 1 and 512 characters',
268
+ );
269
+ expect(() => validateResourceIdsInObject({ toolCallId: '' })).toThrow(
270
+ 'Fingerprint must be between 1 and 512 characters',
271
+ );
272
+ });
273
+
274
+ it('validates string arrays under resource id keys', () => {
275
+ expect(() =>
276
+ validateResourceIdsInObject({
277
+ projectUuid: [VALID_UUID, VALID_UUID],
278
+ }),
279
+ ).not.toThrow();
280
+ expect(() =>
281
+ validateResourceIdsInObject({
282
+ projectUuid: [VALID_UUID, 'invalid'],
283
+ }),
284
+ ).toThrow('Invalid UUID format');
285
+ });
286
+
287
+ it('ignores non-resource keys', () => {
288
+ expect(() =>
289
+ validateResourceIdsInObject({
290
+ query: 'what? growth%',
291
+ name: '../etc/passwd',
292
+ }),
293
+ ).not.toThrow();
294
+ });
295
+
296
+ it('handles null and undefined', () => {
297
+ expect(() => validateResourceIdsInObject(null)).not.toThrow();
298
+ expect(() => validateResourceIdsInObject(undefined)).not.toThrow();
299
+ });
300
+ });
301
+ });
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Descriptor-driven argument validation for CLI and MCP tools (RFC Phase 0).
3
+ * Validates known resource identifier keys with semantic type rules.
4
+ */
5
+
6
+ import {
7
+ rejectControlChars,
8
+ validateFingerprint,
9
+ validateSlug,
10
+ validateUuid,
11
+ validateUuidOrSlug,
12
+ } from './input-validation';
13
+
14
+ /** Object keys whose string values are treated as resource identifiers. */
15
+ export const RESOURCE_ID_KEYS = new Set([
16
+ 'project',
17
+ 'projectUuid',
18
+ 'projectUuids',
19
+ 'projects',
20
+ 'agentUuid',
21
+ 'threadUuid',
22
+ 'messageUuid',
23
+ 'promptUuid',
24
+ 'evalUuid',
25
+ 'runUuid',
26
+ 'artifactUuid',
27
+ 'versionUuid',
28
+ 'versionUuidA',
29
+ 'versionUuidB',
30
+ 'mcpServerUuid',
31
+ 'toolCallId',
32
+ 'fingerprint',
33
+ 'savedQueryUuid',
34
+ 'slug',
35
+ 'userUuid',
36
+ 'groupUuid',
37
+ 'spaceUuid',
38
+ 'spaceUuids',
39
+ 'parentSpaceUuid',
40
+ 'targetSpaceUuid',
41
+ 'itemUuids',
42
+ 'roleUuid',
43
+ 'dashboardUuid',
44
+ 'dashboardUuidOrSlug',
45
+ 'sourceDashboardUuid',
46
+ 'schedulerUuid',
47
+ 'organizationUuid',
48
+ 'chartUuid',
49
+ 'chartUuidOrSlug',
50
+ 'sourceChartUuidOrSlug',
51
+ 'contentUuidOrSlug',
52
+ 'tileUuid',
53
+ 'newSlug',
54
+ ]);
55
+
56
+ /** Keys that accept OpenAPI UuidOrSlug (UUID or slug), not UUID-only. */
57
+ const UUID_OR_SLUG_KEYS = new Set([
58
+ 'dashboardUuid',
59
+ 'dashboardUuidOrSlug',
60
+ 'chartUuid',
61
+ 'chartUuidOrSlug',
62
+ 'sourceChartUuidOrSlug',
63
+ 'contentUuidOrSlug',
64
+ ]);
65
+
66
+ export type ArgumentSource = 'body' | 'option' | 'positional';
67
+
68
+ export type ArgumentSemanticType =
69
+ 'boolean' | 'fingerprint' | 'free-text' | 'json' | 'number' | 'slug' | 'uuid-or-slug' | 'uuid';
70
+
71
+ /** Per-argument validation metadata supplied by CLI/MCP command definitions. */
72
+ export interface ArgumentDescriptor {
73
+ name: string;
74
+ source: ArgumentSource;
75
+ semanticType: ArgumentSemanticType;
76
+ required?: boolean;
77
+ }
78
+
79
+ function isMissing(value: unknown): boolean {
80
+ return value === undefined || value === null;
81
+ }
82
+
83
+ function requireString(value: unknown, name: string, label: string): string {
84
+ if (typeof value !== 'string') {
85
+ throw new Error(`Argument '${name}' must be a string ${label}`);
86
+ }
87
+ return value;
88
+ }
89
+
90
+ function validateUuidArgument(value: unknown, name: string): void {
91
+ validateUuid(requireString(value, name, 'UUID'));
92
+ }
93
+
94
+ function validateSlugArgument(value: unknown, name: string): void {
95
+ validateSlug(requireString(value, name, 'slug'));
96
+ }
97
+
98
+ function validateFingerprintArgument(value: unknown, name: string): void {
99
+ validateFingerprint(requireString(value, name, 'fingerprint'));
100
+ }
101
+
102
+ function validateFreeTextArgument(value: unknown, _name: string): void {
103
+ if (typeof value === 'string') {
104
+ rejectControlChars(value);
105
+ }
106
+ }
107
+
108
+ function validateJsonArgument(value: unknown, name: string): void {
109
+ if (typeof value !== 'string') {
110
+ return;
111
+ }
112
+ rejectControlChars(value);
113
+ try {
114
+ JSON.parse(value);
115
+ } catch {
116
+ throw new Error(`Argument '${name}' must be valid JSON`);
117
+ }
118
+ }
119
+
120
+ function validateBooleanArgument(value: unknown, name: string): void {
121
+ if (typeof value !== 'boolean') {
122
+ throw new Error(`Argument '${name}' must be a boolean`);
123
+ }
124
+ }
125
+
126
+ function validateNumberArgument(value: unknown, name: string): void {
127
+ if (typeof value !== 'number' || Number.isNaN(value)) {
128
+ throw new Error(`Argument '${name}' must be a number`);
129
+ }
130
+ }
131
+
132
+ function validateUuidOrSlugArgument(value: unknown, name: string): void {
133
+ validateUuidOrSlug(requireString(value, name, 'UUID or slug'));
134
+ }
135
+
136
+ function validateBySemanticType(
137
+ value: unknown,
138
+ semanticType: ArgumentSemanticType,
139
+ name: string,
140
+ ): void {
141
+ switch (semanticType) {
142
+ case 'boolean':
143
+ validateBooleanArgument(value, name);
144
+ break;
145
+ case 'fingerprint':
146
+ validateFingerprintArgument(value, name);
147
+ break;
148
+ case 'free-text':
149
+ validateFreeTextArgument(value, name);
150
+ break;
151
+ case 'json':
152
+ validateJsonArgument(value, name);
153
+ break;
154
+ case 'number':
155
+ validateNumberArgument(value, name);
156
+ break;
157
+ case 'slug':
158
+ validateSlugArgument(value, name);
159
+ break;
160
+ case 'uuid':
161
+ validateUuidArgument(value, name);
162
+ break;
163
+ case 'uuid-or-slug':
164
+ validateUuidOrSlugArgument(value, name);
165
+ break;
166
+ default: {
167
+ const exhaustive: never = semanticType;
168
+ throw new Error(`Unknown semantic type: ${exhaustive}`);
169
+ }
170
+ }
171
+ }
172
+
173
+ function validateResourceIdValue(key: string, value: string): void {
174
+ if (key === 'slug' || key === 'newSlug') {
175
+ validateSlug(value);
176
+ return;
177
+ }
178
+ if (key === 'fingerprint' || key === 'toolCallId') {
179
+ validateFingerprint(value);
180
+ return;
181
+ }
182
+ if (UUID_OR_SLUG_KEYS.has(key)) {
183
+ validateUuidOrSlug(value);
184
+ return;
185
+ }
186
+ validateUuid(value);
187
+ }
188
+
189
+ function validateResourceIdValues(key: string, value: unknown): void {
190
+ if (typeof value === 'string') {
191
+ validateResourceIdValue(key, value);
192
+ return;
193
+ }
194
+ if (Array.isArray(value)) {
195
+ for (const item of value) {
196
+ if (typeof item !== 'string') {
197
+ throw new Error(`Argument '${key}' must be a string or string array`);
198
+ }
199
+ validateResourceIdValue(key, item);
200
+ }
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Validates tool arguments against explicit descriptors.
206
+ * Identifier semantic types (`uuid`, `slug`, `fingerprint`) receive strict validation.
207
+ */
208
+ export function validateArguments(
209
+ args: Record<string, unknown>,
210
+ descriptors: ArgumentDescriptor[],
211
+ ): void {
212
+ for (const descriptor of descriptors) {
213
+ const value = args[descriptor.name];
214
+ if (isMissing(value)) {
215
+ if (descriptor.required) {
216
+ throw new Error(`Required argument '${descriptor.name}' is missing`);
217
+ }
218
+ continue;
219
+ }
220
+
221
+ if (Array.isArray(value)) {
222
+ for (const item of value) {
223
+ validateBySemanticType(item, descriptor.semanticType, descriptor.name);
224
+ }
225
+ } else {
226
+ validateBySemanticType(value, descriptor.semanticType, descriptor.name);
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Recursively walks an object (and nested arrays/objects) and validates any
233
+ * string value under a key in {@link RESOURCE_ID_KEYS}.
234
+ */
235
+ export function validateResourceIdsInObject(obj: unknown): void {
236
+ if (obj === null || obj === undefined) {
237
+ return;
238
+ }
239
+
240
+ if (Array.isArray(obj)) {
241
+ for (const item of obj) {
242
+ validateResourceIdsInObject(item);
243
+ }
244
+ return;
245
+ }
246
+
247
+ if (typeof obj !== 'object') {
248
+ return;
249
+ }
250
+
251
+ const record = obj as Record<string, unknown>;
252
+ for (const [key, value] of Object.entries(record)) {
253
+ if (RESOURCE_ID_KEYS.has(key)) {
254
+ validateResourceIdValues(key, value);
255
+ }
256
+ validateResourceIdsInObject(value);
257
+ }
258
+ }
@@ -0,0 +1,87 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ import { afterEach, describe, expect, it, vi } from 'vitest';
6
+
7
+ import { closeAuditLog, getSessionId, initAuditLog, logAuditEntry } from './audit';
8
+
9
+ describe('audit', () => {
10
+ const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
11
+
12
+ afterEach(() => {
13
+ stderrSpy.mockClear();
14
+ });
15
+
16
+ it('getSessionId returns a stable UUID for the process', () => {
17
+ expect(getSessionId()).toMatch(
18
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
19
+ );
20
+ expect(getSessionId()).toBe(getSessionId());
21
+ });
22
+
23
+ it('initAuditLog announces stderr destination when no file path is given', () => {
24
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
25
+ try {
26
+ initAuditLog();
27
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
28
+ expect.stringContaining('[audit] Writing to stderr'),
29
+ );
30
+ } finally {
31
+ consoleErrorSpy.mockRestore();
32
+ }
33
+ });
34
+
35
+ it('logAuditEntry writes NDJSON to stderr by default', () => {
36
+ initAuditLog();
37
+
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
+ });
47
+
48
+ const auditLine = stderrSpy.mock.calls
49
+ .map(([chunk]) => String(chunk))
50
+ .find((line) => line.includes('"tool":"test_tool"'));
51
+ 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"');
56
+ });
57
+
58
+ it('logAuditEntry appends to a file when initAuditLog receives a path', async () => {
59
+ const dir = mkdtempSync(join(tmpdir(), 'audit-test-'));
60
+ const filePath = join(dir, 'audit.ndjson');
61
+
62
+ try {
63
+ initAuditLog(filePath);
64
+
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
+ });
73
+
74
+ await closeAuditLog();
75
+
76
+ // filePath is a temp path from mkdtempSync in this test only
77
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
78
+ 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"');
82
+ } finally {
83
+ await closeAuditLog();
84
+ rmSync(dir, { recursive: true, force: true });
85
+ }
86
+ });
87
+ });
package/src/audit.ts CHANGED
@@ -2,17 +2,29 @@
2
2
  * Structured audit logger for Lightdash tool invocations (MCP and CLI).
3
3
  *
4
4
  * Each operation is recorded as a single NDJSON line containing:
5
- * timestamp, sessionId, tool/command name, projectUuids (if present), status, and durationMs.
5
+ * timestamp, sessionId, tool/command name, projectUuids (if present), status, durationMs,
6
+ * and optional OAuth attribution fields (tokenHash, subject) when available.
6
7
  *
7
8
  * Output destination:
8
9
  * - If LIGHTDASH_TOOLS_AUDIT_LOG is set to a file path, entries are appended to that file.
9
10
  * - Otherwise entries are written to stderr with an "[audit]" prefix.
10
11
  */
11
12
 
12
- import { createWriteStream, type WriteStream } from 'node:fs';
13
13
  import { randomUUID } from 'node:crypto';
14
+ import { createWriteStream, type WriteStream } from 'node:fs';
14
15
 
15
- export type AuditStatus = 'success' | 'error' | 'blocked';
16
+ export type AuditStatus =
17
+ | 'blocked'
18
+ | 'confirmation_cancelled'
19
+ | 'confirmation_declined'
20
+ | 'confirmation_requested'
21
+ | 'deletion_failed'
22
+ | 'deletion_succeeded'
23
+ | 'error'
24
+ | 'promotion_failed'
25
+ | 'promotion_succeeded'
26
+ | 'resource_changed'
27
+ | 'success';
16
28
 
17
29
  export type AuditLogEntry = {
18
30
  timestamp: string;
@@ -21,6 +33,10 @@ export type AuditLogEntry = {
21
33
  tool: string;
22
34
  /** Project UUIDs involved in the call, if any (covers both projectUuid and projectUuids[]). */
23
35
  projectUuids?: string[];
36
+ /** SHA-256 hash of the OAuth bearer token (never the raw token). */
37
+ tokenHash?: string;
38
+ /** Lightdash user UUID when the call runs under OAuth bearer auth. */
39
+ subject?: string;
24
40
  status: AuditStatus;
25
41
  durationMs: number;
26
42
  };
@@ -59,3 +75,16 @@ export function logAuditEntry(entry: AuditLogEntry): void {
59
75
  process.stderr.write(`[audit] ${line}`);
60
76
  }
61
77
  }
78
+
79
+ /** Closes the file stream, if any. Awaits pending writes before resolving. */
80
+ export function closeAuditLog(): Promise<void> {
81
+ const stream = _writeStream;
82
+ if (!stream) return Promise.resolve();
83
+ return new Promise((resolve, reject) => {
84
+ stream.end(() => {
85
+ _writeStream = undefined;
86
+ resolve();
87
+ });
88
+ stream.on('error', reject);
89
+ });
90
+ }