@synopackageland/cli 0.54.5 → 0.54.6

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.54.6 (2026-11-15)
4
+
5
+ - Approval baselines with an SDK inventory read historical approval facts instead of replaying the latest UI and lifecycle formats. Older entry pages without `launch.html` remain comparable; missing facts, inconsistent payload/asset pins and invalid executor task bindings report `APPROVAL_BASELINE_INVALID` with the failing fact.
6
+ - The build-stamped entry runtime writes `meta[name="synopkgland-build"]` before boot. Cached fixed entry HTML can identify the current build without changing its bytes or URL.
7
+
3
8
  ## 0.54.5 (2026-11-15)
4
9
 
5
10
  - The url launcher, a short path to `app` and the mobile `entry` open the fixed entry page as `launch.html`, a file name no earlier build used. Browsers cached the old build-specific `entry.html` as fresh for years (DSM sends package files without Cache-Control and with a 1970 Last-Modified), so after an upgrade the main menu could open the old build. `entry.html` keeps the same fixed content for old links. `inspect` checks both pages and reports a launcher that still points at `entry.html`.
@@ -87,9 +87,15 @@ export async function spkApprovalDiff(current, baseline, report) {
87
87
  if (!baseline)
88
88
  return noApproval(nextReport) ? notRequired() : approvalDiff(undefined, undefined);
89
89
  const next = inventory(nextReport);
90
- const old = await inspectAnySpk(baseline, { baseline: true });
90
+ let old;
91
+ try {
92
+ old = await inspectAnySpk(baseline, { baseline: true });
93
+ }
94
+ catch (error) {
95
+ throw new Error('[APPROVAL_BASELINE_INVALID] Cannot read baseline archive or approval facts: ' + error.message);
96
+ }
91
97
  if (!old.dsm.ok || old.findings.length)
92
- throw new Error('[APPROVAL_BASELINE_INVALID] Baseline SPK failed inspection: ' + [...old.findings, ...old.dsm.errors.map(e => e.message)].join('; '));
98
+ throw new Error('[APPROVAL_BASELINE_INVALID] Baseline approval facts are invalid: ' + [...old.findings, ...old.dsm.errors.map(e => e.message)].join('; '));
93
99
  const diff = old.package === nextReport.package && old.arch === nextReport.arch && noApproval(old) && noApproval(nextReport) ? notRequired() : approvalDiff(inventory(old), next);
94
100
  return resourceDiff(old, nextReport, diff);
95
101
  }
