@synopackageland/cli 0.47.4 → 0.48.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 (49) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +19 -19
  3. package/assets/go/route-audit/main.go +1 -1
  4. package/assets/init-compose.md +1 -1
  5. package/dist/add.js +10 -0
  6. package/dist/cli.js +9 -1
  7. package/dist/ctl/ai-tools.d.ts +29 -0
  8. package/dist/ctl/ai-tools.js +28 -0
  9. package/dist/ctl/cli.d.ts +5 -2
  10. package/dist/ctl/cli.js +34 -1
  11. package/dist/ctl/descriptor.d.ts +7 -3
  12. package/dist/ctl/descriptor.js +24 -4
  13. package/dist/ctl/generate.d.ts +1 -0
  14. package/dist/ctl/generate.js +16 -0
  15. package/dist/ctl/import-openapi.d.ts +8 -0
  16. package/dist/ctl/import-openapi.js +149 -0
  17. package/dist/ctl/registry.d.ts +47 -0
  18. package/dist/ctl/registry.js +119 -0
  19. package/dist/error-registry.js +6 -3
  20. package/dist/init-upstream.js +3 -2
  21. package/dist/init.js +22 -4
  22. package/dist/runtime/sdk-source.d.ts +1 -1
  23. package/dist/runtime/sdk-source.js +1 -1
  24. package/dist/standalone/api-description-inspect.js +3 -0
  25. package/dist/standalone/api-description.d.ts +6 -1
  26. package/dist/standalone/api-description.js +35 -57
  27. package/dist/standalone/api-permissions.d.ts +3 -1
  28. package/dist/standalone/api-permissions.js +14 -6
  29. package/dist/standalone/bridge-build.js +8 -2
  30. package/dist/standalone/bridge-runtime.d.ts +1 -0
  31. package/dist/standalone/bridge-runtime.js +1 -0
  32. package/dist/standalone/build.js +1 -0
  33. package/dist/standalone/manifest.d.ts +1 -0
  34. package/dist/standalone/manifest.js +17 -3
  35. package/dist/standalone/operation-registry.d.ts +13 -0
  36. package/dist/standalone/operation-registry.js +83 -0
  37. package/docs/ctl-external.md +5 -2
  38. package/package.json +2 -2
  39. package/schema/synopkgland-api-v2.schema.json +504 -0
  40. package/skills/SKILL.md +11 -10
  41. package/skills/reference/compose.md +3 -3
  42. package/skills/reference/create.md +8 -8
  43. package/skills/reference/ctl.md +81 -40
  44. package/skills/reference/files.md +1 -1
  45. package/skills/reference/identity-gateway.md +13 -19
  46. package/skills/reference/identity.md +3 -4
  47. package/skills/reference/install.md +2 -2
  48. package/skills/reference/portal.md +1 -1
  49. package/skills/reference/upstream-fork.md +11 -7
