@nimiplatform/app-tools 0.2.1 → 0.2.2

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.
@@ -1,5 +1,17 @@
1
1
  export const SUPPORTED_APP_SCAFFOLD_PROFILES = ['standalone'];
2
2
 
3
+ export function resolveWindowsResourceVersion(appVersion) {
4
+ const semverPattern = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u;
5
+ if (typeof appVersion !== 'string' || !semverPattern.test(appVersion)) {
6
+ throw new Error(`Windows production packaging requires an exact semantic App version: ${String(appVersion)}`);
7
+ }
8
+ const coreComponents = appVersion.split(/[+-]/u, 1)[0].split('.');
9
+ if (coreComponents.some((component) => BigInt(component) > 65535n)) {
10
+ throw new Error(`Windows production packaging requires App version core components in the 0..65535 range: ${appVersion}`);
11
+ }
12
+ return `${coreComponents.join('.')}.0`;
13
+ }
14
+
3
15
  export function buildDefaultStarterFiles(identity) {
4
16
  return [
5
17
  {
@@ -33,6 +45,16 @@ export function buildDefaultStarterFiles(identity) {
33
45
  content: DEFAULT_ELECTRON_PRELOAD_BUNDLER,
34
46
  mutationClass: 'scaffold-managed glue',
35
47
  },
48
+ {
49
+ path: 'scripts/clean-electron-production.mjs',
50
+ content: DEFAULT_ELECTRON_PRODUCTION_CLEANER,
51
+ mutationClass: 'scaffold-managed glue',
52
+ },
53
+ {
54
+ path: 'scripts/package-electron-production.mjs',
55
+ content: renderDefaultElectronProductionPackager(identity),
56
+ mutationClass: 'scaffold-managed glue',
57
+ },
36
58
  {
37
59
  path: 'tsconfig.electron.json',
38
60
  content: DEFAULT_ELECTRON_TSCONFIG,
@@ -90,6 +112,184 @@ const DEFAULT_ELECTRON_PRELOAD_BUNDLER = [
90
112
  '',
91
113
  ].join('\n');
92
114
 
115
+ const DEFAULT_ELECTRON_PRODUCTION_CLEANER = [
116
+ "import { rm } from 'node:fs/promises';",
117
+ "import path from 'node:path';",
118
+ "import { fileURLToPath } from 'node:url';",
119
+ '',
120
+ "const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');",
121
+ "await rm(path.join(appRoot, 'dist-electron-package'), { recursive: true, force: true });",
122
+ '',
123
+ ].join('\n');
124
+
125
+ function renderDefaultElectronProductionPackager(identity) {
126
+ return [
127
+ "import { spawn } from 'node:child_process';",
128
+ "import { copyFile, cp, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';",
129
+ "import { createRequire } from 'node:module';",
130
+ "import { tmpdir } from 'node:os';",
131
+ "import path from 'node:path';",
132
+ "import { fileURLToPath } from 'node:url';",
133
+ "import { packager } from '@electron/packager';",
134
+ "import { build } from 'esbuild';",
135
+ '',
136
+ `const APP_EXECUTABLE_NAME = ${JSON.stringify(identity.cargoPackageName)};`,
137
+ `const APP_PRODUCT_NAME = ${JSON.stringify(identity.appTitle)};`,
138
+ `const APP_VERSION = ${JSON.stringify(identity.version)};`,
139
+ resolveWindowsResourceVersion.toString(),
140
+ 'const WINDOWS_RESOURCE_VERSION = resolveWindowsResourceVersion(APP_VERSION);',
141
+ "const NATIVE_BINDING_PACKAGE = '@nimiplatform/kit-protected-local-win32-x64';",
142
+ "const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');",
143
+ "const outputRoot = path.join(appRoot, 'dist-electron-package');",
144
+ "const requireFromApp = createRequire(path.join(appRoot, 'package.json'));",
145
+ '',
146
+ "if (process.platform !== 'win32' || process.arch !== 'x64') {",
147
+ " throw new Error('The windows-x86_64 Electron production profile requires a win32-x64 build host.');",
148
+ '}',
149
+ '',
150
+ "const appPackage = JSON.parse(await readFile(path.join(appRoot, 'package.json'), 'utf8'));",
151
+ "for (const sectionName of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {",
152
+ ' if (Object.hasOwn(appPackage[sectionName] || {}, NATIVE_BINDING_PACKAGE)) {',
153
+ " throw new Error('The protected native binding must arrive through the Kit optional dependency.');",
154
+ ' }',
155
+ '}',
156
+ "const electronPackage = JSON.parse(await readFile(requireFromApp.resolve('electron/package.json'), 'utf8'));",
157
+ "const kitEntry = requireFromApp.resolve('@nimiplatform/kit/shell/electron/main');",
158
+ "const kitRoot = await findPackageRoot(kitEntry, '@nimiplatform/kit');",
159
+ "const kitPackage = JSON.parse(await readFile(path.join(kitRoot, 'package.json'), 'utf8'));",
160
+ 'if (!Object.hasOwn(kitPackage.optionalDependencies || {}, NATIVE_BINDING_PACKAGE)) {',
161
+ " throw new Error('Kit does not declare the windows-x64 protected native binding as optional.');",
162
+ '}',
163
+ "const requireFromKit = createRequire(path.join(kitRoot, 'package.json'));",
164
+ 'const nativeEntry = requireFromKit.resolve(NATIVE_BINDING_PACKAGE);',
165
+ 'const nativePackageRoot = await findPackageRoot(nativeEntry, NATIVE_BINDING_PACKAGE);',
166
+ '',
167
+ 'await rm(outputRoot, { recursive: true, force: true });',
168
+ "const stagingRoot = await mkdtemp(path.join(tmpdir(), 'nimi-electron-packager-'));",
169
+ "const productionSourceRoot = path.join(stagingRoot, 'app');",
170
+ "const packagerTempRoot = path.join(stagingRoot, 'packager');",
171
+ 'let packageCompleted = false;',
172
+ '',
173
+ 'try {',
174
+ ' await build({',
175
+ " entryPoints: [path.join(appRoot, 'src-electron/main.ts')],",
176
+ " outfile: path.join(appRoot, 'dist-electron/main.js'),",
177
+ ' bundle: true,',
178
+ " platform: 'node',",
179
+ " target: 'node22',",
180
+ " format: 'esm',",
181
+ " packages: 'external',",
182
+ " external: ['electron'],",
183
+ " define: { __NIMI_ELECTRON_PRODUCTION__: 'true' },",
184
+ " logLevel: 'silent',",
185
+ ' });',
186
+ '',
187
+ " await realpath(path.join(appRoot, 'dist', 'index.html'));",
188
+ " await realpath(path.join(appRoot, 'dist-electron', 'preload.cjs'));",
189
+ '',
190
+ ' await mkdir(path.join(productionSourceRoot, \'dist-electron\'), { recursive: true });',
191
+ " await copyFile(path.join(appRoot, 'package.json'), path.join(productionSourceRoot, 'package.json'));",
192
+ " await copyFile(path.join(appRoot, 'pnpm-lock.yaml'), path.join(productionSourceRoot, 'pnpm-lock.yaml'));",
193
+ " await cp(path.join(appRoot, 'dist'), path.join(productionSourceRoot, 'dist'), { recursive: true, force: false });",
194
+ " await copyFile(path.join(appRoot, 'dist-electron', 'main.js'), path.join(productionSourceRoot, 'dist-electron', 'main.js'));",
195
+ " await copyFile(path.join(appRoot, 'dist-electron', 'preload.cjs'), path.join(productionSourceRoot, 'dist-electron', 'preload.cjs'));",
196
+ ' await installProductionDependencies(productionSourceRoot);',
197
+ '',
198
+ " const productionManifestPath = path.join(productionSourceRoot, 'package.json');",
199
+ " const productionManifest = JSON.parse(await readFile(productionManifestPath, 'utf8'));",
200
+ ' delete productionManifest.devDependencies;',
201
+ " await writeFile(productionManifestPath, `${JSON.stringify(productionManifest, null, 2)}\\n`);",
202
+ " await rm(path.join(productionSourceRoot, 'pnpm-lock.yaml'));",
203
+ '',
204
+ " const nativeDestination = path.join(productionSourceRoot, 'node_modules', ...NATIVE_BINDING_PACKAGE.split('/'));",
205
+ ' await rm(nativeDestination, { recursive: true, force: true });',
206
+ ' await mkdir(path.dirname(nativeDestination), { recursive: true });',
207
+ ' await cp(nativePackageRoot, nativeDestination, { recursive: true, dereference: true, force: false });',
208
+ ' await mkdir(packagerTempRoot, { recursive: true });',
209
+ '',
210
+ ' const packagePaths = await packager({',
211
+ ' dir: productionSourceRoot,',
212
+ " platform: 'win32',",
213
+ " arch: 'x64',",
214
+ ' name: APP_EXECUTABLE_NAME,',
215
+ ' executableName: APP_EXECUTABLE_NAME,',
216
+ ' appVersion: WINDOWS_RESOURCE_VERSION,',
217
+ ' buildVersion: WINDOWS_RESOURCE_VERSION,',
218
+ ' electronVersion: electronPackage.version,',
219
+ ' out: outputRoot,',
220
+ ' tmpdir: packagerTempRoot,',
221
+ ' overwrite: false,',
222
+ ' asar: false,',
223
+ ' prune: false,',
224
+ ' quiet: true,',
225
+ ' derefSymlinks: true,',
226
+ ' afterInitialize: [async ({ buildPath }) => {',
227
+ " const packagedManifestPath = path.join(buildPath, 'package.json');",
228
+ " const packagedManifest = JSON.parse(await readFile(packagedManifestPath, 'utf8'));",
229
+ ' packagedManifest.version = APP_VERSION;',
230
+ " await writeFile(packagedManifestPath, `${JSON.stringify(packagedManifest, null, 2)}\\n`);",
231
+ ' }],',
232
+ ' win32metadata: {',
233
+ ' ProductName: APP_PRODUCT_NAME,',
234
+ ' FileDescription: APP_PRODUCT_NAME,',
235
+ ' InternalName: APP_EXECUTABLE_NAME,',
236
+ ' OriginalFilename: `${APP_EXECUTABLE_NAME}.exe`,',
237
+ " 'requested-execution-level': 'asInvoker',",
238
+ ' },',
239
+ ' });',
240
+ " if (!Array.isArray(packagePaths) || packagePaths.length !== 1) throw new Error('Electron packager returned an ambiguous production package.');",
241
+ ' const expectedPackageRoot = path.join(outputRoot, `${APP_EXECUTABLE_NAME}-win32-x64`);',
242
+ ' if (path.resolve(packagePaths[0]).toLowerCase() !== path.resolve(expectedPackageRoot).toLowerCase()) {',
243
+ " throw new Error('Electron packager returned an unexpected production package path.');",
244
+ ' }',
245
+ ' await realpath(path.join(expectedPackageRoot, `${APP_EXECUTABLE_NAME}.exe`));',
246
+ ' packageCompleted = true;',
247
+ ' process.stdout.write(`[nimi-app] Electron production package: ${expectedPackageRoot}\\n`);',
248
+ '} finally {',
249
+ ' const cleanupTasks = [rm(stagingRoot, { recursive: true, force: true })];',
250
+ ' if (!packageCompleted) cleanupTasks.push(rm(outputRoot, { recursive: true, force: true }));',
251
+ ' await Promise.all(cleanupTasks);',
252
+ '}',
253
+ '',
254
+ 'async function installProductionDependencies(projectRoot) {',
255
+ " const command = 'pnpm install --prod --frozen-lockfile --ignore-scripts --node-linker=hoisted';",
256
+ " const commandShell = process.env.ComSpec || 'cmd.exe';",
257
+ ' await new Promise((resolve, reject) => {',
258
+ " const child = spawn(commandShell, ['/d', '/s', '/c', command], {",
259
+ ' cwd: projectRoot,',
260
+ " stdio: 'inherit',",
261
+ ' windowsHide: true,',
262
+ ' });',
263
+ " child.once('error', reject);",
264
+ " child.once('exit', (code, signal) => {",
265
+ ' if (code === 0) {',
266
+ ' resolve();',
267
+ ' return;',
268
+ ' }',
269
+ " reject(new Error(`pnpm production dependency staging failed (${signal || `exit ${String(code)}`}).`));",
270
+ ' });',
271
+ ' });',
272
+ '}',
273
+ '',
274
+ 'async function findPackageRoot(entry, expectedName) {',
275
+ ' let current = path.dirname(await realpath(entry));',
276
+ ' for (;;) {',
277
+ " const manifestPath = path.join(current, 'package.json');",
278
+ ' try {',
279
+ " const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));",
280
+ ' if (manifest.name === expectedName) return current;',
281
+ ' } catch (error) {',
282
+ " if (error?.code !== 'ENOENT') throw error;",
283
+ ' }',
284
+ ' const parent = path.dirname(current);',
285
+ " if (parent === current) throw new Error(`Unable to locate installed package ${expectedName}.`);",
286
+ ' current = parent;',
287
+ ' }',
288
+ '}',
289
+ '',
290
+ ].join('\n');
291
+ }
292
+
93
293
  const DEFAULT_ELECTRON_TSCONFIG = `${JSON.stringify({
94
294
  extends: './tsconfig.json',
95
295
  compilerOptions: {
@@ -1002,8 +1202,12 @@ function renderDefaultElectronMain(identity) {
1002
1202
  ' registerNimiElectronAppBridge,',
1003
1203
  "} from '@nimiplatform/kit/shell/electron/main';",
1004
1204
  '',
1205
+ 'declare const __NIMI_ELECTRON_PRODUCTION__: boolean;',
1206
+ '',
1005
1207
  `const APP_ID = '${identity.appId}';`,
1006
1208
  `const NATIVE_BUNDLE_IDENTIFIER = ${JSON.stringify(identity.nativeBundleIdentifier)};`,
1209
+ "const IS_PRODUCTION_BUNDLE = typeof __NIMI_ELECTRON_PRODUCTION__ !== 'undefined'",
1210
+ ' && __NIMI_ELECTRON_PRODUCTION__;',
1007
1211
  "const currentDir = path.dirname(fileURLToPath(import.meta.url));",
1008
1212
  "const appRoot = path.resolve(currentDir, '..');",
1009
1213
  "const preloadPath = path.join(currentDir, 'preload.cjs');",
@@ -1057,7 +1261,13 @@ function renderDefaultElectronMain(identity) {
1057
1261
  '}',
1058
1262
  '',
1059
1263
  'function readDevelopmentRendererUrl(): string {',
1264
+ " const flag = '--nimi-dev-renderer-url';",
1060
1265
  " const prefix = '--nimi-dev-renderer-url=';",
1266
+ ' const hasDevelopmentRendererArgument = process.argv.some((value) => value === flag || value.startsWith(prefix));',
1267
+ ' if (IS_PRODUCTION_BUNDLE && hasDevelopmentRendererArgument) {',
1268
+ " throw new Error('The production Electron bundle rejects --nimi-dev-renderer-url.');",
1269
+ ' }',
1270
+ ' if (process.argv.includes(flag)) throw new Error(\'Nimi development renderer URL is missing.\');',
1061
1271
  ' const values = process.argv.filter((value) => value.startsWith(prefix));',
1062
1272
  ' if (values.length === 0) return \'\';',
1063
1273
  " if (values.length !== 1) throw new Error('Nimi development renderer URL must be singular.');",
@@ -19,6 +19,8 @@ import {
19
19
  SUPPORTED_APP_SCAFFOLD_PROFILES,
20
20
  buildDefaultStarterFiles,
21
21
  } from './app-scaffold-profiles.mjs';
22
+
23
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-009b
22
24
  export { SUPPORTED_APP_SCAFFOLD_PROFILES };
23
25
  const DEFAULT_APP_ID = 'my.nimi-app';
24
26
  const DEFAULT_APP_TITLE = 'My Nimi App';
@@ -35,6 +37,7 @@ const GENERATED_GITIGNORE = [
35
37
  'node_modules/',
36
38
  'dist/',
37
39
  'dist-electron/',
40
+ 'dist-electron-package/',
38
41
  'src-tauri/target/',
39
42
  '.env.local',
40
43
  '.env.*.local',
@@ -151,13 +154,11 @@ const APP_RELEASE_WORKFLOW = [
151
154
  ' NIMI_APP_TARGET: ${{ matrix.target }}',
152
155
  ' shell: pwsh',
153
156
  ' run: pnpm exec nimi-app build --target $env:NIMI_APP_TARGET',
154
- ' - name: Build and sign production target',
157
+ ' - name: Build production target',
155
158
  " if: github.event_name == 'push' && github.ref_type == 'tag'",
156
159
  ' env:',
157
160
  ' NIMI_APP_TARGET: ${{ matrix.target }}',
158
161
  ' NIMI_APP_PRODUCTION: true',
159
- ' WINDOWS_CERTIFICATE_BASE64: ${{ secrets.WINDOWS_CERTIFICATE_BASE64 }}',
160
- ' WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}',
161
162
  ' shell: pwsh',
162
163
  ' run: pnpm exec nimi-app build --target $env:NIMI_APP_TARGET --production',
163
164
  ' - name: Require build to preserve the tracked source tree',
@@ -539,6 +540,7 @@ export function resolveAppScaffoldCandidateCreateInput(input) {
539
540
  function buildPackageJson(profile, versions, identity) {
540
541
  const dependencies = buildRuntimeDependencies(profile, versions, identity.capabilityResolution);
541
542
  const devDependencies = {
543
+ '@electron/packager': versions.electronPackagerVersion,
542
544
  '@nimiplatform/app-tools': versions.appToolsVersion,
543
545
  '@nimiplatform/nimi-coding': versions.nimicodingVersion,
544
546
  '@tailwindcss/vite': versions.tailwindcssViteVersion,
@@ -562,6 +564,7 @@ function buildPackageJson(profile, versions, identity) {
562
564
  version: identity.version,
563
565
  private: true,
564
566
  type: 'module',
567
+ main: 'dist-electron/main.js',
565
568
  packageManager: versions.packageManager,
566
569
  pnpm: {
567
570
  onlyBuiltDependencies: ['electron', 'esbuild', 'protobufjs'],
@@ -581,7 +584,8 @@ function buildPackageJson(profile, versions, identity) {
581
584
  typecheck: 'tsc --noEmit',
582
585
  build: 'tsc --noEmit && vite build',
583
586
  'build:electron': 'tsc -p tsconfig.electron.json && node scripts/bundle-electron-preload.mjs',
584
- 'build:shell': 'tauri build',
587
+ 'build:electron:production': 'node scripts/clean-electron-production.mjs && pnpm run build && pnpm run build:electron && node scripts/package-electron-production.mjs',
588
+ 'build:tauri:production': 'tauri build',
585
589
  postinstall: 'install-electron --no',
586
590
  validate: 'node scripts/validate.mjs',
587
591
  },
@@ -976,16 +980,16 @@ export function renderAppBuildProfile(options = {}) {
976
980
  'windows-x86_64': {
977
981
  os: 'windows',
978
982
  arch: 'x86_64',
979
- build_command: 'pnpm run build:shell',
980
- payload_path: `src-tauri/target/release/${identity.cargoPackageName}.exe`,
983
+ build_command: 'pnpm run build:electron:production',
984
+ payload_path: `dist-electron-package/${identity.cargoPackageName}-win32-x64`,
981
985
  runtime_entry: `payload/${identity.cargoPackageName}.exe`,
982
986
  },
983
987
  } : undefined);
984
988
  return YAML.stringify({
985
- build_profile_ref: 'tauri-pnpm-vite',
989
+ build_profile_ref: 'electron-packager-pnpm-vite',
986
990
  test_command: options.testCommand || 'pnpm run test:app',
987
- build_command: options.buildCommand || 'pnpm run build:shell',
988
- output_path: 'src-tauri/target/release',
991
+ build_command: options.buildCommand || 'pnpm run build:electron:production',
992
+ output_path: 'dist-electron-package',
989
993
  lockfile_path: 'pnpm-lock.yaml',
990
994
  lockfile_policy: LOCKFILE_POLICY,
991
995
  ci_install_command: 'pnpm install --frozen-lockfile',
@@ -1255,6 +1259,7 @@ function buildDependencyMatrix(profile, versions, capabilityResolution) {
1255
1259
  '@tauri-apps/cli': versions.tauriCliVersion,
1256
1260
  '@tailwindcss/vite': versions.tailwindcssViteVersion,
1257
1261
  '@vitejs/plugin-react': versions.viteReactPluginVersion,
1262
+ '@electron/packager': versions.electronPackagerVersion,
1258
1263
  electron: versions.electronVersion,
1259
1264
  esbuild: versions.esbuildVersion,
1260
1265
  yaml: versions.yamlVersion,
package/lib/index.mjs CHANGED
@@ -17,7 +17,6 @@ import {
17
17
  testAppProject,
18
18
  } from './app-project-lifecycle.mjs';
19
19
  import { aggregateAppTargetCandidates, packAppTarget } from './app-pack.mjs';
20
- import { windowsPowerShellEnv } from './windows-powershell.mjs';
21
20
  export { runDevShell } from '../scripts/dev-shell.mjs';
22
21
  export {
23
22
  validateSimulatorAppSource,
@@ -105,49 +104,8 @@ function runAppCommand(targetDir, command, options = {}) {
105
104
  };
106
105
  }
107
106
 
108
- function signWindowsTarget(targetDir, relativePayloadPath) {
109
- const targetPath = path.resolve(targetDir, ...relativePayloadPath.split('/'));
110
- const rootPrefix = `${path.resolve(targetDir)}${path.sep}`;
111
- if (!targetPath.startsWith(rootPrefix) || !existsSync(targetPath) || !statSync(targetPath).isFile()) {
112
- throw new Error(`Windows production signing target is missing: ${relativePayloadPath}`);
113
- }
114
- const script = [
115
- "$ErrorActionPreference = 'Stop'",
116
- "if ([string]::IsNullOrWhiteSpace($env:WINDOWS_CERTIFICATE_BASE64) -or [string]::IsNullOrWhiteSpace($env:WINDOWS_CERTIFICATE_PASSWORD)) { throw 'Windows signing credentials are missing' }",
117
- "$pfxPath = Join-Path ([IO.Path]::GetTempPath()) ('nimi-app-sign-' + [guid]::NewGuid().ToString('N') + '.pfx')",
118
- '$cert = $null',
119
- 'try {',
120
- ' [IO.File]::WriteAllBytes($pfxPath, [Convert]::FromBase64String($env:WINDOWS_CERTIFICATE_BASE64))',
121
- ' $password = ConvertTo-SecureString $env:WINDOWS_CERTIFICATE_PASSWORD -AsPlainText -Force',
122
- " $cert = Import-PfxCertificate -FilePath $pfxPath -CertStoreLocation 'Cert:\\CurrentUser\\My' -Password $password -Exportable:$false",
123
- " if (-not $cert) { throw 'Windows signing certificate import failed' }",
124
- " $kitsRoot = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\\10\\bin'",
125
- " $signTool = Get-ChildItem -LiteralPath $kitsRoot -Filter 'signtool.exe' -Recurse -File | Where-Object { $_.FullName -match '\\\\x64\\\\signtool\\.exe$' } | Sort-Object FullName -Descending | Select-Object -First 1",
126
- " if (-not $signTool) { throw 'signtool.exe was not found' }",
127
- " & $signTool.FullName sign /fd SHA256 /td SHA256 /tr 'http://timestamp.digicert.com' /sha1 $cert.Thumbprint $env:NIMI_APP_SIGN_TARGET",
128
- " if ($LASTEXITCODE -ne 0) { throw 'signtool failed' }",
129
- ' $signature = Get-AuthenticodeSignature -LiteralPath $env:NIMI_APP_SIGN_TARGET',
130
- " if ($signature.Status -ne 'Valid') { throw ('Authenticode status: ' + $signature.Status) }",
131
- ' $signature.SignerCertificate.Subject',
132
- '} finally {',
133
- " if ($cert) { Remove-Item -LiteralPath ('Cert:\\CurrentUser\\My\\' + $cert.Thumbprint) -Force -ErrorAction SilentlyContinue }",
134
- ' [IO.File]::Delete($pfxPath)',
135
- '}',
136
- ].join('\n');
137
- const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
138
- cwd: targetDir,
139
- encoding: 'utf8',
140
- env: windowsPowerShellEnv({ NIMI_APP_SIGN_TARGET: targetPath }),
141
- });
142
- if (result.status !== 0) {
143
- const detail = [result.error?.message, result.stdout, result.stderr].filter(Boolean).join('\n').trim();
144
- throw new Error(`Windows production signing failed${detail ? `: ${detail}` : ''}`);
145
- }
146
- return { subject: String(result.stdout || '').trim() };
147
- }
148
-
149
107
  function appToolRunners() {
150
- return { runNimicodingSync, runAppCommand, signWindowsTarget };
108
+ return { runNimicodingSync, runAppCommand };
151
109
  }
152
110
 
153
111
  export function createApp(cwd, options = {}) {
@@ -1,3 +1,10 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-024b
2
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-034a
3
+
4
+ import { spawnSync } from 'node:child_process';
5
+ import { closeSync, existsSync, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
6
+ import path from 'node:path';
7
+
1
8
  export function windowsPowerShellEnv(overrides = {}, baseEnv = process.env) {
2
9
  const env = { ...baseEnv, ...overrides };
3
10
  for (const key of Object.keys(env)) {
@@ -5,3 +12,261 @@ export function windowsPowerShellEnv(overrides = {}, baseEnv = process.env) {
5
12
  }
6
13
  return env;
7
14
  }
15
+
16
+ const WINDOWS_PE_SIGNATURE = 0x00004550;
17
+ const WINDOWS_PE_MACHINE_AMD64 = 0x8664;
18
+ const WINDOWS_PE32_PLUS_MAGIC = 0x020b;
19
+ const WINDOWS_PE_CHARACTERISTIC_EXECUTABLE_IMAGE = 0x0002;
20
+ const WINDOWS_PE_CHARACTERISTIC_SYSTEM = 0x1000;
21
+ const WINDOWS_PE_CHARACTERISTIC_DLL = 0x2000;
22
+ const WINDOWS_PE_SUBSYSTEM_GUI = 2;
23
+ const WINDOWS_PE_SUBSYSTEM_CUI = 3;
24
+
25
+ function readExact(fd, length, position, label) {
26
+ const buffer = Buffer.alloc(length);
27
+ let offset = 0;
28
+ while (offset < length) {
29
+ const read = readSync(fd, buffer, offset, length - offset, position + offset);
30
+ if (read === 0) throw new Error(`Windows executable PE verification failed: truncated ${label}`);
31
+ offset += read;
32
+ }
33
+ return buffer;
34
+ }
35
+
36
+ function validateWindowsExecutablePeHeader(executablePath) {
37
+ const fd = openSync(executablePath, 'r');
38
+ try {
39
+ const size = fstatSync(fd).size;
40
+ if (!Number.isSafeInteger(size) || size < 64) {
41
+ throw new Error('Windows executable PE verification failed: truncated DOS header');
42
+ }
43
+ const dosHeader = readExact(fd, 64, 0, 'DOS header');
44
+ if (dosHeader[0] !== 0x4d || dosHeader[1] !== 0x5a) {
45
+ throw new Error('Windows executable PE verification failed: DOS signature must be MZ');
46
+ }
47
+ const peOffset = dosHeader.readUInt32LE(0x3c);
48
+ if (peOffset < 64 || peOffset > size - 24) {
49
+ throw new Error('Windows executable PE verification failed: PE header offset is out of bounds');
50
+ }
51
+ const coffHeader = readExact(fd, 24, peOffset, 'PE and COFF header');
52
+ if (coffHeader.readUInt32LE(0) !== WINDOWS_PE_SIGNATURE) {
53
+ throw new Error('Windows executable PE verification failed: PE signature is invalid');
54
+ }
55
+ const machine = coffHeader.readUInt16LE(4);
56
+ if (machine !== WINDOWS_PE_MACHINE_AMD64) {
57
+ throw new Error(`Windows executable PE verification failed: machine must be AMD64 (0x8664), observed 0x${machine.toString(16).padStart(4, '0')}`);
58
+ }
59
+ const sectionCount = coffHeader.readUInt16LE(6);
60
+ const optionalHeaderSize = coffHeader.readUInt16LE(20);
61
+ const characteristics = coffHeader.readUInt16LE(22);
62
+ const optionalHeaderOffset = peOffset + 24;
63
+ const sectionTableOffset = optionalHeaderOffset + optionalHeaderSize;
64
+ const sectionTableEnd = sectionTableOffset + sectionCount * 40;
65
+ if (sectionCount === 0 || optionalHeaderSize < 70 || sectionTableEnd > size) {
66
+ throw new Error('Windows executable PE verification failed: optional header or section table is out of bounds');
67
+ }
68
+ const optionalHeader = readExact(fd, 70, optionalHeaderOffset, 'PE optional header');
69
+ const magic = optionalHeader.readUInt16LE(0);
70
+ if (magic !== WINDOWS_PE32_PLUS_MAGIC) {
71
+ throw new Error(`Windows executable PE verification failed: optional header must be PE32+ (0x020b), observed 0x${magic.toString(16).padStart(4, '0')}`);
72
+ }
73
+ if ((characteristics & WINDOWS_PE_CHARACTERISTIC_EXECUTABLE_IMAGE) === 0) {
74
+ throw new Error('Windows executable PE verification failed: IMAGE_FILE_EXECUTABLE_IMAGE is required');
75
+ }
76
+ if ((characteristics & WINDOWS_PE_CHARACTERISTIC_DLL) !== 0) {
77
+ throw new Error('Windows executable PE verification failed: IMAGE_FILE_DLL is not a process Runtime entry');
78
+ }
79
+ if ((characteristics & WINDOWS_PE_CHARACTERISTIC_SYSTEM) !== 0) {
80
+ throw new Error('Windows executable PE verification failed: IMAGE_FILE_SYSTEM is not a user-mode Runtime entry');
81
+ }
82
+ const subsystem = optionalHeader.readUInt16LE(68);
83
+ if (subsystem !== WINDOWS_PE_SUBSYSTEM_GUI && subsystem !== WINDOWS_PE_SUBSYSTEM_CUI) {
84
+ throw new Error(`Windows executable PE verification failed: subsystem must be WINDOWS_GUI or WINDOWS_CUI, observed ${subsystem}`);
85
+ }
86
+ } finally {
87
+ closeSync(fd);
88
+ }
89
+ }
90
+
91
+ const WINDOWS_EXECUTABLE_FACTS_SCRIPT = String.raw`
92
+ $ErrorActionPreference = 'Stop'
93
+
94
+ Add-Type -TypeDefinition @'
95
+ using System;
96
+ using System.ComponentModel;
97
+ using System.Runtime.InteropServices;
98
+
99
+ public static class NimiWindowsExecutionProfile
100
+ {
101
+ private const uint ResourceNameValid = 0x00000008;
102
+ private const uint RunlevelInformationInActivationContext = 5;
103
+ private static readonly IntPtr InvalidHandleValue = new IntPtr(-1);
104
+
105
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
106
+ private struct ActivationContext
107
+ {
108
+ public uint Size;
109
+ public uint Flags;
110
+ [MarshalAs(UnmanagedType.LPWStr)] public string Source;
111
+ public ushort ProcessorArchitecture;
112
+ public ushort LanguageId;
113
+ [MarshalAs(UnmanagedType.LPWStr)] public string AssemblyDirectory;
114
+ public IntPtr ResourceName;
115
+ [MarshalAs(UnmanagedType.LPWStr)] public string ApplicationName;
116
+ public IntPtr Module;
117
+ }
118
+
119
+ [StructLayout(LayoutKind.Sequential)]
120
+ public struct RunLevelInformation
121
+ {
122
+ public uint Flags;
123
+ public uint RunLevel;
124
+ public uint UiAccess;
125
+ }
126
+
127
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
128
+ private static extern IntPtr CreateActCtxW(ref ActivationContext activationContext);
129
+
130
+ [DllImport("kernel32.dll", SetLastError = true)]
131
+ private static extern void ReleaseActCtx(IntPtr activationContext);
132
+
133
+ [DllImport("kernel32.dll", SetLastError = true)]
134
+ [return: MarshalAs(UnmanagedType.Bool)]
135
+ private static extern bool QueryActCtxW(
136
+ uint flags,
137
+ IntPtr activationContext,
138
+ IntPtr subInstance,
139
+ uint informationClass,
140
+ ref RunLevelInformation buffer,
141
+ UIntPtr bufferSize,
142
+ out UIntPtr writtenOrRequired);
143
+
144
+ public static RunLevelInformation Read(string executablePath)
145
+ {
146
+ ActivationContext input = new ActivationContext();
147
+ input.Size = checked((uint)Marshal.SizeOf(typeof(ActivationContext)));
148
+ input.Flags = ResourceNameValid;
149
+ input.Source = executablePath;
150
+ input.ResourceName = new IntPtr(1);
151
+ IntPtr activationContext = CreateActCtxW(ref input);
152
+ if (activationContext == InvalidHandleValue)
153
+ {
154
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to create an activation context from the embedded process manifest");
155
+ }
156
+
157
+ try
158
+ {
159
+ RunLevelInformation output = new RunLevelInformation();
160
+ UIntPtr writtenOrRequired;
161
+ bool queried = QueryActCtxW(
162
+ 0,
163
+ activationContext,
164
+ IntPtr.Zero,
165
+ RunlevelInformationInActivationContext,
166
+ ref output,
167
+ (UIntPtr)Marshal.SizeOf(typeof(RunLevelInformation)),
168
+ out writtenOrRequired);
169
+ if (!queried)
170
+ {
171
+ throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Windows activation-context run level");
172
+ }
173
+ return output;
174
+ }
175
+ finally
176
+ {
177
+ ReleaseActCtx(activationContext);
178
+ }
179
+ }
180
+ }
181
+ '@
182
+
183
+ $runLevel = [NimiWindowsExecutionProfile]::Read($env:NIMI_APP_EXECUTABLE_PATH)
184
+ if ($runLevel.Flags -ne 0 -or $runLevel.RunLevel -ne 1 -or $runLevel.UiAccess -ne 0) {
185
+ throw ('Windows executable must resolve requestedExecutionLevel=asInvoker and uiAccess=false; observed flags=' + $runLevel.Flags + ', runLevel=' + $runLevel.RunLevel + ', uiAccess=' + $runLevel.UiAccess)
186
+ }
187
+
188
+ $signature = Get-AuthenticodeSignature -LiteralPath $env:NIMI_APP_EXECUTABLE_PATH
189
+ $certificateSubject = $null
190
+ if ($null -ne $signature.SignerCertificate) {
191
+ $certificateSubject = [string]$signature.SignerCertificate.Subject
192
+ }
193
+ [pscustomobject]@{
194
+ authenticode = [pscustomobject]@{
195
+ status = [string]$signature.Status
196
+ signature_type = [string]$signature.SignatureType
197
+ certificate_subject = $certificateSubject
198
+ }
199
+ execution_profile = [pscustomobject]@{
200
+ requested_execution_level = 'asInvoker'
201
+ ui_access = $false
202
+ }
203
+ } | ConvertTo-Json -Compress -Depth 4
204
+ `;
205
+
206
+ export function observeWindowsExecutableFacts(executablePath) {
207
+ if (process.platform !== 'win32' || process.arch !== 'x64') {
208
+ throw new Error('Windows executable observation must run on windows-x86_64');
209
+ }
210
+ if (typeof executablePath !== 'string' || !path.isAbsolute(executablePath)) {
211
+ throw new Error('Windows executable observation requires an absolute path');
212
+ }
213
+ if (!existsSync(executablePath)) {
214
+ throw new Error(`Windows executable observation target is missing: ${executablePath}`);
215
+ }
216
+ const target = lstatSync(executablePath);
217
+ if (!target.isFile() || target.isSymbolicLink()) {
218
+ throw new Error(`Windows executable observation target must be a direct regular file: ${executablePath}`);
219
+ }
220
+ validateWindowsExecutablePeHeader(executablePath);
221
+
222
+ const result = spawnSync('powershell.exe', [
223
+ '-NoProfile',
224
+ '-NonInteractive',
225
+ '-Command',
226
+ WINDOWS_EXECUTABLE_FACTS_SCRIPT,
227
+ ], {
228
+ encoding: 'utf8',
229
+ env: windowsPowerShellEnv({ NIMI_APP_EXECUTABLE_PATH: executablePath }),
230
+ });
231
+ if (result.status !== 0) {
232
+ const detail = [result.error?.message, result.stdout, result.stderr].filter(Boolean).join('\n').trim();
233
+ throw new Error(`Windows executable profile verification failed${detail ? `: ${detail}` : ''}`);
234
+ }
235
+
236
+ let observed;
237
+ try {
238
+ observed = JSON.parse(String(result.stdout || '').trim());
239
+ } catch (error) {
240
+ throw new Error(`Windows executable observation returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
241
+ }
242
+ const status = observed?.authenticode?.status;
243
+ const signatureType = observed?.authenticode?.signature_type;
244
+ const certificateSubject = observed?.authenticode?.certificate_subject;
245
+ if (typeof status !== 'string' || !status || status !== status.trim()) {
246
+ throw new Error('Windows executable observation returned an invalid Authenticode status');
247
+ }
248
+ if (typeof signatureType !== 'string' || !signatureType || signatureType !== signatureType.trim()) {
249
+ throw new Error('Windows executable observation returned an invalid signature type');
250
+ }
251
+ if (certificateSubject !== null && (
252
+ typeof certificateSubject !== 'string'
253
+ || !certificateSubject
254
+ || certificateSubject !== certificateSubject.trim()
255
+ )) {
256
+ throw new Error('Windows executable observation returned an invalid certificate subject');
257
+ }
258
+ if (
259
+ observed?.execution_profile?.requested_execution_level !== 'asInvoker'
260
+ || observed?.execution_profile?.ui_access !== false
261
+ ) {
262
+ throw new Error('Windows executable observation returned an invalid execution profile');
263
+ }
264
+ return Object.freeze({
265
+ authenticode: Object.freeze({
266
+ status,
267
+ signature_type: signatureType,
268
+ certificate_subject: certificateSubject,
269
+ }),
270
+ execution_profile: Object.freeze({ requested_execution_level: 'asInvoker', ui_access: false }),
271
+ });
272
+ }