@synopackageland/cli 0.49.1 → 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.
Files changed (96) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +10 -0
  3. package/dist/build-spk/generator.js +3 -3
  4. package/dist/build-spk/reproducible-archive.js +3 -1
  5. package/dist/ctl/ai-tools.d.ts +11 -1
  6. package/dist/ctl/ai-tools.js +4 -4
  7. package/dist/ctl/cli.d.ts +8 -1
  8. package/dist/ctl/cli.js +54 -5
  9. package/dist/ctl/descriptor.d.ts +15 -2
  10. package/dist/ctl/descriptor.js +9 -4
  11. package/dist/ctl/diagnostics.d.ts +16 -0
  12. package/dist/ctl/diagnostics.js +11 -0
  13. package/dist/ctl/flows.js +2 -0
  14. package/dist/ctl/input.d.ts +5 -3
  15. package/dist/ctl/input.js +3 -3
  16. package/dist/ctl/native-auth-command.d.ts +9 -0
  17. package/dist/ctl/native-auth-command.js +103 -0
  18. package/dist/ctl/native-executor.d.ts +16 -0
  19. package/dist/ctl/native-executor.js +187 -0
  20. package/dist/ctl/native-file-types.d.ts +16 -0
  21. package/dist/ctl/native-file-types.js +57 -0
  22. package/dist/ctl/native-files.d.ts +13 -0
  23. package/dist/ctl/native-files.js +115 -0
  24. package/dist/ctl/native-metadata.d.ts +10 -0
  25. package/dist/ctl/native-metadata.js +50 -0
  26. package/dist/ctl/native-paths.d.ts +4 -0
  27. package/dist/ctl/native-paths.js +65 -0
  28. package/dist/ctl/native-protocol.d.ts +21 -0
  29. package/dist/ctl/native-protocol.js +150 -0
  30. package/dist/ctl/native-registry.d.ts +8 -0
  31. package/dist/ctl/native-registry.js +182 -0
  32. package/dist/ctl/native-schemas.d.ts +7 -0
  33. package/dist/ctl/native-schemas.js +25 -0
  34. package/dist/ctl/native-store.d.ts +67 -0
  35. package/dist/ctl/native-store.js +342 -0
  36. package/dist/ctl/native-transfers.d.ts +13 -0
  37. package/dist/ctl/native-transfers.js +331 -0
  38. package/dist/ctl/native-transport.d.ts +30 -0
  39. package/dist/ctl/native-transport.js +148 -0
  40. package/dist/ctl/native-types.d.ts +15 -0
  41. package/dist/ctl/native-types.js +1 -0
  42. package/dist/ctl/registry.d.ts +5 -4
  43. package/dist/ctl/registry.js +12 -1
  44. package/dist/ctl/service.d.ts +34 -1
  45. package/dist/ctl/service.js +122 -1
  46. package/dist/ctl/windows-acl.d.ts +39 -0
  47. package/dist/ctl/windows-acl.js +80 -0
  48. package/dist/ctl/windows-prompt.d.ts +5 -0
  49. package/dist/ctl/windows-prompt.js +119 -0
  50. package/dist/ctl/windows-sddl.d.ts +20 -0
  51. package/dist/ctl/windows-sddl.js +162 -0
  52. package/dist/ctl/windows-security-helper.d.ts +7 -0
  53. package/dist/ctl/windows-security-helper.js +88 -0
  54. package/dist/ctl/windows-security.d.ts +10 -0
  55. package/dist/ctl/windows-security.js +95 -0
  56. package/dist/ctl/windows-tools.d.ts +11 -0
  57. package/dist/ctl/windows-tools.js +23 -0
  58. package/dist/error-registry.js +15 -0
  59. package/dist/generated/native-http.d.ts +189 -0
  60. package/dist/generated/native-http.js +1 -0
  61. package/dist/nas/store.d.ts +3 -1
  62. package/dist/nas/store.js +6 -3
  63. package/dist/nas/transport.d.ts +1 -0
  64. package/dist/native-http-schema/descriptor.schema.json +242 -0
  65. package/dist/native-http-schema/inventory.schema.json +121 -0
  66. package/dist/native-http-schema/registry.schema.json +872 -0
  67. package/dist/native-http-schema/source.json +1 -0
  68. package/dist/runtime/sdk-source.d.ts +1 -1
  69. package/dist/runtime/sdk-source.js +1 -1
  70. package/dist/spk/extract.d.ts +6 -0
  71. package/dist/spk/extract.js +39 -0
  72. package/dist/standalone/api-description.d.ts +2 -5
  73. package/dist/standalone/build.js +5 -1
  74. package/dist/standalone/compose-errors.js +5 -0
  75. package/dist/standalone/daemon.js +1 -0
  76. package/dist/standalone/inspect-spk.js +23 -37
  77. package/dist/standalone/install-ports.js +2 -1
  78. package/dist/standalone/lifecycle.js +9 -2
  79. package/dist/standalone/manifest.d.ts +1 -0
  80. package/dist/standalone/manifest.js +22 -5
  81. package/dist/standalone/native-http-inspect.d.ts +9 -0
  82. package/dist/standalone/native-http-inspect.js +43 -0
  83. package/dist/standalone/native-http.d.ts +31 -0
  84. package/dist/standalone/native-http.js +120 -0
  85. package/dist/standalone/native-layout.js +2 -0
  86. package/dist/standalone/operation-registry.d.ts +2 -7
  87. package/dist/standalone/operation-registry.js +3 -0
  88. package/dist/standalone/spk.d.ts +1 -0
  89. package/dist/standalone/spk.js +15 -1
  90. package/package.json +3 -2
  91. package/schema/dsm-api-contract.json +8 -7
  92. package/skills/SKILL.md +2 -2
  93. package/skills/reference/compose.md +21 -0
  94. package/skills/reference/ctl.md +229 -0
  95. package/skills/reference/daemon-mode.md +1 -1
  96. package/skills/reference/upstream-fork.md +5 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.50.0
