@synopackageland/cli 0.53.5 → 0.53.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.53.6 (2026-11-11)
4
+
5
+ - `ui_secret_ignores` entries can name a bundler-hashed chunk with one `[hash]` (`app/chunks/Dialog-[hash].js`), so an unrelated frontend change no longer breaks the build with `UI_SECRET_IGNORE_MISSING`. `[hash]` matches `[A-Za-z0-9_-]{6,64}` inside one path segment, with no other glob syntax, and must match exactly one file; more than one fails with `UI_SECRET_IGNORE_AMBIGUOUS`, listing them.
6
+ - New `match` (a string or a list): the exact flagged texts to exempt. It is required with `[hash]` and optional for exact paths. Other hits in the same file still fail `PUBLIC_UI_UNSAFE`, and a listed text that no longer occurs fails with `UI_SECRET_IGNORE_STALE`. Exact paths without `match` behave as before. Source maps are still never exempt.
7
+ - `build` and project `check` print each unexempted hit (truncated) with a ready-to-paste entry; known token signatures are never printed, and `check <spk>`/`inspect` still report patterns only. Project `check` scans JS/CSS minified as `build` packs it, so printed texts agree with `build`. `[UI_SECRET_IGNORED]` names the resolved file and the `[hash]` entry.
8
+ - SPKs record the resolved exact file and its `match` list in `sdk-package.json`/`native-layout.json`, never `[hash]`; inspection re-checks them. SPKs from earlier releases inspect unchanged. Earlier CLIs cannot read a recorded `match` and report the exceptions as invalid when inspecting a new SPK that uses it.
9
+
3
10
  ## 0.53.5 (2026-11-11)
4
11
 
5
12
  - Page `ctl external` describe so an App's MCP Catalog can grow far past 1 MiB while every message stays within it. Describe returns one page with the Catalog `revision` and, until the last page, a `nextCursor`; request the next page with `{"protocol","action":"describe","revision","cursor"}`. These map directly onto MCP `tools/list` `cursor`/`nextCursor`. A page from a changed revision refuses with `CTL_EXTERNAL_REVISION`; list again from the first page. A page holds at most 1024 tools, and a page with `nextCursor` holds at least one.
@@ -3,7 +3,7 @@ import { posix } from "node:path";
3
3
  import * as tar from "tar";
4
4
  import { ARCH_ELF_MACHINE } from "./dsm-spec.js";
5
5
  import { archiveInventory, formatArchiveIssue } from './archive-inventory.js';
6
- import { applyUiIgnores, publicUiReport, uiFileProblems } from "../standalone/public-ui.js";
6
+ import { applyUiIgnores, logicalUiFile, publicUiReport, resolveUiSecretIgnores, staleUiIgnores, uiFileProblems } from "../standalone/public-ui.js";
7
7
  const XZ_MAGIC = Buffer.from([0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00]);
8
8
  const ELF_MAGIC = Buffer.from("\x7fELF", "latin1");
9
9
  const MAX_TEXT = 1024 * 1024;
@@ -164,17 +164,31 @@ export async function checkPayload(payloadPath, info, findings, policy = {}) {
164
164
  checkUiConfig(file, sections, findings);
165
165
  checkElf(files, info.arch, findings);
166
166
  const ui = files.filter(file => file.path.startsWith("ui/"));
167
+ let ignores = [];
168
+ try {
169
+ // New builds record exact files; older or hand-made metadata may still hold [hash].
170
+ ignores = resolveUiSecretIgnores(ui.map(file => logicalUiFile(file.path.slice(3), policy.moduleVersion)), policy.ignores ?? [], false);
171
+ }
172
+ catch (error) {
173
+ findings.add("SPK_UI_UNSAFE", error.message, "ui/");
174
+ }
175
+ const scanned = [];
167
176
  for (const file of ui) {
168
177
  if (file.content === undefined) {
169
178
  findings.add("SPK_UI_UNSAFE", "Public UI file exceeds the 64 MiB scan limit.", at(file.path));
170
179
  continue;
171
180
  }
172
- const problems = applyUiIgnores(uiFileProblems(file.path.slice(3), file.content), policy.ignores ?? [], policy.moduleVersion);
181
+ const raw = uiFileProblems(file.path.slice(3), file.content);
182
+ scanned.push(...raw);
183
+ // Inspection may run on SPKs from others: report patterns, never the flagged text.
184
+ const problems = applyUiIgnores(raw, ignores, policy.moduleVersion);
173
185
  for (const problem of problems) {
174
186
  if (policy.sourceMaps === false && ["source-map-file", "sourceMappingURL"].includes(problem.pattern))
175
187
  continue;
176
- findings.add(problem.ignored ? "SPK_UI_SECRET_IGNORED" : "SPK_UI_UNSAFE", `Public UI pattern: ${problem.pattern}${problem.ignored ? `; reason: ${problem.ignored}` : "; remove it before packaging"}.`, at(file.path));
188
+ findings.add(problem.ignored ? "SPK_UI_SECRET_IGNORED" : "SPK_UI_UNSAFE", `Public UI pattern: ${problem.pattern}${problem.ignored ? `; ${problem.ignoredBy ? `matched ui/${problem.ignoredBy}; ` : ""}reason: ${problem.ignored}` : "; remove it before packaging"}.`, at(file.path));
177
189
  }
178
190
  }
191
+ for (const stale of staleUiIgnores(scanned, ignores, policy.moduleVersion))
192
+ findings.add("SPK_UI_UNSAFE", "A recorded ui_secret_ignores match no longer occurs in this file; rebuild the SPK.", at(`ui/${stale.file}`));
179
193
  return publicUiReport(ui.filter(file => file.content !== undefined).map(file => ({ file: file.path, content: file.content.toString("utf8") })));
180
194
  }
@@ -18,7 +18,7 @@ export declare const SPK_RULES: {
18
18
  };
