@joripspace/cli 0.4.2 → 0.5.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.
@@ -1,257 +1,257 @@
1
- const fs = require('node:fs');
2
- const crypto = require('node:crypto');
3
- const os = require('node:os');
4
- const path = require('node:path');
5
-
6
- function safeProjectRelativePath(value, errorPrefix = 'unsafe project file path') {
7
- const normalized = String(value || '')
8
- .replace(/\\/g, '/')
9
- .replace(/^\.\//, '');
10
- if (
11
- !normalized ||
12
- normalized.startsWith('/') ||
13
- /^[A-Za-z]:\//.test(normalized) ||
14
- normalized
15
- .split('/')
16
- .some(
17
- (part) =>
18
- !part ||
19
- part === '.' ||
20
- part === '..' ||
21
- /[ .]$/.test(part) ||
22
- /[<>:"|?*\x00-\x1f]/.test(part) ||
23
- /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(part)
24
- )
25
- ) {
26
- throw new Error(`${errorPrefix}: ${value}`);
27
- }
28
- return normalized;
29
- }
30
-
31
- function resolveProjectFileTarget(root, value, errorPrefix = 'unsafe project file path') {
32
- const relative = safeProjectRelativePath(value, errorPrefix);
33
- const rootPath = realProjectRoot(root);
34
- const target = path.resolve(rootPath, ...relative.split('/'));
35
- assertContained(rootPath, target, relative);
36
- const blockers = [];
37
- let current = rootPath;
38
- const parts = relative.split('/');
39
- for (let index = 0; index < parts.length; index += 1) {
40
- current = path.join(current, parts[index]);
41
- const stat = lstatOrNull(current);
42
- if (!stat) continue;
43
- if (stat.isSymbolicLink()) {
44
- throw new Error(
45
- `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
46
- );
47
- }
48
- const isTarget = index === parts.length - 1;
49
- if ((!isTarget && !stat.isDirectory()) || (isTarget && !stat.isFile())) {
50
- blockers.push(parts.slice(0, index + 1).join('/'));
51
- break;
52
- }
53
- assertContained(rootPath, fs.realpathSync.native(current), relative);
54
- }
55
- return { blockers, relative, root: rootPath, target };
56
- }
57
-
58
- function backupAndRemoveProjectPaths(root, relatives, backupRoot) {
59
- const selected = minimalPaths(relatives);
60
- const rootPath = realProjectRoot(root);
61
- if (!path.isAbsolute(backupRoot)) {
62
- throw new Error('project backups must use an absolute directory outside the workspace');
63
- }
64
- const backupLocation = fs.realpathSync.native(path.resolve(backupRoot));
65
- const fromWorkspace = path.relative(rootPath, backupLocation);
66
- if (isContainedRelative(fromWorkspace)) {
67
- throw new Error('project backups must use an absolute directory outside the workspace');
68
- }
69
- const backupStat = fs.lstatSync(backupLocation);
70
- if (!backupStat.isDirectory() || backupStat.isSymbolicLink()) {
71
- throw new Error('project backup target is not a safe directory');
72
- }
73
- for (const relative of selected) {
74
- const location = resolveExistingProjectPath(root, relative);
75
- if (!location) continue;
76
- const backup = path.join(backupLocation, ...relative.split('/'));
77
- fs.mkdirSync(path.dirname(backup), { recursive: true });
78
- if (location.stat.isDirectory()) {
79
- fs.cpSync(location.target, backup, { recursive: true, errorOnExist: true });
80
- } else {
81
- fs.copyFileSync(location.target, backup, fs.constants.COPYFILE_EXCL);
82
- }
83
- fs.rmSync(location.target, { recursive: location.stat.isDirectory(), force: true });
84
- }
85
- return selected;
86
- }
87
-
88
- function createExternalBackupRoot(workspaceDir, category = 'restore', dataRootOverride = '') {
89
- const workspace = realProjectRoot(workspaceDir);
90
- const configuredRoot = String(dataRootOverride || process.env.JORIPSPACE_DATA_DIR || '').trim();
91
- const dataRoot = configuredRoot
92
- ? path.resolve(configuredRoot)
93
- : process.platform === 'win32'
94
- ? path.join(process.env.LOCALAPPDATA || os.homedir(), 'JoripSpace')
95
- : process.platform === 'darwin'
96
- ? path.join(os.homedir(), 'Library', 'Application Support', 'JoripSpace')
97
- : path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'joripspace');
98
- const workspaceKey = crypto
99
- .createHash('sha256')
100
- .update(process.platform === 'win32' ? workspace.toLowerCase() : workspace)
101
- .digest('hex')
102
- .slice(0, 20);
103
- const safeCategory = String(category || 'restore').toLowerCase();
104
- if (!/^[a-z][a-z0-9-]{0,31}$/.test(safeCategory)) {
105
- throw new Error('invalid backup category');
106
- }
107
- const resolvedDataRoot = prospectiveRealPath(dataRoot);
108
- const dataFromWorkspace = path.relative(workspace, resolvedDataRoot);
109
- if (isContainedRelative(dataFromWorkspace)) {
110
- throw new Error('JoripSpace user data directory must be outside the project workspace');
111
- }
112
- const parent = path.join(resolvedDataRoot, 'backups', workspaceKey, safeCategory);
113
- fs.mkdirSync(parent, { recursive: true });
114
- const realParent = fs.realpathSync.native(parent);
115
- const fromWorkspace = path.relative(workspace, realParent);
116
- if (isContainedRelative(fromWorkspace)) {
117
- throw new Error('JoripSpace user data directory must be outside the project workspace');
118
- }
119
- const backupRoot = path.join(
120
- realParent,
121
- `${new Date().toISOString().replace(/[:.]/g, '-')}-${crypto.randomUUID()}`
122
- );
123
- fs.mkdirSync(backupRoot, { recursive: false, mode: 0o700 });
124
- return fs.realpathSync.native(backupRoot);
125
- }
126
-
127
- function prospectiveRealPath(target) {
128
- let current = path.resolve(target);
129
- const missing = [];
130
- while (!fs.existsSync(current)) {
131
- const parent = path.dirname(current);
132
- if (parent === current) break;
133
- missing.unshift(path.basename(current));
134
- current = parent;
135
- }
136
- const existing = fs.realpathSync.native(current);
137
- return path.join(existing, ...missing);
138
- }
139
-
140
- function resolveProjectDirectoryTarget(root, value) {
141
- const relative = safeProjectRelativePath(value);
142
- const rootPath = realProjectRoot(root);
143
- const target = path.resolve(rootPath, ...relative.split('/'));
144
- assertContained(rootPath, target, relative);
145
- let current = rootPath;
146
- for (const [index, part] of relative.split('/').entries()) {
147
- current = path.join(current, part);
148
- const stat = lstatOrNull(current);
149
- if (!stat) continue;
150
- if (stat.isSymbolicLink()) {
151
- throw new Error(
152
- `project path contains a symbolic link or junction: ${relative
153
- .split('/')
154
- .slice(0, index + 1)
155
- .join('/')}`
156
- );
157
- }
158
- if (!stat.isDirectory()) throw new Error(`project directory path is blocked by a file: ${relative}`);
159
- assertContained(rootPath, fs.realpathSync.native(current), relative);
160
- }
161
- return { relative, root: rootPath, target };
162
- }
163
-
164
- function resolveExistingProjectPath(root, value) {
165
- const relative = safeProjectRelativePath(value);
166
- const rootPath = realProjectRoot(root);
167
- let current = rootPath;
168
- const parts = relative.split('/');
169
- for (const [index, part] of parts.entries()) {
170
- current = path.join(current, part);
171
- const stat = lstatOrNull(current);
172
- if (!stat) return null;
173
- if (stat.isSymbolicLink()) {
174
- throw new Error(
175
- `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
176
- );
177
- }
178
- assertContained(rootPath, fs.realpathSync.native(current), relative);
179
- if (index < parts.length - 1 && !stat.isDirectory()) return null;
180
- if (index === parts.length - 1) return { relative, root: rootPath, stat, target: current };
181
- }
182
- return null;
183
- }
184
-
185
- function assertNonOverlappingFilePlan(relatives) {
186
- const paths = new Map();
187
- for (const relative of relatives) {
188
- const key = relative.toLowerCase();
189
- if (paths.has(key)) {
190
- throw new Error(`project file plan contains a duplicate cross-platform path: ${relative}`);
191
- }
192
- paths.set(key, relative);
193
- }
194
- for (const relative of paths.values()) {
195
- const parts = relative.split('/');
196
- for (let length = 1; length < parts.length; length += 1) {
197
- const parent = parts.slice(0, length).join('/');
198
- const plannedParent = paths.get(parent.toLowerCase());
199
- if (plannedParent) {
200
- throw new Error(`project file plan contains a file/directory collision: ${plannedParent}`);
201
- }
202
- }
203
- }
204
- }
205
-
206
- function minimalPaths(relatives) {
207
- const unique = new Map(relatives.map((relative) => [relative.toLowerCase(), relative]));
208
- const sorted = [...unique.values()].sort(
209
- (left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right)
210
- );
211
- return sorted.filter(
212
- (candidate) =>
213
- !sorted.some(
214
- (parent) => parent !== candidate && candidate.toLowerCase().startsWith(`${parent.toLowerCase()}/`)
215
- )
216
- );
217
- }
218
-
219
- function realProjectRoot(root) {
220
- const resolved = path.resolve(root);
221
- if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
222
- throw new Error(`project workspace does not exist: ${resolved}`);
223
- }
224
- return fs.realpathSync.native(resolved);
225
- }
226
-
227
- function assertContained(root, target, relative) {
228
- const fromRoot = path.relative(root, target);
229
- if (fromRoot === '..' || fromRoot.startsWith(`..${path.sep}`) || path.isAbsolute(fromRoot)) {
230
- throw new Error(`project path escapes the workspace: ${relative}`);
231
- }
232
- }
233
-
234
- function isContainedRelative(relative) {
235
- return (
236
- relative === '' ||
237
- (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
238
- );
239
- }
240
-
241
- function lstatOrNull(target) {
242
- try {
243
- return fs.lstatSync(target);
244
- } catch (error) {
245
- if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
246
- throw error;
247
- }
248
- }
249
-
250
- module.exports = {
251
- assertNonOverlappingFilePlan,
252
- backupAndRemoveProjectPaths,
253
- createExternalBackupRoot,
254
- resolveProjectDirectoryTarget,
255
- resolveProjectFileTarget,
256
- safeProjectRelativePath,
257
- };
1
+ const fs = require('node:fs');
2
+ const crypto = require('node:crypto');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+
6
+ function safeProjectRelativePath(value, errorPrefix = 'unsafe project file path') {
7
+ const normalized = String(value || '')
8
+ .replace(/\\/g, '/')
9
+ .replace(/^\.\//, '');
10
+ if (
11
+ !normalized ||
12
+ normalized.startsWith('/') ||
13
+ /^[A-Za-z]:\//.test(normalized) ||
14
+ normalized
15
+ .split('/')
16
+ .some(
17
+ (part) =>
18
+ !part ||
19
+ part === '.' ||
20
+ part === '..' ||
21
+ /[ .]$/.test(part) ||
22
+ /[<>:"|?*\x00-\x1f]/.test(part) ||
23
+ /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i.test(part)
24
+ )
25
+ ) {
26
+ throw new Error(`${errorPrefix}: ${value}`);
27
+ }
28
+ return normalized;
29
+ }
30
+
31
+ function resolveProjectFileTarget(root, value, errorPrefix = 'unsafe project file path') {
32
+ const relative = safeProjectRelativePath(value, errorPrefix);
33
+ const rootPath = realProjectRoot(root);
34
+ const target = path.resolve(rootPath, ...relative.split('/'));
35
+ assertContained(rootPath, target, relative);
36
+ const blockers = [];
37
+ let current = rootPath;
38
+ const parts = relative.split('/');
39
+ for (let index = 0; index < parts.length; index += 1) {
40
+ current = path.join(current, parts[index]);
41
+ const stat = lstatOrNull(current);
42
+ if (!stat) continue;
43
+ if (stat.isSymbolicLink()) {
44
+ throw new Error(
45
+ `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
46
+ );
47
+ }
48
+ const isTarget = index === parts.length - 1;
49
+ if ((!isTarget && !stat.isDirectory()) || (isTarget && !stat.isFile())) {
50
+ blockers.push(parts.slice(0, index + 1).join('/'));
51
+ break;
52
+ }
53
+ assertContained(rootPath, fs.realpathSync.native(current), relative);
54
+ }
55
+ return { blockers, relative, root: rootPath, target };
56
+ }
57
+
58
+ function backupAndRemoveProjectPaths(root, relatives, backupRoot) {
59
+ const selected = minimalPaths(relatives);
60
+ const rootPath = realProjectRoot(root);
61
+ if (!path.isAbsolute(backupRoot)) {
62
+ throw new Error('project backups must use an absolute directory outside the workspace');
63
+ }
64
+ const backupLocation = fs.realpathSync.native(path.resolve(backupRoot));
65
+ const fromWorkspace = path.relative(rootPath, backupLocation);
66
+ if (isContainedRelative(fromWorkspace)) {
67
+ throw new Error('project backups must use an absolute directory outside the workspace');
68
+ }
69
+ const backupStat = fs.lstatSync(backupLocation);
70
+ if (!backupStat.isDirectory() || backupStat.isSymbolicLink()) {
71
+ throw new Error('project backup target is not a safe directory');
72
+ }
73
+ for (const relative of selected) {
74
+ const location = resolveExistingProjectPath(root, relative);
75
+ if (!location) continue;
76
+ const backup = path.join(backupLocation, ...relative.split('/'));
77
+ fs.mkdirSync(path.dirname(backup), { recursive: true });
78
+ if (location.stat.isDirectory()) {
79
+ fs.cpSync(location.target, backup, { recursive: true, errorOnExist: true });
80
+ } else {
81
+ fs.copyFileSync(location.target, backup, fs.constants.COPYFILE_EXCL);
82
+ }
83
+ fs.rmSync(location.target, { recursive: location.stat.isDirectory(), force: true });
84
+ }
85
+ return selected;
86
+ }
87
+
88
+ function createExternalBackupRoot(workspaceDir, category = 'restore', dataRootOverride = '') {
89
+ const workspace = realProjectRoot(workspaceDir);
90
+ const configuredRoot = String(dataRootOverride || process.env.JORIPSPACE_DATA_DIR || '').trim();
91
+ const dataRoot = configuredRoot
92
+ ? path.resolve(configuredRoot)
93
+ : process.platform === 'win32'
94
+ ? path.join(process.env.LOCALAPPDATA || os.homedir(), 'JoripSpace')
95
+ : process.platform === 'darwin'
96
+ ? path.join(os.homedir(), 'Library', 'Application Support', 'JoripSpace')
97
+ : path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'joripspace');
98
+ const workspaceKey = crypto
99
+ .createHash('sha256')
100
+ .update(process.platform === 'win32' ? workspace.toLowerCase() : workspace)
101
+ .digest('hex')
102
+ .slice(0, 20);
103
+ const safeCategory = String(category || 'restore').toLowerCase();
104
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(safeCategory)) {
105
+ throw new Error('invalid backup category');
106
+ }
107
+ const resolvedDataRoot = prospectiveRealPath(dataRoot);
108
+ const dataFromWorkspace = path.relative(workspace, resolvedDataRoot);
109
+ if (isContainedRelative(dataFromWorkspace)) {
110
+ throw new Error('JoripSpace user data directory must be outside the project workspace');
111
+ }
112
+ const parent = path.join(resolvedDataRoot, 'backups', workspaceKey, safeCategory);
113
+ fs.mkdirSync(parent, { recursive: true });
114
+ const realParent = fs.realpathSync.native(parent);
115
+ const fromWorkspace = path.relative(workspace, realParent);
116
+ if (isContainedRelative(fromWorkspace)) {
117
+ throw new Error('JoripSpace user data directory must be outside the project workspace');
118
+ }
119
+ const backupRoot = path.join(
120
+ realParent,
121
+ `${new Date().toISOString().replace(/[:.]/g, '-')}-${crypto.randomUUID()}`
122
+ );
123
+ fs.mkdirSync(backupRoot, { recursive: false, mode: 0o700 });
124
+ return fs.realpathSync.native(backupRoot);
125
+ }
126
+
127
+ function prospectiveRealPath(target) {
128
+ let current = path.resolve(target);
129
+ const missing = [];
130
+ while (!fs.existsSync(current)) {
131
+ const parent = path.dirname(current);
132
+ if (parent === current) break;
133
+ missing.unshift(path.basename(current));
134
+ current = parent;
135
+ }
136
+ const existing = fs.realpathSync.native(current);
137
+ return path.join(existing, ...missing);
138
+ }
139
+
140
+ function resolveProjectDirectoryTarget(root, value) {
141
+ const relative = safeProjectRelativePath(value);
142
+ const rootPath = realProjectRoot(root);
143
+ const target = path.resolve(rootPath, ...relative.split('/'));
144
+ assertContained(rootPath, target, relative);
145
+ let current = rootPath;
146
+ for (const [index, part] of relative.split('/').entries()) {
147
+ current = path.join(current, part);
148
+ const stat = lstatOrNull(current);
149
+ if (!stat) continue;
150
+ if (stat.isSymbolicLink()) {
151
+ throw new Error(
152
+ `project path contains a symbolic link or junction: ${relative
153
+ .split('/')
154
+ .slice(0, index + 1)
155
+ .join('/')}`
156
+ );
157
+ }
158
+ if (!stat.isDirectory()) throw new Error(`project directory path is blocked by a file: ${relative}`);
159
+ assertContained(rootPath, fs.realpathSync.native(current), relative);
160
+ }
161
+ return { relative, root: rootPath, target };
162
+ }
163
+
164
+ function resolveExistingProjectPath(root, value) {
165
+ const relative = safeProjectRelativePath(value);
166
+ const rootPath = realProjectRoot(root);
167
+ let current = rootPath;
168
+ const parts = relative.split('/');
169
+ for (const [index, part] of parts.entries()) {
170
+ current = path.join(current, part);
171
+ const stat = lstatOrNull(current);
172
+ if (!stat) return null;
173
+ if (stat.isSymbolicLink()) {
174
+ throw new Error(
175
+ `project path contains a symbolic link or junction: ${parts.slice(0, index + 1).join('/')}`
176
+ );
177
+ }
178
+ assertContained(rootPath, fs.realpathSync.native(current), relative);
179
+ if (index < parts.length - 1 && !stat.isDirectory()) return null;
180
+ if (index === parts.length - 1) return { relative, root: rootPath, stat, target: current };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function assertNonOverlappingFilePlan(relatives) {
186
+ const paths = new Map();
187
+ for (const relative of relatives) {
188
+ const key = relative.toLowerCase();
189
+ if (paths.has(key)) {
190
+ throw new Error(`project file plan contains a duplicate cross-platform path: ${relative}`);
191
+ }
192
+ paths.set(key, relative);
193
+ }
194
+ for (const relative of paths.values()) {
195
+ const parts = relative.split('/');
196
+ for (let length = 1; length < parts.length; length += 1) {
197
+ const parent = parts.slice(0, length).join('/');
198
+ const plannedParent = paths.get(parent.toLowerCase());
199
+ if (plannedParent) {
200
+ throw new Error(`project file plan contains a file/directory collision: ${plannedParent}`);
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ function minimalPaths(relatives) {
207
+ const unique = new Map(relatives.map((relative) => [relative.toLowerCase(), relative]));
208
+ const sorted = [...unique.values()].sort(
209
+ (left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right)
210
+ );
211
+ return sorted.filter(
212
+ (candidate) =>
213
+ !sorted.some(
214
+ (parent) => parent !== candidate && candidate.toLowerCase().startsWith(`${parent.toLowerCase()}/`)
215
+ )
216
+ );
217
+ }
218
+
219
+ function realProjectRoot(root) {
220
+ const resolved = path.resolve(root);
221
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
222
+ throw new Error(`project workspace does not exist: ${resolved}`);
223
+ }
224
+ return fs.realpathSync.native(resolved);
225
+ }
226
+
227
+ function assertContained(root, target, relative) {
228
+ const fromRoot = path.relative(root, target);
229
+ if (fromRoot === '..' || fromRoot.startsWith(`..${path.sep}`) || path.isAbsolute(fromRoot)) {
230
+ throw new Error(`project path escapes the workspace: ${relative}`);
231
+ }
232
+ }
233
+
234
+ function isContainedRelative(relative) {
235
+ return (
236
+ relative === '' ||
237
+ (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
238
+ );
239
+ }
240
+
241
+ function lstatOrNull(target) {
242
+ try {
243
+ return fs.lstatSync(target);
244
+ } catch (error) {
245
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
246
+ throw error;
247
+ }
248
+ }
249
+
250
+ module.exports = {
251
+ assertNonOverlappingFilePlan,
252
+ backupAndRemoveProjectPaths,
253
+ createExternalBackupRoot,
254
+ resolveProjectDirectoryTarget,
255
+ resolveProjectFileTarget,
256
+ safeProjectRelativePath,
257
+ };