vigievuln 1.0.0 → 1.1.0

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +48 -6
  3. package/completions/vigievuln.bash +4 -1
  4. package/completions/vigievuln.zsh +3 -0
  5. package/lib/account-client.js +165 -0
  6. package/lib/account-session.js +436 -0
  7. package/lib/application-plugins/runner.js +73 -13
  8. package/lib/application-plugins/wordpress.js +10 -3
  9. package/lib/application-providers/live-snapshot.js +6 -1
  10. package/lib/application-providers/wordfence-client.js +70 -0
  11. package/lib/application-providers/wordfence-projection.js +76 -0
  12. package/lib/application-providers/wordfence-v3.js +22 -6
  13. package/lib/certfr.js +17 -2
  14. package/lib/cli-command-routing.js +49 -0
  15. package/lib/cli-project-commands.js +85 -0
  16. package/lib/cli-watch.js +110 -0
  17. package/lib/cms-snapshot-warm.js +11 -4
  18. package/lib/codecs/composer/registry.js +2 -2
  19. package/lib/codecs/composer/relations.js +18 -0
  20. package/lib/codecs/composer.codec.js +2 -0
  21. package/lib/codecs/go/parse.js +23 -9
  22. package/lib/codecs/go/registry.js +2 -2
  23. package/lib/codecs/go.codec.js +20 -3
  24. package/lib/codecs/maven.codec.js +20 -1
  25. package/lib/codecs/npm/collect.js +90 -6
  26. package/lib/codecs/npm/registry.js +2 -2
  27. package/lib/codecs/nuget/parse.js +5 -1
  28. package/lib/codecs/nuget/registry.js +2 -2
  29. package/lib/codecs/nuget.codec.js +2 -12
  30. package/lib/codecs/pypi/registry.js +2 -2
  31. package/lib/codecs/ruby/parse.js +3 -0
  32. package/lib/codecs/ruby/registry.js +2 -2
  33. package/lib/codecs/ruby/relations.js +62 -0
  34. package/lib/codecs/ruby.codec.js +4 -1
  35. package/lib/codecs/version-evidence.js +18 -0
  36. package/lib/cve-match.js +4 -0
  37. package/lib/deps-descriptor.js +1 -1
  38. package/lib/epss.js +6 -2
  39. package/lib/euvd.js +20 -2
  40. package/lib/hosted-proxy.js +49 -0
  41. package/lib/kev.js +17 -1
  42. package/lib/nvd.js +4 -4
  43. package/lib/osv-db.js +1 -0
  44. package/lib/osv.js +3 -2
  45. package/lib/outdated.js +6 -5
  46. package/lib/packagist-audit.js +3 -3
  47. package/lib/project-client.js +121 -0
  48. package/lib/project-descriptor.js +30 -0
  49. package/lib/providers/certfr.js +1 -0
  50. package/lib/providers/euvd.js +1 -0
  51. package/lib/providers/github.js +1 -0
  52. package/lib/providers/index.js +15 -5
  53. package/lib/providers/kev.js +1 -1
  54. package/lib/providers/wordfence.js +5 -1
  55. package/lib/resource-cache/engine.js +149 -20
  56. package/lib/resource-cache/validate.js +10 -3
  57. package/lib/resource-cache/wordfence.js +77 -0
  58. package/lib/retire.js +29 -14
  59. package/lib/source-health.js +6 -0
  60. package/lib/transitive.js +1 -1
  61. package/package.json +1 -1
  62. package/vigievuln.js +158 -52