19
19
  readonly SPK_UI_SECRET_IGNORED: {
20
20
  readonly severity: "warning";
21
- readonly description: "An exact public UI file has a secret-scan exception with a reason.";
21
+ readonly description: "A public UI file has a secret-scan exception with a reason (and, when listed, only its matched texts).";
22
22
  readonly source: "Public UI policy";
23
23
  };
24
24
  readonly SPK_ARCHIVE_INVALID: {
package/dist/spk/rules.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const GUIDE = "DSM 7 Developer Guide";
2
2
  export const SPK_RULES = {
3
3
  SPK_UI_UNSAFE: { severity: "error", description: "Public UI contains source maps or secret-looking content.", source: "Public UI policy" },
4
- SPK_UI_SECRET_IGNORED: { severity: "warning", description: "An exact public UI file has a secret-scan exception with a reason.", source: "Public UI policy" },
4
+ SPK_UI_SECRET_IGNORED: { severity: "warning", description: "A public UI file has a secret-scan exception with a reason (and, when listed, only its matched texts).", source: "Public UI policy" },
5
5
  SPK_ARCHIVE_INVALID: { severity: "error", description: "An archive has noncanonical or colliding names, repeated entries, or unsupported entry types.", source: "Archive inventory" },
6
6
  SPK_NOT_TAR: { severity: "error", description: "The file is not a readable tar archive; an SPK is an uncompressed tar.", source: `${GUIDE}: Package Structure` },
7
7
  SPK_ENTRY_UNSAFE: { severity: "error", description: "A path inside the SPK escapes the archive root (an absolute path or ..), or is a link.", source: `${GUIDE}: Package Structure` },
@@ -5,7 +5,7 @@ import { validateMetadata, metadataInfoFields } from "../package-metadata.js";
5
5
  import { createHash } from 'node:crypto';
6
6
  import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
7
7
  import { enforceRepositorySecrets, readAllowedSecretFiles } from '../secret-files.js';
8
- import { enforcePublicUi, minifyUiTree, readUiSecretIgnores, uiFiles } from './public-ui.js';
8
+ import { enforcePublicUi, minifyUiTree, readUiSecretIgnores, storedUiSecretIgnores, uiFiles } from './public-ui.js';
9
9
  import { tmpdir } from 'node:os';
10
10
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
11
  import { parse } from 'yaml';
@@ -355,9 +355,9 @@ export async function buildNativeLayout(options) {
355
355
  mkdirSync(target);
356
356
  copyTree(payload, target);
357
357
  minifyUiTree(join(target, 'ui'));
358
- enforcePublicUi(join(target, 'ui'), m.uiSecretIgnores);
358
+ const uiIgnores = enforcePublicUi(join(target, 'ui'), m.uiSecretIgnores);
359
359
  const files = layoutFiles(target);
360
- const ignoredUi = uiFiles(join(target, 'ui')).filter(file => m.uiSecretIgnores?.some(ignore => ignore.file === file)).map(file => `ui/${file}`);
360
+ const ignoredUi = uiFiles(join(target, 'ui')).filter(file => uiIgnores.some(ignore => ignore.file === file)).map(file => `ui/${file}`);
361
361
  await createReproducibleTar(target, join(stage, 'package.tgz'), { gzip: true, rejectSecrets: true, allowSecretFiles: [...new Set([...(m.allowSecretFiles ?? []), ...ignoredUi])] });
362
362
  rmSync(target, { recursive: true });
363
363
  const fields = { package: m.package, version, arch: layoutInfoArch(arch), os_min_ver: m.os_min_ver, displayname: m.displayname, description: m.description, maintainer: m.maintainer, dsmuidir: 'ui', dsmappname: `SYNO.SDS.${m.package}.Instance`, startable: 'yes', thirdparty: 'yes', checksum: createHash('md5').update(readFileSync(join(stage, 'package.tgz'))).digest('hex') };
@@ -366,7 +366,7 @@ export async function buildNativeLayout(options) {
366
366
  if (new Set(info.map(([k]) => k)).size !== info.length)
367
367
  fail('INFO anchor collides with an INFO field');
368
368
  writeFileSync(join(stage, 'INFO'), info.map(([k, v]) => `${k}="${v.replace(/([\\"$`])/g, '\\$1')}"\n`).join(''));
369
- writeFileSync(join(stage, 'native-layout.json'), JSON.stringify({ format: 1, arch, dependencies: m.dependencies ?? { packages: [] }, ...(m.uiSecretIgnores?.length ? { ui_secret_ignores: m.uiSecretIgnores } : {}), binaries: binaries.map(({ path, linkage }) => ({ path, linkage })), files, ...(m.layout.anchors ? { anchors: m.layout.anchors } : {}), ...(m.portal ? { portal: m.portal } : {}) }));
369
+ writeFileSync(join(stage, 'native-layout.json'), JSON.stringify({ format: 1, arch, dependencies: m.dependencies ?? { packages: [] }, ...(uiIgnores.length ? { ui_secret_ignores: storedUiSecretIgnores(uiIgnores) } : {}), binaries: binaries.map(({ path, linkage }) => ({ path, linkage })), files, ...(m.layout.anchors ? { anchors: m.layout.anchors } : {}), ...(m.portal ? { portal: m.portal } : {}) }));
370
370
  for (const name of ['INFO', 'native-layout.json'])
371
371
  chmodSync(join(stage, name), 0o644);
372
372
  const output = join(outDir, `${m.package}-${version}-${arch}.spk`);
@@ -1,11 +1,22 @@
1
1
  export interface UiSecretIgnore {
2
2
  file: string;
3
3
  reason: string;
4
+ match?: string[];
4
5
  }
6
+ /** A build-time ignore after `[hash]` resolution; `pattern` is set only for placeholder entries. */
7
+ export interface ResolvedUiSecretIgnore extends UiSecretIgnore {
8
+ pattern?: string;
9
+ }
10
+ /**
11
+ * `matches` holds the exact flagged text, for patterns that flag text. It can be a
12
+ * credential: print it only through showUiMatch and only for the developer's own project.
13
+ */
5
14
  export interface UiProblem {
6
15
  file: string;
7
16
  pattern: string;
17
+ matches?: string[];
8
18
  ignored?: string;
19
+ ignoredBy?: string;
9
20
  }
10
21
  export interface PublicUiReport {
11
22
  /** A whitespace heuristic, not a claim that source code is confidential. */
@@ -15,7 +26,16 @@ export interface PublicUiReport {
15
26
  unminified: string[];
16
27
  sourceMaps: string[];
17
28
  }
29
+ /** One bundler content-hash token; it never crosses `/` and admits no other glob syntax. */
30
+ export declare const UI_HASH_TOKEN = "[hash]";
18
31
  export declare function readUiSecretIgnores(value: unknown): UiSecretIgnore[];
32
+ /**
33
+ * Resolve ignores against logical UI files. A `[hash]` entry must match exactly one
34
+ * file. With `requireMatch`, every entry must match; ambiguity always fails.
35
+ */
36
+ export declare function resolveUiSecretIgnores(files: Iterable<string>, ignores: UiSecretIgnore[], requireMatch?: boolean): ResolvedUiSecretIgnore[];
37
+ /** The form recorded in build metadata: resolved exact files, never `[hash]`. */
38
+ export declare function storedUiSecretIgnores(ignores: ResolvedUiSecretIgnore[]): UiSecretIgnore[];
19
39
  export declare function isUiBundle(file: string): boolean;
20
40
  /** No format conversion or property mangling: classic globals and ESM exports stay public. */
21
41
  export declare function minifyUi(content: string, file: string): string;
@@ -24,9 +44,35 @@ export declare function uiFiles(root: string): string[];
24
44
  export declare function minifyUiTree(root: string, skip?: string[]): void;
25
45
  export declare function uiFileProblems(file: string, input: string | Buffer): UiProblem[];
26
46
  export declare function logicalUiFile(file: string, moduleVersion?: string): string;
27
- export declare function applyUiIgnores(problems: UiProblem[], ignores: UiSecretIgnore[], moduleVersion?: string): UiProblem[];
28
- export declare function scanUiTree(root: string, ignores?: UiSecretIgnore[], moduleVersion?: string): UiProblem[];
29
- export declare function enforcePublicUi(root: string, ignores?: UiSecretIgnore[], moduleVersion?: string): void;
47
+ /**
48
+ * `ignores` must already be resolved to exact logical files (see resolveUiSecretIgnores).
49
+ * An entry with `match` exempts only hits whose text it lists; an unexempted problem
50
+ * keeps only its unlisted matches.
51
+ */
52
+ export declare function applyUiIgnores(problems: UiProblem[], ignores: ResolvedUiSecretIgnore[], moduleVersion?: string): UiProblem[];
53
+ export interface StaleUiIgnore {
54
+ file: string;
55
+ entry: string;
56
+ match: string;
57
+ }
58
+ /** Listed `match` texts that no longer occur in their file, so ignore lists cannot rot. */
59
+ export declare function staleUiIgnores(problems: UiProblem[], ignores: ResolvedUiSecretIgnore[], moduleVersion?: string): StaleUiIgnore[];
60
+ /**
61
+ * Display form of flagged text: truncated, and redacted when it looks like a real
62
+ * token signature. Use only for the developer's own project (build, check).
63
+ */
64
+ export declare function showUiMatch(text: string, limit?: number): string;
65
+ /** A logical file with a bundler-looking hash (Name-AbCd1234.js) becomes Name-[hash].js. */
66
+ export declare function suggestUiIgnoreFile(file: string): string;
67
+ /**
68
+ * A ready-to-paste ui_secret_ignores block for reviewed false positives. Texts that
69
+ * look like real tokens or exceed 200 characters are left for the developer to copy.
70
+ */
71
+ export declare function uiIgnoreSuggestion(problems: UiProblem[], moduleVersion?: string): string;
72
+ export declare function describeUiProblem(problem: UiProblem): string;
73
+ export declare function scanUiTree(root: string, ignores?: ResolvedUiSecretIgnore[], moduleVersion?: string, packed?: boolean): UiProblem[];
74
+ /** Returns the resolved ignores; record them with storedUiSecretIgnores. */
75
+ export declare function enforcePublicUi(root: string, ignores?: UiSecretIgnore[], moduleVersion?: string): ResolvedUiSecretIgnore[];
30
76
  export declare function publicUiReport(files: Array<{
31
77
  file: string;
32
78
  content: string;
@@ -2,21 +2,72 @@ import { existsSync, lstatSync, readFileSync, readdirSync, rmSync, writeFileSync
2
2
  import { basename, extname, join } from "node:path";
3
3
  import { transformSync } from "esbuild";
4
4
  import { readAllowedSecretFiles } from "../secret-files.js";
5
+ /** One bundler content-hash token; it never crosses `/` and admits no other glob syntax. */
6
+ export const UI_HASH_TOKEN = "[hash]";
7
+ const UI_HASH_CHARS = "[A-Za-z0-9_-]{6,64}";
8
+ const SOURCE_MAP_PATTERNS = ["source-map-file", "sourceMappingURL"];
9
+ function hashPattern(file) {
10
+ const at = file.indexOf(UI_HASH_TOKEN);
11
+ if (at < 0)
12
+ return undefined;
13
+ const quote = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ return new RegExp(`^${quote(file.slice(0, at))}${UI_HASH_CHARS}${quote(file.slice(at + UI_HASH_TOKEN.length))}$`);
15
+ }
5
16
  export function readUiSecretIgnores(value) {
6
17
  if (value === undefined)
7
18
  return [];
8
- const invalid = () => Object.assign(new Error("ui_secret_ignores must be an array of {file, reason}; file is an exact path relative to ui/ and reason must be nonempty. Module snapshot hashes are omitted (app/file.js)."), { code: "UI_SECRET_IGNORES_INVALID" });
9
- if (!Array.isArray(value) || value.some(item => !item || typeof item !== "object" ||
10
- Array.isArray(item) || Object.keys(item).some(key => !["file", "reason"].includes(key)) ||
11
- typeof item.reason !== "string" || !item.reason.trim() || /[\x00-\x1f\x7f]/.test(item.reason)))
19
+ const invalid = () => Object.assign(new Error("ui_secret_ignores must be an array of {file, reason, match}; file is an exact path relative to ui/, optionally with one [hash] for a bundler content hash (app/chunks/Dialog-[hash].js); reason must be nonempty; match is the exact flagged text (or a list of them), required with [hash]. Module snapshot hashes are omitted (app/file.js)."), { code: "UI_SECRET_IGNORES_INVALID" });
20
+ const matches = (item) => item.match === undefined ? undefined : Array.isArray(item.match) ? item.match : [item.match];
21
+ if (!Array.isArray(value) || value.some(item => {
22
+ if (!item || typeof item !== "object" || Array.isArray(item) ||
23
+ Object.keys(item).some(key => !["file", "reason", "match"].includes(key)) || typeof item.file !== "string" ||
24
+ typeof item.reason !== "string" || !item.reason.trim() || /[\x00-\x1f\x7f]/.test(item.reason))
25
+ return true;
26
+ const match = matches(item);
27
+ // Without match, a [hash] entry would silently exempt new hits in a changed chunk.
28
+ if (match === undefined)
29
+ return item.file.includes(UI_HASH_TOKEN);
30
+ return !match.length || new Set(match).size !== match.length ||
31
+ match.some(text => typeof text !== "string" || !text || text.length > 4096);
32
+ }))
12
33
  throw invalid();
34
+ // Replace one token with an inert character so the exact-path rules still reject
35
+ // any further brackets, globs, separators inside it and dot segments.
13
36
  try {
14
- readAllowedSecretFiles(value.map(item => item.file));
37
+ readAllowedSecretFiles(value.map(item => item.file.replace(UI_HASH_TOKEN, "")));
15
38
  }
16
39
  catch {
17
40
  throw invalid();
18
41
  }
19
- return value.map(item => ({ file: item.file, reason: item.reason.trim() }));
42
+ return value.map(item => ({ file: item.file, reason: item.reason.trim(), ...(matches(item) ? { match: [...matches(item)] } : {}) }));
43
+ }
44
+ /**
45
+ * Resolve ignores against logical UI files. A `[hash]` entry must match exactly one
46
+ * file. With `requireMatch`, every entry must match; ambiguity always fails.
47
+ */
48
+ export function resolveUiSecretIgnores(files, ignores, requireMatch = true) {
49
+ const list = [...files];
50
+ const present = new Set(list);
51
+ const resolved = [];
52
+ for (const ignore of ignores) {
53
+ const match = hashPattern(ignore.file);
54
+ const found = match ? list.filter(file => match.test(file)) : present.has(ignore.file) ? [ignore.file] : [];
55
+ if (found.length > 1)
56
+ throw Object.assign(new Error(`ui_secret_ignores ui/${ignore.file} matches ${found.length} files; it must match exactly one: ${found.map(file => `ui/${file}`).join(", ")}`), { code: "UI_SECRET_IGNORE_AMBIGUOUS" });
57
+ if (!found.length) {
58
+ if (requireMatch)
59
+ throw Object.assign(new Error(match ? `ui_secret_ignores ui/${ignore.file} matches no file` : `ui_secret_ignores file does not exist: ui/${ignore.file}`), { code: "UI_SECRET_IGNORE_MISSING" });
60
+ continue;
61
+ }
62
+ resolved.push({ ...ignore, file: found[0], ...(match ? { pattern: ignore.file } : {}) });
63
+ }
64
+ if (new Set(resolved.map(item => item.file)).size !== resolved.length)
65
+ throw Object.assign(new Error("ui_secret_ignores lists the same UI file more than once; keep one entry per file."), { code: "UI_SECRET_IGNORE_AMBIGUOUS" });
66
+ return resolved;
67
+ }
68
+ /** The form recorded in build metadata: resolved exact files, never `[hash]`. */
69
+ export function storedUiSecretIgnores(ignores) {
70
+ return ignores.map(({ file, reason, match }) => ({ file, reason, ...(match ? { match } : {}) }));
20
71
  }
21
72
  export function isUiBundle(file) {
22
73
  return [".js", ".mjs", ".cjs", ".css"].includes(extname(file).toLowerCase());
@@ -105,7 +156,8 @@ const PASSWORD_CAPTIONS = new Set([
105
156
  "passwort", "benutzerpasswort", "mot de passe", "mot de passe utilisateur",
106
157
  "contraseña", "contraseña de usuario", "password utente",
107
158
  ]);
108
- function credentialLiteral(content) {
159
+ function credentialLiterals(content, bundle) {
160
+ const found = [];
109
161
  const literals = /(?:^|[,{])\s*(?:"(password|secret)"|'(password|secret)'|(password|secret))\s*:\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|`([^`$\r\n]+)`|(\d+(?:\.\d+)?)\b)/gi;
110
162
  for (const match of content.matchAll(literals)) {
111
163
  const key = match[1] ?? match[2] ?? match[3];
@@ -113,10 +165,19 @@ function credentialLiteral(content) {
113
165
  const caption = value.replace(/\\(?:u([0-9a-f]{4})|x([0-9a-f]{2}))/gi, (_escape, unicode, hex) => String.fromCharCode(parseInt(unicode ?? hex, 16))).toLowerCase();
114
166
  if (key.toLowerCase() === "password" && PASSWORD_CAPTIONS.has(caption))
115
167
  continue;
116
- return true;
168
+ found.push(match[0].replace(/^[,{]?\s*/, ""));
117
169
  }
118
- return /(?:^|[^\w$"'`])(?:password|secret)\s*=\s*(?:"[^"\r\n]+"|'[^'\r\n]+'|`[^`$\r\n]+`|\d+(?:\.\d+)?\b)|["'`](?:password|secret)=[^"'`\s]+/i.test(content);
170
+ const assignments = /(?<![\w$"'`])(?:password|secret)\s*=\s*(?:"[^"\r\n]+"|'[^'\r\n]+'|`[^`$\r\n]+`|\d+(?:\.\d+)?\b)|["'`](?:password|secret)=[^"'`\s]+/gi;
171
+ for (const match of content.matchAll(assignments))
172
+ found.push(match[0]);
173
+ // Unquoted values in environment/config/HTML text; JS variable assignments are not literals.
174
+ if (!bundle)
175
+ for (const match of content.matchAll(/(?<![\w$])(?:password|secret)\s*=\s*[^\s"'`<>{};,]+/gi))
176
+ found.push(match[0]);
177
+ return found;
119
178
  }
