frakment 3.0.0 → 3.0.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.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "frakment",
3
- "version": "3.0.0",
3
+ "version": "3.0.1",
4
4
  "description": "MIT-licensed CLI and design system for the Frakment component registry",
5
5
  "keywords": [
6
6
  "components",
@@ -11,7 +11,7 @@ var __rest = (this && this.__rest) || function (s, e) {
11
11
  };
12
12
  import { createHash } from "node:crypto";
13
13
  import { existsSync } from "node:fs";
14
- import { lstat, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
14
+ import { readFile } from "node:fs/promises";
15
15
  import path from "node:path";
16
16
  import chalk from "chalk";
17
17
  import { execa } from "execa";
@@ -19,6 +19,8 @@ import ora from "ora";
19
19
  import prompts from "prompts";
20
20
  import { detectPackageManager, findProjectRoot } from "../utils/detect.js";
21
21
  import { logger } from "../utils/logger.js";
22
+ import { resolveSafePath as assertSafePath, writeFileWithinProject, } from "../utils/safe-path.js";
23
+ export { assertSafePath };
22
24
  const componentNamePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
23
25
  const dependencyPattern = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:@[0-9A-Za-z*~^<>=|.+_-]+)?$/u;
24
26
  const maxRegistryPayloadBytes = 10 * 1024 * 1024;
@@ -74,9 +76,12 @@ function assertDependency(dependency) {
74
76
  throw new Error(`Invalid dependency in registry payload: ${String(dependency)}`);
75
77
  }
76
78
  }
77
- const getDependencyName = (dependency) => {
79
+ export const getDependencyName = (dependency) => {
78
80
  if (dependency.startsWith("@")) {
79
- return dependency.slice(0, dependency.indexOf("@", 1));
81
+ const versionSeparator = dependency.indexOf("@", 1);
82
+ return versionSeparator === -1
83
+ ? dependency
84
+ : dependency.slice(0, versionSeparator);
80
85
  }
81
86
  return dependency.split("@")[0];
82
87
  };
@@ -181,57 +186,26 @@ async function fetchComponent(name, registryUrl, spinner) {
181
186
  process.exit(1);
182
187
  }
183
188
  }
