@synopackageland/cli 0.48.20 → 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,10 @@
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
+
3
8
  ## 0.48.20
4
9
 
5
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
@@ -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])
@@ -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) : [];
@@ -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.20",
3
+ "version": "0.48.21",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -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