Skip to content

Commit b18f5d6

Browse files
authored
fix(cli): template accepts an absolute path inside the project; outside, it names the command that works (#11793)
[fix] `astryx template <name> <path>` and `astryx template --cdn <path>` accept an absolute path inside the project root, also through a symlinked project folder. It is written exactly as its relative path. An absolute path outside the project is still refused with `ERR_PATH_TRAVERSAL`. For `astryx template <name> <path>`, the receipt says the path was written as its relative path (`data.givenPath` in `--json`), and the refusal names a command that writes inside the project (`astryx template <name> src/pages/<name>`, or `src/components/<name>` for a block) and the command that prints the source without writing anything. For `--cdn`, the receipt is unchanged, and the refusal names `astryx template --cdn cdn.template.html`.
1 parent bf6316e commit b18f5d6

14 files changed

Lines changed: 641 additions & 64 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@astryxdesign/cli': patch
3+
---
4+
5+
[fix] `astryx template <name> <path>` and `astryx template --cdn <path>` accept an absolute path inside the project root, also through a symlinked project folder. It is written exactly as its relative path. An absolute path outside the project is still refused with `ERR_PATH_TRAVERSAL`. For `astryx template <name> <path>`, the receipt says the path was written as its relative path (`data.givenPath` in `--json`), and the refusal names a command that writes inside the project (`astryx template <name> src/pages/<name>`, or `src/components/<name>` for a block) and the command that prints the source without writing anything. For `--cdn`, the receipt is unchanged, and the refusal names `astryx template --cdn cdn.template.html`.
6+
7+
@josephfarina

‎packages/cli/README.md‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

‎packages/cli/api/template/cdn/cdn.mjs‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,21 @@
2020
import * as fs from 'node:fs';
2121
import * as path from 'node:path';
2222
import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';
23-
import {assertWithin, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
23+
import {
24+
assertWithin,
25+
PathSafetyError,
26+
} from '../../../foundation/fs/path-safety.mjs';
2427
import {stripCopyrightHeader} from '../../../foundation/text/copyright-header.mjs';
2528
import {getXdsVersion} from '../../../foundation/agent-docs/agent-docs.mjs';
2629
import {AstryxError} from '../../error.mjs';
2730
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
2831

2932
/** The annotated CDN starter that ships with the CLI. */
30-
export const CDN_TEMPLATE_SRC = path.join(CLI_ROOT, 'assets', 'cdn.template.html');
33+
export const CDN_TEMPLATE_SRC = path.join(
34+
CLI_ROOT,
35+
'assets',
36+
'cdn.template.html',
37+
);
3138

3239
/** Where it lands when the caller does not say. */
3340
export const CDN_TEMPLATE_DEFAULT_PATH = 'cdn.template.html';
@@ -51,14 +58,34 @@ export function templateCdn(options = {}) {
5158
cwd = process.cwd(),
5259
} = options;
5360

61+
const inside = [
62+
{
63+
name: `astryx template --cdn ${CDN_TEMPLATE_DEFAULT_PATH}`,
64+
reason: 'write the page inside the project',
65+
},
66+
];
67+
// An absolute path inside the project is the same write as its relative
68+
// form.
5469
let resolved;
5570
try {
56-
resolved = assertWithin(targetPath, cwd, {label: 'cdn template path'});
71+
resolved = assertWithin(targetPath, cwd, {
72+
allowAbsolute: true,
73+
label: 'cdn template path',
74+
});
5775
} catch (err) {
58-
if (err instanceof PathSafetyError) {
59-
throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
60-
}
61-
throw err;
76+
if (!(err instanceof PathSafetyError)) throw err;
77+
const outside =
78+
path.isAbsolute(targetPath) &&
79+
err.code === ERROR_CODES.ERR_PATH_TRAVERSAL &&
80+
!err.viaSymlink;
81+
throw new AstryxError(
82+
outside
83+
? `Invalid cdn template path "${targetPath}": it is outside the project root (${path.resolve(cwd)}). ` +
84+
'The page is written only inside the project.'
85+
: err.message,
86+
inside,
87+
ERROR_CODES.ERR_PATH_TRAVERSAL,
88+
);
6289
}
6390

6491
const relative = path.relative(cwd, resolved) || targetPath;
@@ -74,7 +101,9 @@ export function templateCdn(options = {}) {
74101
};
75102
}
76103

77-
const source = stripCopyrightHeader(fs.readFileSync(CDN_TEMPLATE_SRC, 'utf-8'));
104+
const source = stripCopyrightHeader(
105+
fs.readFileSync(CDN_TEMPLATE_SRC, 'utf-8'),
106+
);
78107
const contents = source.replaceAll(CDN_VERSION_PLACEHOLDER, version);
79108
fs.mkdirSync(path.dirname(resolved), {recursive: true});
80109
fs.writeFileSync(resolved, contents);

‎packages/cli/api/template/copy/copy.mjs‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,21 @@ import {
3232
* Scaffold an already-resolved template to `targetPath` (relative to `cwd`) and
3333
* return the `template.copy` receipt.
3434
* @param {import('../../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate} match
35-
* @param {{targetPath: string, cwd: string, overwrite?: boolean, iconSets?: Parameters<typeof mapTemplateIcons>[1]}} ctx
36-
* `iconSets`: the project's icon sets; without them the icons are unchanged
35+
* @param {{targetPath: string, cwd: string, overwrite?: boolean, iconSets?: Parameters<typeof mapTemplateIcons>[1], command?: string}} ctx
36+
* `iconSets`: the project's icon sets; without them the icons are unchanged.
37+
* `command`: the command that selects this template, without a path; the
38+
* refusal of a path outside the project suggests it
3739
* @returns {import('../template.type.mjs').TemplateCopyResponse}
3840
*/
3941
export function templateCopy(
4042
match,
41-
{targetPath, cwd, overwrite = false, iconSets = NO_ICON_SETS},
43+
{
44+
targetPath,
45+
cwd,
46+
overwrite = false,
47+
iconSets = NO_ICON_SETS,
48+
command = `astryx template ${match.dirName} --type ${match.type}`,
49+
},
4250
) {
4351
if (!fs.existsSync(match.filePath)) {
4452
throw new AstryxError(
@@ -60,21 +68,46 @@ export function templateCopy(
6068

6169
// Path-safety: the guard sees the file that will be written, not only its
6270
// directory — a symlink at that name would otherwise carry the write
63-
// outside the project root. Runs BEFORE any mkdir/write.
71+
// outside the project root. Runs BEFORE any mkdir/write. An absolute path
72+
// inside the project is the same write as its relative form.
6473
let outputFilePath;
6574
try {
6675
outputFilePath = assertWithin(fileTarget, cwd, {
76+
allowAbsolute: true,
6777
label: 'template target path',
6878
});
6979
} catch (err) {
70-
if (err instanceof PathSafetyError) {
80+
if (!(err instanceof PathSafetyError)) throw err;
81+
// Outside the project there is nothing to write, so the refusal names a
82+
// place inside the project and the print that writes nothing.
83+
if (
84+
path.isAbsolute(targetPath) &&
85+
err.code === ERROR_CODES.ERR_PATH_TRAVERSAL &&
86+
!err.viaSymlink
87+
) {
88+
const folder = path.posix.join(
89+
'src',
90+
match.type === 'block' ? 'components' : 'pages',
91+
match.dirName,
92+
);
7193
throw new AstryxError(
72-
err.message,
73-
undefined,
94+
`Invalid template target path "${targetPath}": it is outside the project root (${path.resolve(cwd)}). ` +
95+
'The template is written only inside the project. Give a path inside it, or print the source.',
96+
[
97+
{
98+
name: `${command} ${folder}`,
99+
reason: `write the ${match.type} inside the project`,
100+
},
101+
{name: command, reason: 'print the source and write nothing'},
102+
],
74103
ERROR_CODES.ERR_PATH_TRAVERSAL,
75104
);
76105
}
77-
throw err;
106+
throw new AstryxError(
107+
err.message,
108+
undefined,
109+
ERROR_CODES.ERR_PATH_TRAVERSAL,
110+
);
78111
}
79112
const outputDir = path.dirname(outputFilePath);
80113
const outputFileName = path.basename(outputFilePath);
@@ -138,6 +171,7 @@ export function templateCopy(
138171
notes,
139172
missingPackages: missing,
140173
installCommand,
174+
...(path.isAbsolute(targetPath) ? {givenPath: targetPath} : {}),
141175
...(icons ? {icons} : {}),
142176
},
143177
};

‎packages/cli/api/template/template.doc.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export const doc = {
8989
name: 'options.targetPath',
9090
type: 'string',
9191
description:
92-
'Destination (relative to cwd) to scaffold the template into. Its presence switches a named lookup into a copy. ' +
92+
'Destination inside cwd to scaffold the template into: a relative path, or an absolute path inside cwd, which is written as its relative path and reported as data.givenPath. A path outside cwd is refused with ERR_PATH_TRAVERSAL. Its presence switches a named lookup into a copy. ' +
9393
"A path that ends in .tsx, .ts, .jsx, .js, .mjs, .cjs, .css, .scss, .json, .md or .html is the file to write; any other path is a directory, which receives page.tsx for a page template or the block's own file name for a block.",
9494
},
9595
{
@@ -125,7 +125,7 @@ export const doc = {
125125
{
126126
type: 'template.copy',
127127
description:
128-
'A receipt after scaffolding the template into the project: the template id, output directory, written file name, file count, `demoMediaReplaced` — how many Astryx demo media references were replaced with placeholders, `demoContentReplaced` — how many Astryx docs-only demo content elements were replaced with a `<Text>` placeholder, `notes` — setup notes naming what the template needs that the project lacks (missing packages, missing StyleX compiler; empty when satisfied), `missingPackages` — external package names the template imports that are not in the project, and `installCommand` — a ready-to-run install command with the detected package manager and workspace version ranges (null when nothing is missing, or when several lockfiles leave the package manager undetermined; `missingPackages` still names the packages).',
128+
'A receipt after scaffolding the template into the project: the template id, output directory, written file name, file count, `givenPath` — the absolute path as given, present only when it was inside the project, `demoMediaReplaced` — how many Astryx demo media references were replaced with placeholders, `demoContentReplaced` — how many Astryx docs-only demo content elements were replaced with a `<Text>` placeholder, `notes` — setup notes naming what the template needs that the project lacks (missing packages, missing StyleX compiler; empty when satisfied), `missingPackages` — external package names the template imports that are not in the project, and `installCommand` — a ready-to-run install command with the detected package manager and workspace version ranges (null when nothing is missing, or when several lockfiles leave the package manager undetermined; `missingPackages` still names the packages).',
129129
},
130130
{
131131
type: 'template.cdn',
@@ -152,7 +152,7 @@ export const doc = {
152152
},
153153
{
154154
code: 'ERR_PATH_TRAVERSAL',
155-
when: 'the copy target path is absolute or escapes the project root',
155+
when: 'the copy target path is outside the project root',
156156
},
157157
{
158158
code: 'ERR_FILE_EXISTS',

‎packages/cli/api/template/template.mjs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,5 +224,12 @@ export async function template(name, options = {}) {
224224
return templateShow(match, {iconSets});
225225
}
226226

227-
return templateCopy(match, {targetPath, cwd, overwrite, iconSets});
227+
// The command as typed selects the same template again, an integration
228+
// replacement included.
229+
const command = [
230+
`astryx template ${name}`,
231+
type ? ` --type ${type}` : '',
232+
packageFilter ? ` --package ${packageFilter}` : '',
233+
].join('');
234+
return templateCopy(match, {targetPath, cwd, overwrite, iconSets, command});
228235
}

‎packages/cli/api/template/template.type.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
* @property {string[]} data.notes Setup notes: what the template needs that the project lacks (missing packages, missing StyleX compiler). Each note is one actionable line. Empty when the template needs nothing the project lacks.
8787
* @property {string[]} data.missingPackages External package names the template imports that are not in the project's dependencies. Empty when none are missing.
8888
* @property {string | null} data.installCommand A ready-to-run install command for the missing packages, using the project's package manager and the CLI workspace's version ranges. Null when no packages are missing, or when several lockfiles leave the package manager undetermined; missingPackages still names the packages.
89+
* @property {string} [data.givenPath] The absolute path as given, present only when it named a place inside the project root. The write is the same as for its relative path: `outputDir` for a folder, or `outputDir` and `fileName` for a file.
8990
* @property {TemplateIconsReport} [data.icons] Experimental, present only when the project sets `experimental.iconSet`: how the written file's icons follow the project's icon set, each icon `mapped` (source and target), a `placeholder`, or `kept`, the sets used with their licenses, and the icon-set state. It may change or be removed in a patch release.
9091
*/
9192

‎packages/cli/api/theme/build/build.mjs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -340,8 +340,8 @@ function realOrSelf(file) {
340340
/**
341341
* `target` spelled through real directories: the deepest ancestor that exists
342342
* is resolved through its symlinks, and the missing rest is appended as given.
343-
* The build confines its outputs by it, and the theme editor's compile guard
344-
* reads paths through it too, so both read a path the same way.
343+
* The build groups and locates its outputs by it, and the theme editor's
344+
* compile guard reads paths through it too, so both read a path the same way.
345345
* @param {string} target absolute path
346346
* @returns {string}
347347
*/
@@ -795,17 +795,17 @@ const FAMILY_REMEDY =
795795
/**
796796
* Refuse an output outside `root`: every write is confined, whether `out` names
797797
* the path or it defaults to the theme file's directory (architecture:cli-surface
798-
* INV10). Both sides are compared by real location, so an absolute path that
799-
* reaches the working directory through a symlink is inside it, and a symlink
800-
* inside it that leads elsewhere is not.
798+
* INV10). assertWithin reads the absolute path, so a path that reaches the
799+
* working directory through a symlink is inside it, and a symlink inside it
800+
* that leads elsewhere is not.
801801
* @param {string} dest absolute output path
802802
* @param {string} root the directory writes stay inside: the working directory
803803
* @param {string} remedy what to do instead; ends the error message
804804
* @param {string} [shown] the path as the caller wrote it, for the message
805805
*/
806806
function confineOutput(dest, root, remedy, shown = dest) {
807807
try {
808-
assertWithin(realLocation(dest), realOrSelf(path.resolve(root)), {
808+
assertWithin(dest, root, {
809809
allowAbsolute: true,
810810
label: 'output path',
811811
});

‎packages/cli/clients/cli/commands/template.doc.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export const doc = {
3636
param: 'options.targetPath',
3737
required: false,
3838
description:
39-
'Where to scaffold the template, relative to the project root. A path that ends in .tsx, .ts, .jsx, .js, .mjs, .cjs, .css, .scss, .json, .md or .html is the file to write; ' +
39+
'Where to scaffold the template, inside the project root: a relative path, or an absolute path inside the project, which is written as its relative path. A path outside the project is refused. A path that ends in .tsx, .ts, .jsx, .js, .mjs, .cjs, .css, .scss, .json, .md or .html is the file to write; ' +
4040
"any other path is a directory, which receives page.tsx for a page template or the block's own file name for a block. " +
4141
'Omit it to print the source.',
4242
},

‎packages/cli/clients/cli/commands/template.mjs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44
* @file template command — thin CLI wrapper around api/template.mjs
55
*/
66

7+
import path from 'node:path';
78
import {jsonOut} from '../../../foundation/response/json.mjs';
9+
import {isFilePathArg} from '../../../foundation/fs/path-safety.mjs';
810
import {
911
emit,
1012
section,
@@ -319,11 +321,20 @@ export function registerTemplate(program) {
319321
demoContentReplaced,
320322
notes,
321323
icons,
324+
givenPath,
322325
} = result.data;
323326
const file = `${outputDir}/${fileName}`;
327+
const givenRelative =
328+
givenPath !== undefined && isFilePathArg(givenPath)
329+
? path.join(outputDir, fileName)
330+
: outputDir;
324331
const iconText = iconLines(icons);
325332
emit(
326333
text(`Copied template to ${file}`),
334+
givenPath !== undefined &&
335+
text(
336+
`${givenPath} is inside the project, so it was written as its relative path, ${givenRelative}.`,
337+
),
327338
record({package: result.package}),
328339
demoMediaReplaced > 0 &&
329340
text(

0 commit comments

Comments
 (0)