@xkwdstore/agent 2.0.2 → 2.0.4

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,77 +1,77 @@
1
- 'use strict';
2
-
3
- /**
4
- * Pure, side-effect-free proxy launch policy.
5
- *
6
- * Extracted from startSession() so the fail-closed proxy routing decision can
7
- * be unit-tested without Playwright/Chrome. The agent calls decideProxyLaunch()
8
- * with the configured proxy string, the network mode, and the proxy health
9
- * result, then acts on the returned decision.
10
- *
11
- * FAIL-CLOSED RULES (Phase 2):
12
- * - A proxy was provided → it MUST be reachable, or the launch ABORTS.
13
- * We never silently fall back to a direct
14
- * connection (that would leak the real IP for an
15
- * account configured to use a proxy).
16
- * - No proxy + proxy_required → ABORT. Do not open a direct browser.
17
- * - No proxy + direct_allowed → launch direct (the user opted out of proxy).
18
- * - Malformed proxy string → ABORT (treat as unreachable).
19
- */
20
-
21
- /**
22
- * @param {object} opts
23
- * @param {string|null|undefined} opts.proxyStr - raw proxy string (host:port[:user:pass]) or empty
24
- * @param {string} [opts.networkMode] - 'proxy_required' | 'direct_allowed'. REQUIRED — a
25
- * missing/unknown mode FAILS CLOSED (abort); the agent never coerces an
26
- * unknown mode to 'direct_allowed' (that would leak the real IP). The backend
27
- * persists an explicit mode per account (default 'proxy_required').
28
- * @param {{ok:boolean, reason?:string}|null|undefined} opts.health - checkProxyHealth result
29
- * (null/undefined when no proxy was configured or it could not be parsed)
30
- * @returns {{action:'launch'|'abort', useProxy:boolean, reason:string, error?:string}}
31
- */
32
- function decideProxyLaunch({ proxyStr, networkMode, health } = {}) {
33
- // Phase 16: a missing/unknown network mode FAILS CLOSED. The agent never
34
- // coerces an unknown mode to 'direct_allowed' — the safe default is to refuse
35
- // the launch rather than risk a direct (real-IP) connection. The backend
36
- // persists an explicit mode per account, so receiving none/unknown here is a
37
- // contract violation, not a backward-compatible default.
38
- const mode = networkMode === 'proxy_required' ? 'proxy_required'
39
- : networkMode === 'direct_allowed' ? 'direct_allowed'
40
- : null;
41
- if (mode === null) {
42
- return {
43
- action: 'abort',
44
- useProxy: false,
45
- reason: 'network_mode_required',
46
- error: 'Account network mode is missing or unknown; refusing to launch without an explicit proxy policy.',
47
- };
48
- }
49
- const hasProxy = !!(proxyStr && String(proxyStr).trim());
50
-
51
- if (hasProxy) {
52
- // A proxy was configured — it must be reachable or we abort. Never fall
53
- // open to direct.
54
- if (!health || !health.ok) {
55
- return {
56
- action: 'abort',
57
- useProxy: true,
58
- reason: 'proxy_unreachable',
59
- error: 'Proxy is not reachable. Check the proxy credentials/host or try again.',
60
- };
61
- }
62
- return { action: 'launch', useProxy: true, reason: 'proxy_ok' };
63
- }
64
-
65
- // No proxy configured.
66
- if (mode === 'proxy_required') {
67
- return {
68
- action: 'abort',
69
- useProxy: false,
70
- reason: 'proxy_required_missing',
71
- error: 'A proxy is required for this account but none is configured. Assign a proxy before launching.',
72
- };
73
- }
74
- return { action: 'launch', useProxy: false, reason: 'direct_allowed' };
75
- }
76
-
1
+ 'use strict';
2
+
3
+ /**
4
+ * Pure, side-effect-free proxy launch policy.
5
+ *
6
+ * Extracted from startSession() so the fail-closed proxy routing decision can
7
+ * be unit-tested without Playwright/Chrome. The agent calls decideProxyLaunch()
8
+ * with the configured proxy string, the network mode, and the proxy health
9
+ * result, then acts on the returned decision.
10
+ *
11
+ * FAIL-CLOSED RULES (Phase 2):
12
+ * - A proxy was provided → it MUST be reachable, or the launch ABORTS.
13
+ * We never silently fall back to a direct
14
+ * connection (that would leak the real IP for an
15
+ * account configured to use a proxy).
16
+ * - No proxy + proxy_required → ABORT. Do not open a direct browser.
17
+ * - No proxy + direct_allowed → launch direct (the user opted out of proxy).
18
+ * - Malformed proxy string → ABORT (treat as unreachable).
19
+ */
20
+
21
+ /**
22
+ * @param {object} opts
23
+ * @param {string|null|undefined} opts.proxyStr - raw proxy string (host:port[:user:pass]) or empty
24
+ * @param {string} [opts.networkMode] - 'proxy_required' | 'direct_allowed'. REQUIRED — a
25
+ * missing/unknown mode FAILS CLOSED (abort); the agent never coerces an
26
+ * unknown mode to 'direct_allowed' (that would leak the real IP). The backend
27
+ * persists an explicit mode per account (default 'proxy_required').
28
+ * @param {{ok:boolean, reason?:string}|null|undefined} opts.health - checkProxyHealth result
29
+ * (null/undefined when no proxy was configured or it could not be parsed)
30
+ * @returns {{action:'launch'|'abort', useProxy:boolean, reason:string, error?:string}}
31
+ */
32
+ function decideProxyLaunch({ proxyStr, networkMode, health } = {}) {
33
+ // Phase 16: a missing/unknown network mode FAILS CLOSED. The agent never
34
+ // coerces an unknown mode to 'direct_allowed' — the safe default is to refuse
35
+ // the launch rather than risk a direct (real-IP) connection. The backend
36
+ // persists an explicit mode per account, so receiving none/unknown here is a
37
+ // contract violation, not a backward-compatible default.
38
+ const mode = networkMode === 'proxy_required' ? 'proxy_required'
39
+ : networkMode === 'direct_allowed' ? 'direct_allowed'
40
+ : null;
41
+ if (mode === null) {
42
+ return {
43
+ action: 'abort',
44
+ useProxy: false,
45
+ reason: 'network_mode_required',
46
+ error: 'Account network mode is missing or unknown; refusing to launch without an explicit proxy policy.',
47
+ };
48
+ }
49
+ const hasProxy = !!(proxyStr && String(proxyStr).trim());
50
+
51
+ if (hasProxy) {
52
+ // A proxy was configured — it must be reachable or we abort. Never fall
53
+ // open to direct.
54
+ if (!health || !health.ok) {
55
+ return {
56
+ action: 'abort',
57
+ useProxy: true,
58
+ reason: 'proxy_unreachable',
59
+ error: 'Proxy is not reachable. Check the proxy credentials/host or try again.',
60
+ };
61
+ }
62
+ return { action: 'launch', useProxy: true, reason: 'proxy_ok' };
63
+ }
64
+
65
+ // No proxy configured.
66
+ if (mode === 'proxy_required') {
67
+ return {
68
+ action: 'abort',
69
+ useProxy: false,
70
+ reason: 'proxy_required_missing',
71
+ error: 'A proxy is required for this account but none is configured. Assign a proxy before launching.',
72
+ };
73
+ }
74
+ return { action: 'launch', useProxy: false, reason: 'direct_allowed' };
75
+ }
76
+
77
77
  module.exports = { decideProxyLaunch };
