@synopackageland/cli 0.48.19 → 0.48.21

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,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.48.21
4
+
5
+ - ctl and MCP return App results and errors exactly as the App sent them; values that match request parameters are no longer replaced with `<redacted>`, so public fields such as `admin` stay intact
6
+ - Diagnostic logs mask only exactly named secret fields
7
+
8
+ ## 0.48.20
9
+
10
+ - Add optional App testing guidance, from fast local unit and ctl registry contracts through local package checks, real-NAS ctl, deterministic UI tests and optional AI steps
11
+ - Include shared test and support files during project initialization while preserving existing files and the App-open smoke
12
+ - Require an explicit AI model profile and default reasoning effort to low; missing settings report the required environment variables instead of selecting a provider silently
13
+
14
+ ### Upgrading
15
+
16
+ AI steps using `magpieAgent()` or `e2eAgent()` now require `E2E_LLM_BASE_URL`, `E2E_LLM_MODEL` and either `E2E_LLM_API_KEY` or `E2E_LLM_API_KEY_FILE` (a private mode-600 key file). Set them in the test process environment or an untracked environment file before running AI steps. `E2E_LLM_REASONING_EFFORT` is optional and defaults to `low`. No endpoint, model or key is supplied automatically; non-AI tests need no AI profile.
17
+
3
18
  ## 0.48.19
4
19
 
5
20
  - Skill documents multi-user Apps: administrator scope confirmation first, each user's home as the default destination root with relative subfolders created as that user, and a `SYNO.Core.User.Home` check with a reminder when user home is off
@@ -5,7 +5,6 @@ import { CtlStore } from './store.js';
5
5
  import { CtlClient } from './service.js';
6
6
  import { canonicalOrigin, createRequest } from './transport.js';
7
7
  import { nasOptions } from '../nas/options.js';
8
- import { SensitiveOutput } from './redaction.js';
9
8
  const LIMIT = 1048576;
10
9
  const PROTOCOL = /^[a-z][a-z0-9-]{0,63}$/;
11
10
  const METHOD = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/;