@@ -0,0 +1,436 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { randomUUID } = require('node:crypto');
7
+ const { spawnSync } = require('node:child_process');
8
+
9
+ class AccountSessionError extends Error {
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.name = 'AccountSessionError';
13
+ this.code = code;
14
+ }
15
+ }
16
+
17
+ // The account API uses epoch milliseconds. Never persist credentials or the
18
+ // entire login response: the only permitted fields are token and expiresAt.
19
+ function validateAccountSession(value, now = Date.now()) {
20
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
21
+ typeof value.token !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(value.token) ||
22
+ !Number.isSafeInteger(value.expiresAt) || value.expiresAt <= 0) {
23
+ throw new AccountSessionError('INVALID_SESSION', 'Invalid account session. Sign in again.');
24
+ }
25
+ if (value.expiresAt <= now) {
26
+ throw new AccountSessionError('SESSION_EXPIRED', 'Account session expired. Sign in again.');
27
+ }
28
+ return { token: value.token, expiresAt: value.expiresAt };
29
+ }
30
+
31
+ /**
32
+ * Synchronous, small private credential store, separate from ~/.fad-checker.
33
+ * Options are trusted injection points for local tests, not CLI input.
34
+ * Windows uses the native helper below; POSIX retains its permission checks.
35
+ * The home directory and its ancestors must be trusted. Atomic replacement
36
+ * prevents partial reads, but does not provide cross-process session locking.
37
+ */
38
+ function createAccountSessionStore({ homeDir = os.homedir(), fsImpl = fs, now = Date.now,
39
+ platform = process.platform, spawnSyncImpl = spawnSync, windowsRoot = process.env.SystemRoot } = {}) {
40
+ if (platform === 'win32') return createWindowsSessionStore({ homeDir, now, spawnSyncImpl, windowsRoot });
41
+ const directory = path.join(path.resolve(homeDir), '.vigievuln');
42
+ const filePath = path.join(directory, 'account-session.json');
43
+ const unsafe = () => new AccountSessionError('UNSAFE_SESSION_FILE', 'Account session storage must be private, owned by the current user and free of links.');
44
+
45
+ function check(stat, isDirectory) {
46
+ if (typeof process.getuid !== 'function' || stat.uid !== process.getuid() ||
47
+ (stat.mode & 0o7777) !== (isDirectory ? 0o700 : 0o600) ||
48
+ (isDirectory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1)) throw unsafe();
49
+ }
50
+
51
+ function checkDirectory(create = false) {
52
+ if (create) {
53
+ try { fsImpl.mkdirSync(directory, { mode: 0o700 }); }
54
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
55
+ }
56
+ try { check(fsImpl.lstatSync(directory), true); return true; }
57
+ catch (error) { if (error.code === 'ENOENT' && !create) return false; throw error; }
58
+ }
59
+
60
+ function checkFile() {
61
+ try { check(fsImpl.lstatSync(filePath), false); return true; }
62
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
63
+ }
64
+
65
+ // Do not leak contents, paths or injected filesystem error messages.
66
+ function guarded(operation) {
67
+ try { return operation(); }
68
+ catch (error) {
69
+ if (error instanceof AccountSessionError) throw error;
70
+ throw new AccountSessionError('SESSION_IO', 'Unable to access private account session storage.');
71
+ }
72
+ }
73
+
74
+ function clear() {
75
+ return guarded(() => {
76
+ if (!checkDirectory() || !checkFile()) return;
77
+ fsImpl.unlinkSync(filePath);
78
+ });
79
+ }
80
+
81
+ function read() {
82
+ return guarded(() => {
83
+ if (!checkDirectory() || !checkFile()) return null;
84
+ let fd;
85
+ let value;
86
+ try {
87
+ fd = fsImpl.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
88
+ const stat = fsImpl.fstatSync(fd);
89
+ check(stat, false);
90
+ if (stat.size > 4096) throw new AccountSessionError('INVALID_SESSION', 'Invalid account session file. Sign in again.');
91
+ // A bounded read also handles a file growing after fstat.
92
+ const buffer = Buffer.alloc(4097);
93
+ let length = 0;
94
+ let count;
95
+ do {
96
+ count = fsImpl.readSync(fd, buffer, length, buffer.length - length, null);
97
+ length += count;
98
+ } while (count && length < buffer.length);
99
+ if (length > 4096) throw new AccountSessionError('INVALID_SESSION', 'Invalid account session file. Sign in again.');
100
+ try { value = JSON.parse(buffer.toString('utf8', 0, length)); }
101
+ catch { throw new AccountSessionError('INVALID_SESSION', 'Invalid account session file. Sign in again.'); }
102
+ } finally { if (fd !== undefined) fsImpl.closeSync(fd); }
103
+ try { return validateAccountSession(value, now()); }
104
+ catch (error) {
105
+ if (error.code !== 'SESSION_EXPIRED') throw error;
106
+ clear();
107
+ return null;
108
+ }
109
+ });
110
+ }
111
+
112
+ function write(value) {
113
+ return guarded(() => {
114
+ const session = validateAccountSession(value, now());
115
+ checkDirectory(true);
116
+ checkFile();
117
+ const temporary = path.join(directory, `.account-session-${randomUUID()}.tmp`);
118
+ let fd;
119
+ let created = false;
120
+ try {
121
+ fd = fsImpl.openSync(temporary, 'wx', 0o600);
122
+ created = true;
123
+ fsImpl.fchmodSync(fd, 0o600);
124
+ check(fsImpl.fstatSync(fd), false);
125
+ fsImpl.writeFileSync(fd, JSON.stringify(session) + '\n', 'utf8');
126
+ fsImpl.fsyncSync(fd);
127
+ fsImpl.closeSync(fd);
128
+ fd = undefined;
129
+ checkDirectory();
130
+ checkFile();
131
+ fsImpl.renameSync(temporary, filePath);
132
+ } finally {
133
+ try { if (fd !== undefined) fsImpl.closeSync(fd); }
134
+ finally {
135
+ if (created) {
136
+ try { fsImpl.unlinkSync(temporary); }
137
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
138
+ }
139
+ }
140
+ }
141
+ });
142
+ }
143
+
144
+ return { filePath, read, write, clear };
145
+ }
146
+
147
+ // Windows PowerShell 5.1 and .NET Framework are OS components. No PATH lookup,
148
+ // shell, profile, downloaded module, execution-policy bypass or generated script
149
+ // file is used. Both source and request travel over stdin, in separate frames:
150
+ // only the constant first line is compiled, NEVER request data. This also avoids
151
+ // Windows' command-line length limit. Add-Type may create compiler temporaries,
152
+ // but its input contains no session, path or other user data.
153
+ const WINDOWS_BOOTSTRAP = `
154
+ $ErrorActionPreference = 'Stop'
155
+ $ProgressPreference = 'SilentlyContinue'
156
+ try {
157
+ [Console]::InputEncoding = New-Object Text.UTF8Encoding($false, $true)
158
+ [Console]::OutputEncoding = New-Object Text.UTF8Encoding($false, $true)
159
+ $source = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Console]::ReadLine()))
160
+ Add-Type -TypeDefinition $source -ReferencedAssemblies System.Security.dll,System.Web.Extensions.dll
161
+ [VigieVulnSession]::Run([Console]::In.ReadToEnd())
162
+ } catch {
163
+ [Console]::Out.Write('{"error":"SESSION_IO"}')
164
+ exit 1
165
+ }
166
+ `;
167
+
168
+ // Deliberately restricted to local NTFS and ordinary DOS paths. Existing ACLs
169
+ // are checked, never silently repaired. All ancestors are held open without
170
+ // delete sharing; storage objects are inspected through OPEN_REPARSE_POINT
171
+ // handles. Reads, deletion and temporary-file publication use those handles.
172
+ // As on POSIX, the home/ancestors, OS, process environment and same-user processes
173
+ // are trusted. This is not a defence against administrators or the current user.
174
+ const WINDOWS_SOURCE = String.raw`
175
+ using System;
176
+ using System.IO;
177
+ using System.Text;
178
+ using System.Collections.Generic;
179
+ using System.Runtime.InteropServices;
180
+ using System.Security.AccessControl;
181
+ using System.Security.Principal;
182
+ using System.Security.Cryptography;
183
+ using System.Web.Script.Serialization;
184
+ using Microsoft.Win32.SafeHandles;
185
+
186
+ public static class VigieVulnSession {
187
+ const uint Read = 0x80000000, Write = 0x40000000, Delete = 0x10000;
188
+ const uint Reparse = 0x400, Directory = 0x10, OpenReparse = 0x00200000, Backup = 0x02000000;
189
+ const int FullControl = 0x1f01ff;
190
+ static readonly byte[] Header = Encoding.ASCII.GetBytes("VVSESSION-DPAPI-1\n");
191
+ static readonly byte[] Entropy = Encoding.UTF8.GetBytes("VigieVuln/account-session/v1");
192
+ static readonly SecurityIdentifier User = WindowsIdentity.GetCurrent().User;
193
+
194
+ [StructLayout(LayoutKind.Sequential)] struct SecurityAttributes {
195
+ public int Length; public IntPtr Descriptor; public int Inherit;
196
+ }
197
+ [StructLayout(LayoutKind.Sequential)] struct Info {
198
+ public uint Attributes;
199
+ public System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Modified;
200
+ public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
201
+ }
202
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
203
+ static extern SafeFileHandle CreateFileW(string path, uint access, uint share, ref SecurityAttributes sa, uint creation, uint flags, IntPtr template);
204
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
205
+ static extern bool CreateDirectoryW(string path, ref SecurityAttributes sa);
206
+ [DllImport("kernel32.dll", SetLastError=true)]
207
+ static extern bool GetFileInformationByHandle(SafeFileHandle handle, out Info info);
208
+ [DllImport("kernel32.dll")] static extern uint GetFileType(SafeFileHandle handle);
209
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern uint GetDriveTypeW(string root);
210
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
211
+ static extern bool GetVolumeInformationW(string root, IntPtr label, uint labelSize, out uint serial, out uint component, out uint flags, StringBuilder fs, uint fsSize);
212
+ [DllImport("advapi32.dll", SetLastError=true)]
213
+ static extern uint GetSecurityInfo(SafeFileHandle handle, int type, uint flags, out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr descriptor);
214
+ [DllImport("advapi32.dll")] static extern uint GetSecurityDescriptorLength(IntPtr descriptor);
215
+ [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr memory);
216
+ [DllImport("kernel32.dll", SetLastError=true)]
217
+ static extern bool ReadFile(SafeFileHandle handle, byte[] data, uint size, out uint read, IntPtr overlapped);
218
+ [DllImport("kernel32.dll", SetLastError=true)]
219
+ static extern bool WriteFile(SafeFileHandle handle, byte[] data, uint size, out uint written, IntPtr overlapped);
220
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool FlushFileBuffers(SafeFileHandle handle);
221
+ [DllImport("kernel32.dll", SetLastError=true)]
222
+ static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, byte[] data, uint size);
223
+
224
+ class StoreError : Exception {
225
+ public readonly string Code;
226
+ public StoreError(string code) { Code = code; }
227
+ }
228
+ static void Unsafe() { throw new StoreError("UNSAFE_SESSION_FILE"); }
229
+ static void Invalid() { throw new StoreError("INVALID_SESSION"); }
230
+ static void IO() { throw new StoreError("SESSION_IO"); }
231
+
232
+ static Info Check(SafeFileHandle handle, bool directory, bool privateAcl) {
233
+ Info info;
234
+ if (!GetFileInformationByHandle(handle, out info)) { IO(); }
235
+ if (GetFileType(handle) != 1 || (info.Attributes & Reparse) != 0 ||
236
+ ((info.Attributes & Directory) != 0) != directory || (!directory && info.Links != 1)) Unsafe();
237
+ if (!privateAcl) return info;
238
+ IntPtr owner, group, dacl, sacl, descriptor;
239
+ uint result = GetSecurityInfo(handle, 1, 5, out owner, out group, out dacl, out sacl, out descriptor);
240
+ if (result != 0) IO();
241
+ try {
242
+ byte[] bytes = new byte[GetSecurityDescriptorLength(descriptor)];
243
+ Marshal.Copy(descriptor, bytes, 0, bytes.Length);
244
+ RawSecurityDescriptor sd = new RawSecurityDescriptor(bytes, 0);
245
+ if (!User.Equals(sd.Owner) || (sd.ControlFlags & ControlFlags.DiscretionaryAclProtected) == 0 ||
246
+ sd.DiscretionaryAcl == null || sd.DiscretionaryAcl.Count != 1) Unsafe();
247
+ CommonAce ace = sd.DiscretionaryAcl[0] as CommonAce;
248
+ AceFlags expected = directory ? AceFlags.ContainerInherit | AceFlags.ObjectInherit : AceFlags.None;
249
+ if (ace == null || ace.IsCallback || ace.AceQualifier != AceQualifier.AccessAllowed ||
250
+ !User.Equals(ace.SecurityIdentifier) || ace.AccessMask != FullControl || ace.AceFlags != expected) Unsafe();
251
+ } finally { LocalFree(descriptor); }
252
+ return info;
253
+ }
254
+
255
+ static SafeFileHandle Open(string path, uint access, bool directory, bool missing) {
256
+ SecurityAttributes sa = new SecurityAttributes();
257
+ sa.Length = Marshal.SizeOf(sa);
258
+ SafeFileHandle handle = CreateFileW(path, access, directory ? 3u : 1u, ref sa, 3, OpenReparse | Backup, IntPtr.Zero);
259
+ if (!handle.IsInvalid) return handle;
260
+ int error = Marshal.GetLastWin32Error();
261
+ handle.Dispose();
262
+ if (missing && error == 2) return null;
263
+ IO(); return null;
264
+ }
265
+
266
+ // The DACL is attached at creation, including to empty temporary files.
267
+ static SafeFileHandle CreatePrivate(string path, bool directory) {
268
+ RawSecurityDescriptor sd = new RawSecurityDescriptor("O:" + User.Value + "D:P(A;" + (directory ? "OICI" : "") + ";FA;;;" + User.Value + ")");
269
+ byte[] bytes = new byte[sd.BinaryLength]; sd.GetBinaryForm(bytes, 0);
270
+ IntPtr memory = Marshal.AllocHGlobal(bytes.Length);
271
+ try {
272
+ Marshal.Copy(bytes, 0, memory, bytes.Length);
273
+ SecurityAttributes sa = new SecurityAttributes();
274
+ sa.Length = Marshal.SizeOf(sa); sa.Descriptor = memory;
275
+ if (directory) {
276
+ if (!CreateDirectoryW(path, ref sa) && Marshal.GetLastWin32Error() != 183) IO();
277
+ return Open(path, 0x20080, true, false);
278
+ }
279
+ SafeFileHandle handle = CreateFileW(path, Read | Write | Delete, 0, ref sa, 1, OpenReparse, IntPtr.Zero);
280
+ if (handle.IsInvalid) { handle.Dispose(); IO(); }
281
+ return handle;
282
+ } finally { Marshal.FreeHGlobal(memory); }
283
+ }
284
+
285
+ static void Remove(SafeFileHandle handle) {
286
+ if (!SetFileInformationByHandle(handle, 4, new byte[] { 1 }, 1)) IO();
287
+ }
288
+ static void Rename(SafeFileHandle handle, string destination) {
289
+ byte[] name = Encoding.Unicode.GetBytes(destination);
290
+ // FILE_RENAME_INFO: DWORD flags, aligned HANDLE, DWORD length, WCHAR[].
291
+ int lengthOffset = 2 * IntPtr.Size, nameOffset = lengthOffset + 4;
292
+ byte[] data = new byte[nameOffset + name.Length + 2];
293
+ data[0] = 1;
294
+ Buffer.BlockCopy(BitConverter.GetBytes(name.Length), 0, data, lengthOffset, 4);
295
+ Buffer.BlockCopy(name, 0, data, nameOffset, name.Length);
296
+ if (!SetFileInformationByHandle(handle, 3, data, (uint)data.Length)) IO();
297
+ }
298
+ static void CheckExisting(string file) {
299
+ using (SafeFileHandle handle = Open(file, 0x20080, false, true)) {
300
+ if (handle != null) Check(handle, false, true);
301
+ }
302
+ }
303
+
304
+ static object Execute(Dictionary<string, object> request) {
305
+ string operation = (string)request["operation"], home = (string)request["homeDir"];
306
+ if (operation != "read" && operation != "write" && operation != "clear") IO();
307
+ // Reject UNC/device paths, alternate streams and DOS path aliases.
308
+ if (!System.Text.RegularExpressions.Regex.IsMatch(home, @"^[A-Za-z]:\\") || home.IndexOf(':', 2) >= 0 ||
309
+ home.IndexOf('/') >= 0 || home.IndexOf('\0') >= 0 || Path.GetFullPath(home) != home) Unsafe();
310
+ string root = home.Substring(0, 3);
311
+ uint serial, component, flags;
312
+ StringBuilder format = new StringBuilder(32);
313
+ if (GetDriveTypeW(root) != 3 || !GetVolumeInformationW(root, IntPtr.Zero, 0, out serial, out component, out flags, format, 32) ||
314
+ format.ToString() != "NTFS") throw new StoreError("WINDOWS_SESSION_UNAVAILABLE");
315
+
316
+ byte[] encrypted = null;
317
+ if (operation == "write") {
318
+ byte[] plain = Encoding.UTF8.GetBytes((string)request["session"]);
319
+ try { encrypted = ProtectedData.Protect(plain, Entropy, DataProtectionScope.CurrentUser); }
320
+ finally { Array.Clear(plain, 0, plain.Length); }
321
+ }
322
+ List<SafeFileHandle> parents = new List<SafeFileHandle>();
323
+ try {
324
+ string current = root;
325
+ SafeFileHandle parent = Open(current, 0x80, true, false); parents.Add(parent); Check(parent, true, false);
326
+ foreach (string part in home.Substring(3).Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries)) {
327
+ if (part.EndsWith(".") || part.EndsWith(" ")) Unsafe();
328
+ current = Path.Combine(current, part);
329
+ parent = Open(current, 0x80, true, false); parents.Add(parent); Check(parent, true, false);
330
+ }
331
+ string directory = Path.Combine(home, ".vigievuln"), file = Path.Combine(directory, "account-session.json");
332
+ using (SafeFileHandle dir = operation == "write" ? CreatePrivate(directory, true) : Open(directory, 0x20080, true, true)) {
333
+ if (dir == null) return null;
334
+ Check(dir, true, true);
335
+ if (operation == "write") {
336
+ CheckExisting(file);
337
+ string temporary = Path.Combine(directory, ".account-session-" + Guid.NewGuid().ToString("N") + ".tmp");
338
+ using (SafeFileHandle handle = CreatePrivate(temporary, false)) {
339
+ bool committed = false;
340
+ try {
341
+ Check(handle, false, true);
342
+ byte[] data = new byte[Header.Length + encrypted.Length];
343
+ Buffer.BlockCopy(Header, 0, data, 0, Header.Length);
344
+ Buffer.BlockCopy(encrypted, 0, data, Header.Length, encrypted.Length);
345
+ uint written;
346
+ if (data.Length > 4096 || !WriteFile(handle, data, (uint)data.Length, out written, IntPtr.Zero) || written != data.Length || !FlushFileBuffers(handle)) IO();
347
+ Check(handle, false, true); CheckExisting(file);
348
+ Rename(handle, file); committed = true;
349
+ } finally { if (!committed) Remove(handle); }
350
+ }
351
+ return null;
352
+ }
353
+ using (SafeFileHandle handle = Open(file, Read | (operation == "clear" ? Delete : 0), false, true)) {
354
+ if (handle == null) return null;
355
+ Info info = Check(handle, false, true);
356
+ if (operation == "clear") { Remove(handle); return null; }
357
+ if (info.SizeHigh != 0 || info.SizeLow > 4096 || info.SizeLow <= Header.Length) Invalid();
358
+ byte[] data = new byte[info.SizeLow]; uint count;
359
+ if (!ReadFile(handle, data, (uint)data.Length, out count, IntPtr.Zero) || count != data.Length) IO();
360
+ for (int i = 0; i < Header.Length; i++) if (data[i] != Header[i]) Invalid();
361
+ byte[] cipher = new byte[data.Length - Header.Length];
362
+ Buffer.BlockCopy(data, Header.Length, cipher, 0, cipher.Length);
363
+ byte[] plain;
364
+ try { plain = ProtectedData.Unprotect(cipher, Entropy, DataProtectionScope.CurrentUser); }
365
+ catch (CryptographicException) { Invalid(); return null; }
366
+ try { return new UTF8Encoding(false, true).GetString(plain); }
367
+ finally { Array.Clear(plain, 0, plain.Length); }
368
+ }
369
+ }
370
+ } finally { for (int i = parents.Count - 1; i >= 0; i--) parents[i].Dispose(); }
371
+ }
372
+ public static void Run(string input) {
373
+ JavaScriptSerializer json = new JavaScriptSerializer(); json.MaxJsonLength = 16384;
374
+ object response;
375
+ try { response = new { value = Execute(json.Deserialize<Dictionary<string, object>>(input)) }; }
376
+ catch (StoreError error) { response = new { error = error.Code }; }
377
+ catch { response = new { error = "SESSION_IO" }; }
378
+ // Write directly to stdout rather than the PowerShell object pipeline.
379
+ Console.Out.Write(json.Serialize(response));
380
+ }
381
+ }
382
+ `;
383
+
384
+ function createWindowsSessionStore({ homeDir, now, spawnSyncImpl, windowsRoot }) {
385
+ const resolvedHome = path.win32.resolve(homeDir);
386
+ const filePath = path.win32.join(resolvedHome, '.vigievuln', 'account-session.json');
387
+ const messages = {
388
+ SESSION_IO: 'Unable to access private account session storage.',
389
+ INVALID_SESSION: 'Invalid account session file. Sign in again.',
390
+ UNSAFE_SESSION_FILE: 'Account session storage must be private, owned by the current user and free of links.',
391
+ WINDOWS_SESSION_UNAVAILABLE: 'Private account sessions require Windows PowerShell 5.1, DPAPI and a local NTFS home directory.',
392
+ };
393
+ const fail = code => new AccountSessionError(code, messages[code]);
394
+ function run(operation, session) {
395
+ try {
396
+ if (typeof windowsRoot !== 'string' || !/^[a-z]:\\[^\r\n\0]*$/i.test(windowsRoot) || windowsRoot.includes('..')) {
397
+ throw fail('WINDOWS_SESSION_UNAVAILABLE');
398
+ }
399
+ const result = spawnSyncImpl(path.win32.join(windowsRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
400
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(WINDOWS_BOOTSTRAP, 'utf16le').toString('base64')], {
401
+ shell: false, windowsHide: true, cwd: windowsRoot, encoding: 'utf8', timeout: 15000, maxBuffer: 16384,
402
+ input: Buffer.from(WINDOWS_SOURCE, 'utf8').toString('base64') + '\n' + JSON.stringify({
403
+ operation, homeDir: resolvedHome, ...(session ? { session: JSON.stringify(session) } : {}),
404
+ }),
405
+ });
406
+ if (!result || result.error || result.signal || result.status !== 0 || typeof result.stdout !== 'string' ||
407
+ Buffer.byteLength(result.stdout, 'utf8') > 16384) throw fail('SESSION_IO');
408
+ const response = JSON.parse(result.stdout);
409
+ if (!response || typeof response !== 'object' || Array.isArray(response)) throw fail('SESSION_IO');
410
+ if (Object.hasOwn(response, 'error')) throw fail(Object.hasOwn(messages, response.error) ? response.error : 'SESSION_IO');
411
+ if (!Object.hasOwn(response, 'value') || (response.value !== null && (operation !== 'read' || typeof response.value !== 'string'))) throw fail('SESSION_IO');
412
+ return response.value;
413
+ } catch (error) {
414
+ if (error instanceof AccountSessionError) throw error;
415
+ // Child-process errors can contain stdin, stderr, paths or decrypted data.
416
+ throw fail('SESSION_IO');
417
+ }
418
+ }
419
+ function clear() { run('clear'); }
420
+ function write(value) { run('write', validateAccountSession(value, now())); }
421
+ function read() {
422
+ const contents = run('read');
423
+ if (contents === null) return null;
424
+ let value;
425
+ try { value = JSON.parse(contents); } catch { throw fail('INVALID_SESSION'); }
426
+ try { return validateAccountSession(value, now()); }
427
+ catch (error) {
428
+ if (error.code !== 'SESSION_EXPIRED') throw error;
429
+ clear();
430
+ return null;
431
+ }
432
+ }
433
+ return { filePath, read, write, clear };
434
+ }
435
+
436
+ module.exports = { createAccountSessionStore, validateAccountSession, AccountSessionError };
@@ -7,6 +7,13 @@ const { selectPlugins } = require("./select");
7
7
 
