@synopackageland/cli 0.52.7 → 0.52.9

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.
@@ -0,0 +1,173 @@
1
+ package main
2
+
3
+ import (
4
+ "context"
5
+ "errors"
6
+ "github.com/synopackageland/syno-pkg-land-sdk/compose"
7
+ "os"
8
+ "path/filepath"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ func TestProfileEvidence(t *testing.T) {
14
+ if os.Getuid() != 0 {
15
+ t.Skip("root-owned profile evidence")
16
+ }
17
+ d := t.TempDir()
18
+ p := filepath.Join(d, "profile.config")
19
+ if id, e := readProfile(p); e != nil || id != "" {
20
+ t.Fatal(id, e)
21
+ }
22
+ want := strings.Repeat("a", 64)
23
+ for _, raw := range []string{`{}`, `{"id":"short"}`, `{"id":"` + want + `"}{}`, `invalid`} {
24
+ os.WriteFile(p, []byte(raw), 0600)
25
+ if _, e := readProfile(p); e == nil {
26
+ t.Fatal("unknown profile admitted")
27
+ }
28
+ }
29
+ os.WriteFile(p, []byte(`{"id":"`+want+`","private":"never exported"}`), 0600)
30
+ if id, e := readProfile(p); e != nil || id != want {
31
+ t.Fatal(id, e)
32
+ }
33
+ os.Chmod(p, 0666)
34
+ if _, e := readProfile(p); e == nil {
35
+ t.Fatal("writable profile")
36
+ }
37
+ os.Chmod(p, 0600)
38
+ link := filepath.Join(d, "link.config")
39
+ os.Symlink(p, link)
40
+ if _, e := readProfile(link); e == nil {
41
+ t.Fatal("symlink")
42
+ }
43
+ if _, e := readProfile(d); e == nil {
44
+ t.Fatal("directory")
45
+ }
46
+ os.Link(p, filepath.Join(d, "hardlink"))
47
+ if _, e := readProfile(p); e == nil {
48
+ t.Fatal("hardlink")
49
+ }
50
+ }
51
+ func TestContainerOwnership(t *testing.T) {
52
+ a := adapter{owner: compose.WorkerOwner{Package: "ExampleApp", Project: "exampleapp", Path: "/volume1/@appstore/ExampleApp/compose", Services: []string{"web"}}}
53
+ v := compose.WorkerContainer{ID: strings.Repeat("a", 64), State: "exited", Name: "exampleapp-web-1", Project: "exampleapp", Service: "web", WorkingDir: a.owner.Path, ConfigFiles: a.owner.Path + "/docker-compose.yml"}
54
+ if !a.validateContainer(v) {
55
+ t.Fatal("owned")
56
+ }
57
+ for _, edit := range []func(*compose.WorkerContainer){func(v *compose.WorkerContainer) { v.Project = "foreign" }, func(v *compose.WorkerContainer) { v.Name = "foreign" }, func(v *compose.WorkerContainer) { v.WorkingDir += "/../compose" }, func(v *compose.WorkerContainer) { v.Service = "foreign" }, func(v *compose.WorkerContainer) { v.ID = "short" }, func(v *compose.WorkerContainer) { v.ConfigFiles = "/foreign/docker-compose.yml" }} {
58
+ c := v
59
+ edit(&c)
60
+ if a.validateContainer(c) {
61
+ t.Fatal("foreign admitted")
62
+ }
63
+ }
64
+ if got := a.canonical("/var/packages/ExampleApp/target/compose"); got != a.owner.Path {
65
+ t.Fatal(got)
66
+ }
67
+ for _, path := range []string{"/var/packages/OtherApp/target/compose", a.owner.Path + "/../compose"} {
68
+ if a.canonical(path) == a.owner.Path {
69
+ t.Fatal("arbitrary alias admitted")
70
+ }
71
+ }
72
+ }
73
+
74
+ func TestNativeAdapterCallsSDKReconciliation(t *testing.T) {
75
+ if os.Getuid() != 0 {
76
+ t.Skip("root-owned profile evidence")
77
+ }
78
+ for _, mode := range []string{"remove", "refresh", "unknown-write", "foreign", "get-2105", "running", "orphan", "foreign-orphan"} {
79
+ t.Run(mode, func(t *testing.T) {
80
+ root := t.TempDir()
81
+ id := strings.Repeat("a", 64)
82
+ name := "exampleapp-web-1"
83
+ a := adapter{owner: compose.WorkerOwner{Package: "ExampleApp", Project: "exampleapp", Path: "/volume1/@appstore/ExampleApp/compose", Services: []string{"web"}}, id: "owned", profileRoot: root}
84
+ ids := []any{id}
85
+ state := "exited"
86
+ project := "exampleapp"
87
+ writes := []string{}
88
+ if mode == "running" {
89
+ state = "running"
90
+ }
91
+ if mode == "foreign" {
92
+ project = "foreign"
93
+ }
94
+ profile := filepath.Join(root, name+".config")
95
+ if mode != "refresh" {
96
+ os.WriteFile(profile, []byte(`{"id":"`+id+`"}`), 0600)
97
+ }
98
+ oldCall := callAPI
99
+ t.Cleanup(func() { callAPI = oldCall })
100
+ callAPI = func(_ context.Context, apiName, method string, args map[string]any) (map[string]any, error) {
101
+ if apiName == "SYNO.Docker.Project" {
102
+ if mode == "get-2105" {
103
+ return nil, errors.New("2105")
104
+ }
105
+ containers := []any{}
106
+ for range ids {
107
+ containers = append(containers, map[string]any{"Id": id, "Name": "/" + name, "Config": map[string]any{"Labels": map[string]any{"com.docker.compose.project": project, "com.docker.compose.service": "web", "com.docker.compose.project.working_dir": a.owner.Path, "com.docker.compose.project.config_files": a.owner.Path + "/docker-compose.admin.yaml"}}, "State": map[string]any{"Status": state}})
108
+ }
109
+ return map[string]any{"id": "owned", "name": "exampleapp", "path": a.owner.Path, "is_package": true, "containerIds": ids, "containers": containers}, nil
110
+ }
111
+ if apiName != "SYNO.Docker.Container" {
112
+ t.Fatal(apiName)
113
+ }
114
+ if method == "list" {
115
+ if args["type"] != "all" || args["limit"] != -1 || args["offset"] != 0 {
116
+ t.Fatal(args)
117
+ }
118
+ rows := []any{}
119
+ if mode == "foreign-orphan" {
120
+ rows = append(rows, map[string]any{"name": name, "id": strings.Repeat("b", 64)})
121
+ }
122
+ return map[string]any{"containers": rows, "total": float64(len(rows))}, nil
123
+ }
124
+ if args["name"] != name {
125
+ t.Fatal("unowned mutation", args)
126
+ }
127
+ writes = append(writes, method)
128
+ if mode == "unknown-write" {
129
+ return nil, errors.New("private error")
130
+ }
131
+ if method == "delete" {
132
+ if args["force"] != false || args["preserve_profile"] != false {
133
+ t.Fatal(args)
134
+ }
135
+ ids = []any{}
136
+ os.Remove(profile)
137
+ } else if method == "stop" {
138
+ state = "exited"
139
+ os.WriteFile(profile, []byte(`{"id":"`+id+`"}`), 0600)
140
+ } else {
141
+ t.Fatal(method)
142
+ }
143
+ return map[string]any{}, nil
144
+ }
145
+ action := compose.RemoveStoppedWorkerContainers
146
+ if mode == "refresh" {
147
+ action = compose.RefreshWorkerProfiles
148
+ }
149
+ var err error
150
+ if strings.Contains(mode, "orphan") {
151
+ a.snapshot = []compose.WorkerContainer{{ID: id, Name: name}}
152
+ ids = []any{}
153
+ err = a.cleanupOrphans(context.Background())
154
+ } else {
155
+ err = compose.ReconcileWorkerContainers(context.Background(), &a, a.id, a.owner, action)
156
+ }
157
+ switch mode {
158
+ case "remove", "refresh", "orphan":
159
+ if err != nil || len(writes) != 1 {
160
+ t.Fatal(err, writes)
161
+ }
162
+ case "unknown-write":
163
+ if err == nil || len(writes) != 1 || strings.Contains(err.Error(), "private") {
164
+ t.Fatal(err, writes)
165
+ }
166
+ default:
167
+ if err == nil || len(writes) != 0 {
168
+ t.Fatal(err, writes)
169
+ }
170
+ }
171
+ })
172
+ }
173
+ }
@@ -1,11 +1,11 @@
1
- import { sharedFolderCombobox } from './share-combobox.js';
1
+ import { sharedFolderActivation, sharedFolderCombobox } from './share-combobox.js';
2
2
  export function renderDelegateScopeSteps(t) {
3
3
  const box = sharedFolderCombobox(t, 'delegate_share');
4
4
  box.desc = t('label.sharedFolder');
5
5
  const item = box.subitems[0];
6
6
  item.desc = t('label.sharedFolder');
7
7
  item.validator = { allowBlank: true }; // Home works even on a NAS without local shares.
8
- return [{ step_title: t('install.step'), items: [
8
+ return [{ step_title: t('install.step'), activeate: sharedFolderActivation('delegate_share'), items: [
9
9
  { desc: t('consent.appOwnSpace') }, { desc: t('delegate.preselection') },
10
10
  box, { type: 'multiselect', subitems: [{ key: 'delegate_home', desc: t('delegate.home'), defaultValue: false }] },
11
11
  ] }];
@@ -3,6 +3,7 @@ import { type Translate } from "./wizard-i18n.js";
3
3
  export interface InstallWizardStep {
4
4
  step_title: string;
5
5
  items: Array<Record<string, unknown>>;
6
+ activeate?: string;
6
7
  }
7
8
  /** The static JSON wizard per locale, and the dynamic script per locale. */
8
9
  export interface InstallWizardFiles {
@@ -6,3 +6,6 @@ export declare function composeProjectName(packageId: string): string;
6
6
  * needed (and kept, to preserve upgrade behaviour) while a tag is unpinned.
7
7
  */
8
8
  export declare function renderDockerProjectResource(packageId: string, projectPath?: string, forcePull?: boolean, projectNameOverride?: string): Record<string, unknown>;
9
+ /** Accept the previous generator's explicit recreation flag during inspection.
10
+ * Only this known legacy field may differ; new builds always emit false. */
11
+ export declare function matchesComposeWorkerResource(actual: string | undefined, expected: string | undefined): boolean;
@@ -21,7 +21,7 @@ export function renderDockerProjectResource(packageId, projectPath = "compose",
21
21
  path: projectPath,
22
22
  build_params: {
23
23
  force_pull: forcePull,
24
- force_recreate: true,
24
+ force_recreate: false,
25
25
  build: false,
26
26
  },
27
27
  },
@@ -29,3 +29,22 @@ export function renderDockerProjectResource(packageId, projectPath = "compose",
29
29
  },
30
30
  };
31
31
  }
32
+ /** Accept the previous generator's explicit recreation flag during inspection.
33
+ * Only this known legacy field may differ; new builds always emit false. */
34
+ export function matchesComposeWorkerResource(actual, expected) {
35
+ if (actual === expected)
36
+ return true;
37
+ if (!actual || !expected)
38
+ return false;
39
+ try {
40
+ const value = JSON.parse(actual);
41
+ const projects = value['docker-project']?.projects;
42
+ if (!Array.isArray(projects) || projects.length !== 1 || projects[0]?.build_params?.force_recreate !== true)
43
+ return false;
44
+ projects[0].build_params.force_recreate = false;
45
+ return JSON.stringify(value) === expected;
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
@@ -1,3 +1,10 @@
1
1
  import type { Translate } from "./wizard-i18n.js";
2
2
  /** A wizard combobox listing the NAS's Shared Folders (`SYNO.Core.Share list`) into the variable `key`. */
3
3
  export declare function sharedFolderCombobox(t: Translate, key: string): Record<string, unknown>;
4
+ /**
5
+ * DSM's api_store loader unconditionally selects the first record, even with
6
+ * autoSelect: false. Bind the same read-only API store on step activation so
7
+ * loading the list preserves the declared/retained value (or an empty choice).
8
+ * `activeate` is the spelling of the legacy DSM wizard hook.
9
+ */
10
+ export declare function sharedFolderActivation(key: string): string;
@@ -11,17 +11,20 @@ export function sharedFolderCombobox(t, key) {
11
11
  editable: false,
12
12
  forceSelection: true,
13
13
  autoSelect: false,
14
- mode: "remote",
15
- api_store: {
16
- api: "SYNO.Core.Share",
17
- method: "list",
18
- version: 1,
19
- baseParams: { limit: -1, offset: 0 },
20
- root: "shares",
21
- idProperty: "name",
22
- fields: ["name"],
23
- },
14
+ mode: "local",
15
+ triggerAction: "all",
16
+ store: [],
17
+ defaultValue: "",
24
18
  validator: { allowBlank: false },
25
19
  }],
26
20
  };
27
21
  }
22
+ /**
23
+ * DSM's api_store loader unconditionally selects the first record, even with
24
+ * autoSelect: false. Bind the same read-only API store on step activation so
25
+ * loading the list preserves the declared/retained value (or an empty choice).
26
+ * `activeate` is the spelling of the legacy DSM wizard hook.
27
+ */
28
+ export function sharedFolderActivation(key) {
29
+ return `{var field=arguments[0].getForm().findField(${JSON.stringify(key)});if(!field||field.synopkglandShareStore)return;var value=field.getValue();var store=new SYNO.API.JsonStore({api:'SYNO.Core.Share',method:'list',version:1,baseParams:{limit:-1,offset:0},root:'shares',idProperty:'name',fields:['name'],appWindow:arguments[0].owner,autoDestroy:true,autoLoad:false});field.bindStore(store);field.synopkglandShareStore=true;field.setValue(value);store.load();}`;
30
+ }
package/dist/cli.js CHANGED
@@ -361,6 +361,15 @@ async function runCliWithin(argv) {
361
361
  .option("--dry-run", "Print the removal plan without writing to DSM")
362
362
  .option("--json", "Print a single JSON object")
363
363
  .action(async (id, options) => { const { uninstallPackage } = await import('./host/package-commands.js'); const result = await uninstallPackage(id, options); emit('uninstall', result, JSON.stringify(result, null, 2)); });
364
+ program.command("compose-admin-helper")
365
+ .description("Build the administrator-only Compose adapter for a trusted NAS channel")
366
+ .requiredOption("--arch <arch>", "x86_64 or aarch64")
367
+ .requiredOption("--output <path>", "Output native executable")
368
+ .action(async (options) => {
369
+ const { buildComposeAdminHelper } = await import('./host/compose-admin-build.js');
370
+ const result = buildComposeAdminHelper(options.arch, options.output);
371
+ emit('compose-admin-helper', result, JSON.stringify(result, null, 2));
372
+ });
364
373
  program.command("ctl").description("Control registered NAS Apps using described AI commands (ctl --help)");
365
374
  program.command("audit-entry <main>")
366
375
  .description("Audit one custom Go payload's target import graph without executing it")
@@ -57,6 +57,7 @@ export interface InstallWaitOptions {
57
57
  }
58
58
  export declare function waitForInstalledVersion(readState: (remainingMs: number) => InstalledPackageState | undefined | Promise<InstalledPackageState | undefined>, options: InstallWaitOptions): Promise<InstalledPackageState>;
59
59
  export interface UninstallPackageOptions {
60
+ composeProject?: string;
60
61
  dsmOrigin: string;
61
62
  cookieHeader: string;
62
63
  packageId: string;
@@ -2,12 +2,13 @@ import { CtlError } from '../ctl/errors.js';
2
2
  import { readFileSync } from "node:fs";
3
3
  import { progressReporter } from '../terminal-output.js';
4
4
  import { pullContainerImages } from './container-pull.js';
5
+ import { openComposeAdmin, withComposeLifecycleLock, composeAdminConfigured, composeAdminWarning, COMPOSE_ADMIN_GUIDANCE } from './compose-admin.js';
5
6
  import { reclaimOwnedComposeProject } from './compose-project-recovery.js';
6
7
  import { savePullFailure } from './package-diagnostics.js';
7
8
  import { readPackageOperation, operationOwnerAlive, savePackageOperation, clearPackageOperation, releasePackageOperation } from './package-operation.js';
8
9
  import { cancelableInstall, installDelay, installWorkload, installCanceled } from './install-control.js';
9
10
  import { dsmFetch } from "./dsm-http.js";
10
- import { assertDsmCompoundResponse } from "./dsm-compound.js";
11
+ import { assertDsmCompoundResponse, DsmCompoundError } from "./dsm-compound.js";
11
12
  import { dsmRequestTimeoutMs, dsmOperationTimeoutMs, dsmUninstallTimeoutMs, dsmPollIntervalMs, isHostTimeout } from '../nas/timeouts.js';
12
13
  function normalizeDeppkgs(deppkgs) {
13
14
  if (typeof deppkgs === "string") {
@@ -267,12 +268,16 @@ function uninstallFailure(packageId, error) {
267
268
  return failure;
268
269
  }
269
270
  export async function uninstallPackageFromDsm(options) {
271
+ return withComposeLifecycleLock(options.dsmOrigin, options.packageId, () => uninstallPackageLocked(options));
272
+ }
273
+ async function uninstallPackageLocked(options) {
270
274
  const deadline = Date.now() + (options.deadlineMs ?? dsmUninstallTimeoutMs());
271
275
  const requestMs = dsmRequestTimeoutMs(), operationMs = dsmOperationTimeoutMs();
272
276
  const pollMs = options.pollMs ?? dsmPollIntervalMs();
273
277
  const progress = progressReporter(options.onProgress);
274
278
  let phase = 'checking package state';
275
279
  let previousFailure;
280
+ let composeAdmin;
276
281
  const expired = () => new CtlError('DSM_UNINSTALL_TIMEOUT', `Package ${options.packageId}: overall uninstall budget exhausted while ${phase}; DSM may still be stopping/uninstalling.`, 'Check Package Center before retrying; stop/uninstall requests were not replayed');
277
282
  const remaining = (limit) => {
278
283
  if (Date.now() >= deadline)
@@ -335,18 +340,27 @@ export async function uninstallPackageFromDsm(options) {
335
340
  throw new CtlError('PACKAGE_BUSY', `Package ${options.packageId} has an unresolved operation`, 'Wait for DSM to finish before uninstalling');
336
341
  if (before.installed === false)
337
342
  return;
343
+ if (options.composeProject) {
344
+ if (composeAdminConfigured())
345
+ composeAdmin = await openComposeAdmin({ packageId: options.packageId,
346
+ origin: options.dsmOrigin, project: options.composeProject });
347
+ else
348
+ progress(composeAdminWarning(options.packageId));
349
+ }
338
350
  const broken = packageIsBroken(before) && !installInProgress(before);
339
351
  if (broken) {
340
352
  previousFailure = failureDetail(before);
341
- progress(`${options.packageId}: broken package (${previousFailure || before.status}); uninstalling directly without stop…`);
353
+ progress(`${options.packageId}: broken package (${previousFailure || before.status}); ${composeAdmin ? 'verifying stopped Compose containers' : 'uninstalling directly without stop'}…`);
342
354
  }
343
- if (!broken && !packageStatusIsStopped(before)) {
355
+ if ((!broken || composeAdmin) && !packageStatusIsStopped(before)) {
344
356
  phase = 'stopping';
345
357
  await dispatch('SYNO.Core.Package.Control', 'stop');
346
358
  const stopped = await wait(state => state.installed === false || packageStatusIsStopped(state));
347
359
  if (stopped.installed === false)
348
360
  return;
349
361
  }
362
+ if (composeAdmin)
363
+ await composeAdmin.remove();
350
364
  phase = 'uninstalling';
351
365
  await dispatch('SYNO.Core.Package.Uninstallation', 'uninstall');
352
366
  await wait(state => state.installed === false);
@@ -354,6 +368,9 @@ export async function uninstallPackageFromDsm(options) {
354
368
  catch (error) {
355
369
  throw uninstallFailure(options.packageId, error);
356
370
  }
371
+ finally {
372
+ await composeAdmin?.close();
373
+ }
357
374
  }
358
375
  export function catalogInstallationRequests(entry, installed, sid, volumePath) {
359
376
  const install = {
@@ -456,6 +473,9 @@ async function uploadLocalSpk(options, sid, timeoutMs) {
456
473
  return { id: body.data.id, taskId: body.data.task_id };
457
474
  }
458
475
  export async function installPackageFromLocalSpk(options) {
476
+ return withComposeLifecycleLock(options.dsmOrigin, options.packageId, () => installPackageLocked(options));
477
+ }
478
+ async function installPackageLocked(options) {
459
479
  const deadline = options.deadlineMs === undefined ? Infinity : Date.now() + options.deadlineMs;
460
480
  const consumePoll = installWorkload(options.packageId, options.maxPolls);
461
481
  const controller = new AbortController();
@@ -464,6 +484,7 @@ export async function installPackageFromLocalSpk(options) {
464
484
  options = { ...options, signal };
465
485
  let operation;
466
486
  let verified = false;
487
+ let composeAdmin;
467
488
  const requestMs = dsmRequestTimeoutMs(), operationMs = dsmOperationTimeoutMs();
468
489
  const pollMs = options.pollMs ?? dsmPollIntervalMs();
469
490
  const progress = progressReporter(options.onProgress);
@@ -479,6 +500,35 @@ export async function installPackageFromLocalSpk(options) {
479
500
  process.once('SIGTERM', cancel);
480
501
  try {
481
502
  const sid = extractSid(options.cookieHeader);
503
+ const adminEnabled = composeAdminConfigured();
504
+ const profileWorkerFailure = (state) => Boolean(options.composeProject && state?.installed === true && state.version === options.version &&
505
+ !state.state && state.error?.code === 272 && /docker-project/i.test(JSON.stringify(state.error.workerMsg ?? [])));
506
+ const recoveryError = (error, state) => {
507
+ if (!adminEnabled && profileWorkerFailure(state) && error instanceof Error) {
508
+ const detail = failureDetail(state);
509
+ if (!error.message.includes(detail))
510
+ error.message += ` (DSM worker error: ${detail})`;
511
+ error.message += ` ${COMPOSE_ADMIN_GUIDANCE}`;
512
+ if (error instanceof CtlError)
513
+ error.hint += ` ${COMPOSE_ADMIN_GUIDANCE}`;
514
+ }
515
+ return error;
516
+ };
517
+ let recoveryAttempted = false;
518
+ const recoverProfile = async (state) => {
519
+ if (recoveryAttempted || !adminEnabled || !profileWorkerFailure(state))
520
+ return;
521
+ recoveryAttempted = true;
522
+ composeAdmin ??= await openComposeAdmin({ packageId: options.packageId, origin: options.dsmOrigin,
523
+ project: options.composeProject, signal });
524
+ if (!await composeAdmin.refresh())
525
+ return;
526
+ progress(`${options.packageId}: verified worker profile repaired; starting this version once…`);
527
+ await dsmWebApi(options.dsmOrigin, options.cookieHeader, { api: 'SYNO.Core.Package.Control', method: 'start',
528
+ version: '1', id: jsonApiParam(options.packageId), _sid: sid }, { timeoutMs: remaining(operationMs), signal });
529
+ return waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget), { signal, ignoreOperation: true }), { packageId: options.packageId, expectedVersion: options.version, requireRunning: true, repairing: true,
530
+ deadlineMs: Number.isFinite(deadline) ? remaining(Number.MAX_SAFE_INTEGER) : undefined, pollMs, consumePoll, signal, onProgress: progress });
531
+ };
482
532
  let before;
483
533
  while (!before) {
484
534
  consumePoll();
@@ -499,8 +549,39 @@ export async function installPackageFromLocalSpk(options) {
499
549
  throw new CtlError('PACKAGE_BUSY', `Package ${options.packageId} already has an unresolved operation`, 'Check package status before installing again');
500
550
  if (options.composeProject) {
501
551
  phase = 'checking Compose project ownership';
552
+ if (!adminEnabled)
553
+ progress(composeAdminWarning(options.packageId));
502
554
  await reclaimOwnedComposeProject({ ...options, projectName: options.composeProject,
503
- reclaim: !before.installed || packageIsBroken(before), onProgress: progress });
555
+ reclaim: adminEnabled ? false : !before.installed || packageIsBroken(before),
556
+ requireAbsent: adminEnabled && !before.installed, onProgress: progress });
557
+ if (adminEnabled && before.installed) {
558
+ // Capture installed inventory while the native NAS lock is held, before STOP.
559
+ composeAdmin = await openComposeAdmin({ packageId: options.packageId, origin: options.dsmOrigin,
560
+ project: options.composeProject, signal });
561
+ const recovered = await recoverProfile(before);
562
+ if (recovered) {
563
+ verified = true;
564
+ return recovered;
565
+ }
566
+ if (recoveryAttempted)
567
+ throw new CtlError('COMPOSE_WORKER_PROFILE_UNAVAILABLE', 'No verified profile repair was available; package install was not replayed', 'Inspect this App in Container Manager');
568
+ if (!packageStatusIsStopped(before)) {
569
+ phase = 'stopping';
570
+ await dsmWebApi(options.dsmOrigin, options.cookieHeader, { api: 'SYNO.Core.Package.Control',
571
+ method: 'stop', version: '1', id: jsonApiParam(options.packageId), _sid: sid }, { timeoutMs: remaining(operationMs), signal });
572
+ while (true) {
573
+ consumePoll();
574
+ const state = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal, ignoreOperation: true });
575
+ if (packageStatusIsStopped(state))
576
+ break;
577
+ if (state && packageIsBroken(state))
578
+ throw new CtlError('DSM_STOP_FAILED', 'Package stop failed; no containers were removed', 'Check DSM package status');
579
+ await installDelay(Math.min(pollMs, remaining(requestMs)), signal);
580
+ }
581
+ }
582
+ // Broken packages are not assumed stopped: SDK validates every container.
583
+ await composeAdmin.remove();
584
+ }
504
585
  }
505
586
  if (options.containerImages?.length) {
506
587
  phase = 'pulling container images';
@@ -531,17 +612,40 @@ export async function installPackageFromLocalSpk(options) {
531
612
  assertDsmCompoundResponse(response);
532
613
  }
533
614
  catch (error) {
534
- if (!isHostTimeout(error))
615
+ if (!isHostTimeout(error)) {
616
+ if (error instanceof DsmCompoundError && error.api === 'SYNO.Core.Package.Installation' && error.method === 'install') {
617
+ const state = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal, ignoreOperation: true });
618
+ const recovered = await recoverProfile(state);
619
+ if (recovered) {
620
+ verified = true;
621
+ return recovered;
622
+ }
623
+ throw recoveryError(error, state);
624
+ }
535
625
  throw error;
626
+ }
536
627
  timedOut = true;
537
628
  progress(`${options.packageId}: install/upgrade request timed out; DSM may still be installing/starting; checking state…`);
538
629
  }
539
- const completed = await waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget), { signal, ignoreOperation: true }), { packageId: options.packageId, expectedVersion: options.version,
630
+ const waitForCompletion = () => waitForInstalledVersion(budget => fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, Math.min(requestMs, budget), { signal, ignoreOperation: true }), { packageId: options.packageId, expectedVersion: options.version,
540
631
  deadlineMs: Number.isFinite(deadline) ? remaining(Number.MAX_SAFE_INTEGER) : undefined, pollMs, requireRunning: true, consumePoll, signal,
541
632
  // A lost same-version reinstall reply must not accept the old running instance.
542
633
  requireTransition: timedOut && !packageIsBroken(before) && before.installed === true && before.version === options.version,
543
634
  repairing: options.repair && packageIsBroken(before),
544
635
  onProgress: progress });
636
+ let completed;
637
+ try {
638
+ completed = await waitForCompletion();
639
+ }
640
+ catch (error) {
641
+ if (!(error instanceof CtlError) || error.code !== 'DSM_INSTALL_FAILED' || timedOut || !options.composeProject)
642
+ throw error;
643
+ const failed = await fetchInstalledPackageState(options.dsmOrigin, options.cookieHeader, options.packageId, remaining(requestMs), { signal, ignoreOperation: true });
644
+ const recovered = await recoverProfile(failed);
645
+ if (!recovered)
646
+ throw recoveryError(error, failed);
647
+ completed = recovered;
648
+ }
545
649
  verified = true;
546
650
  progress(`${options.packageId}: ${phase} complete (${completed.version}, DSM status ${completed.status})`);
547
651
  return completed;
@@ -552,11 +656,14 @@ export async function installPackageFromLocalSpk(options) {
552
656
  if (isHostTimeout(error)) {
553
657
  if (Date.now() >= deadline)
554
658
  throw installBudgetExpired(options);
659
+ if (phase !== 'uploading')
660
+ throw new CtlError('HOST_TIMEOUT', `Package request timed out while ${phase}; DSM state is unconfirmed`, 'Inspect DSM before retrying; no write was replayed');
555
661
  throw new CtlError('HOST_TIMEOUT', 'SPK upload request timed out; no install request was sent', 'Check the NAS connection and DSM_OPERATION_TIMEOUT_SECONDS before retrying');
556
662
  }
557
663
  throw error;
558
664
  }
559
665
  finally {
666
+ await composeAdmin?.close();
560
667
  process.removeListener('SIGINT', cancel);
561
668
  process.removeListener('SIGTERM', cancel);
562
669
  if (operation) {
@@ -0,0 +1,6 @@
1
+ /** Build the CLI-owned adapter from its locked Go module, never App sources. */
2
+ export declare function buildComposeAdminHelper(arch: string, output: string): {
3
+ sdk: string;
4
+ path: string;
5
+ arch: string;
6
+ };
@@ -0,0 +1,17 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { resolve } from 'node:path';
4
+ import { pinnedGoBuildEnv } from '../build-spk/go-toolchain.js';
5
+ /** Build the CLI-owned adapter from its locked Go module, never App sources. */
6
+ export function buildComposeAdminHelper(arch, output) {
7
+ if (arch !== 'x86_64' && arch !== 'aarch64')
8
+ throw new Error('Compose administrator helper supports x86_64 or aarch64');
9
+ const path = resolve(output);
10
+ const result = spawnSync('go', ['build', '-mod=readonly', '-trimpath', '-buildvcs=false', '-ldflags=-s -w', '-o', path, '.'], {
11
+ cwd: fileURLToPath(new URL('../../assets/go/compose-admin', import.meta.url)),
12
+ env: { ...process.env, ...pinnedGoBuildEnv(arch) }, encoding: 'utf8', timeout: 120_000
13
+ });
14
+ if (result.status !== 0)
15
+ throw new Error('COMPOSE_ADMIN_BUILD_FAILED: ' + (result.stderr || result.error?.message || 'go build failed'));
16
+ return { sdk: '0.53.11', path, arch };
17
+ }
@@ -0,0 +1,22 @@
1
+ export declare const COMPOSE_ADMIN_GUIDANCE = "Configure SYNOPKGLAND_COMPOSE_ADMIN_COMMAND as a JSON argv array for the CLI native helper on this NAS (see docs/compose-admin.md).";
2
+ /** An absent/empty command keeps normal DSM lifecycle behavior. A configured
3
+ * command, including an invalid one, must pass the strict adapter checks. */
4
+ export declare const composeAdminConfigured: (command?: string | undefined) => boolean;
5
+ export declare const composeAdminWarning: (pkg: string) => string;
6
+ export interface ComposeAdminSession {
7
+ remove(): Promise<void>;
8
+ refresh(): Promise<boolean>;
9
+ close(): Promise<void>;
10
+ }
11
+ /** Explicit trusted root channel; never run an App-supplied executable. The
12
+ * configured command receives the origin and package, but no DSM credentials. */
13
+ export declare function openComposeAdmin(options: {
14
+ packageId: string;
15
+ origin: string;
16
+ project?: string;
17
+ command?: string;
18
+ signal?: AbortSignal;
19
+ }): Promise<ComposeAdminSession>;
20
+ /** Excludes CLI races for every package operation. The NAS helper additionally
21
+ * holds its flock across installed inventory capture, stop, reconcile and write. */
22
+ export declare function withComposeLifecycleLock<T>(origin: string, pkg: string, work: () => Promise<T>): Promise<T>;