@synopackageland/cli 0.48.23 → 0.48.24

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.48.24
4
+
5
+ - Check tracked secret files only inside the App project directory, and warn about untracked local secrets across the repository without clone-safe ignore rules
6
+ - Preserve tracked upstream fixtures, environment templates and public certificates; detect private-key PEM content and binary PKCS#12 instead of rejecting certificate filenames
7
+ - Enforce the project check during builds and CLI release/publish preflight; reject non-template environment files, npm auth tokens and private-key PEM blocks during SPK packing
8
+ - Protect local secrets in generated ignore files and document secret placement for own Apps and upstream forks
9
+ - Allow explicit `allow_secret_files` payload paths with build warnings and check notices; reject patterns and missing files without relaxing repository or metadata checks
10
+
3
11
  ## 0.48.23
4
12
 
5
13
  - Show paths that bypass DSM sign-in in inspect and check, including upstream-auth paths, permanent and optional passthrough, and public gateway/upstream access; JSON includes the declared paths and nonblocking review notices
@@ -5,4 +5,6 @@ export declare function collectArchiveEntries(root: string): string[];
5
5
  /** Writes `sourceDir` to `outputPath` as a tar whose bytes depend only on the file contents. */
6
6
  export declare function createReproducibleTar(sourceDir: string, outputPath: string, options?: {
7
7
  gzip?: boolean;
8
+ rejectSecrets?: boolean;
9
+ allowSecretFiles?: string[];
8
10
  }): Promise<void>;
@@ -1,6 +1,7 @@
1
- import { readdirSync, statSync } from "node:fs";
1
+ import { lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import * as tar from "tar";
4
+ import { allowedSecretFileWarnings, readAllowedSecretFiles, secretFile } from "../secret-files.js";
4
5
  /** Every archive this CLI writes uses the same timestamp so builds are byte-identical. */
5
6
  export const FIXED_MTIME = new Date(0);
6
7
  /** Relative paths of every file under `root`, depth-first and sorted for a stable archive order. */
@@ -24,11 +25,35 @@ export function collectArchiveEntries(root) {
24
25
  }
25
26
  /** Writes `sourceDir` to `outputPath` as a tar whose bytes depend only on the file contents. */
26
27
  export async function createReproducibleTar(sourceDir, outputPath, options = {}) {
28
+ const entries = collectArchiveEntries(sourceDir);
29
+ if (options.rejectSecrets) {
30
+ const allowed = new Set(readAllowedSecretFiles(options.allowSecretFiles));
31
+ const files = new Set(entries);
32
+ for (const path of allowed) {
33
+ if (!files.has(path) || !lstatSync(join(sourceDir, path)).isFile()) {
34
+ throw Object.assign(new Error(`allow_secret_files entry must match an existing regular payload file exactly: ${JSON.stringify(path)}`), {
35
+ code: "SECRET_FILE_ALLOWLIST_MISSING",
36
+ hint: "Use an exact path relative to package.tgz; generate the file before packing or remove the entry.",
37
+ });
38
+ }
39
+ }
40
+ for (const warning of allowedSecretFileWarnings([...allowed])) {
41
+ console.warn(`[${warning.code}] ${warning.message}\n${warning.suggestion}`);
42
+ }
43
+ for (const path of entries) {
44
+ if (!allowed.has(path) && secretFile(path, () => readFileSync(join(sourceDir, path)))) {
45
+ throw Object.assign(new Error(`Secret file cannot be packed: ${JSON.stringify(path)}`), {
46
+ code: "SECRET_FILE_PACKED",
47
+ hint: "Remove the secret from packaged UI, payload and metadata inputs; provide it at runtime.",
48
+ });
49
+ }
50
+ }
51
+ }
27
52
  await tar.c({
28
53
  file: outputPath,
29
54
  cwd: sourceDir,
30
55
  gzip: options.gzip ?? false,
31
56
  portable: true,
32
57
  mtime: FIXED_MTIME,
33
- }, collectArchiveEntries(sourceDir));
58
+ }, entries);
34
59
  }
@@ -1,6 +1,14 @@
1
1
  import { COMPOSE_ERRORS } from "./standalone/compose-errors.js";