4
+
5
+ - Preserve headless Compose STOP failures and stop before restart; missing Container Manager profiles remain normal lifecycle state
6
+
7
+ - Add native HTTP ctl execution for v3 metadata on Compose and native Apps, using the shared SDK contract and authenticated metadata description
8
+ - Store upstream credentials in the OS keyring or an encrypted local vault, scoped to DSM profile, account, package and auth metadata
9
+ - Offer explicit credential renewal after authentication failures without replaying commands or uncertain mutations
10
+ - Add bounded streaming uploads and downloads, secure local file handling, MIME/byte checks and completion receipts
11
+ - Accept action-token text responses and empty successful mutation responses while rejecting symlinked file ancestors
12
+ - Pin CLI-owned SDK defaults to 0.52.0; retain compatible templates and their independent scaffold SDK pins
13
+
3
14
  ## 0.49.1
4
15
 
5
16
  - Pass the same build-stamped App bundle URL to SDK entry preload and mount for every generated mobile App entry
package/README.md CHANGED
@@ -698,3 +698,13 @@ For same-origin App URLs, see [DSM path ingress](docs/path-ingress.md).
698
698
  `npm run gates` runs basic checks and is the default for release packaging and CI.
699
699
  Use `npm run gates:full` only when explicitly requested. See
700
700
  [release entry points and checks](docs/release-checks.md) for the complete inventory.
701
+
702
+ ## Native HTTP ctl
703
+
704
+ Apps with existing upstream APIs can declare `ctl.transport: native-http` and a
705
+ v3 operation registry. The CLI validates matching SDK metadata, enrolls scoped
706
+ upstream credentials through the OS keyring or an encrypted local vault, and
707
+ executes HTTP bindings without forwarding DSM cookies. Authentication failures
708
+ offer explicit renewal without replaying the command. Uploads and downloads
709
+ stream with declared byte/MIME limits and secure local file handling. Read
710
+ `synopkgland skill show ctl` for configuration, auth commands and transfer rules.
@@ -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,5 +1,15 @@
1
1
  import type { CtlClient, DiscoverOptions } from './service.js';
2
2
  export declare function listAiTools(client: CtlClient, appName: string, options?: DiscoverOptions): Promise<{
3
+ auth?: {
4
+ state: import("./native-store.js").NativeStoreState;
5
+ reason?: string;
6
+ detail?: import("./windows-acl.js").WindowsAclDiagnostic;
7
+ scheme: "header" | "greader-client-login";
8
+ credentialUrl: string;
9
+ instructions: string;
10
+ command: string;
11
+ } | undefined;
12
+ credentialGuidance?: string | undefined;
3
13
  package: {
4
14
  id: string;
5
15
  version: string;
@@ -18,7 +28,7 @@ export declare function listAiTools(client: CtlClient, appName: string, options?
18
28
  destructiveHint: boolean;
19
29
  openWorldHint: boolean;
20
30
  };
21
- ai: "hidden" | "read" | "preview" | "draft" | "human-only";
31
+ ai: "read" | "preview" | "draft" | "human-only" | "hidden";
22
32
  flow: import("./descriptor.js").Flow;
23
33
  }[];
24
34
  }>;
@@ -2,9 +2,9 @@ import { CtlError } from './errors.js';
2
2
  import { registryTools } from './registry.js';
3
3
  export async function listAiTools(client, appName, options = {}) {
4
4
  const app = client.selectApp(await client.discover(options), appName);
5
- if (app.version !== 2 || !app.payload.operations)
6
- throw new CtlError('CTL_AI_REGISTRY_REQUIRED', 'AI tools require a v2 registry.', 'Migrate the App operation registry.', 5);
7
- return { package: app.payload.package, sha256: app.sha256, tools: registryTools({ format: 'synopkgland.api', version: 2, operations: app.payload.operations }) };
5
+ if (app.version === 1 || app.version === 2 && !app.payload.operations)
6
+ throw new CtlError('CTL_AI_REGISTRY_REQUIRED', 'AI tools require an operation registry.', 'Migrate the App operation registry.', 5);
7
+ return { package: app.payload.package, sha256: app.sha256, tools: registryTools({ operations: app.version === 3 ? app.payload.commands : app.payload.operations }), ...(app.payload.execution ? { auth: await client.nativeState(app), credentialGuidance: 'Ask the user to run ctl auth in their own terminal. Never request credentials in chat.' } : {}) };
8
8
  }