@@ -110,7 +109,6 @@ export class ExternalClient {
110
109
  if (app.payload.transport.auth !== 'dsm-session')
111
110
  fail('CTL_EXTERNAL_TRANSPORT', 'External callers require the DSM session transport.');
112
111
  const pins = { package: { id: pkg.id, version: pkg.version }, descriptionSha256: app.sha256 };
113
- const output = new SensitiveOutput({ carriers: [session.token, session.cookie, ...session.cookie.split(';').map(part => part.slice(part.indexOf('=') + 1).trim())] }, { type: 'object', properties: { carriers: { writeOnly: true } } });
114
112
  const invoke = async (request) => {
115
113
  await assertCurrent();
116
114
  // The App must verify these pins and revision in its dispatch boundary,
@@ -128,7 +126,7 @@ export class ExternalClient {
128
126
  };
129
127
  const catalog = validateCatalog(await invoke({ protocol, action: 'describe' }));
130
128
  if (input.action === 'describe')
131
- return output.clean(catalog);
129
+ return catalog;
132
130
  if (catalog.revision !== input.revision)
133
131
  fail('CTL_EXTERNAL_REVISION', 'External tool revision changed.');
134
132
  const tool = catalog.tools.find(tool => tool._meta.method === input.method);
@@ -136,12 +134,11 @@ export class ExternalClient {
136
134
  fail('CTL_EXTERNAL_METHOD', 'Method is not an external tool.');
137
135
  if (!ajv.validate(tool.inputSchema, input.arguments))
138
136
  fail('CTL_EXTERNAL_INPUT', 'Arguments do not match the current tool schema.', 3);
139
- const sensitive = new SensitiveOutput(input.arguments, tool.inputSchema);
140
137
  // Exactly one call attempt. Errors, lost replies and invalid results never replay it.
141
138
  const result = await invoke(input);
142
139
  if (!ajv.validate(tool.outputSchema, result))
143
140
  fail('CTL_EXTERNAL_RESULT', 'External result does not match its schema.', 5);
144
- return output.clean(sensitive.clean(result, tool.outputSchema));
141
+ return result;
145
142
  }
146
143
  }
147
144
  export async function runExternal(argv, io = {}) {
@@ -1,15 +1,7 @@
1
1
  import type { Descriptor, Operation } from './descriptor.js';
2
- import { CtlError } from './errors.js';
3
2
  type Schema = Record<string, any> | boolean | undefined;
4
3
  export declare const REDACTED = "<redacted>";
5
4
  export declare function redactValue<T>(value: T, schema: Schema, root?: Schema, onSecret?: (value: unknown) => void): T;
6
5
  export declare function publicOperation(operation: Operation): Operation;
7
6
  export declare function publicDescriptor(description: Descriptor): Descriptor;
8
- export declare class SensitiveOutput {
9
- private readonly secrets;
10
- constructor(params: unknown, schema: Schema);
11
- private remember;
12
- clean<T>(value: T, schema?: Schema): T;
13
- error(error: unknown): CtlError;
14
- }
15
7
  export {};
@@ -1,4 +1,3 @@
1
- import { CtlError, ctlError } from './errors.js';
2
1
  import { schemaPattern } from './pattern.js';
3
2
  export const REDACTED = '<redacted>';
4
3
  function reference(root, ref) {
@@ -150,68 +149,3 @@ export function publicDescriptor(description) {
150
149
  commands: Object.fromEntries(Object.entries(description.payload.commands).map(([id, operation]) => [id, publicOperation(operation)])),
151
150
  } };
152
151
  }
153
- // Redact copies of known secret values even when an App repeats them in a result
154
- // under another key, a job ID, or an error string. Requests keep their originals.
155
- export class SensitiveOutput {
156
- secrets = new Set();
157
- constructor(params, schema) { redactValue(params, schema, schema, value => this.remember(value)); }
158
- remember(value) {
159
- if (typeof value === 'string') {
160
- if (!value || value === REDACTED)
161
- return;
162
- this.secrets.add(value);
163
- this.secrets.add(encodeURIComponent(value));
164
- try {
165
- const url = new URL(value);
166
- if (['http:', 'https:'].includes(url.protocol)) {
167
- for (const part of [url.username, url.password, ...url.searchParams.values()])
168
- if (part)
169
- this.secrets.add(part);
170
- }
171
- }
172
- catch { /* Not a URL. */ }
173
- }
174
- else if (value && typeof value === 'object') {
175
- for (const [key, child] of Object.entries(value)) {
176
- if (!Array.isArray(value))
177
- this.remember(key);
178
- this.remember(child);
179
- }
180
- }
181
- else if (value !== undefined && value !== null)
182
- this.secrets.add(String(value));
183
- }
184
- clean(value, schema) {
185
- const redacted = redactValue(value, schema, schema, secret => this.remember(secret));
186
- const secrets = [...this.secrets].sort((a, b) => b.length - a.length);
187
- const text = (input) => {
188
- if (input === REDACTED)
189
- return input;
190
- // Keep replacements separate from remaining text. This also handles large
191
- // upload/base64 values without compiling them into a regular expression.
192
- let parts = [input];
193
- for (const secret of secrets)
194
- parts = parts.flatMap(part => {
195
- if (part === null)
196
- return [null];
197
- return part.split(secret).flatMap((chunk, index) => index ? [null, chunk] : [chunk]);
198
- });
199
- return parts.map(part => part === null ? REDACTED : part).join('');
200
- };
201
- const walk = (input) => {
202
- if (typeof input === 'string')
203
- return text(input);
204
- if (Array.isArray(input))
205
- return input.map(walk);
206
- if (input && typeof input === 'object')
207
- return Object.fromEntries(Object.entries(input).map(([key, child]) => [this.secrets.has(key) ? REDACTED : key, walk(child)]));
208
- return input !== null && this.secrets.has(String(input)) ? REDACTED : input;
209
- };
210
- return walk(redacted);
211
- }
212
- error(error) {
213
- const original = ctlError(error);
214
- const safe = this.clean({ message: original.message, hint: original.hint, allowed: original.allowed, plan: original.plan });
215
- return new CtlError(original.code, safe.message, safe.hint, original.exitCode, safe.allowed, safe.plan);
216
- }
217
- }
@@ -2,7 +2,6 @@ import { CtlError, ctlError, errorData } from './errors.js';
2
2
  import { APP_COOKIE, CTL_TIMEOUT_MS, createRequest } from './transport.js';
3
3
  import { DESCRIPTION_METHOD, validateDescriptor, ajv } from './descriptor.js';
4
4
  import { runFlow } from './flows.js';
5
- import { SensitiveOutput } from './redaction.js';
6
5
  import { localFile, transferRequest } from './transfers.js';
7
6
  import { selectApp, selectOperation, operationInput, requestPlan, confirmOperation } from './input.js';
8
7
  export async function boundedMap(items, limit, fn) { const output = new Array(items.length); let next = 0; await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => { while (next < items.length) {
@@ -132,52 +131,46 @@ export class CtlClient {
132
131
  const app = this.selectApp(listing, name);
133
132
  const { id, operation } = selectOperation(app, path);
134
133
  const params = operationInput(operation, args, options.stdin, `run: synopkgland ctl ${name} ${operation.cli.join(' ')} --host ${this.host.name} --help`);
135
- const output = new SensitiveOutput(params, operation.paramsSchema);
136
134
  if (operation.flow.type === 'job') {
137
135
  this.until = undefined;
138
136
  this.jobRequestBudget = options.timeoutMs ?? operation.flow.timeoutMs ?? CTL_TIMEOUT_MS;
139
137
  }
138
+ const plan = requestPlan(app, id, params);
139
+ if (operation.flow.type === 'upload')
140
+ localFile(params[operation.flow.fileParam]);
141
+ confirmOperation(operation, !!options.yes, !!options.dryRun, plan);
142
+ if (options.dryRun)
143
+ return { dryRun: true, request: plan };
144
+ const session = await this.store.session(this.host);
145
+ let appSession = session;
146
+ if (app.payload.transport.auth === 'dsm-app-session') {
147
+ const boot = await this.request(app.payload.transport.path, { method: 'identity.session', params: { bootstrap: true } }, session);
148
+ // The transport adapter adds only validated, path-scoped App cookies for this call.
149
+ if (boot?.success !== true)
150
+ throw new CtlError('CTL_APP_SESSION', 'App session bootstrap failed; HTTPS is required.', `run: synopkgland host show ${this.host.name}`, 5);
151
+ appSession = this.appCookieSession(session, boot);
152
+ }
140
153
  try {
141
- const plan = requestPlan(app, id, params);
142
- if (operation.flow.type === 'upload')
143
- localFile(params[operation.flow.fileParam]);
144
- confirmOperation(operation, !!options.yes, !!options.dryRun, plan);
145
- if (options.dryRun)
146
- return { dryRun: true, request: plan };
147
- const session = await this.store.session(this.host);
148
- let appSession = session;
149
- if (app.payload.transport.auth === 'dsm-app-session') {
150
- const boot = await this.request(app.payload.transport.path, { method: 'identity.session', params: { bootstrap: true } }, session);
151
- // The transport adapter adds only validated, path-scoped App cookies for this call.
152
- if (boot?.success !== true)
153
- throw new CtlError('CTL_APP_SESSION', 'App session bootstrap failed; HTTPS is required.', `run: synopkgland host show ${this.host.name}`, 5);
154
- appSession = this.appCookieSession(session, boot);
155
- }
156
- try {
157
- const invoke = async (method, input) => {
158
- if (!app.payload.bindings[method])
159
- throw new CtlError('CTL_METHOD_NOT_ALLOWED', 'Flow method is not allowlisted.', 'Refresh the API description.', 4);
160
- const response = await this.request(app.payload.transport.path, { method, params: input }, appSession, options.signal);
161
- if (response?.success !== true) {
162
- const code = String(response?.error?.code ?? 'invalid_response');
163
- throw new CtlError(['admin_required', 'app_privilege_denied'].includes(code) ? 'CTL_PERMISSION_DENIED' : 'CTL_APP_ERROR', `App rejected operation (${code}).`, 'Check command permissions and App state.', ['admin_required', 'app_privilege_denied'].includes(code) ? 4 : 5);
164
- }
165
- return response.data;
166
- };
167
- const result = await runFlow(operation.flow, params, invoke, { wait: options.wait, signal: options.signal, timeoutMs: this.remaining(options.timeoutMs ?? CTL_TIMEOUT_MS),
168
- ndjson: (method, input) => transferRequest(appSession, app.payload.transport.path, method, input, { trust: this.store.trust(this.host), timeoutMs: this.remaining(options.timeoutMs ?? CTL_TIMEOUT_MS) }),
169
- upload: (method, input, flow) => transferRequest(appSession, app.payload.transport.path, method, {}, { trust: this.store.trust(this.host), timeoutMs: this.remaining(options.timeoutMs ?? CTL_TIMEOUT_MS), file: { path: String(input[flow.fileParam]), parent: String(input[flow.parentParam]), name: String(input[flow.nameParam]) } }) });
170
- if (operation.resultSchema && !ajv.validate(operation.resultSchema, result))
171
- throw new CtlError('CTL_RESPONSE_INVALID', 'Result does not match command schema.', 'Check the App version.', 5);
172
- return output.clean(result, operation.resultSchema);
173
- }
174
- finally {
175
- if (app.payload.transport.auth === 'dsm-app-session')
176
- await this.request(app.payload.transport.path, { method: 'identity.logout', params: {} }, appSession);
177
- }
154
+ const invoke = async (method, input) => {
155
+ if (!app.payload.bindings[method])
156
+ throw new CtlError('CTL_METHOD_NOT_ALLOWED', 'Flow method is not allowlisted.', 'Refresh the API description.', 4);
157
+ const response = await this.request(app.payload.transport.path, { method, params: input }, appSession, options.signal);
158
+ if (response?.success !== true) {
159
+ const code = String(response?.error?.code ?? 'invalid_response');
160
+ throw new CtlError(['admin_required', 'app_privilege_denied'].includes(code) ? 'CTL_PERMISSION_DENIED' : 'CTL_APP_ERROR', `App rejected operation (${code}).`, 'Check command permissions and App state.', ['admin_required', 'app_privilege_denied'].includes(code) ? 4 : 5);
161
+ }
162
+ return response.data;
163
+ };
164
+ const result = await runFlow(operation.flow, params, invoke, { wait: options.wait, signal: options.signal, timeoutMs: this.remaining(options.timeoutMs ?? CTL_TIMEOUT_MS),
165
+ ndjson: (method, input) => transferRequest(appSession, app.payload.transport.path, method, input, { trust: this.store.trust(this.host), timeoutMs: this.remaining(options.timeoutMs ?? CTL_TIMEOUT_MS) }),
166
+ upload: (method, input, flow) => transferRequest(appSession, app.payload.transport.path, method, {}, { trust: this.store.trust(this.host), timeoutMs: this.remaining(options.timeoutMs ?? CTL_TIMEOUT_MS), file: { path: String(input[flow.fileParam]), parent: String(input[flow.parentParam]), name: String(input[flow.nameParam]) } }) });
167
+ if (operation.resultSchema && !ajv.validate(operation.resultSchema, result))
168
+ throw new CtlError('CTL_RESPONSE_INVALID', 'Result does not match command schema.', 'Check the App version.', 5);
169
+ return result;
178
170
  }
179
- catch (error) {
180
- throw output.error(error);
171
+ finally {
172
+ if (app.payload.transport.auth === 'dsm-app-session')
173
+ await this.request(app.payload.transport.path, { method: 'identity.logout', params: {} }, appSession);
181
174
  }
182
175
  }
183
176
  appCookieSession(session, body) { if (typeof body[APP_COOKIE] !== 'string' || !body[APP_COOKIE])
package/dist/e2e/dsm.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type AppOpenSmokeOptions, type SmokeMarker } from "./app-open.js";
2
- export { deriveSmokeEntry, type AppOpenSmokeOptions, type SmokeMarker } from "./app-open.js";
2
+ export { deriveSmokeEntry, readSmokeEntry, type AppOpenSmokeOptions, type SmokeMarker } from "./app-open.js";
3
3
  import { surfaceOf } from "@e2e-dev/web";
4
4
  type Env = Readonly<Record<string, string | undefined>>;
5
5
  type App = {
@@ -42,7 +42,7 @@ export declare function redactDsmSecrets(text: string): string;
42
42
  * a saved session must restore the real cookies. Does nothing when `dir` is missing.
43
43
  */
44
44
  export declare function protectE2eOutput(dir: string): void;
45
- /** magpie's GPT-6 Luna at max reasoning effort unless E2E_LLM_* says otherwise. */
45
+ /** AI is opt-in: no endpoint, credential or model is selected for the caller. */
46
46
  export declare function llmSettings(env?: Env): {
47
47
  baseURL: string;
48
48
  model: string;
@@ -50,7 +50,7 @@ export declare function llmSettings(env?: Env): {
50
50
  reasoningEffort: string;
51
51
  };
52
52
  /** The `agents.default` entry of e2e.config.ts: model plus the effort sent with every request. */
53
- export declare function magpieAgent(env?: Env): {
53
+ export declare function e2eAgent(env?: Env): {
54
54
  model: import("@ai-sdk/provider").LanguageModelV4;
55
55
  providerOptions: {
56
56
  openai: {
@@ -58,6 +58,8 @@ export declare function magpieAgent(env?: Env): {
58
58
  };
59
59
  };
60
60
  };
61
+ /** Backwards-compatible name; uses only the caller's E2E_LLM_* configuration. */
62
+ export declare const magpieAgent: typeof e2eAgent;
61
63
  /**
62
64
  * Reads one account from a private JSON file: `{username, password}` or
63
65
  * `{users: {<user>: {username, password}}}`. Errors never include the values.
package/dist/e2e/dsm.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // It signs in once per run (a saved, private profile is restored when still valid),
4
4
  // opens DSM app windows and Application Portal pages (accepting their native
5
5
  // dialogs when given the `browser` fixture), dismisses DSM notifications,
6
- // configures the magpie LLM, and runs a command through an SSH tunnel to the NAS
6
+ // configures an optional user-selected LLM, and runs a command through an SSH tunnel to the NAS
7
7
  // (on a free loopback port unless DSM_E2E_TUNNEL_PORT names one). DSM's session
8
8
  // cookies and tokens are masked in what that command prints and leaves in its
9
9
  // e2e output, which is made private (directories 700, files 600).
@@ -21,7 +21,7 @@ import { dirname, join, resolve } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import { createRequire } from "node:module";
23
23
  import { readSmokeEntry } from "./app-open.js";
24
- export { deriveSmokeEntry } from "./app-open.js";
24
+ export { deriveSmokeEntry, readSmokeEntry } from "./app-open.js";
25
25
  import { surfaceOf, test, web } from "@e2e-dev/web";
26
26
  import { withDsmCertificates } from "./certificates.js";
27
27
  const safeName = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
@@ -232,17 +232,35 @@ function redactFile(file) {
232
232
  writeFileSync(file, masked, { mode: 0o600 });
233
233
  }
234
234
  // ---- LLM ------------------------------------------------------------------
235
- /** magpie's GPT-6 Luna at max reasoning effort unless E2E_LLM_* says otherwise. */
235
+ /** AI is opt-in: no endpoint, credential or model is selected for the caller. */
236
236
  export function llmSettings(env = process.env) {
237
+ const baseURL = env.E2E_LLM_BASE_URL?.trim();
238
+ const model = env.E2E_LLM_MODEL?.trim();
239
+ let apiKey = env.E2E_LLM_API_KEY?.trim();
240
+ const missing = [
241
+ ...(!baseURL ? ['E2E_LLM_BASE_URL'] : []),
242
+ ...(!model ? ['E2E_LLM_MODEL'] : []),
243
+ ...(!apiKey && !env.E2E_LLM_API_KEY_FILE?.trim() ? ['E2E_LLM_API_KEY or E2E_LLM_API_KEY_FILE'] : []),
244
+ ];
245
+ if (missing.length) {
246
+ throw new Error(`AI e2e configuration is missing: ${missing.join(', ')}. Set these variables before calling e2eAgent() or magpieAgent(); there is no default endpoint, model or key. Non-AI tests do not need a model profile.`);
247
+ }
248
+ if (!apiKey && env.E2E_LLM_API_KEY_FILE) {
249
+ requirePrivate(env.E2E_LLM_API_KEY_FILE, 'AI key file');
250
+ apiKey = readFileSync(env.E2E_LLM_API_KEY_FILE, 'utf8').trim();
251
+ }
252
+ if (!apiKey)
253
+ throw new Error('AI e2e requires E2E_LLM_API_KEY or E2E_LLM_API_KEY_FILE; configure a model profile or use the non-AI tests.');
237
254
  return {
238
- baseURL: env.E2E_LLM_BASE_URL || "http://127.0.0.1:3425/v1",
239
- model: env.E2E_LLM_MODEL || "codex/gpt-6-luna",
240
- apiKey: env.E2E_LLM_API_KEY || "magpie-local",
241
- reasoningEffort: env.E2E_LLM_REASONING_EFFORT || "max",
255
+ baseURL: baseURL,
256
+ model: model,
257
+ apiKey,
258
+ reasoningEffort: env.E2E_LLM_REASONING_EFFORT || 'low',
242
259
  };
243
260
  }
244
261
  /** The `agents.default` entry of e2e.config.ts: model plus the effort sent with every request. */
245
- export function magpieAgent(env = process.env) {
262
+ export function e2eAgent(env = process.env) {
263
+ const settings = llmSettings(env);
246
264
  // Keep the synchronous config API; load the optional ESM provider only when
247
265
  // an agent is requested (Node 22.12+ supports require(esm)). Smoke tests do
248
266
  // not need the AI SDK or any model provider installed.
@@ -253,14 +271,15 @@ export function magpieAgent(env = process.env) {
253
271
  catch (error) {
254
272
  if (!['MODULE_NOT_FOUND', 'ERR_MODULE_NOT_FOUND'].includes(error.code ?? ''))
255
273
  throw error;
256
- throw new Error('magpieAgent requires optional @ai-sdk/openai and ai; install them to run AI agents.', { cause: error });
274
+ throw new Error('e2eAgent requires optional @ai-sdk/openai and ai; install them to run AI agents.', { cause: error });
257
275
  }
258
- const settings = llmSettings(env);
259
276
  return {
260
277
  model: provider.createOpenAI({ baseURL: settings.baseURL, apiKey: settings.apiKey }).chat(settings.model),
261
278
  providerOptions: { openai: { reasoningEffort: settings.reasoningEffort } },
262
279
  };
263
280
  }
281
+ /** Backwards-compatible name; uses only the caller's E2E_LLM_* configuration. */
282
+ export const magpieAgent = e2eAgent;
264
283
  // ---- Accounts and profiles ------------------------------------------------
265
284
  function requirePrivate(file, what) {
266
285
  if (statSync(file).mode & 0o077)
@@ -1,5 +1,4 @@
1
1
  import type { InstalledPackageState } from './catalog-install.js';
2
- /** Diagnostic text is untrusted and can contain daemon URLs or echoed credentials. */
3
2
  export declare function maskDiagnostic(text: string): string;
4
3
  export declare function savePullFailure(origin: string, packageId: string, message?: string): void;
5
4
  export declare function packageDiagnostics(packageId: string, state: InstalledPackageState | undefined, origin: string): Record<string, unknown>;
@@ -2,23 +2,24 @@ import { createHash } from 'node:crypto';
2
2
  import { mkdirSync, readFileSync, renameSync, writeFileSync, rmSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
- /** Diagnostic text is untrusted and can contain daemon URLs or echoed credentials. */
5
+ // Logs redact these complete field names only, never matching a secret value
6
+ // against unrelated values or public response keys.
7
+ const secretName = /^(?:password|passwd|token|synotoken|sid|_sid|authorization|cookie|set-cookie)$/i;
6
8
  export function maskDiagnostic(text) {
7
9
  return text.replace(/https?:\/\/[^\s"'<>]+/gi, value => {
8
10
  try {
9
11
  const url = new URL(value);
10
- if (!url.username && !url.password && !url.search && !url.hash)
11
- return value;
12
12
  url.username = '';
13
13
  url.password = '';
14
- url.search = '';
15
- url.hash = '';
14
+ for (const key of [...url.searchParams.keys()])
15
+ if (secretName.test(key))
16
+ url.searchParams.set(key, '<redacted>');
16
17
  return url.href;
17
18
  }
18
19
  catch {
19
- return '<redacted URL>';
20
+ return value;
20
21
  }
21
- }).replace(/\b(password|passwd|token|synotoken|_sid|authorization|cookie|set-cookie)\s*[:=]\s*[^\r\n]+/gi, '$1=<redacted>');
22
+ }).replace(/(^|[\s{,])(["']?)(password|passwd|token|synotoken|sid|_sid|authorization|cookie|set-cookie)\2\s*[:=]\s*[^\r\n]+/gim, '$1$2$3$2=<redacted>');
22
23
  }
23
24
  function pathFor(origin, packageId) {
24
25
  const key = createHash('sha256').update(new URL(origin).origin + '\0' + packageId).digest('hex');
@@ -50,7 +51,7 @@ function readPullFailure(origin, packageId) {
50
51
  }
51
52
  export function packageDiagnostics(packageId, state, origin) {
52
53
  const clean = (value) => typeof value === 'string' ? maskDiagnostic(value) : Array.isArray(value) ? value.map(clean)
53
- : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, v]) => [key, /password|passwd|token|sid|authorization|cookie/i.test(key) ? '<redacted>' : clean(v)])) : value;
54
+ : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, v]) => [key, secretName.test(key) ? '<redacted>' : clean(v)])) : value;
54
55
  const worker = clean(state?.error?.workerMsg ?? []);
55
56
  const messages = (value) => typeof value === 'string' ? [value] : Array.isArray(value) ? value.flatMap(messages)
56
57
  : value && typeof value === 'object' ? Object.values(value).flatMap(messages) : [];
package/dist/init.js CHANGED
@@ -207,7 +207,8 @@ export function initFromTemplate(template, targetDir, options = {}) {
207
207
  "AGENTS.md",
208
208
  "CLAUDE.md",
209
209
  ...sharedScripts,
210
- ...["package.json", "e2e.config.ts", "tests/e2e/smoke.e2e.ts"].filter(file => existsSync(join(shared, file))),
210
+ ...["package.json", "e2e.config.ts", "e2e.ai.config.ts"].filter(file => existsSync(join(shared, file))),
211
+ ...["tests", "scripts"].flatMap(dir => existsSync(join(shared, dir)) ? templateFiles(join(shared, dir)).map(file => `${dir}/${file}`) : []),
211
212
  ];
212
213
  const files = [
213
214
  ...templateFiles(source),
package/dist/skill.js CHANGED
@@ -5,6 +5,7 @@ const SKILL_CATALOG = [
5
5
  { id: "orchestrator", file: "SKILL.md", when: "Read first" },
6
6
  { id: "host-install", file: "reference/host-install.md", when: "Shared NAS login, store/local SPK installation and removal" },
7
7
  { id: "ctl", file: "reference/ctl.md", when: "Operate registered NAS Apps or design AI commands" },
8
+ { id: "testing", file: "reference/testing.md", when: "Choose optional local, NAS ctl, UI or AI tests" },
8
9
  {
9
10
  id: "create",
10
11
  file: "reference/create.md",
@@ -191,10 +191,7 @@ returning evidence afterward cannot undo an unauthorized effect.
191
191
  The CLI rereads local session/host/approval state before each external RPC. It
192
192
  does not refresh expired sessions. All errors return bounded generic text;
193
193
  upstream messages, request arguments and exception text are never echoed.
194
- Session carriers and schema-marked sensitive call values are redacted from
195
- results. The App remains responsible for its own secret-free Catalog and Result.
196
- Authentication failures exit 2, invalid input/options 3, trust/permission/revision
197
- refusals 4, contract failures 5 and network failures 6.
194
+ Responses, including errors and MCP tool results, are returned unchanged after validation. Public response keys are never renamed or removed based on secret values. Log masking uses exact secret field names only.
198
195
 
199
196
  There is exactly one mutation dispatch attempt. Timeout, interruption, invalid
200
197
  evidence/schema or oversized output may follow a committed mutation; none
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.48.19",
3
+ "version": "0.48.21",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
package/skills/SKILL.md CHANGED
@@ -347,6 +347,21 @@ readiness 不跟隨 redirect,check 不會發 HTTP。Compose 不支援 ctl。
347
347
 
348
348
  For controlling installed Apps or designing task-level AI commands, read [reference/ctl.md](reference/ctl.md). Declare operations once in a synopkgland.api v2 registry with a required ai class; run `ctl generate`, `ctl generate --check` and `check`. Operation descriptions belong only in that registry; read the generated per-App reference. Import OSS APIs hidden and obtain explicit per-API opt-in grouped by area before exposing them. Use ctl host list, register/renew explicitly, discover all commands, and always name the host when agents may operate multiple NAS machines.
349
349
 
350
+ ## Optional basic testing
351
+
352
+ Scaffold the basic test files by default. Ask once whether the user wants no
353
+ tests, local/non-AI tests, or optional AI steps too; respect the answer for the
354
+ task. Writing and running tests are optional. Accept no tests, do not nag, and
355
+ never block a build or release on tests. The default local loop uses only fast
356
+ unit/ctl registry contracts; the full suite is slow. Real-NAS ctl, App-open smoke,
357
+ UI e2e and AI e2e run only when the user explicitly asks.
358
+
359
+ Read [reference/testing.md](reference/testing.md) when creating or extending tests
360
+ for tier commands, meaningful ctl/UI assertions and bounded job lifecycle tests.
361
+ Non-AI tiers need no AI key. AI steps need a configured endpoint, key location
362
+ and model; if setup is unknown, ask the user for those values. Choose the cheapest
363
+ adequate model with low effort, never an expensive default.
364
+
350
365
  ## App-open smoke
351
366
 
352
367
  Every generated project has `tests/e2e/smoke.e2e.ts` and `npm run e2e:smoke`.
@@ -356,7 +371,7 @@ reuses the existing DSM credentials/profiles/tunnel, and registers administrator
356
371
  normal-user and fresh anonymous tests. Configure `DSM_E2E_ACCOUNT_ADMIN` and
357
372
  `DSM_E2E_ACCOUNT_NORMAL` as private account files; a missing normal profile and
358
373
  credentials is a reported skip. Smoke needs `e2e`, `@e2e-dev/web` and Chromium;
359
- `ai` and `@ai-sdk/openai` are required only for `magpieAgent()`. Declare an optional
374
+ `ai` and `@ai-sdk/openai` are optional installs required only for AI steps. Declare an optional
360
375
  interstitial as `preReady: {clickIfVisible: {text: "Continue on this device"}}`.
361
376
  For `entry: admin-only`, N must see the SDK gateway denial page or an explicit
362
377
  DSM denial/launcher privilege signal without an App window. Timeout alone is not
@@ -253,11 +253,11 @@ until the existing API proves that work stopped.
253
253
 
254
254
  ## Sensitive parameters
255
255
 
256
- App authors must mark passkeys, tokens, private URLs, torrent/base64 and upload content with standard JSON Schema `writeOnly: true`, including nested objects, array items and local references. Mark sensitive response fields in resultSchema too. Do not embed real secrets in schema defaults/enums/examples or command examples.
256
+ App authors must mark passkeys, tokens, private URLs, torrent/base64 and upload content with standard JSON Schema `writeOnly: true`, including nested objects, array items and local references. Do not embed real secrets in schema defaults/enums/examples or command examples.
257
257
 
258
258
  Parameter and result schema `pattern` and `patternProperties` use the linear RE2 engine, with at most 4096 characters per pattern. Backreferences, lookarounds and other unsupported syntax are rejected during description validation. If an unvalidated or cached privacy pattern cannot be compiled, redaction conservatively applies that pattern's annotations to every property.
259
259
 
260
- CLI plans, dry-run, missing-yes errors, JSON/multi-host output and known input values repeated by the App use the fixed string `<redacted>`. Schema validation errors never echo instance values or paths. This changes presentation only: authorized requests still send the original values. The CLI does not log or cache business parameters. Sensitive description examples/defaults are masked in list/help and disk caches; a cache altered by redaction requires a fresh authenticated description/hash check before execution. Fill placeholders locally; never paste secrets into AI messages or logs.
260
+ Request previews (plans, dry-run and missing-yes plans) mask schema-marked input values with `<redacted>`. Operation results, errors and ctl/MCP responses are returned unchanged, including public keys and schema-marked response values. Logs redact only exact secret field names; they never replace values or keys merely because they match a secret value. Schema validation errors never echo instance values or paths. This changes presentation only: authorized requests still send the original values. The CLI does not log or cache business parameters. Sensitive description examples/defaults are masked in list/help and disk caches; a cache altered by redaction requires a fresh authenticated description/hash check before execution. Fill placeholders locally; never paste secrets into AI messages or logs.
261
261
 
262
262
  ## Command naming recommendations
263
263
 
@@ -0,0 +1,134 @@
1
+ # Optional basic App tests
2
+
3
+ Include the scaffold by default; ask once whether the user wants no tests,
4
+ local/non-AI tests, or optional AI steps as well. Honor the choice throughout the
5
+ task. Declining tests is fine: skip writing and running them, do not nag, and
6
+ never block a build or release on tests. The full suite is slow; do not run it
7
+ after every change. Nothing runs on a NAS automatically.
8
+
9
+ ## Tiers, cheapest first
10
+
11
+ | Tier | Explicit command | Minimal useful assertion |
12
+ | --- | --- | --- |
13
+ | Local unit / ctl registry | `npm test` or `npm run test:unit` | Pin an operation's CLI path, read/write effect and handler; unit-test business results |
14
+ | Local package | `npm run test:local` | Check, build one architecture, inspect each emitted SPK |
15
+ | Real-NAS ctl | `npm run test:nas:ctl` | Use actual `synopkgland ctl` commands and assert package ID, caller role and nonroot UID |
16
+ | Real-NAS UI, no AI | `npm run e2e:ui` | Use selectors, perform the primary action and assert its changed saved/read-back result |
17
+ | Optional AI UI step | `npm run e2e:ai` | One bounded `agent.act` followed by the same deterministic result assertion |
18
+
19
+ After the user opts into tests, the default development loop runs only the first
20
+ tier relevant to the change. The local package tier is a separate, explicit
21
+ check. Every NAS tier, including `npm run e2e:smoke`, needs an explicit user
22
+ request and authorized fixtures. Keep build/release and lifecycle hooks independent
23
+ of tests. Test failures are evidence to report, not an automatic release veto.
24
+
25
+ `init` includes examples under `tests/unit`, `tests/local`, `tests/ctl` and
26
+ `tests/e2e`, plus independent npm scripts. Adapt examples when replacing the
27
+ starter status operation; an empty upstream registry has no starter contract to
28
+ test. Do not add ctl to a wrapper merely to enable the example. Existing
29
+ backend-language unit tests remain useful when the user chooses them.
30
+
31
+ ## Real-NAS ctl through the CLI
32
+
33
+ Discover the installed App's commands with `synopkgland ctl list --host <profile>
34
+ --app <package> --json`, completing approval only within the user's authorization.
35
+ Use the registered CLI host/session, not raw HTTP or a mocked transport. Configure
36
+ `APP_TEST_HOST` and optionally `APP_TEST_APP` (package ID/known alias) and
37
+ `APP_TEST_CTL_COMMAND` (a JSON argv array from discovery). The starter example
38
+ uses `app status`, then asserts concrete `package`, `admin` and `process.uid`
39
+ values. Replace these assertions with your App's real contract.
40
+
41
+ For a write, create only an authorized private fixture, read it back through ctl,
42
+ assert its ID and exact changed fields, then clean up. A successful exit or valid
43
+ JSON schema alone does not establish the intended result. Do not replay an
44
+ uncertain write; query its original ID first.
45
+
46
+ ## UI without AI
47
+
48
+ Keep the separate App-open smoke for administrator, normal-user and anonymous
49
+ entry policy. Rendering alone does not test the main feature.
50
+
51
+ The action example uses `APP_TEST_ACTION` (a CSS selector), `APP_TEST_RESULT`
52
+ (a result selector) and `APP_TEST_EXPECTED` (exact resulting text). Prepare an
53
+ authorized fixture whose initial value differs from the expected result. Fill
54
+ required fields before clicking, then assert the saved/read-back outcome: for
55
+ example, rename a fixture and verify its new name after reload, or enqueue a job
56
+ and verify its ID in the list. Replace generic selectors/assertions with stable
57
+ App-specific ones. The example follows the manifest's window/page launcher;
58
+ `APP_TEST_ENTRY` optionally selects a configured entry path.
59
+
60
+ Reuse `DSM_E2E_ACCOUNT_ADMIN` / `DSM_E2E_ACCOUNT_NORMAL` private account files,
61
+ saved profiles and the existing tunnel. Read [host-install.md](host-install.md)
62
+ for CLI sessions. Keep `.env` and `.e2e/` untracked; no test installs or deploys
63
+ an App on its own. Non-AI config imports no model provider and needs no AI key.
64
+
65
+ ## Long-running jobs: test the lifecycle, never full completion
66
+
67
+ Use a deliberately long, private fixture and adapt the following helper's
68
+ callbacks and state/progress fields to the actual App registry. Each callback
69
+ must have its own request timeout; ctl callbacks execute the discovered CLI
70
+ commands. UI tests drive the same controls and observe the same job ID.
71
+
72
+ ```js
73
+ import assert from 'node:assert/strict';
74
+ import {setTimeout as delay} from 'node:timers/promises';
75
+
76
+ async function until(get, predicate) {
77
+ const deadline = Date.now() + 10_000;
78
+ do {
79
+ const value = await get();
80
+ if (predicate(value)) return value;
81
+ assert.ok(!['completed', 'failed'].includes(value.state));
82
+ await delay(100);
83
+ } while (Date.now() < deadline);
84
+ throw new Error('Job lifecycle observation timed out');
85
+ }
86
+
87
+ async function lifecycle(api, fixture) {
88
+ const job = await api.start(fixture);
89
+ try {
90
+ const progressed = await until(() => api.get(job.id), j => j.progress > 0);
91
+ assert.equal(progressed.id, job.id);
92
+ await api.pause(job.id);
93
+ const paused = await until(() => api.get(job.id), j => j.state === 'paused');
94
+ assert.ok(paused.progress >= progressed.progress);
95
+ const resuming = await api.resume(job.id); // adapter returns the retained snapshot
96
+ assert.equal(resuming.id, job.id);
97
+ assert.ok(resuming.progress >= paused.progress);
98
+ const resumed = await until(() => api.get(job.id), j =>
99
+ j.state === 'running' && j.progress >= paused.progress);
100
+ assert.equal(resumed.id, job.id);
101
+ assert.ok(resumed.progress >= paused.progress); // no reset on resume
102
+ // Prefer a retained checkpoint/byte offset too, when the App exposes one.
103
+ } finally {
104
+ await api.cancel(job.id);
105
+ const cancelled = await until(() => api.get(job.id), j => j.state === 'cancelled');
106
+ assert.equal(cancelled.id, job.id);
107
+ }
108
+ }
109
+ ```
110
+
111
+ Assert retained checkpoint/progress on resume; do not accept a new job ID or a
112
+ reset. Cancel even when an assertion fails and clean up only the test fixture.
113
+ Never wait for the entire workload to finish. If the App cannot pause/resume,
114
+ report that unsupported lifecycle step rather than inventing a command.
115
+
116
+ ## Optional AI profile
117
+
118
+ Offer only non-AI tiers when the user wants no AI. If they request AI, install
119
+ `ai` and `@ai-sdk/openai` explicitly; the normal scaffold does not need them.
120
+ `e2e.ai.config.ts` is loaded only by `e2e:ai`. `e2eAgent()` reads:
121
+
122
+ - `E2E_LLM_BASE_URL`: the user's OpenAI-compatible endpoint
123
+ - `E2E_LLM_MODEL`: the cheapest model adequate for this bounded action
124
+ - `E2E_LLM_API_KEY_FILE`: a private mode-600 file containing the key, or
125
+ `E2E_LLM_API_KEY` supplied through the environment
126
+ - `E2E_LLM_REASONING_EFFORT`: defaults to `low`
127
+
128
+ There is no built-in endpoint, key or model. The legacy `magpieAgent` export is
129
+ an alias with the same explicit configuration. Never select an expensive model
130
+ by default. If no profile exists and you do not know the user's setup, ask for
131
+ the endpoint, key location and model. Do not print keys or put them in argv.
132
+
133
+ Set `APP_TEST_AI_ACTION` to one authorized fixture action. Keep a deterministic
134
+ selector/result assertion after `agent.act`; an AI assertion alone is insufficient.