@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,187 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { ajv } from './descriptor.js';
3
+ import { CtlError } from './errors.js';
4
+ import { strictJson } from './json.js';
5
+ import { nativePath, nativeNetwork } from './native-transport.js';
6
+ import { decodeNative, pointer, project, mismatch, nativeMime, nativeActionToken } from './native-protocol.js';
7
+ export function boundValue(binding, params, actionToken) {
8
+ return 'literal' in binding ? binding.literal : 'param' in binding ? Object.hasOwn(params, binding.param) ? params[binding.param] : undefined : actionToken;
9
+ }
10
+ function encodedSegment(value) {
11
+ if (!['string', 'number', 'boolean'].includes(typeof value))
12
+ throw new CtlError('CTL_NATIVE_PATH_INVALID', 'Path parameter must be a bounded scalar.', 'Check the command parameters.', 3);
13
+ const text = String(value);
14
+ if (!text || text.length > 512 || /[/%\\\x00-\x20\x7f]/.test(text) || text === '.' || text === '..')
15
+ throw new CtlError('CTL_NATIVE_PATH_INVALID', 'Invalid native path segment.', 'Use a single unencoded path segment.', 3);
16
+ return encodeURIComponent(text);
17
+ }
18
+ export function nativeRequest(http, params, actionToken, extraQuery) {
19
+ const path = http.path.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, key) => encodedSegment(params[key]));
20
+ nativePath(path, true);
21
+ if (/[{}]/.test(path))
22
+ throw mismatch();
23
+ const query = new URLSearchParams();
24
+ const append = (target, key, value) => { for (const part of Array.isArray(value) ? value : [value])
25
+ if (part !== undefined)
26
+ target.append(key, String(part)); };
27
+ for (const [key, binding] of Object.entries(http.query ?? {}))
28
+ append(query, key, boundValue(binding, params, actionToken));
29
+ for (const [key, value] of extraQuery ?? []) {
30
+ if (query.has(key))
31
+ throw mismatch();
32
+ query.append(key, value);
33
+ }
34
+ const headers = { ...http.headers };
35
+ let body;
36
+ if (http.body) {
37
+ const fields = Object.fromEntries(Object.entries(http.body.fields).map(([key, binding]) => [key, boundValue(binding, params, actionToken)]).filter(([, value]) => value !== undefined));
38
+ if (http.body.encoding === 'json') {
39
+ body = Buffer.from(JSON.stringify(fields));
40
+ headers['content-type'] = 'application/json';
41
+ }
42
+ else {
43
+ const form = new URLSearchParams();
44
+ for (const [key, value] of Object.entries(fields))
45
+ append(form, key, value);
46
+ body = Buffer.from(form.toString());
47
+ headers['content-type'] = 'application/x-www-form-urlencoded';
48
+ }
49
+ if (body.length > (http.body.encoding === 'form' ? 65536 : 1048576))
50
+ throw new CtlError('CTL_INPUT_TOO_LARGE', 'Native request exceeds its input bound.', 'Reduce the command input.', 3);
51
+ }
52
+ return { method: http.method, path, query, headers, ...(body ? { body } : {}) };
53
+ }
54
+ function validateResult(op, value) { if (op.resultSchema && !ajv.validate(op.resultSchema, value))
55
+ throw mismatch(); }
56
+ export async function executeNative(op, params, http, transport, options = {}) {
57
+ if (!op.http)
58
+ throw mismatch();
59
+ const invoke = async (extraQuery) => {
60
+ const deadline = AbortSignal.timeout(options.timeoutMs ?? 60000), signal = options.signal ? AbortSignal.any([deadline, options.signal]) : deadline;
61
+ const bounded = request => transport({ ...request, signal, timeoutMs: options.timeoutMs });
62
+ const needsAction = Object.values(op.http.body?.fields ?? {}).some(b => 'actionToken' in b);
63
+ const action = needsAction ? await nativeActionToken(http, bounded) : undefined;
64
+ const request = { ...nativeRequest(op.http, params, action, extraQuery), effect: op.effect };
65
+ return decodeNative(await bounded(request), op.http.response, http.limits.maxResponseBytes, op.effect !== 'read');
66
+ };
67
+ if (op.flow.type === 'upload-http' || op.flow.type === 'download-file') {
68
+ if (!options.transfer)
69
+ throw new CtlError('CTL_NATIVE_TRANSFER_UNAVAILABLE', 'Native file transfer support is unavailable.', 'Install a CLI with the native file flow module.', 5);
70
+ return options.transfer(op, params, { http, transport, signal: options.signal });
71
+ }
72
+ if (op.flow.type === 'invoke') {
73
+ const { value } = await invoke();
74
+ validateResult(op, value);
75
+ return value;
76
+ }
77
+ if (op.flow.type === 'paginate-http') {
78
+ const config = op.flow.pagination, items = [], seen = new Set(), pages = new Set();
79
+ let bytes = 0, page = 1, cursor;
80
+ const continuation = (offset = 0) => config.mode === 'page' ? { page, itemOffset: offset } : { cursor: cursor ?? null, itemOffset: offset };
81
+ const incomplete = (reason, offset = 0) => ({ items, incomplete: true, reason, continuation: continuation(offset) });
82
+ for (let count = 0; count < config.maxPages; count++) {
83
+ const query = new URLSearchParams({ [config.sizeParam]: String(config.pageSize) });
84
+ if (config.mode === 'page')
85
+ query.set(config.pageParam, String(page));
86
+ else if (cursor !== undefined)
87
+ query.set(config.cursorParam, cursor);
88
+ const reply = await invoke(query);
89
+ if (bytes + reply.bytes > config.maxBytes)
90
+ return incomplete('maxBytes');
91
+ bytes += reply.bytes;
92
+ const rows = pointer(reply.raw, config.items), next = pointer(reply.raw, config.next);
93
+ if (!Array.isArray(rows))
94
+ throw mismatch();
95
+ const hash = createHash('sha256').update(JSON.stringify(rows)).digest('hex');
96
+ if (rows.length && pages.has(hash))
97
+ return incomplete('no-progress');
98
+ pages.add(hash);
99
+ const remaining = config.maxItems - items.length;
100
+ const accepted = rows.slice(0, remaining);
101
+ if (op.resultSchema?.items)
102
+ for (const row of rows)
103
+ if (!ajv.validate(op.resultSchema.items, row))
104
+ throw mismatch();
105
+ items.push(...accepted);
106
+ if (accepted.length < rows.length)
107
+ return incomplete('maxItems', accepted.length);
108
+ if (next === null || next === '') {
109
+ validateResult(op, items);
110
+ return { items, incomplete: false };
111
+ }
112
+ if (config.mode === 'cursor') {
113
+ if (typeof next !== 'string' || Buffer.byteLength(next) > 4096 || /[\x00-\x1f\x7f]/.test(next))
114
+ throw mismatch();
115
+ if (seen.has(next) || next === cursor)
116
+ return incomplete('duplicate-cursor');
117
+ seen.add(next);
118
+ cursor = next;
119
+ }
120
+ else {
121
+ if (typeof next !== 'string' && typeof next !== 'boolean')
122
+ throw mismatch();
123
+ page++;
124
+ }
125
+ if (rows.length === 0)
126
+ return incomplete('no-progress');
127
+ if (items.length >= config.maxItems)
128
+ return incomplete('maxItems');
129
+ }
130
+ return incomplete('maxPages');
131
+ }
132
+ if (op.flow.type === 'ndjson') {
133
+ const flow = op.flow;
134
+ if (!flow.maxBytes || !flow.maxLineBytes || !flow.maxLines)
135
+ throw mismatch();
136
+ const response = await transport({ ...nativeRequest(op.http, params), signal: options.signal });
137
+ if (!op.http.response.statuses.includes(response.status)) {
138
+ response.body.destroy();
139
+ throw mismatch();
140
+ }
141
+ nativeMime(response, op.http.response.contentTypes);
142
+ const output = [];
143
+ let total = 0, partial = Buffer.alloc(0);
144
+ const line = (bytes) => { if (bytes.length > flow.maxLineBytes)
145
+ throw mismatch(); let raw; try {
146
+ raw = strictJson(bytes);
147
+ }
148
+ catch {
149
+ throw mismatch();
150
+ } const value = project(raw, op.http.response); if (op.resultSchema?.type === 'array') {
151
+ if (!ajv.validate(op.resultSchema.items, value))
152
+ throw mismatch();
153
+ }
154
+ else
155
+ validateResult(op, value); output.push(value); if (output.length > flow.maxLines)
156
+ throw mismatch(); };
157
+ try {
158
+ for await (const chunk of response.body) {
159
+ const bytes = Buffer.from(chunk);
160
+ total += bytes.length;
161
+ if (total > Math.min(flow.maxBytes, op.http.response.maxBytes))
162
+ throw mismatch();
163
+ const data = Buffer.concat([partial, bytes]);
164
+ let start = 0, at;
165
+ while ((at = data.indexOf(10, start)) >= 0) {
166
+ line(data.subarray(start, at));
167
+ start = at + 1;
168
+ }
169
+ partial = Buffer.from(data.subarray(start));
170
+ if (partial.length > flow.maxLineBytes)
171
+ throw mismatch();
172
+ }
173
+ if (partial.length)
174
+ line(partial);
175
+ }
176
+ catch (error) {
177
+ response.body.destroy();
178
+ if (error instanceof CtlError)
179
+ throw error;
180
+ throw nativeNetwork(error, op.effect !== 'read');
181
+ }
182
+ if (op.resultSchema?.type === 'array')
183
+ validateResult(op, output);
184
+ return { items: output };
185
+ }
186
+ throw mismatch();
187
+ }
@@ -0,0 +1,16 @@
1
+ import { CtlError } from './errors.js';
2
+ export declare const TRANSFER_HARD_BYTES: number;
3
+ export declare const OPML_MAX_BYTES: number;
4
+ export declare const FILE_CHUNK_BYTES: number;
5
+ export declare function fileError(code: string, message: string): CtlError;
6
+ export declare function transferLimit(...caps: number[]): number;
7
+ export declare function documentMime(prefix: Buffer): string | undefined;
8
+ /** Bounded UTF-8 lexical admission only; no XML parser or entity resolver is run.
9
+ * Inspect the entire OPML before upload, including declarations after the prefix. */
10
+ export declare class OpmlGuard {
11
+ private decoder;
12
+ private leading;
13
+ private tail;
14
+ private root;
15
+ push(bytes: Uint8Array, final?: boolean): void;
16
+ }
@@ -0,0 +1,57 @@
1
+ import { CtlError } from './errors.js';
2
+ export const TRANSFER_HARD_BYTES = 16 * 1024 ** 3;
3
+ export const OPML_MAX_BYTES = 1024 ** 2;
4
+ export const FILE_CHUNK_BYTES = 32 * 1024;
5
+ export function fileError(code, message) {
6
+ return new CtlError('CTL_NATIVE_' + code, message, 'Check the local file and App state before retrying; no request was replayed.', 5);
7
+ }
8
+ export function transferLimit(...caps) {
9
+ if (caps.some(n => !Number.isSafeInteger(n) || n < 1))
10
+ throw fileError('FILE_BOUND', 'Invalid transfer bound.');
11
+ return Math.min(TRANSFER_HARD_BYTES, ...caps);
12
+ }
13
+ export function documentMime(prefix) {
14
+ if (prefix.subarray(0, 5).equals(Buffer.from('%PDF-')))
15
+ return 'application/pdf';
16
+ if (prefix.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
17
+ return 'image/png';
18
+ if (prefix.length >= 3 && prefix[0] === 255 && prefix[1] === 216 && prefix[2] === 255)
19
+ return 'image/jpeg';
20
+ return undefined;
21
+ }
22
+ /** Bounded UTF-8 lexical admission only; no XML parser or entity resolver is run.
23
+ * Inspect the entire OPML before upload, including declarations after the prefix. */
24
+ export class OpmlGuard {
25
+ decoder = new TextDecoder('utf-8', { fatal: true });
26
+ leading = '';
27
+ tail = '';
28
+ root = false;
29
+ push(bytes, final = false) {
30
+ let text;
31
+ try {
32
+ text = this.decoder.decode(bytes, { stream: !final });
33
+ }
34
+ catch {
35
+ throw fileError('FILE_TYPE', 'OPML must use UTF-8 XML.');
36
+ }
37
+ const scan = this.tail + text;
38
+ if (/<!\s*(?:DOCTYPE|ENTITY)\b/i.test(scan) || scan.includes('\0'))
39
+ throw fileError('FILE_TYPE', 'OPML declarations and external entities are refused.');
40
+ this.tail = scan.slice(-64);
41
+ if (!this.root) {
42
+ this.leading += text;
43
+ const head = this.leading.replace(/^\uFEFF/, '').replace(/^\s*(?:<\?xml\s[^?]*\?>)?\s*(?:<!--[\s\S]*?-->\s*)*/, '');
44
+ const declaration = /^\uFEFF?\s*<\?xml\s([^?]*)\?>/.exec(this.leading);
45
+ if (declaration && /encoding\s*=\s*['"](?!utf-8['"])[^'"]+['"]/i.test(declaration[1]))
46
+ throw fileError('FILE_TYPE', 'OPML must use UTF-8 XML.');
47
+ if (/^<opml(?:\s|\/?>)/.test(head)) {
48
+ this.root = true;
49
+ this.leading = '';
50
+ }
51
+ else if (final || Buffer.byteLength(this.leading) > FILE_CHUNK_BYTES)
52
+ throw fileError('FILE_TYPE', 'Expected an OPML root within the prefix bound.');
53
+ }
54
+ if (final && !this.root)
55
+ throw fileError('FILE_TYPE', 'Expected an OPML root element.');
56
+ }
57
+ }
@@ -0,0 +1,13 @@
1
+ import type { FileHandle } from 'node:fs/promises';
2
+ export declare function openUpload(value: unknown): Promise<{
3
+ handle: FileHandle;
4
+ size: number;
5
+ name: string;
6
+ unchanged(): Promise<void>;
7
+ }>;
8
+ export declare function openDownload(value: unknown): Promise<{
9
+ handle: FileHandle;
10
+ publish(check?: () => void): Promise<void>;
11
+ close(): Promise<void>;
12
+ }>;
13
+ export declare function localFailure(error: unknown): Error;
@@ -0,0 +1,115 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, lstat, link, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, parse, resolve, sep } from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { fileError } from './native-file-types.js';
6
+ import { trustedAncestors } from './native-paths.js';
7
+ function localPath(value) {
8
+ if (typeof value !== 'string' || !value || /[\x00-\x1f\x7f]/.test(value))
9
+ throw fileError('FILE_INVALID', 'A local file path without control characters is required.');
10
+ return resolve(value);
11
+ }
12
+ function same(a, b) { return a.dev === b.dev && a.ino === b.ino; }
13
+ /** Resolve trusted ancestors, then walk canonical directories through held descriptors.
14
+ * Descriptor-relative filesystem aliases are required; unsupported platforms fail closed. */
15
+ async function parent(value) {
16
+ const full = localPath(value), canonicalParent = trustedAncestors(dirname(full)), root = parse(canonicalParent).root;
17
+ const alias = process.platform === 'linux' ? '/proc/self/fd/' : process.platform === 'darwin' ? '/dev/fd/' : undefined;
18
+ if (!alias || !constants.O_NOFOLLOW)
19
+ throw fileError('FILE_PLATFORM', 'Secure descriptor-relative local files are unavailable on this platform.');
20
+ let dir = await open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
21
+ try {
22
+ for (const component of canonicalParent.slice(root.length).split(sep).filter(Boolean)) {
23
+ const next = await open(alias + dir.fd + '/' + component, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
24
+ await dir.close();
25
+ dir = next;
26
+ }
27
+ return { path: alias + dir.fd, name: basename(full), close: () => dir.close() };
28
+ }
29
+ catch (error) {
30
+ await dir.close();
31
+ throw error;
32
+ }
33
+ }
34
+ export async function openUpload(value) {
35
+ let handle;
36
+ try {
37
+ const dir = await parent(value);
38
+ try {
39
+ const path = dir.path + '/' + dir.name, before = await lstat(path, { bigint: true });
40
+ if (!before.isFile())
41
+ throw fileError('FILE_INVALID', 'Upload source must be a regular file without symlinks.');
42
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
43
+ const stat = await handle.stat({ bigint: true });
44
+ if (!stat.isFile() || !same(stat, before))
45
+ throw fileError('FILE_CHANGED', 'Upload source changed while opening.');
46
+ const fd = handle;
47
+ return { handle: fd, size: Number(stat.size), name: dir.name.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 200) || 'upload',
48
+ async unchanged() {
49
+ const after = await fd.stat({ bigint: true });
50
+ if (!same(stat, after) || stat.size !== after.size || stat.mtimeNs !== after.mtimeNs || stat.ctimeNs !== after.ctimeNs)
51
+ throw fileError('FILE_CHANGED', 'Upload source changed; outcome_unknown if dispatched.');
52
+ } };
53
+ }
54
+ finally {
55
+ await dir.close();
56
+ }
57
+ }
58
+ catch (error) {
59
+ await handle?.close();
60
+ throw error;
61
+ }
62
+ }
63
+ export async function openDownload(value) {
64
+ const dir = await parent(value), target = dir.path + '/' + dir.name;
65
+ const partial = dir.path + '/.ctl-partial-' + randomBytes(16).toString('hex');
66
+ let handle;
67
+ try {
68
+ try {
69
+ await lstat(target);
70
+ throw fileError('FILE_EXISTS', 'Download destination already exists.');
71
+ }
72
+ catch (error) {
73
+ if (error.code !== 'ENOENT')
74
+ throw error;
75
+ }
76
+ handle = await open(partial, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
77
+ const fd = handle;
78
+ return { handle: fd,
79
+ async publish(check = () => { }) {
80
+ await fd.sync();
81
+ const [held, named] = await Promise.all([fd.stat({ bigint: true }), lstat(partial, { bigint: true })]);
82
+ if (!named.isFile() || !same(held, named) || held.nlink !== 1n)
83
+ throw fileError('FILE_CHANGED', 'Download partial changed before publication.');
84
+ check();
85
+ // link() is atomic and refuses every existing destination, including symlinks.
86
+ await link(partial, target);
87
+ },
88
+ async close() { try {
89
+ await fd.close();
90
+ }
91
+ finally {
92
+ try {
93
+ await unlink(partial);
94
+ }
95
+ finally {
96
+ await dir.close();
97
+ }
98
+ } } };
99
+ }
100
+ catch (error) {
101
+ await handle?.close();
102
+ await dir.close();
103
+ throw error;
104
+ }
105
+ }
106
+ export function localFailure(error) {
107
+ const code = error?.code;
108
+ if (typeof code === 'string' && code.startsWith('CTL_'))
109
+ return error;
110
+ if (code === 'EEXIST')
111
+ return fileError('FILE_EXISTS', 'Download destination already exists.');
112
+ if (code === 'ENOSPC' || code === 'EDQUOT')
113
+ return fileError('FILE_DISK_FULL', 'Local disk is full; the download was not published.');
114
+ return fileError('FILE_IO', 'Local file access failed; no completed download was published.');
115
+ }
@@ -0,0 +1,10 @@
1
+ import type { NativeDescriptor, NativeInventory, NativeRegistry, NativeInventoryBinding } from './native-types.js';
2
+ export declare const HTTP_INVENTORY_FILE = "synopkgland-http-inventory.json";
3
+ export declare const digest: (value: unknown) => string;
4
+ export declare function nativeRegistry(descriptor: NativeDescriptor): NativeRegistry;
5
+ export declare function nativeBindings(registry: NativeRegistry): Record<string, NativeInventoryBinding>;
6
+ export declare function validateNativeDescriptor(value: any, id: string, version: string): NativeDescriptor;
7
+ export declare function validateNativeArtifacts(descriptor: any, inventory: any): {
8
+ descriptor: NativeDescriptor;
9
+ inventory: NativeInventory;
10
+ };
@@ -0,0 +1,50 @@
1
+ import { canonicalize } from 'json-canonicalize';
2
+ import { createHash } from 'node:crypto';
3
+ import { nativeShape, nativeFeatures } from './native-schemas.js';
4
+ import { validateNativeRegistry } from './native-registry.js';
5
+ import { CtlError } from './errors.js';
6
+ export const HTTP_INVENTORY_FILE = 'synopkgland-http-inventory.json';
7
+ export const digest = (value) => createHash('sha256').update(canonicalize(value)).digest('hex');
8
+ const same = (a, b) => canonicalize(a) === canonicalize(b);
9
+ const fail = () => { throw new CtlError('CTL_DESCRIPTOR_INVALID', 'Native metadata schema, semantics or digest mismatch.', 'Refresh metadata using a matching SDK and CLI.', 5); };
10
+ export function nativeRegistry(descriptor) {
11
+ const { type: _, ...nativeHttp } = descriptor.payload.execution;
12
+ return { format: 'synopkgland.api', version: 3, nativeHttp, operations: descriptor.payload.commands };
13
+ }
14
+ export function nativeBindings(registry) { return Object.fromEntries(Object.entries(registry.operations).map(([name, op]) => [name, { effect: op.effect, permission: op.permission, kind: op.kind, flow: op.flow, http: op.http }])); }
15
+ export function validateNativeDescriptor(value, id, version) {
16
+ if (!nativeShape.descriptor(value))
17
+ fail();
18
+ const d = value, p = d.payload;
19
+ if (p.package.id !== id || p.package.version !== version || p.transport.path !== `/webman/3rdparty/${id}/cgi/api.cgi` || !same(p.features, nativeFeatures()))
20
+ fail();
21
+ const registry = nativeRegistry(d);
22
+ // The frozen describe wire carries no inventory. The SDK handler checks its
23
+ // containment; locally recheck semantics and restrict execution to templates.
24
+ try {
25
+ validateNativeRegistry(registry);
26
+ }
27
+ catch {
28
+ return fail();
29
+ }
30
+ if (p.entry === 'admin-only' && Object.values(p.commands).some(op => op.permission !== 'administrators'))
31
+ fail();
32
+ if (!same(p.bindings, nativeBindings(registry)) || digest(registry) !== p.registrySha256 || digest({ basePath: p.execution.basePath, auth: p.execution.auth, entryPolicyDigest: p.entryPolicyDigest }) !== p.authSha256 || digest({ format: d.format, version: d.version, payload: p }) !== d.sha256)
33
+ fail();
34
+ return d;
35
+ }
36
+ export function validateNativeArtifacts(descriptor, inventory) {
37
+ const d = validateNativeDescriptor(descriptor, descriptor?.payload?.package?.id, descriptor?.payload?.package?.version);
38
+ if (!nativeShape.inventory(inventory))
39
+ fail();
40
+ const i = inventory, p = d.payload;
41
+ if (!same(p.package, i.package) || p.entry !== i.entry || p.entryPolicyDigest !== i.entryPolicyDigest || p.execution.basePath !== i.basePath || p.registrySha256 !== i.registrySha256 || p.authSha256 !== i.authSha256 || !same(p.bindings, i.bindings) || digest(i) !== p.inventorySha256)
42
+ fail();
43
+ try {
44
+ validateNativeRegistry(nativeRegistry(d), { basePath: i.basePath, upstreamAuthPaths: i.upstreamAuthPaths, entry: i.entry });
45
+ }
46
+ catch {
47
+ return fail();
48
+ }
49
+ return { descriptor: d, inventory: i };
50
+ }
@@ -0,0 +1,4 @@
1
+ /** Resolve the longest existing ancestor once, after checking every directory
2
+ * and symlink in its lexical path and link targets. Missing suffixes are retained.
3
+ * Callers must separately enforce no-follow ownership/modes on private leaves. */
4
+ export declare function trustedAncestors(path: string): string;
@@ -0,0 +1,54 @@
1
+ import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
2
+ import { basename, dirname, join, parse, resolve, sep } from 'node:path';
3
+ function owner(stat) { return stat.uid === 0 || stat.uid === process.getuid?.(); }
4
+ function safeDirectory(stat) {
5
+ // Sticky public directories protect entries from other users (the usual tmp
6
+ // directory). Group-writable or non-sticky public directories are unsafe.
7
+ return stat.isDirectory() && owner(stat) && (!(stat.mode & 0o022) || !!(stat.mode & 0o002) && !!(stat.mode & 0o1000));
8
+ }
9
+ const unsafe = () => new Error('Unsafe local ancestor.');
10
+ /** Resolve the longest existing ancestor once, after checking every directory
11
+ * and symlink in its lexical path and link targets. Missing suffixes are retained.
12
+ * Callers must separately enforce no-follow ownership/modes on private leaves. */
13
+ export function trustedAncestors(path) {
14
+ const absolute = resolve(path), missing = [];
15
+ let existing = absolute;
16
+ for (;;) {
17
+ try {
18
+ lstatSync(existing);
19
+ break;
20
+ }
21
+ catch (error) {
22
+ if (error.code !== 'ENOENT' || dirname(existing) === existing)
23
+ throw error;
24
+ missing.unshift(basename(existing));
25
+ existing = dirname(existing);
26
+ }
27
+ }
28
+ if (process.platform === 'win32')
29
+ return join(realpathSync(existing), ...missing);
30
+ let current = parse(existing).root, pending = existing.slice(current.length).split(sep).filter(Boolean), links = 0;
31
+ if (!safeDirectory(lstatSync(current)))
32
+ throw unsafe();
33
+ while (pending.length) {
34
+ const next = join(current, pending.shift()), stat = lstatSync(next);
35
+ if (stat.isSymbolicLink()) {
36
+ // POSIX symlink mode bits are conventionally 0777 and not access controls;
37
+ // check link ownership, its containing directories and resolved target.
38
+ if (!owner(stat) || ++links > 40)
39
+ throw unsafe();
40
+ const target = resolve(current, readlinkSync(next)), root = parse(target).root;
41
+ pending = [...target.slice(root.length).split(sep).filter(Boolean), ...pending];
42
+ current = root;
43
+ }
44
+ else {
45
+ if (!safeDirectory(stat))
46
+ throw unsafe();
47
+ current = next;
48
+ }
49
+ }
50
+ const canonical = realpathSync(existing), held = lstatSync(current), actual = lstatSync(canonical);
51
+ if (canonical !== current || held.dev !== actual.dev || held.ino !== actual.ino || !safeDirectory(actual))
52
+ throw unsafe();
53
+ return join(canonical, ...missing);
54
+ }
@@ -0,0 +1,21 @@
1
+ import { CtlError } from './errors.js';
2
+ import type { NativeHttp, NativeCredential, HttpResponse } from './native-types.js';
3
+ import { type NativeTransport, type NativeResponse } from './native-transport.js';
4
+ export declare function pointer(value: any, path: string): any;
5
+ export declare function mismatch(): CtlError;
6
+ export declare function nativeMime(response: NativeResponse, allowed: string[]): void;
7
+ export declare function project(value: unknown, spec: HttpResponse): unknown;
8
+ export declare function decodeNative(response: NativeResponse, spec: HttpResponse, maxBytes: number, mutation?: boolean): Promise<{
9
+ raw: any;
10
+ value: any;
11
+ bytes: number;
12
+ }>;
13
+ export declare function authorization(http: NativeHttp, record: NativeCredential): string;
14
+ export interface EnrollmentInput {
15
+ token?: string;
16
+ username?: string;
17
+ apiPassword?: string;
18
+ }
19
+ /** Auth replies are private protocol input. Only selected display identity survives. */
20
+ export declare function enrollNative(http: NativeHttp, input: EnrollmentInput, transport: (auth?: string) => NativeTransport): Promise<NativeCredential>;
21
+ export declare function nativeActionToken(http: NativeHttp, transport: NativeTransport): Promise<string>;