@astralkit/cli 4.2.0 → 4.2.1

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,48 @@ 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
+ if (configContent.includes('plugins: [')) {
151
+ // plugins array exists — add to it
152
+ const updated = configContent.replace(
153
+ /plugins:\s*\[/,
154
+ `plugins: [\n ${pluginLine},`
155
+ );
156
+ fs.writeFileSync(configFile, updated, 'utf8');
157
+ p.log.success(`Added AstralKit plugin to ${pc.cyan(path.relative(process.cwd(), configFile))}`);
158
+ } else if (configContent.includes('plugins:')) {
159
+ // plugins exists but not as array — warn
160
+ p.log.warn('Could not auto-add plugin to tailwind config.');
161
+ p.log.info(`Add manually: ${pc.cyan(pluginLine)} to your plugins array.`);
162
+ } else {
163
+ p.log.warn('No plugins array found in tailwind config.');
164
+ p.log.info(`Add manually: ${pc.cyan(`plugins: [${pluginLine}]`)}`);
165
+ }
166
+ } else {
167
+ p.log.step('AstralKit Tailwind plugin already registered');
168
+ }
169
+ } else {
170
+ p.log.warn('No tailwind.config found. AstralKit Tailwind v3 plugin not registered.');
171
+ p.log.info(`Create one and add: ${pc.cyan("plugins: [require('astralkit/tailwind.cjs')]")}`);
172
+ }
173
+ }
174
+
133
175
  // ─── Step 5: AI rules file ───────────────────────────
134
176
  const rulesFile = 'astralkit-ai-rules.md';
135
177
  const rulesPath = path.join(process.cwd(), rulesFile);
@@ -142,7 +184,7 @@ export async function initCommand(options) {
142
184
  p.outro(pc.green('AstralKit is ready!'));
143
185
 
144
186
  console.log();
145
- console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add pricing-table'));
187
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add button-variants'));
146
188
  console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
147
189
  console.log();
148
190
  }
@@ -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
@@ -78,11 +78,12 @@ export function findCssEntryFile(dir = process.cwd()) {
78
78
 
79
79
  export function getRequiredCssImports(tailwindVersion) {
80
80
  if (tailwindVersion === 3) {
81
+ // v3: no @import "astralkit/theme" — the @theme directive is v4-only.
82
+ // The astralkit/tailwind plugin handles token registration for v3 via addBase.
81
83
  return [
82
84
  '@tailwind base;',
83
85
  '@tailwind components;',
84
86
  '@tailwind utilities;',
85
- '@import "astralkit/theme";',
86
87
  '@import "astralkit/utilities";',
87
88
  ];
88
89
  }
@@ -123,6 +124,27 @@ export function getMissingCssImports(cssFilePath, tailwindVersion) {
123
124
 
124
125
  export function addCssImports(cssFilePath, imports) {
125
126
  const existing = fs.existsSync(cssFilePath) ? fs.readFileSync(cssFilePath, 'utf8') : '';
127
+
128
+ // Separate Tailwind directives from AstralKit imports
129
+ const tailwindDirectives = imports.filter(i => i.startsWith('@tailwind') || i === '@import "tailwindcss";');
130
+ const astralkitImports = imports.filter(i => i.includes('astralkit'));
131
+
132
+ // For v3: if @tailwind directives already exist, add astralkit imports AFTER them
133
+ if (existing.includes('@tailwind utilities')) {
134
+ // Find the last @tailwind line and insert after it
135
+ const lines = existing.split('\n');
136
+ let lastTailwindIdx = -1;
137
+ for (let i = 0; i < lines.length; i++) {
138
+ if (lines[i].trim().startsWith('@tailwind')) lastTailwindIdx = i;
139
+ }
140
+ if (lastTailwindIdx >= 0 && astralkitImports.length > 0) {
141
+ lines.splice(lastTailwindIdx + 1, 0, '', ...astralkitImports);
142
+ fs.writeFileSync(cssFilePath, lines.join('\n'));
143
+ return;
144
+ }
145
+ }
146
+
147
+ // Default: prepend everything (v4 or fresh file)
126
148
  fs.writeFileSync(cssFilePath, imports.join('\n') + '\n\n' + existing);
127
149
  }
128
150
 
@@ -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);