@@ -0,0 +1,47 @@
1
+ import { type Operation } from './descriptor.js';
2
+ export declare const AI_CLASSES: readonly ["read", "preview", "draft", "human-only", "hidden"];
3
+ export type AIClass = typeof AI_CLASSES[number];
4
+ export type RegisteredOperation = Operation & {
5
+ ai: AIClass;
6
+ paramsSchema: Record<string, any>;
7
+ resultSchema: Record<string, any>;
8
+ upstream?: {
9
+ method: string;
10
+ path: string;
11
+ };
12
+ preview?: string;
13
+ longRunning?: boolean;
14
+ };
15
+ /** Unbound source of the synopkgland.api v2 build artifact. Keys are real route names. */
16
+ export interface OperationRegistry {
17
+ format: 'synopkgland.api';
18
+ version: 2;
19
+ operations: Record<string, RegisteredOperation>;
20
+ }
21
+ export declare const INFRASTRUCTURE_METHODS: Set<string>;
22
+ export declare function registryFile(root: string, file: string): string;
23
+ export declare function readRegistry(path: string): OperationRegistry;
24
+ export declare function validateRegistry(value: any): asserts value is OperationRegistry;
25
+ export declare function checkRouteEquality(registry: OperationRegistry, routes: {
26
+ method: string;
27
+ permission: string;
28
+ }[]): void;
29
+ export declare function registryPermissions(registry: OperationRegistry): string;
30
+ export declare function registryTools(registry: OperationRegistry): {
31
+ execution: string;
32
+ preview?: string | undefined;
33
+ name: string;
34
+ description: string;
35
+ inputSchema: Record<string, any>;
36
+ outputSchema: Record<string, any>;
37
+ annotations: {
38
+ readOnlyHint: boolean;
39
+ destructiveHint: boolean;
40
+ openWorldHint: boolean;
41
+ };
42
+ ai: "read" | "preview" | "draft" | "human-only" | "hidden";
43
+ flow: import("./descriptor.js").Flow;
44
+ }[];
45
+ export declare function registryReference(registry: OperationRegistry): string;
46
+ export declare function writeGenerated(path: string, contents: string, check: boolean): void;
47
+ export declare function registryArtifacts(root: string, registry: OperationRegistry, check: boolean): void;
@@ -0,0 +1,119 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
2
+ import { dirname, join, resolve, relative, isAbsolute } from 'node:path';
3
+ import { readBounded, strictJson } from './json.js';
4
+ import { ajv, safeSchema, validateFlow } from './descriptor.js';
5
+ export const AI_CLASSES = ['read', 'preview', 'draft', 'human-only', 'hidden'];
6
+ export const INFRASTRUCTURE_METHODS = new Set(['synopkgland.describe', 'identity.status', 'identity.login', 'identity.session', 'identity.logout']);
7
+ const METHOD = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/;
8
+ export function registryFile(root, file) {
9
+ const path = resolve(root, file), rel = relative(root, path);
10
+ if (!rel || rel.startsWith('..') || isAbsolute(rel))
11
+ throw Error('CTL_REGISTRY_PATH: registry must be inside the packaging directory.');
12
+ return path;
13
+ }
14
+ export function readRegistry(path) {
15
+ const raw = readBounded(path);
16
+ const value = strictJson(raw);
17
+ validateRegistry(value);
18
+ return value;
19
+ }
20
+ export function validateRegistry(value) {
21
+ const fail = (why) => { throw Error('CTL_REGISTRY_INVALID: ' + why); };
22
+ if (!value || value.format !== 'synopkgland.api' || value.version !== 2 || !value.operations || Array.isArray(value.operations) || typeof value.operations !== 'object' || Object.keys(value.operations).length > 1024 || Object.keys(value).some(k => !['format', 'version', 'operations'].includes(k)))
23
+ fail('expected synopkgland.api v2 operations.');
24
+ const bindings = {};
25
+ const paths = new Set();
26
+ for (const [name, op] of Object.entries(value.operations)) {
27
+ if (!METHOD.test(name) || name.length > 128 || INFRASTRUCTURE_METHODS.has(name) || !op || typeof op.summary !== 'string' || !op.summary.trim() || op.summary.length > 1024 || !AI_CLASSES.includes(op.ai))
28
+ fail(`${name}: explicit ai class and English summary are required.`);
29
+ if (!['read', 'write', 'destructive'].includes(op.effect) || !['public', 'authenticated', 'administrators', 'integration'].includes(op.permission))
30
+ fail(`${name}: effect and permission are required.`);
31
+ if (!Array.isArray(op.cli) || !op.cli.length || op.cli.length > 8 || op.cli.some(p => typeof p !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(p)))
32
+ fail(`${name}: invalid cli path.`);
33
+ if (op.ai !== 'hidden') {
34
+ const path = op.cli.join(' ');
35
+ if (paths.has(path))
36
+ fail('duplicate cli path.');
37
+ paths.add(path);
38
+ }
39
+ for (const schema of [op.paramsSchema, op.resultSchema]) {
40
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema))
41
+ fail(`${name}: params/result schemas are required.`);
42
+ safeSchema(schema);
43
+ ajv.compile(schema);
44
+ }
45
+ if (['read', 'preview'].includes(op.ai) && op.effect !== 'read')
46
+ fail(`${name}: read/preview tools must be non-mutating.`);
47
+ if (op.ai === 'draft' && (op.effect === 'read' || !op.preview))
48
+ fail(`${name}: draft writes require a preview operation.`);
49
+ if (op.longRunning && op.flow?.type !== 'job')
50
+ fail(`${name}: long operations require job flow.`);
51
+ if (op.longRunning !== undefined && typeof op.longRunning !== 'boolean')
52
+ fail(`${name}: invalid longRunning.`);
53
+ if (!op.flow || (op.flow.type === 'job' ? op.flow.start : op.flow.method) !== name)
54
+ fail(`${name}: flow must start at its registered method.`);
55
+ bindings[name] = { effect: op.effect, permission: op.permission };
56
+ }
57
+ for (const [name, op] of Object.entries(value.operations)) {
58
+ try {
59
+ if (op.permission === 'integration') {
60
+ if (op.ai !== 'hidden' || op.flow.type !== 'invoke')
61
+ throw Error('integration exposure');
62
+ continue;
63
+ }
64
+ validateFlow(op, bindings);
65
+ const level = { public: 0, authenticated: 1, administrators: 2, integration: 3 };
66
+ for (const method of op.flow.type === 'job' ? [op.flow.start, op.flow.poll, ...(op.flow.result ? [op.flow.result] : [])] : [op.flow.method])
67
+ if (level[op.permission] < level[bindings[method].permission])
68
+ throw Error('permission');
69
+ }
70
+ catch {
71
+ fail(`${name}: invalid flow or missing helper spec.`);
72
+ }
73
+ if (op.preview) {
74
+ const preview = value.operations[op.preview];
75
+ if (!preview || preview.ai !== 'preview' || preview.effect !== 'read')
76
+ fail(`${name}: preview must name a non-mutating preview operation.`);
77
+ }
78
+ }
79
+ }
80
+ export function checkRouteEquality(registry, routes) {
81
+ const names = new Set();
82
+ for (const route of routes) {
83
+ if (names.has(route.method))
84
+ throw Error('CTL_ROUTE_MISMATCH: duplicate route ' + route.method);
85
+ names.add(route.method);
86
+ if (INFRASTRUCTURE_METHODS.has(route.method))
87
+ continue;
88
+ const op = registry.operations[route.method];
89
+ if (!op || op.permission !== route.permission)
90
+ throw Error('CTL_ROUTE_MISMATCH: missing spec or permission mismatch for ' + route.method);
91
+ }
92
+ for (const name of Object.keys(registry.operations))
93
+ if (!names.has(name))
94
+ throw Error('CTL_ROUTE_MISMATCH: no handler for ' + name);
95
+ }
96
+ export function registryPermissions(registry) {
97
+ return JSON.stringify({ schema: 1, default: 'administrators', methods: Object.fromEntries(Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).map(([name, op]) => [name, op.permission])) }, null, 2) + '\n';
98
+ }
99
+ export function registryTools(registry) {
100
+ return Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).filter(([, op]) => ['read', 'preview', 'draft'].includes(op.ai)).map(([name, op]) => ({ name, description: op.summary, inputSchema: op.paramsSchema, outputSchema: op.resultSchema, annotations: { readOnlyHint: op.effect === 'read', destructiveHint: op.effect === 'destructive', openWorldHint: false }, ai: op.ai, flow: op.flow, ...(op.preview ? { preview: op.preview } : {}), execution: op.ai === 'draft' ? 'preview-and-human-confirmation' : 'flow' }));
101
+ }
102
+ export function registryReference(registry) {
103
+ return '<!-- Generated by synopkgland ctl generate; edit the operation registry. -->\n# App operations\n\n' + Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).map(([name, op]) => `## ${name}\n\n${op.summary.replaceAll('<', '&lt;')}\n\nAI: ${op.ai}; effect: ${op.effect}; permission: ${op.permission}; flow: ${op.flow.type}\n\n${op.ai === 'hidden' ? 'No ctl or AI exposure.' : `ctl: \`${op.cli.join(' ')}\``}\n${op.preview ? `\nPreview: \`${op.preview}\`; obtain human confirmation before execution.\n` : ''}`).join('\n');
104
+ }
105
+ export function writeGenerated(path, contents, check) {
106
+ if (check) {
107
+ if (!existsSync(path) || readFileSync(path, 'utf8') !== contents)
108
+ throw Error('CTL_GENERATED_DRIFT: run synopkgland ctl generate.');
109
+ }
110
+ else {
111
+ mkdirSync(dirname(path), { recursive: true });
112
+ writeFileSync(path, contents);
113
+ }
114
+ }
115
+ export function registryArtifacts(root, registry, check) {
116
+ writeGenerated(join(root, 'generated', 'tools.json'), JSON.stringify({ tools: registryTools(registry) }, null, 2) + '\n', check);
117
+ writeGenerated(join(root, 'generated', 'operations.md'), registryReference(registry), check);
118
+ writeGenerated(join(root, 'generated', 'routes.json'), JSON.stringify(Object.fromEntries(Object.entries(registry.operations).sort(([a], [b]) => a.localeCompare(b)).map(([name, op]) => [name, { permission: op.permission, effect: op.effect }])), null, 2) + '\n', check);
119
+ }
@@ -35,13 +35,16 @@ export const ERROR_REGISTRY = {
35
35
  INIT_UPSTREAM_IMAGE_INVALID: { code: "INIT_UPSTREAM_IMAGE_INVALID", description: "The upstream image repository is invalid.", suggestion: "Supply the official repository without a tag or digest; upgrade.sh selects the matching release and resolves its digest." },
36
36
  CTL_APP_NEEDS_APPROVAL: { "code": "CTL_APP_NEEDS_APPROVAL", "description": "The installed App needs approval or re-approval.", "suggestion": "Run synopkgland ctl list --app <package-id> --approve-installed --host <host>." },
37
37
  COMPOSE_HEALTH_REQUIRED: { code: "COMPOSE_HEALTH_REQUIRED", description: "Compose web readiness was not selected.", suggestion: "Set compose.web.health.path and expected 2xx status for the actual App; redirects are not followed." },
38
+ CTL_REGISTRY_REQUIRED: { code: 'CTL_REGISTRY_REQUIRED', description: 'The App needs a single operation registry.', suggestion: 'Replace ctl.commands with ctl.registry and run synopkgland ctl generate.' },
39
+ CTL_REGISTRY_INVALID: { code: 'CTL_REGISTRY_INVALID', description: 'The operation registry is invalid.', suggestion: 'Declare every method with its required ai class, schemas, effect, permission and fixed flow.' },
40
+ CTL_ROUTE_MISMATCH: { code: 'CTL_ROUTE_MISMATCH', description: 'Operation specs and registered handlers differ.', suggestion: 'Match all method names and permissions in both directions, including hidden methods.' },
41
+ CTL_GENERATED_DRIFT: { code: 'CTL_GENERATED_DRIFT', description: 'Generated operation artifacts differ from the registry.', suggestion: 'Run synopkgland ctl generate, then synopkgland ctl generate --check.' },
38
42
  CTL_UNSUPPORTED_BACKEND: { "code": "CTL_UNSUPPORTED_BACKEND", "description": "Automatic descriptions require a native SDK backend.", "suggestion": "Disable ctl for binary/Compose wrappers or implement the public contract separately." },
39
43
  CTL_DESCRIBE_REQUIRED: { "code": "CTL_DESCRIBE_REQUIRED", "description": "The Go backend has no build-only registry exporter.", "suggestion": "Update the native template and implement --describe using api.DescribeRoutes." },
40
44
  CTL_DESCRIBE_FAILED: { "code": "CTL_DESCRIBE_FAILED", "description": "The backend registry export failed.", "suggestion": "Check the backend --describe output and build diagnostics." },
41
- CTL_COMMAND_UNREGISTERED: { "code": "CTL_COMMAND_UNREGISTERED", "description": "A command references an unregistered backend method.", "suggestion": "Correct ctl.commands bindings or register the backend method." },
42
- CTL_DESCRIPTOR_INVALID: { "code": "CTL_DESCRIPTOR_INVALID", "description": "The generated API description violates the public contract.", "suggestion": "Correct ctl.commands and rebuild the private synopkgland-api.json." },
45
+ CTL_DESCRIPTOR_INVALID: { "code": "CTL_DESCRIPTOR_INVALID", "description": "The generated API description violates the public contract.", "suggestion": "Correct ctl.registry, run ctl generate and rebuild the private synopkgland-api.json." },
43
46
  APPROVAL_BASELINE_INVALID: { code: "APPROVAL_BASELINE_INVALID", description: "The --baseline SPK failed inspection, so approval retention cannot be compared.", suggestion: "Pass the previous released SPK of the same package and architecture, unmodified; inspect it to see each finding." },
44
- CTL_DECLARATION_INVALID: { "code": "CTL_DECLARATION_INVALID", "description": "The ctl declaration is invalid.", "suggestion": "Check ctl.enabled, aliases and explicit commands in dsm-package.yaml." },
47
+ CTL_DECLARATION_INVALID: { "code": "CTL_DECLARATION_INVALID", "description": "The ctl declaration is invalid.", "suggestion": "Check ctl.enabled, aliases and ctl.registry in dsm-package.yaml." },
45
48
  ...{
46
49
  LAUNCHER_PORTAL_MISMATCH: {
47
50
  code: "LAUNCHER_PORTAL_MISMATCH",
@@ -47,6 +47,7 @@ export function writeForkScaffold(packaging, template, options) {
47
47
  doc.setIn(['metadata', 'distributor_url'], options.publisherUrl);
48
48
  doc.set('entry', 'admin-only');
49
49
  doc.delete('ctl');
50
+ writeFileSync(join(packaging, 'operations.json'), JSON.stringify({ format: 'synopkgland.api', version: 2, operations: {} }, null, 2) + '\n');
50
51
  if (official) {
51
52
  doc.setIn(['identity_gateway', 'access'], 'dsm-admins');
52
53
  if (!options.from) {
@@ -74,13 +75,13 @@ If you package someone else's open-source project, set maintainer to the origina
74
75
 
75
76
  Keep the upstream fork/history and remote upstream. All wrapper-owned files belong in synology/; never edit upstream files or treat the App as an SDK component. Read synopkgland skill show upstream-fork.
76
77
 
77
- Leave ctl absent from the manifest by default. Ask whether the user wants AI control; add ctl only when explicitly requested. If requested, read synopkgland skill show ctl and produce ctl-plan covering existing UI actions and public API endpoints, including common reads and writes. Status-only commands do not meet completion. Wrap existing native APIs without changing upstream code or inventing features. Long operations must return through existing asynchronous APIs without waiting for completion; report synchronous-only long APIs as blockers for discussion.
78
+ Leave ctl absent from the manifest by default. Inventory upstream APIs with \`synopkgland ctl import-openapi openapi.json --output synology/operations.json\` (or import a handwritten v2 registry); every new entry is hidden. Group discovered APIs by area, recommend a small useful set, and ask the user about each API. Only explicitly approved APIs may be exposed; never use an all-or-nothing opt-in. Keep all specs and adapters in synology/ and reuse the existing external/ingress transport. Add ctl.registry only after implementing the selected adapters, then run ctl generate and ctl generate --check. If requested, read synopkgland skill show ctl and produce ctl-plan covering existing UI actions and public API endpoints, including common reads and writes. Status-only commands do not meet completion. Wrap existing native APIs without changing upstream code or inventing features. Long operations must return through existing asynchronous APIs without waiting for completion; report synchronous-only long APIs as blockers for discussion.
78
79
 
79
80
  Commit the scaffold, then run bash synology/upgrade.sh <upstream-tag> <build-number>. It fetches the exact tag, verifies ancestry/untouched upstream files, merges, derives version/provenance, checks and builds. Commit synology/ before upgrading again. It does not publish or touch a NAS.
80
81
 
81
82
  ${official ? 'Default: use the upstream official image. upgrade.sh updates its release tag and resolves an OCI index/manifest digest through synopkgland images pin, writing only synology/compose.image.yaml. Container Manager downloads that pinned official image at install. Configure upstream-recipe.json repository/service and imageTag: tag (exact upstream tag) or version (strip v only when upstream image naming requires it). Review multi-architecture support and upstream source/license correspondence. The SELECT_UPSTREAM_TAG placeholder must be replaced by a successful upgrade before check/build.' : 'Native App: implement build-source.sh as the native payload hook; it deliberately fails until implemented. Stage official release binaries pinned by SHA-256 (the OpenList route), or compile the merged source with a source build hook. Verify the release digest before staging architecture-specific daemon.targets; keep the SDK management shell separate.'}
82
83
 
83
- Use DSM administrator identity without an additional App password, an OIDC/SSO server or upstream source changes. Prefer supported trusted-header/proxy auth (FreshRSS), otherwise disable upstream login/enable guest behind the administrator-only gateway after a bounded first bootstrap (Uptime Kuma disableAuth). The third shipped pattern is the existing SDK 0.17.3 token adapter: mode: token, access: dsm-admins, entry: admin-only. OpenList obtains its native API token with the unmodified admin token CLI while stopped, stores it package-private 0600 under a 0700 directory, and the gateway injects Authorization server-side after DSM admission; packaging never delivers it to the browser. All DSM admins share one upstream admin; token reset requires package restart; WebDAV keeps its own native credentials. The upstream admin token/settings APIs remain unchanged. Verify actual DSM admission/revocation separately. Use supported config, environment, argv or proxy adapters. Every App lifecycle phase runs as the package UID. For upstream fixed-UID data directories, currently provide a synology/ startup adapter or writable path without root/chown; replace it with the framework ownership mechanism when available. Preserve licenses and the full source/component inventory.
84
+ Use DSM administrator identity without an additional App password, an OIDC/SSO server or upstream source changes. Prefer supported trusted-header/proxy auth (FreshRSS), otherwise disable upstream login/enable guest behind the administrator-only gateway after a bounded first bootstrap (Uptime Kuma disableAuth). The third shipped pattern is the existing SDK token adapter: mode: token, access: dsm-admins, entry: admin-only. OpenList obtains its native API token with the unmodified admin token CLI while stopped, stores it package-private 0600 under a 0700 directory, and the gateway injects Authorization server-side after DSM admission; packaging never delivers it to the browser. All DSM admins share one upstream admin; token reset requires package restart; WebDAV keeps its own native credentials. The upstream admin token/settings APIs remain unchanged. Verify actual DSM admission/revocation separately. Use supported config, environment, argv or proxy adapters. Every App lifecycle phase runs as the package UID. For upstream fixed-UID data directories, currently provide a synology/ startup adapter or writable path without root/chown; replace it with the framework ownership mechanism when available. Preserve licenses and the full source/component inventory.
84
85
  `;