@@ -1,133 +1,133 @@
1
- 'use strict';
2
-
3
- /**
4
- * Protect a plaintext secret at rest (Phase 11).
5
- *
6
- * The local agent persists its long-lived device credential (a 365-day JWT) to
7
- * config.json on the customer's PC. Storing it in plaintext means anyone who
8
- * can read that file (a malicious process running as the same or a more
9
- * privileged user, a copied disk image, a backup) can impersonate the device
10
- * for a year. protectSecret wraps it so the on-disk form is not directly usable.
11
- *
12
- * On Windows, the agent uses DPAPI (CryptProtectData, current-user scope) via
13
- * PowerShell — no native dependency to build or ship, and the protected blob is
14
- * decryptable only by the same Windows user account on the same machine. On
15
- * non-Windows (development / CI), DPAPI is unavailable, so we fall back to a
16
- * plaintext envelope with a warning. The plaintext fallback is gated: it is
17
- * only used when DPAPI cannot be reached, and it is clearly marked in the
18
- * envelope so callers can refuse/warn. Production deployments run on Windows.
19
- *
20
- * Envelope shape: { scheme: 'dpapi' | 'plaintext', value: <string>, v: 1 }
21
- */
22
-
23
- const { execFileSync } = require('child_process');
24
- const os = require('os');
25
- const path = require('path');
26
-
27
- const isWindows = os.platform() === 'win32';
28
- const PS_TIMEOUT_MS = 15000;
29
-
30
- /**
31
- * Absolute path to Windows PowerShell 5.1 — never bare `powershell`/`pwsh`.
32
- * Mirrors deviceKeyStore._powershellExe() so DPAPI behaves identically.
33
- */
34
- function _powershellExe() {
35
- if (!isWindows) return 'powershell.exe';
36
- const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
37
- return path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
38
- }
39
-
40
- /**
41
- * Protect `plaintext` with DPAPI (current-user scope) via the .NET ProtectedData
42
- * API through PowerShell. Returns the protected blob as a base64 string. Throws
43
- * if PowerShell / the System.Security assembly is unavailable — callers catch
44
- * and fall back. We use ProtectedData directly (rather than ConvertTo/From-
45
- * SecureString) because the SecureString cmdlets live in Microsoft.PowerShell.
46
- * Security, whose auto-load is unreliable under -NoProfile on some installs.
47
- */
48
- function dpApiProtect(plaintext) {
49
- // Base64-encode the secret so it can be embedded in the PowerShell command
50
- // without quoting/escaping issues.
51
- const b64 = Buffer.from(plaintext, 'utf8').toString('base64');
52
- const ps =
53
- "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
54
- "Add-Type -AssemblyName System.Security; " +
55
- "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
56
- "[Convert]::FromBase64String('" + b64 + "'), " +
57
- "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
58
- "[Console]::Out.Write([Convert]::ToBase64String($b))";
59
- return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], {
60
- windowsHide: true,
61
- encoding: 'utf8',
62
- timeout: PS_TIMEOUT_MS,
63
- }).trim();
64
- }
65
-
66
- /**
67
- * Reverse dpApiProtect. `blob` is the base64 string returned by dpApiProtect.
68
- * Returns the plaintext. Throws on any failure.
69
- */
70
- function dpApiUnprotect(blob) {
71
- const ps =
72
- "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
73
- "Add-Type -AssemblyName System.Security; " +
74
- "$b = [Convert]::FromBase64String('" + String(blob) + "'); " +
75
- "$p = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
76
- "$b, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
77
- "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($p))";
78
- return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], {
79
- windowsHide: true,
80
- encoding: 'utf8',
81
- timeout: PS_TIMEOUT_MS,
82
- });
83
- }
84
-
85
- /**
86
- * Wrap a plaintext secret for at-rest storage. Returns an envelope. Always
87
- * resolves (never throws): DPAPI failure falls back to a plaintext envelope.
88
- */
89
- function protectSecret(plaintext) {
90
- if (plaintext == null) return null;
91
- if (isWindows) {
92
- try {
93
- return { scheme: 'dpapi', value: dpApiProtect(plaintext), v: 1 };
94
- } catch (err) {
95
- console.warn('[secretStore] DPAPI protection failed; falling back to plaintext: ' + (err && err.message));
96
- }
97
- } else if (typeof console !== 'undefined' && console.warn) {
98
- // Non-Windows: DPAPI is not available. Plaintext fallback is intentional for
99
- // dev/CI; production agents run on Windows where DPAPI is used.
100
- console.warn('[secretStore] non-Windows host: device token stored as plaintext (no DPAPI).');
101
- }
102
- return { scheme: 'plaintext', value: plaintext, v: 1 };
103
- }
104
-
105
- /**
106
- * Unwrap an envelope (or a legacy plaintext string) back to plaintext. Returns
107
- * null for a missing/unknown envelope (fail closed — never return an empty
108
- * secret that could mask a missing one).
109
- */
110
- function unprotectSecret(envelope) {
111
- if (envelope == null) return null;
112
- // Legacy pre-Phase-11 config stored the raw plaintext token string.
113
- if (typeof envelope === 'string') return envelope;
114
- if (typeof envelope !== 'object') return null;
115
- if (envelope.scheme === 'plaintext') return envelope.value != null ? String(envelope.value) : null;
116
- if (envelope.scheme === 'dpapi') {
117
- try { return dpApiUnprotect(envelope.value); }
118
- catch (err) {
119
- console.error('[secretStore] DPAPI unprotect failed: ' + (err && err.message));
120
- return null;
121
- }
122
- }
123
- // Unknown scheme — fail closed.
124
- return null;
125
- }
126
-
127
- module.exports = {
128
- protectSecret,
129
- unprotectSecret,
130
- // Exposed for testing on Windows only (no-op guard on non-Windows).
131
- _dpApiAvailable: isWindows,
132
- _powershellExe,
1
+ 'use strict';
2
+
3
+ /**
4
+ * Protect a plaintext secret at rest (Phase 11).
5
+ *
6
+ * The local agent persists its long-lived device credential (a 365-day JWT) to
7
+ * config.json on the customer's PC. Storing it in plaintext means anyone who
8
+ * can read that file (a malicious process running as the same or a more
9
+ * privileged user, a copied disk image, a backup) can impersonate the device
10
+ * for a year. protectSecret wraps it so the on-disk form is not directly usable.
11
+ *
12
+ * On Windows, the agent uses DPAPI (CryptProtectData, current-user scope) via
13
+ * PowerShell — no native dependency to build or ship, and the protected blob is
14
+ * decryptable only by the same Windows user account on the same machine. On
15
+ * non-Windows (development / CI), DPAPI is unavailable, so we fall back to a
16
+ * plaintext envelope with a warning. The plaintext fallback is gated: it is
17
+ * only used when DPAPI cannot be reached, and it is clearly marked in the
18
+ * envelope so callers can refuse/warn. Production deployments run on Windows.
19
+ *
20
+ * Envelope shape: { scheme: 'dpapi' | 'plaintext', value: <string>, v: 1 }
21
+ */
22
+
23
+ const { execFileSync } = require('child_process');
24
+ const os = require('os');
25
+ const path = require('path');
26
+
27
+ const isWindows = os.platform() === 'win32';
28
+ const PS_TIMEOUT_MS = 15000;
29
+
30
+ /**
31
+ * Absolute path to Windows PowerShell 5.1 — never bare `powershell`/`pwsh`.
32
+ * Mirrors deviceKeyStore._powershellExe() so DPAPI behaves identically.
33
+ */
34
+ function _powershellExe() {
35
+ if (!isWindows) return 'powershell.exe';
36
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
37
+ return path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
38
+ }
39
+
40
+ /**
41
+ * Protect `plaintext` with DPAPI (current-user scope) via the .NET ProtectedData
42
+ * API through PowerShell. Returns the protected blob as a base64 string. Throws
43
+ * if PowerShell / the System.Security assembly is unavailable — callers catch
44
+ * and fall back. We use ProtectedData directly (rather than ConvertTo/From-
45
+ * SecureString) because the SecureString cmdlets live in Microsoft.PowerShell.
46
+ * Security, whose auto-load is unreliable under -NoProfile on some installs.
47
+ */
48
+ function dpApiProtect(plaintext) {
49
+ // Base64-encode the secret so it can be embedded in the PowerShell command
50
+ // without quoting/escaping issues.
51
+ const b64 = Buffer.from(plaintext, 'utf8').toString('base64');
52
+ const ps =
53
+ "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
54
+ "Add-Type -AssemblyName System.Security; " +
55
+ "$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
56
+ "[Convert]::FromBase64String('" + b64 + "'), " +
57
+ "$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
58
+ "[Console]::Out.Write([Convert]::ToBase64String($b))";
59
+ return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], {
60
+ windowsHide: true,
61
+ encoding: 'utf8',
62
+ timeout: PS_TIMEOUT_MS,
63
+ }).trim();
64
+ }
65
+
66
+ /**
67
+ * Reverse dpApiProtect. `blob` is the base64 string returned by dpApiProtect.
68
+ * Returns the plaintext. Throws on any failure.
69
+ */
70
+ function dpApiUnprotect(blob) {
71
+ const ps =
72
+ "[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
73
+ "Add-Type -AssemblyName System.Security; " +
74
+ "$b = [Convert]::FromBase64String('" + String(blob) + "'); " +
75
+ "$p = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
76
+ "$b, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
77
+ "[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($p))";
78
+ return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], {
79
+ windowsHide: true,
80
+ encoding: 'utf8',
81
+ timeout: PS_TIMEOUT_MS,
82
+ });
83
+ }
84
+
85
+ /**
86
+ * Wrap a plaintext secret for at-rest storage. Returns an envelope. Always
87
+ * resolves (never throws): DPAPI failure falls back to a plaintext envelope.
88
+ */
89
+ function protectSecret(plaintext) {
90
+ if (plaintext == null) return null;
91
+ if (isWindows) {
92
+ try {
93
+ return { scheme: 'dpapi', value: dpApiProtect(plaintext), v: 1 };
94
+ } catch (err) {
95
+ console.warn('[secretStore] DPAPI protection failed; falling back to plaintext: ' + (err && err.message));
96
+ }
97
+ } else if (typeof console !== 'undefined' && console.warn) {
98
+ // Non-Windows: DPAPI is not available. Plaintext fallback is intentional for
99
+ // dev/CI; production agents run on Windows where DPAPI is used.
100
+ console.warn('[secretStore] non-Windows host: device token stored as plaintext (no DPAPI).');
101
+ }
102
+ return { scheme: 'plaintext', value: plaintext, v: 1 };
103
+ }
104
+
105
+ /**
106
+ * Unwrap an envelope (or a legacy plaintext string) back to plaintext. Returns
107
+ * null for a missing/unknown envelope (fail closed — never return an empty
108
+ * secret that could mask a missing one).
109
+ */
110
+ function unprotectSecret(envelope) {
111
+ if (envelope == null) return null;
112
+ // Legacy pre-Phase-11 config stored the raw plaintext token string.
113
+ if (typeof envelope === 'string') return envelope;
114
+ if (typeof envelope !== 'object') return null;
115
+ if (envelope.scheme === 'plaintext') return envelope.value != null ? String(envelope.value) : null;
116
+ if (envelope.scheme === 'dpapi') {
117
+ try { return dpApiUnprotect(envelope.value); }
118
+ catch (err) {
119
+ console.error('[secretStore] DPAPI unprotect failed: ' + (err && err.message));
120
+ return null;
121
+ }
122
+ }
123
+ // Unknown scheme — fail closed.
124
+ return null;
125
+ }
126
+
127
+ module.exports = {
128
+ protectSecret,
129
+ unprotectSecret,
130
+ // Exposed for testing on Windows only (no-op guard on non-Windows).
131
+ _dpApiAvailable: isWindows,
132
+ _powershellExe,
133
133
  };