Desktop app that records your on-screen work session and uses the GitHub Copilot SDK to reconstruct it as an intent + ordered steps, then builds a reusable Skill or Automation for Microsoft Autopilots like Scout, Microsoft Copilot Cowork, or Copilot Studio.
TypeScript agent-skillsai-agentsautomationcopilotcopilot-clicopilot-coworkcopilot-studioelectronmicrosoft-scoutscreen-recording
Fix fresh Windows registry recovery and prepare 0.6.1
Giorgio Ughini6e872ef2d214
diff --git a/INSTALL.md b/INSTALL.mdindex 62bf2cd..47e56ea 100644--- a/INSTALL.md+++ b/INSTALL.md@@ -252,14 +252,40 @@ so that `replace-registry-host` maps the lockfile's canonical npmjs URLs onto thconfigured mirror. Machines with no npm configuration are unaffected and continueto use `registry.npmjs.org`.-Configure a mirror once with:+On Windows, this discovery does not require Node.js or npm to be installed.+The installer preserves an explicit `NPM_CONFIG_GLOBALCONFIG`; otherwise it+checks the system npm's reported global configuration, an explicit+`NPM_CONFIG_PREFIX` (`etc\npmrc` beneath that prefix), or the standard locations:+`%APPDATA%\npm\etc\npmrc`, then `nodejs\etc\npmrc` beneath the native, current,+and x86 Program Files directories. This includes managed configuration placed+in those locations before npm is available on PATH. Existing user `.npmrc`+and npm environment settings retain npm's normal precedence. The installer+does not modify these files.++This reads locally available settings; it does not trigger an Intune/device-policy+sync. On an unconfigured Windows machine, a public-registry network failure can+trigger one Microsoft-specific recovery attempt if local device/account metadata+provides a Microsoft Entra tenant hint. This is only a routing hint, not+authorization. The installer announces the retry, applies the registry only to+the retry process, and preserves lockfile integrity and script approvals. It+never changes saved settings or weakens TLS verification. Explicit npm+configuration, other organizations, and non-network failures do not trigger this+fallback. If recovery is unavailable or fails, the installer stops with guidance+for your organization's approved package-feed provisioning.++If npm is already on PATH, configure a mirror once with:```shnpm config set registry <url> --location=global```-The installers never pin or override the registry themselves; they only make the-machine's existing npm configuration visible to the portable runtime. The+If npm is not installed globally, the Windows installer's dependency-error+message includes a command using the exact path to its downloaded npm. That+command sets the approved registry in your user configuration; substitute the+URL supplied by your organization and follow its feed-authentication instructions.++The installers preserve existing npm configuration. The Windows recovery path+above is limited to an otherwise unconfigured public-registry failure. Thelockfile's integrity hashes are verified whichever registry serves the packages,so a mirror cannot substitute different content.diff --git a/RELEASING.md b/RELEASING.mdindex ffd2ab4..5a2bda2 100644--- a/RELEASING.md+++ b/RELEASING.md@@ -53,7 +53,10 @@ Inspect:The committed lockfile must use canonical `registry.npmjs.org` resolved URLs.Microsoft contributors may fetch through a configured internal mirror, but-internal feed URLs must never be committed. Review every new dependency install+internal feed URLs must never be committed to the lockfile or contributor+configuration. The Windows installer's narrowly gated Microsoft recovery endpoint+is an explicitly approved exception in implementation code only; do not copy it+into README examples or installation commands. Review every new dependency installscript before adding an exact-version approval; explicitly deny scripts thatare not required.diff --git a/common/microsoft-signin-hint.ts b/common/microsoft-signin-hint.tsnew file mode 100644index 0000000..5e51a08--- /dev/null+++ b/common/microsoft-signin-hint.ts@@ -0,0 +1,104 @@+import type { ExecFileOptionsWithStringEncoding } from "node:child_process";+import { win32 } from "node:path";++// Microsoft's public microsoft.com OpenID metadata, verified 2026-09-15:+// https://login.microsoftonline.com/microsoft.com/v2.0/.well-known/openid-configuration+// This is a routing hint only, never proof of identity, employment, or authorization.+const MICROSOFT_TENANT_ID = "72f988bf-86f1-41af-91ab-2d7cd011db47";+const MAX_OUTPUT_BYTES = 128 * 1024;+const TIMEOUT_MS = 3_000;++/**+ * Parse only dsregcmd's documented device/user state and associated tenant sections.+ * https://learn.microsoft.com/en-us/entra/identity/devices/troubleshoot-device-dsregcmd+ * Unknown/localized output deliberately produces no hint.+ */+export function parseMicrosoftSignInHint(output: string): boolean {+ if (Buffer.byteLength(output, "utf8") > MAX_OUTPUT_BYTES) return false;++ const sections = new Map<string, Map<string, string>>();+ let section: Map<string, string> | undefined;+ for (const line of output.split(/\r?\n/)) {+ const heading = /^\s*\|\s*([^|]+?)\s*\|\s*$/.exec(line);+ if (heading) {+ const name = heading[1].trim();+ section = undefined;+ if (!/^(Device State|User State|Tenant Details|Work Account \d+)$/.test(name)) continue;+ if (sections.has(name)) return false;+ section = new Map();+ sections.set(name, section);+ continue;+ }+ if (!section) continue;+ const field = /^\s*(AzureAdJoined|WorkplaceJoined|TenantId|WorkplaceTenantId)\s*:\s*(.*?)\s*$/.exec(line);+ if (!field) continue;+ if (section.has(field[1])) return false;+ section.set(field[1], field[2]);+ }++ const isMicrosoft = (tenant: string | undefined) =>+ tenant?.toLowerCase() === MICROSOFT_TENANT_ID;+ if (+ sections.get("Device State")?.get("AzureAdJoined") === "YES" &&+ isMicrosoft(sections.get("Tenant Details")?.get("TenantId"))+ ) return true;++ return sections.get("User State")?.get("WorkplaceJoined") === "YES" &&+ [...sections].some(([name, fields]) =>+ /^Work Account \d+$/.test(name) && isMicrosoft(fields.get("WorkplaceTenantId")),+ );+}++export interface MicrosoftSignInHintDependencies {+ platform: string;+ systemRoot: string | undefined;+ execFile: (+ file: string,+ args: string[],+ options: ExecFileOptionsWithStringEncoding,+ callback: (error: Error | null, stdout: string, stderr: string) => void,+ ) => void;+ log: { info(message: string, details: { reason: string }): void };+}++/** Injectable probe for tests; it never reads credentials or searches account stores. */+export function createMicrosoftSignInHintProbe(deps: MicrosoftSignInHintDependencies) {+ return async (): Promise<boolean> => {+ const noHint = (reason: string): false => {+ deps.log.info("Microsoft sign-in hint unavailable", { reason });+ return false;+ };+ if (deps.platform !== "win32") return noHint("unsupported-platform");++ // Never fall back to PATH, the current directory, or a relative/UNC root.+ const root = deps.systemRoot;+ if (!root || !/^[a-z]:\\/i.test(root) || /[\x00-\x1f]/.test(root) ||+ root.split(/[\\/]/).some((part) => part === "..")) {+ return noHint("unsupported-system-path");+ }++ try {+ const output = await new Promise<string>((resolve, reject) => {+ deps.execFile(win32.join(root, "System32", "dsregcmd.exe"), ["/status"], {+ encoding: "utf8",+ timeout: TIMEOUT_MS,+ maxBuffer: MAX_OUTPUT_BYTES,+ windowsHide: true,+ shell: false,+ }, (error, stdout) => {+ if (error) reject(error);+ else resolve(stdout);+ });+ });+ return parseMicrosoftSignInHint(output) || noHint("no-matching-hint");+ } catch (error) {+ // Whitelist categories only: messages/stdout/stderr can contain account/device data.+ const failure = error as { code?: unknown; killed?: unknown } | null;+ const reason = failure?.code === "ENOENT" ? "executable-missing"+ : failure?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "output-limit"+ : failure?.code === "ETIMEDOUT" || failure?.killed === true ? "timeout"+ : "probe-failed";+ return noHint(reason);+ }+ };+}diff --git a/electron/microsoft-signin-hint.ts b/electron/microsoft-signin-hint.tsindex a09d280..1c3c1c0 100644--- a/electron/microsoft-signin-hint.ts+++ b/electron/microsoft-signin-hint.ts@@ -1,108 +1,9 @@-import { execFile, type ExecFileOptionsWithStringEncoding } from "node:child_process";-import { win32 } from "node:path";+import { execFile } from "node:child_process";+import { createMicrosoftSignInHintProbe } from "../common/microsoft-signin-hint";import { createLogger } from "./logger";-// Microsoft's public microsoft.com OpenID metadata, verified 2026-09-15:-// https://login.microsoftonline.com/microsoft.com/v2.0/.well-known/openid-configuration-// This is a routing hint only, never proof of identity, employment, or authorization.-const MICROSOFT_TENANT_ID = "72f988bf-86f1-41af-91ab-2d7cd011db47";-const MAX_OUTPUT_BYTES = 128 * 1024;-const TIMEOUT_MS = 3_000;--/**- * Parse only dsregcmd's documented device/user state and associated tenant sections.- * https://learn.microsoft.com/en-us/entra/identity/devices/troubleshoot-device-dsregcmd- * Unknown/localized output deliberately produces no hint.- */-export function parseMicrosoftSignInHint(output: string): boolean {- if (Buffer.byteLength(output, "utf8") > MAX_OUTPUT_BYTES) return false;-- const sections = new Map<string, Map<string, string>>();- let section: Map<string, string> | undefined;- for (const line of output.split(/\r?\n/)) {- const heading = /^\s*\|\s*([^|]+?)\s*\|\s*$/.exec(line);- if (heading) {- const name = heading[1].trim();- section = undefined;- if (!/^(Device State|User State|Tenant Details|Work Account \d+)$/.test(name)) continue;- if (sections.has(name)) return false;- section = new Map();- sections.set(name, section);- continue;- }- if (!section) continue;- const field = /^\s*(AzureAdJoined|WorkplaceJoined|TenantId|WorkplaceTenantId)\s*:\s*(.*?)\s*$/.exec(line);- if (!field) continue;- if (section.has(field[1])) return false;- section.set(field[1], field[2]);- }-- const isMicrosoft = (tenant: string | undefined) =>- tenant?.toLowerCase() === MICROSOFT_TENANT_ID;- if (- sections.get("Device State")?.get("AzureAdJoined") === "YES" &&- isMicrosoft(sections.get("Tenant Details")?.get("TenantId"))- ) return true;-- return sections.get("User State")?.get("WorkplaceJoined") === "YES" &&- [...sections].some(([name, fields]) =>- /^Work Account \d+$/.test(name) && isMicrosoft(fields.get("WorkplaceTenantId")),- );-}--export interface MicrosoftSignInHintDependencies {- platform: string;- systemRoot: string | undefined;- execFile: (- file: string,- args: string[],- options: ExecFileOptionsWithStringEncoding,- callback: (error: Error | null, stdout: string, stderr: string) => void,- ) => void;- log: Pick<ReturnType<typeof createLogger>, "info">;-}--/** Injectable probe for tests; it never reads credentials or searches account stores. */-export function createMicrosoftSignInHintProbe(deps: MicrosoftSignInHintDependencies) {- return async (): Promise<boolean> => {- const noHint = (reason: string): false => {- deps.log.info("Microsoft sign-in hint unavailable", { reason });- return false;- };- if (deps.platform !== "win32") return noHint("unsupported-platform");-- // Never fall back to PATH, the current directory, or a relative/UNC root.- const root = deps.systemRoot;- if (!root || !/^[a-z]:\\/i.test(root) || /[\x00-\x1f]/.test(root) ||- root.split(/[\\/]/).some((part) => part === "..")) {- return noHint("unsupported-system-path");- }-- try {- const output = await new Promise<string>((resolve, reject) => {- deps.execFile(win32.join(root, "System32", "dsregcmd.exe"), ["/status"], {- encoding: "utf8",- timeout: TIMEOUT_MS,- maxBuffer: MAX_OUTPUT_BYTES,- windowsHide: true,- shell: false,- }, (error, stdout) => {- if (error) reject(error);- else resolve(stdout);- });- });- return parseMicrosoftSignInHint(output) || noHint("no-matching-hint");- } catch (error) {- // Whitelist categories only: messages/stdout/stderr can contain account/device data.- const failure = error as { code?: unknown; killed?: unknown } | null;- const reason = failure?.code === "ENOENT" ? "executable-missing"- : failure?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" ? "output-limit"- : failure?.code === "ETIMEDOUT" || failure?.killed === true ? "timeout"- : "probe-failed";- return noHint(reason);- }- };-}+export { createMicrosoftSignInHintProbe, parseMicrosoftSignInHint } from "../common/microsoft-signin-hint";+export type { MicrosoftSignInHintDependencies } from "../common/microsoft-signin-hint";export async function hasMicrosoftSignInHint(): Promise<boolean> {return createMicrosoftSignInHintProbe({diff --git a/install.ps1 b/install.ps1index 1062dd6..163e0aa 100644--- a/install.ps1+++ b/install.ps1@@ -329,6 +329,12 @@ function Get-SystemNpmGlobalConfigPath {}function Get-MachineNpmConfigPath {+ # Explicit caller configuration is already understood by portable npm. Never+ # replace it, including a missing file that npm itself must handle.+ if (-not [string]::IsNullOrWhiteSpace($env:NPM_CONFIG_GLOBALCONFIG)) {+ return $null+ }+# The portable Node.js archive ships no builtin npmrc, so npm resolves its# global config inside the throwaway runtime directory and silently ignores a# registry configured for this machine. Point npm back at the real file so@@ -339,13 +345,32 @@ function Get-MachineNpmConfigPath {if (-not [string]::IsNullOrWhiteSpace($reported)) {$candidates.Add($reported)}- if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) {- $candidates.Add((Join-Path $env:APPDATA "npm\etc\npmrc"))+ if (-not [string]::IsNullOrWhiteSpace($env:NPM_CONFIG_PREFIX)) {+ $candidates.Add((Join-Path $env:NPM_CONFIG_PREFIX "etc\npmrc"))+ # An explicit prefix must not inherit another installation's global config.+ return Resolve-MachineNpmConfigPath -CandidatePaths $candidates.ToArray()+ }++ foreach ($candidate in (Get-DefaultWindowsNpmConfigPaths)) {+ $candidates.Add($candidate)}return Resolve-MachineNpmConfigPath -CandidatePaths $candidates.ToArray()}+function Get-DefaultWindowsNpmConfigPaths {+ # Managed settings may exist at a standard prefix before npm is installed or+ # available on PATH. Probe files, not an executable or a corporate endpoint.+ if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) {+ Join-Path $env:APPDATA "npm\etc\npmrc"+ }+ foreach ($programFiles in @($env:ProgramW6432, $env:ProgramFiles, ${env:ProgramFiles(x86)})) {+ if (-not [string]::IsNullOrWhiteSpace($programFiles)) {+ Join-Path $programFiles "nodejs\etc\npmrc"+ }+ }+}+function Get-WindowsArchitecture {$architecture = [Environment]::GetEnvironmentVariable("PROCESSOR_ARCHITECTURE",@@ -672,6 +697,8 @@ if (Test-Path -LiteralPath $sourceDirectory -PathType Container) {"package.json","package-lock.json","scripts\check-lockfile-portability.mjs",+ "scripts\install-windows-dependencies.mjs",+ "common\microsoft-signin-hint.ts","scripts\install-reviewed-electron.mjs","scripts\run-reviewed-electron.mjs")@@ -732,23 +759,22 @@ if (Test-Path -LiteralPath $sourceDirectory -PathType Container) {try {Invoke-CheckedCommand `- -FilePath $runtime.Npm `+ -FilePath $runtime.Node `-Arguments @(- "ci",- "--no-audit",- "--no-fund",- "--ignore-scripts=false",- "--dangerously-allow-all-scripts=false",- "--strict-allow-scripts"+ "scripts\install-windows-dependencies.mjs",+ (Join-Path $runtime.Root "node_modules\npm\bin\npm-cli.js")) `-Description "npm ci"} catch {+ $configureRegistry = "& '$($runtime.Npm.Replace("'", "''"))' config set registry '<approved-registry-url>' --location=user"throw ("$($_.Exception.Message) Dependencies were requested from $effectiveRegistry. " +- "If your network blocks that registry, configure a compatible mirror for this " +- "machine with 'npm config set registry <url> --location=global' and run the " +- "installer again. The lockfile's integrity hashes are verified whichever " +- "registry serves the packages."+ "If your network blocks that registry, complete your organization's package-feed " ++ "provisioning and run the installer again. To configure an approved mirror manually, " ++ "use the bundled npm (no global npm installation is required): $configureRegistry . " ++ "Replace the placeholder with your organization's approved URL and complete any " ++ "required feed authentication. The lockfile's integrity hashes are verified " ++ "whichever registry serves the packages.")}diff --git a/package-lock.json b/package-lock.jsonindex b3899a0..a337b4e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "skill-recorder",- "version": "0.6.0",+ "version": "0.6.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "skill-recorder",- "version": "0.6.0",+ "version": "0.6.1","license": "MIT","dependencies": {"@github/copilot-sdk": "^1.0.6",diff --git a/package.json b/package.jsonindex 982f0e7..b4d6144 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "skill-recorder",- "version": "0.6.0",+ "version": "0.6.1","description": "Records a user's on-screen work session and derives a structured description for building AI-agent skills.","author": "Skill Recorder contributors","repository": "github:microsoft/skill-recorder",@@ -19,7 +19,7 @@"check:lockfile": "node scripts/check-lockfile-portability.mjs","typecheck": "tsc --noEmit","typecheck:evals": "tsc --noEmit -p evals/tsconfig.json",- "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test evals/builder-imports.test.ts common/architecture-registry.test.ts electron/architectures/catalogue-registry.test.ts common/audio.test.ts common/microphone.test.ts common/screen.test.ts common/narration.test.ts common/sensitive.test.ts common/skill.test.ts electron/recording-controls-bounds.test.ts electron/recorder-window-sizing.test.ts electron/recording-privacy.test.ts electron/crash-guards.test.ts electron/copilot-signin-auth.test.ts electron/copilot-signin-flow.test.ts electron/copilot-signin-process.test.ts electron/microsoft-signin-hint.test.ts src/analysis-recovery.test.ts electron/recorder/controller.test.ts electron/recorder/session-store.test.ts electron/frames/extractor.test.ts electron/pipeline.test.ts electron/narration/audio-analysis.test.ts electron/narration/analyze-gate.test.ts electron/narration/transcribe.test.ts electron/narration/whisper.test.ts electron/sensitive/scanner.test.ts electron/sensitive/secrets.test.ts electron/sensitive/tessdata-source.test.ts electron/sensitive/ocr.test.ts electron/sensitive/frame-redact.test.ts electron/sensitive/frame-heuristics.test.ts electron/terminal/terminal.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts electron/skillbuilder/plan-tools.test.ts electron/skillbuilder/placement.test.ts src/skill-placement.test.ts scripts/compliance.test.mjs",+ "test": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs --test evals/builder-imports.test.ts common/architecture-registry.test.ts electron/architectures/catalogue-registry.test.ts common/audio.test.ts common/microphone.test.ts common/screen.test.ts common/narration.test.ts common/sensitive.test.ts common/skill.test.ts electron/recording-controls-bounds.test.ts electron/recorder-window-sizing.test.ts electron/recording-privacy.test.ts electron/crash-guards.test.ts electron/copilot-signin-auth.test.ts electron/copilot-signin-flow.test.ts electron/copilot-signin-process.test.ts electron/microsoft-signin-hint.test.ts src/analysis-recovery.test.ts electron/recorder/controller.test.ts electron/recorder/session-store.test.ts electron/frames/extractor.test.ts electron/pipeline.test.ts electron/narration/audio-analysis.test.ts electron/narration/analyze-gate.test.ts electron/narration/transcribe.test.ts electron/narration/whisper.test.ts electron/sensitive/scanner.test.ts electron/sensitive/secrets.test.ts electron/sensitive/tessdata-source.test.ts electron/sensitive/ocr.test.ts electron/sensitive/frame-redact.test.ts electron/sensitive/frame-heuristics.test.ts electron/terminal/terminal.test.ts electron/sessions.test.ts electron/debug-bundle.test.ts electron/skillbuilder/plan-tools.test.ts electron/skillbuilder/placement.test.ts src/skill-placement.test.ts scripts/compliance.test.mjs scripts/install-windows-dependencies.test.mjs","eval": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/run.ts","eval:terminal": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/run.ts --only=terminal-output-required,terminal-failure-recovery,terminal-sensitive-output","eval:builder": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/builder/run.ts",diff --git a/scripts/compliance.test.mjs b/scripts/compliance.test.mjsindex 5c4f2f6..d14c99f 100644--- a/scripts/compliance.test.mjs+++ b/scripts/compliance.test.mjs@@ -939,10 +939,15 @@ test("source and release instructions remain compliance-preserving", async () =>windowsInstaller,/\(& \$nodeExe [^\r\n]+\| Select-Object -First 1\)/,);+ const dependencyInstaller = await readFile(+ path.join(repoRoot, "scripts", "install-windows-dependencies.mjs"), "utf8",+ );+ assert.match(windowsInstaller, /"scripts\\install-windows-dependencies\.mjs"/);assert.match(- windowsInstaller,+ dependencyInstaller,/"ci",\s+"--no-audit",\s+"--no-fund",\s+"--ignore-scripts=false",\s+"--dangerously-allow-all-scripts=false",\s+"--strict-allow-scripts"/,);+ assert.doesNotMatch(dependencyInstaller, /--registry|--global|--location|strict.ssl.*false|REPLACE_REGISTRY_HOST/);assert.match(windowsInstaller, /"scripts\\check-lockfile-portability\.mjs"/);assert.match(windowsInstaller, /"scripts\\install-reviewed-electron\.mjs"/);assert.doesNotMatch(windowsInstaller, /node_modules\\electron\\install\.js/);diff --git a/scripts/install-windows-dependencies.mjs b/scripts/install-windows-dependencies.mjsnew file mode 100644index 0000000..3832dee--- /dev/null+++ b/scripts/install-windows-dependencies.mjs@@ -0,0 +1,127 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Skill Recorder contributors++import { execFile, spawn } from "node:child_process";+import { statSync } from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { createMicrosoftSignInHintProbe } from "../common/microsoft-signin-hint.ts";++const microsoftRegistry = "https://packagefeedproxy.microsoft.io/npm/";+export const installArguments = [+ "ci", "--no-audit", "--no-fund", "--ignore-scripts=false",+ "--dangerously-allow-all-scripts=false", "--strict-allow-scripts",+];++function exists(file) {+ try {+ statSync(file);+ return true;+ } catch (error) {+ if (error.code === "ENOENT") return false;+ throw error;+ }+}++export function isUnconfiguredPublicRegistry(config, env, cwd, npmCli, fileExists = exists) {+ if (config.registry !== "https://registry.npmjs.org/") return false;+ // Be conservative: even an explicitly selected public registry must be honored.+ if (Object.keys(env).some((key) => /^npm_config_/i.test(key))) return false;+ if (!config.userconfig || !config.globalconfig) return false;+ if (Object.entries(config).some(([key, value]) =>+ value != null && (/:registry$/i.test(key) || /(?:_auth|_password|username)/i.test(key)),+ )) return false;+ return ![+ config.userconfig, config.globalconfig, path.join(cwd, ".npmrc"),+ path.resolve(path.dirname(npmCli), "..", "npmrc"),+ ].some(fileExists);+}++export function isPublicRegistryAccessFailure(stderr) {+ const codes = [...stderr.matchAll(/^npm (?:error|ERR!) code (\S+)\s*$/gm)].map((match) => match[1]);+ const accessCodes = new Set([+ "ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ESOCKETTIMEDOUT", "ENOTFOUND",+ "EAI_AGAIN", "ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE",+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",+ "SELF_SIGNED_CERT_IN_CHAIN", "DEPTH_ZERO_SELF_SIGNED_CERT", "CERT_HAS_EXPIRED",+ ]);+ return codes.length === 1 && accessCodes.has(codes[0]) &&+ /^npm (?:error|ERR!) (?:[^\r\n]* )?request to https:\/\/registry\.npmjs\.org\/[^\s]* failed, reason:/m.test(stderr);+}++export async function installWithRecovery({ run, eligible, microsoftHint, env, log }) {+ const first = await run(installArguments, env);+ if (first.code === 0) return;+ const initialFailure = `npm ci failed with exit code ${first.code}.`;+ if (!eligible || !isPublicRegistryAccessFailure(first.stderr) || !await microsoftHint()) {+ throw new Error(`${initialFailure} No automatic registry fallback applies; existing configuration was preserved.`);+ }++ log("Public npm registry access failed on a Microsoft-associated Windows device/account. Retrying once through Microsoft's package registry; no npm settings will be saved.");+ // Change only this child process's environment, never the caller or npmrc files.+ const retryEnv = Object.fromEntries(Object.entries(env).filter(([key]) => !/^npm_config_registry$/i.test(key)));+ retryEnv.NPM_CONFIG_REGISTRY = microsoftRegistry;+ const retry = await run(installArguments, retryEnv);+ if (retry.code !== 0) {+ throw new Error(`${initialFailure} Microsoft registry retry also failed with exit code ${retry.code}. See the errors above; complete approved feed/network provisioning before retrying.`);+ }+ log("Dependencies installed through the Microsoft registry. Persistent npm configuration is unchanged.");+}++export function runNpm(npmCli, args, env, capture = false) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [npmCli, ...args], {+ env, windowsHide: true, shell: false,+ stdio: ["ignore", capture ? "pipe" : "inherit", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ let outputLimit = false;+ child.stdout?.on("data", (chunk) => {+ stdout += chunk.toString();+ if (stdout.length > 1024 * 1024) {+ outputLimit = true;+ child.kill();+ }+ });+ child.stderr.on("data", (chunk) => {+ if (!capture) process.stderr.write(chunk);+ stderr = (stderr + chunk.toString()).slice(-64 * 1024);+ });+ child.on("error", reject);+ child.on("close", (code) => {+ if (outputLimit) reject(new Error("npm configuration output exceeded its size limit."));+ else if (code === null) reject(new Error("npm was interrupted; registry recovery was not attempted."));+ else resolve({ code, stdout, stderr });+ });+ });+}++async function main() {+ if (process.platform !== "win32") throw new Error("This dependency installer is Windows-only.");+ const npmCli = process.argv[2];+ if (!npmCli || !path.isAbsolute(npmCli)) throw new Error("An absolute bundled npm CLI path is required.");+ const env = { ...process.env };+ const result = await runNpm(npmCli, ["config", "list", "--json"], env, true);+ if (result.code !== 0) throw new Error("Could not read npm configuration; no registry fallback was attempted.");+ const config = JSON.parse(result.stdout);+ const log = (message) => console.log(`[Skill Recorder] ${message}`);+ const eligible = isUnconfiguredPublicRegistry(config, env, process.cwd(), npmCli);+ const microsoftHint = createMicrosoftSignInHintProbe({+ platform: process.platform,+ systemRoot: env.SystemRoot ?? env.windir,+ execFile,+ log: { info: (message, details) => log(`${message}: ${details.reason}`) },+ });+ await installWithRecovery({+ run: (args, childEnv) => runNpm(npmCli, args, childEnv),+ eligible, microsoftHint, env, log,+ });+}++if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {+ main().catch((error) => {+ console.error(`[Skill Recorder] ${error.message}`);+ process.exitCode = 1;+ });+}diff --git a/scripts/install-windows-dependencies.test.mjs b/scripts/install-windows-dependencies.test.mjsnew file mode 100644index 0000000..2059012--- /dev/null+++ b/scripts/install-windows-dependencies.test.mjs@@ -0,0 +1,198 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Skill Recorder contributors++import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";+import {+ installArguments, installWithRecovery, isPublicRegistryAccessFailure,+ isUnconfiguredPublicRegistry, runNpm,+} from "./install-windows-dependencies.mjs";+import { parseMicrosoftSignInHint } from "../common/microsoft-signin-hint.ts";++const accessFailure = (code = "ECONNRESET", host = "registry.npmjs.org") =>+ `npm error code ${code}\nnpm error request to https://${host}/zod/-/zod-4.4.3.tgz failed, reason: connection terminated\n`;+const config = {+ registry: "https://registry.npmjs.org/", userconfig: "user-npmrc",+ globalconfig: "global-npmrc", _auth: null,+};+const cwd = path.resolve("fixture");+const npmCli = path.join(cwd, "runtime", "node_modules", "npm", "bin", "npm-cli.js");++test("only an unconfigured public registry is eligible", () => {+ const eligible = (overrides = {}, env = {}, exists = () => false) =>+ isUnconfiguredPublicRegistry({ ...config, ...overrides }, env, cwd, npmCli, exists);+ assert.equal(eligible(), true);+ for (const registry of ["https://example.invalid/", "http://registry.npmjs.org/", "https://registry.npmjs.org.evil.invalid/"]) {+ assert.equal(eligible({ registry }), false);+ }+ for (const name of ["NPM_CONFIG_REGISTRY", "npm_config_registry", "NPM_CONFIG_USERCONFIG", "NPM_CONFIG_GLOBALCONFIG", "NPM_CONFIG_PREFIX", "npm_config_@github:registry"]) {+ assert.equal(eligible({}, { [name]: "explicit" }), false);+ }+ for (const file of [+ config.userconfig, config.globalconfig, path.join(cwd, ".npmrc"),+ path.resolve(path.dirname(npmCli), "..", "npmrc"),+ ]) {+ assert.equal(eligible({}, {}, (candidate) => candidate === file), false, file);+ }+ assert.equal(eligible({ userconfig: null }), false);+ assert.equal(eligible({ globalconfig: null }), false);+ assert.equal(eligible({ "@github:registry": "https://example.invalid/" }), false);+ assert.equal(eligible({ "//registry.npmjs.org/:_authToken": "secret" }), false);+ assert.throws(() => eligible({}, {}, () => { throw new Error("Access denied"); }), /Access denied/);+});++test("registry-access classification excludes package, build, permissions, and integrity failures", () => {+ for (const code of ["ECONNRESET", "ETIMEDOUT", "ENOTFOUND", "ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE", "SELF_SIGNED_CERT_IN_CHAIN"]) {+ assert.equal(isPublicRegistryAccessFailure(accessFailure(code)), true, code);+ }+ assert.equal(isPublicRegistryAccessFailure(accessFailure().replaceAll("npm error", "npm ERR!").replaceAll("\n", "\r\n")), true);+ for (const code of ["EINTEGRITY", "EPERM", "EACCES", "E404", "E401", "E403", "ETARGET", "1"]) {+ assert.equal(isPublicRegistryAccessFailure(accessFailure(code)), false, code);+ }+ assert.equal(isPublicRegistryAccessFailure(accessFailure("ECONNRESET", "example.invalid")), false);+ assert.equal(isPublicRegistryAccessFailure(accessFailure("ECONNRESET", "registry.npmjs.org.evil.invalid")), false);+ assert.equal(isPublicRegistryAccessFailure("ECONNRESET while building"), false);+ assert.equal(isPublicRegistryAccessFailure(accessFailure() + "npm error code EINTEGRITY\n"), false);+});++function harness({ first = { code: 1, stderr: accessFailure() }, retry = { code: 0, stderr: "" }, eligible = true, hint = true } = {}) {+ const calls = [];+ const messages = [];+ const env = Object.freeze({ PATH: "original", EXAMPLE: "preserved" });+ let hintCalls = 0;+ return {+ calls, messages, env, hints: () => hintCalls,+ execute: () => installWithRecovery({+ run: async (args, childEnv) => {+ calls.push({ args, env: childEnv });+ return calls.length === 1 ? first : retry;+ },+ eligible, env, microsoftHint: async () => { hintCalls++; return hint; },+ log: (message) => messages.push(message),+ }),+ };+}++test("public success never probes the tenant or switches registries", async () => {+ const h = harness({ first: { code: 0, stderr: "" } });+ await h.execute();+ assert.equal(h.calls.length, 1);+ assert.equal(h.hints(), 0);+ assert.equal(h.messages.length, 0);+});++test("Microsoft access failure retries exactly once with identical policy flags and a child-only override", async () => {+ const h = harness();+ await h.execute();+ assert.equal(h.calls.length, 2);+ assert.equal(h.hints(), 1);+ for (const call of h.calls) assert.deepEqual(call.args, installArguments);+ assert.equal(h.calls[0].env, h.env);+ assert.notEqual(h.calls[1].env, h.env);+ assert.equal(h.calls[1].env.PATH, h.env.PATH);+ assert.equal(h.calls[1].env.EXAMPLE, "preserved");+ assert.equal(h.calls[1].env.NPM_CONFIG_REGISTRY, "https://packagefeedproxy.microsoft.io/npm/");+ assert.equal(h.env.NPM_CONFIG_REGISTRY, undefined);+ assert.match(h.messages[0], /Retrying once/);+ assert.match(h.messages[1], /installed/);+});++test("Windows command-line entry point reads config and executes the supplied bundled npm", {+ skip: process.platform !== "win32",+}, async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "installer-entry-"));+ try {+ const cli = path.join(root, "npm fixture.cjs");+ await writeFile(cli, `+ const assert = require("node:assert/strict");+ if (process.argv[2] === "config") {+ console.log(JSON.stringify({+ registry: "https://example.invalid/",+ userconfig: ${JSON.stringify(path.join(root, "user-npmrc"))},+ globalconfig: ${JSON.stringify(path.join(root, "global-npmrc"))}+ }));+ } else {+ assert.deepEqual(process.argv.slice(2), ${JSON.stringify(installArguments)});+ console.log("fixture installation complete");+ }+ `);+ const entry = fileURLToPath(new URL("./install-windows-dependencies.mjs", import.meta.url));+ const result = await runNpm(entry, [cli], { ...process.env }, true);+ assert.equal(result.code, 0, result.stderr);+ assert.match(result.stdout, /fixture installation complete/);++ await writeFile(cli, 'console.error("configuration failure"); process.exitCode = 1;');+ const failed = await runNpm(entry, [cli], { ...process.env }, true);+ assert.equal(failed.code, 1);+ assert.match(failed.stderr, /Could not read npm configuration; no registry fallback was attempted/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("non-Microsoft, configured, and non-network failures never retry", async () => {+ for (const options of [+ { hint: false }, { eligible: false },+ { first: { code: 1, stderr: accessFailure("EINTEGRITY") } },+ ]) {+ const h = harness(options);+ await assert.rejects(h.execute(), /No automatic registry fallback applies/);+ assert.equal(h.calls.length, 1);+ if (options.hint !== false) assert.equal(h.hints(), 0);+ }+});++test("failed fallback reports both attempts without another retry or environment mutation", async () => {+ const h = harness({ retry: { code: 42, stderr: "npm error code E403\n" } });+ await assert.rejects(h.execute(), /exit code 1.*retry also failed with exit code 42/);+ assert.equal(h.calls.length, 2);+ assert.equal(h.env.NPM_CONFIG_REGISTRY, undefined);+ assert.equal(h.messages.length, 1);+});++test("installer uses the same joined/registered Microsoft tenant parser as app sign-in", () => {+ const tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";+ assert.equal(parseMicrosoftSignInHint(`| Device State |\nAzureAdJoined : YES\n| Tenant Details |\nTenantId : ${tenant}`), true);+ assert.equal(parseMicrosoftSignInHint(`| User State |\nWorkplaceJoined : YES\n| Work Account 1 |\nWorkplaceTenantId : ${tenant}`), true);+ assert.equal(parseMicrosoftSignInHint("| Device State |\nAzureAdJoined : YES\n| Tenant Details |\nTenantId : another-company"), false);+ assert.equal(parseMicrosoftSignInHint(`| Tenant Details |\nTenantId : ${tenant}`), false);+});++test("real child-process execution captures npm errors and applies the override only on retry", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "installer-npm-"));+ try {+ const cli = path.join(root, "fake-npm.cjs");+ await writeFile(cli, `+ const assert = require("node:assert/strict");+ const args = process.argv.slice(2);+ if (args[0] === "config") {+ console.log(JSON.stringify({ registry: "https://registry.npmjs.org/" }));+ } else {+ assert.deepEqual(args, ${JSON.stringify(installArguments)});+ if (!process.env.NPM_CONFIG_REGISTRY) {+ console.error(${JSON.stringify(accessFailure())});+ process.exitCode = 1;+ } else {+ assert.equal(process.env.NPM_CONFIG_STRICT_SSL, undefined);+ }+ }+ `);+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^npm_config_/i.test(key)));+ const result = await runNpm(cli, ["config", "list", "--json"], env, true);+ assert.equal(result.code, 0);+ assert.equal(JSON.parse(result.stdout).registry, config.registry);+ let attempts = 0;+ await installWithRecovery({+ run: (args, childEnv) => { attempts++; return runNpm(cli, args, childEnv); },+ eligible: true, env, microsoftHint: async () => true, log: () => {},+ });+ assert.equal(attempts, 2);+ assert.equal(env.NPM_CONFIG_REGISTRY, undefined);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/scripts/install-windows.test.ps1 b/scripts/install-windows.test.ps1index de7f053..f4092e2 100644--- a/scripts/install-windows.test.ps1+++ b/scripts/install-windows.test.ps1@@ -7,6 +7,8 @@ param(Set-StrictMode -Version Latest$ErrorActionPreference = "Stop"+$npmCommand = Get-Command npm.cmd -CommandType Application -ErrorAction SilentlyContinue |+ Select-Object -First 1$tokens = $null$parseErrors = $null@@ -24,7 +26,10 @@ $helperNames = @("ConvertTo-ExtendedLengthPath","Move-DirectoryTree","Remove-DirectoryTree",- "Resolve-MachineNpmConfigPath"+ "Resolve-MachineNpmConfigPath",+ "Get-SystemNpmGlobalConfigPath",+ "Get-DefaultWindowsNpmConfigPaths",+ "Get-MachineNpmConfigPath")$functionDefinitions = @($installerAst.FindAll(@@ -81,6 +86,109 @@ try {if ($quoted -ne [IO.Path]::GetFullPath($machineNpmrc)) {throw "Resolve-MachineNpmConfigPath did not normalize a quoted npm path: $quoted"}++ # Isolate discovery from the test host's npm installation and configuration.+ & {+ $environmentNames = @(+ "APPDATA", "ProgramW6432", "ProgramFiles", "ProgramFiles(x86)",+ "NPM_CONFIG_GLOBALCONFIG", "NPM_CONFIG_PREFIX", "NPM_CONFIG_USERCONFIG",+ "NPM_CONFIG_REGISTRY"+ )+ $savedEnvironment = @{}+ foreach ($name in $environmentNames) {+ $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, "Process")+ [Environment]::SetEnvironmentVariable($name, $null, "Process")+ }+ function Get-Command { return $null }+ try {+ $env:APPDATA = Join-Path $npmConfigRoot "appdata"+ $env:ProgramW6432 = Join-Path $npmConfigRoot "native-program-files"+ $env:ProgramFiles = Join-Path $npmConfigRoot "program-files"+ ${env:ProgramFiles(x86)} = Join-Path $npmConfigRoot "x86-program-files"++ if ($null -ne (Get-SystemNpmGlobalConfigPath)) {+ throw "Discovery unexpectedly found npm on the clean-machine fixture."+ }+ if ($null -ne (Get-MachineNpmConfigPath)) {+ throw "A clean noncorporate machine must retain npm's default registry."+ }++ $paths = @(Get-DefaultWindowsNpmConfigPaths)+ if ($paths.Count -ne 4) {+ throw "Expected the user, native, current, and x86 global config locations."+ }+ # Create the lowest-priority files first to exercise every fallback.+ for ($index = $paths.Count - 1; $index -ge 0; $index--) {+ $path = $paths[$index]+ New-Item -ItemType Directory -Path (Split-Path -Parent $path) -Force | Out-Null+ Set-Content -LiteralPath $path -Value "registry=https://example.invalid/npm/" -Encoding ASCII+ if ((Get-MachineNpmConfigPath) -ne $path) {+ throw "npm-free discovery did not select $path."+ }+ }++ $env:NPM_CONFIG_PREFIX = Join-Path $npmConfigRoot "explicit-prefix"+ if ($null -ne (Get-MachineNpmConfigPath)) {+ throw "A caller's empty prefix must not pick up another installation's settings."+ }+ $prefixConfig = Join-Path $env:NPM_CONFIG_PREFIX "etc\npmrc"+ New-Item -ItemType Directory -Path (Split-Path -Parent $prefixConfig) -Force | Out-Null+ Set-Content -LiteralPath $prefixConfig -Value "registry=https://example.invalid/custom/" -Encoding ASCII+ if ((Get-MachineNpmConfigPath) -ne $prefixConfig) {+ throw "The explicit npm prefix was not honored without npm."+ }+ $env:NPM_CONFIG_PREFIX = $null++ foreach ($explicitConfig in @($machineNpmrc, $missingNpmrc)) {+ $env:NPM_CONFIG_GLOBALCONFIG = $explicitConfig+ if ($null -ne (Get-MachineNpmConfigPath)) {+ throw "Discovery must leave explicit globalconfig to npm, even if missing."+ }+ if ($env:NPM_CONFIG_GLOBALCONFIG -ne $explicitConfig) {+ throw "Discovery modified the caller's globalconfig."+ }+ }+ $env:NPM_CONFIG_GLOBALCONFIG = $null++ function Get-SystemNpmGlobalConfigPath { return $machineNpmrc }+ if ((Get-MachineNpmConfigPath) -ne $machineNpmrc) {+ throw "The system npm's reported global configuration must take precedence."+ }++ if ($npmCommand) {+ $env:NPM_CONFIG_GLOBALCONFIG = Get-MachineNpmConfigPath+ $env:NPM_CONFIG_USERCONFIG = Join-Path $npmConfigRoot "user.npmrc"+ $originalHash = (Get-FileHash -LiteralPath $machineNpmrc).Hash+ Push-Location $npmConfigRoot+ try {+ function Assert-NpmRegistry {+ param([string]$Expected)+ $actual = @(& $npmCommand.Source config get registry 2>$null)+ if ($LASTEXITCODE -ne 0 -or $actual.Count -ne 1 -or $actual[0] -ne $Expected) {+ throw "npm did not honor the expected registry precedence."+ }+ }+ Assert-NpmRegistry "https://example.invalid/npm/"+ Set-Content -LiteralPath $env:NPM_CONFIG_USERCONFIG `+ -Value "registry=https://example.invalid/user/" -Encoding ASCII+ Assert-NpmRegistry "https://example.invalid/user/"+ $env:NPM_CONFIG_REGISTRY = "https://example.invalid/environment/"+ Assert-NpmRegistry "https://example.invalid/environment/"+ if ((Get-FileHash -LiteralPath $machineNpmrc).Hash -ne $originalHash) {+ throw "Reading npm settings modified the managed global configuration."+ }+ } finally {+ Pop-Location+ }+ } else {+ Write-Warning "npm is unavailable; skipping the real-npm precedence check (npm-free discovery was tested)."+ }+ } finally {+ foreach ($name in $environmentNames) {+ [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name], "Process")+ }+ }+ }} finally {Remove-Item -LiteralPath $npmConfigRoot -Recurse -Force}