@pyrokine/mcp-ssh 2.4.2 → 3.0.0

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,7 +1,8 @@
1
1
  import { createHash } from 'crypto';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
- import { escapeShellArg } from './tools/utils.js';
4
+ import { remoteJoin } from './remote-platform.js';
5
+ import { formatFileMode } from './file-mode.js';
5
6
  export const DIRECTORY_VERIFY_MAX_ENTRIES = 50_000;
6
7
  export const DIRECTORY_VERIFY_MAX_MISMATCHES = 20;
7
8
  export const DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES = 256 * 1024 * 1024;
@@ -21,48 +22,53 @@ function rootHash(entries) {
21
22
  }
22
23
  return hash.digest('hex');
23
24
  }
24
- async function hashFile(filePath) {
25
+ async function hashFile(filePath, size, maxBytes) {
25
26
  const hash = createHash('sha256');
26
- await new Promise((resolve, reject) => {
27
- const stream = fs.createReadStream(filePath);
28
- stream.on('data', (chunk) => hash.update(chunk));
29
- stream.on('error', reject);
30
- stream.on('end', resolve);
31
- });
32
- return hash.digest('hex');
33
- }
34
- function globPatternToRegExp(pattern) {
35
- let expression = '';
36
- for (let index = 0; index < pattern.length; ++index) {
37
- const character = pattern[index];
38
- if (character === '*' && pattern[index + 1] === '*') {
39
- expression += '.*';
40
- ++index;
41
- }
42
- else if (character === '*') {
43
- expression += '[^/]*';
44
- }
45
- else if (character === '?') {
46
- expression += '[^/]';
47
- }
48
- else {
49
- expression += character.replace(/[.+^${}()|[\]\\]/g, '\\$&');
27
+ let readBytes = 0;
28
+ for await (const chunk of fs.createReadStream(filePath)) {
29
+ readBytes += Buffer.byteLength(chunk);
30
+ if (readBytes > maxBytes) {
31
+ throw new Error('local file grew beyond directory manifest hash budget');
50
32
  }
33
+ hash.update(chunk);
51
34
  }
52
- return new RegExp(`^${expression}$`);
35
+ if (readBytes !== size) {
36
+ throw new Error('local file changed during manifest hashing');
37
+ }
38
+ return hash.digest('hex');
53
39
  }
54
- const excludePatternCache = new Map();
55
40
  export function matchesDirectoryExclude(relativePath, patterns) {
56
41
  const normalizedPath = relativePath.replace(/^\.\//, '').replace(/^\//, '');
57
42
  const basename = path.posix.basename(normalizedPath);
58
43
  return Boolean(patterns?.some((pattern) => {
59
44
  const normalizedPattern = pattern.replace(/^\//, '');
60
- let regex = excludePatternCache.get(normalizedPattern);
61
- if (!regex) {
62
- regex = globPatternToRegExp(normalizedPattern);
63
- excludePatternCache.set(normalizedPattern, regex);
45
+ const candidate = normalizedPattern.includes('/') ? normalizedPath : basename;
46
+ const matches = new Uint8Array(candidate.length + 1);
47
+ matches[0] = 1;
48
+ for (let index = 0; index < normalizedPattern.length; ++index) {
49
+ const character = normalizedPattern[index];
50
+ const globstar = character === '*' && normalizedPattern[index + 1] === '*';
51
+ if (globstar) {
52
+ ++index;
53
+ }
54
+ let previous = matches[0];
55
+ if (character !== '*') {
56
+ matches[0] = 0;
57
+ }
58
+ for (let offset = 1; offset <= candidate.length; ++offset) {
59
+ const before = matches[offset];
60
+ const value = candidate[offset - 1];
61
+ if (character === '*') {
62
+ const canConsume = globstar ? /./.test(value) : value !== '/';
63
+ matches[offset] = before || (matches[offset - 1] && canConsume) ? 1 : 0;
64
+ }
65
+ else {
66
+ matches[offset] = previous && (character === '?' ? value !== '/' : character === value) ? 1 : 0;
67
+ }
68
+ previous = before;
69
+ }
64
70
  }
65
- return regex.test(normalizedPattern.includes('/') ? normalizedPath : basename);
71
+ return matches[candidate.length] === 1;
66
72
  }));
67
73
  }
68
74
  export async function createLocalDirectoryManifest(rootPath, request, exclude, followSymlinks = false) {
@@ -78,7 +84,7 @@ export async function createLocalDirectoryManifest(rootPath, request, exclude, f
78
84
  path: '.',
79
85
  type: 'directory',
80
86
  size: 0,
81
- mode: (rootStats.mode & 0o777).toString(8).padStart(4, '0'),
87
+ mode: formatFileMode(rootStats.mode),
82
88
  owner: String(rootStats.uid),
83
89
  },
84
90
  ];
@@ -117,7 +123,7 @@ export async function createLocalDirectoryManifest(rootPath, request, exclude, f
117
123
  path: relativePath,
118
124
  type: 'directory',
119
125
  size: 0,
120
- mode: (stats.mode & 0o777).toString(8).padStart(4, '0'),
126
+ mode: formatFileMode(stats.mode),
121
127
  owner: String(stats.uid),
122
128
  });
123
129
  await visit(fullPath, relativePath);
@@ -136,14 +142,14 @@ export async function createLocalDirectoryManifest(rootPath, request, exclude, f
136
142
  limitReason = 'total_bytes';
137
143
  return;
138
144
  }
145
+ sha256 = await hashFile(fullPath, stats.size, Math.min(maxFileBytes, maxTotalBytes - hashedBytes));
139
146
  hashedBytes += stats.size;
140
- sha256 = await hashFile(fullPath);
141
147
  }
142
148
  entries.push({
143
149
  path: relativePath,
144
150
  type: 'file',
145
151
  size: stats.size,
146
- mode: (stats.mode & 0o777).toString(8).padStart(4, '0'),
152
+ mode: formatFileMode(stats.mode),
147
153
  owner: String(stats.uid),
148
154
  sha256,
149
155
  });
@@ -172,204 +178,151 @@ export async function createLocalDirectoryManifest(rootPath, request, exclude, f
172
178
  unsupportedSamples,
173
179
  };
174
180
  }
175
- export function createEmptyDirectoryManifest() {
176
- const entries = [];
177
- return {
178
- entries,
179
- count: 0,
180
- rootSha256: rootHash(entries),
181
- limited: false,
182
- skippedSymlinks: 0,
183
- skippedUnsupported: 0,
184
- unsupportedSamples: [],
185
- };
186
- }
187
- function buildExcludeRegexes(exclude) {
188
- const pathPatterns = [];
189
- const basenamePatterns = [];
190
- for (const pattern of exclude ?? []) {
191
- const normalized = pattern.replace(/^\//, '');
192
- const expression = globPatternToRegExp(normalized).source.replace(/^\^|\$$/g, '');
193
- if (normalized.includes('/')) {
194
- pathPatterns.push(expression);
195
- }
196
- else {
197
- basenamePatterns.push(expression);
198
- }
199
- }
200
- return {
201
- path: pathPatterns.length > 0 ? `^(${pathPatterns.join('|')})$` : undefined,
202
- basename: basenamePatterns.length > 0 ? `^(${basenamePatterns.join('|')})$` : undefined,
203
- };
204
- }
205
- export function buildRemoteDirectoryManifestCommand(rootPath, request, exclude, followSymlinks = false) {
181
+ export async function createRemoteDirectoryManifest(sftp, rootPath, request, exclude, followSymlinks = false, style = 'posix') {
206
182
  const maxEntries = Math.min(request.maxEntries ?? 10_000, DIRECTORY_VERIFY_MAX_ENTRIES);
207
183
  const maxFileBytes = Math.min(request.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_FILE_BYTES);
208
184
  const maxTotalBytes = Math.min(request.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES);
209
- const normalizedRoot = rootPath.replace(/\/+$/, '') || '/';
210
- const root = escapeShellArg(normalizedRoot);
211
- const includeHash = request.sha256 === true;
212
- const excludeRegexes = buildExcludeRegexes(exclude);
213
- const pathExcludeRegex = excludeRegexes.path ? escapeShellArg(excludeRegexes.path) : undefined;
214
- const basenameExcludeRegex = excludeRegexes.basename ? escapeShellArg(excludeRegexes.basename) : undefined;
215
- const findFollow = followSymlinks ? '-L' : '-H';
216
- const script = [
217
- 'set -euo pipefail',
218
- 'export LC_ALL=C',
219
- `root=${root}`,
220
- '[ -d "$root" ] || { printf "remote directory does not exist\\n" >&2; exit 3; }',
221
- 'count=0',
222
- 'hashed_bytes=0',
223
- 'skipped_symlinks=0',
224
- 'skipped_unsupported=0',
225
- 'unsupported_samples=()',
226
- 'excluded_dirs=()',
227
- 'while IFS= read -r -d "" item; do',
228
- ' if [ "$item" = "__MCP_FIND_ERROR__" ]; then exit 4; fi',
229
- ` if [ "$item" = "$root" ]; then
230
- rel=.
231
- elif [ "$root" = / ]; then
232
- rel=\${item#/}
233
- else
234
- rel=\${item#"$root"/}
235
- fi`,
236
- ' for excluded_dir in "${excluded_dirs[@]}"; do case "$rel" in "$excluded_dir"/*) continue 2;; esac; done',
237
- pathExcludeRegex
238
- ? ` if [ "$rel" != . ] && printf %s "$rel" | grep -Eq -- ${pathExcludeRegex}; then
239
- [ -d "$item" ] && excluded_dirs+=("$rel")
240
- continue
241
- fi`
242
- : ' :',
243
- basenameExcludeRegex
244
- ? ` base=\${rel##*/}
245
- if [ "$rel" != . ] && printf %s "$base" | grep -Eq -- ${basenameExcludeRegex}; then
246
- [ -d "$item" ] && excluded_dirs+=("$rel")
247
- continue
248
- fi`
249
- : ' :',
250
- followSymlinks
251
- ? ' :'
252
- : ' if [ "$rel" != . ] && [ -L "$item" ]; then skipped_symlinks=$((skipped_symlinks + 1)); continue; fi',
253
- ` if [ -d "$item" ]; then
254
- type=directory
255
- size=0
256
- elif [ -f "$item" ]; then
257
- type=file
258
- size=$(stat -c %s -- "$item")
259
- else
260
- skipped_unsupported=$((skipped_unsupported + 1))
261
- if [ "\${#unsupported_samples[@]}" -lt 10 ]; then
262
- unsupported_samples+=("$(printf %s "$rel" | base64 | tr -d "\\n")")
263
- fi
264
- continue
265
- fi`,
266
- ' count=$((count + 1))',
267
- ` if [ "$count" -gt ${maxEntries} ]; then printf '__MCP_LIMIT__\\tentries\\n'; break; fi`,
268
- ' raw_mode=$(stat -c %a -- "$item")',
269
- ' mode=$(printf \'%04o\' "$((8#$raw_mode & 0777))")',
270
- ' owner=$(stat -c %u -- "$item")',
271
- includeHash
272
- ? ` if [ "$type" = file ]; then
273
- if [ "$size" -gt ${maxFileBytes} ]; then printf '__MCP_LIMIT__\\tfile_bytes\\n'; break; fi
274
- next_hashed_bytes=$((hashed_bytes + size))
275
- if [ "$next_hashed_bytes" -gt ${maxTotalBytes} ]; then printf '__MCP_LIMIT__\\ttotal_bytes\\n'; break; fi
276
- hashed_bytes=$next_hashed_bytes
277
- digest=$(sha256sum -- "$item" | cut -d " " -f 1)
278
- else digest=; fi`
279
- : ' digest=',
280
- ' encoded=$(printf %s "$rel" | base64 | tr -d "\\n")',
281
- ' printf "%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n" "$encoded" "$type" "$size" "$mode" "$owner" "$digest"',
282
- `done < <({ find ${findFollow} "$root" -print0 || printf '%s\\0' '__MCP_FIND_ERROR__'; })`,
283
- 'printf "__MCP_SKIPPED_SYMLINKS__\\t%s\\n" "$skipped_symlinks"',
284
- 'printf "__MCP_SKIPPED_UNSUPPORTED__\\t%s\\n" "$skipped_unsupported"',
285
- 'for sample in "${unsupported_samples[@]}"; do printf "__MCP_UNSUPPORTED_SAMPLE__\\t%s\\n" "$sample"; done',
286
- ].join('\n');
287
- return `bash -c ${escapeShellArg(script)}`;
288
- }
289
- function decodeManifestPath(encodedPath) {
290
- const decodedPath = Buffer.from(encodedPath, 'base64').toString('utf-8');
291
- if (!encodedPath ||
292
- !/^[A-Za-z0-9+/]+={0,2}$/.test(encodedPath) ||
293
- encodedPath.length % 4 !== 0 ||
294
- !decodedPath ||
295
- decodedPath.length > 4096 ||
296
- decodedPath.includes('\0') ||
297
- path.posix.isAbsolute(decodedPath) ||
298
- decodedPath.split('/').includes('..')) {
299
- throw new Error('remote directory verification returned malformed manifest path');
185
+ const join = (parent, child) => remoteJoin(style, parent, child);
186
+ const stat = (remotePath) => new Promise((resolve, reject) => {
187
+ sftp.stat(remotePath, (error, stats) => (error ? reject(error) : resolve(stats)));
188
+ });
189
+ const lstat = (remotePath) => new Promise((resolve, reject) => {
190
+ sftp.lstat(remotePath, (error, stats) => (error ? reject(error) : resolve(stats)));
191
+ });
192
+ const root = await stat(rootPath);
193
+ if ((root.mode & 0o170000) !== 0o040000) {
194
+ throw new Error('remote directory verification root is not a directory');
300
195
  }
301
- return decodedPath;
302
- }
303
- export function parseRemoteDirectoryManifest(output) {
304
- const entries = [];
305
- const paths = new Set();
196
+ const entry = (name, kind, stats, sha256) => ({
197
+ path: name,
198
+ type: kind,
199
+ size: kind === 'file' ? stats.size : 0,
200
+ mode: formatFileMode(stats.mode),
201
+ owner: String(stats.uid),
202
+ sha256,
203
+ });
204
+ const entries = [entry('.', 'directory', root)];
205
+ let hashedBytes = 0;
306
206
  let skippedSymlinks = 0;
307
207
  let skippedUnsupported = 0;
308
208
  const unsupportedSamples = [];
309
209
  let limitReason;
310
- for (const line of output.split('\n')) {
311
- if (!line) {
312
- continue;
313
- }
314
- if (line.startsWith('__MCP_LIMIT__\t')) {
315
- const reason = line.slice('__MCP_LIMIT__\t'.length);
316
- if (reason === 'entries' || reason === 'file_bytes' || reason === 'total_bytes') {
317
- limitReason = reason;
318
- continue;
319
- }
320
- throw new Error('remote directory verification returned an unknown limit reason');
321
- }
322
- if (line.startsWith('__MCP_SKIPPED_SYMLINKS__\t')) {
323
- const count = Number(line.slice('__MCP_SKIPPED_SYMLINKS__\t'.length));
324
- if (!Number.isSafeInteger(count) || count < 0) {
325
- throw new Error('remote directory verification returned an invalid symlink count');
326
- }
327
- skippedSymlinks = count;
328
- continue;
210
+ const active = new Set();
211
+ const visit = async (directory, relative, depth) => {
212
+ if (depth > 64) {
213
+ limitReason = 'depth';
214
+ return;
329
215
  }
330
- if (line.startsWith('__MCP_SKIPPED_UNSUPPORTED__\t')) {
331
- const count = Number(line.slice('__MCP_SKIPPED_UNSUPPORTED__\t'.length));
332
- if (!Number.isSafeInteger(count) || count < 0) {
333
- throw new Error('remote directory verification returned an invalid unsupported entry count');
334
- }
335
- skippedUnsupported = count;
336
- continue;
216
+ const resolved = await new Promise((resolve, reject) => {
217
+ sftp.realpath(directory, (error, result) => (error ? reject(error) : resolve(result)));
218
+ });
219
+ if (active.has(resolved)) {
220
+ ++skippedSymlinks;
221
+ return;
337
222
  }
338
- if (line.startsWith('__MCP_UNSUPPORTED_SAMPLE__\t')) {
339
- const encodedPath = line.slice('__MCP_UNSUPPORTED_SAMPLE__\t'.length);
340
- const samplePath = decodeManifestPath(encodedPath);
341
- if (unsupportedSamples.length >= 10) {
342
- throw new Error('remote directory verification returned too many unsupported entry samples');
223
+ active.add(resolved);
224
+ const handle = await new Promise((resolve, reject) => {
225
+ sftp.opendir(directory, (error, result) => (error ? reject(error) : resolve(result)));
226
+ });
227
+ try {
228
+ while (!limitReason) {
229
+ const batch = await new Promise((resolve, reject) => {
230
+ sftp.readdir(handle, (error, list) => {
231
+ if (error && error.code === 1) {
232
+ resolve(null);
233
+ }
234
+ else if (error) {
235
+ reject(error);
236
+ }
237
+ else {
238
+ resolve(list);
239
+ }
240
+ });
241
+ });
242
+ if (!batch || batch.length === 0) {
243
+ break;
244
+ }
245
+ for (const item of batch) {
246
+ const name = item.filename;
247
+ if (!name || name.length > 1024 || name === '.' || name === '..' || /[\\/\0]/.test(name)) {
248
+ throw new Error('remote directory verification returned unsafe entry name');
249
+ }
250
+ const relativePath = relative ? `${relative}/${name}` : name;
251
+ if (matchesDirectoryExclude(relativePath, exclude)) {
252
+ continue;
253
+ }
254
+ if (entries.length >= maxEntries) {
255
+ limitReason = 'entries';
256
+ break;
257
+ }
258
+ const fullPath = join(directory, name);
259
+ const link = await lstat(fullPath);
260
+ if ((link.mode & 0o170000) === 0o120000 && !followSymlinks) {
261
+ ++skippedSymlinks;
262
+ continue;
263
+ }
264
+ const stats = (link.mode & 0o170000) === 0o120000 ? await stat(fullPath) : link;
265
+ if ((stats.mode & 0o170000) === 0o040000) {
266
+ entries.push(entry(relativePath, 'directory', stats));
267
+ await visit(fullPath, relativePath, depth + 1);
268
+ }
269
+ else if ((stats.mode & 0o170000) === 0o100000) {
270
+ if (!Number.isSafeInteger(stats.size) || stats.size < 0) {
271
+ throw new Error('remote manifest returned an invalid file size');
272
+ }
273
+ let sha256;
274
+ if (request.sha256) {
275
+ if (stats.size > maxFileBytes) {
276
+ limitReason = 'file_bytes';
277
+ break;
278
+ }
279
+ if (hashedBytes + stats.size > maxTotalBytes) {
280
+ limitReason = 'total_bytes';
281
+ break;
282
+ }
283
+ const digest = createHash('sha256');
284
+ let actualSize = 0;
285
+ for await (const chunk of sftp.createReadStream(fullPath)) {
286
+ actualSize += Buffer.byteLength(chunk);
287
+ if (actualSize > maxFileBytes) {
288
+ limitReason = 'file_bytes';
289
+ break;
290
+ }
291
+ if (hashedBytes + actualSize > maxTotalBytes) {
292
+ limitReason = 'total_bytes';
293
+ break;
294
+ }
295
+ digest.update(chunk);
296
+ }
297
+ if (limitReason) {
298
+ break;
299
+ }
300
+ if (actualSize !== stats.size) {
301
+ throw new Error('remote file changed during manifest hashing');
302
+ }
303
+ hashedBytes += actualSize;
304
+ sha256 = digest.digest('hex');
305
+ }
306
+ entries.push(entry(relativePath, 'file', stats, sha256));
307
+ }
308
+ else {
309
+ ++skippedUnsupported;
310
+ if (unsupportedSamples.length < 10) {
311
+ unsupportedSamples.push(relativePath);
312
+ }
313
+ }
314
+ if (limitReason) {
315
+ break;
316
+ }
317
+ }
343
318
  }
344
- unsupportedSamples.push(samplePath);
345
- continue;
346
- }
347
- const fields = line.split('\t');
348
- if (fields.length !== 6) {
349
- throw new Error('remote directory verification returned malformed manifest data');
350
319
  }
351
- const [encodedPath, type, sizeText, mode, owner, sha256] = fields;
352
- const size = Number(sizeText);
353
- const entryPath = decodeManifestPath(encodedPath);
354
- if (paths.has(entryPath) ||
355
- (type !== 'file' && type !== 'directory') ||
356
- !Number.isSafeInteger(size) ||
357
- size < 0 ||
358
- !/^0[0-7]{3}$/.test(mode) ||
359
- !/^\d+$/.test(owner) ||
360
- (sha256 !== undefined && sha256 !== '' && !/^[a-f0-9]{64}$/.test(sha256))) {
361
- throw new Error('remote directory verification returned malformed manifest data');
320
+ finally {
321
+ active.delete(resolved);
322
+ await new Promise((resolve, reject) => sftp.close(handle, (error) => (error ? reject(error) : resolve())));
362
323
  }
363
- paths.add(entryPath);
364
- entries.push({
365
- path: entryPath,
366
- type,
367
- size,
368
- mode,
369
- owner,
370
- sha256: sha256 || undefined,
371
- });
372
- }
324
+ };
325
+ await visit(rootPath, '', 0);
373
326
  return {
374
327
  entries,
375
328
  count: entries.length,
@@ -381,6 +334,18 @@ export function parseRemoteDirectoryManifest(output) {
381
334
  unsupportedSamples,
382
335
  };
383
336
  }
337
+ export function createEmptyDirectoryManifest() {
338
+ const entries = [];
339
+ return {
340
+ entries,
341
+ count: 0,
342
+ rootSha256: rootHash(entries),
343
+ limited: false,
344
+ skippedSymlinks: 0,
345
+ skippedUnsupported: 0,
346
+ unsupportedSamples: [],
347
+ };
348
+ }
384
349
  export function compareDirectoryManifests(expected, actual, request, deletionBaseline) {
385
350
  if (expected.limited || actual.limited || (request.deletions && deletionBaseline?.limited)) {
386
351
  return {
@@ -0,0 +1,6 @@
1
+ export declare const FILE_CREATE_MODE_MASK = 511;
2
+ export declare const FILE_MODE_MASK = 4095;
3
+ export declare function extractFileMode(mode: number): number;
4
+ export declare function formatFileMode(mode: number): string;
5
+ export declare function formatFilePermissions(mode: number): string;
6
+ export declare function parseExpectedFileMode(value: string): number | undefined;
@@ -0,0 +1,71 @@
1
+ const S_IFMT = 0o170000;
2
+ const S_IFDIR = 0o040000;
3
+ const S_IFREG = 0o100000;
4
+ const S_IFLNK = 0o120000;
5
+ export const FILE_CREATE_MODE_MASK = 0o777;
6
+ export const FILE_MODE_MASK = 0o7777;
7
+ export function extractFileMode(mode) {
8
+ return mode & FILE_MODE_MASK;
9
+ }
10
+ export function formatFileMode(mode) {
11
+ return extractFileMode(mode).toString(8).padStart(4, '0');
12
+ }
13
+ function executeCharacter(mode, executeBit, specialBit, special) {
14
+ if (mode & specialBit) {
15
+ return mode & executeBit ? special : special.toUpperCase();
16
+ }
17
+ return mode & executeBit ? 'x' : '-';
18
+ }
19
+ export function formatFilePermissions(mode) {
20
+ const fileType = mode & S_IFMT;
21
+ const type = fileType === S_IFDIR ? 'd' : fileType === S_IFLNK ? 'l' : fileType === S_IFREG ? '-' : '?';
22
+ const permissions = [
23
+ mode & 0o400 ? 'r' : '-',
24
+ mode & 0o200 ? 'w' : '-',
25
+ executeCharacter(mode, 0o100, 0o4000, 's'),
26
+ mode & 0o040 ? 'r' : '-',
27
+ mode & 0o020 ? 'w' : '-',
28
+ executeCharacter(mode, 0o010, 0o2000, 's'),
29
+ mode & 0o004 ? 'r' : '-',
30
+ mode & 0o002 ? 'w' : '-',
31
+ executeCharacter(mode, 0o001, 0o1000, 't'),
32
+ ];
33
+ return type + permissions.join('');
34
+ }
35
+ export function parseExpectedFileMode(value) {
36
+ const trimmed = value.trim();
37
+ if (/^[0-7]{3,4}$/.test(trimmed)) {
38
+ return Number.parseInt(trimmed, 8) & FILE_MODE_MASK;
39
+ }
40
+ const match = /^(?:[-dl?])?([r-][w-][xSs-][r-][w-][xSs-][r-][w-][xTt-])$/.exec(trimmed);
41
+ if (!match) {
42
+ return undefined;
43
+ }
44
+ const bits = match[1];
45
+ let mode = 0;
46
+ if (bits[0] === 'r')
47
+ mode |= 0o400;
48
+ if (bits[1] === 'w')
49
+ mode |= 0o200;
50
+ if (bits[2] === 'x' || bits[2] === 's')
51
+ mode |= 0o100;
52
+ if (bits[2] === 's' || bits[2] === 'S')
53
+ mode |= 0o4000;
54
+ if (bits[3] === 'r')
55
+ mode |= 0o040;
56
+ if (bits[4] === 'w')
57
+ mode |= 0o020;
58
+ if (bits[5] === 'x' || bits[5] === 's')
59
+ mode |= 0o010;
60
+ if (bits[5] === 's' || bits[5] === 'S')
61
+ mode |= 0o2000;
62
+ if (bits[6] === 'r')
63
+ mode |= 0o004;
64
+ if (bits[7] === 'w')
65
+ mode |= 0o002;
66
+ if (bits[8] === 'x' || bits[8] === 't')
67
+ mode |= 0o001;
68
+ if (bits[8] === 't' || bits[8] === 'T')
69
+ mode |= 0o1000;
70
+ return mode;
71
+ }