@lightdash-tools/common 0.4.0 → 0.6.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.
@@ -3,5 +3,4 @@
3
3
  * This file was auto-generated by openapi-typescript.
4
4
  * Do not make direct changes to the file.
5
5
  */
6
- /* eslint-disable no-irregular-whitespace */
7
6
  Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/common",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Shared utilities and types for Lightdash AI.",
5
5
  "keywords": [],
6
6
  "license": "Apache-2.0",
@@ -8,7 +8,7 @@
8
8
  "main": "dist/index.js",
9
9
  "types": "dist/index.d.ts",
10
10
  "devDependencies": {
11
- "@types/node": "^25.2.3",
11
+ "@types/node": "^25.3.4",
12
12
  "openapi-typescript": "^7.13.0"
13
13
  },
14
14
  "scripts": {
package/src/audit.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * timestamp, sessionId, tool/command name, projectUuids (if present), status, and durationMs.
6
6
  *
7
7
  * Output destination:
8
- * - If LIGHTDASH_AUDIT_LOG is set to a file path, entries are appended to that file.
8
+ * - If LIGHTDASH_TOOLS_AUDIT_LOG is set to a file path, entries are appended to that file.
9
9
  * - Otherwise entries are written to stderr with an "[audit]" prefix.
10
10
  */
11
11
 
package/src/env.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Environment variable names for lightdash-tools.
3
+ * All project-specific vars use the LIGHTDASH_TOOLS_ prefix to distinguish
4
+ * from official Lightdash vars (LIGHTDASH_URL, LIGHTDASH_API_KEY).
5
+ */
6
+
7
+ export const ENV_LIGHTDASH_TOOLS_DRY_RUN = 'LIGHTDASH_TOOLS_DRY_RUN';
8
+ export const ENV_LIGHTDASH_TOOLS_AUDIT_LOG = 'LIGHTDASH_TOOLS_AUDIT_LOG';
9
+ export const ENV_LIGHTDASH_TOOLS_SAFETY_MODE = 'LIGHTDASH_TOOLS_SAFETY_MODE';
10
+ export const ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECTS = 'LIGHTDASH_TOOLS_ALLOWED_PROJECTS';
package/src/index.ts CHANGED
@@ -2,9 +2,15 @@ export function greet(name: string): string {
2
2
  return `Hello, ${name}!`;
3
3
  }
4
4
 
5
+ // Export env var constants
6
+ export * from './env';
7
+
5
8
  // Export safety logic
6
9
  export * from './safety';
7
10
 
11
+ // Export input validation
12
+ export * from './input-validation';
13
+
8
14
  // Export audit logger (shared by MCP and CLI)
9
15
  export * from './audit';
10
16
 
@@ -0,0 +1,107 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { rejectControlChars, validateResourceId, validateSafeOutputDir } from './input-validation';
3
+
4
+ describe('input-validation', () => {
5
+ describe('rejectControlChars', () => {
6
+ it('accepts empty string', () => {
7
+ expect(rejectControlChars('')).toBe('');
8
+ });
9
+
10
+ it('accepts clean ASCII strings', () => {
11
+ expect(rejectControlChars('hello')).toBe('hello');
12
+ expect(rejectControlChars('project-123')).toBe('project-123');
13
+ expect(rejectControlChars('a b c')).toBe('a b c');
14
+ });
15
+
16
+ it('throws on null character', () => {
17
+ expect(() => rejectControlChars('x\u0000y')).toThrow(
18
+ 'Input contains invalid control characters',
19
+ );
20
+ });
21
+
22
+ it('throws on newline in user string', () => {
23
+ expect(() => rejectControlChars('x\ny')).toThrow('Input contains invalid control characters');
24
+ });
25
+
26
+ it('throws on other control chars', () => {
27
+ expect(() => rejectControlChars('\x01')).toThrow();
28
+ expect(() => rejectControlChars('a\x1fb')).toThrow();
29
+ });
30
+
31
+ it('allows space (0x20)', () => {
32
+ expect(rejectControlChars('a b')).toBe('a b');
33
+ });
34
+ });
35
+
36
+ describe('validateResourceId', () => {
37
+ it('accepts valid UUID', () => {
38
+ expect(validateResourceId('550e8400-e29b-41d4-a716-446655440000')).toBe(
39
+ '550e8400-e29b-41d4-a716-446655440000',
40
+ );
41
+ });
42
+
43
+ it('accepts safe slug', () => {
44
+ expect(validateResourceId('my-chart-slug')).toBe('my-chart-slug');
45
+ expect(validateResourceId('chart_123')).toBe('chart_123');
46
+ });
47
+
48
+ it('throws on ? in ID', () => {
49
+ expect(() => validateResourceId('uuid?fields=name')).toThrow('Resource ID must not contain');
50
+ });
51
+
52
+ it('throws on # in ID', () => {
53
+ expect(() => validateResourceId('uuid#fragment')).toThrow('Resource ID must not contain');
54
+ });
55
+
56
+ it('throws on % in ID', () => {
57
+ expect(() => validateResourceId('uuid%2e')).toThrow('Resource ID must not contain');
58
+ });
59
+
60
+ it('throws on path traversal', () => {
61
+ expect(() => validateResourceId('../etc/passwd')).toThrow('Resource ID must not contain');
62
+ expect(() => validateResourceId('uuid/../other')).toThrow('Resource ID must not contain');
63
+ });
64
+
65
+ it('throws on control chars', () => {
66
+ expect(() => validateResourceId('x\u0000y')).toThrow(
67
+ 'Input contains invalid control characters',
68
+ );
69
+ });
70
+
71
+ it('throws when id is not a string', () => {
72
+ expect(() => validateResourceId(123 as unknown as string)).toThrow(
73
+ 'Resource ID must be a string',
74
+ );
75
+ });
76
+ });
77
+
78
+ describe('validateSafeOutputDir', () => {
79
+ it('accepts path within CWD', () => {
80
+ const result = validateSafeOutputDir('output');
81
+ expect(result).toContain(process.cwd());
82
+ });
83
+
84
+ it('accepts relative subdir', async () => {
85
+ const pathModule = await import('node:path');
86
+ const result = validateSafeOutputDir('foo/bar');
87
+ expect(result).toBe(pathModule.resolve(process.cwd(), 'foo/bar'));
88
+ });
89
+
90
+ it('throws on .. traversal', () => {
91
+ expect(() => validateSafeOutputDir('../other')).toThrow(
92
+ 'Path must be within current working directory',
93
+ );
94
+ });
95
+
96
+ it('throws on .. traversal escaping CWD', () => {
97
+ expect(() => validateSafeOutputDir('../../etc')).toThrow(
98
+ 'Path must be within current working directory',
99
+ );
100
+ });
101
+
102
+ it('accepts CWD itself', () => {
103
+ const result = validateSafeOutputDir('.');
104
+ expect(result).toBe(process.cwd());
105
+ });
106
+ });
107
+ });
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Input validation for agent-invoked CLI and MCP tools.
3
+ * Guards against hallucinated or adversarial inputs (control chars, path injection, query params in IDs).
4
+ *
5
+ * @see https://justin.poehnelt.com/posts/rewrite-your-cli-for-ai-agents/
6
+ */
7
+
8
+ import * as path from 'node:path';
9
+
10
+ const FORBIDDEN_IN_RESOURCE_ID = /[?#%]|\.\./;
11
+
12
+ function hasControlChars(str: string): boolean {
13
+ for (let i = 0; i < str.length; i++) {
14
+ if (str.charCodeAt(i) < 0x20) return true;
15
+ }
16
+ return false;
17
+ }
18
+
19
+ /**
20
+ * Rejects strings containing ASCII control characters (code < 0x20).
21
+ * Agents may generate invisible characters; humans rarely do.
22
+ *
23
+ * @param str - User-provided string to validate
24
+ * @returns The input string if valid
25
+ * @throws Error if control characters are present
26
+ */
27
+ export function rejectControlChars(str: string): string {
28
+ if (str === '') return str;
29
+ if (hasControlChars(str)) {
30
+ throw new Error('Input contains invalid control characters');
31
+ }
32
+ return str;
33
+ }
34
+
35
+ /**
36
+ * Validates a resource ID (projectUuid, slug, etc.) to prevent path/query injection.
37
+ * Rejects: ?, #, %, .., and control characters.
38
+ * Accepts: valid UUIDs and safe slugs (alphanumeric, hyphen, underscore).
39
+ *
40
+ * @param id - Resource ID to validate
41
+ * @returns The input if valid
42
+ * @throws Error if forbidden characters are present
43
+ */
44
+ export function validateResourceId(id: string): string {
45
+ if (typeof id !== 'string') {
46
+ throw new Error('Resource ID must be a string');
47
+ }
48
+ rejectControlChars(id);
49
+ if (FORBIDDEN_IN_RESOURCE_ID.test(id)) {
50
+ throw new Error('Resource ID must not contain ?, #, %, or path traversal (..)');
51
+ }
52
+ return id;
53
+ }
54
+
55
+ /**
56
+ * Validates that a file path is safe for output within the current working directory.
57
+ * Rejects: .. traversal, absolute paths outside CWD.
58
+ *
59
+ * @param filePath - Path to validate (relative or absolute)
60
+ * @returns Resolved absolute path within CWD
61
+ * @throws Error if path escapes CWD
62
+ */
63
+ export function validateSafeOutputDir(filePath: string): string {
64
+ const cwd = process.cwd();
65
+ const resolved = path.resolve(cwd, filePath);
66
+ const cwdNormalized = path.resolve(cwd);
67
+ if (resolved !== cwdNormalized && !resolved.startsWith(cwdNormalized + path.sep)) {
68
+ throw new Error(`Path must be within current working directory: ${cwd}`);
69
+ }
70
+ return resolved;
71
+ }
@@ -39,24 +39,24 @@ describe('Safety Logic', () => {
39
39
  });
40
40
 
41
41
  describe('getSafetyModeFromEnv', () => {
42
- const originalEnv = process.env.LIGHTDASH_TOOL_SAFETY_MODE;
42
+ const originalEnv = process.env.LIGHTDASH_TOOLS_SAFETY_MODE;
43
43
 
44
44
  afterEach(() => {
45
- process.env.LIGHTDASH_TOOL_SAFETY_MODE = originalEnv;
45
+ process.env.LIGHTDASH_TOOLS_SAFETY_MODE = originalEnv;
46
46
  });
47
47
 
48
48
  it('should return READ_ONLY by default when env is not set', () => {
49
- delete process.env.LIGHTDASH_TOOL_SAFETY_MODE;
49
+ delete process.env.LIGHTDASH_TOOLS_SAFETY_MODE;
50
50
  expect(getSafetyModeFromEnv()).toBe(SafetyMode.READ_ONLY);
51
51
  });
52
52
 
53
53
  it('should return value from env when set to valid mode', () => {
54
- process.env.LIGHTDASH_TOOL_SAFETY_MODE = SafetyMode.WRITE_IDEMPOTENT;
54
+ process.env.LIGHTDASH_TOOLS_SAFETY_MODE = SafetyMode.WRITE_IDEMPOTENT;
55
55
  expect(getSafetyModeFromEnv()).toBe(SafetyMode.WRITE_IDEMPOTENT);
56
56
  });
57
57
 
58
58
  it('should return READ_ONLY when env is set to invalid value', () => {
59
- process.env.LIGHTDASH_TOOL_SAFETY_MODE = 'invalid-mode';
59
+ process.env.LIGHTDASH_TOOLS_SAFETY_MODE = 'invalid-mode';
60
60
  expect(getSafetyModeFromEnv()).toBe(SafetyMode.READ_ONLY);
61
61
  });
62
62
  });
package/src/safety.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { ENV_LIGHTDASH_TOOLS_SAFETY_MODE, ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECTS } from './env';
2
+
1
3
  /**
2
4
  * Hierarchical safety modes for Lightdash AI tools and CLI.
3
5
  */
@@ -63,7 +65,7 @@ export function isAllowed(mode: SafetyMode | string, annotations: ToolAnnotation
63
65
  * Resolves safety mode from environment variable.
64
66
  */
65
67
  export function getSafetyModeFromEnv(): SafetyMode {
66
- const mode = process.env.LIGHTDASH_TOOL_SAFETY_MODE;
68
+ const mode = process.env[ENV_LIGHTDASH_TOOLS_SAFETY_MODE];
67
69
  if (Object.values(SafetyMode).includes(mode as SafetyMode)) {
68
70
  return mode as SafetyMode;
69
71
  }
@@ -78,7 +80,7 @@ export function getSafetyModeFromEnv(): SafetyMode {
78
80
  * Note: CLI/MCP flags (--allowed-projects) always take priority over this env var.
79
81
  */
80
82
  export function getAllowedProjectUuidsFromEnv(): string[] {
81
- const raw = process.env.LIGHTDASH_TOOLS_ALLOWED_PROJECTS ?? '';
83
+ const raw = process.env[ENV_LIGHTDASH_TOOLS_ALLOWED_PROJECTS] ?? '';
82
84
  return raw
83
85
  .split(',')
84
86
  .map((s) => s.trim())