@synopackageland/cli 0.49.1 → 0.50.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 (75) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +10 -0
  3. package/dist/ctl/ai-tools.d.ts +9 -1
  4. package/dist/ctl/ai-tools.js +4 -4
  5. package/dist/ctl/cli.d.ts +8 -1
  6. package/dist/ctl/cli.js +40 -5
  7. package/dist/ctl/descriptor.d.ts +15 -2
  8. package/dist/ctl/descriptor.js +9 -4
  9. package/dist/ctl/flows.js +2 -0
  10. package/dist/ctl/input.d.ts +5 -3
  11. package/dist/ctl/input.js +3 -3
  12. package/dist/ctl/native-auth-command.d.ts +9 -0
  13. package/dist/ctl/native-auth-command.js +98 -0
  14. package/dist/ctl/native-executor.d.ts +16 -0
  15. package/dist/ctl/native-executor.js +187 -0
  16. package/dist/ctl/native-file-types.d.ts +16 -0
  17. package/dist/ctl/native-file-types.js +57 -0
  18. package/dist/ctl/native-files.d.ts +13 -0
  19. package/dist/ctl/native-files.js +115 -0
  20. package/dist/ctl/native-metadata.d.ts +10 -0
  21. package/dist/ctl/native-metadata.js +50 -0
  22. package/dist/ctl/native-paths.d.ts +4 -0
  23. package/dist/ctl/native-paths.js +54 -0
  24. package/dist/ctl/native-protocol.d.ts +21 -0
  25. package/dist/ctl/native-protocol.js +150 -0
  26. package/dist/ctl/native-registry.d.ts +8 -0
  27. package/dist/ctl/native-registry.js +182 -0
  28. package/dist/ctl/native-schemas.d.ts +7 -0
  29. package/dist/ctl/native-schemas.js +25 -0
  30. package/dist/ctl/native-store.d.ts +61 -0
  31. package/dist/ctl/native-store.js +348 -0
  32. package/dist/ctl/native-transfers.d.ts +13 -0
  33. package/dist/ctl/native-transfers.js +331 -0
  34. package/dist/ctl/native-transport.d.ts +30 -0
  35. package/dist/ctl/native-transport.js +148 -0
  36. package/dist/ctl/native-types.d.ts +15 -0
  37. package/dist/ctl/native-types.js +1 -0
  38. package/dist/ctl/registry.d.ts +5 -4
  39. package/dist/ctl/registry.js +12 -1
  40. package/dist/ctl/service.d.ts +32 -1
  41. package/dist/ctl/service.js +122 -1
  42. package/dist/error-registry.js +15 -0
  43. package/dist/generated/native-http.d.ts +189 -0
  44. package/dist/generated/native-http.js +1 -0
  45. package/dist/nas/store.d.ts +3 -1
  46. package/dist/nas/store.js +6 -3
  47. package/dist/nas/transport.d.ts +1 -0
  48. package/dist/native-http-schema/descriptor.schema.json +242 -0
  49. package/dist/native-http-schema/inventory.schema.json +121 -0
  50. package/dist/native-http-schema/registry.schema.json +872 -0
  51. package/dist/native-http-schema/source.json +1 -0
  52. package/dist/runtime/sdk-source.d.ts +1 -1
  53. package/dist/runtime/sdk-source.js +1 -1
  54. package/dist/standalone/api-description.d.ts +2 -5
  55. package/dist/standalone/build.js +5 -1
  56. package/dist/standalone/compose-errors.js +5 -0
  57. package/dist/standalone/inspect-spk.js +2 -17
  58. package/dist/standalone/lifecycle.js +9 -2
  59. package/dist/standalone/manifest.d.ts +1 -0
  60. package/dist/standalone/manifest.js +22 -5
  61. package/dist/standalone/native-http-inspect.d.ts +9 -0
  62. package/dist/standalone/native-http-inspect.js +43 -0
  63. package/dist/standalone/native-http.d.ts +31 -0
  64. package/dist/standalone/native-http.js +120 -0
  65. package/dist/standalone/operation-registry.d.ts +2 -7
  66. package/dist/standalone/operation-registry.js +3 -0
  67. package/dist/standalone/spk.d.ts +1 -0
  68. package/dist/standalone/spk.js +15 -1
  69. package/package.json +2 -2
  70. package/schema/dsm-api-contract.json +8 -7
  71. package/skills/SKILL.md +2 -2
  72. package/skills/reference/compose.md +21 -0
  73. package/skills/reference/ctl.md +198 -0
  74. package/skills/reference/daemon-mode.md +1 -1
  75. package/skills/reference/upstream-fork.md +5 -2
