@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
@@ -4,6 +4,11 @@ import { DESCRIPTION_METHOD, validateDescriptor, ajv } from './descriptor.js';
4
4
  import { runFlow } from './flows.js';
5
5
  import { localFile, transferRequest } from './transfers.js';
6
6
  import { selectApp, selectOperation, operationInput, requestPlan, confirmOperation } from './input.js';
7
+ import { nativeScope, nativeHostScope } from './native-store.js';
8
+ import { createNativeTransport } from './native-transport.js';
9
+ import { authorization, enrollNative } from './native-protocol.js';
10
+ import { executeNative } from './native-executor.js';
11
+ import { createNativeTransfer } from './native-transfers.js';
7
12
  export async function boundedMap(items, limit, fn) { const output = new Array(items.length); let next = 0; await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => { while (next < items.length) {
8
13
  const index = next++;
9
14
  output[index] = await fn(items[index]);
@@ -11,12 +16,79 @@ export async function boundedMap(items, limit, fn) { const output = new Array(it
11
16
  export class CtlClient {
12
17
  store;
13
18
  host;
19
+ timeoutMs;
20
+ nativeOptions;
14
21
  request;
15
- constructor(store, host, request, timeoutMs = CTL_TIMEOUT_MS) {
22
+ constructor(store, host, request, timeoutMs = CTL_TIMEOUT_MS, nativeOptions = {}) {
16
23
  this.store = store;
17
24
  this.host = host;
25
+ this.timeoutMs = timeoutMs;
26
+ this.nativeOptions = nativeOptions;
18
27
  this.request = request ?? createRequest(host.origin, () => this.remaining(timeoutMs), undefined, store.trust(host));
19
28
  }
29
+ nativeApproved(app) {
30
+ const host = this.store.get(this.host.name), approval = host.approved[app.payload.package.id];
31
+ if (host.origin !== this.host.origin || host.username !== this.host.username || approval?.version !== app.payload.package.version || approval.hash !== app.sha256)
32
+ throw this.needsApproval(app.payload.package);
33
+ }
34
+ nativeTransport(app, auth) {
35
+ const execution = app.payload.execution;
36
+ if (!execution)
37
+ throw new CtlError('CTL_NATIVE_TRANSPORT_REQUIRED', 'App does not declare native HTTP.', 'Use ordinary ctl commands for this App.', 5);
38
+ const transport = this.nativeOptions.transportFor?.(app, auth) ?? createNativeTransport(this.host.origin, execution.basePath, this.nativePaths(app).map(path => path.split('/{')[0]), this.store.trust(this.host), auth === undefined ? undefined : () => auth, this.nativePaths(app));
39
+ return input => { this.nativeApproved(app); return transport({ ...input, timeoutMs: input.timeoutMs ?? this.timeoutMs }); };
40
+ }
41
+ nativePaths(app) {
42
+ const auth = app.payload.execution.auth;
43
+ return [...Object.values(app.payload.commands).map(op => op.http.path), ...(auth.type === 'header' ? [auth.verify.path] : [auth.exchangePath, auth.identityPath, auth.actionTokenPath])];
44
+ }
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
+ 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), ...await this.store.native.status(nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 })) }; }
48
+ nativeRequired(app) {
49
+ const guide = this.nativeGuidance(app);
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);
51
+ }
52
+ async freshNative(app) {
53
+ const assertApproval = () => this.nativeApproved(app);
54
+ assertApproval();
55
+ const session = await this.store.session(this.host);
56
+ const pkg = (await this.inventory(session)).find(pkg => pkg.id === app.payload.package.id);
57
+ if (!pkg || pkg.version !== app.payload.package.version)
58
+ throw this.needsApproval(pkg ?? app.payload.package);
59
+ assertApproval();
60
+ const response = await this.request(app.payload.transport.path, { method: DESCRIPTION_METHOD, params: {} }, session);
61
+ if (response?.success !== true)
62
+ throw new CtlError('CTL_PERMISSION_DENIED', 'Native metadata admission was refused.', 'Restore DSM login and App entry permission.', 4);
63
+ const fresh = validateDescriptor(response.data, pkg.id, pkg.version);
64
+ if (fresh.sha256 !== app.sha256 || fresh.version !== 3)
65
+ throw this.needsApproval(fresh.payload.package);
66
+ assertApproval();
67
+ // A concurrent logout cannot be hidden by the already loaded DSM carriers.
68
+ if (!process.env.DSM_PASSWORD) {
69
+ const current = await this.store.credentials.get(this.store.key(this.host));
70
+ if (current?.cookie !== session.cookie || current?.token !== session.token)
71
+ throw new CtlError('CTL_NOT_AUTHENTICATED', 'DSM login changed during admission.', 'Run host login in your own terminal.', 2);
72
+ }
73
+ return fresh;
74
+ }
75
+ async authApp(name, options = {}) {
76
+ const app = this.selectApp(await this.discover({ ...options, app: name, refresh: true }), name);
77
+ if (app.version !== 3 || !app.payload.execution)
78
+ throw new CtlError('CTL_NATIVE_TRANSPORT_REQUIRED', 'App does not declare native credential authentication.', 'Use its declared transport.', 5);
79
+ return app;
80
+ }
81
+ async resetNative(app) { await this.store.native.delete(nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 })); }
82
+ async enroll(app, input, store = 'keychain', confirm) {
83
+ // Recheck admission before touching auth input or overwriting a local credential.
84
+ await this.freshNative(app);
85
+ const record = await enrollNative(app.payload.execution, input, auth => { const transport = this.nativeTransport(app, auth); return request => transport({ ...request, signal: AbortSignal.timeout(this.timeoutMs) }); });
86
+ if (confirm && !await confirm(record.identity ?? {}))
87
+ throw new CtlError('CTL_CONFIRM_REQUIRED', 'Native identity was not confirmed.', 'Run ctl auth again in your own terminal.', 7);
88
+ // Check local approval again after the human identity confirmation.
89
+ this.nativeApproved(app);
90
+ await this.store.native.set(nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 }), nativeHostScope(this.host), record, store);
91
+ }
20
92
  until;
