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