9
9
  /** A draft is always a preview and plan. This API has no write-confirmation input.
10
10
  * Humans can execute the reviewed ctl plan separately with the normal --yes guard.
@@ -12,7 +12,7 @@ export async function listAiTools(client, appName, options = {}) {
12
12
  */
13
13
  export async function runAiTool(client, appName, method, params, options = {}) {
14
14
  const app = client.selectApp(await client.discover(options), appName);
15
- const op = app.version === 2 ? app.payload.commands[method] : undefined;
15
+ const op = app.version !== 1 ? app.payload.commands[method] : undefined;
16
16
  if (!op || !['read', 'preview', 'draft'].includes(op.ai ?? ''))
17
17
  throw new CtlError('CTL_AI_NOT_EXPOSED', 'Operation is not an AI tool.', 'Use the generated tool list.', 4);
18
18
  const args = ['--input', '-'], stdin = JSON.stringify(params);
package/dist/ctl/cli.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { CtlStore, type Host } from './store.js';
2
2
  import { type JsonRequest } from './transport.js';
3
3
  import type { Descriptor } from './descriptor.js';
4
+ import type { NativeTransport } from './native-transport.js';
5
+ import type { NativeTransfer } from './native-executor.js';
4
6
  export interface CtlIO {
5
7
  store?: CtlStore;
6
8
  out?: (line: string) => void;
@@ -8,6 +10,10 @@ export interface CtlIO {
8
10
  isTTY?: boolean;
9
11
  prompt?: (message: string, secret?: boolean) => Promise<string>;
10
12
  requestFor?: (host: Host) => JsonRequest;
13
+ nativeTransportFor?: (host: Host, app: Descriptor, authorization?: string) => NativeTransport;
14
+ nativeTransfer?: NativeTransfer;
15
+ secretStdin?: () => string;
16
+ openBrowser?: (url: string) => Promise<void>;
11
17
  }
12
18
  export declare function listView(host: string, apps: Descriptor[]): {
13
19
  commands: {
@@ -19,6 +25,7 @@ export declare function listView(host: string, apps: Descriptor[]): {
19
25
  }[];
20
26
  examples: string[];
21
27
  summary: string;
28
+ http?: import("./native-types.js").HttpOperation;
22
29
  kind?: "rpc" | "ai" | "stream";
23
30
  ai?: import("./registry.js").AIClass;
24
31
  preview?: string;
@@ -41,7 +48,7 @@ export declare function listView(host: string, apps: Descriptor[]): {
41
48
  displayName: string;
42
49
  };
43
50
  aliases: string[];
44
- protocolVersion: 2 | 1;
51
+ protocolVersion: 3 | 2 | 1;
45
52
  developedBy: string;
46
53
  provenance: string;
47
54
  hash: string;
package/dist/ctl/cli.js CHANGED
@@ -11,18 +11,34 @@ import { canonicalOrigin, CTL_TIMEOUT_MS, createRequest } from './transport.js';
11
11
  import { loginDsm, logoutDsm } from './dsm-auth.js';
12
12
  import { publicOperation } from './redaction.js';
13
13
  import { runExternal } from './external.js';
14
- const USAGE = 'synopkgland host add|list|show|login|logout|remove|revoke|default|trust; ctl generate [--check]; ctl import-openapi <file|https-url>; 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';
14
+ import { authCommand } from './native-auth-command.js';
15
+ import { createNativeTransfer } from './native-transfers.js';
16
+ import { windowsPrompt } from './windows-prompt.js';
17
+ import { ctlPhase } from './diagnostics.js';
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';
15
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 });
16
28
  if (!process.stdin.isTTY)
17
29
  throw new CtlError('CTL_INTERACTION_REQUIRED', 'Interactive input required.', 'Use --username and --password-stdin for host authentication.', 2);
30
+ ctlPhase('prompt.write', { secret });
18
31
  process.stderr.write(message);
32
+ ctlPhase('prompt.readline-create', { secret });
19
33
  const muted = new Writable({ write(chunk, _encoding, done) { if (!secret)
20
34
  process.stderr.write(chunk); done(); } });
21
35
  const rl = createInterface({ input: process.stdin, output: muted, terminal: true });
36
+ ctlPhase('prompt.readline-ready', { secret });
22
37
  try {
23
38
  return await rl.question('');
24
39
  }
25
40
  finally {
41
+ ctlPhase('prompt.done', { secret });
26
42
  rl.close();
27
43
  if (secret)
28
44
  process.stderr.write('\n');
@@ -67,7 +83,7 @@ function example(host, app, op) {
67
83
  return `printf '%s' ${q(JSON.stringify(params))} | ${base} --input -` + (op.effect === 'read' ? '' : ' --yes');
68
84
  });
69
85
  }
70
- export function listView(host, apps) { return apps.map(app => ({ host, package: app.payload.package, aliases: app.payload.aliases, protocolVersion: app.version, developedBy: app.payload.provenance.developedBy, provenance: 'self-declared', hash: app.sha256, ...(app.payload.external ? { external: app.payload.external } : {}), commands: Object.entries(app.payload.commands).map(([id, original]) => { const op = publicOperation(original); return { id, ...op, parameters: op.paramsSchema ?? 'Undescribed parameters; use --input', flags: typedFlags(op), examples: example(host, app, op) }; }) })); }
86
+ export function listView(host, apps) { return apps.map(app => ({ host, package: app.payload.package, aliases: app.payload.aliases, protocolVersion: app.version, developedBy: app.payload.provenance.developedBy, provenance: 'self-declared', hash: app.sha256, ...(app.payload.external ? { external: app.payload.external } : {}), commands: Object.entries(app.payload.commands).filter(([, op]) => op.ai !== 'hidden').map(([id, original]) => { const op = publicOperation(original); return { id, ...op, parameters: op.paramsSchema ?? 'Undescribed parameters; use --input', flags: typedFlags(op), examples: example(host, app, op) }; }) })); }
71
87
  export async function runCtl(argv, io = {}) {
72
88
  if (argv[0] === 'generate' || argv[0] === 'import-openapi') {
73
89
  try {
@@ -106,8 +122,20 @@ async function runCtlWithin(argv, io = {}) {
106
122
  if (timeout && (!/^\d+$/.test(timeout) || Number(timeout) < 1 || Number(timeout) > 3600))
107
123
  throw new CtlError('CTL_ARGUMENT_INVALID', '--timeout must be 1–3600 seconds.', 'Use --timeout 60.');
108
124
  const timeoutMs = timeout ? Number(timeout) * 1000 : CTL_TIMEOUT_MS;
109
- const client = (host) => new CtlClient(store, host, io.requestFor?.(host), timeoutMs);
125
+ const client = (host) => new CtlClient(store, host, io.requestFor?.(host), timeoutMs, { transportFor: io.nativeTransportFor ? (app, authorization) => io.nativeTransportFor(host, app, authorization) : undefined, transfer: io.nativeTransfer ?? createNativeTransfer({ timeoutMs, handleSignals: true, progress: tty && !json ? value => (io.err ?? console.error)(`${value.direction}: ${value.bytes}${value.total === undefined ? '' : ' / ' + value.total} bytes`) : undefined }) });
110
126
  const discoverOptions = { refresh, app: appFilter, approve, confirm: tty ? async (packages) => /^y(es)?$/i.test(await ask('Allow DSM session to fixed description endpoints for ' + packages.map(p => p.id + '@' + p.version).join(', ') + '? [y/N] ')) : undefined };
127
+ if (args[0] === 'auth') {
128
+ if (help) {
129
+ emit({ ok: true, data: { usage: 'synopkgland ctl auth --app <package> [--host profile] [--reset] [--secret-stdin] [--store keychain|encrypted-file]', guidance: 'Humans only. Never paste credentials into chat or pass them as command arguments.' } });
130
+ return;
131
+ }
132
+ if (allHosts || yes || dryRun || refresh || approve)
133
+ throw new CtlError('CTL_ARGUMENT_INVALID', 'Auth requires one App and one registered profile.', 'Use ctl auth --app <package> --host <profile>.', 3);
134
+ const host = store.select(hostOption);
135
+ await authCommand(client(host), args.slice(1), appFilter, { tty, ask, err: io.err ?? console.error, readSecret: io.secretStdin, openBrowser: io.openBrowser });
136
+ emit({ ok: true, data: { authenticated: !args.slice(1).includes('--reset'), localOnly: true, upstreamTokenRevoked: false } });
137
+ return;
138
+ }
111
139
  if (args[0] === 'tools' || args[0] === 'tool') {
112
140
  if (yes || dryRun || allHosts || approve || refresh)
113
141
  throw new CtlError('CTL_ARGUMENT_INVALID', 'Tool commands do not accept mutation, approval or multi-host flags.', 'Use ctl tools <app> or ctl tool <app> <method> --input -.', 3);
@@ -272,7 +300,11 @@ async function runCtlWithin(argv, io = {}) {
272
300
  if (args.length !== 1)
273
301
  throw new CtlError('CTL_ARGUMENT_INVALID', 'Unexpected list arguments.', `run: synopkgland ctl list --host ${name}`);
274
302
  const result = await ctl.discover(discoverOptions);
275
- return { host: name, ok: true, data: { apps: listView(name, result.apps), diagnostics: result.diagnostics, cacheHits: result.cacheHits } };
303
+ const apps = listView(name, result.apps);
304
+ for (let i = 0; i < apps.length; i++)
305
+ if (result.apps[i].payload.execution)
306
+ Object.assign(apps[i], { auth: await ctl.nativeState(result.apps[i]) });
307
+ return { host: name, ok: true, data: { apps, diagnostics: result.diagnostics, cacheHits: result.cacheHits } };
276
308
  }
277
309
  if (args[0] === 'help' || help) {
278
310
  const nameArg = args[0] === 'help' ? args[1] : args[0];
@@ -290,7 +322,24 @@ async function runCtlWithin(argv, io = {}) {
290
322
  throw new CtlError('CTL_ARGUMENT_INVALID', '--timeout must be 1–3600 seconds.', 'Use --timeout 60.');
291
323
  const firstFlag = tail.findIndex(token => token.startsWith('--'));
292
324
  const path = firstFlag < 0 ? tail : tail.slice(0, firstFlag), params = firstFlag < 0 ? [] : tail.slice(firstFlag);
293
- const data = await ctl.execute(args[0], path, params, { ...discoverOptions, yes, dryRun, stdin: commonInput, wait: !noWait, timeoutMs: timeout ? Number(timeout) * 1000 : undefined });
325
+ if (tty && !json)
326
+ store.native.setUnlock(() => ask('Native vault passphrase (hidden): ', true));
327
+ let data;
328
+ try {
329
+ data = await ctl.execute(args[0], path, params, { ...discoverOptions, yes, dryRun, stdin: commonInput, wait: !noWait, timeoutMs: timeout ? Number(timeout) * 1000 : undefined });
330
+ }
331
+ catch (error) {
332
+ if (error instanceof CtlError && ['CTL_NATIVE_AUTH_REQUIRED', 'CTL_NATIVE_AUTH_INVALID'].includes(error.code) && tty && !json && names.length === 1) {
333
+ const err = io.err ?? console.error, invalid = error.code === 'CTL_NATIVE_AUTH_INVALID';
334
+ err(error.code + ': ' + error.message);
335
+ err(error.hint);
336
+ if (/^y(es)?$/i.test(await ask(invalid ? 'Enter a new token now? [y/N] ' : 'Set up the App credential now? [y/N] '))) {
337
+ await authCommand(ctl, [], args[0], { tty, ask, err, readSecret: io.secretStdin, openBrowser: io.openBrowser });
338
+ throw new CtlError('CTL_NATIVE_AUTH_READY', 'Native credential saved. Rerun the original command explicitly.', 'The original operation was not replayed.', 2);
339
+ }
340
+ }
341
+ throw error;
342
+ }
294
343
  return { host: name, ok: true, data };
295
344
  }
296
345
  catch (error) {
@@ -1,8 +1,10 @@
1
1
  import Ajv2020 from 'ajv/dist/2020.js';
2
+ import type { NativeFlow, NativeHttp, HttpOperation } from './native-types.js';
2
3
  export declare const DESCRIPTION_METHOD = "synopkgland.describe";
3
4
  export declare const DESCRIPTION_FILE = "synopkgland-api.json";
4
5
  export type Operation = {
5
6
  summary: string;
7
+ http?: HttpOperation;
6
8
  kind?: 'rpc' | 'ai' | 'stream';
7
9
  ai?: import('./registry.js').AIClass;
8
10
  preview?: string;
@@ -15,7 +17,7 @@ export type Operation = {
15
17
  examples?: Record<string, unknown>[];
16
18
  flow: Flow;
17
19
  };
18
- export type Flow = {
20
+ export type Flow = NativeFlow | {
19
21
  type: 'invoke';
20
22
  method: string;
21
23
  } | {
@@ -41,6 +43,9 @@ export type Flow = {
41
43
  } | {
42
44
  type: 'ndjson';
43
45
  method: string;
46
+ maxLines?: number;
47
+ maxLineBytes?: number;
48
+ maxBytes?: number;
44
49
  } | {
45
50
  type: 'upload';
46
51
  method: string;
@@ -68,6 +73,14 @@ export interface ApiPayload {
68
73
  path: string;
69
74
  auth: string;
70
75
  };
76
+ execution?: (NativeHttp & {
77
+ type: 'native-http';
78
+ });
79
+ features?: string[];
80
+ entryPolicyDigest?: string;
81
+ registrySha256?: string;
82
+ inventorySha256?: string;
83
+ authSha256?: string;
71
84
  operations?: Record<string, import('./registry.js').RegisteredOperation>;
72
85
  commands: Record<string, Operation>;
73
86
  bindings: Record<string, Binding>;
@@ -77,7 +90,7 @@ export interface ApiPayload {
77
90
  }
78
91
  export interface Descriptor {
79
92
  format: 'synopkgland.api';
80
- version: 1 | 2;
93
+ version: 1 | 2 | 3;
81
94
  payload: ApiPayload;
82
95
  sha256: string;
83
96
  }
@@ -4,17 +4,20 @@ import { createHash } from 'node:crypto';
4
4
  import { canonicalize } from 'json-canonicalize';
5
5
  import Ajv2020 from 'ajv/dist/2020.js';
6
6
  import { CtlError } from './errors.js';
7
+ import { validateNativeDescriptor } from './native-metadata.js';
7
8
  import { schemaRegExp } from './pattern.js';
8
9
  export const DESCRIPTION_METHOD = 'synopkgland.describe';
9
10
  export const DESCRIPTION_FILE = 'synopkgland-api.json';
10
11
  export const ajv = new Ajv2020.default({ allErrors: true, strict: false, validateFormats: false, addUsedSchema: false, code: { regExp: schemaRegExp } });
11
12
  const descriptorSchemaV2 = ajv.compile(JSON.parse(readFileSync(new URL('../../schema/synopkgland-api-v2.schema.json', import.meta.url), 'utf8')));
12
13
  const descriptorSchema = ajv.compile(JSON.parse(readFileSync(new URL('../../schema/synopkgland-api-v1.schema.json', import.meta.url), 'utf8')));
13
- export function makeDescriptor(payload) { const value = { format: 'synopkgland.api', version: (payload.operations ? 2 : 1), payload }; return { ...value, sha256: createHash('sha256').update(canonicalize(value)).digest('hex') }; }
14
+ export function makeDescriptor(payload) { const value = { format: 'synopkgland.api', version: (payload.execution ? 3 : payload.operations ? 2 : 1), payload }; return { ...value, sha256: createHash('sha256').update(canonicalize(value)).digest('hex') }; }
14
15
  export function validateDescriptor(value, id, version) {
15
16
  const fail = (message) => { throw new CtlError('CTL_DESCRIPTOR_INVALID', message, 'run: synopkgland ctl list --refresh', 5); };
16
- if (!value || value.format !== 'synopkgland.api' || ![1, 2].includes(value.version) || !value.payload || !/^([0-9a-f]{64})$/.test(value.sha256))
17
+ if (!value || value.format !== 'synopkgland.api' || ![1, 2, 3].includes(value.version) || !value.payload || !/^([0-9a-f]{64})$/.test(value.sha256))
17
18
  return fail('Unsupported API description format.');
19
+ if (value.version === 3)
20
+ return validateNativeDescriptor(value, id, version);
18
21
  if (!(value.version === 2 ? descriptorSchemaV2 : descriptorSchema)(value))
19
22
  return fail('API description schema validation failed.');
20
23
  const p = value.payload;
@@ -32,7 +35,8 @@ export function validateDescriptor(value, id, version) {
32
35
  return fail('Missing internal method bindings.');
33
36
  if (value.version === 2) {
34
37
  try {
35
- validateRegistry({ format: 'synopkgland.api', version: 2, operations: p.operations });
38
+ if (value.version === 2)
39
+ validateRegistry({ format: 'synopkgland.api', version: 2, operations: p.operations });
36
40
  }
37
41
  catch {
38
42
  return fail('Invalid operation registry.');
@@ -61,7 +65,8 @@ export function validateDescriptor(value, id, version) {
61
65
  if (method.length > 128 || !/^([a-z][a-z0-9_]*\.)+[a-z][a-z0-9_]*$/.test(method) || !op || typeof op.summary !== 'string' || !['read', 'write', 'destructive'].includes(op.effect) || !['public', 'authenticated', 'administrators'].includes(op.permission) || !Array.isArray(op.cli) || !op.cli.length || op.cli.some(s => typeof s !== 'string' || !/^[a-z][a-z0-9-]*$/.test(s)))
62
66
  return fail('Invalid command metadata.');
63
67
  try {
64
- validateFlow(op, p.bindings);
68
+ if (value.version !== 3)
69
+ validateFlow(op, p.bindings);
65
70
  }
66
71
  catch {
67
72
  return fail('Invalid command flow or method bindings.');
@@ -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
+ }
package/dist/ctl/flows.js CHANGED
@@ -46,6 +46,8 @@ export async function runFlow(flow, params, send, options) {
46
46
  }
47
47
  throw new CtlError('CTL_FLOW_LIMIT', 'Pagination page limit reached; result is incomplete.', 'Narrow the query.', 5);
48
48
  }
49
+ if (flow.type !== 'job')
50
+ throw new CtlError('CTL_FLOW_UNSUPPORTED', 'Native flow requires native HTTP transport.', 'Use a compatible CLI.', 5);
49
51
  const accepted = await invoke(flow.start, params);
50
52
  if (options.wait === false)
51
53
  return { accepted: true, job: accepted };
@@ -13,12 +13,14 @@ export declare function flagName(key: string): string;
13
13
  export declare function flagValueType(schema: any): string | undefined;
14
14
  export declare function operationInput(op: Operation, args: string[], stdin?: string, helpHint?: string): Record<string, unknown>;
15
15
  export declare function requestPlan(app: Descriptor, id: string, params: Record<string, unknown>): {
16
- package: string;
17
- version: string;
18
- path: string;
19
16
  command: string;
20
17
  flow: import("./descriptor.js").Flow;
21
18
  params: Record<string, unknown>;
22
19
  effect: "read" | "write" | "destructive";
20
+ transport?: string | undefined;
21
+ method?: "POST" | "GET" | "PUT" | "PATCH" | "DELETE" | undefined;
22
+ package: string;
23
+ version: string;
24
+ path: string;
23
25
  };
24
26
  export declare function confirmOperation(op: Operation, yes: boolean, dryRun: boolean, plan: unknown): void;
package/dist/ctl/input.js CHANGED
@@ -32,10 +32,10 @@ export function selectApp(apps, name) {
32
32
  return choose(name, apps.flatMap(app => [app.id, ...app.aliases]), 'app');
33
33
  }
34
34
  export function selectOperation(app, path) {
35
- const found = Object.entries(app.payload.commands).find(([, op]) => op.cli.join(' ') === path.join(' '));
35
+ const found = Object.entries(app.payload.commands).find(([, op]) => op.ai !== 'hidden' && op.cli.join(' ') === path.join(' '));
36
36
  if (found)
37
37
  return { id: found[0], operation: found[1] };
38
- return choose(path.join(' '), Object.values(app.payload.commands).map(op => op.cli.join(' ')), 'command');
38
+ return choose(path.join(' '), Object.values(app.payload.commands).filter(op => op.ai !== 'hidden').map(op => op.cli.join(' ')), 'command');
39
39
  }
40
40
  export const RESERVED_FLAGS = new Set(['ca', 'strict-tls', 'host', 'all-hosts', 'json', 'app', 'refresh', 'yes', 'dry-run', 'approve-installed', 'help', 'input', 'wait', 'no-wait', 'timeout']);
41
41
  export function flagName(key) { return key.replace(/[A-Z]/g, c => '-' + c.toLowerCase()).replaceAll('_', '-'); }
@@ -135,7 +135,7 @@ export function operationInput(op, args, stdin, helpHint) {
135
135
  }
136
136
  return params;
137
137
  }
138
- export function requestPlan(app, id, params) { return { package: app.payload.package.id, version: app.payload.package.version, path: app.payload.transport.path, command: id, flow: app.payload.commands[id].flow, params: redactValue(params, app.payload.commands[id].paramsSchema), effect: app.payload.commands[id].effect }; }
138
+ export function requestPlan(app, id, params) { const operation = app.payload.commands[id], native = app.payload.execution; return { package: app.payload.package.id, version: app.payload.package.version, path: native ? native.basePath.slice(0, -1) + operation.http.path : app.payload.transport.path, ...(native ? { transport: 'native-http', method: operation.http.method } : {}), command: id, flow: operation.flow, params: redactValue(params, operation.paramsSchema), effect: operation.effect }; }
139
139
  export function confirmOperation(op, yes, dryRun, plan) {
140
140
  if (!dryRun && op.effect !== 'read' && !yes)
141
141
  throw new CtlError('CTL_CONFIRM_REQUIRED', 'State-changing operation requires --yes.', 'Inspect with --dry-run, then repeat the same command with --yes.', 7, undefined, plan);
@@ -0,0 +1,9 @@
1
+ import type { CtlClient } from './service.js';
2
+ export declare function openNativeCredentialPage(url: string): Promise<void>;
3
+ export declare function authCommand(client: CtlClient, args: string[], appName: string | undefined, io: {
4
+ tty: boolean;
5
+ ask: (message: string, secret?: boolean) => Promise<string>;
6
+ err: (message: string) => void;
7
+ readSecret?: () => string;
8
+ openBrowser?: (url: string) => Promise<void>;
9
+ }): Promise<void>;
@@ -0,0 +1,103 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { CtlError } from './errors.js';
3
+ import { ctlPhase } from './diagnostics.js';
4
+ import { readBounded, strictJson } from './json.js';
5
+ import { validateNativeToken } from './native-store.js';
6
+ export async function openNativeCredentialPage(url) {
7
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';
8
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
9
+ await new Promise((resolve, reject) => { const child = spawn(command, args, { stdio: 'ignore', windowsHide: true, shell: false }); child.once('error', () => reject(new CtlError('CTL_BROWSER_UNAVAILABLE', 'Could not open the browser.', 'Open the displayed credential URL manually.', 5))); child.once('exit', code => code === 0 ? resolve() : reject(new CtlError('CTL_BROWSER_UNAVAILABLE', 'Browser opener did not succeed.', 'Open the displayed credential URL manually.', 5))); });
10
+ }
11
+ export async function authCommand(client, args, appName, io) {
12
+ let reset = false, stdin = false, store;
13
+ const seen = new Set();
14
+ const invalid = () => new CtlError('CTL_ARGUMENT_INVALID', 'Invalid auth options. Credentials are never accepted in arguments.', 'Use ctl auth --app <package> [--reset] [--secret-stdin] [--store encrypted-file].', 3);
15
+ for (let i = 0; i < args.length; i++) {
16
+ const [flag, inline] = args[i].split('=');
17
+ if (seen.has(flag))
18
+ throw invalid();
19
+ seen.add(flag);
20
+ if (flag === '--reset' && inline === undefined)
21
+ reset = true;
22
+ else if (flag === '--secret-stdin' && inline === undefined)
23
+ stdin = true;
24
+ else if (flag === '--store') {
25
+ const value = inline ?? args[++i];
26
+ if (value !== 'keychain' && value !== 'encrypted-file')
27
+ throw invalid();
28
+ store = value;
29
+ }
30
+ else
31
+ throw invalid();
32
+ }
33
+ if (!appName || !reset && !stdin && !io.tty)
34
+ throw new CtlError('CTL_NATIVE_AUTH_REQUIRED', 'Run ctl auth in your own terminal. Never paste a token into chat.', 'Use --app <package>; human automation may supply --secret-stdin.', 2);
35
+ if (client.host.ephemeral)
36
+ throw new CtlError('CTL_HOST_REQUIRED', 'Native credentials require a registered NAS profile.', 'Register a named profile with host add.', 2);
37
+ const app = await client.authApp(appName), http = app.payload.execution, guide = client.nativeGuidance(app);
38
+ if (reset) {
39
+ await client.resetNative(app);
40
+ io.err('Deleted this scope from local storage. The App token remains valid upstream.');
41
+ return;
42
+ }
43
+ store ??= await client.nativeStoreKind(app) ?? 'keychain';
44
+ if (store === 'encrypted-file' && !io.tty)
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');
47
+ io.err('Credential location: ' + guide.credentialUrl);
48
+ io.err(guide.instructions);
49
+ ctlPhase('auth.browser-confirm');
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');
52
+ try {
53
+ await (io.openBrowser ?? openNativeCredentialPage)(guide.credentialUrl);
54
+ }
55
+ catch {
56
+ io.err('Browser opener unavailable; open the displayed URL manually.');
57
+ }
58
+ }
59
+ ctlPhase('auth.credential-input');
60
+ let input;
61
+ if (stdin) {
62
+ let raw;
63
+ try {
64
+ raw = io.readSecret?.() ?? readBounded(0, 16384);
65
+ }
66
+ catch {
67
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'Cannot read bounded native auth input.', 'Supply one token, or one strict username/apiPassword JSON object.', 2);
68
+ }
69
+ if (Buffer.byteLength(raw) > 16384)
70
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'Native auth input exceeds its byte bound.', 'Supply a bounded secret through stdin.', 2);
71
+ if (http.auth.type === 'header') {
72
+ const token = raw.replace(/\r?\n$/, '');
73
+ validateNativeToken(token);
74
+ input = { token };
75
+ }
76
+ else {
77
+ try {
78
+ const value = strictJson(raw);
79
+ if (!value || Array.isArray(value) || typeof value !== 'object' || Object.keys(value).sort().join(',') !== 'apiPassword,username' || typeof value.username !== 'string' || typeof value.apiPassword !== 'string')
80
+ throw Error();
81
+ input = value;
82
+ }
83
+ catch {
84
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'Expected one username/apiPassword JSON object.', 'Supply only the declared native auth fields on stdin.', 2);
85
+ }
86
+ }
87
+ }
88
+ else
89
+ input = http.auth.type === 'header' ? { token: await io.ask('Native API token (hidden): ', true) } : { username: await io.ask('Native account name: '), apiPassword: await io.ask('Native API password (hidden): ', true) };
90
+ if (store === 'encrypted-file')
91
+ client.store.native.setUnlock(async () => {
92
+ const passphrase = await io.ask('Independent vault passphrase (hidden): ', true);
93
+ if (passphrase !== await io.ask('Confirm vault passphrase (hidden): ', true))
94
+ throw new CtlError('CTL_NATIVE_VAULT_LOCKED', 'Vault passphrases do not match.', 'Run ctl auth again.', 2);
95
+ return passphrase;
96
+ });
97
+ await client.enroll(app, input, store, stdin ? undefined : async (identity) => {
98
+ io.err(Object.keys(identity).length ? 'Verified native App identity: ' + JSON.stringify(identity) : 'Native credential verified; this declaration provides no selected display identity.');
99
+ io.err('The native App account is not a proof of the DSM account identity.');
100
+ return /^y(es)?$/i.test(await io.ask('Store this App credential locally? [y/N] '));
101
+ });
102
+ io.err(store === 'keychain' ? 'Saved verified native token in the OS keychain.' : 'Saved verified native token in the encrypted local vault.');
103
+ }
@@ -0,0 +1,16 @@
1
+ import type { Operation } from './descriptor.js';
2
+ import type { NativeHttp, HttpOperation, HttpBinding } from './native-types.js';
3
+ import { type NativeRequest, type NativeTransport } from './native-transport.js';
4
+ export declare function boundValue(binding: HttpBinding, params: Record<string, unknown>, actionToken?: string): unknown;
5
+ export declare function nativeRequest(http: HttpOperation, params: Record<string, unknown>, actionToken?: string, extraQuery?: URLSearchParams): NativeRequest;
6
+ /** Transfer owners use the same prepared operation and token-free transport. */
7
+ export type NativeTransfer = (operation: Operation, params: Record<string, unknown>, context: {
8
+ http: NativeHttp;
9
+ transport: NativeTransport;
10
+ signal?: AbortSignal;
11
+ }) => Promise<unknown>;
12
+ export declare function executeNative(op: Operation, params: Record<string, unknown>, http: NativeHttp, transport: NativeTransport, options?: {
13
+ signal?: AbortSignal;
14
+ transfer?: NativeTransfer;
15
+ timeoutMs?: number;
16
+ }): Promise<unknown>;