2
+ import { SECRET_FILE_FIX } from "./secret-files.js";
2
3
  export const ERROR_REGISTRY = {
3
4
  ...COMPOSE_ERRORS,
5
+ SECRET_FILE_TRACKED: { code: "SECRET_FILE_TRACKED", description: "Git tracks a local secret file.", suggestion: SECRET_FILE_FIX },
6
+ SECRET_FILE_UNIGNORED: { code: "SECRET_FILE_UNIGNORED", description: "A local secret file lacks a repository ignore rule.", suggestion: SECRET_FILE_FIX },
7
+ SECRET_FILE_PACKED: { code: "SECRET_FILE_PACKED", description: "An SPK input contains a local secret file.", suggestion: "Remove the secret from packaged UI, payload and metadata inputs; provide it at runtime." },
8
+ SECRET_FILE_ALLOWLIST_INVALID: { code: "SECRET_FILE_ALLOWLIST_INVALID", description: "allow_secret_files is not a list of unique exact payload paths.", suggestion: "Use payload-relative file paths without globs, absolute paths, dot segments or duplicates." },
9
+ SECRET_FILE_ALLOWLIST_MISSING: { code: "SECRET_FILE_ALLOWLIST_MISSING", description: "An allowed secret path does not match a regular payload file.", suggestion: "Generate the file before packing or remove the entry from allow_secret_files; directories are not allowed." },
10
+ SECRET_FILE_ALLOWED: { code: "SECRET_FILE_ALLOWED", description: "A payload file is explicitly exempted from the SPK secret guard.", suggestion: "Do not use this for credentials; prefer generating keys at install/runtime. Tracked secrets still fail repository checks." },
11
+ SECRET_FILES_CHECK_FAILED: { code: "SECRET_FILES_CHECK_FAILED", description: "The repository secret-file check could not finish.", suggestion: "Restore Git repository and file access and retry." },
4
12
  HOST_CERT_CHANGED: { "code": "HOST_CERT_CHANGED", "description": "Strict TLS: the NAS certificate differs from the recorded SHA-256", "suggestion": "Verify old/new fingerprints, then run synopkgland host trust <name>" },
5
13
  HOST_TLS_UNTRUSTED: { "code": "HOST_TLS_UNTRUSTED", "description": "Strict TLS: the NAS certificate failed CA, hostname or validity verification", "suggestion": "Check the CA file, NAS hostname and certificate validity, or omit strict TLS" },
6
14
  HOST_DNS_FAILED: { "code": "HOST_DNS_FAILED", "description": "The NAS hostname could not be resolved", "suggestion": "Check the registered hostname and DNS" },
package/dist/init.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { validateForkRecipe, writeForkScaffold } from "./init-upstream.js";
2
+ import { ENV_TEMPLATE_NAMES } from "./secret-files.js";
2
3
  import { goChildEnv } from "./runtime/go-env.js";
3
4
  import { spawnSync } from "node:child_process";
4
5
  import { parse, parseDocument } from "yaml";
@@ -276,6 +277,11 @@ export function initFromTemplate(template, targetDir, options = {}) {
276
277
  renameSync(join(targetDir, from), join(targetDir, to));
277
278
  }
278
279
  }
280
+ const ignoreFile = join(targetDir, ".gitignore");
281
+ const ignore = existsSync(ignoreFile) ? readFileSync(ignoreFile, "utf8") : "";
282
+ // Applies inside synology/ for a fork; never change upstream ignore files.
283
+ const secretRules = [".env", ".env.*", ...ENV_TEMPLATE_NAMES.map(name => `!${name}`)];
284
+ writeFileSync(ignoreFile, `${ignore.trimEnd()}\n\n# Local secrets\n${secretRules.join("\n")}\n`);
279
285
  for (const file of files.map(targetName))
280
286
  substitute(join(targetDir, file), substitutions);
281
287
  if (localSdk && isNativeTemplate(template))
