@contember/create 2.2.0-alpha.2 → 2.2.0-alpha.20
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/CLAUDE.md +22 -0
- package/dist/development/run.cjs +7 -7
- package/dist/development/run.cjs.map +1 -1
- package/dist/development/run.js +8 -8
- package/dist/development/run.js.map +1 -1
- package/dist/development/src/commands/WorkspaceCreateCommand.cjs +36 -23
- package/dist/development/src/commands/WorkspaceCreateCommand.cjs.map +1 -1
- package/dist/development/src/commands/WorkspaceCreateCommand.js +37 -24
- package/dist/development/src/commands/WorkspaceCreateCommand.js.map +1 -1
- package/dist/development/src/lib/FileSystem.cjs +10 -4
- package/dist/development/src/lib/FileSystem.cjs.map +1 -1
- package/dist/development/src/lib/FileSystem.js +8 -2
- package/dist/development/src/lib/FileSystem.js.map +1 -1
- package/dist/development/src/lib/TemplateInstaller.cjs +71 -60
- package/dist/development/src/lib/TemplateInstaller.cjs.map +1 -1
- package/dist/development/src/lib/TemplateInstaller.js +71 -60
- package/dist/development/src/lib/TemplateInstaller.js.map +1 -1
- package/dist/development/src/lib/fsErrors.cjs +7 -0
- package/dist/development/src/lib/fsErrors.cjs.map +1 -0
- package/dist/development/src/lib/fsErrors.js +7 -0
- package/dist/development/src/lib/fsErrors.js.map +1 -0
- package/dist/development/src/lib/projectPath.cjs +66 -0
- package/dist/development/src/lib/projectPath.cjs.map +1 -0
- package/dist/development/src/lib/projectPath.js +66 -0
- package/dist/development/src/lib/projectPath.js.map +1 -0
- package/dist/development/src/lib/remoteTemplate.cjs +108 -0
- package/dist/development/src/lib/remoteTemplate.cjs.map +1 -0
- package/dist/development/src/lib/remoteTemplate.js +108 -0
- package/dist/development/src/lib/remoteTemplate.js.map +1 -0
- package/dist/development/src/lib/tar.cjs +243 -0
- package/dist/development/src/lib/tar.cjs.map +1 -0
- package/dist/development/src/lib/tar.js +243 -0
- package/dist/development/src/lib/tar.js.map +1 -0
- package/dist/production/run.cjs +7 -7
- package/dist/production/run.cjs.map +1 -1
- package/dist/production/run.js +8 -8
- package/dist/production/run.js.map +1 -1
- package/dist/production/src/commands/WorkspaceCreateCommand.cjs +36 -23
- package/dist/production/src/commands/WorkspaceCreateCommand.cjs.map +1 -1
- package/dist/production/src/commands/WorkspaceCreateCommand.js +37 -24
- package/dist/production/src/commands/WorkspaceCreateCommand.js.map +1 -1
- package/dist/production/src/lib/FileSystem.cjs +10 -4
- package/dist/production/src/lib/FileSystem.cjs.map +1 -1
- package/dist/production/src/lib/FileSystem.js +8 -2
- package/dist/production/src/lib/FileSystem.js.map +1 -1
- package/dist/production/src/lib/TemplateInstaller.cjs +71 -60
- package/dist/production/src/lib/TemplateInstaller.cjs.map +1 -1
- package/dist/production/src/lib/TemplateInstaller.js +71 -60
- package/dist/production/src/lib/TemplateInstaller.js.map +1 -1
- package/dist/production/src/lib/fsErrors.cjs +7 -0
- package/dist/production/src/lib/fsErrors.cjs.map +1 -0
- package/dist/production/src/lib/fsErrors.js +7 -0
- package/dist/production/src/lib/fsErrors.js.map +1 -0
- package/dist/production/src/lib/projectPath.cjs +66 -0
- package/dist/production/src/lib/projectPath.cjs.map +1 -0
- package/dist/production/src/lib/projectPath.js +66 -0
- package/dist/production/src/lib/projectPath.js.map +1 -0
- package/dist/production/src/lib/remoteTemplate.cjs +108 -0
- package/dist/production/src/lib/remoteTemplate.cjs.map +1 -0
- package/dist/production/src/lib/remoteTemplate.js +108 -0
- package/dist/production/src/lib/remoteTemplate.js.map +1 -0
- package/dist/production/src/lib/tar.cjs +243 -0
- package/dist/production/src/lib/tar.cjs.map +1 -0
- package/dist/production/src/lib/tar.js +243 -0
- package/dist/production/src/lib/tar.js.map +1 -0
- package/dist/types/commands/WorkspaceCreateCommand.d.ts +15 -3
- package/dist/types/commands/WorkspaceCreateCommand.d.ts.map +1 -1
- package/dist/types/lib/FileSystem.d.ts +2 -0
- package/dist/types/lib/FileSystem.d.ts.map +1 -1
- package/dist/types/lib/TemplateInstaller.d.ts +9 -1
- package/dist/types/lib/TemplateInstaller.d.ts.map +1 -1
- package/dist/types/lib/fsErrors.d.ts +3 -0
- package/dist/types/lib/fsErrors.d.ts.map +1 -0
- package/dist/types/lib/projectPath.d.ts +12 -0
- package/dist/types/lib/projectPath.d.ts.map +1 -0
- package/dist/types/lib/remoteTemplate.d.ts +15 -0
- package/dist/types/lib/remoteTemplate.d.ts.map +1 -0
- package/dist/types/lib/tar.d.ts +28 -0
- package/dist/types/lib/tar.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +5 -7
- package/resources/templates/default/README.md +3 -1
- package/resources/templates/default/admin/app/components/navigation.tsx +95 -8
- package/resources/templates/default/admin/app/pages/tenant.tsx +328 -77
- package/resources/templates/default/admin/entrypoint/components/login.tsx +1 -1
- package/resources/templates/default/admin/entrypoint/pages/magicLink.tsx +1 -1
- package/resources/templates/default/admin/entrypoint/pages/magicLinkSent.tsx +1 -1
- package/resources/templates/default/admin/entrypoint/pages/passwordReset.tsx +1 -1
- package/resources/templates/default/admin/entrypoint/pages/resetRequest.tsx +1 -1
- package/resources/templates/default/admin/entrypoint/pages/resetRequestSuccess.tsx +1 -1
- package/resources/templates/default/admin/lib/editor/common/editor-inline-toolbar.tsx +3 -0
- package/resources/templates/default/admin/lib/editor/sortable-block.tsx +5 -4
- package/resources/templates/default/admin/lib/tenant/config/auth-policy-list.tsx +86 -0
- package/resources/templates/default/admin/lib/tenant/config/common.tsx +71 -0
- package/resources/templates/default/admin/lib/tenant/config/identity-provider-list.tsx +113 -0
- package/resources/templates/default/admin/lib/tenant/config/index.ts +5 -0
- package/resources/templates/default/admin/lib/tenant/config/mail-template-list.tsx +108 -0
- package/resources/templates/default/admin/lib/tenant/config/tenant-config-view.tsx +182 -0
- package/resources/templates/default/admin/lib/tenant/dict.ts +453 -4
- package/resources/templates/default/admin/lib/tenant/errors.ts +10 -0
- package/resources/templates/default/admin/lib/tenant/forms/add-project-member.tsx +57 -0
- package/resources/templates/default/admin/lib/tenant/forms/change-my-profile.tsx +40 -0
- package/resources/templates/default/admin/lib/tenant/forms/change-profile.tsx +55 -0
- package/resources/templates/default/admin/lib/tenant/forms/common.tsx +9 -2
- package/resources/templates/default/admin/lib/tenant/forms/create-global-api-key.tsx +69 -0
- package/resources/templates/default/admin/lib/tenant/forms/global-roles-control.tsx +113 -0
- package/resources/templates/default/admin/lib/tenant/forms/index.ts +11 -0
- package/resources/templates/default/admin/lib/tenant/forms/invite.tsx +42 -4
- package/resources/templates/default/admin/lib/tenant/forms/login.tsx +4 -10
- package/resources/templates/default/admin/lib/tenant/forms/memberships-control.tsx +3 -1
- package/resources/templates/default/admin/lib/tenant/forms/mfa-code-fields.tsx +81 -0
- package/resources/templates/default/admin/lib/tenant/forms/passwordless-signin.tsx +4 -10
- package/resources/templates/default/admin/lib/tenant/forms/set-person-password.tsx +58 -0
- package/resources/templates/default/admin/lib/tenant/forms/set-project-secret.tsx +59 -0
- package/resources/templates/default/admin/lib/tenant/forms/sign-up.tsx +73 -0
- package/resources/templates/default/admin/lib/tenant/hooks/index.ts +2 -0
- package/resources/templates/default/admin/lib/tenant/idp/identity-provider-connections.tsx +124 -0
- package/resources/templates/default/admin/lib/tenant/idp/index.ts +1 -0
- package/resources/templates/default/admin/lib/tenant/index.ts +7 -0
- package/resources/templates/default/admin/lib/tenant/listing/api-key-list.tsx +160 -22
- package/resources/templates/default/admin/lib/tenant/listing/auth-log-list.tsx +179 -0
- package/resources/templates/default/admin/lib/tenant/listing/global-api-key-list.tsx +149 -0
- package/resources/templates/default/admin/lib/tenant/listing/index.ts +7 -0
- package/resources/templates/default/admin/lib/tenant/listing/member-delete-dialog.tsx +1 -1
- package/resources/templates/default/admin/lib/tenant/listing/member-list.tsx +20 -11
- package/resources/templates/default/admin/lib/tenant/listing/mfa.tsx +29 -0
- package/resources/templates/default/admin/lib/tenant/listing/person-actions.tsx +179 -0
- package/resources/templates/default/admin/lib/tenant/listing/person-detail.tsx +141 -0
- package/resources/templates/default/admin/lib/tenant/listing/person-list.tsx +13 -2
- package/resources/templates/default/admin/lib/tenant/listing/persons-list.tsx +128 -0
- package/resources/templates/default/admin/lib/tenant/listing/project-secret-list.tsx +82 -0
- package/resources/templates/default/admin/lib/tenant/otp/backup-codes.tsx +81 -0
- package/resources/templates/default/admin/lib/tenant/otp/email-otp-setup.tsx +133 -0
- package/resources/templates/default/admin/lib/tenant/otp/index.ts +2 -0
- package/resources/templates/default/admin/lib/tenant/security/index.ts +2 -0
- package/resources/templates/default/admin/lib/tenant/security/passwordless-toggle.tsx +63 -0
- package/resources/templates/default/admin/lib/tenant/security/session-list.tsx +143 -0
- package/resources/templates/default/admin/lib/ui/label.tsx +25 -2
- package/resources/templates/default/admin/lib/ui/menu.tsx +1 -1
- package/resources/templates/default/admin/lib/ui/progress.tsx +75 -11
- package/resources/templates/default/admin/lib/ui/separator.tsx +27 -3
- package/resources/templates/default/admin/lib/ui/sidebar.tsx +1 -1
- package/resources/templates/default/admin/lib/ui/toggle.tsx +41 -2
- package/resources/templates/default/admin/lib/utils/classNames.ts +107 -0
- package/resources/templates/default/admin/lib/utils/cn.ts +3 -3
- package/resources/templates/default/admin/lib/utils/index.ts +1 -0
- package/resources/templates/default/admin/lib/utils/uic.tsx +2 -3
- package/resources/templates/default/admin/package.json +1 -7
- package/resources/templates/default/docker/object-storage/README.md +13 -0
- package/resources/templates/default/docker/object-storage/identities.json +13 -0
- package/resources/templates/default/docker-compose.yaml +29 -7
- package/src/commands/WorkspaceCreateCommand.ts +51 -24
- package/src/lib/FileSystem.ts +7 -2
- package/src/lib/TemplateInstaller.ts +87 -69
- package/src/lib/fsErrors.ts +2 -0
- package/src/lib/projectPath.ts +79 -0
- package/src/lib/remoteTemplate.ts +130 -0
- package/src/lib/tar.ts +283 -0
- package/src/run.ts +8 -7
- package/tests/cases/unit/create-process.test.ts +66 -0
- package/tests/cases/unit/fileSystem.test.ts +14 -0
- package/tests/cases/unit/fixtures/template.tar.gz +0 -0
- package/tests/cases/unit/remoteTemplate.test.ts +277 -0
- package/tests/cases/unit/template-installer-cleanup.test.ts +150 -0
- package/tests/cases/unit/template-installer-containment.test.ts +133 -0
- package/tests/cases/unit/template-installer-symlinks.test.ts +37 -0
- package/tests/cases/unit/workspace-create.test.ts +81 -0
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import { join } from 'node:path'
|
|
2
|
-
import { FileSystem } from './FileSystem.js'
|
|
3
2
|
import jsyaml from 'js-yaml'
|
|
4
|
-
import
|
|
3
|
+
import { FileSystem } from './FileSystem.js'
|
|
4
|
+
import { resolveNewProjectPath, resolveProjectPath } from './projectPath.js'
|
|
5
|
+
import { downloadTemplate } from './remoteTemplate.js'
|
|
6
|
+
|
|
7
|
+
interface TemplateInstallerOutput {
|
|
8
|
+
warn(message: string): void
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
type CloneTemplate = (source: string, target: string) => Promise<void>
|
|
12
|
+
|
|
13
|
+
const cloneTemplate: CloneTemplate = (source, target) => downloadTemplate(source, target)
|
|
5
14
|
|
|
6
15
|
export class TemplateInstaller {
|
|
7
16
|
private localTemplates: Record<string, string>
|
|
@@ -9,6 +18,8 @@ export class TemplateInstaller {
|
|
|
9
18
|
constructor(
|
|
10
19
|
private readonly resourceDir: string,
|
|
11
20
|
private readonly fs: FileSystem,
|
|
21
|
+
private readonly output: TemplateInstallerOutput,
|
|
22
|
+
private readonly clone: CloneTemplate = cloneTemplate,
|
|
12
23
|
) {
|
|
13
24
|
this.localTemplates = {
|
|
14
25
|
['default']: join(this.resourceDir, 'templates/default'),
|
|
@@ -20,85 +31,92 @@ export class TemplateInstaller {
|
|
|
20
31
|
targetDir: string,
|
|
21
32
|
variables: Record<string, string> = {},
|
|
22
33
|
) => {
|
|
23
|
-
let
|
|
34
|
+
let temporaryTemplateDir: string | undefined
|
|
35
|
+
let remoteTemplate: string | undefined
|
|
24
36
|
|
|
25
37
|
if (this.localTemplates[template]) {
|
|
26
38
|
template = this.localTemplates[template]
|
|
27
39
|
} else {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
await emitter.clone(tmpDir)
|
|
40
|
+
remoteTemplate = template
|
|
41
|
+
temporaryTemplateDir = await this.fs.createTempDir()
|
|
42
|
+
template = temporaryTemplateDir
|
|
43
|
+
}
|
|
33
44
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
}
|
|
45
|
+
try {
|
|
46
|
+
if (remoteTemplate !== undefined) {
|
|
47
|
+
try {
|
|
48
|
+
await this.clone(remoteTemplate, template)
|
|
49
|
+
} catch (error) {
|
|
50
|
+
throw new Error(`Failed to clone template from repository: ${error}`)
|
|
40
51
|
}
|
|
41
|
-
|
|
42
|
-
template = tmpDir
|
|
43
|
-
} catch (error) {
|
|
44
|
-
throw new Error(`Failed to clone template from repository: ${error}`)
|
|
45
52
|
}
|
|
46
|
-
}
|
|
47
53
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
})
|
|
54
|
+
const templateConfigFile = join(template, 'contember.template.yaml')
|
|
55
|
+
if (!(await this.fs.pathExists(templateConfigFile))) {
|
|
56
|
+
throw new Error(`${template} is not a Contember template`)
|
|
57
|
+
}
|
|
58
|
+
const config = (await this.readYaml(templateConfigFile)) as {
|
|
59
|
+
type?: string
|
|
60
|
+
remove?: string[]
|
|
61
|
+
patchPackageJson?: boolean
|
|
62
|
+
rename?: Record<string, string>
|
|
63
|
+
copy?: Record<string, string>
|
|
64
|
+
replaceVariables?: string[]
|
|
65
|
+
}
|
|
66
|
+
const nodeModulesDir = join(template, 'node_modules')
|
|
67
|
+
const skippedFiles = new Set([...(config.remove || []).map(it => join(template, it)), templateConfigFile])
|
|
68
|
+
if (await this.fs.pathExists(targetDir)) {
|
|
69
|
+
throw `${targetDir} already exists`
|
|
70
|
+
}
|
|
71
|
+
await this.fs.copy(template, targetDir, {
|
|
72
|
+
filter: src => !src.startsWith(nodeModulesDir) && !skippedFiles.has(src),
|
|
73
|
+
})
|
|
69
74
|
|
|
70
|
-
|
|
75
|
+
if (config.patchPackageJson) {
|
|
76
|
+
await this.replaceFileContent(join(targetDir, 'package.json'), content => {
|
|
77
|
+
const {
|
|
78
|
+
name,
|
|
79
|
+
version,
|
|
80
|
+
'scripts-template': scripts,
|
|
81
|
+
scripts: _nullScripts,
|
|
82
|
+
license,
|
|
83
|
+
...json
|
|
84
|
+
} = JSON.parse(content)
|
|
85
|
+
return JSON.stringify({ scripts, ...json }, null, ' ')
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
// The template is untrusted input: every directive path must stay inside the new project.
|
|
89
|
+
const projectPath = (path: string) => resolveProjectPath(this.fs, targetDir, path)
|
|
90
|
+
for (const [source, target] of Object.entries(config.rename || {})) {
|
|
91
|
+
await this.fs.rename(await projectPath(source), await projectPath(target))
|
|
92
|
+
}
|
|
93
|
+
for (const [source, target] of Object.entries(config.copy || {})) {
|
|
94
|
+
await this.fs.copy(await projectPath(source), await resolveNewProjectPath(this.fs, targetDir, target))
|
|
95
|
+
}
|
|
71
96
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
for (const [source, target] of Object.entries(config.copy || {})) {
|
|
89
|
-
await this.fs.copy(join(targetDir, source), join(targetDir, target))
|
|
97
|
+
for (const file of config.replaceVariables || []) {
|
|
98
|
+
const path = await projectPath(file)
|
|
99
|
+
if (!(await this.fs.pathExists(path))) {
|
|
100
|
+
continue
|
|
101
|
+
}
|
|
102
|
+
await this.replaceFileContent(path, content =>
|
|
103
|
+
Object.entries(variables).reduce(
|
|
104
|
+
(content, [key, value]) => content.replace(new RegExp(`{${key}}`, 'g'), value),
|
|
105
|
+
content,
|
|
106
|
+
))
|
|
107
|
+
}
|
|
108
|
+
} finally {
|
|
109
|
+
if (temporaryTemplateDir !== undefined) {
|
|
110
|
+
await this.cleanupTemporaryTemplate(temporaryTemplateDir)
|
|
111
|
+
}
|
|
90
112
|
}
|
|
113
|
+
}
|
|
91
114
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
await this.replaceFileContent(path, content =>
|
|
98
|
-
Object.entries(variables).reduce(
|
|
99
|
-
(content, [key, value]) => content.replace(new RegExp(`{${key}}`, 'g'), value),
|
|
100
|
-
content,
|
|
101
|
-
))
|
|
115
|
+
private cleanupTemporaryTemplate = async (path: string): Promise<void> => {
|
|
116
|
+
try {
|
|
117
|
+
await this.fs.remove(path, { recursive: true, force: true })
|
|
118
|
+
} catch {
|
|
119
|
+
this.output.warn('Failed to clean up the temporary template directory.')
|
|
102
120
|
}
|
|
103
121
|
}
|
|
104
122
|
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
2
|
+
import { FileSystem } from './FileSystem.js'
|
|
3
|
+
import { isNotFound } from './fsErrors.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Resolves a path from a template directive against the project root.
|
|
7
|
+
* Refuses absolute paths, the root itself and anything that leaves the root, lexically or through a symlink.
|
|
8
|
+
*/
|
|
9
|
+
export const resolveProjectPath = async (fs: FileSystem, root: string, path: string): Promise<string> => {
|
|
10
|
+
const outside = new Error(`Template path "${path}" points outside the project`)
|
|
11
|
+
if (isAbsolute(path)) {
|
|
12
|
+
throw outside
|
|
13
|
+
}
|
|
14
|
+
const resolved = resolve(root, path)
|
|
15
|
+
if (!isStrictlyInside(root, resolved)) {
|
|
16
|
+
throw outside
|
|
17
|
+
}
|
|
18
|
+
const realRoot = await fs.realPath(root)
|
|
19
|
+
const realPath = await resolveExistingPrefix(fs, resolved)
|
|
20
|
+
if (realPath === undefined) {
|
|
21
|
+
throw new Error(`Template path "${path}" passes through a dangling symlink`)
|
|
22
|
+
}
|
|
23
|
+
if (!isStrictlyInside(realRoot, realPath)) {
|
|
24
|
+
throw outside
|
|
25
|
+
}
|
|
26
|
+
return resolved
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Like resolveProjectPath, and the path must not exist yet. fs.cp into an existing directory writes entries the check
|
|
31
|
+
* above never saw, and Bun's fs.cp follows symlinks it finds there.
|
|
32
|
+
*/
|
|
33
|
+
export const resolveNewProjectPath = async (fs: FileSystem, root: string, path: string): Promise<string> => {
|
|
34
|
+
const resolved = await resolveProjectPath(fs, root, path)
|
|
35
|
+
if (await isPresent(fs, resolved)) {
|
|
36
|
+
throw new Error(`Template path "${path}" already exists`)
|
|
37
|
+
}
|
|
38
|
+
return resolved
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isStrictlyInside = (root: string, path: string): boolean => {
|
|
42
|
+
const rel = relative(root, path)
|
|
43
|
+
return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* realpath() of the longest existing prefix, with the missing components appended (they cannot be symlinks).
|
|
48
|
+
* Returns undefined for a dangling symlink: writing to it would create its target, wherever that is.
|
|
49
|
+
*/
|
|
50
|
+
const resolveExistingPrefix = async (fs: FileSystem, path: string): Promise<string | undefined> => {
|
|
51
|
+
try {
|
|
52
|
+
return await fs.realPath(path)
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (!isNotFound(error)) {
|
|
55
|
+
throw error
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (await isPresent(fs, path)) {
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
const parent = dirname(path)
|
|
62
|
+
if (parent === path) {
|
|
63
|
+
return path
|
|
64
|
+
}
|
|
65
|
+
const realParent = await resolveExistingPrefix(fs, parent)
|
|
66
|
+
return realParent === undefined ? undefined : join(realParent, basename(path))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const isPresent = async (fs: FileSystem, path: string): Promise<boolean> => {
|
|
70
|
+
try {
|
|
71
|
+
await fs.lstat(path)
|
|
72
|
+
return true
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (isNotFound(error)) {
|
|
75
|
+
return false
|
|
76
|
+
}
|
|
77
|
+
throw error
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { mkdir } from 'node:fs/promises'
|
|
2
|
+
import { promisify } from 'node:util'
|
|
3
|
+
import { gunzip } from 'node:zlib'
|
|
4
|
+
import { extractTar, parseTar } from './tar.js'
|
|
5
|
+
|
|
6
|
+
export type TemplateHost = 'github' | 'gitlab' | 'bitbucket' | 'git.sr.ht'
|
|
7
|
+
|
|
8
|
+
export interface RemoteTemplateSource {
|
|
9
|
+
readonly host: TemplateHost
|
|
10
|
+
readonly user: string
|
|
11
|
+
readonly name: string
|
|
12
|
+
readonly subdir: readonly string[]
|
|
13
|
+
/** A branch, tag or commit; `HEAD` is the default branch. */
|
|
14
|
+
readonly ref: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const hosts: ReadonlySet<string> = new Set(['github', 'gitlab', 'bitbucket', 'git.sr.ht'])
|
|
18
|
+
const isTemplateHost = (value: string): value is TemplateHost => hosts.has(value)
|
|
19
|
+
|
|
20
|
+
// The source grammar of degit 2.8.4: `[host:|https://host/|git@host:]user/repo[/subdir][#ref]`.
|
|
21
|
+
const sourcePattern = /^(?:(?:https:\/\/)?([^:/]+\.[^:/]+)\/|git@([^:/]+)[:/]|([^/]+):)?([^/\s]+)\/([^/\s#]+)(?:((?:\/[^/\s#]+)+))?(?:\/)?(?:#(.+))?/
|
|
22
|
+
|
|
23
|
+
const isSafeSegment = (segment: string): boolean => segment !== '' && segment !== '.' && segment !== '..'
|
|
24
|
+
|
|
25
|
+
export const parseTemplateSource = (source: string): RemoteTemplateSource => {
|
|
26
|
+
const match = sourcePattern.exec(source)
|
|
27
|
+
if (!match) {
|
|
28
|
+
throw new Error(`Could not parse template source ${JSON.stringify(source)}`)
|
|
29
|
+
}
|
|
30
|
+
const host = (match[1] ?? match[2] ?? match[3] ?? 'github').replace(/\.(com|org)$/, '')
|
|
31
|
+
if (!isTemplateHost(host)) {
|
|
32
|
+
throw new Error('Remote templates are supported from GitHub, GitLab, Bitbucket and Sourcehut')
|
|
33
|
+
}
|
|
34
|
+
const user = match[4]
|
|
35
|
+
const name = match[5].replace(/\.git$/, '')
|
|
36
|
+
const subdir = (match[6] ?? '').split('/').filter(it => it !== '')
|
|
37
|
+
const ref = match[7] ?? 'HEAD'
|
|
38
|
+
if (![user, name, ...subdir, ...ref.split('/')].every(isSafeSegment)) {
|
|
39
|
+
throw new Error(`Could not parse template source ${JSON.stringify(source)}`)
|
|
40
|
+
}
|
|
41
|
+
return { host, user, name, subdir, ref }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const templateArchiveUrl = ({ host, user, name, ref }: RemoteTemplateSource): string => {
|
|
45
|
+
const repo = `${encodeURIComponent(user)}/${encodeURIComponent(name)}`
|
|
46
|
+
const path = ref.split('/').map(encodeURIComponent).join('/')
|
|
47
|
+
switch (host) {
|
|
48
|
+
case 'github':
|
|
49
|
+
return `https://github.com/${repo}/archive/${path}.tar.gz`
|
|
50
|
+
case 'gitlab':
|
|
51
|
+
return `https://gitlab.com/${repo}/-/archive/${path}/${encodeURIComponent(`${name}-${ref.split('/').join('-')}`)}.tar.gz`
|
|
52
|
+
case 'bitbucket':
|
|
53
|
+
return `https://bitbucket.org/${repo}/get/${path}.tar.gz`
|
|
54
|
+
case 'git.sr.ht':
|
|
55
|
+
return `https://git.sr.ht/${repo}/archive/${path}.tar.gz`
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Generous for a project template; it bounds what a hostile or broken archive can make us buffer or write. */
|
|
60
|
+
const maxArchiveBytes = 64 * 1024 * 1024
|
|
61
|
+
const maxExtractedBytes = 512 * 1024 * 1024
|
|
62
|
+
|
|
63
|
+
const readBody = async (response: Response, url: string): Promise<Uint8Array> => {
|
|
64
|
+
const declared = Number(response.headers.get('content-length'))
|
|
65
|
+
if (declared > maxArchiveBytes) {
|
|
66
|
+
throw new Error(`Template archive ${url} is larger than ${maxArchiveBytes} bytes`)
|
|
67
|
+
}
|
|
68
|
+
if (!response.body) {
|
|
69
|
+
return new Uint8Array()
|
|
70
|
+
}
|
|
71
|
+
const chunks: Uint8Array[] = []
|
|
72
|
+
let total = 0
|
|
73
|
+
for await (const chunk of response.body) {
|
|
74
|
+
total += chunk.length
|
|
75
|
+
if (total > maxArchiveBytes) {
|
|
76
|
+
throw new Error(`Template archive ${url} is larger than ${maxArchiveBytes} bytes`)
|
|
77
|
+
}
|
|
78
|
+
chunks.push(chunk)
|
|
79
|
+
}
|
|
80
|
+
return Buffer.concat(chunks)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type Fetch = (url: string, init: RequestInit) => Promise<Response>
|
|
84
|
+
|
|
85
|
+
const maxRedirects = 5
|
|
86
|
+
|
|
87
|
+
/** Follows redirects by hand, so that every hop, not only the last one, has to stay on HTTPS. */
|
|
88
|
+
const fetchOverHttps = async (url: string, fetchArchive: Fetch): Promise<Response> => {
|
|
89
|
+
let current = url
|
|
90
|
+
for (let hop = 0;; hop++) {
|
|
91
|
+
let response: Response
|
|
92
|
+
try {
|
|
93
|
+
response = await fetchArchive(current, { redirect: 'manual' })
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw new Error(`Could not download ${current}: ${error}. Behind a proxy, Node needs NODE_USE_ENV_PROXY=1 with HTTPS_PROXY.`)
|
|
96
|
+
}
|
|
97
|
+
if (response.status < 300 || response.status >= 400) {
|
|
98
|
+
if (!response.ok) {
|
|
99
|
+
throw new Error(`Could not download ${current}: HTTP ${response.status}`)
|
|
100
|
+
}
|
|
101
|
+
return response
|
|
102
|
+
}
|
|
103
|
+
const location = response.headers.get('location')
|
|
104
|
+
if (location === null || hop >= maxRedirects) {
|
|
105
|
+
throw new Error(`Could not download ${url}: too many or invalid redirects`)
|
|
106
|
+
}
|
|
107
|
+
const next = new URL(location, current)
|
|
108
|
+
if (next.protocol !== 'https:') {
|
|
109
|
+
throw new Error(`Could not download ${url}: redirected to a non-HTTPS location`)
|
|
110
|
+
}
|
|
111
|
+
current = next.href
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Downloads the source's archive over HTTPS and extracts it (or its subdirectory) into `targetDir`. */
|
|
116
|
+
export const downloadTemplate = async (source: string, targetDir: string, fetchArchive: Fetch = fetch): Promise<void> => {
|
|
117
|
+
const parsed = parseTemplateSource(source)
|
|
118
|
+
const url = templateArchiveUrl(parsed)
|
|
119
|
+
const response = await fetchOverHttps(url, fetchArchive)
|
|
120
|
+
const compressed = await readBody(response, url)
|
|
121
|
+
let archive: Uint8Array
|
|
122
|
+
try {
|
|
123
|
+
archive = await promisify(gunzip)(compressed, { maxOutputLength: maxExtractedBytes })
|
|
124
|
+
} catch (error) {
|
|
125
|
+
throw new Error(`Template archive ${url} is not a readable gzip file (or exceeds ${maxExtractedBytes} bytes): ${error}`)
|
|
126
|
+
}
|
|
127
|
+
await mkdir(targetDir, { recursive: true })
|
|
128
|
+
// Every host wraps the repository in one top-level directory.
|
|
129
|
+
await extractTar(parseTar(archive), targetDir, { strip: 1, subdir: parsed.subdir })
|
|
130
|
+
}
|
package/src/lib/tar.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { lstat, mkdir, symlink, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { join, resolve, sep } from 'node:path'
|
|
3
|
+
import { hasCode, isNotFound } from './fsErrors.js'
|
|
4
|
+
|
|
5
|
+
export type TarEntry =
|
|
6
|
+
| { readonly type: 'file'; readonly path: string; readonly mode: number; readonly data: Uint8Array }
|
|
7
|
+
| { readonly type: 'directory'; readonly path: string }
|
|
8
|
+
| { readonly type: 'symlink'; readonly path: string; readonly target: string }
|
|
9
|
+
|
|
10
|
+
const blockSize = 512
|
|
11
|
+
const decoder = new TextDecoder()
|
|
12
|
+
|
|
13
|
+
const readString = (block: Uint8Array, offset: number, length: number): string => {
|
|
14
|
+
const field = block.subarray(offset, offset + length)
|
|
15
|
+
const end = field.indexOf(0)
|
|
16
|
+
return decoder.decode(end === -1 ? field : field.subarray(0, end))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const readOctal = (block: Uint8Array, offset: number, length: number, field: string): number => {
|
|
20
|
+
const text = readString(block, offset, length).trim()
|
|
21
|
+
if (!/^[0-7]*$/.test(text)) {
|
|
22
|
+
throw new Error(`Invalid tar archive: unreadable ${field} field`)
|
|
23
|
+
}
|
|
24
|
+
return text === '' ? 0 : Number.parseInt(text, 8)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const verifyChecksum = (block: Uint8Array): void => {
|
|
28
|
+
const expected = readOctal(block, 148, 8, 'checksum')
|
|
29
|
+
let sum = 0
|
|
30
|
+
for (let i = 0; i < blockSize; i++) {
|
|
31
|
+
sum += i >= 148 && i < 156 ? 0x20 : block[i]
|
|
32
|
+
}
|
|
33
|
+
if (sum !== expected) {
|
|
34
|
+
throw new Error('Invalid tar archive: header checksum mismatch')
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** PAX extended header records: `<length> <key>=<value>\n`. */
|
|
39
|
+
const parsePax = (data: Uint8Array): Map<string, string> => {
|
|
40
|
+
const records = new Map<string, string>()
|
|
41
|
+
let offset = 0
|
|
42
|
+
while (offset < data.length) {
|
|
43
|
+
const space = data.indexOf(0x20, offset)
|
|
44
|
+
const length = space === -1 ? Number.NaN : Number(decoder.decode(data.subarray(offset, space)))
|
|
45
|
+
if (!Number.isSafeInteger(length) || length <= 0 || offset + length > data.length) {
|
|
46
|
+
throw new Error('Invalid tar archive: malformed PAX header')
|
|
47
|
+
}
|
|
48
|
+
const record = decoder.decode(data.subarray(space + 1, offset + length - 1))
|
|
49
|
+
const equals = record.indexOf('=')
|
|
50
|
+
if (equals > 0) {
|
|
51
|
+
records.set(record.slice(0, equals), record.slice(equals + 1))
|
|
52
|
+
}
|
|
53
|
+
offset += length
|
|
54
|
+
}
|
|
55
|
+
return records
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Reads a POSIX (ustar/PAX) or GNU tar archive. Rejects entry types other than files, directories and symlinks. */
|
|
59
|
+
export const parseTar = (archive: Uint8Array): TarEntry[] => {
|
|
60
|
+
const entries: TarEntry[] = []
|
|
61
|
+
let pax = new Map<string, string>()
|
|
62
|
+
let longName: string | undefined
|
|
63
|
+
let longLink: string | undefined
|
|
64
|
+
let offset = 0
|
|
65
|
+
while (offset + blockSize <= archive.length) {
|
|
66
|
+
const header = archive.subarray(offset, offset + blockSize)
|
|
67
|
+
if (header.every(byte => byte === 0)) {
|
|
68
|
+
return entries
|
|
69
|
+
}
|
|
70
|
+
verifyChecksum(header)
|
|
71
|
+
const type = String.fromCharCode(header[156])
|
|
72
|
+
const paxSize = pax.get('size')
|
|
73
|
+
if (paxSize !== undefined && !/^\d+$/.test(paxSize)) {
|
|
74
|
+
throw new Error('Invalid tar archive: unreadable PAX size')
|
|
75
|
+
}
|
|
76
|
+
const size = paxSize !== undefined ? Number(paxSize) : readOctal(header, 124, 12, 'size')
|
|
77
|
+
const dataStart = offset + blockSize
|
|
78
|
+
if (!Number.isSafeInteger(size) || dataStart + size > archive.length) {
|
|
79
|
+
throw new Error('Invalid tar archive: entry exceeds the archive')
|
|
80
|
+
}
|
|
81
|
+
const data = archive.subarray(dataStart, dataStart + size)
|
|
82
|
+
offset = dataStart + Math.ceil(size / blockSize) * blockSize
|
|
83
|
+
|
|
84
|
+
if (type === 'x') {
|
|
85
|
+
pax = parsePax(data)
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
if (type === 'g') {
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
if (type === 'L' || type === 'K') {
|
|
92
|
+
const value = readString(data, 0, data.length)
|
|
93
|
+
if (type === 'L') {
|
|
94
|
+
longName = value
|
|
95
|
+
} else {
|
|
96
|
+
longLink = value
|
|
97
|
+
}
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const isUstar = readString(header, 257, 5) === 'ustar'
|
|
102
|
+
const prefix = isUstar ? readString(header, 345, 155) : ''
|
|
103
|
+
const name = readString(header, 0, 100)
|
|
104
|
+
const path = pax.get('path') ?? longName ?? (prefix ? `${prefix}/${name}` : name)
|
|
105
|
+
const linkTarget = pax.get('linkpath') ?? longLink ?? readString(header, 157, 100)
|
|
106
|
+
pax = new Map()
|
|
107
|
+
longName = undefined
|
|
108
|
+
longLink = undefined
|
|
109
|
+
|
|
110
|
+
if (type === '0' || type === '\0' || type === '7') {
|
|
111
|
+
entries.push({ type: 'file', path, mode: readOctal(header, 100, 8, 'mode'), data })
|
|
112
|
+
} else if (type === '5') {
|
|
113
|
+
entries.push({ type: 'directory', path })
|
|
114
|
+
} else if (type === '2') {
|
|
115
|
+
entries.push({ type: 'symlink', path, target: linkTarget })
|
|
116
|
+
} else {
|
|
117
|
+
throw new Error(`Unsupported tar entry "${path}" (type ${JSON.stringify(type)})`)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
throw new Error('Invalid tar archive: missing end-of-archive marker')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const unsafe = (what: string, value: string): Error => new Error(`Refusing ${what} in template archive: ${JSON.stringify(value)}`)
|
|
124
|
+
|
|
125
|
+
/** Longer and deeper than any real template path; together they bound the per-component work for each entry. */
|
|
126
|
+
const maxPathLength = 4096
|
|
127
|
+
const maxPathDepth = 256
|
|
128
|
+
|
|
129
|
+
/** The entry's path components below `subdir`, or `undefined` when it lies outside; throws on paths that could escape. */
|
|
130
|
+
const relativeComponents = (path: string, strip: number, subdir: readonly string[]): string[] | undefined => {
|
|
131
|
+
if (path.startsWith('/')) {
|
|
132
|
+
throw unsafe('absolute path', path)
|
|
133
|
+
}
|
|
134
|
+
if (path.length > maxPathLength) {
|
|
135
|
+
throw unsafe('overlong path', path.slice(0, 100))
|
|
136
|
+
}
|
|
137
|
+
const components = path.split('/').filter(it => it !== '' && it !== '.').slice(strip)
|
|
138
|
+
if (components.length > maxPathDepth) {
|
|
139
|
+
throw unsafe('too deeply nested path', path.slice(0, 100))
|
|
140
|
+
}
|
|
141
|
+
if (components.length <= subdir.length || subdir.some((it, index) => components[index] !== it)) {
|
|
142
|
+
return undefined
|
|
143
|
+
}
|
|
144
|
+
const relative = components.slice(subdir.length)
|
|
145
|
+
if (relative.some(it => it === '..' || it.includes('\\'))) {
|
|
146
|
+
throw unsafe('path', path)
|
|
147
|
+
}
|
|
148
|
+
return relative
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Resolves `target` from the link's directory; it must stay inside the root and not pass through another archive link. */
|
|
152
|
+
const isContainedLinkTarget = (link: readonly string[], target: string, links: ReadonlySet<string>): boolean => {
|
|
153
|
+
if (target.length > maxPathLength || target.startsWith('/') || target.includes('\\') || /^[a-zA-Z]:/.test(target)) {
|
|
154
|
+
return false
|
|
155
|
+
}
|
|
156
|
+
const resolved = link.slice(0, -1)
|
|
157
|
+
const parts = target.split('/').filter(it => it !== '' && it !== '.')
|
|
158
|
+
if (parts.length > maxPathDepth) {
|
|
159
|
+
return false
|
|
160
|
+
}
|
|
161
|
+
for (const [index, part] of parts.entries()) {
|
|
162
|
+
if (part === '..') {
|
|
163
|
+
if (resolved.length === 0) {
|
|
164
|
+
return false
|
|
165
|
+
}
|
|
166
|
+
resolved.pop()
|
|
167
|
+
} else {
|
|
168
|
+
resolved.push(part)
|
|
169
|
+
if (index < parts.length - 1 && links.has(resolved.join('/'))) {
|
|
170
|
+
return false
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return true
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Creates the directories one component at a time and refuses to pass through a symlink. The string checks cannot see
|
|
179
|
+
* aliases a case-insensitive or normalising filesystem makes (`D/L` is `d/l`), the filesystem itself can.
|
|
180
|
+
*/
|
|
181
|
+
const ensureDirectory = async (root: string, components: readonly string[], path: string): Promise<void> => {
|
|
182
|
+
let current = root
|
|
183
|
+
for (const component of components) {
|
|
184
|
+
current = join(current, component)
|
|
185
|
+
try {
|
|
186
|
+
const stat = await lstat(current)
|
|
187
|
+
if (stat.isSymbolicLink()) {
|
|
188
|
+
throw unsafe('entry below a symlink', path)
|
|
189
|
+
}
|
|
190
|
+
if (!stat.isDirectory()) {
|
|
191
|
+
throw new Error(`Template archive entry ${JSON.stringify(path)} collides with a file`)
|
|
192
|
+
}
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (!isNotFound(error)) {
|
|
195
|
+
throw error
|
|
196
|
+
}
|
|
197
|
+
await mkdir(current)
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Walks a created link's target on the filesystem: no component before the last may be a symlink. */
|
|
203
|
+
const assertTargetWithoutLinks = async (root: string, link: readonly string[], target: string, path: string): Promise<void> => {
|
|
204
|
+
const resolved = link.slice(0, -1)
|
|
205
|
+
const parts = target.split('/').filter(it => it !== '' && it !== '.')
|
|
206
|
+
for (const [index, part] of parts.entries()) {
|
|
207
|
+
if (part === '..') {
|
|
208
|
+
resolved.pop()
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
resolved.push(part)
|
|
212
|
+
if (index === parts.length - 1) {
|
|
213
|
+
return
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
if ((await lstat(join(root, ...resolved))).isSymbolicLink()) {
|
|
217
|
+
throw unsafe('symlink pointing outside the template', `${path} -> ${target}`)
|
|
218
|
+
}
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (isNotFound(error)) {
|
|
221
|
+
// a dangling target; the string check already kept it inside
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
if (hasCode(error, 'ENOTDIR')) {
|
|
225
|
+
throw unsafe('symlink resolving through a file', `${path} -> ${target}`)
|
|
226
|
+
}
|
|
227
|
+
throw error
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export interface ExtractOptions {
|
|
233
|
+
/** Leading path components dropped from every entry, e.g. the archive's top-level directory. */
|
|
234
|
+
readonly strip: number
|
|
235
|
+
/** Only entries below this directory (after `strip`) are extracted, relative to it. */
|
|
236
|
+
readonly subdir?: readonly string[]
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Writes the entries into `targetDir`. Paths stay inside it, no entry may sit below a symlink, and a link target must
|
|
241
|
+
* resolve inside without passing through another link. Checked on the names first, then on the filesystem while
|
|
242
|
+
* writing. Links are created last, so no file is written through one.
|
|
243
|
+
*/
|
|
244
|
+
export const extractTar = async (entries: readonly TarEntry[], targetDir: string, { strip, subdir = [] }: ExtractOptions): Promise<void> => {
|
|
245
|
+
const root = resolve(targetDir)
|
|
246
|
+
const selected = entries.flatMap(entry => {
|
|
247
|
+
const relative = relativeComponents(entry.path, strip, subdir)
|
|
248
|
+
return relative ? [{ entry, relative }] : []
|
|
249
|
+
})
|
|
250
|
+
const links = new Set(selected.filter(it => it.entry.type === 'symlink').map(it => it.relative.join('/')))
|
|
251
|
+
for (const { entry, relative } of selected) {
|
|
252
|
+
if (relative.some((_, index) => index > 0 && links.has(relative.slice(0, index).join('/')))) {
|
|
253
|
+
throw unsafe('entry below a symlink', entry.path)
|
|
254
|
+
}
|
|
255
|
+
if (entry.type === 'symlink' && !isContainedLinkTarget(relative, entry.target, links)) {
|
|
256
|
+
throw unsafe('symlink pointing outside the template', `${entry.path} -> ${entry.target}`)
|
|
257
|
+
}
|
|
258
|
+
if (!resolve(root, ...relative).startsWith(root + sep)) {
|
|
259
|
+
throw unsafe('path', entry.path)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
await mkdir(root, { recursive: true })
|
|
263
|
+
for (const { entry, relative } of selected) {
|
|
264
|
+
if (entry.type === 'directory') {
|
|
265
|
+
await ensureDirectory(root, relative, entry.path)
|
|
266
|
+
} else if (entry.type === 'file') {
|
|
267
|
+
await ensureDirectory(root, relative.slice(0, -1), entry.path)
|
|
268
|
+
// `wx` never follows or replaces an existing entry
|
|
269
|
+
await writeFile(join(root, ...relative), entry.data, { mode: (entry.mode & 0o777) || 0o644, flag: 'wx' })
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const created: { relative: readonly string[]; target: string; path: string }[] = []
|
|
273
|
+
for (const { entry, relative } of selected) {
|
|
274
|
+
if (entry.type === 'symlink') {
|
|
275
|
+
await ensureDirectory(root, relative.slice(0, -1), entry.path)
|
|
276
|
+
await symlink(entry.target, join(root, ...relative))
|
|
277
|
+
created.push({ relative, target: entry.target, path: entry.path })
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
for (const link of created) {
|
|
281
|
+
await assertTargetWithoutLinks(root, link.relative, link.target, link.path)
|
|
282
|
+
}
|
|
283
|
+
}
|