184
- export async function assertSafePath(cwd, relativePath) {
185
- if (typeof relativePath !== "string" || relativePath.length === 0) {
186
- throw new Error("Invalid file path in registry payload");
187
- }
188
- if (relativePath.includes("\0")) {
189
- throw new Error(`Null byte in path: ${relativePath}`);
190
- }
191
- if (path.isAbsolute(relativePath) || /^[a-zA-Z]:/.test(relativePath)) {
192
- throw new Error(`Absolute path rejected: ${relativePath}`);
193
- }
194
- if (relativePath.split(/[\\/]/).some((seg) => seg === "..")) {
195
- throw new Error(`Parent traversal rejected: ${relativePath}`);
196
- }
197
- const root = path.resolve(cwd);
198
- const target = path.resolve(root, relativePath);
199
- if (target !== root && !target.startsWith(root + path.sep)) {
200
- throw new Error(`Path escapes project root: ${relativePath}`);
201
- }
202
- const realRoot = await realpath(root).catch(() => root);
203
- let existingParent = path.dirname(target);
204
- while (!existsSync(existingParent)) {
205
- existingParent = path.dirname(existingParent);
206
- }
207
- const realParent = await realpath(existingParent).catch(() => existingParent);
208
- if (realParent !== realRoot && !realParent.startsWith(realRoot + path.sep)) {
209
- throw new Error(`Symlink escape rejected: ${relativePath}`);
210
- }
211
- if (existsSync(target) && (await lstat(target)).isSymbolicLink()) {
212
- throw new Error(`Symlink target rejected: ${relativePath}`);
213
- }
214
- return target;
215
- }
216
189
  async function writeFileSafely(file, cwd, options, aliases) {
217
190
  const targetPath = await assertSafePath(cwd, file.path);
218
- if (existsSync(targetPath) && !options.overwrite) {
219
- const { overwrite } = await prompts({
191
+ let overwrite = options.overwrite === true;
192
+ if (existsSync(targetPath) && !overwrite) {
193
+ const { overwrite: shouldOverwrite } = await prompts({
220
194
  initial: false,
221
195
  message: `${file.path} already exists. Overwrite?`,
222
196
  name: "overwrite",
223
197
  type: "confirm",
224
198
  });
225
- if (overwrite === undefined || !overwrite) {
199
+ if (shouldOverwrite === undefined || !shouldOverwrite) {
226
200
  logger.info(`Skipped ${file.path}.`);
227
201
  return null;
228
202
  }
203
+ overwrite = true;
229
204
  }
230
- await mkdir(path.dirname(targetPath), { recursive: true });
231
205
  const output = file.encoding === "base64"
232
206
  ? Buffer.from(file.content, "base64")
233
207
  : rewriteImports(file.content, aliases).replaceAll("\r\n", "\n");
234
- await writeFile(targetPath, output);
208
+ await writeFileWithinProject(cwd, file.path, output, overwrite);
235
209
  return file.path;
236
210
  }
237
211
  export async function add(componentNamesInput, options = {}) {
@@ -374,6 +348,7 @@ export async function add(componentNamesInput, options = {}) {
374
348
  catch (error) {
375
349
  s.fail("Failed to install dependencies.");
376
350
  logger.warn(error instanceof Error ? error.message : "Unknown error");
351
+ process.exitCode = 1;
377
352
  }
378
353
  }
379
354
  }
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import chalk from "chalk";
5
5
  import { execa } from "execa";
@@ -7,6 +7,7 @@ import ora from "ora";
7
7
  import prompts from "prompts";
8
8
  import { detectGlobalsCss, detectPackageManager, findProjectRoot, } from "../utils/detect.js";
9
9
  import { logger } from "../utils/logger.js";
10
+ import { resolveSafePath, writeFileWithinProject } from "../utils/safe-path.js";
10
11
  const __dirname = import.meta.dirname;
11
12
  const templatesDir = path.resolve(__dirname, "../../templates");
12
13
  const defaultRegistry = "https://www.arrafi.dev/frakment/r";
@@ -28,7 +29,7 @@ export async function init() {
28
29
  process.exit(1);
29
30
  }
30
31
  const cssPath = detectGlobalsCss(cwd);
31
- const cssFullPath = path.join(cwd, cssPath);
32
+ const cssFullPath = await resolveSafePath(cwd, cssPath);
32
33
  const cssCheck = ora("Verifying Tailwind CSS config").start();
33
34
  if (!existsSync(cssFullPath)) {
34
35
  cssCheck.fail(`CSS file not found: ${cssPath}`);
@@ -43,7 +44,7 @@ export async function init() {
43
44
  process.exit(1);
44
45
  }
45
46
  cssCheck.succeed(`Verifying Tailwind CSS config. Found ${chalk.cyan("v4")} in ${chalk.cyan(cssPath)}.`);
46
- const configPath = path.join(cwd, configFile);
47
+ const configPath = await resolveSafePath(cwd, configFile);
47
48
  const configExists = existsSync(configPath);
48
49
  let shouldWriteConfig = !configExists;
49
50
  if (configExists) {
@@ -68,7 +69,7 @@ export async function init() {
68
69
  const s = ora("Writing components.json").start();
69
70
  const template = JSON.parse(await readFile(path.join(templatesDir, "components.json"), "utf-8"));
70
71
  const config = Object.assign(Object.assign({}, template), { registry: defaultRegistry, tailwind: Object.assign(Object.assign({}, template.tailwind), { css: cssPath }) });
71
- await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`);
72
+ await writeFileWithinProject(cwd, configFile, `${JSON.stringify(config, null, 2)}\n`);
72
73
  s.succeed("Writing components.json.");
73
74
  }
74
75
  const themeSpinner = ora("Updating CSS variables").start();
@@ -91,12 +92,12 @@ export async function init() {
91
92
  else {
92
93
  css = `${css.trimEnd()}\n\n${wrapped}\n`;
93
94
  }
94
- await writeFile(cssFullPath, css);
95
+ await writeFileWithinProject(cwd, cssPath, css);
95
96
  themeSpinner.succeed(`Updating CSS variables in ${cssPath}`);
96
- if (!existsSync(path.join(cwd, "lib/utils.ts"))) {
97
+ const utilsPath = await resolveSafePath(cwd, "lib/utils.ts");
98
+ if (!existsSync(utilsPath)) {
97
99
  const s = ora("Creating lib/utils.ts").start();
98
- await mkdir(path.join(cwd, "lib"), { recursive: true });
99
- await writeFile(path.join(cwd, "lib/utils.ts"), `import { clsx, type ClassValue } from "clsx";
100
+ await writeFileWithinProject(cwd, "lib/utils.ts", `import { clsx, type ClassValue } from "clsx";
100
101
  import { twMerge } from "tailwind-merge";
101
102
 
102
103
  export function cn(...inputs: ClassValue[]) {
@@ -106,13 +107,13 @@ export function cn(...inputs: ClassValue[]) {
106
107
  s.succeed("Created 1 file:");
107
108
  logger.log(" - lib/utils.ts");
108
109
  }
109
- if (existsSync(path.join(cwd, "lib/motion.ts"))) {
110
+ const motionPath = await resolveSafePath(cwd, "lib/motion.ts");
111
+ if (existsSync(motionPath)) {
110
112
  }
111
113
  else {
112
114
  const s = ora("Creating lib/motion.ts").start();
113
- await mkdir(path.join(cwd, "lib"), { recursive: true });
114
115
  const motion = await readFile(path.join(templatesDir, "lib/motion.ts"), "utf-8");
115
- await writeFile(path.join(cwd, "lib/motion.ts"), motion);
116
+ await writeFileWithinProject(cwd, "lib/motion.ts", motion);
116
117
  s.succeed("Created 1 file:");
117
118
  logger.log(" - lib/motion.ts");
118
119
  }
@@ -137,6 +138,8 @@ export function cn(...inputs: ClassValue[]) {
137
138
  catch (error) {
138
139
  s.fail("Failed to install dependencies.");
139
140
  logger.warn(error instanceof Error ? error.message : "Unknown error");
141
+ process.exitCode = 1;
142
+ return;
140
143
  }
141
144
  }
142
145
  logger.break();
@@ -5,8 +5,17 @@ import chalk from "chalk";
5
5
  import ora from "ora";
6
6
  import { findProjectRoot } from "../utils/detect.js";
7
7
  import { logger } from "../utils/logger.js";
8
+ import { resolveRegistryUrl } from "./add.js";
9
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10
+ export const isRegistryIndex = (value) => isRecord(value) &&
11
+ Array.isArray(value.components) &&
12
+ value.components.every((component) => isRecord(component) &&
13
+ typeof component.name === "string" &&
14
+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(component.name) &&
15
+ (component.description === undefined ||
16
+ typeof component.description === "string"));
8
17
  export async function list(options) {
9
- var _a, _b;
18
+ var _a;
10
19
  let cwd;
11
20
  const preflight = ora("Preflight checks").start();
12
21
  try {
@@ -23,19 +32,33 @@ export async function list(options) {
23
32
  logger.info("Run `frakment init` first.");
24
33
  process.exit(1);
25
34
  }
26
- const config = JSON.parse(await readFile(configPath, "utf-8"));
27
- const registryUrl = ((_a = options.registry) !== null && _a !== void 0 ? _a : config.registry).replace(/\/$/u, "");
35
+ let registryUrl;
36
+ try {
37
+ const configRaw = await readFile(configPath, "utf-8");
38
+ const config = JSON.parse(configRaw.replace(/^\uFEFF/u, ""));
39
+ registryUrl = resolveRegistryUrl(config, options);
40
+ }
41
+ catch (error) {
42
+ logger.error(error instanceof Error ? error.message : "Invalid components.json.");
43
+ process.exit(1);
44
+ }
28
45
  const s = ora("Fetching components").start();
29
46
  let index;
30
47
  try {
31
- const res = await fetch(`${registryUrl}/index.json`);
48
+ const res = await fetch(`${registryUrl}/index.json`, {
49
+ signal: AbortSignal.timeout(30000),
50
+ });
32
51
  if (!res.ok) {
33
52
  throw new Error(`HTTP ${res.status}`);
34
53
  }
35
- index = await res.json();
54
+ const response = await res.json();
55
+ if (!isRegistryIndex(response)) {
56
+ throw new Error("Registry index has an invalid shape");
57
+ }
58
+ index = response;
36
59
  }
37
- catch (_c) {
38
- s.fail("Failed to fetch component list.");
60
+ catch (error) {
61
+ s.fail(`Failed to fetch component list: ${error instanceof Error ? error.message : "unknown error"}`);
39
62
  process.exit(1);
40
63
  }
41
64
  s.succeed(`Found ${index.components.length} component(s).`);
@@ -47,7 +70,7 @@ export async function list(options) {
47
70
  const nameWidth = Math.max(...index.components.map((c) => c.name.length));
48
71
  logger.break();
49
72
  for (const c of index.components) {
50
- logger.log(` ${chalk.cyan(c.name.padEnd(nameWidth))} ${chalk.dim((_b = c.description) !== null && _b !== void 0 ? _b : "")}`);
73
+ logger.log(` ${chalk.cyan(c.name.padEnd(nameWidth))} ${chalk.dim((_a = c.description) !== null && _a !== void 0 ? _a : "")}`);
51
74
  }
52
75
  logger.break();
53
76
  logger.log(`Add one with ${chalk.cyan("frakment add <name>")}`);
@@ -17,6 +17,9 @@ export function detectPackageManager(cwd) {
17
17
  if (existsSync(path.join(cwd, "yarn.lock"))) {
18
18
  return "yarn";
19
19
  }
20
+ if (existsSync(path.join(cwd, "bun.lock"))) {
21
+ return "bun";
22
+ }
20
23
  if (existsSync(path.join(cwd, "bun.lockb"))) {
21
24
  return "bun";
22
25
  }
@@ -0,0 +1,93 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { link, lstat, mkdir, realpath, rename, rm, writeFile, } from "node:fs/promises";
3
+ import path from "node:path";
4
+ const isWithin = (root, target) => {
5
+ const relative = path.relative(root, target);
6
+ return (relative === "" ||
7
+ (relative !== ".." &&
8
+ !relative.startsWith(`..${path.sep}`) &&
9
+ !path.isAbsolute(relative)));
10
+ };
11
+ const isPathMissing = (error) => error instanceof Error && "code" in error && error.code === "ENOENT";
12
+ export async function resolveSafePath(cwd, relativePath) {
13
+ if (typeof relativePath !== "string" || relativePath.length === 0) {
14
+ throw new Error("Invalid file path in registry payload");
15
+ }
16
+ if (relativePath.includes("\0")) {
17
+ throw new Error(`Null byte in path: ${relativePath}`);
18
+ }
19
+ if (path.isAbsolute(relativePath) ||
20
+ path.win32.isAbsolute(relativePath) ||
21
+ /^[a-zA-Z]:/u.test(relativePath)) {
22
+ throw new Error(`Absolute path rejected: ${relativePath}`);
23
+ }
24
+ if (relativePath.split(/[\\/]/u).some((segment) => segment === "..")) {
25
+ throw new Error(`Parent traversal rejected: ${relativePath}`);
26
+ }
27
+ const root = await realpath(path.resolve(cwd));
28
+ const target = path.resolve(root, relativePath);
29
+ if (!isWithin(root, target)) {
30
+ throw new Error(`Path escapes project root: ${relativePath}`);
31
+ }
32
+ let existingAncestor = path.dirname(target);
33
+ let realAncestor;
34
+ while (true) {
35
+ try {
36
+ realAncestor = await realpath(existingAncestor);
37
+ break;
38
+ }
39
+ catch (error) {
40
+ if (!isPathMissing(error)) {
41
+ throw error;
42
+ }
43
+ const parent = path.dirname(existingAncestor);
44
+ if (parent === existingAncestor) {
45
+ throw error;
46
+ }
47
+ existingAncestor = parent;
48
+ }
49
+ }
50
+ if (!isWithin(root, realAncestor)) {
51
+ throw new Error(`Symlink escape rejected: ${relativePath}`);
52
+ }
53
+ const canonicalTarget = path.resolve(realAncestor, path.relative(existingAncestor, target));
54
+ if (!isWithin(root, canonicalTarget)) {
55
+ throw new Error(`Path escapes project root: ${relativePath}`);
56
+ }
57
+ try {
58
+ if ((await lstat(target)).isSymbolicLink()) {
59
+ throw new Error(`Symlink target rejected: ${relativePath}`);
60
+ }
61
+ }
62
+ catch (error) {
63
+ if (!isPathMissing(error)) {
64
+ throw error;
65
+ }
66
+ }
67
+ return canonicalTarget;
68
+ }
69
+ export async function writeFileWithinProject(cwd, relativePath, contents, overwrite = true) {
70
+ const initialTarget = await resolveSafePath(cwd, relativePath);
71
+ await mkdir(path.dirname(initialTarget), { recursive: true });
72
+ const target = await resolveSafePath(cwd, relativePath);
73
+ const parent = await realpath(path.dirname(target));
74
+ const root = await realpath(path.resolve(cwd));
75
+ if (!isWithin(root, parent)) {
76
+ throw new Error(`Symlink escape rejected: ${relativePath}`);
77
+ }
78
+ const canonicalTarget = path.join(parent, path.basename(target));
79
+ const temporary = path.join(parent, `.frakment-${randomUUID()}.tmp`);
80
+ await writeFile(temporary, contents, { flag: "wx" });
81
+ try {
82
+ if (overwrite) {
83
+ await rename(temporary, canonicalTarget);
84
+ }
85
+ else {
86
+ await link(temporary, canonicalTarget);
87
+ }
88
+ }
89
+ finally {
90
+ await rm(temporary, { force: true });
91
+ }
92
+ return canonicalTarget;
93
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "frakment",
3
- "version": "3.0.0",
3
+ "version": "3.0.1",
4
4
  "description": "MIT-licensed CLI and design system for the Frakment component registry",
5
5
  "keywords": [
6
6
  "components",