@synopackageland/cli 0.54.8 → 0.54.10

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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.54.10 (2026-11-21)
4
+
5
+ - `check <spk>` and `inspect` scan public `ui/` files over 64 MiB instead of rejecting them with `SPK_UI_UNSAFE`: a larger file (such as a Go CGI) is streamed in 16 MiB windows with 1 MiB overlap, so a match longer than 1 MiB is still flagged but reported by its first 1 MiB. Executables keep their binary-pattern scanning.
6
+
7
+ ## 0.54.9 (2026-11-18)
8
+
9
+ - Use SDK 0.53.51 by default.
10
+ - `identity_gateway.origin` adds a second, administrator-only browser origin to a path-ingress App: an HTTPS port (`https`, default for the installer port `gateway_origin`) served by DSM's nginx through a `server` block (`sso/native-origin-nginx.conf`) and the gateway's separate mutually authenticated socket, forwarded to a package Unix socket (`upstream`). Optional `cookies: dsm-passthrough` forwards the upstream's own DSM cookies except `id`/`did`; optional `headers` sends the administrator. It needs `install.ports: true`, DSM 7.2-64570 and an SDK with `OriginVersion`. A port conflict on this port only warns. `inspect` replays the server block and the gateway origin.
11
+
3
12
  ## 0.54.8 (2026-11-18)
4
13
 
5
14
  - Use SDK 0.53.50 by default.
package/dist/bin.js CHANGED
File without changes
@@ -65,6 +65,17 @@ export declare const WIZARD_MESSAGES: {
65
65
  es: string;
66
66
  it: string;
67
67
  };
68
+ "ports.origin": {
69
+ en: string;
70
+ "zh-TW": string;
71
+ "zh-CN": string;
72
+ ja: string;
73
+ ko: string;
74
+ de: string;
75
+ fr: string;
76
+ es: string;
77
+ it: string;
78
+ };
68
79
  "ports.signin": {
69
80
  en: string;
70
81
  "zh-TW": string;
@@ -65,6 +65,17 @@ export const WIZARD_MESSAGES = {
65
65
  "es": "Puerto HTTPS",
66
66
  "it": "Porta HTTPS"
67
67
  },
68
+ "ports.origin": {
69
+ "en": "Dedicated HTTPS port",
70
+ "zh-TW": "專用 HTTPS 連接埠",
71
+ "zh-CN": "专用 HTTPS 端口",
72
+ "ja": "専用 HTTPS ポート",
73
+ "ko": "전용 HTTPS 포트",
74
+ "de": "Eigener HTTPS-Port",
75
+ "fr": "Port HTTPS dédié",
76
+ "es": "Puerto HTTPS dedicado",
77
+ "it": "Porta HTTPS dedicata"
78
+ },
68
79
  "ports.signin": {
69
80
  "en": "Local sign-in port",
70
81
  "zh-TW": "本機登入連接埠",
@@ -1 +1 @@
1
- {"module":"github.com/synopackageland/syno-pkg-land-sdk","version":"0.53.50","local":false}
1
+ {"module":"github.com/synopackageland/syno-pkg-land-sdk","version":"0.53.51","local":false}
@@ -1,7 +1,7 @@
1
1
  export { goPrivateCovers } from './go-env.js';
2
2
  import { type ExecutorManifest } from './sdk-executor-manifest.js';
3
3
  /** Pinned SDK for CLI-owned controllers and Compose planning; App pins take precedence. */
4
- export declare const DEFAULT_SDK_VERSION = "0.53.50";
4
+ export declare const DEFAULT_SDK_VERSION = "0.53.51";
5
5
  export declare const SDK_PACKAGE = "@synopackageland/sdk";
6
6
  export declare const SDK_MODULE = "github.com/synopackageland/syno-pkg-land-sdk";
7
7
  export declare const EXECUTOR_MODULE = "github.com/synopackageland/syno-pkg-land-sdk/executor";
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
  import { readExecutorManifest, predatesExecutorManifest } from './sdk-executor-manifest.js';
7
7
  /** Pinned SDK for CLI-owned controllers and Compose planning; App pins take precedence. */
8
- export const DEFAULT_SDK_VERSION = '0.53.50';
8
+ export const DEFAULT_SDK_VERSION = '0.53.51';
9
9
  export const SDK_PACKAGE = '@synopackageland/sdk';
10
10
  export const SDK_MODULE = 'github.com/synopackageland/syno-pkg-land-sdk';
11
11
  export const EXECUTOR_MODULE = `${SDK_MODULE}/executor`;
@@ -3,10 +3,12 @@ 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, logicalUiFile, publicUiReport, resolveUiSecretIgnores, staleUiIgnores, uiFileProblems } from "../standalone/public-ui.js";
6
+ import { applyUiIgnores, logicalUiFile, publicUiReport, resolveUiSecretIgnores, staleUiIgnores, uiFileProblems, UiStreamScanner } 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;
10
+ /** ui/ files up to this size are scanned whole; larger ones (e.g. a Go CGI) are streamed in windows. */
11
+ const MAX_UI_IN_MEMORY = 64 * MAX_TEXT;
10
12
  const HEAD_BYTES = 20;
11
13
  /** `section:key`: a DSM string reference rather than literal text. */
12
14
  const STRING_REF = /^([A-Za-z0-9_]+):([A-Za-z0-9_]+)$/;
@@ -40,16 +42,24 @@ async function scanPayload(payloadPath, wanted, findings) {
40
42
  if (entry.type !== "File")
41
43
  return;
42
44
  const file = { path, head: Buffer.alloc(0) };
43
- const keep = wanted(path) && (entry.size ?? 0) <= (path.startsWith("ui/") ? 64 * MAX_TEXT : MAX_TEXT);
45
+ const ui = path.startsWith("ui/");
46
+ const keep = wanted(path) && (entry.size ?? 0) <= (ui ? MAX_UI_IN_MEMORY : MAX_TEXT);
47
+ // Only the payload's own ui/ files need a secret scan at any size.
48
+ const stream = !keep && ui && wanted(path) ? new UiStreamScanner(path.slice(3)) : undefined;
44
49
  const chunks = [];
45
50
  entry.on("data", (chunk) => {
46
51
  if (file.head.length < HEAD_BYTES)
47
52
  file.head = Buffer.concat([file.head, chunk]).subarray(0, HEAD_BYTES);
48
53
  if (keep)
49
54
  chunks.push(chunk);
55
+ stream?.write(chunk);
56
+ });
57
+ entry.on("end", () => {
58
+ if (keep)
59
+ file.content = Buffer.concat(chunks);
60
+ if (stream)
61
+ file.problems = stream.end();
50
62
  });
51
- entry.on("end", () => { if (keep)
52
- file.content = Buffer.concat(chunks); });
53
63
  files.push(file);
54
64
  },
55
65
  });
@@ -174,11 +184,12 @@ export async function checkPayload(payloadPath, info, findings, policy = {}) {
174
184
  }
175
185
  const scanned = [];
