/** 공유 산출물의 경로를 검증하고 기존 파일 보존 또는 원자 교체를 수행한다. */ const fs = require('fs'); const path = require('path'); const { randomUUID } = require('crypto'); function safeSegment(value) { if (typeof value !== 'string' || Buffer.byteLength(value) > 200 || !/^[\p{L}\p{N}_-][\p{L}\p{N}_.-]{0,159}$/u.test(value) || value.endsWith('.') || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)) throw new Error('Unsafe file name'); return value; } function directory(target) { let absolute = path.resolve(target); // macOS 기본 시스템 별칭은 정규 위치로 옮긴 뒤 검사한다. 사용자 하위 symlink는 허용하지 않는다. if (process.platform === 'darwin') for (const alias of ['/var', '/tmp', '/etc']) { if (absolute === alias || absolute.startsWith(alias + '/')) { if (fs.realpathSync(alias) === '/private' + alias) absolute = '/private' + absolute; } } const root = path.parse(absolute).root; let current = root; for (const part of absolute.slice(root.length).split(path.sep).filter(Boolean)) { current = path.join(current, part); try { fs.mkdirSync(current); } catch (error) { if (error.code !== 'EEXIST') throw error; } const stat = fs.lstatSync(current); if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Unsafe directory: symlink or non-directory'); } return absolute; } function readRegular(file) { file = path.join(directory(path.dirname(file)), path.basename(file)); const stat = fs.lstatSync(file); if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Unsafe destination: expected a regular file'); const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); try { if (!fs.fstatSync(fd).isFile()) throw new Error('Unsafe destination'); return fs.readFileSync(fd); } finally { fs.closeSync(fd); } } function writeProtected(root, parts, content, { replace = false, mode = 0o600, allowHidden = false } = {}) { if (!Array.isArray(parts) || !parts.length) throw new Error('Destination components are required'); parts.forEach((part, index) => safeSegment(allowHidden && index === parts.length - 1 && typeof part === 'string' && part.startsWith('.') ? part.slice(1) : part)); const parent = directory(path.join(root, ...parts.slice(0, -1))); const file = path.join(parent, parts.at(-1)); const data = Buffer.from(content); try { const current = readRegular(file); if (current.equals(data)) return { file, created: false }; if (!replace) throw new Error('Existing file differs; preserving local content'); } catch (error) { if (error.code !== 'ENOENT') throw error; } const temporary = path.join(parent, '.bada-' + randomUUID() + '.tmp'); try { fs.writeFileSync(temporary, data, { flag: 'wx', mode }); fs.chmodSync(temporary, mode); directory(parent); if (replace) { try { readRegular(file); } catch (error) { if (error.code !== 'ENOENT') throw error; } fs.renameSync(temporary, file); } else { // hard link 생성은 목적지가 이미 생긴 경우 EEXIST로 실패하며 기존 파일을 교체하지 않는다. try { fs.linkSync(temporary, file); } catch (error) { if (error.code !== 'EEXIST' || !readRegular(file).equals(data)) throw error; } } return { file, created: true }; } finally { try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; } } } module.exports = { safeSegment, directory, readRegular, writeProtected };