@synopackageland/cli 0.50.0 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ export const sddlIssueKinds = ['unknown-ace-type', 'unsupported-ace-type', 'unknown-sid-alias', 'invalid-sid', 'unknown-flag', 'duplicate-flag', 'unknown-rights', 'unsupported-object-guid', 'section', 'missing-section', 'malformed-ace', 'malformed-descriptor', 'bounds', 'native-output', 'private-readback'];
2
+ /** Diagnostic tokens are grammar fragments, never arbitrary input or paths. */
3
+ export function safeSddlToken(value) {
4
+ if (/^S-1-(?:\d+-)+\d+$/.test(value))
5
+ return value.replace(/^S-1-5-21-.+$/, 'S-1-5-21-*').replace(/^S-1-15-2-.+$/, 'S-1-15-2-*').slice(0, 80);
6
+ return /^(?:[A-Z]{1,32}|[OGDS]:|0x[0-9a-f]{1,16})$/i.test(value) ? value : '<invalid>';
7
+ }
8
+ export class SddlError extends Error {
9
+ detail;
10
+ constructor(tokenKind = 'malformed-descriptor', token = '', section) {
11
+ const safe = safeSddlToken(token);
12
+ super(`Unsupported or incomplete Windows security descriptor (${tokenKind}=${safe}${section ? ' section=' + section : ''}).`);
13
+ this.detail = { category: 'invalid-descriptor', tokenKind, token: safe, ...(section ? { section } : {}) };
14
+ }
15
+ }
16
+ function refuse(kind, token = '', section) { throw new SddlError(kind, token, section); }
17
+ const aliases = { SY: 'S-1-5-18', BA: 'S-1-5-32-544', BU: 'S-1-5-32-545', BG: 'S-1-5-32-546', WD: 'S-1-1-0', AU: 'S-1-5-11', AN: 'S-1-5-7', CO: 'S-1-3-0', CG: 'S-1-3-1', OW: 'S-1-3-4', LS: 'S-1-5-19', NS: 'S-1-5-20', IU: 'S-1-5-4', SU: 'S-1-5-6', AC: 'S-1-15-2-1', UN: 'S-1-16-0', LW: 'S-1-16-4096', ME: 'S-1-16-8192', MP: 'S-1-16-8448', HI: 'S-1-16-12288', SI: 'S-1-16-16384' };
18
+ // LA/LG depend on the machine domain. Preserve their identities in pure parsing;
19
+ // the native reader supplies numeric resolutions for owner checks and icacls.
20
+ Object.assign(aliases, { LA: 'LA', LG: 'LG', NU: 'S-1-5-2', PU: 'S-1-5-32-547', AO: 'S-1-5-32-548', SO: 'S-1-5-32-549', PO: 'S-1-5-32-550', BO: 'S-1-5-32-551', RE: 'S-1-5-32-552', RU: 'S-1-5-32-554', RD: 'S-1-5-32-555', NO: 'S-1-5-32-556', MU: 'S-1-5-32-558', LU: 'S-1-5-32-559', IS: 'S-1-5-32-568', CY: 'S-1-5-32-569', ER: 'S-1-5-32-573', CD: 'S-1-5-32-574', RA: 'S-1-5-32-575', ES: 'S-1-5-32-576', HA: 'S-1-5-32-578', AA: 'S-1-5-32-579', RM: 'S-1-5-32-580', PS: 'S-1-5-10', RC: 'S-1-5-12', ED: 'S-1-5-9', WR: 'S-1-5-33', AS: 'S-1-18-1', SS: 'S-1-18-2' });
21
+ const rights = { FA: 0x1f01ff, FR: 0x120089, FW: 0x120116, FX: 0x1200a0, GA: 0x10000000, GR: 0x80000000, GW: 0x40000000, GX: 0x20000000, RC: 0x20000, SD: 0x10000, WD: 0x40000, WO: 0x80000, CC: 1, DC: 2, LC: 4, SW: 8, RP: 16, WP: 32, DT: 64, LO: 128, CR: 256 };
22
+ export function sddlSid(value, section, localAliases = {}) {
23
+ if (/^S-1-(?:\d+-)+\d+$/.test(value))
24
+ return value;
25
+ if ((value === 'LA' || value === 'LG') && Object.hasOwn(localAliases, value))
26
+ return localAliases[value];
27
+ if (Object.hasOwn(aliases, value))
28
+ return aliases[value];
29
+ return refuse(/^[A-Z]{2}$/.test(value) ? 'unknown-sid-alias' : 'invalid-sid', value, section);
30
+ }
31
+ function tokens(value, known, section) {
32
+ const found = [];
33
+ while (value) {
34
+ const next = known.find(token => value.startsWith(token));
35
+ if (!next)
36
+ refuse('unknown-flag', value.slice(0, 2), section);
37
+ if (found.includes(next))
38
+ refuse('duplicate-flag', next, section);
39
+ found.push(next);
40
+ value = value.slice(next.length);
41
+ }
42
+ return found;
43
+ }
44
+ export function sddlRights(value, section = 'D:', mandatory = false) {
45
+ if (/^0x[0-9a-f]{1,8}$/i.test(value)) {
46
+ const mask = parseInt(value.slice(2), 16);
47
+ if (mandatory && (mask & ~7))
48
+ refuse('unknown-rights', value, section);
49
+ return mask;
50
+ }
51
+ if (/^0x/i.test(value) || value.length % 2)
52
+ refuse('unknown-rights', value, section);
53
+ const known = mandatory ? { NW: 1, NR: 2, NX: 4 } : rights;
54
+ let mask = 0;
55
+ for (let index = 0; index < value.length; index += 2) {
56
+ const part = value.slice(index, index + 2);
57
+ if (!(part in known))
58
+ refuse('unknown-rights', part, section);
59
+ mask |= known[part];
60
+ }
61
+ return mask >>> 0;
62
+ }
63
+ const conditional = ['XA', 'XD', 'ZA', 'ZD', 'XU', 'XL', 'ZU', 'ZL'];
64
+ function aceType(type, section) {
65
+ if (conditional.includes(type))
66
+ refuse('unsupported-ace-type', type, section);
67
+ if (!(section === 'D:' ? ['A', 'D', 'OA', 'OD'] : ['ML', 'AU', 'AL']).includes(type))
68
+ refuse(['A', 'D', 'OA', 'OD', 'ML', 'AU', 'AL', 'OU', 'OL', 'RA', 'SP', 'TL', 'FL'].includes(type) ? 'unsupported-ace-type' : 'unknown-ace-type', type, section);
69
+ }
70
+ /** Owner+DACL SDDL. SACL audit/mandatory labels never grant DACL access. */
71
+ export function parseWindowsSddl(input, currentUser, reparsePoint = false, localAliases = {}) {
72
+ if (!localAliases || typeof localAliases !== 'object' || Array.isArray(localAliases))
73
+ refuse('native-output');
74
+ for (const [alias, sid] of Object.entries(localAliases))
75
+ if (!['LA', 'LG'].includes(alias) || !new RegExp('^S-1-5-21-(?:[0-9]+-){3}' + (alias === 'LA' ? '500' : '501') + '$').test(sid))
76
+ refuse('native-output');
77
+ if (Buffer.isBuffer(input) && input.length % 2)
78
+ refuse('malformed-descriptor');
79
+ const text = (Buffer.isBuffer(input) ? input.toString('utf16le') : input).replace(/^\uFEFF/, '').trim();
80
+ if (!text || text.length > 1024 * 1024 || text.includes('\0'))
81
+ refuse('bounds');
82
+ const components = {};
83
+ let position = 0;
84
+ while (position < text.length) {
85
+ const key = text[position], section = (key + ':');
86
+ if (!'OGDS'.includes(key) || text[position + 1] !== ':' || key in components)
87
+ refuse('section', section);
88
+ const start = position + 2;
89
+ position = start;
90
+ let depth = 0;
91
+ for (; position < text.length; position++) {
92
+ const character = text[position];
93
+ if (character === '(') {
94
+ if (depth || !['D', 'S'].includes(key))
95
+ refuse('malformed-ace', '', section);
96
+ const end = text.indexOf(';', position);
97
+ if (end < 0 || end - position > 8)
98
+ refuse('malformed-ace', '', section);
99
+ aceType(text.slice(position + 1, end), section);
100
+ depth++;
101
+ }
102
+ else if (character === ')') {
103
+ if (--depth < 0)
104
+ refuse('malformed-ace', '', section);
105
+ }
106
+ if (!depth && 'OGDS'.includes(character) && text[position + 1] === ':')
107
+ break;
108
+ }
109
+ if (depth)
110
+ refuse('malformed-ace', '', section);
111
+ components[key] = text.slice(start, position);
112
+ }
113
+ if (!components.O)
114
+ refuse('missing-section', 'O:', 'O:');
115
+ const owner = sddlSid(components.O, 'O:', localAliases);
116
+ sddlSid(currentUser, 'O:');
117
+ if (components.G !== undefined)
118
+ sddlSid(components.G, 'G:', localAliases);
119
+ const rules = [];
120
+ let protectedDacl = false, nullDacl = components.D === undefined;
121
+ for (const section of ['D:', 'S:']) {
122
+ const value = components[section[0]];
123
+ if (value === undefined)
124
+ continue;
125
+ const first = value.indexOf('('), prefix = first < 0 ? value : value.slice(0, first);
126
+ const nullMarker = prefix.includes('NO_ACCESS_CONTROL');
127
+ const flags = tokens(prefix.replace('NO_ACCESS_CONTROL', ''), ['AI', 'AR', 'P'], section);
128
+ if (section === 'D:') {
129
+ nullDacl = nullMarker;
130
+ protectedDacl = flags.includes('P');
131
+ }
132
+ if (nullMarker) {
133
+ if (first >= 0)
134
+ refuse('malformed-ace', 'NO_ACCESS_CONTROL', section);
135
+ continue;
136
+ }
137
+ let rest = first < 0 ? '' : value.slice(first), count = 0;
138
+ while (rest) {
139
+ const end = rest.indexOf(')');
140
+ if (rest[0] !== '(' || end < 0 || count++ >= 4096)
141
+ refuse('malformed-ace', '', section);
142
+ const fields = rest.slice(1, end).split(';');
143
+ rest = rest.slice(end + 1);
144
+ if (fields.length !== 6)
145
+ refuse('malformed-ace', '', section);
146
+ const [type, flagText, access, objectGuid, inheritGuid, account] = fields;
147
+ aceType(type, section);
148
+ for (const guid of [objectGuid, inheritGuid])
149
+ if (guid && (!['OA', 'OD'].includes(type) || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(guid)))
150
+ refuse('unsupported-object-guid', '', section);
151
+ const aceFlags = tokens(flagText, section === 'S:' && type !== 'ML' ? ['ID', 'OI', 'CI', 'IO', 'NP', 'SA', 'FA'] : ['ID', 'OI', 'CI', 'IO', 'NP'], section);
152
+ const sid = sddlSid(account, section, localAliases), mask = sddlRights(access, section, type === 'ML');
153
+ if (type === 'ML' && !/^S-1-16-\d+$/.test(sid))
154
+ refuse('invalid-sid', sid, section);
155
+ if (section === 'S:')
156
+ continue; // Auditing/mandatory labels are not access grants.
157
+ // Treat object-scoped grants as grants on the entire object, conservatively.
158
+ rules.push({ sid, type: type === 'A' || type === 'OA' ? 'Allow' : 'Deny', rights: mask, inheritOnly: aceFlags.includes('IO'), inherited: aceFlags.includes('ID'), objectInherit: aceFlags.includes('OI'), containerInherit: aceFlags.includes('CI'), noPropagate: aceFlags.includes('NP') });
159
+ }
160
+ }
161
+ return { currentUser, owner, nullDacl, reparsePoint, rules, protected: protectedDacl, ...(Object.keys(localAliases).length ? { aliasSids: { ...localAliases } } : {}) };
162
+ }
@@ -0,0 +1,7 @@
1
+ import type { WindowsLocalAliases } from './windows-acl.js';
2
+ export declare function readWindowsDescriptor(path: string): {
3
+ sddl: string;
4
+ reparsePoint: boolean;
5
+ directory: boolean;
6
+ aliasSids?: WindowsLocalAliases;
7
+ };
@@ -0,0 +1,88 @@
1
+ // Isolated native ACL readback. No PowerShell, WMI or account-name parsing.
2
+ import koffi from 'koffi';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { readBounded, strictJson } from './json.js';
5
+ import { windowsSystemTool } from './windows-tools.js';
6
+ export function readWindowsDescriptor(path) {
7
+ if (process.platform !== 'win32')
8
+ throw new Error('Windows only');
9
+ const advapi = koffi.load(windowsSystemTool('advapi32.dll')), kernel = koffi.load(windowsSystemTool('kernel32.dll'));
10
+ const attributes = kernel.func('uint32_t __stdcall GetFileAttributesW(const char16_t *path)');
11
+ const lastError = kernel.func('uint32_t __stdcall GetLastError()');
12
+ const release = kernel.func('void * __stdcall LocalFree(void *memory)');
13
+ const read = advapi.func('uint32_t __stdcall GetNamedSecurityInfoW(const char16_t *name, int type, uint32_t info, void *owner, void *group, void *dacl, void *sacl, _Out_ void **descriptor)');
14
+ const convert = advapi.func('int __stdcall ConvertSecurityDescriptorToStringSecurityDescriptorW(void *descriptor, uint32_t revision, uint32_t info, _Out_ void **text, _Out_ uint32_t *length)');
15
+ const value = attributes(path);
16
+ if (value === 0xffffffff)
17
+ throw Object.assign(new Error('Native inspection failed'), { win32Code: lastError() });
18
+ if (value & 0x400)
19
+ throw new Error('Reparse point refused');
20
+ const descriptor = [null], text = [null], length = [0];
21
+ try {
22
+ const result = read(path, 1, 5, null, null, null, null, descriptor);
23
+ if (result) {
24
+ descriptor[0] = null;
25
+ throw Object.assign(new Error('Native inspection failed'), { win32Code: result });
26
+ }
27
+ if (!convert(descriptor[0], 1, 5, text, length)) {
28
+ text[0] = null;
29
+ throw Object.assign(new Error('Native conversion failed'), { win32Code: lastError() });
30
+ }
31
+ if (!length[0] || length[0] > 1024 * 1024 || !text[0])
32
+ throw new Error('Native descriptor bound exceeded');
33
+ // The API reports buffer capacity, not string length. Decode only inside that
34
+ // bound, then stop at NUL; unused buffer space must never reach the parser.
35
+ const buffer = koffi.decode.string16(text[0], length[0]), end = buffer.indexOf('\0');
36
+ if (end < 0)
37
+ throw new Error('Native descriptor is not terminated');
38
+ const sddl = buffer.slice(0, end), aliasSids = {};
39
+ const relative = [...new Set([...sddl.matchAll(/(?<=[:;])(LA|LG)(?=[OGDS]:|\)|$)/g)].map(match => match[1]))];
40
+ if (relative.length) {
41
+ const toSid = advapi.func('int __stdcall ConvertStringSidToSidW(const char16_t *alias, _Out_ void **sid)');
42
+ const toString = advapi.func('int __stdcall ConvertSidToStringSidW(void *sid, _Out_ void **text)');
43
+ for (const alias of relative) {
44
+ const binary = [null], string = [null];
45
+ try {
46
+ if (!toSid(alias, binary)) {
47
+ binary[0] = null;
48
+ throw Object.assign(new Error('Native SID conversion failed'), { win32Code: lastError() });
49
+ }
50
+ if (!toString(binary[0], string)) {
51
+ string[0] = null;
52
+ throw Object.assign(new Error('Native SID conversion failed'), { win32Code: lastError() });
53
+ }
54
+ // This API returns an OS-allocated NUL-terminated SID string.
55
+ const sid = koffi.decode.string16(string[0]);
56
+ if (!new RegExp('^S-1-5-21-(?:[0-9]+-){3}' + (alias === 'LA' ? '500' : '501') + '$').test(sid))
57
+ throw new Error('Invalid local SID');
58
+ aliasSids[alias] = sid;
59
+ }
60
+ finally {
61
+ if (string[0])
62
+ release(string[0]);
63
+ if (binary[0])
64
+ release(binary[0]);
65
+ }
66
+ }
67
+ }
68
+ return { sddl, reparsePoint: false, directory: !!(value & 0x10), ...(relative.length ? { aliasSids } : {}) };
69
+ }
70
+ finally {
71
+ if (text[0])
72
+ release(text[0]);
73
+ if (descriptor[0])
74
+ release(descriptor[0]);
75
+ }
76
+ }
77
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
78
+ try {
79
+ const value = strictJson(readBounded(0, 256 * 1024));
80
+ if (typeof value?.path !== 'string' || value.path.includes('\0'))
81
+ throw new Error('Invalid request');
82
+ process.stdout.write(JSON.stringify(readWindowsDescriptor(value.path)) + '\n');
83
+ }
84
+ catch (error) {
85
+ const code = error.win32Code;
86
+ process.stdout.write(JSON.stringify({ errorCode: Number.isInteger(code) && code >= 0 ? code : 0 }) + '\n');
87
+ }
88
+ }
@@ -0,0 +1,10 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import type { WindowsAclSnapshot } from './windows-acl.js';
3
+ export declare function parseWhoamiUser(text: string): string;
4
+ export declare function createWindowsSecurityTools(execute?: typeof execFileSync): {
5
+ inspect: (path: string) => WindowsAclSnapshot & {
6
+ directory: boolean;
7
+ };
8
+ privatize: (path: string) => WindowsAclSnapshot;
9
+ currentUser: () => string;
10
+ };
@@ -0,0 +1,95 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { parseWindowsSddl, SddlError } from './windows-sddl.js';
4
+ import { windowsSystemTool, WindowsToolFailure, windowsChildDiagnostic } from './windows-tools.js';
5
+ export function parseWhoamiUser(text) {
6
+ const cells = [];
7
+ let cell = '', quoted = false;
8
+ for (let index = 0; index < text.length; index++) {
9
+ const character = text[index];
10
+ if (character === '"') {
11
+ if (quoted && text[index + 1] === '"') {
12
+ cell += '"';
13
+ index++;
14
+ }
15
+ else
16
+ quoted = !quoted;
17
+ }
18
+ else if (character === ',' && !quoted) {
19
+ cells.push(cell);
20
+ cell = '';
21
+ }
22
+ else
23
+ cell += character;
24
+ }
25
+ cells.push(cell.trim());
26
+ if (quoted || cells.length !== 2 || !/^S-1-(?:\d+-)+\d+$/.test(cells[1]))
27
+ throw new SddlError('native-output');
28
+ return cells[1];
29
+ }
30
+ export function createWindowsSecurityTools(execute) {
31
+ let identity;
32
+ function run(file, args, input) {
33
+ try {
34
+ return (execute ?? execFileSync)(file, args, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, maxBuffer: 1024 * 1024, ...(input === undefined ? {} : { input }) });
35
+ }
36
+ catch (error) {
37
+ throw new WindowsToolFailure(windowsChildDiagnostic(error));
38
+ }
39
+ }
40
+ function currentUser() {
41
+ if (!identity) {
42
+ try {
43
+ identity = { sid: parseWhoamiUser(run(windowsSystemTool('whoami.exe'), ['/user', '/fo', 'csv', '/nh'])) };
44
+ }
45
+ catch (error) {
46
+ identity = { error: new WindowsToolFailure(windowsChildDiagnostic(error)) };
47
+ }
48
+ }
49
+ if ('error' in identity)
50
+ throw identity.error;
51
+ return identity.sid;
52
+ }
53
+ function inspect(path) {
54
+ const current = currentUser();
55
+ let result;
56
+ try {
57
+ result = JSON.parse(run(process.execPath, [fileURLToPath(new URL('./windows-security-helper.js', import.meta.url))], JSON.stringify({ path })));
58
+ }
59
+ catch (error) {
60
+ if (error instanceof WindowsToolFailure)
61
+ throw error;
62
+ throw new SddlError('native-output');
63
+ }
64
+ if (Number.isInteger(result?.errorCode))
65
+ throw new WindowsToolFailure({ category: result.errorCode === 5 ? 'access-denied' : 'native-error', win32Code: result.errorCode });
66
+ if (typeof result?.sddl !== 'string' || typeof result.reparsePoint !== 'boolean' || typeof result.directory !== 'boolean')
67
+ throw new SddlError('native-output');
68
+ const parsed = parseWindowsSddl(result.sddl, current, result.reparsePoint, result.aliasSids ?? {});
69
+ if (parsed.owner === 'LA' || parsed.owner === 'LG' || parsed.rules.some(rule => rule.sid === 'LA' || rule.sid === 'LG'))
70
+ throw new SddlError('native-output');
71
+ return { ...parsed, directory: result.directory };
72
+ }
73
+ function privatize(path) {
74
+ const before = inspect(path), sid = currentUser();
75
+ if (before.reparsePoint || ![sid, 'S-1-5-18', 'S-1-5-32-544', ...(before.aliasSids?.LA ? [before.aliasSids.LA] : [])].includes(before.owner))
76
+ throw new SddlError('private-readback');
77
+ const others = [...new Set(before.rules.map(rule => rule.sid).filter(value => value !== sid))];
78
+ if (others.length > 32)
79
+ throw new SddlError('private-readback');
80
+ const tool = windowsSystemTool('icacls.exe');
81
+ run(tool, [path, '/inheritance:r', '/grant:r', `*${sid}:${before.directory ? '(OI)(CI)' : ''}F`, '/Q', '/L']);
82
+ // /grant:r replaces only this user's grants; remove other explicit ACEs too.
83
+ if (others.length)
84
+ run(tool, [path, '/remove', ...others.map(value => '*' + value), '/Q', '/L']);
85
+ if (before.rules.some(rule => rule.sid === sid && rule.type === 'Deny'))
86
+ run(tool, [path, '/remove:d', '*' + sid, '/Q', '/L']);
87
+ if (before.owner !== sid)
88
+ run(tool, [path, '/setowner', '*' + sid, '/Q', '/L']);
89
+ const after = inspect(path);
90
+ if (after.owner !== sid || !after.protected || after.rules.some(rule => rule.type === 'Allow' && rule.sid !== sid && rule.rights !== 0))
91
+ throw new SddlError('private-readback');
92
+ return after;
93
+ }
94
+ return { inspect, privatize, currentUser };
95
+ }
@@ -0,0 +1,11 @@
1
+ export interface WindowsChildDiagnostic {
2
+ category: 'access-denied' | 'spawn-failed' | 'native-error' | 'other';
3
+ exitCode?: number;
4
+ win32Code?: number;
5
+ }
6
+ export declare function windowsSystemTool(name: 'whoami.exe' | 'icacls.exe' | 'advapi32.dll' | 'kernel32.dll', env?: NodeJS.ProcessEnv): string;
7
+ export declare class WindowsToolFailure extends Error {
8
+ detail: WindowsChildDiagnostic;
9
+ constructor(detail: WindowsChildDiagnostic);
10
+ }
11
+ export declare function windowsChildDiagnostic(error: unknown): WindowsChildDiagnostic;
@@ -0,0 +1,23 @@
1
+ import { win32 } from 'node:path';
2
+ export function windowsSystemTool(name, env = process.env) {
3
+ const get = (key) => Object.entries(env).find(([name]) => name.toLowerCase() === key.toLowerCase())?.[1];
4
+ const root = get('SystemRoot') ?? get('WINDIR') ?? 'C:\\Windows';
5
+ if (!win32.isAbsolute(root) || root.includes('\0'))
6
+ throw new Error('Invalid Windows system root');
7
+ return win32.join(root, 'System32', name);
8
+ }
9
+ export class WindowsToolFailure extends Error {
10
+ detail;
11
+ constructor(detail) {
12
+ super('Windows security inspection failed.');
13
+ this.detail = detail;
14
+ }
15
+ }
16
+ export function windowsChildDiagnostic(error) {
17
+ if (error instanceof WindowsToolFailure)
18
+ return error.detail;
19
+ const value = error;
20
+ const stderr = typeof value?.stderr === 'string' ? value.stderr : Buffer.isBuffer(value?.stderr) ? value.stderr.toString('utf8') : '';
21
+ const category = value?.code === 'ENOENT' ? 'spawn-failed' : /access.*denied|permissiondenied/i.test(stderr) ? 'access-denied' : 'other';
22
+ return { category, ...(Number.isInteger(value?.status) && Number(value.status) >= 0 ? { exitCode: Number(value.status) } : {}) };
23
+ }
@@ -1 +1 @@
1
- {"module":"github.com/synopackageland/syno-pkg-land-sdk","version":"development","local":true}
1
+ {"module":"github.com/synopackageland/syno-pkg-land-sdk","version":"0.52.0","local":false}
@@ -0,0 +1,6 @@
1
+ /** Extract an inventoried SPK archive into a private directory, preserving safe header modes. */
2
+ export declare function extractSpkArchive(options: {
3
+ file: string;
4
+ cwd: string;
5
+ filter?: (path: string) => boolean;
6
+ }): Promise<string[]>;
@@ -0,0 +1,39 @@
1
+ import { chmodSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import * as tar from "tar";
4
+ /** Extract an inventoried SPK archive into a private directory, preserving safe header modes. */
5
+ export async function extractSpkArchive(options) {
6
+ const modes = new Map();
7
+ const findings = [];
8
+ await tar.x({
9
+ ...options,
10
+ preserveOwner: false,
11
+ filter: (path, entry) => {
12
+ if (options.filter && !options.filter(path))
13
+ return false;
14
+ const mode = entry.mode ?? 0;
15
+ if (mode & 0o6000)
16
+ findings.push(`archive contains a setuid/setgid file: ${path}`);
17
+ if (mode & 0o002)
18
+ findings.push(`archive contains a world-writable file: ${path}`);
19
+ const relative = path.replace(/^\.\//, "").replace(/\/$/, "");
20
+ if (!relative || relative === ".")
21
+ return false; // Keep the private extraction root private.
22
+ if (path.startsWith("/") || /^[A-Za-z]:/.test(path) || relative.includes("\\") ||
23
+ relative.split("/").some(part => !part || part === "." || part === "..") ||
24
+ !("type" in entry) || !["File", "Directory"].includes(entry.type)) {
25
+ findings.push(`archive contains an unsafe path or type: ${path}`);
26
+ return false;
27
+ }
28
+ // Sanitize before tar creates anything; validation still reads the original headers.
29
+ entry.mode = mode & 0o777 & ~0o002;
30
+ modes.set(relative, entry.mode);
31
+ return true;
32
+ },
33
+ });
34
+ // chmod after all writes; restore children before potentially read-only parents.
35
+ for (const [path, mode] of [...modes].sort(([a], [b]) => b.split("/").length - a.split("/").length)) {
36
+ chmodSync(join(options.cwd, path), mode);
37
+ }
38
+ return findings;
39
+ }
@@ -293,6 +293,7 @@ export function copyDaemonPayload(manifest, arch, target, controller) {
293
293
  writeFileSync(join(target, "config.json"), daemonConfig(manifest), {
294
294
  mode: 0o644,
295
295
  });
296
+ chmodSync(join(target, "config.json"), 0o644);
296
297
  }
297
298
  function writeNodeLauncher(source, target, node) {
298
299
  if (source && existsSync(join(source, NODE_LAUNCHER.split("/")[0])))