@@ -0,0 +1,348 @@
1
+ import { createHash, randomBytes, scryptSync, createCipheriv, createDecipheriv } from 'node:crypto';
2
+ import { mkdirSync, lstatSync, openSync, closeSync, fstatSync, readFileSync, writeFileSync, renameSync, rmSync, fsyncSync, constants } from 'node:fs';
3
+ import { basename, dirname, join, resolve, parse, sep } from 'node:path';
4
+ import { trustedAncestors } from './native-paths.js';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { canonicalize } from 'json-canonicalize';
7
+ import { CtlError } from './errors.js';
8
+ import { strictJson } from './json.js';
9
+ export const NATIVE_SERVICE = 'synopkgland.ctl.native';
10
+ export function authDigest(http, entryPolicyDigest = '') {
11
+ return createHash('sha256').update(canonicalize({ basePath: http.basePath, auth: http.auth, entryPolicyDigest })).digest('hex');
12
+ }
13
+ export function nativeScope(host, pkg, http) {
14
+ return createHash('sha256').update(['synopkgland.ctl.native.v1', host.name, host.origin, host.username, pkg, 'authSha256' in http ? http.authSha256 : authDigest(http)].join('\0')).digest('hex');
15
+ }
16
+ export function nativeHostScope(host) {
17
+ return createHash('sha256').update([host.name, host.origin, host.username].join('\0')).digest('hex');
18
+ }
19
+ const fail = (code = 'CTL_NATIVE_STORE_UNAVAILABLE') => new CtlError(code, code === 'CTL_NATIVE_VAULT_LOCKED' ? 'Encrypted native vault is locked.' : 'Native credential storage is unavailable or unsafe.', 'Unlock the OS keychain, or run ctl auth --store encrypted-file in your own terminal.', 2);
20
+ /** The same audited binding selects Keychain, Credential Manager or Secret Service. */
21
+ export class NativeKeychain {
22
+ factory;
23
+ constructor(factory) {
24
+ this.factory = factory;
25
+ }
26
+ async entry(key) {
27
+ try {
28
+ if (this.factory)
29
+ return await this.factory(NATIVE_SERVICE, key, { linux: { store: 'secret-service' } });
30
+ const { AsyncEntry } = await import('@napi-rs/keyring');
31
+ return new AsyncEntry(NATIVE_SERVICE, key, { linux: { store: 'secret-service' } });
32
+ }
33
+ catch {
34
+ throw fail();
35
+ }
36
+ }
37
+ async get(key) { try {
38
+ return await (await this.entry(key)).getPassword();
39
+ }
40
+ catch {
41
+ throw fail();
42
+ } }
43
+ async set(key, value) { try {
44
+ await (await this.entry(key)).setPassword(value);
45
+ }
46
+ catch {
47
+ throw fail();
48
+ } }
49
+ async delete(key) { try {
50
+ const entry = await this.entry(key);
51
+ if (await entry.getPassword() !== null)
52
+ await entry.deleteCredential();
53
+ }
54
+ catch {
55
+ throw fail();
56
+ } }
57
+ }
58
+ function keyName(key) { if (!/^[a-f0-9]{64}$/.test(key))
59
+ throw fail(); return key; }
60
+ function privatePath(path, directory) {
61
+ const stat = lstatSync(path);
62
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
63
+ throw fail();
64
+ if (process.platform !== 'win32' && ((directory ? (stat.mode & 0o777) !== 0o700 : (stat.mode & 0o077) !== 0) || stat.uid !== process.getuid?.() || !directory && stat.nlink !== 1))
65
+ throw fail();
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
+ }
78
+ }
79
+ function secureWindows(path) { if (process.platform === 'win32')
80
+ windowsAcl(path, true); }
81
+ function directory(root) {
82
+ const absolute = resolve(root);
83
+ let current = parse(absolute).root;
84
+ for (const segment of absolute.slice(current.length).split(sep).filter(Boolean)) {
85
+ current = join(current, segment);
86
+ try {
87
+ if (lstatSync(current).isSymbolicLink())
88
+ throw fail();
89
+ }
90
+ catch (error) {
91
+ if (error.code !== 'ENOENT')
92
+ throw error;
93
+ mkdirSync(current, { mode: 0o700 });
94
+ secureWindows(current);
95
+ }
96
+ }
97
+ privatePath(absolute, true);
98
+ }
99
+ function readPrivate(file) {
100
+ let fd;
101
+ try {
102
+ privatePath(file, false);
103
+ fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
104
+ const stat = fstatSync(fd);
105
+ if (!stat.isFile() || stat.size > 1048576 || stat.nlink !== 1 || process.platform !== 'win32' && ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.()))
106
+ throw fail();
107
+ return readFileSync(fd);
108
+ }
109
+ catch (error) {
110
+ if (error.code === 'ENOENT')
111
+ return null;
112
+ throw fail();
113
+ }
114
+ finally {
115
+ if (fd !== undefined)
116
+ closeSync(fd);
117
+ }
118
+ }
119
+ function atomic(file, data) {
120
+ if (Buffer.byteLength(data) > 1048576)
121
+ throw fail();
122
+ // Validate existing destination too: replacing a symlink is never accepted.
123
+ readPrivate(file);
124
+ const temp = file + '.' + randomBytes(12).toString('hex');
125
+ let fd;
126
+ try {
127
+ fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
128
+ secureWindows(temp);
129
+ writeFileSync(fd, data);
130
+ fsyncSync(fd);
131
+ closeSync(fd);
132
+ fd = undefined;
133
+ renameSync(temp, file);
134
+ }
135
+ finally {
136
+ if (fd !== undefined)
137
+ closeSync(fd);
138
+ rmSync(temp, { force: true });
139
+ }
140
+ }
141
+ export class NativeCredentialStore {
142
+ root;
143
+ keychain;
144
+ unlock;
145
+ passphrase;
146
+ resolvedRoot;
147
+ get stateRoot() {
148
+ if (!this.resolvedRoot) {
149
+ const root = resolve(this.root);
150
+ this.resolvedRoot = join(trustedAncestors(dirname(root)), basename(root));
151
+ }
152
+ return this.resolvedRoot;
153
+ }
154
+ prepare() { try {
155
+ directory(this.stateRoot);
156
+ directory(this.dir);
157
+ }
158
+ catch {
159
+ throw fail();
160
+ } }
161
+ constructor(root, keychain = new NativeKeychain(), unlock) {
162
+ this.root = root;
163
+ this.keychain = keychain;
164
+ this.unlock = unlock;
165
+ }
166
+ setUnlock(unlock) { this.unlock = unlock; }
167
+ get dir() { return join(this.stateRoot, 'native'); }
168
+ index() {
169
+ this.prepare();
170
+ const raw = readPrivate(join(this.dir, 'index.json'));
171
+ if (!raw)
172
+ return { version: 1, records: {} };
173
+ try {
174
+ const index = strictJson(raw);
175
+ if (index.version !== 1 || !index.records || typeof index.records !== 'object' || Array.isArray(index.records))
176
+ throw Error();
177
+ for (const [key, record] of Object.entries(index.records)) {
178
+ keyName(key);
179
+ if (!record || !/^[a-f0-9]{64}$/.test(record.host) || !['keychain', 'encrypted-file'].includes(record.store))
180
+ throw Error();
181
+ }
182
+ return index;
183
+ }
184
+ catch {
185
+ throw fail();
186
+ }
187
+ }
188
+ async locked(work) {
189
+ this.prepare();
190
+ const file = join(this.dir, 'store.lock');
191
+ let fd;
192
+ try {
193
+ fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
194
+ }
195
+ catch {
196
+ throw fail('CTL_NATIVE_STORE_BUSY');
197
+ }
198
+ try {
199
+ secureWindows(file);
200
+ return await work();
201
+ }
202
+ finally {
203
+ closeSync(fd);
204
+ rmSync(file);
205
+ }
206
+ }
207
+ saveIndex(index) { atomic(join(this.dir, 'index.json'), JSON.stringify(index)); }
208
+ async password() {
209
+ if (this.passphrase !== undefined)
210
+ return this.passphrase;
211
+ if (!this.unlock)
212
+ throw fail('CTL_NATIVE_VAULT_LOCKED');
213
+ const value = await this.unlock();
214
+ if (!value || Buffer.byteLength(value) > 4096)
215
+ throw fail('CTL_NATIVE_VAULT_LOCKED');
216
+ return this.passphrase = value;
217
+ }
218
+ vaultFile(key) { return join(this.dir, keyName(key) + '.vault'); }
219
+ async decrypt(key, raw) {
220
+ try {
221
+ const envelope = strictJson(raw);
222
+ if (Object.keys(envelope).sort().join(',') !== 'cipher,data,kdf,nonce,salt,scope,tag,version' || envelope.version !== 1 || envelope.scope !== key || envelope.kdf !== 'scrypt-32768-8-1' || envelope.cipher !== 'aes-256-gcm' || !/^([a-f0-9]{32})$/.test(envelope.salt) || !/^([a-f0-9]{24})$/.test(envelope.nonce) || !/^([a-f0-9]{32})$/.test(envelope.tag) || typeof envelope.data !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(envelope.data) || Buffer.from(envelope.data, 'base64').toString('base64') !== envelope.data)
223
+ throw Error();
224
+ const password = await this.password();
225
+ const derived = scryptSync(password, Buffer.from(envelope.salt, 'hex'), 32, { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
226
+ try {
227
+ const decipher = createDecipheriv('aes-256-gcm', derived, Buffer.from(envelope.nonce, 'hex'));
228
+ decipher.setAAD(Buffer.from(canonicalize({ version: 1, scope: key, kdf: envelope.kdf, cipher: envelope.cipher, salt: envelope.salt, nonce: envelope.nonce })));
229
+ decipher.setAuthTag(Buffer.from(envelope.tag, 'hex'));
230
+ return Buffer.concat([decipher.update(Buffer.from(envelope.data, 'base64')), decipher.final()]).toString('utf8');
231
+ }
232
+ finally {
233
+ derived.fill(0);
234
+ }
235
+ }
236
+ catch (error) {
237
+ if (error instanceof CtlError && error.code === 'CTL_NATIVE_VAULT_LOCKED')
238
+ throw error;
239
+ this.passphrase = undefined;
240
+ throw fail('CTL_NATIVE_VAULT_INVALID');
241
+ }
242
+ }
243
+ async encrypt(key, value) {
244
+ const salt = randomBytes(16), nonce = randomBytes(12), header = { version: 1, scope: key, kdf: 'scrypt-32768-8-1', cipher: 'aes-256-gcm', salt: salt.toString('hex'), nonce: nonce.toString('hex') };
245
+ const derived = scryptSync(await this.password(), salt, 32, { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
246
+ try {
247
+ const cipher = createCipheriv('aes-256-gcm', derived, nonce);
248
+ cipher.setAAD(Buffer.from(canonicalize(header)));
249
+ const data = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
250
+ return JSON.stringify({ ...header, tag: cipher.getAuthTag().toString('hex'), data: data.toString('base64') });
251
+ }
252
+ finally {
253
+ derived.fill(0);
254
+ }
255
+ }
256
+ async kind(key) { return this.index().records[keyName(key)]?.store; }
257
+ async state(key) {
258
+ try {
259
+ const index = this.index(), record = index.records[keyName(key)];
260
+ if (!record)
261
+ return 'missing';
262
+ if (record.invalid)
263
+ return 'invalid';
264
+ 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';
269
+ }
270
+ catch {
271
+ return 'unavailable';
272
+ }
273
+ }
274
+ async get(key) {
275
+ return this.locked(async () => {
276
+ const record = this.index().records[keyName(key)];
277
+ if (!record)
278
+ return null;
279
+ if (record.invalid)
280
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'Native credential was rejected.', 'Run ctl auth --app <package> in your own terminal.', 2);
281
+ const raw = record.store === 'keychain' ? await this.keychain.get(key) : await (async () => { const bytes = readPrivate(this.vaultFile(key)); if (!bytes)
282
+ throw fail(); return this.decrypt(key, bytes); })();
283
+ if (!raw)
284
+ return null;
285
+ try {
286
+ const value = strictJson(raw);
287
+ if (value.version !== 1 || !['header', 'greader-client-login'].includes(value.kind) || typeof value.verifiedAt !== 'string')
288
+ throw Error();
289
+ validateNativeToken(value.token);
290
+ return value;
291
+ }
292
+ catch {
293
+ throw fail('CTL_NATIVE_VAULT_INVALID');
294
+ }
295
+ });
296
+ }
297
+ async set(key, host, value, store = 'keychain') {
298
+ validateNativeToken(value.token);
299
+ keyName(key);
300
+ keyName(host);
301
+ await this.locked(async () => {
302
+ const index = this.index(), prior = index.records[key];
303
+ const serialized = JSON.stringify(value);
304
+ // Switching backends is explicit reset + enrollment, so no hidden orphan
305
+ // secret can survive a failed cross-store migration or host removal.
306
+ if (prior && prior.store !== store)
307
+ throw new CtlError('CTL_NATIVE_STORE_CHANGE_REQUIRED', 'Reset the local credential before changing its storage backend.', 'Run ctl auth --reset to delete locally, then ctl auth with the desired --store in your own terminal.', 2);
308
+ // Existing ciphertext must authenticate before any replacement.
309
+ if (prior?.store === 'encrypted-file') {
310
+ const raw = readPrivate(this.vaultFile(key));
311
+ if (!raw)
312
+ throw fail();
313
+ await this.decrypt(key, raw);
314
+ }
315
+ if (store === 'keychain')
316
+ await this.keychain.set(key, serialized);
317
+ else {
318
+ const existing = readPrivate(this.vaultFile(key));
319
+ if (existing && !prior)
320
+ await this.decrypt(key, existing);
321
+ atomic(this.vaultFile(key), await this.encrypt(key, serialized));
322
+ }
323
+ index.records[key] = { host, store };
324
+ this.saveIndex(index);
325
+ });
326
+ }
327
+ async invalid(key) { await this.locked(async () => { const index = this.index(); if (index.records[key]) {
328
+ index.records[key].invalid = true;
329
+ this.saveIndex(index);
330
+ } }); }
331
+ async deleteRecord(index, key) { const record = index.records[key]; if (!record)
332
+ return; if (record.store === 'keychain')
333
+ await this.keychain.delete(key);
334
+ else {
335
+ readPrivate(this.vaultFile(key));
336
+ rmSync(this.vaultFile(key), { force: true });
337
+ } delete index.records[key]; }
338
+ async delete(key) { keyName(key); await this.locked(async () => { const index = this.index(); await this.deleteRecord(index, key); this.saveIndex(index); }); }
339
+ async removeHost(host) { keyName(host); await this.locked(async () => { const index = this.index(); for (const [key, record] of Object.entries(index.records))
340
+ if (record.host === host) {
341
+ await this.deleteRecord(index, key);
342
+ this.saveIndex(index);
343
+ } }); }
344
+ }
345
+ export function validateNativeToken(value) {
346
+ if (typeof value !== 'string' || Buffer.byteLength(value) < 1 || Buffer.byteLength(value) > 4096 || /[^\x21-\x7e]/.test(value))
347
+ throw new CtlError('CTL_NATIVE_AUTH_INVALID', 'Native token must be a bounded value without whitespace or control characters.', 'Copy the token again; never pass it in command arguments or chat.', 2);
348
+ }
@@ -0,0 +1,13 @@
1
+ import { type NativeTransfer } from './native-executor.js';
2
+ export interface TransferProgress {
3
+ direction: 'upload' | 'download';
4
+ bytes: number;
5
+ total?: number;
6
+ }
7
+ export interface NativeTransferOptions {
8
+ timeoutMs?: number;
9
+ progress?: (progress: TransferProgress) => void;
10
+ handleSignals?: boolean;
11
+ }
12
+ /** Install only on the human ctl entry. Uses the authenticated transport supplied by B. */
13
+ export declare function createNativeTransfer(options?: NativeTransferOptions): NativeTransfer;