85
86
  writeFileSync(join(packaging, 'AGENTS.md'), readFileSync(join(packaging, 'AGENTS.md'), 'utf8') + guidance);
86
87
  }
package/dist/init.js CHANGED
@@ -226,7 +226,11 @@ export function initFromTemplate(template, targetDir, options = {}) {
226
226
  copyTemplateTree(source, targetDir);
227
227
  for (const file of sharedFiles) {
228
228
  mkdirSync(dirname(join(targetDir, file)), { recursive: true });
229
- cpSync(join(shared, file), join(targetDir, file));
229
+ // Keep one instruction entrypoint, including for wrappers without a registry.
230
+ if (file === "CLAUDE.md")
231
+ writeFileSync(join(targetDir, file), "Read [AGENTS.md](AGENTS.md).\n");
232
+ else
233
+ cpSync(join(shared, file), join(targetDir, file));
230
234
  }
231
235
  for (const overlay of overlays)
232
236
  copyTemplateTree(overlay, targetDir);
@@ -245,12 +249,26 @@ export function initFromTemplate(template, targetDir, options = {}) {
245
249
  const path = join(targetDir, PERMISSIONS_FILE[template]);
246
250
  const policy = JSON.parse(readFileSync(path, "utf8"));
247
251
  // Older template releases relied on the administrator default. Materialize
248
- // their three example routes so the generated registry is explicit.
249
- for (const method of ["app.status", "greeting.get", "greeting.set"]) {
252
+ // their status route so the generated registry is explicit.
253
+ for (const method of existsSync(join(targetDir, "operations.json")) ? ["app.status"] : ["app.status", "greeting.get", "greeting.set"]) {
250
254
  policy.methods[method] ??= "administrators";
251
255
  }
252
256
  Object.assign(policy.methods, capability.permissions);
253
257
  writeFileSync(path, JSON.stringify(policy, null, 2) + "\n");
258
+ const registryPath = join(targetDir, 'operations.json');
259
+ if (existsSync(registryPath)) {
260
+ const registry = JSON.parse(readFileSync(registryPath, 'utf8'));
261
+ for (const overlay of overlays) {
262
+ const patch = join(overlay, 'operations.patch.json');
263
+ if (existsSync(patch))
264
+ Object.assign(registry.operations, JSON.parse(readFileSync(patch, 'utf8')).operations);
265
+ }
266
+ for (const [name, permission] of Object.entries(capability.permissions))
267
+ if (registry.operations[name])
268
+ registry.operations[name].permission = permission;
269
+ writeFileSync(registryPath, JSON.stringify(registry, null, 2) + '\n');
270
+ rmSync(join(targetDir, 'operations.patch.json'), { force: true });
271
+ }
254
272
  }
255
273
  for (const [from, to] of Object.entries(RENAMED)) {
256
274
  if (files.includes(from)) {
@@ -352,7 +370,7 @@ export function initNextSteps(template, dir, frontend, localSdk) {
352
370
  const install = frontend
353
371
  ? ` (cd frontend && npm install${localSdk ? " --install-links" : ""})\n`
354
372
  : "";
355
- return `Next steps:\n cd ${dir}\n (cd backend && ${BACKEND_TESTS[template]})\n${install} synopkgland build\nSee README.md.`;
373
+ return `Next steps:\n cd ${dir}\n (cd backend && ${BACKEND_TESTS[template]})\n${install} synopkgland ctl generate\n synopkgland check\n synopkgland build\nSee README.md.`;
356
374
  }
357
375
  /**
358
376
  * --from replaces the example Compose. The manifest takes the requested (or
@@ -1,7 +1,7 @@
1
1
  export { goPrivateCovers } from './go-env.js';
2
2
  import { type ExecutorManifest } from './sdk-executor-manifest.js';
3
3
  /** Pinned SDK for CLI-owned controllers and Compose planning; App pins take precedence. */
4
- export declare const DEFAULT_SDK_VERSION = "0.46.1";
4
+ export declare const DEFAULT_SDK_VERSION = "0.47.0";
5
5
  export declare const SDK_PACKAGE = "@synopackageland/sdk";
6
6
  export declare const SDK_MODULE = "github.com/synopackageland/syno-pkg-land-sdk";
7
7
  export declare const EXECUTOR_MODULE = "github.com/synopackageland/syno-pkg-land-sdk/executor";
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
  import { readExecutorManifest, predatesExecutorManifest } from './sdk-executor-manifest.js';
7
7
  /** Pinned SDK for CLI-owned controllers and Compose planning; App pins take precedence. */
8
- export const DEFAULT_SDK_VERSION = '0.46.1';
8
+ export const DEFAULT_SDK_VERSION = '0.47.0';
9
9
  export const SDK_PACKAGE = '@synopackageland/sdk';
10
10
  export const SDK_MODULE = 'github.com/synopackageland/syno-pkg-land-sdk';
11
11
  export const EXECUTOR_MODULE = `${SDK_MODULE}/executor`;
@@ -1,9 +1,12 @@
1
+ import { INFRASTRUCTURE_METHODS } from '../ctl/registry.js';
1
2
  import { validateDescriptor } from '../ctl/descriptor.js';
2
3
  export function inspectApiDescription(raw, info, expectedHash, registry) {
3
4
  try {
4
5
  const description = validateDescriptor(JSON.parse(raw), info.id, info.version);
5
6
  if (registry && Object.entries(description.payload.bindings).some(([method, binding]) => !Object.hasOwn(registry, method) || registry[method] !== binding.permission))
6
7
  return ['CTL_COMMAND_BINDING_MISMATCH command method/permission differs from build registry.'];
8
+ if (description.version === 2 && registry && Object.keys(registry).some(name => !INFRASTRUCTURE_METHODS.has(name) && !Object.hasOwn(description.payload.operations, name)))
9
+ return ['CTL_ROUTE_MISMATCH registered route has no operation spec.'];
7
10
  return description.sha256 === expectedHash ? [] : ['CTL_DESCRIPTOR_HASH_MISMATCH API description differs from the build record.'];
8
11
  }
9
12
  catch {
@@ -1,7 +1,12 @@
1
- import { type Descriptor } from '../ctl/descriptor.js';
1
+ import type { Descriptor } from '../ctl/descriptor.js';
2
2
  import { type StandaloneManifest } from './manifest.js';
3
3
  import type { CommandRunner } from './build.js';
4
4
  export declare function buildApiDescription(m: StandaloneManifest, bridgeMethods: string[] | undefined, run: CommandRunner): Promise<{
5
5
  description: Descriptor;
6
6
  registry: Record<string, string>;
7
7
  } | undefined>;
8
+ export declare function describeApiRoutes(m: StandaloneManifest, bridgeMethods: string[] | undefined, run: CommandRunner): Promise<{
9
+ method: string;
10
+ permission: string;
11
+ kind?: string;
12
+ }[]>;
@@ -1,25 +1,54 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { portalByExecutor } from '../build-spk/dsm-version.js';
2
+ import { generateOperations } from './operation-registry.js';
3
+ import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { requiredSdk } from '../runtime/sdk-source.js';
6
+ import { renderBridgeJson } from './bridge-json.js';
2
7
  import { goChildEnv } from '../runtime/go-env.js';
3
- import { makeDescriptor, validateDescriptor, flowMethods } from '../ctl/descriptor.js';
4
8
  import { sdkBackend } from './manifest.js';
5
9
  import { readApiPermissions } from './api-permissions.js';
6
10
  import { isBridgeBackend } from './bridge-backend.js';
7
11
  import { StandaloneBuildError } from './spk.js';
8
12
  import { join } from 'node:path';
9
13
  export async function buildApiDescription(m, bridgeMethods, run) {
10
- if (!m.ctl?.enabled)
14
+ if (!m.ctl)
15
+ return undefined;
16
+ if (m.ctl.registry) {
17
+ const artifact = await generateOperations(m, run, true, bridgeMethods);
18
+ return m.ctl.enabled ? artifact : undefined;
19
+ }
20
+ if (!m.ctl.enabled)
11
21
  return undefined;
12
22
  if (m.backend.kind === 'binary' || m.compose)
13
23
  throw new StandaloneBuildError('CTL_UNSUPPORTED_BACKEND', 'Automatic API descriptions require a standard SDK native App.');
24
+ throw new StandaloneBuildError('CTL_REGISTRY_REQUIRED', 'Replace ctl.commands with ctl.registry and run synopkgland ctl generate.');
25
+ }
26
+ export async function describeApiRoutes(m, bridgeMethods, run) {
27
+ if (m.backend.kind === 'binary')
28
+ throw new StandaloneBuildError('CTL_UNSUPPORTED_BACKEND', 'Registry requires an SDK backend.');
14
29
  let methods;
15
30
  const policy = readApiPermissions(sdkBackend(m), m.capabilities);
16
31
  if (isBridgeBackend(m.backend)) {
17
- methods = [...(bridgeMethods ?? []), ...Object.keys(m.apiPermissions?.methods ?? {}).filter(name => Object.values(policy.sdk).some(group => Object.hasOwn(group, name)))].map(method => ({ method, permission: m.apiPermissions?.methods[method] ?? 'administrators' }));
32
+ const backend = m.backend;
33
+ const work = mkdtempSync(join(tmpdir(), 'synopkgland-registry-'));
34
+ try {
35
+ const actual = bridgeMethods ?? backend.methods ?? (await (await import('./bridge-app.js')).stageScriptApp(m, work)).methods;
36
+ const manifestFile = join(work, 'bridge.json'), permissionsFile = join(work, 'permissions.json');
37
+ writeFileSync(manifestFile, renderBridgeJson(m, actual));
38
+ writeFileSync(permissionsFile, JSON.stringify({ schema: 1, default: 'administrators', methods: Object.fromEntries(Object.entries(policy.policy.methods).filter(([name]) => !Object.values(policy.sdk).some(group => Object.hasOwn(group, name)))) }));
39
+ const response = await run('go', ['run', '-trimpath', '-buildvcs=false', './bridge/cmd/describe', manifestFile, permissionsFile, String(!!m.portal && portalByExecutor(m.os_min_ver))], { cwd: requiredSdk(sdkBackend(m)).goDir, env: goChildEnv({ ...process.env, GOOS: undefined, GOARCH: undefined, GOARM: undefined, CGO_ENABLED: '0' }), capture: true });
40
+ if (response.status !== 0)
41
+ throw new StandaloneBuildError('CTL_DESCRIBE_FAILED', 'SDK bridge registry export failed; use an SDK with operation registry support.');
42
+ methods = JSON.parse(response.stdout ?? '');
43
+ }
44
+ finally {
45
+ rmSync(work, { recursive: true, force: true });
46
+ }
18
47
  }
19
48
  else {
20
49
  if (!readFileSync(join(m.backend.dir, m.backend.main, 'main.go'), 'utf8').includes('--describe'))
21
50
  throw new StandaloneBuildError('CTL_DESCRIBE_REQUIRED', 'Go CGI must support build-only --describe; update its template.');
22
- const flags = [`-X main.packageID=${m.package}`, `-X main.version=${m.spkVersion}`, ...(m.capabilities.files || m.capabilities.delegate ? ['-X main.fileStation=session'] : []), ...(m.portal ? ['-X main.portal=on'] : [])].join(' ');
51
+ const flags = [`-X github.com/synopackageland/syno-pkg-land-sdk/api.expectedEntryMode=${m.entry ?? ''}`, `-X main.packageID=${m.package}`, `-X main.version=${m.spkVersion}`, ...(m.capabilities.files || m.capabilities.delegate ? ['-X main.fileStation=session'] : []), ...(m.portal ? [`-X main.portal=${portalByExecutor(m.os_min_ver) ? 'executor' : 'on'}`] : [])].join(' ');
23
52
  const response = await run('go', ['run', '-trimpath', '-buildvcs=false', '-ldflags', flags, m.backend.main, '--describe'], { cwd: m.backend.dir, env: goChildEnv({ ...process.env, GOOS: undefined, GOARCH: undefined, GOARM: undefined, CGO_ENABLED: '0' }), capture: true });
24
53
  if (response.status !== 0)
25
54
  throw new StandaloneBuildError('CTL_DESCRIBE_FAILED', 'Go route metadata export failed.');
@@ -32,56 +61,5 @@ export async function buildApiDescription(m, bridgeMethods, run) {
32
61
  }
33
62
  if (!Array.isArray(methods) || methods.some(item => typeof item.method !== 'string' || typeof item.permission !== 'string'))
34
63
  throw new StandaloneBuildError('CTL_DESCRIBE_FAILED', 'Invalid registry snapshot.');
35
- const registry = new Map(methods.map(item => [item.method, item.permission]));
36
- const rawHTTP = new Set(methods.filter(item => item.kind === 'http').map(item => item.method));
37
- const nonRPC = new Set(methods.filter(item => item.kind && item.kind !== 'json').map(item => item.method));
38
- // Identity transport routes are outside the business registry but have immutable SDK ownership.
39
- if (m.capabilities.identity) {
40
- registry.set('identity.session', 'public');
41
- registry.set('identity.logout', 'public');
42
- }
43
- const bindings = {};
44
- const commands = {};
45
- if (m.ctl.external) {
46
- if (m.capabilities.identity)
47
- throw new StandaloneBuildError('CTL_EXTERNAL_TRANSPORT', 'External entries require the DSM session transport.');
48
- for (const entry of Object.values(m.ctl.external)) {
49
- if (!entry || typeof entry.method !== 'string' || !registry.has(entry.method) || nonRPC.has(entry.method) || m.entry !== 'admin-only' && registry.get(entry.method) !== 'administrators')
50
- throw new StandaloneBuildError('CTL_EXTERNAL_ENTRY', 'External entries require registered administrator RPC methods.');
51
- registry.set(entry.method, 'administrators');
52
- bindings[entry.method] = { permission: 'administrators', effect: 'destructive' };
53
- }
54
- }
55
- const weights = { read: 0, write: 1, destructive: 2 };
56
- for (const [id, declared] of Object.entries(m.ctl.commands)) {
57
- const command = structuredClone(declared);
58
- const names = flowMethods(command.flow);
59
- let permission = 'public';
60
- for (const name of names) {
61
- if (rawHTTP.has(name))
62
- throw new StandaloneBuildError('CTL_COMMAND_UNREGISTERED', `Command ${id} references raw HTTP route ${name}; ctl commands require RPC methods.`);
63
- if (!registry.has(name))
64
- throw new StandaloneBuildError('CTL_COMMAND_UNREGISTERED', `Command ${id} references unregistered method ${name}.`);
65
- const effective = m.entry === 'admin-only' ? 'administrators' : registry.get(name);
66
- registry.set(name, effective);
67
- const effect = command.flow.type === 'job' && name !== command.flow.start ? 'read' : command.effect;
68
- const previous = bindings[name];
69
- if (!previous || weights[effect] > weights[previous.effect])
70
- bindings[name] = { permission: effective, effect };
71
- if (effective === 'administrators' || effective === 'authenticated' && permission === 'public')
72
- permission = effective;
73
- }
74
- commands[id] = { ...command, permission };
75
- }
76
- if (m.capabilities.identity) {
77
- for (const method of ['identity.session', 'identity.logout'])
78
- bindings[method] = { permission: 'public', effect: 'write' };
79
- }
80
- const description = makeDescriptor({ package: { id: m.package, version: m.spkVersion, displayName: m.displayname }, aliases: m.ctl.aliases ?? [m.package.toLowerCase()], provenance: { developedBy: m.ctl.developedBy ?? 'unknown', generator: 'synopkgland-cli' }, entry: m.entry ?? 'policy', transport: { path: `/webman/3rdparty/${m.package}/cgi/api.cgi`, auth: m.capabilities.identity ? 'dsm-app-session' : 'dsm-session' }, commands, bindings, ...(m.ctl.external ? { external: m.ctl.external } : {}) });
81
- try {
82
- return { description: validateDescriptor(description, m.package, m.spkVersion), registry: Object.fromEntries(registry) };
83
- }
84
- catch (error) {
85
- throw new StandaloneBuildError('CTL_DESCRIPTOR_INVALID', error.message);
86
- }
64
+ return methods.map(route => m.entry === 'admin-only' && !['identity.status', 'identity.login', 'identity.session', 'identity.logout'].includes(route.method) ? { ...route, permission: 'administrators' } : route);
87
65
  }
@@ -13,7 +13,9 @@ export interface ApiPermissions {
13
13
  methods: Record<string, ApiPermission>;
14
14
  }
15
15
  export declare function parseApiPermissions(raw: Uint8Array): ApiPermissions;
16
- export declare function readApiPermissions(backend: SdkBackend, capabilities?: Capabilities): {
16
+ export declare function readApiPermissions(backend: SdkBackend, capabilities?: Capabilities, operations?: Record<string, {
17
+ permission: ApiPermission;
18
+ }>): {
17
19
  policy: ApiPermissions;
18
20
  digest: string;
19
21
  sdkDigest: string;
@@ -33,16 +33,24 @@ export function parseApiPermissions(raw) {
33
33
  }
34
34
  return value;
35
35
  }
36
- export function readApiPermissions(backend, capabilities = {}) {
36
+ export function readApiPermissions(backend, capabilities = {}, operations) {
37
37
  const file = join(backend.dir, API_PERMISSIONS_FILE[backend.kind]);
38
- const stat = lstatSync(file);
39
- if (!stat.isFile() || stat.size > MAX_PERMISSIONS_BYTES)
40
- throw new Error("permissions must be a regular bounded JSON file");
41
- const raw = readFileSync(file);
42
- const policy = parseApiPermissions(raw);
43
38
  const version = appSdkVersion(backend);
44
39
  const sdkRaw = version ? readFileSync(join(sdkSource(version).goDir, SDK_PERMISSIONS_FILE)) : Buffer.from("{}");
45
40
  const sdk = JSON.parse(sdkRaw.toString("utf8"));
41
+ const sdkNames = new Set(Object.values(sdk).flatMap(group => Object.keys(group)));
42
+ let raw;
43
+ if (operations) {
44
+ const methods = Object.fromEntries(Object.entries(operations).filter(([name]) => !sdkNames.has(name)).sort(([a], [b]) => a.localeCompare(b)).map(([name, op]) => [name, op.permission]));
45
+ raw = Buffer.from(JSON.stringify({ schema: 1, default: 'administrators', methods }, null, 2) + '\n');
46
+ }
47
+ else {
48
+ const stat = lstatSync(file);
49
+ if (!stat.isFile() || stat.size > MAX_PERMISSIONS_BYTES)
50
+ throw Error('permissions must be a regular bounded JSON file');
51
+ raw = readFileSync(file);
52
+ }
53
+ const policy = parseApiPermissions(raw);
46
54
  for (const methods of Object.values(sdk))
47
55
  for (const method of Object.keys(methods)) {
48
56
  if (Object.hasOwn(policy.methods, method))
@@ -1,4 +1,4 @@
1
- import { copyFileSync, writeFileSync } from "node:fs";
1
+ import { copyFileSync, writeFileSync, readFileSync } from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { API_PERMISSIONS_FILE, readApiPermissions } from "./api-permissions.js";
@@ -58,5 +58,11 @@ function finishApp(m, dir, methods) {
58
58
  if (invalid.length)
59
59
  throw new StandaloneBuildError("STANDALONE_BRIDGE_MANIFEST_INVALID", invalid.join("\n"));
60
60
  writeFileSync(join(dir, BRIDGE_JSON), bridge, { mode: 0o644 });
61
- return { manifest: createHash("sha256").update(bridge).digest("hex"), permissions: permissions.digest };
61
+ let operations;
62
+ if (m.ctl?.enabled && m.ctl.registry) {
63
+ const raw = readFileSync(join(backend.dir, 'synopkgland-operations.json'));
64
+ writeFileSync(join(dir, 'synopkgland-operations.json'), raw);
65
+ operations = createHash('sha256').update(raw).digest('hex');
66
+ }
67
+ return { ...(operations ? { operations } : {}), manifest: createHash("sha256").update(bridge).digest("hex"), permissions: permissions.digest };
62
68
  }
@@ -7,6 +7,7 @@ export declare const RUNTIME_MAIN = "./bridge/cmd/runtime";
7
7
  export interface BridgeDigests {
8
8
  manifest: string;
9
9
  permissions: string;
10
+ operations?: string;
10
11
  }
11
12
  /**
12
13
  * Builds the runtime from the App's SDK release for one architecture, inside
@@ -27,6 +27,7 @@ export async function buildBridgeRuntime(m, arch, work, run, digests) {
27
27
  `-X main.packageID=${m.package}`,
28
28
  `-X main.manifestDigest=${digests.manifest}`,
29
29
  `-X main.permissionsDigest=${digests.permissions}`,
30
+ ...(digests.operations ? [`-X main.operationsDigest=${digests.operations}`] : []),
30
31
  ...(m.portal && portalByExecutor(m.os_min_ver) ? ["-X main.portalMode=executor"] : []),
31
32
  `-X ${SDK_MODULE}/api.expectedSDKPermissionsDigest=${m.apiSDKPermissionsDigest}`,
32
33
  `-X ${SDK_MODULE}/api.expectedPermissionsDigest=${digests.permissions}`,
@@ -274,6 +274,7 @@ async function buildGoCgi(manifest, backend, arch, work, run) {
274
274
  ? [`-X main.fileStation=session`]
275
275
  : []),
276
276
  ...(manifest.entry ? [`-X main.entry=${manifest.entry}`] : []),
277
+ ...(manifest.ctl?.enabled && manifest.ctl.registry ? ["-X main.operationRegistry=on"] : []),
277
278
  ...(manifest.portal
278
279
  ? [
279
280
  `-X main.portal=${portalByExecutor(manifest.os_min_ver) ? "executor" : "on"}`,
@@ -47,6 +47,7 @@ export interface StandaloneI18n {
47
47
  export interface StandaloneManifest {
48
48
  ctl?: {
49
49
  enabled: boolean;
50
+ registry?: string;
50
51
  aliases?: string[];
51
52
  developedBy?: string;
52
53
  commands: Record<string, import("../ctl/descriptor.js").Operation>;
@@ -1,3 +1,4 @@
1
+ import { readRegistry, registryFile } from '../ctl/registry.js';
1
2
  import { gatewayIngressPathProblem, gatewayIngressOwnershipSupported } from './gateway-ingress.js';
2
3
  import { nativeGatewaySdk } from "./native-gateway.js";
3
4
  import { portDefaults } from "./install-ports.js";
@@ -235,7 +236,8 @@ function readManifest(raw, c) {
235
236
  let integrations;
236
237
  if (backend && backend.kind !== "binary") {
237
238
  try {
238
- permissions = readApiPermissions(backend, capabilities);
239
+ const source = isRecord(raw.ctl) && typeof raw.ctl.registry === 'string' ? readRegistry(registryFile(c.root, raw.ctl.registry)) : undefined;
240
+ permissions = readApiPermissions(backend, capabilities, source?.operations);
239
241
  integrations = readIntegrations(raw.integrations, backend, permissions.policy, raw.compose !== undefined, c);
240
242
  }
241
243
  catch (error) {
@@ -537,10 +539,22 @@ function readManifest(raw, c) {
537
539
  (capabilities.rootOps === true && !rootOps)) {
538
540
  return undefined;
539
541
  }
540
- if (raw.ctl !== undefined && (!isRecord(raw.ctl) || typeof raw.ctl.enabled !== "boolean" || raw.ctl.enabled && (!raw.ctl.commands || typeof raw.ctl.commands !== "object"))) {
541
- c.fail("CTL_DECLARATION_INVALID", "ctl requires enabled and explicit commands.");
542
+ if (raw.ctl !== undefined && (!isRecord(raw.ctl) || typeof raw.ctl.enabled !== "boolean" || raw.ctl.enabled && !raw.ctl.registry && (!raw.ctl.commands || typeof raw.ctl.commands !== "object"))) {
543
+ c.fail("CTL_DECLARATION_INVALID", "ctl requires enabled and an operation registry.");
542
544
  return undefined;
543
545
  }
546
+ if (isRecord(raw.ctl) && raw.ctl.registry !== undefined) {
547
+ try {
548
+ if (typeof raw.ctl.registry !== 'string' || raw.ctl.commands !== undefined)
549
+ throw Error('Use ctl.registry without ctl.commands.');
550
+ const registry = readRegistry(registryFile(c.root, raw.ctl.registry));
551
+ raw.ctl.commands = Object.fromEntries(Object.entries(registry.operations).filter(([, op]) => op.ai !== 'hidden'));
552
+ }
553
+ catch (error) {
554
+ c.fail('CTL_REGISTRY_INVALID', error.message);
555
+ return undefined;
556
+ }
557
+ }
544
558
  if (isRecord(raw.ctl) && raw.ctl.external !== undefined) {
545
559
  const external = raw.ctl.external;
546
560
  if (!isRecord(external) || Object.keys(external).length < 1 || Object.keys(external).length > 16 ||
@@ -0,0 +1,13 @@
1
+ import { type Descriptor } from '../ctl/descriptor.js';
2
+ import { type StandaloneManifest } from './manifest.js';
3
+ import type { CommandRunner } from './build.js';
4
+ export declare function operationRegistry(m: StandaloneManifest): import("../ctl/registry.js").OperationRegistry;
5
+ export declare function registryDescriptor(m: StandaloneManifest, registry?: import("../ctl/registry.js").OperationRegistry): Descriptor;
6
+ /** Generation writes metadata only. The exporter constructs routes without running handlers. */
7
+ export declare function generateOperations(m: StandaloneManifest, run: CommandRunner, check?: boolean, bridgeMethods?: string[]): Promise<{
8
+ description: Descriptor;
9
+ registry: {
10
+ 'identity.session'?: string | undefined;
11
+ 'identity.logout'?: string | undefined;
12
+ };
13
+ }>;