179
+ const unique = (items) => [...new Set(items)];
180
+ const allMatches = (pattern, content) => unique([...content.matchAll(new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`))].map(match => match[0]));
120
181
  export function uiFileProblems(file, input) {
121
182
  const executable = Buffer.isBuffer(input) && isExecutable(input);
122
183
  const content = typeof input === "string" ? input : input.toString(executable ? "latin1" : "utf8");
@@ -128,45 +189,144 @@ export function uiFileProblems(file, input) {
128
189
  found.push({ file, pattern: "source-map-file" });
129
190
  if (SOURCE_MAP_COMMENT.test(content))
130
191
  found.push({ file, pattern: "sourceMappingURL" });
131
- for (const [pattern, match] of executable ? BINARY_SECRET_PATTERNS : SECRET_PATTERNS)
132
- if (match.test(content))
133
- found.push({ file, pattern });
192
+ for (const [pattern, match] of executable ? BINARY_SECRET_PATTERNS : SECRET_PATTERNS) {
193
+ const matches = allMatches(match, content);
194
+ if (matches.length)
195
+ found.push({ file, pattern, matches });
196
+ }
134
197
  // Source syntax has no reliable meaning in machine code or pooled constants.
135
- if (!executable && credentialLiteral(content))
136
- found.push({ file, pattern: "credential-literal" });
137
- // Unquoted values in environment/config/HTML text; JS variable assignments are not literals.
138
- if (!executable && !isUiBundle(file) && /(?:^|[^\w$])(?:password|secret)\s*=\s*[^\s"'`<>{};,]+/i.test(content))
139
- if (!found.some(item => item.pattern === "credential-literal"))
140
- found.push({ file, pattern: "credential-literal" });
198
+ const literals = executable ? [] : unique(credentialLiterals(content, isUiBundle(file)));
199
+ if (literals.length)
200
+ found.push({ file, pattern: "credential-literal", matches: literals });
141
201
  return found;
142
202
  }