21
93
  jobRequestBudget;
22
94
  remaining(fallback) { return this.jobRequestBudget ?? (this.until === undefined ? fallback : Math.max(0, this.until - performance.now())); }
@@ -51,6 +123,8 @@ export class CtlClient {
51
123
  return listing.apps.find(app => app.payload.package.id === pkg.id);
52
124
  }
53
125
  async discover(options = {}) {
126
+ if (!this.host.ephemeral)
127
+ this.host = this.store.get(this.host.name);
54
128
  const session = await this.store.session(this.host);
55
129
  let packages = (await this.inventory(session)).map(pkg => {
56
130
  const approved = this.host.approved[pkg.id];
@@ -67,9 +141,11 @@ export class CtlClient {
67
141
  this.host.approved[p.id] = { version: p.version };
68
142
  this.store.save(this.host);
69
143
  }
144
+ const approvalBaseline = structuredClone(this.host.approved);
70
145
  let cacheHits = 0;
71
146
  const results = await boundedMap(packages, 4, async (pkg) => {
72
147
  const approval = this.host.approved[pkg.id];
148
+ const approvalSnapshot = JSON.stringify(approval);
73
149
  if (approval?.version !== pkg.version) {
74
150
  pkg.error = this.needsApproval(pkg);
75
151
  return { error: { package: pkg.id, ...errorData(pkg.error) } };
@@ -92,6 +168,8 @@ export class CtlClient {
92
168
  throw new CtlError('CTL_DESCRIPTION_UNAVAILABLE', `Description refused (${String(response?.error?.code ?? 'invalid response')}).`, 'Use --refresh after updating the App.', 5);
93
169
  description = validateDescriptor(response.data, pkg.id, pkg.version);
94
170
  }
171
+ if (description.version === 3 && !this.host.ephemeral && JSON.stringify(this.store.get(this.host.name).approved[pkg.id]) !== approvalSnapshot)
172
+ throw this.needsApproval(pkg);
95
173
  if (approval.hash && approval.hash !== description.sha256 && !options.approve) {
96
174
  // Remember the observed change so a later cache hit cannot revive the old approval.
97
175
  this.store.putCache(this.host, pkg.id, pkg.version, description);
@@ -111,6 +189,20 @@ export class CtlClient {
111
189
  return { error: { package: pkg.id, ...failure } };
112
190
  }
113
191
  });
192
+ // Keep concurrent revocations and other profile changes; never restore a stale approval map.
193
+ if (!this.host.ephemeral) {
194
+ const current = this.store.get(this.host.name);
195
+ if (current.origin !== this.host.origin || current.username !== this.host.username)
196
+ throw new CtlError('CTL_CREDENTIAL_MISMATCH', 'Registered profile changed during discovery.', 'Repeat discovery with the current profile.', 2);
197
+ for (const pkg of packages)
198
+ if (JSON.stringify(current.approved[pkg.id]) === JSON.stringify(approvalBaseline[pkg.id])) {
199
+ if (this.host.approved[pkg.id])
200
+ current.approved[pkg.id] = this.host.approved[pkg.id];
201
+ else
202
+ delete current.approved[pkg.id];
203
+ }
204
+ this.host = current;
205
+ }
114
206
  this.host.lastUsed = new Date().toISOString();
115
207
  this.store.save(this.host);
116
208
  return { apps: results.flatMap(r => r.description ? [r.description] : []), installed: packages, diagnostics: results.flatMap(r => r.error ? [r.error] : []), cacheHits };
@@ -129,6 +221,8 @@ export class CtlClient {
129
221
  this.until = started + (options.timeoutMs ?? CTL_TIMEOUT_MS);
130
222
  const listing = await this.discover(options);
131
223
  const app = this.selectApp(listing, name);
224
+ if (app.version === 3)
225
+ await this.freshNative(app);
132
226
  const { id, operation } = selectOperation(app, path);
133
227
  const params = operationInput(operation, args, options.stdin, `run: synopkgland ctl ${name} ${operation.cli.join(' ')} --host ${this.host.name} --help`);
134
228
  if (operation.flow.type === 'job') {
@@ -141,6 +235,33 @@ export class CtlClient {
141
235
  confirmOperation(operation, !!options.yes, !!options.dryRun, plan);
142
236
  if (options.dryRun)
143
237
  return { dryRun: true, request: plan };
238
+ if (app.version === 3 && app.payload.execution) {
239
+ // Revocation is checked again before loading any App credential.
240
+ this.nativeApproved(app);
241
+ const key = nativeScope(this.host, app.payload.package.id, { authSha256: app.payload.authSha256 });
242
+ let record;
243
+ try {
244
+ record = await this.store.native.get(key);
245
+ }
246
+ catch (error) {
247
+ if (error instanceof CtlError && error.code === 'CTL_NATIVE_AUTH_INVALID')
248
+ throw new CtlError(error.code, error.message, `${this.nativeGuidance(app).command}; credential location: ${this.nativeGuidance(app).credentialUrl}; ${this.nativeGuidance(app).instructions}`, 2);
249
+ throw error;
250
+ }
251
+ if (!record)
252
+ throw this.nativeRequired(app);
253
+ try {
254
+ return await executeNative(operation, params, app.payload.execution, this.nativeTransport(app, authorization(app.payload.execution, record)), { signal: options.signal, transfer: this.nativeOptions.transfer ?? createNativeTransfer({ timeoutMs: options.timeoutMs ?? this.timeoutMs }), timeoutMs: options.timeoutMs ?? this.timeoutMs });
255
+ }
256
+ catch (error) {
257
+ if (error instanceof CtlError && error.code === 'CTL_NATIVE_AUTH_INVALID') {
258
+ await this.store.native.invalid(key);
259
+ const guide = this.nativeGuidance(app);
260
+ throw new CtlError(error.code, error.message, `${guide.command}; credential location: ${guide.credentialUrl}; ${guide.instructions}`, 2);
261
+ }
262
+ throw error;
263
+ }
264
+ }
144
265
  const session = await this.store.session(this.host);
145
266
  let appSession = session;
146
267
  if (app.payload.transport.auth === 'dsm-app-session') {
@@ -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;
@@ -0,0 +1,162 @@
1
+ export const sddlIssueKinds = ['unknown-ace-type', 'unsupported-ace-type', 'unknown-sid-alias', 'invalid-sid', 'unknown-flag', 'duplicate-flag', 'unknown-rights', 'unsupported-object-guid', 'section', 'missing-section', 'malformed-ace', 'malformed-descriptor', 'bounds', 'native-output', 'private-readback'];
2
+ /** Diagnostic tokens are grammar fragments, never arbitrary input or paths. */
3
+ export function safeSddlToken(value) {
4
+ if (/^S-1-(?:\d+-)+\d+$/.test(value))
5
+ return value.replace(/^S-1-5-21-.+$/, 'S-1-5-21-*').replace(/^S-1-15-2-.+$/, 'S-1-15-2-*').slice(0, 80);
6
+ return /^(?:[A-Z]{1,32}|[OGDS]:|0x[0-9a-f]{1,16})$/i.test(value) ? value : '<invalid>';
7
+ }
8
+ export class SddlError extends Error {
9
+ detail;
10
+ constructor(tokenKind = 'malformed-descriptor', token = '', section) {
11
+ const safe = safeSddlToken(token);
12
+ super(`Unsupported or incomplete Windows security descriptor (${tokenKind}=${safe}${section ? ' section=' + section : ''}).`);
13
+ this.detail = { category: 'invalid-descriptor', tokenKind, token: safe, ...(section ? { section } : {}) };
14
+ }
15
+ }
16
+ function refuse(kind, token = '', section) { throw new SddlError(kind, token, section); }
17
+ const aliases = { SY: 'S-1-5-18', BA: 'S-1-5-32-544', BU: 'S-1-5-32-545', BG: 'S-1-5-32-546', WD: 'S-1-1-0', AU: 'S-1-5-11', AN: 'S-1-5-7', CO: 'S-1-3-0', CG: 'S-1-3-1', OW: 'S-1-3-4', LS: 'S-1-5-19', NS: 'S-1-5-20', IU: 'S-1-5-4', SU: 'S-1-5-6', AC: 'S-1-15-2-1', UN: 'S-1-16-0', LW: 'S-1-16-4096', ME: 'S-1-16-8192', MP: 'S-1-16-8448', HI: 'S-1-16-12288', SI: 'S-1-16-16384' };
18
+ // LA/LG depend on the machine domain. Preserve their identities in pure parsing;
19
+ // the native reader supplies numeric resolutions for owner checks and icacls.
20
+ Object.assign(aliases, { LA: 'LA', LG: 'LG', NU: 'S-1-5-2', PU: 'S-1-5-32-547', AO: 'S-1-5-32-548', SO: 'S-1-5-32-549', PO: 'S-1-5-32-550', BO: 'S-1-5-32-551', RE: 'S-1-5-32-552', RU: 'S-1-5-32-554', RD: 'S-1-5-32-555', NO: 'S-1-5-32-556', MU: 'S-1-5-32-558', LU: 'S-1-5-32-559', IS: 'S-1-5-32-568', CY: 'S-1-5-32-569', ER: 'S-1-5-32-573', CD: 'S-1-5-32-574', RA: 'S-1-5-32-575', ES: 'S-1-5-32-576', HA: 'S-1-5-32-578', AA: 'S-1-5-32-579', RM: 'S-1-5-32-580', PS: 'S-1-5-10', RC: 'S-1-5-12', ED: 'S-1-5-9', WR: 'S-1-5-33', AS: 'S-1-18-1', SS: 'S-1-18-2' });
21
+ const rights = { FA: 0x1f01ff, FR: 0x120089, FW: 0x120116, FX: 0x1200a0, GA: 0x10000000, GR: 0x80000000, GW: 0x40000000, GX: 0x20000000, RC: 0x20000, SD: 0x10000, WD: 0x40000, WO: 0x80000, CC: 1, DC: 2, LC: 4, SW: 8, RP: 16, WP: 32, DT: 64, LO: 128, CR: 256 };
22
+ export function sddlSid(value, section, localAliases = {}) {
23
+ if (/^S-1-(?:\d+-)+\d+$/.test(value))
24
+ return value;
25
+ if ((value === 'LA' || value === 'LG') && Object.hasOwn(localAliases, value))
26
+ return localAliases[value];
27
+ if (Object.hasOwn(aliases, value))
28
+ return aliases[value];
29
+ return refuse(/^[A-Z]{2}$/.test(value) ? 'unknown-sid-alias' : 'invalid-sid', value, section);
30
+ }
31
+ function tokens(value, known, section) {
32
+ const found = [];
33
+ while (value) {
34
+ const next = known.find(token => value.startsWith(token));
35
+ if (!next)
36
+ refuse('unknown-flag', value.slice(0, 2), section);
37
+ if (found.includes(next))
38
+ refuse('duplicate-flag', next, section);
39
+ found.push(next);
40
+ value = value.slice(next.length);
41
+ }
42
+ return found;
43
+ }
44
+ export function sddlRights(value, section = 'D:', mandatory = false) {
45
+ if (/^0x[0-9a-f]{1,8}$/i.test(value)) {
46
+ const mask = parseInt(value.slice(2), 16);
47
+ if (mandatory && (mask & ~7))
48
+ refuse('unknown-rights', value, section);
49
+ return mask;
50
+ }
51
+ if (/^0x/i.test(value) || value.length % 2)
52
+ refuse('unknown-rights', value, section);
53
+ const known = mandatory ? { NW: 1, NR: 2, NX: 4 } : rights;
54
+ let mask = 0;
55
+ for (let index = 0; index < value.length; index += 2) {
56
+ const part = value.slice(index, index + 2);
57
+ if (!(part in known))
58
+ refuse('unknown-rights', part, section);
59
+ mask |= known[part];
60
+ }
61
+ return mask >>> 0;
62
+ }
63
+ const conditional = ['XA', 'XD', 'ZA', 'ZD', 'XU', 'XL', 'ZU', 'ZL'];
64
+ function aceType(type, section) {
65
+ if (conditional.includes(type))
66
+ refuse('unsupported-ace-type', type, section);
67
+ if (!(section === 'D:' ? ['A', 'D', 'OA', 'OD'] : ['ML', 'AU', 'AL']).includes(type))
68
+ refuse(['A', 'D', 'OA', 'OD', 'ML', 'AU', 'AL', 'OU', 'OL', 'RA', 'SP', 'TL', 'FL'].includes(type) ? 'unsupported-ace-type' : 'unknown-ace-type', type, section);
69
+ }
70
+ /** Owner+DACL SDDL. SACL audit/mandatory labels never grant DACL access. */
71
+ export function parseWindowsSddl(input, currentUser, reparsePoint = false, localAliases = {}) {
72
+ if (!localAliases || typeof localAliases !== 'object' || Array.isArray(localAliases))
73
+ refuse('native-output');
74
+ for (const [alias, sid] of Object.entries(localAliases))
75
+ if (!['LA', 'LG'].includes(alias) || !new RegExp('^S-1-5-21-(?:[0-9]+-){3}' + (alias === 'LA' ? '500' : '501') + '$').test(sid))
76
+ refuse('native-output');
77
+ if (Buffer.isBuffer(input) && input.length % 2)
78
+ refuse('malformed-descriptor');
79
+ const text = (Buffer.isBuffer(input) ? input.toString('utf16le') : input).replace(/^\uFEFF/, '').trim();
80
+ if (!text || text.length > 1024 * 1024 || text.includes('\0'))
81
+ refuse('bounds');
82
+ const components = {};
83
+ let position = 0;
84
+ while (position < text.length) {
85
+ const key = text[position], section = (key + ':');
86
+ if (!'OGDS'.includes(key) || text[position + 1] !== ':' || key in components)
87
+ refuse('section', section);
88
+ const start = position + 2;
89
+ position = start;
90
+ let depth = 0;
91
+ for (; position < text.length; position++) {
92
+ const character = text[position];
93
+ if (character === '(') {
94
+ if (depth || !['D', 'S'].includes(key))
95
+ refuse('malformed-ace', '', section);
96
+ const end = text.indexOf(';', position);
97
+ if (end < 0 || end - position > 8)
98
+ refuse('malformed-ace', '', section);
99
+ aceType(text.slice(position + 1, end), section);
100
+ depth++;
101
+ }
102
+ else if (character === ')') {
103
+ if (--depth < 0)
104
+ refuse('malformed-ace', '', section);
105
+ }
106
+ if (!depth && 'OGDS'.includes(character) && text[position + 1] === ':')
107
+ break;
108
+ }
109
+ if (depth)
110
+ refuse('malformed-ace', '', section);
111
+ components[key] = text.slice(start, position);
112
+ }
113
+ if (!components.O)
114
+ refuse('missing-section', 'O:', 'O:');
115
+ const owner = sddlSid(components.O, 'O:', localAliases);
116
+ sddlSid(currentUser, 'O:');
117
+ if (components.G !== undefined)
118
+ sddlSid(components.G, 'G:', localAliases);
119
+ const rules = [];
120
+ let protectedDacl = false, nullDacl = components.D === undefined;
121
+ for (const section of ['D:', 'S:']) {
122
+ const value = components[section[0]];
123
+ if (value === undefined)
124
+ continue;
125
+ const first = value.indexOf('('), prefix = first < 0 ? value : value.slice(0, first);
126
+ const nullMarker = prefix.includes('NO_ACCESS_CONTROL');
127
+ const flags = tokens(prefix.replace('NO_ACCESS_CONTROL', ''), ['AI', 'AR', 'P'], section);
128
+ if (section === 'D:') {
129
+ nullDacl = nullMarker;
130
+ protectedDacl = flags.includes('P');
131
+ }
132
+ if (nullMarker) {
133
+ if (first >= 0)
134
+ refuse('malformed-ace', 'NO_ACCESS_CONTROL', section);
135
+ continue;
136
+ }
137
+ let rest = first < 0 ? '' : value.slice(first), count = 0;
138
+ while (rest) {
139
+ const end = rest.indexOf(')');
140
+ if (rest[0] !== '(' || end < 0 || count++ >= 4096)
141
+ refuse('malformed-ace', '', section);
142
+ const fields = rest.slice(1, end).split(';');
143
+ rest = rest.slice(end + 1);
144
+ if (fields.length !== 6)
145
+ refuse('malformed-ace', '', section);
146
+ const [type, flagText, access, objectGuid, inheritGuid, account] = fields;
147
+ aceType(type, section);
148
+ for (const guid of [objectGuid, inheritGuid])
149
+ if (guid && (!['OA', 'OD'].includes(type) || !/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(guid)))
150
+ refuse('unsupported-object-guid', '', section);
151
+ const aceFlags = tokens(flagText, section === 'S:' && type !== 'ML' ? ['ID', 'OI', 'CI', 'IO', 'NP', 'SA', 'FA'] : ['ID', 'OI', 'CI', 'IO', 'NP'], section);
152
+ const sid = sddlSid(account, section, localAliases), mask = sddlRights(access, section, type === 'ML');
153
+ if (type === 'ML' && !/^S-1-16-\d+$/.test(sid))
154
+ refuse('invalid-sid', sid, section);
155
+ if (section === 'S:')
156
+ continue; // Auditing/mandatory labels are not access grants.
157
+ // Treat object-scoped grants as grants on the entire object, conservatively.
158
+ rules.push({ sid, type: type === 'A' || type === 'OA' ? 'Allow' : 'Deny', rights: mask, inheritOnly: aceFlags.includes('IO'), inherited: aceFlags.includes('ID'), objectInherit: aceFlags.includes('OI'), containerInherit: aceFlags.includes('CI'), noPropagate: aceFlags.includes('NP') });
159
+ }
160
+ }
161
+ return { currentUser, owner, nullDacl, reparsePoint, rules, protected: protectedDacl, ...(Object.keys(localAliases).length ? { aliasSids: { ...localAliases } } : {}) };
162
+ }
@@ -0,0 +1,7 @@
1
+ import type { WindowsLocalAliases } from './windows-acl.js';
2
+ export declare function readWindowsDescriptor(path: string): {
3
+ sddl: string;
4
+ reparsePoint: boolean;
5
+ directory: boolean;
6
+ aliasSids?: WindowsLocalAliases;
7
+ };