@contember/create 2.2.0-alpha.18 → 2.2.0-alpha.19
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/development/src/commands/WorkspaceCreateCommand.cjs +13 -14
- package/dist/development/src/commands/WorkspaceCreateCommand.cjs.map +1 -1
- package/dist/development/src/commands/WorkspaceCreateCommand.js +14 -15
- 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 +13 -14
- package/dist/development/src/lib/TemplateInstaller.cjs.map +1 -1
- package/dist/development/src/lib/TemplateInstaller.js +7 -8
- 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/src/commands/WorkspaceCreateCommand.cjs +13 -14
- package/dist/production/src/commands/WorkspaceCreateCommand.cjs.map +1 -1
- package/dist/production/src/commands/WorkspaceCreateCommand.js +14 -15
- 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 +13 -14
- package/dist/production/src/lib/TemplateInstaller.cjs.map +1 -1
- package/dist/production/src/lib/TemplateInstaller.js +7 -8
- 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.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.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/admin/lib/editor/sortable-block.tsx +5 -4
- 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 +0 -7
- package/src/commands/WorkspaceCreateCommand.ts +14 -15
- package/src/lib/FileSystem.ts +7 -2
- package/src/lib/TemplateInstaller.ts +8 -8
- 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/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-containment.test.ts +133 -0
- package/tests/cases/unit/template-installer-symlinks.test.ts +37 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { rm } from 'node:fs/promises'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import { dirname } from 'node:path'
|
|
5
|
+
import { FileSystem } from '../../../src/lib/FileSystem.js'
|
|
6
|
+
|
|
7
|
+
test('creates the temporary directory inside the OS temp directory', async () => {
|
|
8
|
+
const dir = await new FileSystem().createTempDir()
|
|
9
|
+
try {
|
|
10
|
+
expect(dirname(dir)).toBe(tmpdir())
|
|
11
|
+
} finally {
|
|
12
|
+
await rm(dir, { recursive: true, force: true })
|
|
13
|
+
}
|
|
14
|
+
})
|
|
Binary file
|