@@ -0,0 +1,19 @@
1
+ import type { ValidationError } from "./types.js";
2
+ export declare const SECRET_FILE_FIX = "Move it under synology/ (forks) or add it to the repo .gitignore; remove tracked secrets from the index and rotate exposed credentials.";
3
+ export declare const ENV_TEMPLATE_NAMES: string[];
4
+ /** Exact, canonical POSIX payload paths only; never interpret patterns. */
5
+ export declare function readAllowedSecretFiles(value: unknown): string[] | undefined;
6
+ export declare function allowedSecretFileWarnings(paths?: string[]): ValidationError[];
7
+ /** Environment templates are allowed by name; other environment files are local. */
8
+ export declare function secretFileName(path: string): boolean;
9
+ /** Payload checks inspect content regardless of filename, including extensionless keys. */
10
+ export declare function secretFile(path: string, read: () => string | Buffer): boolean;
11
+ /** Recognize a DER PKCS#12 PFX envelope, rather than treating every binary as a key. */
12
+ export declare function binaryPkcs12(content: Buffer): boolean;
13
+ /** Tracked errors belong to the App directory; local untracked warnings span the repo. */
14
+ export declare function repositorySecretFiles(cwd: string): ValidationError[];
15
+ /** Build/release entry points must refuse tracked secrets, even without `check`. */
16
+ export declare function enforceRepositorySecrets(cwd: string, warn?: {
17
+ (...data: any[]): void;
18
+ (message?: any, ...optionalParams: any[]): void;
19
+ }): void;
@@ -0,0 +1,173 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ export const SECRET_FILE_FIX = "Move it under synology/ (forks) or add it to the repo .gitignore; remove tracked secrets from the index and rotate exposed credentials.";
5
+ export const ENV_TEMPLATE_NAMES = [
6
+ ".env.example", ".env.sample", ".env.template", ".env.dist", ".env.defaults",
7
+ ];
8
+ /** Exact, canonical POSIX payload paths only; never interpret patterns. */
9
+ export function readAllowedSecretFiles(value) {
10
+ if (value === undefined)
11
+ return undefined;
12
+ if (!Array.isArray(value) || value.some(path => typeof path !== "string" ||
13
+ /[\\*?\[\]{}:\x00-\x1f\x7f]/.test(path) ||
14
+ path.split("/").some(part => part === "" || part === "." || part === "..")) || new Set(value).size !== value.length) {
15
+ throw Object.assign(new Error("allow_secret_files must be a list of unique, exact payload-relative file paths; no globs, directories, absolute paths or dot segments."), { code: "SECRET_FILE_ALLOWLIST_INVALID" });
16
+ }
17
+ return [...value];
18
+ }
19
+ export function allowedSecretFileWarnings(paths = []) {
20
+ return paths.map(path => ({
21
+ code: "SECRET_FILE_ALLOWED",
22
+ severity: "warning",
23
+ span: { file: "dsm-package.yaml", line: 1, column: 1 },
24
+ message: `SPK secret guard explicitly allows payload file: ${JSON.stringify(path)}`,
25
+ suggestion: "Do not use this for credentials; prefer generating keys at install/runtime. Tracked secrets still fail repository checks.",
26
+ }));
27
+ }
28
+ /** Environment templates are allowed by name; other environment files are local. */
29
+ export function secretFileName(path) {
30
+ const name = basename(path);
31
+ return (name === ".env" || name.startsWith(".env.")) && !ENV_TEMPLATE_NAMES.includes(name);
32
+ }
33
+ /** Payload checks inspect content regardless of filename, including extensionless keys. */
34
+ export function secretFile(path, read) {
35
+ if (secretFileName(path))
36
+ return true;
37
+ const bytes = read();
38
+ const content = Buffer.isBuffer(bytes) ? bytes.toString("latin1") : bytes;
39
+ return (basename(path) === ".npmrc" && /_authToken/.test(content)) ||
40
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(content);
41
+ }
42
+ /** Recognize a DER PKCS#12 PFX envelope, rather than treating every binary as a key. */
43
+ export function binaryPkcs12(content) {
44
+ const tlv = (offset) => {
45
+ if (offset + 2 > content.length)
46
+ return;
47
+ const tag = content[offset++];
48
+ let length = content[offset++];
49
+ if (length & 0x80) {
50
+ const count = length & 0x7f;
51
+ if (!count || count > 4 || offset + count > content.length)
52
+ return;
53
+ length = 0;
54
+ for (let i = 0; i < count; i++)
55
+ length = length * 256 + content[offset++];
56
+ }
57
+ const end = offset + length;
58
+ if (end > content.length)
59
+ return;
60
+ return { tag, start: offset, end };
61
+ };
62
+ const pfx = tlv(0);
63
+ if (!pfx || pfx.tag !== 0x30 || pfx.end !== content.length)
64
+ return false;
65
+ const version = tlv(pfx.start);
66
+ if (!version || version.tag !== 2 || version.end - version.start !== 1 || content[version.start] !== 3)
67
+ return false;
68
+ const authSafe = tlv(version.end);
69
+ if (!authSafe || authSafe.tag !== 0x30 || authSafe.end > pfx.end)
70
+ return false;
71
+ const oid = tlv(authSafe.start);
72
+ if (!oid || oid.tag !== 6 || oid.end > authSafe.end)
73
+ return false;
74
+ // authSafe is PKCS#7 data or signedData (1.2.840.113549.1.7.1 / .2).
75
+ const type = content.subarray(oid.start, oid.end).toString("hex");
76
+ if (type !== "2a864886f70d010701" && type !== "2a864886f70d010702")
77
+ return false;
78
+ const value = tlv(oid.end);
79
+ return Boolean(value && value.tag === 0xa0 && value.end === authSafe.end);
80
+ }
81
+ function problem(code, path, severity) {
82
+ return {
83
+ code, severity, span: { file: path, line: 1, column: 1 },
84
+ message: `${severity === "error" ? "Git tracks a secret file" : "Secret file lacks a repository .gitignore rule"}: ${JSON.stringify(path)}`,
85
+ suggestion: SECRET_FILE_FIX,
86
+ };
87
+ }
88
+ /** Tracked errors belong to the App directory; local untracked warnings span the repo. */
89
+ export function repositorySecretFiles(cwd) {
90
+ const projectRoot = realpathSync(cwd);
91
+ const gitBytes = (args, input, allowNoMatch = false) => {
92
+ const result = spawnSync("git", args, {
93
+ cwd, input, maxBuffer: 64 * 1024 * 1024,
94
+ env: { ...process.env, LC_ALL: "C" },
95
+ });
96
+ if (result.status !== 0 && !(allowNoMatch && result.status === 1)) {
97
+ throw Object.assign(new Error("Cannot check repository secret files."), {
98
+ code: "SECRET_FILES_CHECK_FAILED",
99
+ hint: "Restore Git repository access and retry.",
100
+ });
101
+ }
102
+ return result.stdout;
103
+ };
104
+ const git = (args, input, allowNoMatch = false) => gitBytes(args, input, allowNoMatch).toString("utf8");
105
+ const location = spawnSync("git", ["rev-parse", "--show-toplevel"], {
106
+ cwd, encoding: "utf8", env: { ...process.env, LC_ALL: "C" },
107
+ });
108
+ if (location.status !== 0) {
109
+ if (location.status === 128 && location.stderr?.includes("not a git repository"))
110
+ return [];
111
+ throw Object.assign(new Error("Cannot check repository secret files."), { code: "SECRET_FILES_CHECK_FAILED" });
112
+ }
113
+ cwd = location.stdout.replace(/\r?\n$/, "");
114
+ const tracked = new Set(git(["ls-files", "--cached", "-z"]).split("\0").filter(Boolean));
115
+ // No exclude-standard: local-only excludes and ignored files must remain visible.
116
+ const files = new Set([...tracked, ...git(["ls-files", "--others", "-z"]).split("\0").filter(Boolean)]);
117
+ const candidates = [...files].sort().filter(path => {
118
+ if (tracked.has(path)) {
119
+ const within = relative(projectRoot, resolve(cwd, path));
120
+ if (isAbsolute(within) || within === ".." || within.startsWith(`..${sep}`))
121
+ return false;
122
+ }
123
+ const name = basename(path);
124
+ return secretFileName(path) || name === ".npmrc" ||
125
+ /\.(?:pem|key|p12)$/.test(name) || name.startsWith("id_rsa");
126
+ });
127
+ if (!candidates.length)
128
+ return [];
129
+ // Verbose NUL output identifies the winning rule. Global rules and info/exclude
130
+ // cannot protect a fresh clone; a negated rule is not an ignore rule.
131
+ const ignored = git(["-c", "core.excludesFile=", "check-ignore", "--no-index", "-v", "-z", "--stdin"], candidates.join("\0") + "\0", true).split("\0");
132
+ const protectedFiles = new Set();
133
+ for (let i = 0; i + 3 < ignored.length; i += 4) {
134
+ const [source, , pattern, path] = ignored.slice(i, i + 4);
135
+ if ((source === ".gitignore" || source.endsWith("/.gitignore")) && !pattern.startsWith("!"))
136
+ protectedFiles.add(path);
137
+ }
138
+ return candidates.flatMap(path => {
139
+ if (!tracked.has(path) && protectedFiles.has(path))
140
+ return [];
141
+ const sensitive = (read) => {
142
+ if (secretFileName(path))
143
+ return true;
144
+ const content = read();
145
+ return secretFile(path, () => content) ||
146
+ (/\.(?:pem|key|p12)$/.test(path) && binaryPkcs12(content));
147
+ };
148
+ let found = false;
149
+ try {
150
+ // Inspect both index and working copy: unstaged cleanup cannot hide a staged key.
151
+ if (tracked.has(path))
152
+ found = sensitive(() => gitBytes(["show", `:${path}`]));
153
+ const local = join(cwd, path);
154
+ if (!found && existsSync(local)) {
155
+ found = sensitive(() => readFileSync(local));
156
+ }
157
+ }
158
+ catch {
159
+ throw Object.assign(new Error(`Cannot check secret file: ${JSON.stringify(path)}`), { code: "SECRET_FILES_CHECK_FAILED" });
160
+ }
161
+ return found ? [problem(tracked.has(path) ? "SECRET_FILE_TRACKED" : "SECRET_FILE_UNIGNORED", path, tracked.has(path) ? "error" : "warning")] : [];
162
+ });
163
+ }
164
+ /** Build/release entry points must refuse tracked secrets, even without `check`. */
165
+ export function enforceRepositorySecrets(cwd, warn = console.warn) {
166
+ const findings = repositorySecretFiles(cwd);
167
+ for (const finding of findings.filter(item => item.severity === "warning")) {
168
+ warn(`[${finding.code}] ${finding.message}\n${finding.suggestion}`);
169
+ }
170
+ const errors = findings.filter(item => item.severity === "error");
171
+ if (errors.length)
172
+ throw Object.assign(new Error(errors.map(item => `[${item.code}] ${item.message}`).join("\n")), { code: "SECRET_FILE_TRACKED", hint: SECRET_FILE_FIX });
173
+ }
@@ -1,4 +1,5 @@
1
1
  import { buildInstallSettings } from './install-settings.js';
