@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.
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import * as tar from "tar";
5
+ import { extractSpkArchive } from "../spk/extract.js";
6
6
  const INSTALL_UIFILE = "install_uifile", UPGRADE_UIFILE = "upgrade_uifile", UNINSTALL_UIFILE = "uninstall_uifile";
7
7
  /** Legacy project detection supplies a migration error, never a second builder. */
8
8
  export async function buildSpk(_options) {
@@ -39,12 +39,12 @@ export async function digestSpkPayload(spkPath) {
39
39
  }
40
40
  export async function extractSpk(spkPath, targetDir) {
41
41
  mkdirSync(targetDir, { recursive: true });
42
- await tar.x({ file: spkPath, cwd: targetDir });
42
+ await extractSpkArchive({ file: spkPath, cwd: targetDir });
43
43
  const tgz = join(targetDir, "package.tgz");
44
44
  if (existsSync(tgz)) {
45
45
  const packageDir = join(targetDir, "package");
46
46
  mkdirSync(packageDir, { recursive: true });
47
- await tar.x({ file: tgz, cwd: packageDir });
47
+ await extractSpkArchive({ file: tgz, cwd: packageDir });
48
48
  }
49
49
  }
50
50
  export function readInfoPackage(spkDir) {
@@ -1,4 +1,4 @@
1
- import { lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
1
+ import { chmodSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import * as tar from "tar";
4
4
  import { allowedSecretFileWarnings, readAllowedSecretFiles, secretFile } from "../secret-files.js";
@@ -56,4 +56,6 @@ export async function createReproducibleTar(sourceDir, outputPath, options = {})
56
56
  portable: true,
57
57
  mtime: FIXED_MTIME,
58
58
  }, entries);
59
+ // package.tgz is itself an entry in the outer SPK; its mode must be stable too.
60
+ chmodSync(outputPath, 0o644);
59
61
  }
@@ -2,6 +2,8 @@ import type { CtlClient, DiscoverOptions } from './service.js';
2
2
  export declare function listAiTools(client: CtlClient, appName: string, options?: DiscoverOptions): Promise<{
3
3
  auth?: {
4
4
  state: import("./native-store.js").NativeStoreState;
5
+ reason?: string;
6
+ detail?: import("./windows-acl.js").WindowsAclDiagnostic;
5
7
  scheme: "header" | "greader-client-login";
6
8
  credentialUrl: string;
7
9
  instructions: string;
package/dist/ctl/cli.js CHANGED
@@ -13,18 +13,32 @@ import { publicOperation } from './redaction.js';
13
13
  import { runExternal } from './external.js';
14
14
  import { authCommand } from './native-auth-command.js';
15
15
  import { createNativeTransfer } from './native-transfers.js';
16
+ import { windowsPrompt } from './windows-prompt.js';
17
+ import { ctlPhase } from './diagnostics.js';
16
18
  const USAGE = 'synopkgland host add|list|show|login|logout|remove|revoke|default|trust; ctl generate [--check]; ctl import-openapi <file|https-url>; ctl auth --app <package> [--host profile] [--reset] [--secret-stdin] [--store keychain|encrypted-file]; ctl tools <app>; ctl tool <app> <method> --input <file|->; ctl list [--host a,b|--all-hosts] [--app pkg] [--refresh]; ctl <alias|package> <command...> [typed flags|--input file|-] [--dry-run] [--yes]; NAS HTTPS accepts any certificate by default; --strict-tls or --ca <file> opts into verification';
17
19
  async function prompt(message, secret = false) {
20
+ if (process.platform === 'win32') {
21
+ ctlPhase('prompt.begin', { secret });
22
+ ctlPhase('prompt.stdin', { secret });
23
+ const input = process.stdin;
24
+ ctlPhase('prompt.stderr', { secret });
25
+ return windowsPrompt(message, secret, input, process.stderr);
26
+ }
27
+ ctlPhase('prompt.begin', { secret, stdinTTY: !!process.stdin.isTTY, stdoutTTY: !!process.stdout.isTTY, stderrTTY: !!process.stderr.isTTY });
18
28
  if (!process.stdin.isTTY)
19
29
  throw new CtlError('CTL_INTERACTION_REQUIRED', 'Interactive input required.', 'Use --username and --password-stdin for host authentication.', 2);
30
+ ctlPhase('prompt.write', { secret });
20
31
  process.stderr.write(message);
32
+ ctlPhase('prompt.readline-create', { secret });
21
33
  const muted = new Writable({ write(chunk, _encoding, done) { if (!secret)
22
34
  process.stderr.write(chunk); done(); } });
23
35
  const rl = createInterface({ input: process.stdin, output: muted, terminal: true });
36
+ ctlPhase('prompt.readline-ready', { secret });
24
37
  try {
25
38
  return await rl.question('');
26
39
  }
27
40
  finally {
41
+ ctlPhase('prompt.done', { secret });
28
42
  rl.close();
29
43
  if (secret)
30
44
  process.stderr.write('\n');
@@ -0,0 +1,16 @@
1
+ import type { SddlIssue, SddlSection } from './windows-sddl.js';
2
+ export type CtlPhase = 'auth.guidance' | 'auth.browser-confirm' | 'auth.browser-open' | 'auth.credential-input' | 'prompt.begin' | 'prompt.stdin' | 'prompt.stderr' | 'prompt.raw-mode' | 'prompt.raw-ready' | 'prompt.write' | 'prompt.flushed' | 'prompt.wait-input' | 'prompt.done' | 'prompt.readline-create' | 'prompt.readline-ready' | 'acl.start' | 'acl.done' | 'acl.failed';
3
+ /** Opt-in private diagnostic channel. Never include prompt text, input, paths or unmasked account SIDs. */
4
+ export declare function ctlPhase(phase: CtlPhase, flags?: {
5
+ secret?: boolean;
6
+ stdinTTY?: boolean;
7
+ stdoutTTY?: boolean;
8
+ stderrTTY?: boolean;
9
+ category?: string;
10
+ exitCode?: number;
11
+ elapsedMs?: number;
12
+ win32Code?: number;
13
+ tokenKind?: SddlIssue;
14
+ token?: string;
15
+ section?: SddlSection;
16
+ }): void;
@@ -0,0 +1,11 @@
1
+ import { appendFileSync } from 'node:fs';
2
+ /** Opt-in private diagnostic channel. Never include prompt text, input, paths or unmasked account SIDs. */
3
+ export function ctlPhase(phase, flags = {}) {
4
+ const file = process.env.SYNOPKGLAND_CTL_DIAGNOSTICS_FILE;
5
+ if (!file)
6
+ return;
7
+ try {
8
+ appendFileSync(file, JSON.stringify({ phase, pid: process.pid, ...flags }) + '\n', { mode: 0o600 });
9
+ }
10
+ catch { /* Diagnostics must not alter authentication behavior. */ }
11
+ }
@@ -1,5 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { CtlError } from './errors.js';
3
+ import { ctlPhase } from './diagnostics.js';
3
4
  import { readBounded, strictJson } from './json.js';
4
5
  import { validateNativeToken } from './native-store.js';
5
6
  export async function openNativeCredentialPage(url) {
@@ -42,9 +43,12 @@ export async function authCommand(client, args, appName, io) {
42
43
  store ??= await client.nativeStoreKind(app) ?? 'keychain';
43
44
  if (store === 'encrypted-file' && !io.tty)
44
45
  throw new CtlError('CTL_NATIVE_VAULT_LOCKED', 'Encrypted-file enrollment requires an interactive passphrase.', 'Use an unlocked OS keychain for automation.', 2);
46
+ ctlPhase('auth.guidance');
45
47
  io.err('Credential location: ' + guide.credentialUrl);
46
48
  io.err(guide.instructions);
49
+ ctlPhase('auth.browser-confirm');
47
50
  if (io.tty && !stdin && /^y(es)?$/i.test(await io.ask('Open the credential page in your browser? [y/N] '))) {
51
+ ctlPhase('auth.browser-open');
48
52
  try {
49
53
  await (io.openBrowser ?? openNativeCredentialPage)(guide.credentialUrl);
50
54
  }
@@ -52,6 +56,7 @@ export async function authCommand(client, args, appName, io) {
52
56
  io.err('Browser opener unavailable; open the displayed URL manually.');
53
57
  }
54
58
  }
59
+ ctlPhase('auth.credential-input');
55
60
  let input;
56
61
  if (stdin) {
57
62
  let raw;
@@ -1,5 +1,6 @@
1
1
  import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
2
2
  import { basename, dirname, join, parse, resolve, sep } from 'node:path';
3
+ import { windowsAcl } from './windows-acl.js';
3
4
  function owner(stat) { return stat.uid === 0 || stat.uid === process.getuid?.(); }
4
5
  function safeDirectory(stat) {
5
6
  // Sticky public directories protect entries from other users (the usual tmp
@@ -25,8 +26,18 @@ export function trustedAncestors(path) {
25
26
  existing = dirname(existing);
26
27
  }
27
28
  }
28
- if (process.platform === 'win32')
29
- return join(realpathSync(existing), ...missing);
29
+ if (process.platform === 'win32') {
30
+ const canonical = realpathSync(existing);
31
+ let ancestor = parse(canonical).root;
32
+ windowsAcl(ancestor, false, 'ancestor');
33
+ for (const segment of canonical.slice(ancestor.length).split(sep).filter(Boolean)) {
34
+ ancestor = join(ancestor, segment);
35
+ if (!lstatSync(ancestor).isDirectory())
36
+ throw unsafe();
37
+ windowsAcl(ancestor, false, 'ancestor');
38
+ }
39
+ return join(canonical, ...missing);
40
+ }
30
41
  let current = parse(existing).root, pending = existing.slice(current.length).split(sep).filter(Boolean), links = 0;
31
42
  if (!safeDirectory(lstatSync(current)))
32
43
  throw unsafe();
@@ -1,3 +1,4 @@
1
+ import { type WindowsAclDiagnostic } from './windows-acl.js';
1
2
  import type { Host } from '../nas/store.js';
2
3
  import type { NativeHttp, NativeCredential } from './native-types.js';
3
4
  export type NativeStoreState = 'missing' | 'stored' | 'locked' | 'invalid' | 'unavailable';
@@ -51,6 +52,11 @@ export declare class NativeCredentialStore {
51
52
  private encrypt;
52
53
  kind(key: string): Promise<NativeStoreKind | undefined>;
53
54
  state(key: string): Promise<NativeStoreState>;
55
+ status(key: string): Promise<{
56
+ state: NativeStoreState;
57
+ reason?: string;
58
+ detail?: WindowsAclDiagnostic;
59
+ }>;
54
60
  get(key: string): Promise<NativeCredential | null>;
55
61
  set(key: string, host: string, value: NativeCredential, store?: NativeStoreKind): Promise<void>;
56
62
  invalid(key: string): Promise<void>;
@@ -2,7 +2,7 @@ import { createHash, randomBytes, scryptSync, createCipheriv, createDecipheriv }
2
2
  import { mkdirSync, lstatSync, openSync, closeSync, fstatSync, readFileSync, writeFileSync, renameSync, rmSync, fsyncSync, constants } from 'node:fs';
3
3
  import { basename, dirname, join, resolve, parse, sep } from 'node:path';
4
4
  import { trustedAncestors } from './native-paths.js';
5
- import { execFileSync } from 'node:child_process';
5
+ import { windowsAcl, WindowsAclError } from './windows-acl.js';
6
6
  import { canonicalize } from 'json-canonicalize';
7
7
  import { CtlError } from './errors.js';
8
8
  import { strictJson } from './json.js';
@@ -57,28 +57,18 @@ export class NativeKeychain {
57
57
  }
58
58
  function keyName(key) { if (!/^[a-f0-9]{64}$/.test(key))
59
59
  throw fail(); return key; }
60
- function privatePath(path, directory) {
60
+ function privatePath(path, directory, policy = 'private') {
61
61
  const stat = lstatSync(path);
62
62
  if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
63
63
  throw fail();
64
64
  if (process.platform !== 'win32' && ((directory ? (stat.mode & 0o777) !== 0o700 : (stat.mode & 0o077) !== 0) || stat.uid !== process.getuid?.() || !directory && stat.nlink !== 1))
65
65
  throw fail();
66
66
  if (process.platform === 'win32')
67
- windowsAcl(path, false);
68
- }
69
- function windowsAcl(path, create) {
70
- // Path is data in the child environment, never PowerShell source or command arguments.
71
- const script = `$ErrorActionPreference='Stop'; $p=$env:SYNOPKGLAND_NATIVE_ACL_PATH; $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $acl=Get-Acl -LiteralPath $p; ${create ? `$acl.SetAccessRuleProtection($true,$false); foreach($r in @($acl.Access)) { [void]$acl.RemoveAccessRuleSpecific($r) }; $acl.SetOwner($sid); $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow')); Set-Acl -LiteralPath $p -AclObject $acl; $acl=Get-Acl -LiteralPath $p;` : ''} if($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value -or !$acl.AreAccessRulesProtected){ exit 1 }; foreach($r in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) { if($r.AccessControlType -eq 'Allow' -and $r.IdentityReference.Value -ne $sid.Value) { exit 1 } };`;
72
- try {
73
- execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { stdio: 'ignore', windowsHide: true, env: { ...process.env, SYNOPKGLAND_NATIVE_ACL_PATH: path } });
74
- }
75
- catch {
76
- throw fail();
77
- }
67
+ windowsAcl(path, false, policy);
78
68
  }
79
69
  function secureWindows(path) { if (process.platform === 'win32')
80
70
  windowsAcl(path, true); }
81
- function directory(root) {
71
+ function directory(root, policy = 'private') {
82
72
  const absolute = resolve(root);
83
73
  let current = parse(absolute).root;
84
74
  for (const segment of absolute.slice(current.length).split(sep).filter(Boolean)) {
@@ -94,7 +84,7 @@ function directory(root) {
94
84
  secureWindows(current);
95
85
  }
96
86
  }
97
- privatePath(absolute, true);
87
+ privatePath(absolute, true, policy);
98
88
  }
99
89
  function readPrivate(file) {
100
90
  let fd;
@@ -109,6 +99,8 @@ function readPrivate(file) {
109
99
  catch (error) {
110
100
  if (error.code === 'ENOENT')
111
101
  return null;
102
+ if (error instanceof WindowsAclError)
103
+ throw error;
112
104
  throw fail();
113
105
  }
114
106
  finally {
@@ -152,10 +144,12 @@ export class NativeCredentialStore {
152
144
  return this.resolvedRoot;
153
145
  }
154
146
  prepare() { try {
155
- directory(this.stateRoot);
147
+ directory(this.stateRoot, 'state');
156
148
  directory(this.dir);
157
149
  }
158
- catch {
150
+ catch (error) {
151
+ if (error instanceof WindowsAclError)
152
+ throw error;
159
153
  throw fail();
160
154
  } }
161
155
  constructor(root, keychain = new NativeKeychain(), unlock) {
@@ -254,21 +248,21 @@ export class NativeCredentialStore {
254
248
  }
255
249
  }
256
250
  async kind(key) { return this.index().records[keyName(key)]?.store; }
257
- async state(key) {
251
+ async state(key) { return (await this.status(key)).state; }
252
+ async status(key) {
258
253
  try {
259
254
  const index = this.index(), record = index.records[keyName(key)];
260
255
  if (!record)
261
- return 'missing';
256
+ return { state: 'missing' };
262
257
  if (record.invalid)
263
- return 'invalid';
258
+ return { state: 'invalid' };
264
259
  if (record.store === 'encrypted-file')
265
- return readPrivate(this.vaultFile(key)) ? 'locked' : 'unavailable';
266
- // Keyring has no portable noninteractive status API. An index hit means
267
- // stored, not unlocked or valid; list/help must never prompt or read a secret.
268
- return 'stored';
260
+ return readPrivate(this.vaultFile(key)) ? { state: 'locked' } : { state: 'unavailable', reason: 'missing-vault' };
261
+ // An index hit does not probe the keyring, prompt, or read any secret.
262
+ return { state: 'stored' };
269
263
  }
270
- catch {
271
- return 'unavailable';
264
+ catch (error) {
265
+ return { state: 'unavailable', reason: error instanceof WindowsAclError ? 'windows-acl-' + error.reason : 'unsafe-or-unavailable-storage', ...(error instanceof WindowsAclError && error.detail ? { detail: error.detail } : {}) };
272
266
  }
273
267
  }
274
268
  async get(key) {
@@ -50,6 +50,8 @@ export declare class CtlClient {
50
50
  nativeStoreKind(app: Descriptor): Promise<NativeStoreKind | undefined>;
51
51
  nativeState(app: Descriptor): Promise<{
52
52
  state: import("./native-store.js").NativeStoreState;
53
+ reason?: string;
54
+ detail?: import("./windows-acl.js").WindowsAclDiagnostic;
53
55
  scheme: "header" | "greader-client-login";
54
56
  credentialUrl: string;
55
57
  instructions: string;
@@ -44,7 +44,7 @@ export class CtlClient {
44
44
  }
45
45
  nativeGuidance(app) { const http = app.payload.execution; return { scheme: http.auth.type, credentialUrl: this.host.origin + http.basePath + http.auth.credentialPage, instructions: http.auth.instructions, command: `synopkgland ctl auth --host ${this.host.name} --app ${app.payload.package.id}` }; }
46
46
  async nativeStoreKind(app) { return this.store.native.kind(nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 })); }
47
- async nativeState(app) { return { ...this.nativeGuidance(app), state: await this.store.native.state(nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 })) }; }
47
+ async nativeState(app) { return { ...this.nativeGuidance(app), ...await this.store.native.status(nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 })) }; }
48
48
  nativeRequired(app) {
49
49
  const guide = this.nativeGuidance(app);
50
50
  return new CtlError('CTL_NATIVE_AUTH_REQUIRED', 'Native App credential is missing. Ask the user to run ctl auth in their own terminal; never request a token in chat.', `${guide.command}; credential location: ${guide.credentialUrl}; ${guide.instructions}`, 2);
@@ -0,0 +1,39 @@
1
+ import { CtlError } from './errors.js';
2
+ import { type WindowsChildDiagnostic } from './windows-tools.js';
3
+ import { type SddlDiagnostic } from './windows-sddl.js';
4
+ export type WindowsAclPolicy = 'ancestor' | 'state' | 'private';
5
+ export type WindowsAclDiagnostic = WindowsChildDiagnostic | SddlDiagnostic;
6
+ export type WindowsLocalAliases = Partial<Record<'LA' | 'LG', string>>;
7
+ export declare const WINDOWS_TRUSTED_INSTALLER = "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
8
+ export interface WindowsAclSnapshot {
9
+ currentUser: string;
10
+ owner: string;
11
+ nullDacl: boolean;
12
+ reparsePoint: boolean;
13
+ protected?: boolean;
14
+ aliasSids?: WindowsLocalAliases;
15
+ rules: {
16
+ sid: string;
17
+ type: 'Allow' | 'Deny';
18
+ rights: number;
19
+ inheritOnly: boolean;
20
+ inherited?: boolean;
21
+ objectInherit?: boolean;
22
+ containerInherit?: boolean;
23
+ noPropagate?: boolean;
24
+ }[];
25
+ }
26
+ export declare class WindowsAclError extends CtlError {
27
+ reason: string;
28
+ detail?: WindowsAclDiagnostic | undefined;
29
+ constructor(reason: string, detail?: WindowsAclDiagnostic | undefined);
30
+ }
31
+ /** Evaluate Allow ACEs conservatively; Deny entries never excuse an unsafe grant.
32
+ * State may be readable by others; native secrets must stay private. Inheritance
33
+ * alone says nothing about safety: validate the actual ACL on every access. */
34
+ export declare function assertWindowsAcl(value: unknown, policy: WindowsAclPolicy): void;
35
+ /** Read full owner+DACL metadata, never infer owner from icacls /save DACL output. */
36
+ export declare const windowsAclSnapshot: (path: string) => WindowsAclSnapshot & {
37
+ directory: boolean;
38
+ };
39
+ export declare function windowsAcl(path: string, create?: boolean, policy?: WindowsAclPolicy): void;
@@ -0,0 +1,80 @@
1
+ import { CtlError } from './errors.js';
2
+ import { ctlPhase } from './diagnostics.js';
3
+ import { windowsChildDiagnostic } from './windows-tools.js';
4
+ import { createWindowsSecurityTools } from './windows-security.js';
5
+ import { SddlError } from './windows-sddl.js';
6
+ export const WINDOWS_TRUSTED_INSTALLER = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464';
7
+ const trusted = (sid, acl, policy) => [acl.currentUser, 'S-1-5-18', 'S-1-5-32-544', 'LA', ...(Object.hasOwn(acl.aliasSids ?? {}, 'LA') ? [acl.aliasSids.LA] : []), ...(policy === 'ancestor' ? [WINDOWS_TRUSTED_INSTALLER] : [])].includes(sid);
8
+ // Include delete/replacement and security-descriptor changes, not only WriteData.
9
+ const WRITE = 0x40000000 | 0x10000000 | 0x000d0156;
10
+ export class WindowsAclError extends CtlError {
11
+ reason;
12
+ detail;
13
+ constructor(reason, detail) {
14
+ super('CTL_NATIVE_STORE_UNAVAILABLE', `Native credential storage ACL refused (${reason})${detail ? ': ' + detail.category + ('tokenKind' in detail ? ' ' + detail.tokenKind + '=' + detail.token + (detail.section ? ' section=' + detail.section : '') : detail.exitCode === undefined ? '' : ' exit ' + detail.exitCode) : ''}.`, 'Use a local state directory owned by your account, Administrators or SYSTEM, without other users having write access.', 2);
15
+ this.reason = reason;
16
+ this.detail = detail;
17
+ }
18
+ }
19
+ const fail = (reason, detail) => new WindowsAclError(reason, detail);
20
+ /** Evaluate Allow ACEs conservatively; Deny entries never excuse an unsafe grant.
21
+ * State may be readable by others; native secrets must stay private. Inheritance
22
+ * alone says nothing about safety: validate the actual ACL on every access. */
23
+ export function assertWindowsAcl(value, policy) {
24
+ const acl = value;
25
+ const sid = (value) => typeof value === 'string' && /^S-\d+(?:-\d+)+$/.test(value);
26
+ const principal = (value) => sid(value) || value === 'LA' || value === 'LG';
27
+ if (!acl || !sid(acl.currentUser) || !principal(acl.owner) || typeof acl.nullDacl !== 'boolean' || typeof acl.reparsePoint !== 'boolean' || !Array.isArray(acl.rules))
28
+ throw fail('invalid-descriptor');
29
+ if (acl.aliasSids !== undefined && (!acl.aliasSids || typeof acl.aliasSids !== 'object' || Array.isArray(acl.aliasSids)))
30
+ throw fail('invalid-descriptor');
31
+ for (const [alias, value] of Object.entries(acl.aliasSids ?? {}))
32
+ if (!['LA', 'LG'].includes(alias) || !new RegExp('^S-1-5-21-(?:[0-9]+-){3}' + (alias === 'LA' ? '500' : '501') + '$').test(value))
33
+ throw fail('invalid-descriptor');
34
+ if (acl.nullDacl)
35
+ throw fail('null-dacl');
36
+ if (acl.reparsePoint)
37
+ throw fail('reparse-point');
38
+ if (!trusted(acl.owner, acl, policy))
39
+ throw fail('untrusted-owner');
40
+ for (const rule of acl.rules) {
41
+ if (!rule || !principal(rule.sid) || !['Allow', 'Deny'].includes(rule.type) || !Number.isInteger(rule.rights) || rule.rights < -0x80000000 || rule.rights > 0xffffffff || typeof rule.inheritOnly !== 'boolean')
42
+ throw fail('invalid-rule');
43
+ if (rule.type !== 'Allow')
44
+ continue;
45
+ // IO does not grant access to this ancestor. Every following directory is
46
+ // checked independently, so any effective inherited grant is checked there.
47
+ if (policy === 'ancestor' && rule.inheritOnly)
48
+ continue;
49
+ // OWNER RIGHTS denotes the already-validated owner. CREATOR OWNER only applies to a future child owned by its creator, never
50
+ // as a wildcard grant on the directory being inspected.
51
+ if (trusted(rule.sid, acl, policy) || rule.sid === 'S-1-3-4' || rule.sid === 'S-1-3-0' && rule.inheritOnly)
52
+ continue;
53
+ // FILE_ADD_SUBDIRECTORY on an ancestor creates siblings; it cannot modify or
54
+ // replace an existing protected child. Keep it forbidden on state/private.
55
+ if ((rule.rights & (policy === 'ancestor' ? WRITE & ~4 : WRITE)) !== 0)
56
+ throw fail('other-user-write');
57
+ if ((rule.rights & ~(0x001f01ff | 0xf0000000)) !== 0)
58
+ throw fail('unsupported-rights');
59
+ if (policy === 'private' && rule.rights !== 0)
60
+ throw fail('other-user-access');
61
+ }
62
+ }
63
+ const tools = createWindowsSecurityTools();
64
+ /** Read full owner+DACL metadata, never infer owner from icacls /save DACL output. */
65
+ export const windowsAclSnapshot = (path) => tools.inspect(path);
66
+ export function windowsAcl(path, create = false, policy = 'private') {
67
+ const started = performance.now();
68
+ ctlPhase('acl.start');
69
+ const elapsed = () => Math.max(0, Math.round(performance.now() - started));
70
+ try {
71
+ const snapshot = create ? tools.privatize(path) : tools.inspect(path);
72
+ assertWindowsAcl(snapshot, policy);
73
+ ctlPhase('acl.done', { elapsedMs: elapsed() });
74
+ }
75
+ catch (error) {
76
+ const failure = error instanceof WindowsAclError ? error : error instanceof SddlError ? fail('invalid-descriptor', error.detail) : fail('inspection-failed', windowsChildDiagnostic(error));
77
+ ctlPhase('acl.failed', { ...failure.detail, elapsedMs: elapsed() });
78
+ throw failure;
79
+ }
80
+ }
@@ -0,0 +1,5 @@
1
+ /** Explicit raw input avoids a synthetic readline output stream on ConPTY.
2
+ * Disable echo before publishing the prompt, flush its write, then accept input. */
3
+ export declare function windowsPrompt(message: string, secret?: boolean, input?: NodeJS.ReadStream & {
4
+ fd: 0;
5
+ }, output?: NodeJS.WritableStream): Promise<string>;
@@ -0,0 +1,119 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { CtlError } from './errors.js';
3
+ import { ctlPhase } from './diagnostics.js';
4
+ const refused = () => new CtlError('CTL_INTERACTION_REQUIRED', 'Interactive terminal input failed or was cancelled.', 'Run the command in your own terminal.', 2);
5
+ /** Explicit raw input avoids a synthetic readline output stream on ConPTY.
6
+ * Disable echo before publishing the prompt, flush its write, then accept input. */
7
+ export function windowsPrompt(message, secret = false, input = process.stdin, output = process.stderr) {
8
+ ctlPhase('prompt.begin', { secret, stdinTTY: !!input.isTTY, stdoutTTY: !!process.stdout.isTTY, stderrTTY: !!process.stderr.isTTY });
9
+ if (!input.isTTY || typeof input.setRawMode !== 'function')
10
+ return Promise.reject(refused());
11
+ return new Promise((resolve, reject) => {
12
+ const priorRaw = !!input.isRaw, priorFlow = input.readableFlowing === true, decoder = new StringDecoder('utf8');
13
+ let answer = '', escape = '', done = false;
14
+ const cleanup = () => {
15
+ input.pause();
16
+ input.off('data', data);
17
+ input.off('end', closed);
18
+ input.off('close', closed);
19
+ input.off('error', closed);
20
+ setImmediate(() => output.off('error', closed));
21
+ try {
22
+ input.setRawMode(priorRaw);
23
+ }
24
+ catch { }
25
+ if (priorFlow)
26
+ input.resume();
27
+ };
28
+ const finish = (failure = false) => {
29
+ if (done)
30
+ return;
31
+ done = true;
32
+ cleanup();
33
+ ctlPhase('prompt.done', { secret });
34
+ if (failure)
35
+ reject(refused());
36
+ else {
37
+ output.write('\n');
38
+ resolve(answer);
39
+ }
40
+ };
41
+ const closed = () => finish(true);
42
+ const data = (chunk) => {
43
+ const text = typeof chunk === 'string' ? chunk : decoder.write(chunk);
44
+ for (const character of text) {
45
+ if (done)
46
+ break;
47
+ if (character === '\x03' || character === '\x04') {
48
+ finish(true);
49
+ break;
50
+ }
51
+ if (escape) {
52
+ escape += character;
53
+ if (escape.length > 32 || escape.length > 2 && /[A-Za-z~]/.test(character) || escape.length === 2 && character !== '[')
54
+ escape = '';
55
+ continue;
56
+ }
57
+ if (character === '\x1b') {
58
+ escape = character;
59
+ continue;
60
+ }
61
+ if (character === '\r' || character === '\n') {
62
+ finish();
63
+ break;
64
+ }
65
+ if (character === '\b' || character === '\x7f') {
66
+ const characters = [...answer];
67
+ if (characters.length) {
68
+ characters.pop();
69
+ answer = characters.join('');
70
+ if (!secret)
71
+ output.write('\b \b');
72
+ }
73
+ continue;
74
+ }
75
+ if (character === '\x15') {
76
+ if (!secret)
77
+ output.write('\b \b'.repeat([...answer].length));
78
+ answer = '';
79
+ continue;
80
+ }
81
+ if (character < ' ' || character === '\x7f')
82
+ continue;
83
+ answer += character;
84
+ if (Buffer.byteLength(answer) > 4096) {
85
+ finish(true);
86
+ break;
87
+ }
88
+ if (!secret)
89
+ output.write(character);
90
+ }
91
+ };
92
+ input.on('data', data);
93
+ input.once('end', closed);
94
+ input.once('close', closed);
95
+ input.once('error', closed);
96
+ output.once('error', closed);
97
+ input.pause();
98
+ try {
99
+ ctlPhase('prompt.raw-mode', { secret });
100
+ input.setRawMode(true);
101
+ ctlPhase('prompt.raw-ready', { secret });
102
+ ctlPhase('prompt.write', { secret });
103
+ output.write(message, error => {
104
+ if (done)
105
+ return;
106
+ if (error) {
107
+ finish(true);
108
+ return;
109
+ }
110
+ ctlPhase('prompt.flushed', { secret });
111
+ ctlPhase('prompt.wait-input', { secret });
112
+ input.resume();
113
+ });
114
+ }
115
+ catch {
116
+ finish(true);
117
+ }
118
+ });
119
+ }
@@ -0,0 +1,20 @@
1
+ import type { WindowsAclSnapshot, WindowsLocalAliases } from './windows-acl.js';
2
+ export declare const sddlIssueKinds: readonly ["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"];
3
+ export type SddlIssue = typeof sddlIssueKinds[number];
4
+ export type SddlSection = 'O:' | 'G:' | 'D:' | 'S:';
5
+ export interface SddlDiagnostic {
6
+ category: 'invalid-descriptor';
7
+ tokenKind: SddlIssue;
8
+ token: string;
9
+ section?: SddlSection;
10
+ }
11
+ /** Diagnostic tokens are grammar fragments, never arbitrary input or paths. */
12
+ export declare function safeSddlToken(value: string): string;
13
+ export declare class SddlError extends Error {
14
+ detail: SddlDiagnostic;
15
+ constructor(tokenKind?: SddlIssue, token?: string, section?: SddlSection);
16
+ }
17
+ export declare function sddlSid(value: string, section?: SddlSection, localAliases?: WindowsLocalAliases): string;
18
+ export declare function sddlRights(value: string, section?: SddlSection, mandatory?: boolean): number;
19
+ /** Owner+DACL SDDL. SACL audit/mandatory labels never grant DACL access. */
20
+ export declare function parseWindowsSddl(input: string | Buffer, currentUser: string, reparsePoint?: boolean, localAliases?: WindowsLocalAliases): WindowsAclSnapshot;