143
203
  export function logicalUiFile(file, moduleVersion) {
144
204
  const prefix = moduleVersion ? `app/${moduleVersion}/` : "";
145
205
  return prefix && file.startsWith(prefix) ? `app/${file.slice(prefix.length)}` : file;
146
206
  }
207
+ /**
208
+ * `ignores` must already be resolved to exact logical files (see resolveUiSecretIgnores).
209
+ * An entry with `match` exempts only hits whose text it lists; an unexempted problem
210
+ * keeps only its unlisted matches.
211
+ */
147
212
  export function applyUiIgnores(problems, ignores, moduleVersion) {
148
213
  return problems.map(problem => {
149
214
  // Source maps are never exempted by a secret-scan exception.
150
- const ignore = !["source-map-file", "sourceMappingURL"].includes(problem.pattern) &&
215
+ const ignore = !SOURCE_MAP_PATTERNS.includes(problem.pattern) &&
151
216
  ignores.find(item => item.file === logicalUiFile(problem.file, moduleVersion));
152
- return ignore ? { ...problem, ignored: ignore.reason } : problem;
217
+ if (!ignore)
218
+ return problem;
219
+ if (ignore.match) {
220
+ const listed = new Set(ignore.match);
221
+ // A file-level hit (no text) cannot be exempted by a text match.
222
+ if (!problem.matches)
223
+ return problem;
224
+ const unlisted = problem.matches.filter(text => !listed.has(text));
225
+ if (unlisted.length)
226
+ return { ...problem, matches: unlisted };
227
+ }
228
+ return { ...problem, ignored: ignore.reason, ...(ignore.pattern ? { ignoredBy: ignore.pattern } : {}) };
229
+ });
230
+ }
231
+ /** Listed `match` texts that no longer occur in their file, so ignore lists cannot rot. */
232
+ export function staleUiIgnores(problems, ignores, moduleVersion) {
233
+ return ignores.flatMap(ignore => {
234
+ if (!ignore.match)
235
+ return [];
236
+ const occurring = new Set(problems.filter(problem => logicalUiFile(problem.file, moduleVersion) === ignore.file)
237
+ .flatMap(problem => problem.matches ?? []));
238
+ return ignore.match.filter(text => !occurring.has(text))
239
+ .map(match => ({ file: ignore.file, entry: ignore.pattern ?? ignore.file, match }));
153
240
  });
154
241
  }
