@astralkit/cli 4.2.0 → 4.2.2

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.
@@ -130,6 +130,57 @@ export async function initCommand(options) {
130
130
  p.log.success(`Created ${pc.cyan(defaultCssRelative)}`);
131
131
  }
132
132
 
133
+ // ─── Step 4b: Tailwind v3 plugin registration ─────────
134
+ //
135
+ // In v3, the @theme directive doesn't exist, so ak-* utility classes
136
+ // (bg-ak-bg, text-ak-text, p-ak-2, etc.) only work if the Tailwind
137
+ // config extends the theme. The astralkit/tailwind plugin does this.
138
+ //
139
+ if (tailwindVersion === 3) {
140
+ const configPath = path.join(process.cwd(), 'tailwind.config.js');
141
+ const configPathTs = path.join(process.cwd(), 'tailwind.config.ts');
142
+ const configFile = fs.existsSync(configPathTs) ? configPathTs : (fs.existsSync(configPath) ? configPath : null);
143
+
144
+ if (configFile) {
145
+ const configContent = fs.readFileSync(configFile, 'utf8');
146
+ if (!configContent.includes('astralkit/tailwind')) {
147
+ // Insert the plugin require into the plugins array
148
+ const pluginLine = "require('astralkit/tailwind.cjs')";
149
+
150
+ // Match `plugins` followed by optional whitespace/newlines and an
151
+ // opening bracket. Covers:
152
+ // plugins: [ (current format)
153
+ // plugins:[ (no space)
154
+ // plugins: \n [ (newline before bracket)
155
+ // plugins = [ (variable assignment style, rare)
156
+ const arrayOpenRe = /plugins\s*[:=]\s*\[/;
157
+
158
+ if (arrayOpenRe.test(configContent)) {
159
+ // plugins array exists — inject after the opening bracket, preserving
160
+ // the user's indentation style as best we can
161
+ const updated = configContent.replace(
162
+ arrayOpenRe,
163
+ (match) => `${match}\n ${pluginLine},`
164
+ );
165
+ fs.writeFileSync(configFile, updated, 'utf8');
166
+ p.log.success(`Added AstralKit plugin to ${pc.cyan(path.relative(process.cwd(), configFile))}`);
167
+ } else if (/plugins\s*[:=]/.test(configContent)) {
168
+ // plugins key exists but not as an array — warn
169
+ p.log.warn('Could not auto-add plugin to tailwind config (plugins is not an array literal).');
170
+ p.log.info(`Add manually: ${pc.cyan(pluginLine)} to your plugins array.`);
171
+ } else {
172
+ p.log.warn('No plugins array found in tailwind config.');
173
+ p.log.info(`Add manually: ${pc.cyan(`plugins: [${pluginLine}]`)}`);
174
+ }
175
+ } else {
176
+ p.log.step('AstralKit Tailwind plugin already registered');
177
+ }
178
+ } else {
179
+ p.log.warn('No tailwind.config found. AstralKit Tailwind v3 plugin not registered.');
180
+ p.log.info(`Create one and add: ${pc.cyan("plugins: [require('astralkit/tailwind.cjs')]")}`);
181
+ }
182
+ }
183
+
133
184
  // ─── Step 5: AI rules file ───────────────────────────
134
185
  const rulesFile = 'astralkit-ai-rules.md';
135
186
  const rulesPath = path.join(process.cwd(), rulesFile);
@@ -142,7 +193,7 @@ export async function initCommand(options) {
142
193
  p.outro(pc.green('AstralKit is ready!'));
143
194
 
144
195
  console.log();
145
- console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add pricing-table'));
196
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add button-variants'));
146
197
  console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
147
198
  console.log();
148
199
  }
@@ -1,6 +1,11 @@
1
1
  import pc from 'picocolors';
2
2
  import * as p from '@clack/prompts';
3
3
  import { listComponents, listBoosters, listWorkflows } from '../lib/api.js';
4
+ import { sanitizeForTerminal } from '../lib/validators.js';
5
+
6
+ // Server-supplied string passthrough protection — strips ANSI/control sequences
7
+ // before printing. Prevents a malicious API from rewriting the terminal.
8
+ const s = (v) => sanitizeForTerminal(v || '');
4
9
 
5
10
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React', html: 'HTML' };
6
11
 
@@ -30,9 +35,9 @@ export async function listCommand(options) {
30
35
  for (const item of items) {
31
36
  const proTag = item.is_pro ? pc.magenta(' [PRO]') : pc.green(' [FREE]');
32
37
  const fw = item.frameworks?.map(f => FRAMEWORK_LABELS[f] || f).join(', ') || '';
33
- console.log(` ${pc.cyan(item.slug || item.name)}${proTag}`);
34
- if (item.description) console.log(pc.gray(` ${item.description}`));
35
- if (fw) console.log(pc.gray(` Frameworks: ${fw}`));
38
+ console.log(` ${pc.cyan(s(item.slug || item.name))}${proTag}`);
39
+ if (item.description) console.log(pc.gray(` ${s(item.description)}`));
40
+ if (fw) console.log(pc.gray(` Frameworks: ${s(fw)}`));
36
41
  console.log();
37
42
  }
38
43
 
@@ -3,8 +3,13 @@ import path from 'path';
3
3
  import pc from 'picocolors';
4
4
  import * as p from '@clack/prompts';
5
5
  import { getProjectConfig, detectFramework } from '../lib/config.js';
6
+ import { validateSlug } from '../lib/validators.js';
6
7
 
7
8
  export async function removeCommand(name, options) {
9
+ // Reject anything that isn't a simple slug. Prevents `astralkit remove ../..`
10
+ // resolving to real filesystem targets and prompting the user to rm -rf them.
11
+ if (!validateSlug(name, 'component or booster name')) process.exit(1);
12
+
8
13
  const config = getProjectConfig();
9
14
  const framework = config?.framework || detectFramework();
10
15
  const componentsDir = config?.componentsDir || 'src/components/ui';
@@ -1,6 +1,9 @@
1
1
  import pc from 'picocolors';
2
2
  import * as p from '@clack/prompts';
3
3
  import { listComponents, listBoosters, listWorkflows } from '../lib/api.js';
4
+ import { sanitizeForTerminal } from '../lib/validators.js';
5
+
6
+ const s = (v) => sanitizeForTerminal(v || '');
4
7
 
5
8
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React', html: 'HTML' };
6
9
 
@@ -42,9 +45,9 @@ export async function searchCommand(query, options) {
42
45
  const typeLabel = item._type ? pc.gray(` [${item._type}]`) : '';
43
46
  const proTag = item.is_pro ? pc.magenta(' [PRO]') : pc.green(' [FREE]');
44
47
  const fw = item.frameworks?.map(f => FRAMEWORK_LABELS[f] || f).join(', ') || '';
45
- console.log(` ${pc.cyan(item.slug || item.name)}${typeLabel}${proTag}`);
46
- if (item.description) console.log(pc.gray(` ${item.description}`));
47
- if (fw) console.log(pc.gray(` Frameworks: ${fw}`));
48
+ console.log(` ${pc.cyan(s(item.slug || item.name))}${typeLabel}${proTag}`);
49
+ if (item.description) console.log(pc.gray(` ${s(item.description)}`));
50
+ if (fw) console.log(pc.gray(` Frameworks: ${s(fw)}`));
48
51
  console.log();
49
52
  }
50
53
 
package/src/lib/api.js CHANGED
@@ -16,8 +16,15 @@ export const API_BASE = (() => {
16
16
  if (!override) return DEFAULT_API_BASE;
17
17
  try {
18
18
  const parsed = new URL(override);
19
- if (parsed.protocol !== 'https:') {
20
- console.warn('\x1b[33m⚠ ASTRALKIT_API_URL uses insecure protocol.\x1b[0m');
19
+ // HTTP is only allowed for explicit localhost — otherwise the API key and
20
+ // bearer token would be sent in cleartext over the network.
21
+ const isLocalhost =
22
+ parsed.hostname === 'localhost' ||
23
+ parsed.hostname === '127.0.0.1' ||
24
+ parsed.hostname === '::1';
25
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLocalhost)) {
26
+ console.error('\x1b[31m✖ ASTRALKIT_API_URL must use https:// (or http:// localhost for dev). Falling back to default.\x1b[0m');
27
+ return DEFAULT_API_BASE;
21
28
  }
22
29
  } catch {
23
30
  console.error('\x1b[31m✖ Invalid ASTRALKIT_API_URL. Falling back to default.\x1b[0m');
@@ -92,7 +99,12 @@ export async function apiRequest(urlPath, options = {}) {
92
99
 
93
100
  if (!response.ok) {
94
101
  const body = await response.text().catch(() => '');
95
- const err = new Error(`API error ${response.status}: ${body || response.statusText}`);
102
+ // Strip control characters + truncate — server response body ends up in
103
+ // console.error, and a malicious server can inject ANSI cursor moves or
104
+ // clear-screen sequences to spoof later prompts.
105
+ // eslint-disable-next-line no-control-regex
106
+ const safeBody = (body || response.statusText || '').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '').slice(0, 500);
107
+ const err = new Error(`API error ${response.status}: ${safeBody}`);
96
108
  err.code = 'API_ERROR';
97
109
  throw err;
98
110
  }
package/src/lib/config.js CHANGED
@@ -45,7 +45,15 @@ export function detectTailwindVersion(dir = process.cwd()) {
45
45
  const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
46
46
  const ver = allDeps['tailwindcss'];
47
47
  if (!ver) return null;
48
- const major = parseInt(ver.replace(/[^0-9]/, ''), 10);
48
+ // Handle: "^4.0.0", "~4.1.2", "4.0.0-beta.1", ">=3.4.0", "file:...", "latest", "next".
49
+ // Strip only the leading non-digits (^ ~ >= etc.) then parse. Anything
50
+ // that doesn't start with a digit after stripping (file:..., latest, next,
51
+ // workspace:*) returns NaN from parseInt and falls through to null —
52
+ // better to return null than guess wrong.
53
+ const match = ver.match(/^\D*(\d+)/);
54
+ if (!match) return null;
55
+ const major = parseInt(match[1], 10);
56
+ if (Number.isNaN(major)) return null;
49
57
  if (major >= 4) return 4;
50
58
  if (major >= 3) return 3;
51
59
  return null;
@@ -78,11 +86,12 @@ export function findCssEntryFile(dir = process.cwd()) {
78
86
 
79
87
  export function getRequiredCssImports(tailwindVersion) {
80
88
  if (tailwindVersion === 3) {
89
+ // v3: no @import "astralkit/theme" — the @theme directive is v4-only.
90
+ // The astralkit/tailwind plugin handles token registration for v3 via addBase.
81
91
  return [
82
92
  '@tailwind base;',
83
93
  '@tailwind components;',
84
94
  '@tailwind utilities;',
85
- '@import "astralkit/theme";',
86
95
  '@import "astralkit/utilities";',
87
96
  ];
88
97
  }
@@ -123,6 +132,33 @@ export function getMissingCssImports(cssFilePath, tailwindVersion) {
123
132
 
124
133
  export function addCssImports(cssFilePath, imports) {
125
134
  const existing = fs.existsSync(cssFilePath) ? fs.readFileSync(cssFilePath, 'utf8') : '';
135
+ const astralkitImports = imports.filter(i => i.includes('astralkit'));
136
+
137
+ // If Tailwind is already imported/directive'd in the file (v3 @tailwind
138
+ // directives OR v4 @import "tailwindcss"), insert astralkit imports AFTER
139
+ // the last Tailwind-related line. This preserves the recommended ordering
140
+ // (tailwindcss first, astralkit after) instead of prepending astralkit
141
+ // imports before tailwindcss in the file.
142
+ const tailwindImportRe = /^@import\s+["']tailwindcss["']/;
143
+ const hasTailwind = existing.includes('@tailwind utilities') || tailwindImportRe.test(existing);
144
+
145
+ if (hasTailwind && astralkitImports.length > 0) {
146
+ const lines = existing.split('\n');
147
+ let lastTailwindIdx = -1;
148
+ for (let i = 0; i < lines.length; i++) {
149
+ const trimmed = lines[i].trim();
150
+ if (trimmed.startsWith('@tailwind') || tailwindImportRe.test(trimmed)) {
151
+ lastTailwindIdx = i;
152
+ }
153
+ }
154
+ if (lastTailwindIdx >= 0) {
155
+ lines.splice(lastTailwindIdx + 1, 0, '', ...astralkitImports);
156
+ fs.writeFileSync(cssFilePath, lines.join('\n'));
157
+ return;
158
+ }
159
+ }
160
+
161
+ // Default: prepend everything (fresh file with no Tailwind yet)
126
162
  fs.writeFileSync(cssFilePath, imports.join('\n') + '\n\n' + existing);
127
163
  }
128
164
 
@@ -3,9 +3,24 @@ import path from 'path';
3
3
  import { execa } from 'execa';
4
4
 
5
5
  export function detectPackageManager(dir = process.cwd()) {
6
- if (fs.existsSync(path.join(dir, 'bun.lockb')) || fs.existsSync(path.join(dir, 'bun.lock'))) return 'bun';
7
- if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
8
- if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
6
+ // Walk up from `dir` to the filesystem root, stopping at the first lockfile
7
+ // found. Handles monorepos where the lockfile lives at the workspace root
8
+ // (e.g., running `astralkit init` inside `packages/my-app/` of a pnpm repo).
9
+ let current = path.resolve(dir);
10
+ const { root } = path.parse(current);
11
+
12
+ while (true) {
13
+ if (fs.existsSync(path.join(current, 'bun.lockb')) || fs.existsSync(path.join(current, 'bun.lock'))) return 'bun';
14
+ if (fs.existsSync(path.join(current, 'pnpm-lock.yaml'))) return 'pnpm';
15
+ if (fs.existsSync(path.join(current, 'yarn.lock'))) return 'yarn';
16
+ if (fs.existsSync(path.join(current, 'package-lock.json'))) return 'npm';
17
+
18
+ if (current === root) break;
19
+ const parent = path.dirname(current);
20
+ if (parent === current) break; // belt-and-suspenders against infinite loops
21
+ current = parent;
22
+ }
23
+
9
24
  return 'npm';
10
25
  }
11
26
 
@@ -5,6 +5,59 @@ import pc from 'picocolors';
5
5
  export const VALID_FRAMEWORKS = ['html', 'react', 'nextjs'];
6
6
  export const SLUG_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
7
7
 
8
+ // Valid npm package name. Optional scope (@scope/), then a lowercase-start
9
+ // token with a-z / 0-9 / dot / dash / underscore. Blocks anything that could
10
+ // be mistaken for an npm flag ("--foo", "-S"), absolute paths, urls, or
11
+ // tarball specs.
12
+ // Does NOT allow version specifiers — callers should validate / strip those
13
+ // separately if they support them.
14
+ export const NPM_PACKAGE_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
15
+
16
+ export function validateNpmPackageName(name) {
17
+ if (typeof name !== 'string' || name.length === 0 || name.length > 214) return false;
18
+ // Split off optional version suffix (@1.2.3 or @^1.0.0) to validate the
19
+ // package-name portion only. Scoped packages complicate this — they start
20
+ // with @ and then we look for the LAST @ to split off version.
21
+ let pkgName = name;
22
+ if (name.startsWith('@')) {
23
+ // @scope/name[@version]
24
+ const atIdx = name.indexOf('@', 1);
25
+ if (atIdx !== -1) pkgName = name.slice(0, atIdx);
26
+ } else {
27
+ const atIdx = name.indexOf('@');
28
+ if (atIdx !== -1) pkgName = name.slice(0, atIdx);
29
+ }
30
+ return NPM_PACKAGE_PATTERN.test(pkgName);
31
+ }
32
+
33
+ /**
34
+ * Filter a list of package names down to a validated subset.
35
+ * Logs rejected entries. Returns { accepted, rejected }.
36
+ */
37
+ export function filterSafePackages(pkgs) {
38
+ const accepted = [];
39
+ const rejected = [];
40
+ for (const pkg of pkgs || []) {
41
+ if (validateNpmPackageName(pkg)) accepted.push(pkg);
42
+ else rejected.push(pkg);
43
+ }
44
+ return { accepted, rejected };
45
+ }
46
+
47
+ /**
48
+ * Strip ANSI / control / cursor-manipulation sequences from server-supplied
49
+ * strings before logging them to the user's terminal. Defends against
50
+ * terminal-injection attacks where a malicious server tries to spoof prompts,
51
+ * clear the screen, or rewrite prior output.
52
+ */
53
+ export function sanitizeForTerminal(str) {
54
+ if (typeof str !== 'string') return '';
55
+ // Strip C0 (0x00-0x1F) and DEL (0x7F) control characters, plus most
56
+ // C1 / CSI sequences. Keep tab (0x09), LF (0x0A), CR (0x0D) for formatting.
57
+ // eslint-disable-next-line no-control-regex
58
+ return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
59
+ }
60
+
8
61
  export function validateFramework(framework) {
9
62
  if (!framework) return true;
10
63
  if (VALID_FRAMEWORKS.includes(framework)) return true;
@@ -34,6 +87,58 @@ export function isSafePath(basedir, filepath) {
34
87
  return !relative.startsWith('..') && !path.isAbsolute(relative);
35
88
  }
36
89
 
90
+ /**
91
+ * Validate that a server-supplied install directory stays within the user's
92
+ * current project. Rejects absolute paths, traversal, and any value that
93
+ * resolves outside cwd.
94
+ *
95
+ * This is the primary guard against a compromised or malicious API server
96
+ * writing files to `/etc`, `~/.ssh`, `%APPDATA%`, etc.
97
+ */
98
+ export function isSafeInstallDir(cwd, requestedDir) {
99
+ if (typeof requestedDir !== 'string' || !requestedDir) return false;
100
+ if (path.isAbsolute(requestedDir)) return false;
101
+ if (requestedDir.includes('..')) return false;
102
+ const resolved = path.resolve(cwd, requestedDir);
103
+ const relative = path.relative(cwd, resolved);
104
+ return !relative.startsWith('..') && !path.isAbsolute(relative);
105
+ }
106
+
107
+ // Files that must never be overwritten by a server-directed install.
108
+ // Includes env files, lockfiles, git metadata, shell dotfiles, CI configs,
109
+ // package manager configs, and Next.js config.
110
+ const SENSITIVE_FILE_PATTERNS = [
111
+ /^\.env(\..+)?$/i,
112
+ /^\.npmrc$/i,
113
+ /^\.yarnrc(\..+)?$/i,
114
+ /^\.pnpmfile\.cjs$/i,
115
+ /^package\.json$/i,
116
+ /^package-lock\.json$/i,
117
+ /^yarn\.lock$/i,
118
+ /^pnpm-lock\.yaml$/i,
119
+ /^bun\.lockb?$/i,
120
+ /^next\.config\.(js|ts|mjs|cjs)$/i,
121
+ /^\.gitignore$/i,
122
+ /^\.git\b/i,
123
+ /^\.github\b/i,
124
+ /^\.circleci\b/i,
125
+ /^\.husky\b/i,
126
+ /^\.vscode\b/i,
127
+ /^\.ssh\b/i,
128
+ /^\.bash/i,
129
+ /^\.zsh/i,
130
+ /^\.profile$/i,
131
+ /^authorized_keys$/i,
132
+ ];
133
+
134
+ export function isSensitivePath(relPath) {
135
+ if (typeof relPath !== 'string') return true;
136
+ // Normalize separators and strip leading ./
137
+ const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '');
138
+ const segments = normalized.split('/').filter(Boolean);
139
+ return segments.some(seg => SENSITIVE_FILE_PATTERNS.some(re => re.test(seg)));
140
+ }
141
+
37
142
  export function writeFiles(baseDir, files) {
38
143
  let count = 0;
39
144
  for (const file of files) {
@@ -41,6 +146,10 @@ export function writeFiles(baseDir, files) {
41
146
  console.log(pc.red(` Skipping suspicious path: ${file.path}`));
42
147
  continue;
43
148
  }
149
+ if (isSensitivePath(file.path)) {
150
+ console.log(pc.red(` Skipping sensitive path: ${file.path}`));
151
+ continue;
152
+ }
44
153
  const filePath = path.resolve(baseDir, file.path);
45
154
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
46
155
  fs.writeFileSync(filePath, file.content);