@synopackageland/cli 0.50.0 → 0.51.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +9 -0
  3. package/dist/build-spk/generator.js +3 -3
  4. package/dist/build-spk/reproducible-archive.js +3 -1
  5. package/dist/build-spk/ui-texts.d.ts +3 -1
  6. package/dist/build-spk/ui-texts.js +17 -8
  7. package/dist/ctl/ai-tools.d.ts +2 -0
  8. package/dist/ctl/cli.js +14 -0
  9. package/dist/ctl/diagnostics.d.ts +16 -0
  10. package/dist/ctl/diagnostics.js +11 -0
  11. package/dist/ctl/native-auth-command.js +5 -0
  12. package/dist/ctl/native-paths.js +13 -2
  13. package/dist/ctl/native-store.d.ts +6 -0
  14. package/dist/ctl/native-store.js +20 -26
  15. package/dist/ctl/service.d.ts +2 -0
  16. package/dist/ctl/service.js +1 -1
  17. package/dist/ctl/windows-acl.d.ts +39 -0
  18. package/dist/ctl/windows-acl.js +80 -0
  19. package/dist/ctl/windows-prompt.d.ts +5 -0
  20. package/dist/ctl/windows-prompt.js +119 -0
  21. package/dist/ctl/windows-sddl.d.ts +20 -0
  22. package/dist/ctl/windows-sddl.js +162 -0
  23. package/dist/ctl/windows-security-helper.d.ts +7 -0
  24. package/dist/ctl/windows-security-helper.js +88 -0
  25. package/dist/ctl/windows-security.d.ts +10 -0
  26. package/dist/ctl/windows-security.js +95 -0
  27. package/dist/ctl/windows-tools.d.ts +11 -0
  28. package/dist/ctl/windows-tools.js +23 -0
  29. package/dist/error-registry.js +6 -1
  30. package/dist/native-http-schema/source.json +1 -1
  31. package/dist/skill.js +1 -0
  32. package/dist/spk/extract.d.ts +6 -0
  33. package/dist/spk/extract.js +39 -0
  34. package/dist/standalone/daemon.js +1 -0
  35. package/dist/standalone/dsm-texts.d.ts +17 -0
  36. package/dist/standalone/dsm-texts.js +102 -0
  37. package/dist/standalone/dsm-window.js +3 -0
  38. package/dist/standalone/inspect-spk.d.ts +2 -0
  39. package/dist/standalone/inspect-spk.js +46 -20
  40. package/dist/standalone/install-ports.js +2 -1
  41. package/dist/standalone/manifest.d.ts +3 -0
  42. package/dist/standalone/manifest.js +33 -20
  43. package/dist/standalone/native-layout.js +2 -0
  44. package/package.json +2 -1
  45. package/schema/dsm-package.schema.json +12 -1
  46. package/skills/SKILL.md +3 -0
  47. package/skills/reference/ctl.md +32 -1
  48. package/skills/reference/dsm-texts.md +95 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.51.0
4
+
5
+ - Add declarative `i18n.dsm_texts`: per-locale DSM strings files become native DSM text sections (for example `[notify]`) in the package, validated against English with matching keys and placeholders; `[synopkgland]` stays reserved
6
+ - Show archived native text sections in `inspect`
7
+
3
8
  ## 0.50.0
4
9
 
5
10
  - Preserve headless Compose STOP failures and stop before restart; missing Container Manager profiles remain normal lifecycle state
package/README.md CHANGED
@@ -708,3 +708,12 @@ executes HTTP bindings without forwarding DSM cookies. Authentication failures
708
708
  offer explicit renewal without replaying the command. Uploads and downloads
709
709
  stream with declared byte/MIME limits and secure local file handling. Read
710
710
  `synopkgland skill show ctl` for configuration, auth commands and transfer rules.
711
+
712
+ ### Native DSM text sections
713
+
714
+ Declare `i18n.dsm_texts: i18n/dsm-texts` to merge package-owned `[notify]` or
715
+ other native sections into `ui/texts/<DSM language>/strings`. `check` validates
716
+ all declared locales, keys and placeholder parity; `build` adds the keys to
717
+ `ui/config` preload lists. `inspect --json <SPK>` reports archived `nativeTexts`
718
+ sections and keys per DSM language. See `synopkgland skill show dsm-texts` and
719
+ [the format and evidence notes](skills/reference/dsm-texts.md).
@@ -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
  }
@@ -1,9 +1,11 @@
1
+ import { type NativeTexts } from "../standalone/dsm-texts.js";
1
2
  import { type InfoTranslations } from "../standalone/i18n.js";
2
3
  /** The English INFO text and its translations, which also name the app in DSM. */
3
4
  export interface AppTitle {
4
5
  displayname: string;
5
6
  description: string;
6
7
  info?: InfoTranslations;
8
+ nativeTexts?: NativeTexts;
7
9
  }