155
- export function scanUiTree(root, ignores = [], moduleVersion) {
156
- const problems = uiFiles(root).flatMap(file => uiFileProblems(file, readFileSync(join(root, file))));
242
+ /**
243
+ * Display form of flagged text: truncated, and redacted when it looks like a real
244
+ * token signature. Use only for the developer's own project (build, check).
245
+ */
246
+ export function showUiMatch(text, limit = 80) {
247
+ if (BINARY_SECRET_PATTERNS.some(([, pattern]) => pattern.test(text)))
248
+ return `<redacted ${text.length} chars>`;
249
+ const quoted = JSON.stringify(text);
250
+ return quoted.length > limit ? `${quoted.slice(0, limit - 4)}..."` : quoted;
251
+ }
252
+ /** A logical file with a bundler-looking hash (Name-AbCd1234.js) becomes Name-[hash].js. */
253
+ export function suggestUiIgnoreFile(file) {
254
+ return file.replace(/^(.*\/)?([^/]*[-.])[A-Za-z0-9_-]{8}(\.[A-Za-z0-9]+)$/, (_all, dir = "", stem, ext) => `${dir}${stem}${UI_HASH_TOKEN}${ext}`);
255
+ }
256
+ /**
257
+ * A ready-to-paste ui_secret_ignores block for reviewed false positives. Texts that
258
+ * look like real tokens or exceed 200 characters are left for the developer to copy.
259
+ */
260
+ export function uiIgnoreSuggestion(problems, moduleVersion) {
261
+ const byFile = new Map();
262
+ const manual = new Set();
263
+ for (const problem of problems) {
264
+ if (SOURCE_MAP_PATTERNS.includes(problem.pattern) || !problem.matches)
265
+ continue;
266
+ const file = logicalUiFile(problem.file, moduleVersion);
267
+ const texts = byFile.get(file) ?? [];
268
+ for (const text of problem.matches) {
269
+ if (text.length > 200 || showUiMatch(text, Infinity).startsWith("<redacted"))
270
+ manual.add(file);
271
+ else
272
+ texts.push(text);
273
+ }
274
+ byFile.set(file, texts);
275
+ }
276
+ if (!byFile.size)
277
+ return "";
278
+ const lines = ["ui_secret_ignores:"];
279
+ for (const [file, texts] of byFile) {
280
+ lines.push(` - file: ${JSON.stringify(suggestUiIgnoreFile(file))}`, " reason: \"<why this is a false positive>\"", " match:");
281
+ for (const text of unique(texts))
282
+ lines.push(` - ${JSON.stringify(text)}`);
283
+ if (manual.has(file) || !texts.length)
284
+ lines.push(` # copy any other flagged text from ui/${file} after review`);
285
+ }
286
+ return lines.join("\n");
287
+ }
288
+ export function describeUiProblem(problem) {
289
+ const shown = (problem.matches ?? []).slice(0, 3).map(text => showUiMatch(text));
290
+ const more = (problem.matches?.length ?? 0) > 3 ? ` (+${problem.matches.length - 3} more)` : "";
291
+ return `ui/${problem.file}: ${problem.pattern}${shown.length ? ` ${shown.join(", ")}${more}` : ""}`;
292
+ }
293
+ /** Scan the files as build packs them: JS/CSS minified, so `match` texts agree with build. */
294
+ function packedUiProblems(file, bytes) {
295
+ if (!isUiBundle(file))
296
+ return uiFileProblems(file, bytes);
297
+ const raw = bytes.toString("utf8");
298
+ let packed;
299
+ try {
300
+ packed = minifyUi(raw, file);
301
+ }
302
+ catch {
303
+ return uiFileProblems(file, bytes);
304
+ }
305
+ // Minifying removes source-map comments; keep reporting them from the original.
306
+ const maps = SOURCE_MAP_COMMENT.test(raw) ? [{ file, pattern: "sourceMappingURL" }] : [];
307
+ return [...uiFileProblems(file, packed), ...maps];
308
+ }
309
+ export function scanUiTree(root, ignores = [], moduleVersion, packed = false) {
310
+ const problems = uiFiles(root).flatMap(file => (packed ? packedUiProblems : uiFileProblems)(file, readFileSync(join(root, file))));
157
311
  return applyUiIgnores(problems, ignores, moduleVersion);
158
312
  }
313
+ /** Returns the resolved ignores; record them with storedUiSecretIgnores. */
159
314
  export function enforcePublicUi(root, ignores = [], moduleVersion) {
160
- const files = new Set(uiFiles(root).map(file => logicalUiFile(file, moduleVersion)));
161
- for (const ignore of ignores)
162
- if (!files.has(ignore.file))
163
- throw Object.assign(new Error(`ui_secret_ignores file does not exist: ui/${ignore.file}`), { code: "UI_SECRET_IGNORE_MISSING" });
164
- const problems = scanUiTree(root, ignores, moduleVersion);
315
+ const resolved = resolveUiSecretIgnores(uiFiles(root).map(file => logicalUiFile(file, moduleVersion)), ignores);
316
+ const raw = scanUiTree(root, [], moduleVersion);
317
+ const stale = staleUiIgnores(raw, resolved, moduleVersion);
318
+ if (stale.length)
319
+ throw Object.assign(new Error(stale.map(item => `ui_secret_ignores ui/${item.entry} match ${showUiMatch(item.match)} no longer occurs in ui/${item.file}`).join("\n")), { code: "UI_SECRET_IGNORE_STALE", hint: "Remove the stale match (or the whole entry) after reviewing the file again." });
320
+ const problems = applyUiIgnores(raw, resolved, moduleVersion);
165
321
  for (const problem of problems.filter(item => item.ignored))
166
- console.warn(`[UI_SECRET_IGNORED] ui/${problem.file}: ${problem.pattern}; reason: ${problem.ignored}`);
322
+ console.warn(`[UI_SECRET_IGNORED] ui/${problem.file}: ${problem.pattern}; ${problem.ignoredBy ? `matched ui/${problem.ignoredBy}; ` : ""}reason: ${problem.ignored}`);
167
323
  const errors = problems.filter(item => !item.ignored);
168
- if (errors.length)
169
- throw Object.assign(new Error(errors.map(item => `ui/${item.file}: ${item.pattern}`).join("\n")), { code: "PUBLIC_UI_UNSAFE", hint: "Files under ui/ are public. Remove credentials and source maps; only false positives may use ui_secret_ignores with a reason." });
324
+ if (errors.length) {
325
+ const paste = uiIgnoreSuggestion(errors, moduleVersion);
326
+ throw Object.assign(new Error(errors.map(describeUiProblem).join("\n") +
327
+ (paste ? `\nOnly if every hit is a reviewed false positive, add to dsm-package.yaml:\n${paste}` : "")), { code: "PUBLIC_UI_UNSAFE", hint: "Files under ui/ are public. Remove credentials and source maps; only false positives may use ui_secret_ignores with a reason and match." });
328
+ }
329
+ return resolved;
170
330
  }
171
331
  export function publicUiReport(files) {
172
332
  const bundles = files.filter(item => isUiBundle(item.file));
@@ -29,7 +29,7 @@ import { createReproducibleTar } from "../build-spk/reproducible-archive.js";
29
29
  import { renderStandaloneScript } from "./lifecycle.js";
30
30
  import { APP_SCRIPTS_DIR, APP_SCRIPTS_SPK_DIR } from "./app-scripts.js";
31
31
  import { MODULE_UI_ENTRY, uiTreeDigest } from "./ui-assets.js";
32
- import { enforcePublicUi, isUiBundle, logicalUiFile, minifyUi, minifyUiTree, uiFiles } from "./public-ui.js";
32
+ import { enforcePublicUi, isUiBundle, logicalUiFile, minifyUi, minifyUiTree, storedUiSecretIgnores, uiFiles } from "./public-ui.js";
33
33
  import { codedMessage } from "../errors.js";
34
34
  import { DSM_LANGS, LOCALES } from "./i18n.js";
35
35
  import { appTitle, CGI_PAYLOAD_PATH, hasSdkWindow, renderUiConfig, renderWindowScript, windowScriptName, } from "./dsm-window.js";
@@ -285,8 +285,8 @@ export async function assembleStandaloneSpk(options) {
285
285
  }
286
286
  writeFileSync(file, JSON.stringify(ports, null, 2) + "\n");
287
287
  }
288
- enforcePublicUi(uiRoot, manifest.uiSecretIgnores, moduleVersion);
289
- const ignoredUi = uiFiles(uiRoot).filter(file => manifest.uiSecretIgnores?.some(ignore => ignore.file === logicalUiFile(file, moduleVersion))).map(file => `ui/${file}`);
288
+ const uiIgnores = enforcePublicUi(uiRoot, manifest.uiSecretIgnores, moduleVersion);
289
+ const ignoredUi = uiFiles(uiRoot).filter(file => uiIgnores.some(ignore => ignore.file === logicalUiFile(file, moduleVersion))).map(file => `ui/${file}`);
290
290
  const packageTgz = join(staging, "package.tgz");
291
291
  await createReproducibleTar(join(staging, "package"), packageTgz, {
292
292
  rejectSecrets: true,
@@ -299,7 +299,8 @@ export async function assembleStandaloneSpk(options) {
299
299
  .digest("hex");
300
300
  writeFile(join(staging, "sdk-package.json"), JSON.stringify({
301
301
  schema: 2,
302
- ...(manifest.uiSecretIgnores?.length ? { ui_secret_ignores: manifest.uiSecretIgnores } : {}),
302
+ // Record resolved exact files: older CLIs reject `[hash]` when inspecting.
303
+ ...(uiIgnores.length ? { ui_secret_ignores: storedUiSecretIgnores(uiIgnores) } : {}),
303
304
  ...(manifest.tcpListeners ? { tcp_listeners: manifest.tcpListeners } : {}),
304
305
  ...(mobile ? { mobile: mobile.record } : {}),
305
306
  dependencies: packageDependencies(manifest),
package/dist/validate.js CHANGED
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { getErrorCode } from "./error-registry.js";
6
6
  import { loadStandaloneManifest } from "./standalone/manifest.js";
7
- import { applyUiIgnores, scanUiTree } from "./standalone/public-ui.js";
7
+ import { applyUiIgnores, describeUiProblem, resolveUiSecretIgnores, scanUiTree, showUiMatch, staleUiIgnores, uiFiles, uiIgnoreSuggestion } from "./standalone/public-ui.js";
8
8
  import { hasSdkWindow } from "./standalone/dsm-window.js";
9
9
  import { uiGuidanceWarnings } from "./standalone/ui-guidance.js";
10
10
  import { isNativeLayout, loadNativeLayout, } from "./standalone/native-layout.js";
@@ -52,14 +52,37 @@ export function validateProject(project, _options = {}) {
52
52
  for (const { dir, prefix } of roots) {
53
53
  if (!existsSync(dir))
54
54
  continue; // A build hook may not have produced its output yet.
55
+ let ignores;
55
56
  try {
56
- const ui = applyUiIgnores(scanUiTree(dir).map(item => ({ ...item, file: prefix + item.file })), manifest.uiSecretIgnores ?? []);
57
- for (const item of ui) {
57
+ // A build hook may not have produced every file yet; only ambiguity fails here.
58
+ ignores = resolveUiSecretIgnores(uiFiles(dir).map(file => prefix + file), manifest.uiSecretIgnores ?? [], false);
59
+ }
60
+ catch (error) {
61
+ const code = error.code;
62
+ problems.push(code === "UI_SECRET_IGNORE_AMBIGUOUS"
63
+ ? { code, span: { file: "dsm-package.yaml", line: 1, column: 1 }, message: error.message, suggestion: "Make the ui_secret_ignores entry specific enough to match exactly one file." }
64
+ : { code: "PUBLIC_UI_SCAN_FAILED", span: { file: "ui/", line: 1, column: 1 }, message: "Cannot read public UI files.", suggestion: "Use only readable regular files and directories." });
65
+ continue;
66
+ }
67
+ try {
68
+ // Scan JS/CSS as build packs it (minified), so printed match texts agree with build.
69
+ const raw = scanUiTree(dir, [], undefined, true).map(item => ({ ...item, file: prefix + item.file }));
70
+ for (const stale of staleUiIgnores(raw, ignores))
71
+ problems.push({
72
+ code: "UI_SECRET_IGNORE_STALE", span: { file: "dsm-package.yaml", line: 1, column: 1 },
73
+ message: `ui_secret_ignores ui/${stale.entry} match ${showUiMatch(stale.match)} no longer occurs in ui/${stale.file}`,
74
+ suggestion: "Remove the stale match (or the whole entry) after reviewing the file again.",
75
+ });
76
+ for (const item of applyUiIgnores(raw, ignores)) {
77
+ const paste = item.ignored ? "" : uiIgnoreSuggestion([item]);
58
78
  const finding = {
59
79
  code: item.ignored ? "UI_SECRET_IGNORED" : "PUBLIC_UI_UNSAFE",
60
80
  span: { file: `ui/${item.file}`, line: 1, column: 1 },
61
- message: `${item.pattern}${item.ignored ? `; reason: ${item.ignored}` : ""}`,
62
- suggestion: "Files under ui/ are public. Remove credentials and source maps; false positives require ui_secret_ignores with a reason.",
81
+ message: item.ignored
82
+ ? `${item.pattern}; ${item.ignoredBy ? `matched ui/${item.ignoredBy}; ` : ""}reason: ${item.ignored}`
83
+ : describeUiProblem(item).slice(`ui/${item.file}: `.length),
84
+ suggestion: "Files under ui/ are public. Remove credentials and source maps; false positives require ui_secret_ignores with a reason and match." +
85
+ (paste ? ` Only if this is a reviewed false positive, add:\n${paste}` : ""),
63
86
  };
64
87
  if (item.ignored)
65
88
  warnings.push(finding);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.53.5",
3
+ "version": "0.53.6",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -29,15 +29,21 @@
29
29
  "additionalProperties": false
30
30
  },
31
31
  "ui_secret_ignores": {
32
- "description": "False-positive exceptions for public UI secret scanning. Exact paths relative to ui/; omit a module snapshot hash (app/help.json). Source maps cannot be ignored.",
32
+ "description": "False-positive exceptions for public UI secret scanning. file is an exact path relative to ui/ (omit a module snapshot hash: app/help.json) and may contain one [hash] for a bundler content hash ([A-Za-z0-9_-]{6,64}, within one path segment) that must match exactly one file. match lists the exact flagged texts to exempt (required with [hash]); other hits in the file still fail, and a listed text that no longer occurs fails the build. Source maps cannot be ignored.",
33
33
  "type": "array",
34
34
  "items": {
35
35
  "type": "object",
36
36
  "required": ["file", "reason"],
37
37
  "properties": {
38
- "file": {"type": "string", "minLength": 1, "pattern": "^(?![\\s\\S]*(?:^|/)\\.{1,2}(?:/|$))[^/\\\\*?\\[\\]{}:\\u0000-\\u001f\\u007f]+(?:/[^/\\\\*?\\[\\]{}:\\u0000-\\u001f\\u007f]+)*$(?![\\s\\S])"},
39
- "reason": {"type": "string", "pattern": "\\S"}
38
+ "file": {"type": "string", "minLength": 1, "pattern": "^(?![\\s\\S]*\\[hash\\][\\s\\S]*\\[hash\\])(?![\\s\\S]*(?:^|/)\\.{1,2}(?:/|$))(?:[^/\\\\*?\\[\\]{}:\\u0000-\\u001f\\u007f]|\\[hash\\])+(?:/(?:[^/\\\\*?\\[\\]{}:\\u0000-\\u001f\\u007f]|\\[hash\\])+)*$(?![\\s\\S])"},
39
+ "reason": {"type": "string", "pattern": "\\S"},
40
+ "match": {"oneOf": [
41
+ {"type": "string", "minLength": 1, "maxLength": 4096},
42
+ {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "minLength": 1, "maxLength": 4096}}
43
+ ]}
40
44
  },
45
+ "if": {"properties": {"file": {"pattern": "\\[hash\\]"}}},
46
+ "then": {"required": ["match"]},
41
47
  "additionalProperties": false
42
48
  }
43
49
  },
@@ -5,17 +5,24 @@ Files under ui/ (including mobile.json and entry.html) are public static files r
5
5
  `build` minifies packaged JS/CSS and removes `.map` files and their JS/CSS comments.
6
6
  `check` scans the current UI output; `check path/to/package.spk` scans the final
7
7
  archived public payload, including generated scripts. Build also scans that payload.
8
- Keep LICENSES files in the output. For a verified false positive, declare an exact
9
- file relative to `ui/` with a reason (omit the module snapshot hash):
8
+ Keep LICENSES files in the output. For a verified false positive, declare the
9
+ file relative to `ui/` (omit the module snapshot hash) with a reason and the
10
+ exact flagged text. A bundler-hashed chunk uses one `[hash]`, which must match
11
+ exactly one file and requires `match`:
10
12
 
11
13
  ```yaml
12
14
  ui_secret_ignores:
13
- - file: app/help.json
14
- reason: Documentation example containing a deliberately fake credential
15
+ - file: "app/chunks/Dialog-[hash].js"
16
+ reason: "Placeholder text in a third-party form, reviewed"
17
+ match: 'secret:"example-value"'
15
18
  ```
16
19
 
17
- Exceptions are recorded in the SPK and reported during inspection. They never
18
- allow source maps and do not bypass repository secret checks.
20
+ Only listed texts are exempt: a new hit in the same file still fails, and a
21
+ listed text that disappears fails as stale. `build` and `check` print a
22
+ ready-to-paste entry for each failing file; paste it only after review.
23
+ Exceptions are recorded in the SPK as resolved files and reported during
24
+ inspection. They never allow source maps and do not bypass repository secret
25
+ checks. See docs/release-checks.md.
19
26
 
20
27
  ## Choose Vue or JSON
21
28