2
+ import { enforceRepositorySecrets } from "../secret-files.js";
2
3
  import { buildAppBackup } from './hyper-backup.js';
3
4
  import { auditGoRoutes, httpRoutesDigest } from './route-audit.js';
4
5
  import { PORTAL_REQUIRES_EXECUTOR } from "../portal/alias.js";
@@ -102,6 +103,7 @@ export function runnerFor(run, jobs, arch) {
102
103
  }
103
104
  /** `build` for a Standalone Package: build the UI, compile the CGI, pack one SPK per arch. */
104
105
  export async function buildStandalone(options) {
106
+ enforceRepositorySecrets(options.root);
105
107
  const loaded = loadStandaloneManifest(options.root);
106
108
  if (!loaded.ok) {
107
109
  const [first] = loaded.errors;
@@ -45,6 +45,8 @@ export interface StandaloneI18n {
45
45
  info: InfoTranslations;
46
46
  }
47
47
  export interface StandaloneManifest {
48
+ /** Exact payload paths exempted from the SPK secret guard, never repository checks. */
49
+ allowSecretFiles?: string[];
48
50
  ctl?: {
49
51
  enabled: boolean;
50
52
  registry?: string;
@@ -1,4 +1,5 @@
1
1
  import { daemonNoFileSdkProblem, daemonNoFileIdentityProblem, DAEMON_NOFILE_MIN_DSM, DAEMON_NOFILE_UNSUPPORTED, DAEMON_NOFILE_ACTIVATION_PROBLEM } from './daemon-nofile.js';
2
+ import { readAllowedSecretFiles } from "../secret-files.js";
2
3
  import { readRegistry, registryFile } from '../ctl/registry.js';
3
4
  import { gatewayIngressPathProblem, gatewayIngressOwnershipSupported } from './gateway-ingress.js';
4
5
  import { nativeGatewaySdk } from "./native-gateway.js";
@@ -46,6 +47,7 @@ import { BRIDGE_RUNTIMES, isBridgeBackend, overlaps, readBridgeBackend, } from "
46
47
  */
47
48
  export const STANDALONE_MANIFEST = "dsm-package.yaml";
48
49
  export const KNOWN_FIELDS = new Set([
50
+ "allow_secret_files",
49
51
  "ctl",
50
52
  "schema",
51
53
  "package",
@@ -154,6 +156,13 @@ export function loadStandaloneManifest(root) {
154
156
  : { ok: false, errors: c.errors };
155
157
  }
156
158
  function readManifest(raw, c) {
159
+ let allowSecretFiles;
160
+ try {
161
+ allowSecretFiles = readAllowedSecretFiles(raw.allow_secret_files);
162
+ }
163
+ catch (error) {
164
+ c.fail("SECRET_FILE_ALLOWLIST_INVALID", error.message);
165
+ }
157
166
  for (const key of Object.keys(raw)) {
158
167
  if (!KNOWN_FIELDS.has(key)) {
159
168
  c.fail("STANDALONE_FIELD_UNKNOWN", `Unsupported field "${key}". A Standalone Package does not accept DSM conf; put lifecycle scripts in dsm-scripts/<DSM script name>.`);
@@ -582,6 +591,7 @@ function readManifest(raw, c) {
582
591
  }
583
592
  return {
584
593
  ...(raw.ctl ? { ctl: raw.ctl } : {}),
594
+ ...(allowSecretFiles ? { allowSecretFiles } : {}),
585
595
  root: c.root,
586
596
  package: packageId,
587
597
  version,
@@ -21,6 +21,8 @@ type Binary = {
21
21
  arches?: LayoutArch[];
22
22
  };
23
23
  export interface NativeLayout {
24
+ /** Exact payload paths exempted from the SPK secret guard, never repository checks. */
25
+ allowSecretFiles?: string[];
24
26
  metadata?: PackageMetadata;
25
27
  dependencies?: PackageDependencies;
26
28
  root: string;
@@ -4,6 +4,7 @@ import { validateMetadata, metadataInfoFields } from "../package-metadata.js";
4
4
  /** Existing native products: the CLI owns archives/INFO, the project owns its layout. */
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
+ import { enforceRepositorySecrets, readAllowedSecretFiles } from '../secret-files.js';
7
8
  import { tmpdir } from 'node:os';
8
9
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
9
10
  import { parse } from 'yaml';
@@ -107,7 +108,9 @@ export function isNativeLayout(root) {
107
108
  }
108
109
  export function loadNativeLayout(root) {
109
110
  try {
110
- const m = object(parse(readFileSync(join(root, 'dsm-package.yaml'), 'utf8')), ['schema', 'backend', 'package', 'version', 'build', 'displayname', 'description', 'maintainer', 'metadata', 'os_min_ver', 'privilege', 'arches', 'layout', 'native', 'icon', 'reproducible', 'portal', 'dependencies']);
111
+ const m = object(parse(readFileSync(join(root, 'dsm-package.yaml'), 'utf8')), ['schema', 'backend', 'package', 'version', 'build', 'displayname', 'description', 'maintainer', 'metadata', 'os_min_ver', 'privilege', 'arches', 'layout', 'native', 'icon', 'reproducible', 'portal', 'dependencies', 'allow_secret_files']);
112
+ const allowSecretFiles = readAllowedSecretFiles(m.allow_secret_files);
113
+ delete m.allow_secret_files;
111
114
  if (m.schema !== 2)
112
115
  fail('schema 2 required; migrate schema: 1 to schema: 2 and add backend: {kind: native}');
113
116
  const backend = object(m.backend, ['kind']);
@@ -163,7 +166,7 @@ export function loadNativeLayout(root) {
163
166
  fail('toolkits require HTTPS and SHA-256');
164
167
  }
165
168
  }
166
- return { ok: true, manifest: { ...m, root: resolve(root), native: { hook: hook(native.hook), ...(native.prepare ? { prepare: hook(native.prepare) } : {}), toolkits } } };
169
+ return { ok: true, manifest: { ...m, ...(allowSecretFiles ? { allowSecretFiles } : {}), root: resolve(root), native: { hook: hook(native.hook), ...(native.prepare ? { prepare: hook(native.prepare) } : {}), toolkits } } };
167
170
  }
168
171
  catch (error) {
169
172
  return { ok: false, errors: [{ code: 'NATIVE_LAYOUT_INVALID', message: String(error) }] };
@@ -298,6 +301,7 @@ export function checkLayoutMetadata(root, inspection = false, packageId) {
298
301
  }
299
302
  }
300
303
  export async function buildNativeLayout(options) {
304
+ enforceRepositorySecrets(options.root);
301
305
  const loaded = loadNativeLayout(options.root);
302
306
  if (!loaded.ok)
303
307
  fail(loaded.errors.map(e => e.message).join('\n'));
@@ -347,7 +351,7 @@ export async function buildNativeLayout(options) {
347
351
  const target = join(stage, 'payload');
348
352
  mkdirSync(target);
349
353
  const files = copyTree(payload, target);
350
- await createReproducibleTar(target, join(stage, 'package.tgz'), { gzip: true });
354
+ await createReproducibleTar(target, join(stage, 'package.tgz'), { gzip: true, rejectSecrets: true, allowSecretFiles: m.allowSecretFiles });
351
355
  rmSync(target, { recursive: true });
352
356
  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') };
353
357
  const deps = dependencyInfo(m.dependencies ?? { packages: [] });
@@ -357,7 +361,7 @@ export async function buildNativeLayout(options) {
357
361
  writeFileSync(join(stage, 'INFO'), info.map(([k, v]) => `${k}="${v.replace(/([\\"$`])/g, '\\$1')}"\n`).join(''));
358
362
  writeFileSync(join(stage, 'native-layout.json'), JSON.stringify({ format: 1, arch, dependencies: m.dependencies ?? { packages: [] }, binaries: binaries.map(({ path, linkage }) => ({ path, linkage })), files, ...(m.layout.anchors ? { anchors: m.layout.anchors } : {}), ...(m.portal ? { portal: m.portal } : {}) }));
359
363
  const output = join(outDir, `${m.package}-${version}-${arch}.spk`);
360
- await createReproducibleTar(stage, output);
364
+ await createReproducibleTar(stage, output, { rejectSecrets: true });
361
365
  return output;
362
366
  }
363
367
  finally {
@@ -250,6 +250,8 @@ export async function assembleStandaloneSpk(options) {
250
250
  }));
251
251
  const packageTgz = join(staging, "package.tgz");
252
252
  await createReproducibleTar(join(staging, "package"), packageTgz, {
253
+ rejectSecrets: true,
254
+ allowSecretFiles: manifest.allowSecretFiles,
253
255
  gzip: true,
254
256
  });
255
257
  rmSync(join(staging, "package"), { recursive: true, force: true });
@@ -355,7 +357,7 @@ export async function assembleStandaloneSpk(options) {
355
357
  });
356
358
  writePackageCenterIcons(staging, icons);
357
359
  mkdirSync(dirname(options.outputPath), { recursive: true });
358
- await createReproducibleTar(staging, options.outputPath);
360
+ await createReproducibleTar(staging, options.outputPath, { rejectSecrets: true });
359
361
  }
360
362
  finally {
361
363
  rmSync(staging, { recursive: true, force: true });
package/dist/validate.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { upstreamAttributionWarnings } from './upstream-attribution.js';
2
+ import { allowedSecretFileWarnings, repositorySecretFiles } from "./secret-files.js";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { getErrorCode } from "./error-registry.js";
@@ -26,18 +27,25 @@ export function validateProject(project, _options = {}) {
26
27
  const policy = loaded.ok && "capabilities" in loaded.manifest
27
28
  ? manifestPolicyProblem(loaded.manifest)
28
29
  : undefined;
29
- const problems = loaded.ok ? (policy ? [policy] : []) : loaded.errors;
30
+ const secrets = repositorySecretFiles(project.root);
31
+ const warnings = [...upstreamAttributionWarnings(project.root), ...secrets.filter(item => item.severity === "warning"),
32
+ ...(loaded.ok ? allowedSecretFileWarnings(loaded.manifest.allowSecretFiles) : [])];
33
+ const problems = [
34
+ ...(loaded.ok ? (policy ? [policy] : []) : loaded.errors).map(error => ({
35
+ ...error,
36
+ span: { file, line: 1, column: 1 },
37
+ suggestion: getErrorCode(error.code)?.suggestion ??
38
+ "Correct the schema-2 declaration; see the SDK Compose support matrix.",
39
+ })),
40
+ ...secrets.filter(item => item.severity === "error"),
41
+ ];
30
42
  return problems.length
31
43
  ? {
32
44
  ok: false,
33
- errors: problems.map((error) => ({
34
- ...error,
35
- span: { file, line: 1, column: 1 },
36
- suggestion: getErrorCode(error.code)?.suggestion ??
37
- "Correct the schema-2 declaration; see the SDK Compose support matrix.",
38
- })),
45
+ warnings,
46
+ errors: problems,
39
47
  }
40
- : { ok: true, errors: [], warnings: [...upstreamAttributionWarnings(project.root),
48
+ : { ok: true, errors: [], warnings: [...warnings,
41
49
  ...(loaded.ok && 'ctl' in loaded.manifest && loaded.manifest.ctl?.enabled && !loaded.manifest.ctl.registry ? [{
42
50
  code: 'CTL_LEGACY_COMMANDS_DEPRECATED', severity: 'warning',
43
51
  span: { file, line: 1, column: 1 },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.48.23",
3
+ "version": "0.48.24",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,9 +31,9 @@
31
31
  "test:scripts": "node --test scripts/test/gate.test.mjs scripts/test/release.test.mjs scripts/test/pack-docker.test.mjs scripts/test/npm-pack.test.mjs scripts/test/executor-bump.test.mjs scripts/test/smoke-exports.test.mjs scripts/test/parallel.test.mjs scripts/test/scaffold-matrix.test.mjs scripts/test/frontend-deps.test.mjs scripts/test/docker-gate.test.mjs scripts/test/gate-plan.test.mjs scripts/test/gates.test.mjs && python3 scripts/test/npm-publish.py",
32
32
  "gates": "bash scripts/ci/gates.sh",
33
33
  "gates:fast": "bash scripts/ci/gates.sh",
34
- "prepublishOnly": "npm run build",
34
+ "prepublishOnly": "npm run build && node --input-type=module -e 'import {enforceRepositorySecrets} from \"./dist/secret-files.js\"; enforceRepositorySecrets(process.cwd())'",
35
35
  "gates:full": "bash scripts/ci/gates.sh --full",
36
- "test:basic": "node --import tsx --test test/schema.test.ts test/standalone-manifest.test.ts test/native-arch.test.ts test/archive-inventory.test.ts",
36
+ "test:basic": "node --import tsx --test test/schema.test.ts test/standalone-manifest.test.ts test/native-arch.test.ts test/archive-inventory.test.ts test/secret-files.test.ts",
37
37
  "check:dsm-contract": "node scripts/check-dsm-api-contract.mjs",
38
38
  "check:dsm-hub": "node scripts/check-dsm-api-hub.mjs"
39
39
  },
@@ -7,6 +7,15 @@
7
7
  "required": ["schema"],
8
8
  "properties": {
9
9
  "schema": {"type": "integer", "const": 2},
10
+ "allow_secret_files": {
11
+ "description": "Exact payload-relative files exempted from the SPK secret guard only. Do not use for credentials; prefer generating keys at install/runtime. Every entry must exist when packing.",
12
+ "type": "array",
13
+ "uniqueItems": true,
14
+ "items": {
15
+ "type": "string",
16
+ "pattern": "^(?![\\s\\S]*(?:^|/)\\.{1,2}(?:/|$))[^/\\\\*?\\[\\]{}:\\u0000-\\u001f\\u007f]+(?:/[^/\\\\*?\\[\\]{}:\\u0000-\\u001f\\u007f]+)*$(?![\\s\\S])"
17
+ }
18
+ },
10
19
  "identity_gateway": {"$ref": "identity-gateway.v1.schema.json"}
11
20
  },
12
21
  "additionalProperties": true
package/skills/SKILL.md CHANGED
@@ -5,6 +5,16 @@ description: Initialize, extend, check, build, inspect, and deploy Synology appl
5
5
 
6
6
  # Independent Synology SPKs
7
7
 
8
+ Keep own-App local secrets in root `.env`, protected by the generated
9
+ `.gitignore`. Upstream forks use `synology/.env`, never the fork root.
10
+ Commit only `.env.example`. Run `synopkgland check`: tracked secrets inside the
11
+ App project directory fail; tracked upstream files outside it are left alone.
12
+ Untracked local secrets anywhere in the repo warn without repository ignore rules,
13
+ including those hidden only by `.git/info/exclude`. Build and release/publish
14
+ enforce the same check. Public certificates and environment templates are allowed;
15
+ SPK packing rejects local environment files, npm tokens and private-key PEM blocks.
16
+ See [reference/create.md](reference/create.md).
17
+
8
18
  The CLI installs templates through its declared npm dependency range. A templates patch needs only a
9
19
  templates release; npm install/update selects a patch in that minor line. The CLI
10
20
  uses the locally installed templates and reads their SDK pin for defaults; it
@@ -28,6 +28,24 @@ Compose 只使用 schema-2 `dsm-package.yaml`,上游原樣保留,SDK planner
28
28
 
29
29
  ## 建置與檢查
30
30
 
31
+ Keep own-App local secrets in root `.env`, protected by the generated `.gitignore`.
32
+ Upstream forks use `synology/.env`, never the fork root or upstream ignore files.
33
+ Commit only `.env.example`, without real secrets.
34
+ `synopkgland check` fails tracked secrets only inside the App project directory;
35
+ tracked upstream files outside it are left alone. Untracked local secrets anywhere
36
+ in the repository warn unless repository `.gitignore` rules protect them.
37
+ Local `.git/info/exclude` and global ignore rules do not protect a clone.
38
+ Build and release/publish enforce the same check. The environment template names
39
+ `.env.example`, `.env.sample`, `.env.template`, `.env.dist` and `.env.defaults`
40
+ are allowed, as are public certificates and CA bundles.
41
+ Repository checks identify sensitive `.pem`, `.key` and `.p12` files by private-key
42
+ PEM content or a binary PKCS#12 envelope, rather than their extensions alone.
43
+ SPK packing rejects non-template `.env`/`.env.*` files, `.npmrc` containing
44
+ `_authToken`, and private-key PEM blocks under any filename. Keys generated at
45
+ runtime are outside the packaged payload.
46
+
47
+ To deliberately package a file blocked by the SPK secret guard, declare top-level `allow_secret_files: ["share/demo/server.key"]` in `dsm-package.yaml`. Each entry must exactly match an existing payload file relative to `package.tgz` when packing; globs, directories and missing files fail the build. Every build warns for each allowed file, and `check` lists the declarations even before build-generated files exist. This applies only to the payload; tracked-secret checks and metadata checks remain enforced. Don't use this for credentials; prefer generating keys at install/runtime.
48
+
31
49
  執行 check、build、inspect,再看 deploy --dry-run。Go CGI 每包驗證 DSM session,root-ops 能力只提供固定管理員核准工作。容器必須使用已建置映像;不支援的特權 host 存取、secret/config 與 build stanza 會拒絕。
32
50
 
33
51
  安裝前讀 deploy.md。需要資料或登入時讀 files.md、identity.md。
@@ -6,6 +6,17 @@ Never edit upstream README, Dockerfile, source, config, workflows or ignore file
6
6
  Do not rewrite the App or treat it as an SDK component. Use `.git/info/exclude`
7
7
  for local output when needed.
8
8
 
9
+ Keep local secrets in `synology/.env`, covered by `synology/.gitignore`; never
10
+ put them at the fork root. Commit only `.env.example`.
11
+ `synopkgland check` only fails tracked secrets inside the App project directory.
12
+ Tracked upstream fixtures and configuration outside that directory are left alone.
13
+ Untracked local secrets anywhere in the repo warn without repository ignore rules.
14
+ `.git/info/exclude` alone does not survive a clone and still warns.
15
+ Environment templates (`.env.example`, `.env.sample`, `.env.template`, `.env.dist`,
16
+ `.env.defaults`) and public CA certificates are allowed. SPK packing rejects
17
+ non-template environment files, npm auth tokens and private-key PEM blocks,
18
+ including fixture keys accidentally copied into a dependency payload.
19
+
9
20
  Apply the [UI copy rule](ui-vue.md#ui-copy-and-i18n) only to UI strings we add
10
21
  under `synology/`, such as DSM install wizards and gateway pages; leave upstream
11
22
  UI/locale strings and release notes unchanged, and exclude upstream source from