8
10
  /**
9
11
  * `ui/config` title fields. With translations they are `section:key`
@@ -26,7 +28,7 @@ export declare function consoleTitle(displayname: string, console: {
26
28
  export declare function uiConsoleTitleFields(app: AppTitle, console: {
27
29
  title?: string;
28
30
  }): ReturnType<typeof uiTitleFields>;
29
- /** `ui/texts/<dsm lang>/strings` for English and every translated language; none without translations. */
31
+ /** Merge validated native sections after the reserved section, in fixed locale/section/key order. */
30
32
  export declare function renderUiTexts(app: AppTitle, console?: {
31
33
  title?: string;
32
34
  }): Map<string, string>;
@@ -1,3 +1,4 @@
1
+ import { nativeTextRefs } from "../standalone/dsm-texts.js";
1
2
  import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { DSM_LANGS, LOCALES } from "../standalone/i18n.js";
@@ -7,6 +8,10 @@ const DESC = `${SECTION}:app_desc`;
7
8
  const CONSOLE_TITLE = `${SECTION}:console_title`;
8
9
  /** `ui/` subdirectory with the strings; a `ui/config` entry's `texts` names it relative to `ui/`. */
9
10
  const TEXTS_DIR = "texts";
11
+ function nativeTextFields(app) {
12
+ const refs = nativeTextRefs(app.nativeTexts);
13
+ return refs.length ? { texts: TEXTS_DIR, preloadTexts: refs } : {};
14
+ }
10
15
  function translated(app) {
11
16
  return Object.values(app.info ?? {}).some((text) => text?.displayname || text?.description);
12
17
  }
@@ -19,8 +24,8 @@ function translated(app) {
19
24
  */
20
25
  export function uiTitleFields(app) {
21
26
  return translated(app)
22
- ? { title: TITLE, desc: DESC, texts: TEXTS_DIR, preloadTexts: [TITLE, DESC] }
23
- : { title: app.displayname, desc: app.description };
27
+ ? { title: TITLE, desc: DESC, texts: TEXTS_DIR, preloadTexts: [TITLE, DESC, ...nativeTextRefs(app.nativeTexts)] }
28
+ : { title: app.displayname, desc: app.description, ...nativeTextFields(app) };
24
29
  }
25
30
  /** The console's name: the declared title in every language, else "<displayname> for DSM". */
26
31
  export function consoleTitle(displayname, console) {
@@ -29,22 +34,26 @@ export function consoleTitle(displayname, console) {
29
34
  /** {@link uiTitleFields} for the console window, which shares the App's description. */
30
35
  export function uiConsoleTitleFields(app, console) {
31
36
  return translated(app)
32
- ? { title: CONSOLE_TITLE, desc: DESC, texts: TEXTS_DIR, preloadTexts: [CONSOLE_TITLE, DESC] }
33
- : { title: consoleTitle(app.displayname, console), desc: app.description };
37
+ ? { title: CONSOLE_TITLE, desc: DESC, texts: TEXTS_DIR, preloadTexts: [CONSOLE_TITLE, DESC, ...nativeTextRefs(app.nativeTexts)] }
38
+ : { title: consoleTitle(app.displayname, console), desc: app.description, ...nativeTextFields(app) };
34
39
  }
35
- /** `ui/texts/<dsm lang>/strings` for English and every translated language; none without translations. */
40
+ /** Merge validated native sections after the reserved section, in fixed locale/section/key order. */
36
41
  export function renderUiTexts(app, console) {
37
42
  const files = new Map();
38
- if (!translated(app))
43
+ if (!translated(app) && !app.nativeTexts)
39
44
  return files;
40
45
  for (const locale of LOCALES) {
41
46
  const text = locale === "en" ? undefined : app.info?.[locale];
42
- if (locale !== "en" && !text)
47
+ const native = app.nativeTexts?.[locale];
48
+ if (!translated(app) && !native)
49
+ continue;
50
+ if (locale !== "en" && !text && !native)
43
51
  continue;
44
52
  const title = text?.displayname ?? app.displayname;
45
53
  const desc = text?.description ?? app.description;
46
54
  const consoleLine = console ? `console_title="${consoleTitle(title, console)}"\n` : "";
47
- files.set(DSM_LANGS[locale], `[${SECTION}]\napp_title="${title}"\napp_desc="${desc}"\n${consoleLine}`);
55
+ const own = translated(app) ? `[${SECTION}]\napp_title="${title}"\napp_desc="${desc}"\n${consoleLine}` : "";
56
+ files.set(DSM_LANGS[locale], own + (own && native ? "\n" : "") + (native ?? ""));
48
57
  }
49
58
  return files;
50
59
  }
@@ -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>;