frakment 4.0.0 → 5.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/bin/index.js CHANGED
@@ -29,6 +29,7 @@ program
29
29
  .description("Add one or more components from the frakment registry")
30
30
  .option("--dry-run", "Show planned file and dependency changes without writing")
31
31
  .option("--registry <url>", "Custom registry URL")
32
+ .option("--allow-untrusted-registry", "Allow installing unsigned files from a custom registry")
32
33
  .option("--skip-dependencies", "Do not install missing npm dependencies")
33
34
  .option("--overwrite", "Overwrite existing files", false)
34
35
  .action(add);
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "frakment",
3
- "version": "4.0.0",
3
+ "version": "5.0.1",
4
4
  "description": "MIT-licensed CLI and design system for the Frakment component registry",
5
5
  "keywords": [
6
6
  "components",
@@ -39,10 +39,10 @@
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/prompts": "^2.4.9",
42
- "@types/react": "19.3.0",
42
+ "@types/react": "19.3.3",
43
43
  "clsx": "^2.1.1",
44
44
  "react": "19.3.1",
45
- "tailwind-merge": "^3.7.1"
45
+ "tailwind-merge": "^3.7.3"
46
46
  },
47
47
  "engines": {
48
48
  "node": ">=22.22.2"
@@ -12,6 +12,7 @@ var __rest = (this && this.__rest) || function (s, e) {
12
12
  import { createHash } from "node:crypto";
13
13
  import { existsSync } from "node:fs";
14
14
  import { readFile } from "node:fs/promises";
15
+ import { createRequire } from "node:module";
15
16
  import path from "node:path";
16
17
  import chalk from "chalk";
17
18
  import { execa } from "execa";
@@ -19,15 +20,27 @@ import ora from "ora";
19
20
  import prompts from "prompts";
20
21
  import { detectPackageManager, findProjectRoot } from "../utils/detect.js";
21
22
  import { logger } from "../utils/logger.js";
23
+ import { assertSecureRegistryUrl, fetchRegistryResponse, readLimitedResponse, } from "../utils/registry-http.js";
22
24
  import { resolveSafePath as assertSafePath, writeFileWithinProject, } from "../utils/safe-path.js";
23
25
  export { assertSafePath };
24
26
  const componentNamePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
25
27
  const dependencyPattern = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*(?:@[0-9A-Za-z*~^<>=|.+_-]+)?$/u;
26
28
  const maxRegistryPayloadBytes = 10 * 1024 * 1024;
27
29
  const maxRegistryManifestBytes = 1024 * 1024;
30
+ const maxTotalRegistryPayloadBytes = 50 * 1024 * 1024;
31
+ const maxTotalInstallBytes = 50 * 1024 * 1024;
32
+ const maxRegistryComponents = 512;
28
33
  const defaultWebRegistry = "https://www.arrafi.dev/frakment/r";
29
- const registryManifestUrl = "https://github.com/frakment/ui/releases/download/registry/manifest.json";
30
- const registrySignatureUrl = "https://github.com/frakment/ui/releases/download/registry/manifest.sigstore.json";
34
+ const cliPackage = createRequire(import.meta.url)("../../package.json");
35
+ if (typeof cliPackage !== "object" ||
36
+ cliPackage === null ||
37
+ !("version" in cliPackage) ||
38
+ typeof cliPackage.version !== "string") {
39
+ throw new Error("CLI package version is unavailable");
40
+ }
41
+ const registryReleaseUrl = `https://github.com/frakment/ui/releases/download/${encodeURIComponent(`frakment@${cliPackage.version}`)}`;
42
+ const registryManifestUrl = `${registryReleaseUrl}/manifest.json`;
43
+ const registrySignatureUrl = `${registryReleaseUrl}/manifest.sigstore.json`;
31
44
  const registrySignerIdentity = "^https://github\\.com/frakment/ui/\\.github/workflows/registry-sign\\.yml@refs/heads/main$";
32
45
  const sigstoreIssuer = "https://token.actions.githubusercontent.com";
33
46
  const defaultAliases = {
@@ -71,32 +84,33 @@ const canonicalize = (value) => {
71
84
  const createIntegrity = (payload) => `sha256:${createHash("sha256")
72
85
  .update(canonicalize(payload), "utf8")
73
86
  .digest("hex")}`;
74
- async function fetchRegistryText(url, maxBytes) {
75
- const response = await fetch(url, { signal: AbortSignal.timeout(10000) });
87
+ async function fetchRegistryBytes(url, maxBytes) {
88
+ var _a;
89
+ const response = await fetchRegistryResponse(url, AbortSignal.timeout(10000));
76
90
  if (!response.ok) {
91
+ await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
77
92
  throw new Error(`HTTP ${response.status} from ${url}`);
78
93
  }
79
- const contentLength = Number(response.headers.get("content-length"));
80
- if (Number.isFinite(contentLength) && contentLength > maxBytes) {
81
- throw new Error(`Response from ${url} is too large`);
82
- }
83
- const raw = await response.text();
84
- if (Buffer.byteLength(raw, "utf8") > maxBytes) {
85
- throw new Error(`Response from ${url} is too large`);
86
- }
87
- return raw;
94
+ return readLimitedResponse(response, maxBytes, url);
88
95
  }
89
- export async function fetchSignedRegistryManifest() {
90
- const [manifestRaw, signatureRaw] = await Promise.all([
91
- fetchRegistryText(registryManifestUrl, maxRegistryManifestBytes),
92
- fetchRegistryText(registrySignatureUrl, maxRegistryManifestBytes),
96
+ const officialRegistryManifestSource = {
97
+ certificateIdentityURI: registrySignerIdentity,
98
+ certificateIssuer: sigstoreIssuer,
99
+ manifestUrl: registryManifestUrl,
100
+ signatureUrl: registrySignatureUrl,
101
+ };
102
+ const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
103
+ export async function fetchSignedRegistryManifest(source = officialRegistryManifestSource) {
104
+ const [manifestBytes, signatureBytes] = await Promise.all([
105
+ fetchRegistryBytes(source.manifestUrl, maxRegistryManifestBytes),
106
+ fetchRegistryBytes(source.signatureUrl, maxRegistryManifestBytes),
93
107
  ]);
94
- const manifest = JSON.parse(manifestRaw);
95
- const signature = JSON.parse(signatureRaw);
108
+ const manifest = JSON.parse(manifestBytes.toString("utf8"));
109
+ const signature = JSON.parse(signatureBytes.toString("utf8"));
96
110
  const sigstore = await import("sigstore");
97
- await sigstore.verify(signature, Buffer.from(manifestRaw, "utf8"), {
98
- certificateIdentityURI: registrySignerIdentity,
99
- certificateIssuer: sigstoreIssuer,
111
+ await sigstore.verify(signature, manifestBytes, {
112
+ certificateIdentityURI: source.certificateIdentityURI,
113
+ certificateIssuer: source.certificateIssuer,
100
114
  });
101
115
  if (!isRecord(manifest) ||
102
116
  manifest.version !== 1 ||
@@ -117,13 +131,46 @@ export async function fetchSignedRegistryManifest() {
117
131
  export function verifySignedRegistryFile(name, raw, manifest) {
118
132
  const expectedDigest = manifest.files[name];
119
133
  const actualDigest = `sha256:${createHash("sha256")
120
- .update(raw, "utf8")
134
+ .update(typeof raw === "string" ? Buffer.from(raw, "utf8") : raw)
121
135
  .digest("hex")}`;
122
136
  if (!expectedDigest || expectedDigest !== actualDigest) {
123
137
  throw new Error(`Registry file ${name} does not match the signed manifest`);
124
138
  }
125
139
  }
126
140
  export const isOfficialRegistryUrl = (url) => url === defaultWebRegistry;
141
+ export function resolveRegistryTrustPolicy(value) {
142
+ if (value === undefined) {
143
+ return undefined;
144
+ }
145
+ if (!isRecord(value)) {
146
+ throw new Error("registryTrust must specify a Sigstore identity and issuer");
147
+ }
148
+ const certificateIdentityURI = value.certificateIdentityURI;
149
+ const certificateIssuer = value.certificateIssuer;
150
+ if (typeof certificateIdentityURI !== "string" ||
151
+ typeof certificateIssuer !== "string") {
152
+ throw new Error("registryTrust must specify a Sigstore identity and issuer");
153
+ }
154
+ for (const trustedUrl of [certificateIdentityURI, certificateIssuer]) {
155
+ const url = new URL(trustedUrl);
156
+ if (url.protocol !== "https:" ||
157
+ url.username ||
158
+ url.password ||
159
+ url.search ||
160
+ url.hash) {
161
+ throw new Error("registryTrust identity and issuer must be HTTPS URLs");
162
+ }
163
+ }
164
+ return { certificateIdentityURI, certificateIssuer };
165
+ }
166
+ export function customRegistryManifestSource(registryUrl, trust) {
167
+ return {
168
+ certificateIdentityURI: `^${escapeRegex(trust.certificateIdentityURI)}$`,
169
+ certificateIssuer: trust.certificateIssuer,
170
+ manifestUrl: `${registryUrl}/manifest.json`,
171
+ signatureUrl: `${registryUrl}/manifest.sigstore.json`,
172
+ };
173
+ }
127
174
  function assertComponentName(name) {
128
175
  if (typeof name !== "string" || !componentNamePattern.test(name)) {
129
176
  throw new Error(`Invalid component name: ${String(name)}`);
@@ -184,6 +231,10 @@ export const validateRegistryPayload = (payload, expectedName) => {
184
231
  const registryDependencies = Array.isArray(payload.registryDependencies)
185
232
  ? payload.registryDependencies
186
233
  : [];
234
+ if (dependencies.length > maxRegistryComponents ||
235
+ registryDependencies.length > maxRegistryComponents) {
236
+ throw new Error("Registry payload has too many dependencies");
237
+ }
187
238
  for (const dependency of dependencies) {
188
239
  assertDependency(dependency);
189
240
  }
@@ -196,11 +247,23 @@ export const validateRegistryPayload = (payload, expectedName) => {
196
247
  }
197
248
  return payload;
198
249
  };
199
- const getRegistryUrl = (value) => {
200
- const url = new URL(value);
201
- if (url.protocol !== "http:" && url.protocol !== "https:") {
202
- throw new Error("Registry URL must use HTTP or HTTPS");
250
+ export function getTotalInstalledBytes(payloads, maxBytes = maxTotalInstallBytes) {
251
+ let totalBytes = 0;
252
+ for (const payload of payloads) {
253
+ for (const file of payload.files) {
254
+ const fileBytes = file.encoding === "base64"
255
+ ? Buffer.from(file.content, "base64").byteLength
256
+ : Buffer.byteLength(file.content, "utf8");
257
+ if (fileBytes > maxBytes - totalBytes) {
258
+ throw new Error(`Total installed file size exceeds ${maxBytes} bytes`);
259
+ }
260
+ totalBytes += fileBytes;
261
+ }
203
262
  }
263
+ return totalBytes;
264
+ }
265
+ const getRegistryUrl = (value) => {
266
+ const url = assertSecureRegistryUrl(value);
204
267
  if (url.username || url.password || url.search || url.hash) {
205
268
  throw new Error("Registry URL must not include credentials, a query, or a fragment");
206
269
  }
@@ -219,26 +282,25 @@ export function resolveRegistryUrl(config, options = {}) {
219
282
  const configured = (_a = registry !== null && registry !== void 0 ? registry : web) !== null && _a !== void 0 ? _a : defaultWebRegistry;
220
283
  return getRegistryUrl((_b = options.registry) !== null && _b !== void 0 ? _b : configured);
221
284
  }
222
- async function fetchComponent(name, registryUrl, spinner, manifest) {
285
+ async function fetchComponent(name, registryUrl, spinner, manifest, downloadBudget) {
286
+ var _a;
223
287
  try {
224
- const res = await fetch(`${registryUrl}/${name}.json`, {
225
- signal: AbortSignal.timeout(30000),
226
- });
288
+ const url = `${registryUrl}/${name}.json`;
289
+ const maxBytes = Math.min(maxRegistryPayloadBytes, maxTotalRegistryPayloadBytes - downloadBudget.bytes);
290
+ if (maxBytes <= 0) {
291
+ throw new Error("Total registry download size exceeds the allowed limit");
292
+ }
293
+ const res = await fetchRegistryResponse(url, AbortSignal.timeout(30000));
227
294
  if (!res.ok) {
295
+ await ((_a = res.body) === null || _a === void 0 ? void 0 : _a.cancel());
228
296
  throw new Error(`HTTP ${res.status}`);
229
297
  }
230
- const contentLength = Number(res.headers.get("content-length"));
231
- if (contentLength > maxRegistryPayloadBytes) {
232
- throw new Error("Registry response is too large");
233
- }
234
- const raw = await res.text();
235
- if (Buffer.byteLength(raw, "utf8") > maxRegistryPayloadBytes) {
236
- throw new Error("Registry response is too large");
237
- }
298
+ const raw = await readLimitedResponse(res, maxBytes, url);
299
+ downloadBudget.bytes += raw.byteLength;
238
300
  if (manifest) {
239
301
  verifySignedRegistryFile(`${name}.json`, raw, manifest);
240
302
  }
241
- const payload = validateRegistryPayload(JSON.parse(raw), name);
303
+ const payload = validateRegistryPayload(JSON.parse(raw.toString("utf8")), name);
242
304
  spinner.text = `Fetching ${name}...`;
243
305
  return payload;
244
306
  }
@@ -278,6 +340,10 @@ export async function add(componentNamesInput, options = {}) {
278
340
  logger.error(`${chalk.red("Error:")} At least one component name is required.`);
279
341
  process.exit(1);
280
342
  }
343
+ if (componentNames.length > maxRegistryComponents) {
344
+ logger.error(`${chalk.red("Error:")} At most ${maxRegistryComponents} components can be installed at once.`);
345
+ process.exit(1);
346
+ }
281
347
  let cwd;
282
348
  const preflight = ora("Preflight checks").start();
283
349
  try {
@@ -296,6 +362,7 @@ export async function add(componentNamesInput, options = {}) {
296
362
  }
297
363
  let config;
298
364
  let registryUrl;
365
+ let registryTrust;
299
366
  try {
300
367
  for (const name of componentNames) {
301
368
  assertComponentName(name);
@@ -303,29 +370,58 @@ export async function add(componentNamesInput, options = {}) {
303
370
  const configRaw = await readFile(configPath, "utf-8");
304
371
  config = JSON.parse(configRaw.replace(/^\uFEFF/u, ""));
305
372
  registryUrl = resolveRegistryUrl(config, options);
373
+ registryTrust = resolveRegistryTrustPolicy(config.registryTrust);
374
+ if (registryTrust && isOfficialRegistryUrl(registryUrl)) {
375
+ throw new Error("registryTrust is only supported for custom registries");
376
+ }
306
377
  }
307
378
  catch (error) {
308
379
  logger.error(error instanceof Error ? error.message : "Invalid configuration.");
309
380
  process.exit(1);
310
381
  }
382
+ const registryHostname = new URL(registryUrl).host;
383
+ const isOfficialRegistry = isOfficialRegistryUrl(registryUrl);
384
+ if (!(isOfficialRegistry ||
385
+ registryTrust ||
386
+ options.allowUntrustedRegistry ||
387
+ options.dryRun)) {
388
+ logger.error(`Registry ${registryHostname} has no configured signature trust. Add registryTrust to components.json or pass --allow-untrusted-registry to accept unsigned source.`);
389
+ process.exit(1);
390
+ }
311
391
  const registrySpinner = ora("Checking registry").start();
312
392
  let signedManifest;
313
- if (registryUrl === defaultWebRegistry) {
393
+ if (isOfficialRegistry) {
314
394
  try {
315
395
  signedManifest = await fetchSignedRegistryManifest();
396
+ logger.info(`Registry ${registryHostname}: Frakment Sigstore signature verified.`);
316
397
  }
317
398
  catch (error) {
318
399
  registrySpinner.fail(`Registry signature verification failed: ${error instanceof Error ? error.message : "unknown error"}`);
319
400
  process.exit(1);
320
401
  }
321
402
  }
403
+ else if (registryTrust) {
404
+ try {
405
+ signedManifest = await fetchSignedRegistryManifest(customRegistryManifestSource(registryUrl, registryTrust));
406
+ logger.info(`Registry ${registryHostname}: Sigstore signature verified for ${registryTrust.certificateIdentityURI}.`);
407
+ }
408
+ catch (error) {
409
+ registrySpinner.fail(`Custom registry signature verification failed: ${error instanceof Error ? error.message : "unknown error"}`);
410
+ process.exit(1);
411
+ }
412
+ }
322
413
  else {
323
- logger.warn("Custom registry is not covered by Frakment's Sigstore signature.");
414
+ logger.warn(`Registry ${registryHostname}: signature not verified; downloaded source is untrusted.`);
415
+ if (options.allowUntrustedRegistry) {
416
+ logger.warn("The untrusted registry was explicitly allowed; its files may be written to this project.");
417
+ }
324
418
  }
325
419
  const roots = new Set(componentNames);
326
420
  const queue = [...roots];
421
+ const queued = new Set(queue);
327
422
  const fetched = new Map();
328
423
  const npmDeps = new Map();
424
+ const downloadBudget = { bytes: 0 };
329
425
  while (queue.length) {
330
426
  const name = queue.shift();
331
427
  if (!name) {
@@ -334,7 +430,11 @@ export async function add(componentNamesInput, options = {}) {
334
430
  if (fetched.has(name)) {
335
431
  continue;
336
432
  }
337
- const payload = await fetchComponent(name, registryUrl, registrySpinner, signedManifest);
433
+ if (fetched.size >= maxRegistryComponents) {
434
+ registrySpinner.fail(`Registry dependency graph exceeds ${maxRegistryComponents} components`);
435
+ process.exit(1);
436
+ }
437
+ const payload = await fetchComponent(name, registryUrl, registrySpinner, signedManifest, downloadBudget);
338
438
  fetched.set(name, payload);
339
439
  for (const d of (_a = payload.dependencies) !== null && _a !== void 0 ? _a : []) {
340
440
  const packageName = getDependencyName(d);
@@ -345,11 +445,19 @@ export async function add(componentNamesInput, options = {}) {
345
445
  }
346
446
  }
347
447
  for (const d of (_b = payload.registryDependencies) !== null && _b !== void 0 ? _b : []) {
348
- if (!fetched.has(d)) {
448
+ if (!queued.has(d)) {
349
449
  queue.push(d);
450
+ queued.add(d);
350
451
  }
351
452
  }
352
453
  }
454
+ try {
455
+ getTotalInstalledBytes(fetched.values());
456
+ }
457
+ catch (error) {
458
+ registrySpinner.fail(error instanceof Error ? error.message : "Invalid total install size");
459
+ process.exit(1);
460
+ }
353
461
  registrySpinner.succeed("Checking registry.");
354
462
  const aliases = normalizeAliases(config.aliases);
355
463
  const isSrcLayout = (_e = (_d = (_c = config.tailwind) === null || _c === void 0 ? void 0 : _c.css) === null || _d === void 0 ? void 0 : _d.startsWith("src/")) !== null && _e !== void 0 ? _e : false;
@@ -5,7 +5,9 @@ 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 { fetchSignedRegistryManifest, isOfficialRegistryUrl, resolveRegistryUrl, verifySignedRegistryFile, } from "./add.js";
8
+ import { fetchRegistryResponse, readLimitedResponse, } from "../utils/registry-http.js";
9
+ import { customRegistryManifestSource, fetchSignedRegistryManifest, isOfficialRegistryUrl, resolveRegistryTrustPolicy, resolveRegistryUrl, verifySignedRegistryFile, } from "./add.js";
10
+ const maxRegistryIndexBytes = 10 * 1024 * 1024;
9
11
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10
12
  export const isRegistryIndex = (value) => isRecord(value) &&
11
13
  Array.isArray(value.components) &&
@@ -15,7 +17,7 @@ export const isRegistryIndex = (value) => isRecord(value) &&
15
17
  (component.description === undefined ||
16
18
  typeof component.description === "string"));
17
19
  export async function list(options) {
18
- var _a;
20
+ var _a, _b;
19
21
  let cwd;
20
22
  const preflight = ora("Preflight checks").start();
21
23
  try {
@@ -33,10 +35,15 @@ export async function list(options) {
33
35
  process.exit(1);
34
36
  }
35
37
  let registryUrl;
38
+ let registryTrust;
36
39
  try {
37
40
  const configRaw = await readFile(configPath, "utf-8");
38
41
  const config = JSON.parse(configRaw.replace(/^\uFEFF/u, ""));
39
42
  registryUrl = resolveRegistryUrl(config, options);
43
+ registryTrust = resolveRegistryTrustPolicy(config.registryTrust);
44
+ if (registryTrust && isOfficialRegistryUrl(registryUrl)) {
45
+ throw new Error("registryTrust is only supported for custom registries");
46
+ }
40
47
  }
41
48
  catch (error) {
42
49
  logger.error(error instanceof Error ? error.message : "Invalid components.json.");
@@ -45,26 +52,30 @@ export async function list(options) {
45
52
  const s = ora("Fetching components").start();
46
53
  let index;
47
54
  try {
48
- const manifest = isOfficialRegistryUrl(registryUrl)
55
+ const registryHostname = new URL(registryUrl).host;
56
+ const isOfficialRegistry = isOfficialRegistryUrl(registryUrl);
57
+ const manifest = isOfficialRegistry
49
58
  ? await fetchSignedRegistryManifest()
50
- : undefined;
51
- if (!manifest) {
52
- logger.warn("Custom registry is not covered by Frakment's Sigstore signature.");
59
+ : registryTrust
60
+ ? await fetchSignedRegistryManifest(customRegistryManifestSource(registryUrl, registryTrust))
61
+ : undefined;
62
+ if (manifest) {
63
+ logger.info(`Registry ${registryHostname}: ${isOfficialRegistry ? "Frakment" : registryTrust === null || registryTrust === void 0 ? void 0 : registryTrust.certificateIdentityURI} Sigstore signature verified.`);
53
64
  }
54
- const res = await fetch(`${registryUrl}/index.json`, {
55
- signal: AbortSignal.timeout(30000),
56
- });
65
+ else {
66
+ logger.warn(`Registry ${registryHostname}: signature not verified.`);
67
+ }
68
+ const indexUrl = `${registryUrl}/index.json`;
69
+ const res = await fetchRegistryResponse(indexUrl, AbortSignal.timeout(30000));
57
70
  if (!res.ok) {
71
+ await ((_a = res.body) === null || _a === void 0 ? void 0 : _a.cancel());
58
72
  throw new Error(`HTTP ${res.status}`);
59
73
  }
60
- const raw = await res.text();
61
- if (Buffer.byteLength(raw, "utf8") > 10 * 1024 * 1024) {
62
- throw new Error("Registry index response is too large");
63
- }
74
+ const raw = await readLimitedResponse(res, maxRegistryIndexBytes, indexUrl);
64
75
  if (manifest) {
65
76
  verifySignedRegistryFile("index.json", raw, manifest);
66
77
  }
67
- const response = JSON.parse(raw);
78
+ const response = JSON.parse(raw.toString("utf8"));
68
79
  if (!isRegistryIndex(response)) {
69
80
  throw new Error("Registry index has an invalid shape");
70
81
  }
@@ -83,7 +94,7 @@ export async function list(options) {
83
94
  const nameWidth = Math.max(...index.components.map((c) => c.name.length));
84
95
  logger.break();
85
96
  for (const c of index.components) {
86
- logger.log(` ${chalk.cyan(c.name.padEnd(nameWidth))} ${chalk.dim((_a = c.description) !== null && _a !== void 0 ? _a : "")}`);
97
+ logger.log(` ${chalk.cyan(c.name.padEnd(nameWidth))} ${chalk.dim((_b = c.description) !== null && _b !== void 0 ? _b : "")}`);
87
98
  }
88
99
  logger.break();
89
100
  logger.log(`Add one with ${chalk.cyan("frakment add <name>")}`);
@@ -0,0 +1,92 @@
1
+ const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
2
+ const maxRegistryRedirects = 5;
3
+ export function isLoopbackHostname(hostname) {
4
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/gu, "");
5
+ return (normalized === "localhost" ||
6
+ normalized === "127.0.0.1" ||
7
+ normalized === "::1");
8
+ }
9
+ export function assertSecureRegistryUrl(value, requireHttps = false) {
10
+ const url = new URL(value);
11
+ if (url.username || url.password || url.hash) {
12
+ throw new Error("Registry URLs must not include credentials or fragments");
13
+ }
14
+ if (url.protocol === "https:") {
15
+ return url;
16
+ }
17
+ if (!requireHttps &&
18
+ url.protocol === "http:" &&
19
+ isLoopbackHostname(url.hostname)) {
20
+ return url;
21
+ }
22
+ if (requireHttps) {
23
+ throw new Error("Registry redirects must not downgrade from HTTPS");
24
+ }
25
+ throw new Error("Registry URLs must use HTTPS unless they target localhost, 127.0.0.1, or ::1");
26
+ }
27
+ export async function fetchRegistryResponse(value, signal) {
28
+ var _a, _b, _c, _d;
29
+ const initialUrl = assertSecureRegistryUrl(value);
30
+ const requireHttps = initialUrl.protocol === "https:";
31
+ let url = initialUrl;
32
+ for (let redirectCount = 0;; redirectCount += 1) {
33
+ const response = await fetch(url, { redirect: "manual", signal });
34
+ const responseUrl = response.url ? new URL(response.url) : url;
35
+ assertSecureRegistryUrl(responseUrl.href, requireHttps);
36
+ if (responseUrl.href !== url.href) {
37
+ await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
38
+ throw new Error("Registry response URL differs from its validated URL");
39
+ }
40
+ if (!redirectStatusCodes.has(response.status)) {
41
+ return response;
42
+ }
43
+ const location = response.headers.get("location");
44
+ if (!location) {
45
+ return response;
46
+ }
47
+ if (redirectCount >= maxRegistryRedirects) {
48
+ await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel());
49
+ throw new Error("Registry exceeded the redirect limit");
50
+ }
51
+ const nextUrl = new URL(location, url);
52
+ if (nextUrl.username || nextUrl.password || nextUrl.hash) {
53
+ await ((_c = response.body) === null || _c === void 0 ? void 0 : _c.cancel());
54
+ throw new Error("Registry redirects must not include credentials or fragments");
55
+ }
56
+ assertSecureRegistryUrl(nextUrl.href, requireHttps);
57
+ await ((_d = response.body) === null || _d === void 0 ? void 0 : _d.cancel());
58
+ url = nextUrl;
59
+ }
60
+ }
61
+ export async function readLimitedResponse(response, maxBytes, source) {
62
+ var _a;
63
+ const contentLength = Number(response.headers.get("content-length"));
64
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
65
+ await ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel());
66
+ throw new Error(`Response from ${source} is too large`);
67
+ }
68
+ if (!response.body) {
69
+ return Buffer.alloc(0);
70
+ }
71
+ const reader = response.body.getReader();
72
+ const chunks = [];
73
+ let totalBytes = 0;
74
+ try {
75
+ while (true) {
76
+ const { done, value } = await reader.read();
77
+ if (done) {
78
+ break;
79
+ }
80
+ totalBytes += value.byteLength;
81
+ if (totalBytes > maxBytes) {
82
+ await reader.cancel();
83
+ throw new Error(`Response from ${source} is too large`);
84
+ }
85
+ chunks.push(Buffer.from(value));
86
+ }
87
+ }
88
+ finally {
89
+ reader.releaseLock();
90
+ }
91
+ return Buffer.concat(chunks, totalBytes);
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "frakment",
3
- "version": "4.0.0",
3
+ "version": "5.0.1",
4
4
  "description": "MIT-licensed CLI and design system for the Frakment component registry",
5
5
  "keywords": [
6
6
  "components",
@@ -34,10 +34,10 @@
34
34
  },
35
35
  "devDependencies": {
36
36
  "@types/prompts": "^2.4.9",
37
- "@types/react": "19.3.0",
37
+ "@types/react": "19.3.3",
38
38
  "clsx": "^2.1.1",
39
39
  "react": "19.3.1",
40
- "tailwind-merge": "^3.7.1"
40
+ "tailwind-merge": "^3.7.3"
41
41
  },
42
42
  "engines": {
43
43
  "node": ">=22.22.2"