@@ -0,0 +1,6 @@
1
+ import type { SpkInspection } from '../standalone/inspect-spk.js';
2
+ /** Read facts, never replay the current CLI's UI or lifecycle generators on a released package.
3
+ * Archive safety is checked by the caller before this private directory is read.
4
+ * Checksums and executor pins establish consistency, not publisher authenticity.
5
+ */
6
+ export declare function inspectApprovalBaseline(dir: string, payload: SpkInspection['payload']): SpkInspection;
@@ -0,0 +1,153 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { parseDocument } from 'yaml';
5
+ import { parseInfo } from './check-info.js';
6
+ import { Findings } from './findings.js';
7
+ import { inspectExecutor, inspectExecutorAnchor } from '../runtime/executor-inspect.js';
8
+ function object(value) {
9
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
10
+ }
11
+ /** Read facts, never replay the current CLI's UI or lifecycle generators on a released package.
12
+ * Archive safety is checked by the caller before this private directory is read.
13
+ * Checksums and executor pins establish consistency, not publisher authenticity.
14
+ */
15
+ export function inspectApprovalBaseline(dir, payload) {
16
+ const findings = [];
17
+ const result = { signed: existsSync(join(dir, 'syno_signature.asc')), payload, findings, capabilities: [] };
18
+ let fact = 'INFO identity';
19
+ try {
20
+ const infoText = readFileSync(join(dir, 'INFO'), 'utf8');
21
+ const parsed = new Findings();
22
+ const info = Object.fromEntries(parseInfo(infoText, parsed));
23
+ if (parsed.list.length)
24
+ throw Error(parsed.list.map(f => f.message).join('; '));
25
+ for (const key of ['package', 'arch', 'version'])
26
+ if (!info[key])
27
+ throw Error(`missing INFO ${key}`);
28
+ if (!/^[A-Za-z][A-Za-z0-9_]{1,63}$/.test(info.package))
29
+ throw Error('invalid INFO package');
30
+ Object.assign(result, { package: info.package, arch: info.arch, version: info.version });
31
+ fact = 'payload checksum';
32
+ const checksum = createHash('md5').update(readFileSync(join(dir, 'package.tgz'))).digest('hex');
33
+ if (info.checksum?.toLowerCase() !== checksum)
34
+ throw Error('INFO checksum does not match package.tgz');
35
+ fact = 'capability inventory';
36
+ const metadata = readObject(join(dir, 'sdk-package.json'));
37
+ if (metadata.schema !== 2 || !Array.isArray(metadata.capabilities) ||
38
+ metadata.capabilities.some((c) => typeof c !== 'string' || !['files', 'jobs', 'identity', 'rootOps', 'delegate', 'webapi', 'composeMounts'].includes(c)) ||
39
+ new Set(metadata.capabilities).size !== metadata.capabilities.length)
40
+ throw Error('sdk-package.json must contain schema 2 capabilities');
41
+ result.capabilities = metadata.capabilities.map((name) => ({ name, requiresAdminApproval: ['rootOps', 'delegate', 'webapi'].includes(name) }));
42
+ fact = 'recorded entry asset digests';
43
+ for (const name of ['mobile', 'entry_page']) {
44
+ const record = metadata[name];
45
+ if (record === undefined)
46
+ continue;
47
+ if (!object(record) || !object(record.files) || !Object.keys(record.files).length)
48
+ throw Error(`invalid ${name} file inventory`);
49
+ for (const [path, digest] of Object.entries(record.files)) {
50
+ if (!/^(?:[\w~-][\w.~-]*\/)*[\w~-][\w.~-]*$/.test(path) || typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest))
51
+ throw Error(`invalid ${name} file pin`);
52
+ const actual = createHash('sha256').update(readFileSync(join(dir, 'approval-payload/ui/app', path))).digest('hex');
53
+ if (actual !== digest)
54
+ throw Error(`${name} digest mismatch for ${path}`);
55
+ }
56
+ }
57
+ fact = 'package privilege';
58
+ const privilege = readObject(join(dir, 'conf/privilege'));
59
+ if (JSON.stringify(privilege) !== JSON.stringify({ defaults: { 'run-as': 'package' } }))
60
+ throw Error('conf/privilege must contain only defaults.run-as: package');
61
+ fact = 'DSM resource registrations';
62
+ const resources = existsSync(join(dir, 'conf/resource')) ? readObject(join(dir, 'conf/resource')) : undefined;
63
+ const paths = new Set(payload.map(p => p.path));
64
+ // These files/declarations require registrations even if conf/resource was removed.
65
+ if (resources)
66
+ validateResources(resources, paths, dir);
67
+ const web = object(resources?.['web-config']) ? resources['web-config'] : undefined;
68
+ const nginx = object(web?.['nginx-static-config']) ? web['nginx-static-config'].enable : undefined;
69
+ const required = [
70
+ ...(metadata.daemon_ingress ? ['daemon/ingress-nginx.conf'] : []),
71
+ ...(metadata.native_gateway ? ['sso/native-nginx.conf'] : []),
72
+ ...(metadata.short_paths ? ['etc/short-paths-nginx.conf'] : []),
73
+ ];
74
+ for (const path of required)
75
+ if (!Array.isArray(nginx) || !nginx.some(e => object(e) && e.relpath === path))
76
+ throw Error(`missing registration for ${path}`);
77
+ if (paths.has('etc/portal.json') && !web?.['app-portal'])
78
+ throw Error('missing app-portal registration');
79
+ if (resources) {
80
+ result.resources = resources;
81
+ }
82
+ fact = 'executor policy, payload pins and task templates';
83
+ const hasExecutor = result.capabilities.some(c => c.requiresAdminApproval) ||
84
+ payload.some(p => p.path.startsWith('executor/')) || info.synopkgland_executor_sha256 !== undefined;
85
+ if (hasExecutor) {
86
+ const inspected = inspectExecutor(join(dir, 'approval-payload'), info.package, info.arch);
87
+ if (!inspected.executor || inspected.findings.length)
88
+ throw Error(inspected.findings.join('; '));
89
+ const anchor = inspectExecutorAnchor(infoText, inspected.executor.executorDigest);
90
+ if (anchor.length)
91
+ throw Error(anchor.join('; '));
92
+ result.executor = inspected.executor;
93
+ }
94
+ }
95
+ catch (error) {
96
+ if (error.message.startsWith('[SDK_DOWNLOAD_FAILED]'))
97
+ throw error;
98
+ findings.push(`Cannot read approval fact ${fact}: ${error.message}`);
99
+ }
100
+ return result;
101
+ }
102
+ function readObject(path) {
103
+ const text = readFileSync(path, 'utf8');
104
+ const value = JSON.parse(text);
105
+ if (parseDocument(text, { uniqueKeys: true }).errors.length || !object(value))
106
+ throw Error(`${path.split('/').pop()} must be an unambiguous JSON object`);
107
+ return value;
108
+ }
109
+ /** Interpret the shipped registrations, without requiring today's serialization or HTML targets. */
110
+ function validateResources(resources, paths, dir) {
111
+ const allowed = ['web-config', 'data-share', 'systemd-user-unit', 'docker-project', 'webservice', 'video-driver', 'port-config'];
112
+ for (const [worker, value] of Object.entries(resources)) {
113
+ if (!allowed.includes(worker) || !object(value))
114
+ throw Error(`unreadable resource worker ${worker}`);
115
+ if (worker === 'systemd-user-unit' && (!existsSync(join(dir, 'conf/systemd')) || !readdirSync(join(dir, 'conf/systemd')).length))
116
+ throw Error('missing systemd unit inventory');
117
+ }
118
+ const web = resources['web-config'];
119
+ if (object(web)) {
120
+ if (Object.keys(web).some(k => !['app-portal', 'nginx-static-config'].includes(k)))
121
+ throw Error('unknown web-config registration');
122
+ const nginx = web['nginx-static-config'];
123
+ if (nginx !== undefined) {
124
+ if (!object(nginx) || Object.keys(nginx).length !== 1 || !Array.isArray(nginx.enable) || !nginx.enable.length)
125
+ throw Error('invalid nginx-static-config inventory');
126
+ const seen = new Set();
127
+ for (const e of nginx.enable) {
128
+ if (!object(e) || Object.keys(e).length !== 2 || typeof e.type !== 'string' || !['dsm', 'www', 'server'].includes(e.type) || typeof e.relpath !== 'string')
129
+ throw Error('invalid nginx registration');
130
+ const key = `${e.type}:${e.relpath}`;
131
+ if (seen.has(key))
132
+ throw Error('duplicate nginx registration');
133
+ seen.add(key);
134
+ if (e.type === 'www' && !web['app-portal'])
135
+ throw Error('www registration has no app-portal');
136
+ }
137
+ }
138
+ }
139
+ // DSM resource paths must point to files in this package, never another package.
140
+ function references(value) {
141
+ if (!object(value) && !Array.isArray(value))
142
+ return;
143
+ for (const [key, child] of Object.entries(value)) {
144
+ if (key === 'relpath' || key.endsWith('-relpath') || key === 'protocol-file') {
145
+ if (typeof child !== 'string' || !paths.has(child))
146
+ throw Error(`resource ${key} does not name a payload file: ${String(child)}`);
147
+ }
148
+ else
149
+ references(child);
150
+ }
151
+ }
152
+ references(resources);
153
+ }
@@ -4,7 +4,7 @@ export interface SpkReport extends SpkInspection {
4
4
  /** Built by synopkgland, so its build contract (`findings`) was checked too. */
5
5
  synopkgland: boolean;
6
6
  info?: Record<string, string>;
7
- /** The DSM 7 package format rules, checked on every SPK. */
7
+ /** DSM 7 format validation; baseline mode validates historical approval facts instead. */
8
8
  dsm: {
9
9
  ok: boolean;
10
10
  errors: SpkFinding[];
@@ -15,6 +15,13 @@ const CONTAINER_MARKER = "synology-app.yaml";
15
15
  * others are never held to it.
16
16
  */
17
17
  export async function inspectAnySpk(spkPath, options = {}) {
18
+ if (options.baseline) {
19
+ const facts = await readFacts(spkPath);
20
+ if (facts.top.has('sdk-package.json') || facts.payload.some(p => p.path.startsWith('executor/'))) {
21
+ const inspection = await inspectSpk(spkPath, undefined, options);
22
+ return { ...inspection, synopkgland: true, dsm: { ok: inspection.findings.length === 0, errors: [], warnings: [] } };
23
+ }
24
+ }
18
25
  const validation = await validateSpk(spkPath, { sourceMaps: false });
19
26
  const dsm = { ok: validation.ok, errors: validation.errors, warnings: validation.warnings };
20
27
  const facts = await readFacts(spkPath);
@@ -1,4 +1,5 @@
1
1
  import { folderPickerWizardFiles } from '../build-spk/folder-picker.js';
2
+ import { inspectApprovalBaseline } from '../spk/approval-baseline.js';
2
3
  import { parseDsmStrings } from "./dsm-texts.js";
3
4
  import { readTCPListeners } from "./tcp-listeners.js";
4
5
  import { entryRecordProblem, inspectEntryFiles, inspectMobileFiles, mobileRecordProblem } from './mobile.js';
@@ -91,6 +92,15 @@ export async function inspectSpk(spkPath, expectedKind, options = {}) {
91
92
  if (findings.length)
92
93
  return { signed: existsSync(join(dir, 'syno_signature.asc')), payload: [], findings, capabilities: [] };
93
94
  }
95
+ if (options.baseline && (existsSync(join(dir, 'sdk-package.json')) || (await listPayload(join(dir, 'package.tgz'), findings)).some(p => p.path.startsWith('executor/')))) {
96
+ const payload = await listPayload(join(dir, 'package.tgz'), findings);
97
+ const target = join(dir, 'approval-payload');
98
+ mkdirSync(target);
99
+ findings.push(...await extractSpkArchive({ file: join(dir, 'package.tgz'), cwd: target }));
100
+ const baseline = inspectApprovalBaseline(dir, payload);
101
+ baseline.findings.unshift(...findings);
102
+ return baseline;
103
+ }
94
104
  if (!expectedKind && existsSync(join(dir, "native-layout.json"))) {
95
105
  let dependencies;
96
106
  try {
@@ -213,7 +213,7 @@ function attachExecutor(ctx, desktopWebApi) {
213
213
  const loadApp = moduleVersion
214
214
  ? `import(${json(appBundle)})`
215
215
  : `new Promise((resolve,reject)=>{const script=document.createElement('script');script.src=new URL(${json(appBundle)},import.meta.url).href;script.dataset.package=${json(manifest.package)};script.onload=()=>resolve(window.DsmPackageApps?.[${json(manifest.package)}]);script.onerror=reject;document.head.appendChild(script)})`;
216
- const source = `import {bootEntryPage} from ${json(entryModule(manifest))};\n${approval}bootEntryPage({...${json(options)},root:document.querySelector('.dsmapp-root'),mount:async(root,ctx)=>{${approval ? 'attachExecutor(ctx);' : ''}const app=await ${loadApp};if(typeof app?.mount!=='function')throw new Error('The UI must export mount(root, ctx)');return app.mount(root,ctx)}});`;
216
+ const source = `import {bootEntryPage} from ${json(entryModule(manifest))};\n${approval}const buildMeta=document.querySelector('meta[name="synopkgland-build"]')||document.head.appendChild(document.createElement('meta'));buildMeta.name='synopkgland-build';buildMeta.content=${json(version)};\nbootEntryPage({...${json(options)},root:document.querySelector('.dsmapp-root'),mount:async(root,ctx)=>{${approval ? 'attachExecutor(ctx);' : ''}const app=await ${loadApp};if(typeof app?.mount!=='function')throw new Error('The UI must export mount(root, ctx)');return app.mount(root,ctx)}});`;
217
217
  const bundled = await build({ stdin: { contents: source, resolveDir: manifest.root, sourcefile: 'synopkgland-entry.generated.js' }, bundle: true, write: false, format: 'esm', platform: 'browser', target: 'es2022', minify: true, keepNames: true, plugins: [{ name: 'app-import', setup(api) { api.onResolve({ filter: /[?]v=/ }, args => ({ path: args.path, external: true })); } }], legalComments: 'none' });
218
218
  files.set('entry.js', Buffer.from(bundled.outputFiles[0].text));
219
219
  const contextSource = approval
package/docs/app-entry.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # App entry and explicit API registration
2
2
 
3
+ ## Verify the running entry build
4
+
5
+ The entry page's `launch.html` and compatibility `entry.html` stay fixed across
6
+ builds. They fetch `entry.json` with `cache: no-store` and a cache-busting query,
7
+ then load its build-stamped `entry.js?v=...`. That runtime writes the current
8
+ build into `<meta name="synopkgland-build">` before starting sign-in or mounting
9
+ the App, including when the browser uses a previously cached HTML page.
10
+
11
+ In the entry page's browser console, read:
12
+
13
+ ```js
14
+ document.querySelector('meta[name="synopkgland-build"]')?.content
15
+ ```
16
+
17
+ Compare it with `build` in the freshly fetched `entry.json` and the loaded
18
+ `entry.js` request's `v` parameter. A missing marker means the current entry
19
+ runtime has not executed; the marker alone does not prove sign-in or App mount
20
+ succeeded. The fixed HTML source deliberately contains no build value. This
21
+ marker applies to the standalone App entry page, not the shared DSM desktop.
22
+
23
+ ## Admission policy
24
+
3
25
  `entry: admin-only` admits verified DSM administrators before any App handler,
4
26
  including a public route, batch member, streamed response, upload or download.
5
27
  `entry: app-privilege` admits verified sessions allowed by DSM Application
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.54.5",
3
+ "version": "0.54.6",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -35,21 +35,25 @@ then uses the existing PasswordConfirm and exact task readback. Older protected
35
35
  runtimes without diagnostic support show an explicit unknown explanation. No App
36
36
  option supplies an approved baseline or permission claim.
37
37
 
38
- Baseline comparison reads historical wizard files as archived data. It does not
39
- replay the current wizard renderer against them. Archive integrity, package
40
- identity, privilege/resources, lifecycle and executor authority remain checked.
41
- The current SPK receives the normal current-format inspection.
42
-
43
- Baseline resource inspection accepts the exact contracts emitted by released
44
- renderers, including Portal path ingress registered on DSM ports alone. It
45
- checks the archived registration against its declared files and workers; it does
46
- not require a historical App to contain a newly introduced Portal `www` entry.
47
- Current SPKs still require the current resource contract. Extra workers, foreign
48
- paths, duplicate registrations and changes to fixed ingress files remain invalid.
49
- The existing archive, payload checksum, executor digest/INFO anchor, ownership
50
- and lifecycle checks remain in force. Unsigned packages have no cryptographic
51
- provenance for `conf/resource`; compatibility recognizes released contracts, not
52
- a claim about which CLI binary produced them.
38
+ For a baseline with `sdk-package.json`, comparison reads approval facts rather
39
+ than replaying today's UI, wizard or lifecycle generators. Older entry pages
40
+ may lack `launch.html`, and their short-path targets and lifecycle wrappers may
41
+ use historical formats. The current SPK still receives full current-format
42
+ inspection. Baseline errors identify the fact that could not be read.
43
+
44
+ The baseline reader checks archive safety, INFO identity and payload checksum,
45
+ the capability inventory, recorded entry asset digests, package-account
46
+ privilege, resource registrations and their referenced files. Executor packages
47
+ also require the policy, root payload digests, executor pins and INFO anchor,
48
+ and task templates from the recorded SDK. Missing or inconsistent facts fail
49
+ with `APPROVAL_BASELINE_INVALID`. A well-formed historical resource registration
50
+ is compared as shipped; it need not equal today's generated serialization.
51
+ Unknown workers, foreign paths and duplicate nginx registrations are rejected.
52
+
53
+ These checks establish internal consistency, not publisher authenticity. Use
54
+ the trusted, previously released artifact and verify its published hash. In
55
+ particular, lifecycle scripts are outside this approval-fact comparison; use
56
+ the CLI that built a release for its full historical format inspection.
53
57
 
54
58
  JSON `resource_changes` and text `Resource` lines show the old and new DSM
55
59
  registrations. Adding an ingress registration, including `www` for the same