8
8
  const DEFAULT_SKIP = new Set([".git", ".idea", ".vscode", "node_modules", "vendor", "dist", "build", "out", "target"]);
9
9
  const posix = p => p.split(path.sep).join("/");
10
+ const WORDFENCE_MAX_LOCAL_AGE_MS = 3600000;
11
+ function staleWordfenceSnapshot(meta, now, autoCached = false) {
12
+ if (!autoCached && meta?.completeness !== "targeted") return false;
13
+ const collectedAt = Date.parse(meta?.collectedAt);
14
+ return meta?.stale === true || !Number.isFinite(collectedAt) || collectedAt > now + 60000 ||
15
+ now - collectedAt > WORDFENCE_MAX_LOCAL_AGE_MS;
16
+ }
10
17
  function privatePath(value) {
11
18
  if (typeof value !== "string" || !value || path.isAbsolute(value) || posix(value).split("/").includes(".."))
12
19
  throw new Error("private component path must stay relative to the scan root");
@@ -95,13 +102,21 @@ async function runApplicationPlugins(root, opts = {}) {
95
102
  // Cached advisory-snapshot reuse: a snapshot the tool itself fetched and cached (in
96
103
  // ~/.fad-checker/advisory-snapshots/, carried between machines by --export-cache /
97
104
  // --import-cache, warmed by --import-anonymized or a prior live scan) is consumed
98
- // without its explicit flag — in EVERY mode. The lanes a scan runs are a function of
99
- // the cache state, not of online/offline, so an air-gapped phase 3 and its online
100
- // reference scan (same command, same options) produce identical results. An explicit
105
+ // without its explicit flag. Hosted online Drupal lookups must reach the proxy instead
106
+ // of letting an implicit snapshot bypass its freshness policy. Offline and direct
107
+ // scans retain the local fallback. An explicit
101
108
  // flag or live URL always wins, the fallback only engages when the source's
102
109
  // application plugin is selected, and the file goes through the same validation
103
110
  // (schema, freshness) as an operator-supplied one.
104
111
  const selectedPluginIds = new Set(plugins.map(plugin => plugin.id));
112
+ const hostedOnline = !opts.offline && require("../providers").hasHostedProxy();
113
+ const wordfenceProxyOnline = !opts.offline && require("../providers").hasProxyRoute();
114
+ const liveWordfenceUrl = opts.offline ? null : opts.liveWordfenceUrl || null;
115
+ // Drupal's live operation is scoped to the inventoried public package identities.
116
+ // Never refresh a bulk catalogue here, and never replace an operator-selected file.
117
+ const liveDrupalAdvisoriesUrl = opts.offline ? null : (opts.liveDrupalAdvisoriesUrl ||
118
+ (hostedOnline && !opts.drupalAdvisoriesPath && selectedPluginIds.has("drupal")
119
+ ? require("../application-providers/live-snapshot").DRUPAL_ADVISORIES_URL : null));
105
120
  const autoCachedSources = new Set();
106
121
  const withCachedFallback = (configured, liveUrl, pluginId, file) => {
107
122
  if (configured || liveUrl || !opts.advisoryCacheDir || !selectedPluginIds.has(pluginId)) return configured || null;
@@ -110,8 +125,9 @@ async function runApplicationPlugins(root, opts = {}) {
110
125
  autoCachedSources.add(cached);
111
126
  return cached;
112
127
  };
113
- const wordfenceFeedPath = withCachedFallback(opts.wordfenceFeedPath, opts.liveWordfenceUrl, "wordpress", "wordfence-v3.json");
114
- const drupalAdvisoriesPath = withCachedFallback(opts.drupalAdvisoriesPath, opts.liveDrupalAdvisoriesUrl, "drupal", "drupal-security-advisories.json");
128
+ const wordfenceFeedPath = withCachedFallback(opts.wordfenceFeedPath, liveWordfenceUrl, "wordpress",
129
+ "wordfence-v3-targeted.json") || withCachedFallback(null, liveWordfenceUrl, "wordpress", "wordfence-v3.json");
130
+ const drupalAdvisoriesPath = withCachedFallback(opts.drupalAdvisoriesPath, liveDrupalAdvisoriesUrl, "drupal", "drupal-security-advisories.json");
115
131
  const prestashopAdvisoriesPath = withCachedFallback(opts.prestashopAdvisoriesPath, opts.livePrestashopAdvisoriesUrl, "prestashop", "github-prestashop-advisories.json");
116
132
  const typo3AdvisoriesPath = withCachedFallback(opts.typo3AdvisoriesPath, opts.liveTypo3AdvisoriesUrl, "typo3", "github-typo3-advisories.json");
117
133
  const spipAdvisoriesPath = withCachedFallback(opts.spipAdvisoriesPath, opts.liveSpipAdvisoriesUrl, "spip", "spip-security-advisories.json");
@@ -129,7 +145,11 @@ async function runApplicationPlugins(root, opts = {}) {
129
145
  const bytes = fs.readFileSync(snapshotPath);
130
146
  const snapshot = JSON.parse(bytes.toString("utf8"));
131
147
  validate(snapshot);
132
- if (opts.maxAdvisoryAgeMs) {
148
+ // Give an expired cache a chance to revalidate before applying the strict
149
+ // age gate. The assessed source is checked again before recording coverage.
150
+ const revalidateWordfence = snapshotPath === wordfenceFeedPath && wordfenceProxyOnline &&
151
+ staleWordfenceSnapshot(snapshot._fadSnapshot, opts.now || Date.now(), autoCachedSources.has(snapshotPath));
152
+ if (opts.maxAdvisoryAgeMs && !revalidateWordfence) {
133
153
  const { assertFresh } = require("../advisory-freshness");
134
154
  assertFresh(snapshot, label, opts.maxAdvisoryAgeMs, opts.now || Date.now());
135
155
  }
@@ -163,9 +183,9 @@ async function runApplicationPlugins(root, opts = {}) {
163
183
  publicSlugForPath: rel => publicSlugs.get(privatePath(rel)) || null,
164
184
  wordfenceFeedPath,
165
185
  drupalAdvisoriesPath,
166
- liveWordfenceUrl: opts.liveWordfenceUrl || null,
186
+ liveWordfenceUrl,
167
187
  wordfenceApiKey: opts.wordfenceApiKey || null,
168
- liveDrupalAdvisoriesUrl: opts.liveDrupalAdvisoriesUrl || null,
188
+ liveDrupalAdvisoriesUrl,
169
189
  prestashopAdvisoriesPath,
170
190
  livePrestashopAdvisoriesUrl: opts.livePrestashopAdvisoriesUrl || null,
171
191
  typo3AdvisoriesPath,
@@ -186,6 +206,39 @@ async function runApplicationPlugins(root, opts = {}) {
186
206
  snapshotCache: new Map(),
187
207
  validatedLocalSources,
188
208
  };
209
+ async function assessApplication(plugin, app, components) {
210
+ const local = validatedLocalSources.get(wordfenceFeedPath)?.snapshot;
211
+ const localStale = staleWordfenceSnapshot(local?._fadSnapshot, context.now,
212
+ autoCachedSources.has(wordfenceFeedPath));
213
+ let assessed;
214
+ let refreshError;
215
+ let usedLocal = true;
216
+ if (plugin.id === "wordpress" && wordfenceProxyOnline && localStale) {
217
+ try {
218
+ assessed = await plugin.assess(app, components, { ...context, wordfenceFeedPath: null,
219
+ liveWordfenceUrl: require("../application-providers/wordfence-projection").SOURCE_URL });
220
+ usedLocal = false;
221
+ } catch (error) {
222
+ if (requiredProviderIds.has("wordfence-v3") && !opts.reportProviderFailures) throw error;
223
+ refreshError = error;
224
+ }
225
+ }
226
+ if (!assessed) assessed = await plugin.assess(app, components, context);
227
+ if (plugin.id !== "wordpress" || !assessed || Array.isArray(assessed)) return assessed;
228
+ let stale = false;
229
+ const coverage = (assessed.coverage || []).map(check => {
230
+ if (check.sourceId !== "wordfence-v3" ||
231
+ !((usedLocal && localStale) || staleWordfenceSnapshot(check.sourceSnapshot, context.now))) return check;
232
+ stale = true;
233
+ return { ...check, sourceSnapshot: { ...check.sourceSnapshot, stale: true },
234
+ execution: check.execution === "completed" ? "partial" : check.execution,
235
+ result: "indeterminate", diagnostic: check.diagnostic || "CMS_ADVISORY_STALE" };
236
+ });
237
+ return { ...assessed, coverage, diagnostics: [...(assessed.diagnostics || []),
238
+ ...(stale ? [{ code: "CMS_ADVISORY_STALE", applicationId: app.id,
239
+ message: `Wordfence snapshot is stale; advisory coverage is indeterminate${refreshError
240
+ ? ` (targeted revalidation failed: ${refreshError.message})` : ""}` }] : [])] };
241
+ }
189
242
  // discover returns candidates, and may add diagnostics (e.g. recognized-but-invalid input);
190
243
  // a bare candidate array stays the documented simple form.
191
244
  function discovered(plugin) {
@@ -245,7 +298,7 @@ async function runApplicationPlugins(root, opts = {}) {
245
298
  continue;
246
299
  }
247
300
  try {
248
- const assessed = await plugin.assess(app, collected.components || [], context) || [];
301
+ const assessed = await assessApplication(plugin, app, collected.components || []) || [];
249
302
  if (Array.isArray(assessed)) result.findings.push(...assessed);
250
303
  else {
251
304
  result.findings.push(...(assessed.findings || []));
@@ -258,11 +311,18 @@ async function runApplicationPlugins(root, opts = {}) {
258
311
  }
259
312
  }
260
313
  } catch (error) {
261
- if (plugin.providerIds.some(id => requiredProviderIds.has(id)))
314
+ const required = plugin.providerIds.filter(id => requiredProviderIds.has(id));
315
+ // A CLI scan must retain its inventory and write partial reports. Its explicit
316
+ // coverage gate runs after export; library callers retain fail-fast semantics.
317
+ if (required.length && (!opts.reportProviderFailures || context.maxAdvisoryAgeMs))
262
318
  throw new Error(`${plugin.id} advisory source failed: ${error.message}`);
263
- result.diagnostics.push({ code: "CMS_PLUGIN_FAILED", applicationId: app.id, message: `assessment failed: ${error.message}` });
264
- if (!journal.records.some(c => c.applicationId === app.id && c.capability === "advisories"))
265
- journal.record({ applicationId: app.id, capability: "advisories", execution: "failed", result: "indeterminate", diagnostic: "CMS_PLUGIN_FAILED" });
319
+ result.diagnostics.push({ code: "CMS_PLUGIN_FAILED", applicationId: app.id,
320
+ sourceIds: required, message: `assessment failed: ${error.message}` });
321
+ if (!journal.records.some(c => c.applicationId === app.id && c.capability === "advisories")) {
322
+ for (const sourceId of required.length ? required : [null])
323
+ journal.record({ applicationId: app.id, ...(sourceId ? { sourceId } : {}),
324
+ capability: "advisories", execution: "failed", result: "indeterminate", diagnostic: "CMS_PLUGIN_FAILED" });
325
+ }
266
326
  }
267
327
  }
268
328
  }
@@ -236,7 +236,10 @@ module.exports = {
236
236
  sourceId: "wordfence-v3", execution: "not-run", result: "indeterminate", expected: components.length,
237
237
  executed: 0, diagnostic: "CMS_PROVIDER_UNCONFIGURED" }, ...integrity.coverage],
238
238
  diagnostics: integrity.diagnostics };
239
- const key = ctx.wordfenceFeedPath ? `wordfence-v3:${ctx.wordfenceFeedPath}` : `wordfence-v3:live:${ctx.liveWordfenceUrl}`;
239
+ const projection = !ctx.wordfenceFeedPath && require("../providers").hasProxyRoute();
240
+ const software = projection ? require("../application-providers/wordfence-projection").componentQueries(components) : null;
241
+ const key = ctx.wordfenceFeedPath ? `wordfence-v3:${ctx.wordfenceFeedPath}` :
242
+ `wordfence-v3:live:${ctx.liveWordfenceUrl}:${projection ? JSON.stringify(software) : "full"}`;
240
243
  let cached = ctx.snapshotCache.get(key);
241
244
  if (!cached && ctx.wordfenceFeedPath) {
242
245
  // Reuse the runner's single validated read when available (freshness and schema
@@ -248,12 +251,16 @@ module.exports = {
248
251
  const feed = validated?.snapshot || JSON.parse(bytes.toString("utf8"));
249
252
  const index = indexFeed(feed);
250
253
  const sourceSnapshot = localSourceSnapshot(ctx, ctx.wordfenceFeedPath, bytes, stat, feed);
254
+ if (index.sourceSnapshot) Object.assign(sourceSnapshot, index.sourceSnapshot);
251
255
  cached = { index, sourceSnapshot };
252
256
  } else if (!cached) {
253
257
  const fetched = await fetchWordfenceFeed(ctx.liveWordfenceUrl, {
254
- fetchImpl: ctx.fetchImpl || undefined, now: ctx.now, apiKey: ctx.wordfenceApiKey,
258
+ fetchImpl: ctx.fetchImpl || undefined, now: ctx.now, apiKey: ctx.wordfenceApiKey, components,
255
259
  });
256
- if (ctx.advisoryCacheDir) writeSnapshotAtomically(path.join(ctx.advisoryCacheDir, "wordfence-v3.json"), fetched.snapshot);
260
+ if (ctx.advisoryCacheDir) {
261
+ if (projection) require("../application-providers/wordfence-client").cacheProjection(ctx.advisoryCacheDir, fetched.snapshot);
262
+ else writeSnapshotAtomically(path.join(ctx.advisoryCacheDir, "wordfence-v3.json"), fetched.snapshot);
263
+ }
257
264
  cached = { index: indexFeed(fetched.snapshot), sourceSnapshot: fetched.sourceSnapshot };
258
265
  }
259
266
  ctx.snapshotCache.set(key, cached);
@@ -70,9 +70,14 @@ function mergeDrupalSnapshots(cached, fetched) {
70
70
  sha256: crypto.createHash("sha256").update(JSON.stringify(snapshot)).digest("hex") } };
71
71
  }
72
72
 
73
- async function fetchWordfenceFeed(url, { fetchImpl = globalThis.fetch, now = Date.now(), apiKey } = {}) {
73
+ async function fetchWordfenceFeed(url, { fetchImpl = globalThis.fetch, now = Date.now(), apiKey, components = [], software } = {}) {
74
74
  const sourceUrl = String(url);
75
75
  const key = typeof apiKey === "string" ? apiKey.trim() : "";
76
+ if (require("../providers").hasProxyRoute()) {
77
+ if (sourceUrl !== WORDFENCE_PRODUCTION_URL)
78
+ throw new Error("Wordfence proxy projections require the official source; direct bulk fallback is unavailable");
79
+ return require("./wordfence-client").fetchWordfenceProjection(components, { fetchImpl, now, apiKey: key, software });
80
+ }
76
81
  const proxyCredentials = sourceUrl === WORDFENCE_PRODUCTION_URL && require("../providers").hasProxyRoute();
77
82
  if (!key && !proxyCredentials)
78
83
  throw new Error("Wordfence live scan requires an API key (--wordfence-api-key or WORDFENCE_API_KEY), or the official feed via --proxy-cache with a server key");