176
186
  for (const file of ui) {
177
- if (file.content === undefined) {
178
- findings.add("SPK_UI_UNSAFE", "Public UI file exceeds the 64 MiB scan limit.", at(file.path));
187
+ const raw = file.content !== undefined ? uiFileProblems(file.path.slice(3), file.content) : file.problems;
188
+ if (raw === undefined) {
189
+ // Not reached for a fully read tar; fail closed if a ui/ file was never scanned.
190
+ findings.add("SPK_UI_UNSAFE", "Public UI file could not be scanned.", at(file.path));
179
191
  continue;
180
192
  }
181
- const raw = uiFileProblems(file.path.slice(3), file.content);
182
193
  scanned.push(...raw);
183
194
  // Inspection may run on SPKs from others: report patterns, never the flagged text.
184
195
  const problems = applyUiIgnores(raw, ignores, policy.moduleVersion);
@@ -190,5 +201,8 @@ export async function checkPayload(payloadPath, info, findings, policy = {}) {
190
201
  }
191
202
  for (const stale of staleUiIgnores(scanned, ignores, policy.moduleVersion))
192
203
  findings.add("SPK_UI_UNSAFE", "A recorded ui_secret_ignores match no longer occurs in this file; rebuild the SPK.", at(`ui/${stale.file}`));
193
- return publicUiReport(ui.filter(file => file.content !== undefined).map(file => ({ file: file.path, content: file.content.toString("utf8") })));
204
+ const report = publicUiReport(ui.filter(file => file.content !== undefined).map(file => ({ file: file.path, content: file.content.toString("utf8") })));
205
+ // Streamed files are not minify-checked, but a source map in one is still reported.
206
+ const streamedMaps = ui.filter(file => file.problems?.some(problem => ["source-map-file", "sourceMappingURL"].includes(problem.pattern))).map(file => file.path);
207
+ return streamedMaps.length ? { ...report, sourceMapFree: false, sourceMaps: [...report.sourceMaps, ...streamedMaps] } : report;
194
208
  }
@@ -115,10 +115,7 @@ export declare function composeManifestContext(m: Pick<StandaloneManifest, 'iden
115
115
  composeMounts: true | undefined;
116
116
  sharedFolder: SharedFolder | undefined;
117
117
  installSettings: InstallSettings | undefined;
118
- installPorts: Record<string, {
119
- default: number;
120
- protocol: "tcp";
121
- }> | undefined;
118
+ installPorts: Record<string, import("./install-ports.js").PortDefinition> | undefined;
122
119
  };
123
120
  export declare function readComposeApp(value: unknown, root: string, arches: NativeArchFamily[], fail: (e: StandaloneError) => void, context?: {
124
121
  package?: string;
@@ -102,6 +102,16 @@ export interface IdentityGateway {
102
102
  account?: {
103
103
  on_delete: DeleteAction[];
104
104
  };
105
+ /** A second, administrator-only HTTPS origin on its own installer port (see docs/origin-port.md). */
106
+ origin?: GatewayOrigin;
107
+ }
108
+ export interface GatewayOrigin {
109
+ /** Default HTTPS port; the administrator may change it (install.ports). */
110
+ https: number;
111
+ /** `unix:<name>.sock`: the App's private socket under var/run. */
112
+ upstream: string;
113
+ cookies?: "dsm-passthrough";
114
+ headers?: Partial<Record<"user" | "email" | "name" | "groups" | "uid", string>>;
105
115
  }
106
116
  /** One delete step; {uid} and {name} are the only placeholders. */
107
117
  export type DeleteAction = {
@@ -64,6 +64,10 @@ function unixUpstreamSdkSupported(dir) {
64
64
  const source = join(dir, "idgateway/unix_upstream.go");
65
65
  return existsSync(source) && /const UnixUpstreamVersion = 1\b/.test(readFileSync(source, "utf8"));
66
66
  }
67
+ function originSdkSupported(dir) {
68
+ const source = join(dir, "idgateway/origin_port.go");
69
+ return existsSync(source) && /const OriginVersion = 1\b/.test(readFileSync(source, "utf8"));
70
+ }
67
71
  function upstreamAuthSdkSupported(dir) {
68
72
  const source = join(dir, "idgateway/upstream_auth.go");
69
73
  return existsSync(source) && /const UpstreamAuthPathsVersion = 1\b/.test(readFileSync(source, "utf8"));
@@ -190,8 +194,9 @@ export function readIdentityGateway(value, daemon, fail, packagedPayload = false
190
194
  "oidc",
191
195
  "token",
192
196
  "account",
197
+ "origin",
193
198
  ])) {
194
- return invalid("accepts only sdk, external_access, secure_context, mode, access, upstream_access, groups, upstream, listen, passthrough, upstream_auth_paths, optional_passthrough, redirects, email_domain, session_ttl, roles, headers, oidc, token and account.");
199
+ return invalid("accepts only sdk, external_access, secure_context, mode, access, upstream_access, launch_path, ingress, groups, max_upload_bytes, response_header_timeout_seconds, upstream, listen, passthrough, upstream_auth_paths, optional_passthrough, redirects, email_domain, session_ttl, roles, headers, oidc, token, account and origin.");
195
200
  }
196
201
  const v = value;
197
202
  if (v.secure_context !== undefined && v.secure_context !== "required")
@@ -301,15 +306,43 @@ export function readIdentityGateway(value, daemon, fail, packagedPayload = false
301
306
  ![listen.http, listen.https].every((p) => p === undefined || port(p)))
302
307
  return invalid("listen needs an http and/or https port.");
303
308
  const issuer = record(v.oidc) ? v.oidc.issuer_port : undefined;
309
+ let origin;
310
+ if (v.origin !== undefined) {
311
+ const o = v.origin;
312
+ const originHeaders = record(o) ? o.headers : undefined;
313
+ if (!record(o) || !only(o, ["https", "upstream", "cookies", "headers"]) ||
314
+ !Number.isInteger(o.https) || o.https < 1024 || o.https > 65535 ||
315
+ typeof o.upstream !== "string" || !unixUpstreamSocket(o.upstream) ||
316
+ (o.cookies !== undefined && o.cookies !== "dsm-passthrough") ||
317
+ (originHeaders !== undefined && (!record(originHeaders) || !only(originHeaders, ["user", "email", "name", "groups", "uid"]) ||
318
+ !Object.values(originHeaders).every(headerName) || !originHeaders.user)))
319
+ return invalid("origin needs https (1024-65535), upstream unix:<name>.sock, optional cookies: dsm-passthrough and optional headers with user.");
320
+ if (composeBridge)
321
+ return invalid("origin cannot be combined with compose.");
322
+ try {
323
+ if (!originSdkSupported(sdkSource(v.sdk).goDir))
324
+ return invalid("The selected SDK lacks the second origin (OriginVersion); use a matching SDK release or an explicit development source override.");
325
+ }
326
+ catch {
327
+ return invalid("The SDK origin source is unavailable; use matching SDK sources.");
328
+ }
329
+ origin = {
330
+ https: o.https,
331
+ upstream: o.upstream,
332
+ ...(o.cookies !== undefined ? { cookies: "dsm-passthrough" } : {}),
333
+ ...(originHeaders !== undefined ? { headers: originHeaders } : {}),
334
+ };
335
+ }
304
336
  const ports = [
305
337
  listen.http,
306
338
  listen.https,
307
339
  ...(composeBridge || unixSocket ? [] : [v.upstream]),
308
340
  issuer,
341
+ origin?.https,
309
342
  ].filter((p) => p !== undefined);
310
343
  if (new Set(ports).size !== ports.length ||
311
344
  ports.some((p) => DSM_PORTS.includes(p)))
312
- return invalid("listen, upstream and oidc.issuer_port must be distinct and not DSM's 5000/5001.");
345
+ return invalid("listen, upstream, oidc.issuer_port and origin.https must be distinct and not DSM's 5000/5001.");
313
346
  const passthrough = v.passthrough ?? [];
314
347
  if (!strings(passthrough, (p) => localPath(p) && p !== "/" && !/^\/_sso(\/|$)/.test(p)))
315
348
  return invalid("passthrough must be path prefixes such as /share/, outside /_sso.");
@@ -410,6 +443,7 @@ export function readIdentityGateway(value, daemon, fail, packagedPayload = false
410
443
  ...(v.session_ttl ? { session_ttl: v.session_ttl } : {}),
411
444
  ...(roles ? { roles } : {}),
412
445
  ...(headers ? { headers: headers } : {}),
446
+ ...(origin ? { origin } : {}),
413
447
  };
414
448
  if (v.mode === "oidc") {
415
449
  const o = v.oidc;
@@ -568,6 +602,16 @@ export function identityGatewayConfig(m) {
568
602
  ...(g.roles ? { roles: g.roles } : {}),
569
603
  ...(g.headers ? { headers: g.headers } : {}),
570
604
  ...(g.oidc ? { oidc: g.oidc } : {}),
605
+ ...(g.origin
606
+ ? {
607
+ origin: {
608
+ https: g.origin.https,
609
+ upstream: `unix:/var/packages/${m.package}/var/run/${unixUpstreamSocket(g.origin.upstream)}`,
610
+ ...(g.origin.cookies ? { cookies: g.origin.cookies } : {}),
611
+ ...(g.origin.headers ? { headers: g.origin.headers } : {}),
612
+ },
613
+ }
614
+ : {}),
571
615
  ...(g.token
572
616
  ? {
573
617
  token: {
@@ -623,6 +667,8 @@ export async function buildIdentityGateway(m, arch, work, run) {
623
667
  runtimeBudgetSource(sdk.goDir, m);
624
668
  if (m.identityGateway.secure_context && !secureContextSdkSupported(sdk.goDir))
625
669
  throw new StandaloneBuildError("STANDALONE_IDENTITY_GATEWAY_INVALID", "secure_context requires an SDK with HTTPS guidance support; upgrade the selected SDK and use matching SDK sources.");
670
+ if (m.identityGateway.origin && !originSdkSupported(sdk.goDir))
671
+ throw new StandaloneBuildError("STANDALONE_IDENTITY_GATEWAY_INVALID", "The selected SDK lacks the second origin (OriginVersion); use a matching SDK release or an explicit development source override.");
626
672
  if (unixUpstreamSocket(m.identityGateway.upstream) && !unixUpstreamSdkSupported(sdk.goDir))
627
673
  throw new StandaloneBuildError("STANDALONE_IDENTITY_GATEWAY_INVALID", "The selected SDK lacks unix upstream support (UnixUpstreamVersion); use a matching SDK release or an explicit development source override.");
628
674
  if (m.identityGateway.upstream_auth_paths && !upstreamAuthSdkSupported(sdk.goDir))
@@ -17,7 +17,8 @@ import { readInstallSettings, settingsInstallSteps, settingsConfig, renderSettin
17
17
  import { MODULE_UI_ENTRY, uiTreeDigest } from "./ui-assets.js";
18
18
  import { minifyUi, isUiBundle } from "./public-ui.js";
19
19
  import { nativePortal } from "./portal.js";
20
- import { nativeGatewaySupported, renderNativeGatewayConfig, renderNativeGatewayDiagnostic, renderNativeGatewayPrepare, NATIVE_GATEWAY_CONFIG, gatewayEntryPath } from './native-gateway.js';
20
+ import { unixUpstreamSocket } from "./gateway-ingress-only.js";
21
+ import { nativeGatewaySupported, renderNativeGatewayConfig, renderNativeOriginConfig, NATIVE_ORIGIN_CONFIG, renderNativeGatewayDiagnostic, renderNativeGatewayPrepare, NATIVE_GATEWAY_CONFIG, gatewayEntryPath } from './native-gateway.js';
21
22
  import { inspectPortalInfo } from "../portal/info.js";
22
23
  import { isDeepStrictEqual } from "node:util";
23
24
  import { inspectCtlArtifacts } from './native-http-inspect.js';
@@ -1362,7 +1363,7 @@ async function recoverNativeGateway(dir, value, info, findings) {
1362
1363
  throw new Error('invalid native gateway record');
1363
1364
  const plan = value;
1364
1365
  if (typeof plan.sdk !== 'string' || !plan.listen || typeof plan.listen !== 'object' || Array.isArray(plan.listen)
1365
- || !plan.ingress && !Object.keys(plan.listen).length || Object.keys(plan).some(k => !['sdk', 'listen', 'ingress'].includes(k))
1366
+ || !plan.ingress && !Object.keys(plan.listen).length || Object.keys(plan).some(k => !['sdk', 'listen', 'ingress', 'origin'].includes(k))
1366
1367
  || Object.entries(plan.listen).some(([k, v]) => !['http', 'https'].includes(k) || !Number.isInteger(v) || v < 1 || v > 65535))
1367
1368
  throw new Error('invalid native gateway ports');
1368
1369
  const target = { package: info.package, os_min_ver: info.os_min_ver, identityGateway: plan };
@@ -1370,15 +1371,24 @@ async function recoverNativeGateway(dir, value, info, findings) {
1370
1371
  throw new Error('invalid gateway ingress namespace');
1371
1372
  if (!nativeGatewaySupported(target))
1372
1373
  throw new Error('unsupported native gateway SDK/DSM floor');
1374
+ const origin = plan.origin;
1375
+ if (origin !== undefined && !nativeOriginRecord(origin))
1376
+ throw new Error('invalid native gateway origin');
1373
1377
  const root = join(dir, 'native-gateway-inspection');
1374
1378
  mkdirSync(root);
1375
- await extractSpkArchive({ file: join(dir, 'package.tgz'), cwd: root, filter: path => ['sso/gateway.json', 'ui/sso/open.cgi', NATIVE_GATEWAY_CONFIG].includes(path.replace(/^\.\//, '')) });
1379
+ await extractSpkArchive({ file: join(dir, 'package.tgz'), cwd: root, filter: path => ['sso/gateway.json', 'ui/sso/open.cgi', NATIVE_GATEWAY_CONFIG, NATIVE_ORIGIN_CONFIG].includes(path.replace(/^\.\//, '')) });
1376
1380
  const config = JSON.parse(readFileSync(join(root, 'sso/gateway.json'), 'utf8'));
1377
1381
  if (config.native_ingress !== true || config.package !== info.package || !isDeepStrictEqual(config.listen, plan.listen) || config.ingress_path !== plan.ingress?.path
1378
1382
  || config.state_dir !== `/var/packages/${info.package}/var/sso`)
1379
1383
  throw new Error('native gateway config does not match its package');
1380
1384
  if (readOptional(join(root, NATIVE_GATEWAY_CONFIG)) !== renderNativeGatewayConfig(target))
1381
1385
  throw new Error('native gateway ingress differs from its fixed proxy');
1386
+ const expectedOrigin = origin && { https: origin.https, upstream: `unix:/var/packages/${info.package}/var/run/${unixUpstreamSocket(origin.upstream)}`,
1387
+ ...(origin.cookies ? { cookies: origin.cookies } : {}), ...(origin.headers ? { headers: origin.headers } : {}) };
1388
+ if (!isDeepStrictEqual(config.origin, expectedOrigin))
1389
+ throw new Error('native gateway origin does not match its package');
1390
+ if (readOptional(join(root, NATIVE_ORIGIN_CONFIG)) !== (origin ? renderNativeOriginConfig(target) : undefined))
1391
+ throw new Error('native gateway origin differs from its fixed proxy');
1382
1392
  for (const key of ['startstop_restart_services'])
1383
1393
  if (!(info[key] ?? '').split(/\s+/).includes('nginx.service'))
1384
1394
  throw new Error(`native gateway requires INFO ${key}`);
@@ -1400,6 +1410,18 @@ async function recoverNativeGateway(dir, value, info, findings) {
1400
1410
  return undefined;
1401
1411
  }
1402
1412
  }
1413
+ /** The recorded identity_gateway.origin: exactly what the manifest reader accepts. */
1414
+ function nativeOriginRecord(v) {
1415
+ if (!v || typeof v !== 'object' || Array.isArray(v))
1416
+ return false;
1417
+ const o = v, h = o.headers;
1418
+ return Object.keys(o).every(k => ['https', 'upstream', 'cookies', 'headers'].includes(k))
1419
+ && Number.isInteger(o.https) && o.https >= 1024 && o.https <= 65535
1420
+ && unixUpstreamSocket(o.upstream) !== undefined && (o.cookies === undefined || o.cookies === 'dsm-passthrough')
1421
+ && (h === undefined || !!h && typeof h === 'object' && !Array.isArray(h)
1422
+ && Object.entries(h).every(([k, name]) => ['user', 'email', 'name', 'groups', 'uid'].includes(k) && typeof name === 'string' && /^[A-Za-z0-9][A-Za-z0-9-]{0,63}$/.test(name))
1423
+ && typeof h.user === 'string');
1424
+ }
1403
1425
  function recoverDaemonNode(value, findings) {
1404
1426
  if (value === undefined)
1405
1427
  return undefined;
@@ -1729,7 +1751,7 @@ async function inspectInstallSettings(dir, payload, metadata, findings) {
1729
1751
  const expected = portDefaults({ ...m, identityGateway: { ...actualGateway, sdk: gateway.sdk, ...(actualGateway.ingress_path ? { ingress: { path: actualGateway.ingress_path } } : {}) } });
1730
1752
  if (config.schema !== 1 || config.package !== info.package || !isDeepStrictEqual(config.ports, ports) || !isDeepStrictEqual(ports, expected))
1731
1753
  throw new Error('port defaults differ from gateway listeners');
1732
- const required = ['sso/gateway.json', 'daemon/config.json', ...(actualGateway.native_ingress ? ['sso/native-nginx.conf'] : []), ...(settings ? ['install/settings.json'] : []), ...payload.filter(p => /^ui\/window-[0-9]+\.js$/.test(p.path)).map(p => p.path)].sort();
1754
+ const required = ['sso/gateway.json', 'daemon/config.json', ...(actualGateway.native_ingress ? ['sso/native-nginx.conf'] : []), ...(actualGateway.origin ? [NATIVE_ORIGIN_CONFIG] : []), ...(settings ? ['install/settings.json'] : []), ...payload.filter(p => /^ui\/window-[0-9]+\.js$/.test(p.path)).map(p => p.path)].sort();
1733
1755
  if (!isDeepStrictEqual(Object.keys(config.files).sort(), required))
1734
1756
  throw new Error('port templates must cover every generated port consumer');
1735
1757
  for (const [path, source] of Object.entries(config.files)) {
@@ -1,9 +1,11 @@
1
1
  import type { StandaloneManifest } from './manifest.js';
2
2
  import type { Translate } from '../build-spk/wizard-i18n.js';
3
- export declare function portDefaults(m: Pick<StandaloneManifest, 'identityGateway' | 'installPorts'>): Record<string, {
3
+ export type PortDefinition = {
4
4
  default: number;
5
5
  protocol: 'tcp';
6
- }>;
6
+ conflict?: 'warn';
7
+ };
8
+ export declare function portDefaults(m: Pick<StandaloneManifest, 'identityGateway' | 'installPorts'>): Record<string, PortDefinition>;
7
9
  export declare function withPort(m: StandaloneManifest, key: string, value: number): StandaloneManifest;
8
10
  interface PortMessages {
9
11
  reserved: string;
@@ -11,10 +13,7 @@ interface PortMessages {
11
13
  duplicate: string;
12
14
  }
13
15
  export declare function portFieldValidator(pkg: string, key: string, reason: string, messages?: PortMessages): string;
14
- export declare function portInstallSteps(m: Pick<StandaloneManifest, 'package' | 'installPorts' | 'identityGateway'>, definitions?: Record<string, {
15
- default: number;
16
- protocol: "tcp";
17
- }>): (t: Translate) => {
16
+ export declare function portInstallSteps(m: Pick<StandaloneManifest, 'package' | 'installPorts' | 'identityGateway'>, definitions?: Record<string, PortDefinition>): (t: Translate) => {
18
17
  step_title: string;
19
18
  items: ({
20
19
  type: string;
@@ -7,10 +7,18 @@ export function portDefaults(m) {
7
7
  return Object.fromEntries([
8
8
  ...Object.entries(g.ingress ? {} : g.listen ?? {}).map(([key, value]) => ['gateway_' + key, { default: value, protocol: 'tcp' }]),
9
9
  ...(g.oidc ? [['oidc_issuer', { default: g.oidc.issuer_port, protocol: 'tcp' }]] : []),
10
+ // An administrator-chosen origin port only warns about a registered service.
11
+ ...(g.origin ? [['gateway_origin', { default: g.origin.https, protocol: 'tcp', conflict: 'warn' }]] : []),
10
12
  ]);
11
13
  }
14
+ function portValue(m, key) {
15
+ const g = m.identityGateway;
16
+ return key === 'oidc_issuer' ? g.oidc.issuer_port : key === 'gateway_origin' ? g.origin.https : g.listen[key.slice(8)];
17
+ }
12
18
  export function withPort(m, key, value) {
13
19
  const g = m.identityGateway;
20
+ if (key === 'gateway_origin')
21
+ return { ...m, identityGateway: { ...g, origin: { ...g.origin, https: value } } };
14
22
  return { ...m, identityGateway: { ...g, listen: { ...g.listen, ...(key.startsWith('gateway_') ? { [key.slice(8)]: value } : {}) }, ...(g.oidc ? { oidc: { ...g.oidc, ...(key === 'oidc_issuer' ? { issuer_port: value } : {}) } } : {}) } };
15
23
  }
16
24
  /** Validate port syntax; service conflicts are advisory and never block Next. */
@@ -85,7 +93,7 @@ export function portInstallSteps(m, definitions = portDefaults(m)) {
85
93
  return (t) => m.installPorts ? [{
86
94
  step_title: t('ports.title'),
87
95
  items: [{ desc: t('ports.notice') }, ...Object.entries(definitions).flatMap(([key, p]) => {
88
- const label = t(key === 'gateway_http' ? 'ports.http' : key === 'gateway_https' ? 'ports.https' : 'ports.signin');
96
+ const label = t(key === 'gateway_http' ? 'ports.http' : key === 'gateway_https' ? 'ports.https' : key === 'gateway_origin' ? 'ports.origin' : 'ports.signin');
89
97
  return [
90
98
  { type: 'textfield', desc: label, subitems: [{ key: 'pkgwizard_port_' + key, desc: label, defaultValue: String(p.default), validator: { allowBlank: false, fn: portFieldValidator(m.package, key, t('ports.invalid'), { reserved: t('ports.reserved', { port: '{port}' }), conflict: t('ports.conflict', { port: '{port}', service: '{service}' }), duplicate: t('ports.duplicate', { port: '{port}' }) }) } }] },
91
99
  { desc: `<div id="synopkgland-port-warning-${m.package}-${key}" role="status" aria-live="polite" style="min-height:44px;visibility:hidden"></div>` },
@@ -112,8 +120,7 @@ export function writePortPayload(m, root, render) {
112
120
  const files = render(marked);
113
121
  let index = 0;
114
122
  for (const [key] of Object.entries(ports)) {
115
- const g = marked.identityGateway;
116
- const value = key === 'oidc_issuer' ? g.oidc.issuer_port : g.listen[key.slice(8)];
123
+ const value = portValue(marked, key);
117
124
  for (const path of Object.keys(files))
118
125
  files[path] = files[path].replaceAll(String(value), '@@PORT_' + key + '@@');
119
126
  index++;
@@ -10,7 +10,7 @@ import { daemonNoFileSdkProblem, daemonNoFileIdentityProblem, DAEMON_NOFILE_MIN_
10
10
  import { readAllowedSecretFiles } from "../secret-files.js";
11
11
  import { readRegistry, registryFile } from '../ctl/registry.js';
12
12
  import { gatewayIngressPathProblem, gatewayIngressOwnershipSupported } from './gateway-ingress.js';
13
- import { nativeGatewaySdk } from "./native-gateway.js";
13
+ import { nativeGatewaySdk, nativeGatewaySupported } from "./native-gateway.js";
14
14
  import { portDefaults } from "./install-ports.js";
15
15
  import { readMemoryAdvice, readMinMemoryMb } from "./install-memory.js";
16
16
  import { readPackageDependencies, packageDependencies, dependencyError } from "./package-dependencies.js";
@@ -369,13 +369,19 @@ function readManifest(raw, c) {
369
369
  c.fail('STANDALONE_IDENTITY_GATEWAY_INVALID', 'Custom ingress requires SDK 0.44.0 or later; update identity_gateway.sdk.');
370
370
  if (daemonIngressMinDsmProblem(typeof raw.os_min_ver === "string" ? raw.os_min_ver : undefined))
371
371
  c.fail('STANDALONE_IDENTITY_GATEWAY_INVALID', 'identity_gateway.ingress requires DSM 7.2-64570 or later.');
372
- if (installPorts && !identityGateway.oidc)
372
+ if (installPorts && !identityGateway.oidc && !identityGateway.origin)
373
373
  c.fail('INSTALL_PORT_INVALID', 'Path ingress has no public gateway ports; remove install.ports.');
374
374
  if (identityGateway.external_access?.single_origin)
375
375
  c.fail('STANDALONE_IDENTITY_GATEWAY_INVALID', 'Path ingress uses the DSM origin and cannot combine with external_access.single_origin.');
376
376
  }
377
377
  if (installPorts && !identityGateway)
378
378
  c.fail('INSTALL_PORT_INVALID', 'install.ports requires an identity gateway');
379
+ if (identityGateway?.origin) {
380
+ if (!installPorts)
381
+ c.fail('INSTALL_PORT_INVALID', 'identity_gateway.origin needs install.ports: true, so the administrator can choose its port.');
382
+ if (!nativeGatewaySupported({ package: raw.package, os_min_ver: osMinVer, identityGateway }))
383
+ c.fail('STANDALONE_IDENTITY_GATEWAY_INVALID', 'identity_gateway.origin is served by DSM nginx and requires DSM 7.2-64570 or later.');
384
+ }
379
385
  if (installPorts && identityGateway) {
380
386
  const [major, minor, patch] = identityGateway.sdk.split('.').map(Number);
381
387
  if (major === 0 && (minor < 38 || minor === 38 && patch < 2))
@@ -1,5 +1,5 @@
1
1
  import type { IdentityGateway } from './identity-gateway.js';
2
- export type NativeGatewayPlan = Pick<IdentityGateway, 'sdk' | 'listen' | 'ingress'>;
2
+ export type NativeGatewayPlan = Pick<IdentityGateway, 'sdk' | 'listen' | 'ingress' | 'origin'>;
3
3
  type Target = {
4
4
  package: string;
5
5
  os_min_ver?: string;
@@ -7,6 +7,8 @@ type Target = {
7
7
  installPorts?: true;
8
8
  };
9
9
  export declare const NATIVE_GATEWAY_CONFIG = "sso/native-nginx.conf";
10
+ /** The second origin's own `server` block (identity_gateway.origin). */
11
+ export declare const NATIVE_ORIGIN_CONFIG = "sso/native-origin-nginx.conf";
10
12
  export declare function nativeGatewaySdk(sdk: string): boolean;
11
13
  export declare function nativeGatewaySupported(m: Target): boolean;
12
14
  /** Observe the boundary before DSM acquires web-config, without claiming port ownership. */
@@ -16,6 +18,8 @@ export declare function renderNativeGatewayPortWait(m: Target, hook: string): st
16
18
  export declare function gatewayEntryPath(m: Target): string;
17
19
  export declare function legacyGatewayNotice(): string;
18
20
  export declare function nativeGatewayResource(m: Target): Record<string, unknown> | undefined;
21
+ /** The second origin: DSM's certificate on its own port, to the gateway's origin socket. */
22
+ export declare function renderNativeOriginConfig(m: Target): string;
19
23
  export declare function renderNativeGatewayConfig(m: Target): string;
20
24
  /** Runs after DSM creates pkgvar, before package start activates the nginx resource. */
21
25
  export declare function renderNativeGatewayPrepare(m: Target): string;
@@ -1,6 +1,8 @@
1
1
  import { gatewayIngressPathProblem, gatewayIngressOwnershipSupported } from './gateway-ingress.js';
2
2
  import { isDsmAtLeast, PORTAL_MIN_DSM } from '../build-spk/dsm-version.js';
3
3
  export const NATIVE_GATEWAY_CONFIG = 'sso/native-nginx.conf';
4
+ /** The second origin's own `server` block (identity_gateway.origin). */
5
+ export const NATIVE_ORIGIN_CONFIG = 'sso/native-origin-nginx.conf';
4
6
  // Earlier SDK releases do not understand native_ingress. Keep their JSON ABI
5
7
  // and put an explanation in front of their existing direct-port launcher.
6
8
  export function nativeGatewaySdk(sdk) {
@@ -110,22 +112,22 @@ export function legacyGatewayNotice() {
110
112
  export function nativeGatewayResource(m) {
111
113
  if (!nativeGatewaySupported(m))
112
114
  return undefined;
115
+ // The origin port is always an installer port: DSM's port-config resource
116
+ // (install/<package>.sc) registers it, so the server entry lists no ports.
117
+ const origin = m.identityGateway.origin ? [{ type: 'server', relpath: NATIVE_ORIGIN_CONFIG }] : [];
113
118
  if (m.identityGateway.ingress)
114
- return { "nginx-static-config": { enable: [{ type: "dsm", relpath: NATIVE_GATEWAY_CONFIG }] } };
119
+ return { "nginx-static-config": { enable: [{ type: "dsm", relpath: NATIVE_GATEWAY_CONFIG }, ...origin] } };
115
120
  const g = m.identityGateway, https = g.listen.https ?? g.listen.http;
116
121
  const ports = [https, ...(g.listen.http && g.listen.http !== https ? [g.listen.http] : [])];
117
122
  return { 'nginx-static-config': { enable: [{ type: 'server', relpath: NATIVE_GATEWAY_CONFIG,
118
- ...(!m.installPorts ? { ports: ports.map(port => ({ port, protocol: 'tcp', schema: port === https ? 'https' : 'http' })) } : {}) }] } };
123
+ ...(!m.installPorts ? { ports: ports.map(port => ({ port, protocol: 'tcp', schema: port === https ? 'https' : 'http' })) } : {}) }, ...origin] } };
119
124
  }
120
- export function renderNativeGatewayConfig(m) {
121
- if (!nativeGatewaySupported(m))
122
- return '';
123
- const g = m.identityGateway, port = g.listen.https ?? g.listen.http;
124
- const state = `/var/packages/${m.package}/var/sso`;
125
+ function nativeProxy(pkg, socket) {
126
+ const state = `/var/packages/${pkg}/var/sso`;
125
127
  // Public ssl_certificate is deliberately inherited from DSM's http context.
126
128
  // Only nginx's master reads the package's private upstream key. No DSM key
127
129
  // is read or copied by the package, and no secret appears in this config.
128
- const proxy = ` proxy_pass https://unix:/tmp/synopkgland-gateway-${m.package}.sock:;
130
+ return ` proxy_pass https://unix:${socket}:;
129
131
  proxy_http_version 1.1;
130
132
  proxy_ssl_verify on;
131
133
  proxy_ssl_verify_depth 1;
@@ -142,6 +144,27 @@ export function renderNativeGatewayConfig(m) {
142
144
  proxy_buffering off;
143
145
  proxy_read_timeout 3600s;
144
146
  `;
147
+ }
148
+ /** The second origin: DSM's certificate on its own port, to the gateway's origin socket. */
149
+ export function renderNativeOriginConfig(m) {
150
+ const o = m.identityGateway?.origin;
151
+ if (!o || !nativeGatewaySupported(m))
152
+ return '';
153
+ return `server {
154
+ listen ${o.https} ssl;
155
+ listen [::]:${o.https} ssl;
156
+ server_name _;
157
+ client_max_body_size 0;
158
+ location / {
159
+ ${nativeProxy(m.package, `/tmp/synopkgland-gateway-${m.package}-origin.sock`)} }
160
+ }
161
+ `;
162
+ }
163
+ export function renderNativeGatewayConfig(m) {
164
+ if (!nativeGatewaySupported(m))
165
+ return '';
166
+ const g = m.identityGateway, port = g.listen.https ?? g.listen.http;
167
+ const proxy = nativeProxy(m.package, `/tmp/synopkgland-gateway-${m.package}.sock`);
145
168
  if (g.ingress) {
146
169
  const problem = gatewayIngressPathProblem(m.package, g.ingress.path);
147
170
  if (problem)
@@ -43,6 +43,24 @@ export declare function uiFiles(root: string): string[];
43
43
  /** Run before computing content addresses or mobile asset inventories. */
44
44
  export declare function minifyUiTree(root: string, skip?: string[]): void;
45
45
  export declare function uiFileProblems(file: string, input: string | Buffer): UiProblem[];
46
+ /** Bytes of each streamed window that own match starts; the rest is context. */
47
+ export declare const UI_STREAM_CHUNK: number;
48
+ /** Trailing context: a match that starts in a chunk is seen whole if it is at most this long. */
49
+ export declare const UI_STREAM_OVERLAP: number;
50
+ /**
51
+ * uiFileProblems for a file too large to hold in memory, fed in arbitrary pieces.
52
+ * The file is cut into chunks; each is scanned with UI_STREAM_LEAD bytes before it and
53
+ * UI_STREAM_OVERLAP bytes after it, and a window keeps only the matches that start
54
+ * inside its own chunk, so every match is counted once and seen whole unless it is
55
+ * longer than the overlap (then it is still flagged, by its first UI_STREAM_OVERLAP bytes).
56
+ * Cuts never split a UTF-8 sequence, so text decodes as it would in one piece.
57
+ */
58
+ export declare class UiStreamScanner {
59
+ #private;
60
+ constructor(file: string, chunk?: number, overlap?: number);
61
+ write(piece: Buffer): void;
62
+ end(): UiProblem[];
63
+ }
46
64
  export declare function logicalUiFile(file: string, moduleVersion?: string): string;
47
65
  /**
48
66
  * `ignores` must already be resolved to exact logical files (see resolveUiSecretIgnores).
@@ -156,26 +156,47 @@ const PASSWORD_CAPTIONS = new Set([
156
156
  "passwort", "benutzerpasswort", "mot de passe", "mot de passe utilisateur",
157
157
  "contraseña", "contraseña de usuario", "password utente",
158
158
  ]);
159
- function credentialLiterals(content, bundle) {
159
+ /** The raw regex hits behind credentialLiterals, with their positions; render with `literal`. */
160
+ function credentialLiteralMatches(content, bundle, from = 0, to = content.length) {
160
161
  const found = [];
161
162
  const literals = /(?:^|[,{])\s*(?:"(password|secret)"|'(password|secret)'|(password|secret))\s*:\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|`([^`$\r\n]+)`|(\d+(?:\.\d+)?)\b)/gi;
162
- for (const match of content.matchAll(literals)) {
163
+ for (const match of matchesIn(literals, content, from, to)) {
163
164
  const key = match[1] ?? match[2] ?? match[3];
164
165
  const value = match[4] ?? match[5] ?? match[6] ?? match[7];
165
166
  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();
166
167
  if (key.toLowerCase() === "password" && PASSWORD_CAPTIONS.has(caption))
167
168
  continue;
168
- found.push(match[0].replace(/^[,{]?\s*/, ""));
169
+ found.push(match);
169
170
  }
170
171
  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]);
172
+ for (const match of matchesIn(assignments, content, from, to))
173
+ found.push(match);
173
174
  // Unquoted values in environment/config/HTML text; JS variable assignments are not literals.
174
175
  if (!bundle)
175
- for (const match of content.matchAll(/(?<![\w$])(?:password|secret)\s*=\s*[^\s"'`<>{};,]+/gi))
176
- found.push(match[0]);
176
+ for (const match of matchesIn(/(?<![\w$])(?:password|secret)\s*=\s*[^\s"'`<>{};,]+/gi, content, from, to))
177
+ found.push(match);
178
+ return found;
179
+ }
180
+ /**
181
+ * Global matches that start in [from, to). Searching begins at `from`, so lookbehinds
182
+ * still see the text before it while `^` and earlier matches cannot reach into it.
183
+ */
184
+ function matchesIn(pattern, content, from = 0, to = content.length) {
185
+ const re = new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`);
186
+ const found = [];
187
+ re.lastIndex = from;
188
+ for (let match = re.exec(content); match && match.index < to; match = re.exec(content)) {
189
+ found.push(match);
190
+ if (match[0] === "")
191
+ re.lastIndex++;
192
+ }
177
193
  return found;
178
194
  }
195
+ /** Only the object-literal form starts with its delimiter; reports omit it. */
196
+ const literal = (match) => match[0].replace(/^[,{]?\s*/, "");
197
+ function credentialLiterals(content, bundle) {
198
+ return credentialLiteralMatches(content, bundle).map(literal);
199
+ }
179
200
  const unique = (items) => [...new Set(items)];
180
201
  const allMatches = (pattern, content) => unique([...content.matchAll(new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`))].map(match => match[0]));
181
202
  export function uiFileProblems(file, input) {
@@ -200,6 +221,100 @@ export function uiFileProblems(file, input) {
200
221
  found.push({ file, pattern: "credential-literal", matches: literals });
201
222
  return found;
202
223
  }
224
+ /** Bytes of each streamed window that own match starts; the rest is context. */
225
+ export const UI_STREAM_CHUNK = 16 * 1024 * 1024;
226
+ /** Trailing context: a match that starts in a chunk is seen whole if it is at most this long. */
227
+ export const UI_STREAM_OVERLAP = 1024 * 1024;
228
+ /** Leading context, so lookbehinds and `^` at a chunk start see the bytes before it. */
229
+ const UI_STREAM_LEAD = 4096;
230
+ /**
231
+ * uiFileProblems for a file too large to hold in memory, fed in arbitrary pieces.
232
+ * The file is cut into chunks; each is scanned with UI_STREAM_LEAD bytes before it and
233
+ * UI_STREAM_OVERLAP bytes after it, and a window keeps only the matches that start
234
+ * inside its own chunk, so every match is counted once and seen whole unless it is
235
+ * longer than the overlap (then it is still flagged, by its first UI_STREAM_OVERLAP bytes).
236
+ * Cuts never split a UTF-8 sequence, so text decodes as it would in one piece.
237
+ */
238
+ export class UiStreamScanner {
239
+ #file;
240
+ #chunk;
241
+ #overlap;
242
+ #pending = [];
243
+ #size = 0;
244
+ #lead = Buffer.alloc(0);
245
+ #executable;
246
+ #head = Buffer.alloc(0);
247
+ #found = new Map();
248
+ constructor(file, chunk = UI_STREAM_CHUNK, overlap = UI_STREAM_OVERLAP) {
249
+ if (!(chunk > 0 && overlap > 0))
250
+ throw new Error("UiStreamScanner needs a positive chunk and overlap");
251
+ this.#file = file;
252
+ this.#chunk = chunk;
253
+ this.#overlap = overlap;
254
+ }
255
+ write(piece) {
256
+ if (this.#executable === undefined) {
257
+ this.#head = Buffer.concat([this.#head, piece]);
258
+ // PE needs its header offset at 60 and the header behind it; 4 KiB covers real files.
259
+ if (this.#head.length < 4096) {
260
+ this.#pending.push(piece);
261
+ this.#size += piece.length;
262
+ return;
263
+ }
264
+ this.#executable = isExecutable(this.#head);
265
+ }
266
+ this.#pending.push(piece);
267
+ this.#size += piece.length;
268
+ while (this.#size >= this.#chunk + this.#overlap)
269
+ this.#scan(false);
270
+ }
271
+ end() {
272
+ if (this.#executable === undefined)
273
+ this.#executable = isExecutable(this.#head);
274
+ this.#scan(true);
275
+ return [...this.#found].map(([pattern, matches]) => ({ file: this.#file, pattern, ...(matches ? { matches: [...matches] } : {}) }));
276
+ }
277
+ #scan(last) {
278
+ const data = Buffer.concat(this.#pending);
279
+ // Own [0, cut); a continuation byte (10xxxxxx) never starts a cut.
280
+ let cut = last ? data.length : this.#chunk;
281
+ if (!this.#executable)
282
+ while (cut < data.length && (data[cut] & 0xc0) === 0x80)
283
+ cut++;
284
+ const decode = (bytes) => bytes.toString(this.#executable ? "latin1" : "utf8");
285
+ const lead = decode(this.#lead), owned = decode(data.subarray(0, cut));
286
+ const text = lead + owned + decode(data.subarray(cut));
287
+ const start = lead.length, end = start + owned.length;
288
+ const add = (pattern, matches) => {
289
+ if (!this.#found.has(pattern))
290
+ this.#found.set(pattern, matches ? new Set() : undefined);
291
+ for (const match of matches ?? [])
292
+ this.#found.get(pattern).add(match);
293
+ };
294
+ const name = basename(this.#file).toLowerCase();
295
+ if (name === ".env" || name.startsWith(".env."))
296
+ add("environment-file");
297
+ if (this.#file.toLowerCase().endsWith(".map"))
298
+ add("source-map-file");
299
+ if (matchesIn(SOURCE_MAP_COMMENT, text, start, end).length)
300
+ add("sourceMappingURL");
301
+ for (const [pattern, match] of this.#executable ? BINARY_SECRET_PATTERNS : SECRET_PATTERNS) {
302
+ const hits = matchesIn(match, text, start, end).map(hit => hit[0]);
303
+ if (hits.length)
304
+ add(pattern, hits);
305
+ }
306
+ if (!this.#executable) {
307
+ const hits = credentialLiteralMatches(text, isUiBundle(this.#file), start, end).map(literal);
308
+ if (hits.length)
309
+ add("credential-literal", hits);
310
+ }
311
+ const before = Buffer.concat([this.#lead, data.subarray(0, cut)]);
312
+ this.#lead = Buffer.from(before.subarray(Math.max(0, before.length - UI_STREAM_LEAD)));
313
+ const rest = data.subarray(cut);
314
+ this.#pending = rest.length ? [Buffer.from(rest)] : [];
315
+ this.#size = rest.length;
316
+ }
317
+ }
203
318
  export function logicalUiFile(file, moduleVersion) {
204
319
  const prefix = moduleVersion ? `app/${moduleVersion}/` : "";
205
320
  return prefix && file.startsWith(prefix) ? `app/${file.slice(prefix.length)}` : file;
@@ -8,7 +8,7 @@ import { portDefaults, portInstallSteps, writePortPayload } from "./install-port
8
8
  import { packageDependencies, dependencyInfo } from "./package-dependencies.js";
9
9
  import { settingsInstallSteps, settingsConfig, nativeFolderConfig } from './install-settings.js';
10
10
  import { backupConfig, backupHookProblem, backupRecord, renderBackupScripts, BACKUP_PAYLOAD_DIR, BACKUP_SCRIPTS_DIR, BACKUP_SCRIPT_MODES } from './hyper-backup.js';
11
- import { nativeGatewaySupported, nativeGatewaySdk, renderNativeGatewayConfig, NATIVE_GATEWAY_CONFIG, legacyGatewayNotice, gatewayEntryPath } from './native-gateway.js';
11
+ import { nativeGatewaySupported, nativeGatewaySdk, renderNativeGatewayConfig, NATIVE_GATEWAY_CONFIG, renderNativeOriginConfig, NATIVE_ORIGIN_CONFIG, legacyGatewayNotice, gatewayEntryPath } from './native-gateway.js';
12
12
  import { portalInfoFields } from "../portal/info.js";
13
13
  import { sdkSource } from "../runtime/sdk-source.js";
14
14
  import { resolvedSdkLaunch } from "../contract/app-launch.js";
@@ -172,6 +172,8 @@ export async function assembleStandaloneSpk(options) {
172
172
  writeFile(join(staging, "package", GATEWAY_CONFIG_PATH), identityGatewayConfig(manifest));
173
173
  if (nativeGatewaySupported(manifest))
174
174
  writeFile(join(staging, 'package', NATIVE_GATEWAY_CONFIG), renderNativeGatewayConfig(manifest));
175
+ if (renderNativeOriginConfig(manifest))
176
+ writeFile(join(staging, 'package', NATIVE_ORIGIN_CONFIG), renderNativeOriginConfig(manifest));
175
177
  if (!nativeGatewaySdk(manifest.identityGateway.sdk))
176
178
  writeFile(join(staging, 'package/ui/sso/open.html'), legacyGatewayNotice());
177
179
  }
@@ -279,6 +281,7 @@ export async function assembleStandaloneSpk(options) {
279
281
  writePortPayload(manifest, join(staging, 'package'), variant => ({
280
282
  'sso/gateway.json': identityGatewayConfig(variant),
281
283
  ...(nativeGatewaySupported(variant) ? { [NATIVE_GATEWAY_CONFIG]: renderNativeGatewayConfig(variant) } : {}),
284
+ ...(renderNativeOriginConfig(variant) ? { [NATIVE_ORIGIN_CONFIG]: renderNativeOriginConfig(variant) } : {}),
282
285
  ...(hasSdkWindow(variant) ? { ['ui/' + windowScriptName(variant)]: renderWindowScript(variant, assetVersion, icons, options.portalText, moduleVersion) } : {}),
283
286
  ...(variant.daemon || variant.compose ? { 'daemon/config.json': daemonConfig(variant) } : {}),
284
287
  ...(variant.installSettings ? { 'install/settings.json': JSON.stringify(settingsConfig(variant), null, 2) + '\n' } : {}),
@@ -343,7 +346,7 @@ export async function assembleStandaloneSpk(options) {
343
346
  ...(gatewayAdmissionPolicy(manifest.identityGateway, manifest.entry) ? { provider_only_oidc: gatewayAdmissionPolicy(manifest.identityGateway, manifest.entry) } : {}),
344
347
  ...(manifest.identityGateway && gatewayExternalAccess(manifest.identityGateway)
345
348
  ? { gateway_external: gatewayExternalAccess(manifest.identityGateway) } : {}),
346
- ...(nativeGatewaySupported(manifest) ? { native_gateway: { sdk: manifest.identityGateway.sdk, listen: manifest.identityGateway.listen, ...(manifest.identityGateway.ingress ? { ingress: manifest.identityGateway.ingress } : {}) } } : {}),
349
+ ...(nativeGatewaySupported(manifest) ? { native_gateway: { sdk: manifest.identityGateway.sdk, listen: manifest.identityGateway.listen, ...(manifest.identityGateway.ingress ? { ingress: manifest.identityGateway.ingress } : {}), ...(manifest.identityGateway.origin ? { origin: manifest.identityGateway.origin } : {}) } } : {}),
347
350
  ...(manifest.daemon?.ingress ? { daemon_ingress: manifest.daemon.ingress } : {}),
348
351
  ...(manifest.daemon?.node ? { daemon_node: manifest.daemon.node } : {}),
349
352
  ...(manifest.daemon?.nofile !== undefined ? { daemon_nofile: manifest.daemon.nofile } : {}),
@@ -10,18 +10,24 @@ identity_gateway:
10
10
  listen: {https: 28443}
11
11
  ```
12
12
 
13
- The manifest's gateway HTTP/HTTPS listeners and optional local OIDC issuer port
14
- are the defaults. The install wizard shows each port with a localized label and
15
- reason. It refuses values outside 1024–65535, reserved DSM/discovery ports,
16
- duplicates and conflicts returned by DSM's `SYNO.Core.Service.PortInfo` listing.
17
- The listing includes DSM and installed-package service definitions. An unreadable,
18
- empty or malformed listing blocks Next; the wizard never assumes a port is free.
13
+ The manifest's gateway HTTP/HTTPS listeners, optional local OIDC issuer port
14
+ and optional second origin port (`identity_gateway.origin.https`, key
15
+ `gateway_origin`) are the defaults. The install wizard shows each port with a
16
+ localized label and reason. It refuses values that are not a number in
17
+ 1024–65535. Reserved DSM/discovery ports, duplicates and conflicts returned by
18
+ DSM's `SYNO.Core.Service.PortInfo` listing are inline warnings; Next stays
19
+ available. An unreadable listing establishes no conflict.
19
20
 
20
21
  The SDK repeats the check with DSM's `servicetool --conf-port-conflict-check` as
21
22
  the package account. It parses the documented `IsConflict` output and allows
22
23
  only its exact existing service ID during upgrade. A successful command exit
23
- alone does not mean a port is free. A concurrent change can still race a check;
24
- DSM's native resource acquisition and the listener bind remain final checks.
24
+ alone does not mean a port is free. A confirmed conflict refuses the port,
25
+ except for ports declared with `conflict: warn` in `install/ports.json` (the
26
+ CLI declares `gateway_origin` this way): their conflict is written to stderr,
27
+ which DSM keeps in the installation log, and the port is kept. Format, range,
28
+ reserved and duplicate values are always refused. A concurrent change can still
29
+ race a check; DSM's native resource acquisition and the listener bind remain
30
+ final checks.
25
31
 
26
32
  The package-account preinst controller materializes the selected values into all
27
33
  generated consumers: gateway configuration, nginx ingress, DSM window launcher,
@@ -56,10 +62,19 @@ fixed protocol discovery ports keep their upstream contract; changing a public
56
62
  host listener does not change the container's internal listening port.
57
63
 
58
64
  Upgrade retains the saved port selection and ignores new wizard environment
59
- values. To change ports, reinstall the same package and choose the new values
60
- in its installation wizard; shared data is retained by default. Re-enter any
61
- required HTTPS origin with the newly selected HTTPS port. The UI never copies
62
- private retained settings into a package or report.
65
+ values. The UI never copies private retained settings into a package or report.
66
+
67
+ ## Change ports after installation
68
+
69
+ An App's own settings page changes installed ports with the SDK's
70
+ `installsettings.ChangePorts(payload, package, pkgvar, map[string]int{"gateway_origin": 6443})`,
71
+ run as the package account. Only declared keys change; the same refusals and
72
+ conflict policies as installation apply, and warnings are returned. It rewrites
73
+ the generated payload files, `install/<package>.sc`, the environment and the
74
+ retained values, so later upgrades keep the change. DSM applies the new nginx
75
+ and port-config resources only when the package starts: restart the package
76
+ afterwards (the SDK's `selfrestart`). Re-enter any required HTTPS origin that
77
+ names a changed port. Reinstalling with new wizard values also works.
63
78
 
64
79
  Use `--param pkgwizard_port_gateway_https=29443` for a first CLI deployment;
65
80
  programmatic upgrades reject port changes. Apps must adopt `install.ports: true`
@@ -136,6 +136,65 @@ package and check both the active nginx location and an authenticated browser
136
136
  navigation. Include anonymous denial, the original entry policy and upstream
137
137
  assets/API calls; a successful install response alone is insufficient.
138
138
 
139
+ ## Second origin port
140
+
141
+ An App with path ingress can also serve a separate browser origin, for example
142
+ to show another web application that needs `/` and its own cookies:
143
+
144
+ ```yaml
145
+ install:
146
+ ports: true
147
+ identity_gateway:
148
+ sdk: <sdk-with-OriginVersion>
149
+ mode: none
150
+ upstream: unix:reverse-ingress.sock
151
+ ingress: {path: /synopkgland/ExampleApp/}
152
+ upstream_auth_paths: [/reverse]
153
+ origin:
154
+ https: 5443 # default; the installer may change it
155
+ upstream: unix:dsm-relay.sock # /var/packages/<package>/var/run/<name>.sock
156
+ cookies: dsm-passthrough # optional
157
+ headers: {user: X-Relay-User} # optional; needs user
158
+ ```
159
+
160
+ `origin` needs `ingress`, `install.ports: true`, no Compose, DSM 7.2-64570 or
161
+ later and an SDK whose `idgateway` declares `OriginVersion = 1`. Its keys are
162
+ `https` (1024–65535, not a reserved DSM port and not another gateway port),
163
+ `upstream` (a Unix socket of the package, as above), `cookies` and `headers`.
164
+
165
+ The build adds `sso/native-origin-nginx.conf`, a DSM nginx `server` block that
166
+ listens on the port with DSM's certificate and forwards everything to the
167
+ gateway's second mutually authenticated socket
168
+ (`/tmp/synopkgland-gateway-<package>-origin.sock`). It is enabled with
169
+ `nginx-static-config` `{type: server}` next to the `dsm` path entry; the
170
+ `port-config` resource registers the port. `inspect` replays this block and the
171
+ gateway's `origin` entry.
172
+
173
+ On that port the gateway:
174
+
175
+ - admits only DSM administrators (the entry is always `admin-only`), whatever the
176
+ App's own entry policy;
177
+ - uses its own session cookie, `synopkgland_sso_<package>_origin`;
178
+ - accepts the sign-in return only for `https://<same host>:<port>/_sso/return`.
179
+ The browser must already be signed in to DSM on that host; otherwise the
180
+ origin shows `login_required` instead of DSM's login page;
181
+ - sends the signed-in administrator in `headers` when `user` is set, otherwise
182
+ no identity;
183
+ - proxies WebSocket upgrades and long polls without a response timeout.
184
+
185
+ Cookies: by default the gateway strips DSM's cookies as on every other route.
186
+ `cookies: dsm-passthrough` forwards the upstream's own `_SSID`, `_CrPoSt`,
187
+ `stay_login` and other cookies in both directions, leaves response
188
+ `Set-Cookie` headers to the upstream, and removes only the gateway's cookies and
189
+ DSM's `id` and `did`, which belong to the DSM origin on the same host.
190
+
191
+ The port is the installer port `gateway_origin`. The wizard shows it as
192
+ "Dedicated HTTPS port"; a port that DSM already lists as used is a warning only,
193
+ for this port also in the package-account controller. Format, range, reserved
194
+ and duplicate values are refused. A port that is really in use makes the App
195
+ fail to start. To change the port after installation, see
196
+ [installer-selected ports](install-ports.md#change-ports-after-installation).
197
+
139
198
  ## Application Portal
140
199
 
141
200
  With `portal`, every generated path ingress is also registered as `type: www`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synopackageland/cli",
3
- "version": "0.54.8",
3
+ "version": "0.54.10",
4
4
  "description": "Syno Package Land Developer Kit CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -26,6 +26,20 @@
26
26
  "docs/install-memory.md",
27
27
  "docs/catalog-text.md"
28
28
  ],
29
+ "scripts": {
30
+ "check:docs": "node --test scripts/check-doc-versions.test.mjs && node scripts/check-doc-versions.mjs",
31
+ "build": "rm -rf dist && node scripts/prepare-native-http.mjs && tsc",
32
+ "test": "pnpm run build && node --import tsx --import ./test/helpers/strict-dsm-setup.ts --test --test-concurrency=${SYNOPKGLAND_GATE_JOBS:-3} test/*.test.ts test/ctl/*.test.ts",
33
+ "test:glossary": "node --test scripts/test/glossary-drift.test.mjs",
34
+ "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",
35
+ "gates": "bash scripts/ci/gates.sh",
36
+ "gates:fast": "bash scripts/ci/gates.sh",
37
+ "prepublishOnly": "pnpm run build && node --input-type=module -e 'import {enforceRepositorySecrets} from \"./dist/secret-files.js\"; enforceRepositorySecrets(process.cwd())'",
38
+ "gates:full": "bash scripts/ci/gates.sh --full",
39
+ "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",
40
+ "check:dsm-contract": "node scripts/check-dsm-api-contract.mjs",
41
+ "check:dsm-hub": "node scripts/check-dsm-api-hub.mjs"
42
+ },
29
43
  "dependencies": {
30
44
  "@napi-rs/keyring": "^2.1.1",
31
45
  "@synopackageland/templates": "~0.44.1",
@@ -88,17 +102,5 @@
88
102
  "./native-layout": "./dist/standalone/native-layout.js",
89
103
  "./e2e": "./dist/e2e/dsm.js"
90
104
  },
91
- "scripts": {
92
- "check:docs": "node --test scripts/check-doc-versions.test.mjs && node scripts/check-doc-versions.mjs",
93
- "build": "rm -rf dist && node scripts/prepare-native-http.mjs && tsc",
94
- "test": "pnpm run build && node --import tsx --import ./test/helpers/strict-dsm-setup.ts --test --test-concurrency=${SYNOPKGLAND_GATE_JOBS:-3} test/*.test.ts test/ctl/*.test.ts",
95
- "test:glossary": "node --test scripts/test/glossary-drift.test.mjs",
96
- "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",
97
- "gates": "bash scripts/ci/gates.sh",
98
- "gates:fast": "bash scripts/ci/gates.sh",
99
- "gates:full": "bash scripts/ci/gates.sh --full",
100
- "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",
101
- "check:dsm-contract": "node scripts/check-dsm-api-contract.mjs",
102
- "check:dsm-hub": "node scripts/check-dsm-api-hub.mjs"
103
- }
105
+ "packageManager": "pnpm@12.18.0"
104
106
  }
@@ -9,6 +9,23 @@
9
9
  "type": "string",
10
10
  "enum": ["required"],
11
11
  "description": "Require an HTTPS browser origin; HTTP document navigations show localized guidance, other App requests receive https_required; omit to retain HTTP support"
12
+ },
13
+ "origin": {
14
+ "type": "object",
15
+ "description": "A second, administrator-only HTTPS origin on its own port, served by DSM nginx with DSM's certificate; needs install.ports: true so the administrator can choose the port",
16
+ "required": ["https", "upstream"],
17
+ "properties": {
18
+ "https": {"type": "integer", "minimum": 1024, "maximum": 65535, "description": "Default port; installer and App settings may change it"},
19
+ "upstream": {"type": "string", "pattern": "^unix:[a-z0-9][a-z0-9-]{0,58}\\.sock$", "description": "The App's private socket under var/run"},
20
+ "cookies": {"type": "string", "enum": ["dsm-passthrough"], "description": "Forward DSM's _SSID, _CrPoSt and stay_login cookies both ways (a proxied DSM)"},
21
+ "headers": {
22
+ "type": "object",
23
+ "required": ["user"],
24
+ "properties": {"user": {"type": "string"}, "email": {"type": "string"}, "name": {"type": "string"}, "groups": {"type": "string"}, "uid": {"type": "string"}},
25
+ "additionalProperties": false
26
+ }
27
+ },
28
+ "additionalProperties": false
12
29
  }
13
30
  },
14
31
  "additionalProperties": true
@@ -375,3 +375,12 @@ NAS route ownership, including saved aliases and stopped SDK packages, and fails
375
375
  closed if inventory cannot be checked. DSM owns registration, upgrade replacement
376
376
  and uninstall cleanup; never overwrite or remove another owner's config. The
377
377
  menu CGI URL remains stable. See [path ingress](https://github.com/synopackageland/syno-pkg-land-cli/blob/main/docs/path-ingress.md).
378
+
379
+ A path-ingress App may add `identity_gateway.origin: {https: 5443, upstream: unix:<name>.sock}`
380
+ for a second, administrator-only browser origin on its own HTTPS port (DSM nginx
381
+ `server` block, installer port `gateway_origin`, conflicts only warn). It needs
382
+ `install.ports: true` and an SDK with `OriginVersion`. `cookies: dsm-passthrough`
383
+ forwards the upstream's own cookies except DSM's `id`/`did`; `headers.user`
384
+ sends the administrator's name. The browser must already be signed in to DSM.
385
+ Change the port later with `installsettings.ChangePorts` and a package restart.
386
+ See [second origin port](https://github.com/synopackageland/syno-pkg-land-cli/blob/main/docs/path-ingress.md#second-origin-port).
@@ -49,7 +49,7 @@ The upgrade wizard prefills and submits the recorded folder without a separate c
49
49
 
50
50
  Uninstall retains the share, files and package account's ACL because DSM data-share Release does nothing. Old selected shares can retain that ACL too. To revoke it, an administrator opens Control Panel > Shared Folder > the folder > Edit > Permissions > System internal user, clears the package account's Read only/Read/Write permission and saves, preserving other rows and data. See [shared-folder behavior](../../docs/shared-folders.md).
51
51
 
52
- Port fields default to declared gateway HTTP/HTTPS and local OIDC listener ports. Validation refuses noncanonical numbers and values outside 1024–65535. Reserved DSM/discovery ports, duplicate selections and conflicts from DSM's `SYNO.Core.Service.PortInfo` inventory produce inline warnings; Next remains available. The inventory is advisory: API, permission or parsing failures do not block Next, and an unsupported row does not hide a later confirmed conflict. DSM's all-protocol entries cover TCP too; numeric ports and string ranges are accepted. The package-account controller repeats the native service conflict check and materializes gateway, nginx, launcher, daemon and `.sc` port-config data from the selected values. A real conflict can still prevent the App from starting.
52
+ Port fields default to declared gateway HTTP/HTTPS, local OIDC listener and second-origin (`gateway_origin`) ports. Validation refuses noncanonical numbers and values outside 1024–65535. Reserved DSM/discovery ports, duplicate selections and conflicts from DSM's `SYNO.Core.Service.PortInfo` inventory produce inline warnings; Next remains available. The inventory is advisory: API, permission or parsing failures do not block Next, and an unsupported row does not hide a later confirmed conflict. DSM's all-protocol entries cover TCP too; numeric ports and string ranges are accepted. The package-account controller repeats the native service conflict check and materializes gateway, nginx, launcher, daemon and `.sc` port-config data from the selected values. A real conflict can still prevent the App from starting.
53
53
 
54
54
  Native subprocesses and Compose `.env` receive `SYNOPKGLAND_PORT_GATEWAY_HTTP`, `SYNOPKGLAND_PORT_GATEWAY_HTTPS` and, when declared, `SYNOPKGLAND_PORT_OIDC_ISSUER`. Go Apps can read `installsettings.PortValues(payloadRoot)`. Bind upstream public-port configuration declaratively:
55
55
 
@@ -66,7 +66,7 @@ compose:
66
66
 
67
67
  Existing runtime file templates can use the same variable in the App's own configuration. Container-internal listener and fixed discovery ports keep their upstream contract. Do not hard-code the selected host port elsewhere.
68
68
 
69
- Upgrade retains the saved ports and ignores submitted replacements. Reinstall to change ports, then re-enter any required HTTPS origin with its new HTTPS port. First-install CLI automation accepts `--param pkgwizard_port_gateway_https=29443`; programmatic upgrade refuses port changes. Omit `install.ports` when no identity gateway is declared.
69
+ Upgrade retains the saved ports and ignores submitted replacements. To change ports, the App calls the SDK's `installsettings.ChangePorts` as the package account and restarts the package, or the user reinstalls; then re-enter any required HTTPS origin with its new HTTPS port. The package-account check refuses a confirmed conflict except on a `conflict: warn` port (`gateway_origin`), where it only warns. First-install CLI automation accepts `--param pkgwizard_port_gateway_https=29443`; programmatic upgrade refuses port changes. Omit `install.ports` when no identity gateway is declared.
70
70
 
71
71
  Use `install.settings` with `type: https-origin`, a localized label and explicit `required: true` for an origin needed by the App. The wizard blocks Next for missing or malformed values and checks the selected HTTPS port. Runtime validation repeats the check.
72
72