@westbayberry/dg 2.0.4 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1 +1,201 @@
1
- UNLICENSED
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 WestBayBerry
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/NOTICE CHANGED
@@ -1 +1,5 @@
1
1
  Dependency Guardian dg CLI
2
+ Copyright 2026 WestBayBerry
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ See the LICENSE file for the full license text.
@@ -6,6 +6,7 @@ import { envAuthToken } from "../auth/env-token.js";
6
6
  import { loadUserConfig } from "../config/settings.js";
7
7
  import { sanitize, sanitizeResponse } from "../security/sanitize.js";
8
8
  import { resolveDgPaths } from "../state/index.js";
9
+ import { dgVersion } from "../commands/version.js";
9
10
  export class AnalyzeError extends Error {
10
11
  statusCode;
11
12
  body;
@@ -22,6 +23,7 @@ const ANALYZE_PATHS = {
22
23
  };
23
24
  const BATCH_SIZE = 200;
24
25
  const DEFAULT_TIMEOUT_MS = 180_000;
26
+ const BATCH_CONCURRENCY = Math.max(1, Number(process.env.DG_ANALYZE_CONCURRENCY) || 4);
25
27
  export async function analyzePackages(packages, options) {
26
28
  const env = options.env ?? process.env;
27
29
  const fetchImpl = options.fetchImpl ?? fetch;
@@ -29,22 +31,47 @@ export async function analyzePackages(packages, options) {
29
31
  const token = resolveToken(env);
30
32
  const deviceId = getOrCreateDeviceId(env);
31
33
  const url = `${baseUrl}${ANALYZE_PATHS[options.ecosystem]}`;
32
- options.onProgress?.(0, packages.length, []);
33
- const responses = [];
34
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35
+ const total = packages.length;
36
+ const batches = [];
34
37
  for (let index = 0; index < packages.length; index += BATCH_SIZE) {
35
- const batch = packages.slice(index, index + BATCH_SIZE);
36
- options.onProgress?.(index, packages.length, batch.map((entry) => entry.name));
37
- responses.push(await analyzeBatchWithRetry(url, batch, token, deviceId, fetchImpl, options.timeoutMs ?? DEFAULT_TIMEOUT_MS));
38
- options.onProgress?.(Math.min(index + batch.length, packages.length), packages.length, batch.map((entry) => entry.name));
38
+ batches.push(packages.slice(index, index + BATCH_SIZE));
39
39
  }
40
+ const batchCount = Math.max(1, batches.length);
41
+ options.onProgress?.({ done: 0, total, batchIndex: 0, batchCount });
42
+ const perBatchDone = new Array(batches.length).fill(0);
43
+ const responses = new Array(batches.length);
44
+ let batchesFinished = 0;
45
+ const reportProgress = () => {
46
+ const done = perBatchDone.reduce((sum, n) => sum + n, 0);
47
+ options.onProgress?.({ done, total, batchIndex: batchesFinished, batchCount });
48
+ };
49
+ let cursor = 0;
50
+ const runWorker = async () => {
51
+ for (let i = cursor++; i < batches.length; i = cursor++) {
52
+ const batch = batches[i];
53
+ if (!batch)
54
+ continue;
55
+ const response = await analyzeBatchWithRetry(url, batch, token, deviceId, fetchImpl, timeoutMs, (batchDone) => {
56
+ perBatchDone[i] = Math.min(batchDone, batch.length);
57
+ reportProgress();
58
+ });
59
+ perBatchDone[i] = batch.length;
60
+ batchesFinished += 1;
61
+ responses[i] = response;
62
+ reportProgress();
63
+ }
64
+ };
65
+ const workers = Math.min(BATCH_CONCURRENCY, Math.max(1, batches.length));
66
+ await Promise.all(Array.from({ length: workers }, () => runWorker()));
40
67
  return mergeAnalyzeResponses(responses);
41
68
  }
42
69
  const MAX_BATCH_ATTEMPTS = 3;
43
- async function analyzeBatchWithRetry(url, batch, token, deviceId, fetchImpl, timeoutMs) {
70
+ async function analyzeBatchWithRetry(url, batch, token, deviceId, fetchImpl, timeoutMs, onBatchProgress) {
44
71
  let lastError;
45
72
  for (let attempt = 1; attempt <= MAX_BATCH_ATTEMPTS; attempt += 1) {
46
73
  try {
47
- return await analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs);
74
+ return await analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs, onBatchProgress);
48
75
  }
49
76
  catch (error) {
50
77
  lastError = error;
@@ -77,7 +104,7 @@ function isRetryableAnalyzeError(error) {
77
104
  function delay(ms) {
78
105
  return new Promise((resolve) => setTimeout(resolve, ms));
79
106
  }
80
- async function analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs) {
107
+ async function analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs, onBatchProgress) {
81
108
  const controller = new AbortController();
82
109
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
83
110
  try {
@@ -85,7 +112,9 @@ async function analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs) {
85
112
  method: "POST",
86
113
  headers: {
87
114
  "Content-Type": "application/json",
115
+ "Accept": "application/x-ndjson",
88
116
  "X-Device-Id": deviceId,
117
+ "X-Dg-Version": dgVersion(),
89
118
  ...(token ? { Authorization: `Bearer ${token}` } : {})
90
119
  },
91
120
  body: JSON.stringify({
@@ -100,6 +129,11 @@ async function analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs) {
100
129
  : `scanner returned ${response.status}`;
101
130
  throw new AnalyzeError(serverMessage, response.status, body);
102
131
  }
132
+ const headers = response.headers;
133
+ const contentType = headers?.get("content-type") ?? "";
134
+ if (contentType.includes("application/x-ndjson") && response.body) {
135
+ return await consumeAnalyzeStream(response.body, onBatchProgress);
136
+ }
103
137
  return normalizeAnalyzeResponse(await response.json());
104
138
  }
105
139
  catch (error) {
@@ -112,6 +146,54 @@ async function analyzeBatch(url, batch, token, deviceId, fetchImpl, timeoutMs) {
112
146
  clearTimeout(timeout);
113
147
  }
114
148
  }
149
+ async function consumeAnalyzeStream(body, onBatchProgress) {
150
+ const reader = body.getReader();
151
+ const decoder = new TextDecoder();
152
+ let buffer = "";
153
+ let result;
154
+ const handleLine = (line) => {
155
+ if (!line)
156
+ return;
157
+ let event;
158
+ try {
159
+ event = JSON.parse(line);
160
+ }
161
+ catch {
162
+ return;
163
+ }
164
+ if (event.type === "progress" || event.type === "cache_hit") {
165
+ if (typeof event.done === "number")
166
+ onBatchProgress(event.done);
167
+ }
168
+ else if (event.type === "error") {
169
+ throw new AnalyzeError(typeof event.error === "string" ? sanitize(event.error) : `scanner returned ${event.statusCode ?? 500}`, typeof event.statusCode === "number" ? event.statusCode : 0, event);
170
+ }
171
+ else if (event.type === "result") {
172
+ result = normalizeAnalyzeResponse(event.payload);
173
+ }
174
+ };
175
+ try {
176
+ for (;;) {
177
+ const { done, value } = await reader.read();
178
+ if (done)
179
+ break;
180
+ buffer += decoder.decode(value, { stream: true });
181
+ let newline;
182
+ while ((newline = buffer.indexOf("\n")) >= 0) {
183
+ handleLine(buffer.slice(0, newline).trim());
184
+ buffer = buffer.slice(newline + 1);
185
+ }
186
+ }
187
+ handleLine(buffer.trim());
188
+ }
189
+ finally {
190
+ reader.cancel().catch(() => undefined);
191
+ }
192
+ if (!result) {
193
+ throw new AnalyzeError("scanner stream ended without a result", 0);
194
+ }
195
+ return result;
196
+ }
115
197
  export function normalizeAnalyzeResponse(raw) {
116
198
  const candidate = raw;
117
199
  if (!candidate || typeof candidate.score !== "number" || !Array.isArray(candidate.packages)) {
@@ -25,7 +25,9 @@ export const setupCommand = {
25
25
  ],
26
26
  handler: (context) => setupHandler(context.args)
27
27
  };
28
- const WINDOWS_UNSUPPORTED = "dg setup does not support Windows yet — Linux and macOS only.\n";
28
+ const WINDOWS_UNSUPPORTED = "dg setup (automatic interception) does not support Windows yet.\n" +
29
+ "You can still protect installs on Windows: prefix the command with dg,\n" +
30
+ "for example `dg pip install <pkg>` or `dg npm install <pkg>`.\n";
29
31
  function setupHandler(args) {
30
32
  const parsed = parseSetupArgs(args);
31
33
  if ("error" in parsed) {
@@ -2,7 +2,7 @@ import { authStatus, displayTier } from "../auth/store.js";
2
2
  import { loadUserConfig } from "../config/settings.js";
3
3
  import { resolvePresentation } from "../presentation/mode.js";
4
4
  import { createTheme } from "../presentation/theme.js";
5
- import { doctorReport } from "../setup/plan.js";
5
+ import { currentShellActivation, doctorReport } from "../setup/plan.js";
6
6
  import { gitHookStatusState } from "../setup/git-hook.js";
7
7
  import { EXIT_USAGE } from "./types.js";
8
8
  export const statusCommand = {
@@ -48,7 +48,8 @@ function buildStatusReport() {
48
48
  const policy = loadUserConfig().policy;
49
49
  return {
50
50
  account: auth,
51
- protection: { shims: checkPassed("shims"), path: checkPassed("path") },
51
+ protection: { shims: checkPassed("shims"), path: checkPassed("path"), configured: checkPassed("shell-rc") },
52
+ reloadHint: currentShellActivation(),
52
53
  commitGuard: safeCommitGuard(),
53
54
  policy: { mode: policy.mode, trustProjectAllowlists: policy.trustProjectAllowlists }
54
55
  };
@@ -83,8 +84,8 @@ function renderStatus(report, theme) {
83
84
  : `${theme.paint("warn", "⚠")} not connected — run ${theme.paint("accent", "dg login")}`;
84
85
  const bare = report.protection.shims && report.protection.path
85
86
  ? `${theme.paint("pass", "✓")} bare npm/pip installs are protected`
86
- : report.protection.shims
87
- ? `${theme.paint("warn", "")} set up active in new terminals (or prefix commands with ${theme.paint("accent", "dg")})`
87
+ : report.protection.shims && report.protection.configured
88
+ ? `${theme.paint("muted", "")} configuredrun ${theme.paint("accent", report.reloadHint)} to activate this shell ${theme.paint("muted", "(already active in new terminals)")}`
88
89
  : `${theme.paint("warn", "⚠")} not set up — run ${theme.paint("accent", "dg setup")}, or prefix commands with ${theme.paint("accent", "dg")}`;
89
90
  const lines = [
90
91
  "Dependency Guardian status",
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
3
  import InkSpinner from "ink-spinner";
4
+ import { formatResetDate } from "./block-render.js";
4
5
  function packageCount(n) {
5
6
  return n === 1 ? "1 package" : `${n} packages`;
6
7
  }
@@ -10,15 +11,26 @@ function rule() {
10
11
  }
11
12
  export const LiveInstall = ({ view }) => {
12
13
  if (view.phase === "scanning") {
13
- return (_jsxs(Box, { paddingX: 1, children: [_jsx(Text, { color: "cyan", children: _jsx(InkSpinner, { type: "dots" }) }), _jsxs(Text, { children: [" ", view.total === 0 ? "DG starting protection…" : `DG verifying ${packageCount(view.total)}…`] }), view.current ? _jsxs(Text, { dimColor: true, children: [" ", view.current] }) : null] }));
14
+ return (_jsxs(Box, { paddingX: 1, children: [_jsx(Text, { color: "cyan", children: _jsx(InkSpinner, { type: "dots" }) }), _jsxs(Text, { children: [" ", view.total === 0
15
+ ? "DG starting protection…"
16
+ : view.resolvedTotal !== undefined
17
+ ? `DG verifying ${view.total}/${Math.max(view.total, view.resolvedTotal)}…`
18
+ : `DG verifying ${packageCount(view.total)}…`] }), view.current ? _jsxs(Text, { dimColor: true, children: [" ", view.current] }) : null] }));
14
19
  }
15
20
  if (view.total === 0 && !view.blocked) {
16
21
  return null;
17
22
  }
18
23
  if (view.blocked) {
19
24
  const blocked = view.blocked;
25
+ if (blocked.cause === "quota-exceeded") {
26
+ const reset = formatResetDate(blocked.resetsAt);
27
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 1, children: [_jsx(Text, { color: "gray", children: rule() }), _jsxs(Text, { color: "yellow", children: ["Quota hit", reset ? ` — resets ${reset}` : ""] }), _jsxs(Text, { dimColor: true, children: [" ", "Override: ", blocked.override ?? "--dg-force-install"] })] }));
28
+ }
20
29
  return (_jsxs(Box, { flexDirection: "column", paddingX: 1, children: [_jsx(Text, { color: "gray", children: rule() }), blocked.kind === "blocked" ? (_jsxs(Text, { color: "red", children: ["\u2718 DG blocked install \u2014 ", blocked.headline] })) : (_jsxs(Text, { color: "yellow", children: ["? DG could not verify ", blocked.packageName, " \u2014 ", blocked.headline] })), _jsxs(Text, { children: [" ", blocked.packageName, " ", blocked.reason] }), blocked.override ? _jsxs(Text, { dimColor: true, children: [" ", "Override: ", blocked.override] }) : null, blocked.nextStep ? _jsxs(Text, { dimColor: true, children: [" ", "Next: ", blocked.nextStep] }) : null] }));
21
30
  }
22
31
  const total = view.verified + view.flagged;
23
- return (_jsx(Box, { paddingX: 1, children: view.flagged > 0 ? (_jsxs(Text, { color: "yellow", children: ["\u26A0 DG verified ", packageCount(total), " \u2014 ", view.flagged, " flagged"] })) : (_jsxs(Text, { color: "green", children: ["\u2713 DG verified ", packageCount(total), " \u2014 clean"] })) }));
32
+ if (view.flagged > 0) {
33
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 1, children: [_jsxs(Text, { color: "yellow", children: ["\u26A0 DG verified ", packageCount(total), " \u2014 ", view.flagged, " flagged"] }), (view.flaggedItems ?? []).map((item, index) => (_jsxs(Text, { dimColor: true, children: [" ", item.packageName, " ", item.reason] }, `${item.packageName}-${index}`)))] }));
34
+ }
35
+ return (_jsx(Box, { paddingX: 1, children: _jsxs(Text, { color: "green", children: ["\u2713 DG verified ", packageCount(total), " \u2014 clean"] }) }));
24
36
  };
@@ -44,20 +44,42 @@ export function describeBlockedInstall(decision) {
44
44
  packageName: decision.packageName,
45
45
  headline: HEADLINES[decision.cause],
46
46
  reason: decision.reason,
47
+ cause: decision.cause,
48
+ ...(decision.resetsAt ? { resetsAt: decision.resetsAt } : {}),
47
49
  ...(nextStep ? { nextStep } : {}),
48
50
  ...(verifiedBad ? {} : { override })
49
51
  };
50
52
  }
53
+ export function describeFlaggedWarn(decision) {
54
+ if (decision.cause === "quota-exceeded") {
55
+ return { packageName: decision.packageName, reason: "installed unverified (over quota)" };
56
+ }
57
+ if (decision.forceOverride?.allowed) {
58
+ return { packageName: decision.packageName, reason: "installed despite block (--dg-force-install)" };
59
+ }
60
+ return { packageName: decision.packageName, reason: decision.reason };
61
+ }
51
62
  export function renderInstallDecision(decision) {
52
63
  if (decision.action === "pass") {
53
64
  return `✓ DG verified ${decision.packageName} — clean\n`;
54
65
  }
55
66
  if (decision.action === "warn") {
67
+ if (decision.cause === "quota-exceeded") {
68
+ const reset = formatResetDate(decision.resetsAt);
69
+ return `⚠ Over quota — installed ${decision.packageName} unverified${reset ? ` (resets ${reset})` : ""}\n`;
70
+ }
56
71
  if (decision.forceOverride?.allowed) {
57
72
  return `⚠ DG override — installing ${decision.packageName} despite block (--dg-force-install)\n`;
58
73
  }
59
74
  return `⚠ DG flagged ${decision.packageName} (warn) — ${decision.reason}\n`;
60
75
  }
76
+ if (decision.cause === "quota-exceeded") {
77
+ const reset = formatResetDate(decision.resetsAt);
78
+ const override = decision.forceOverride && !decision.forceOverride.allowed
79
+ ? "Override: not allowed by your policy"
80
+ : "Override: --dg-force-install";
81
+ return `Quota hit${reset ? ` — resets ${reset}` : ""}\n${override}\n`;
82
+ }
61
83
  const verifiedBad = VERIFIED_BAD.has(decision.cause);
62
84
  const headline = HEADLINES[decision.cause];
63
85
  const lines = [
@@ -83,3 +105,11 @@ export function renderInstallDecision(decision) {
83
105
  }
84
106
  return `${lines.join("\n")}\n`;
85
107
  }
108
+ export function formatResetDate(iso) {
109
+ if (!iso)
110
+ return undefined;
111
+ const date = new Date(iso);
112
+ if (Number.isNaN(date.getTime()))
113
+ return undefined;
114
+ return `${String(date.getUTCMonth() + 1).padStart(2, "0")}/${String(date.getUTCDate()).padStart(2, "0")}`;
115
+ }
@@ -0,0 +1,21 @@
1
+ export function parsePipReportInstallCount(stdout) {
2
+ const trimmed = stdout.trim();
3
+ if (!trimmed)
4
+ return undefined;
5
+ const candidates = [trimmed];
6
+ const brace = trimmed.indexOf("{");
7
+ if (brace > 0)
8
+ candidates.push(trimmed.slice(brace));
9
+ for (const candidate of candidates) {
10
+ try {
11
+ const parsed = JSON.parse(candidate);
12
+ if (Array.isArray(parsed.install)) {
13
+ return parsed.install.length;
14
+ }
15
+ }
16
+ catch {
17
+ continue;
18
+ }
19
+ }
20
+ return undefined;
21
+ }
@@ -4,13 +4,15 @@ import { constants as osConstants } from "node:os";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { EXIT_UNAVAILABLE } from "../commands/types.js";
6
6
  import { loadUserConfig } from "../config/settings.js";
7
- import { describeBlockedInstall, renderInstallDecision } from "../install-ui/block-render.js";
7
+ import { describeBlockedInstall, describeFlaggedWarn, renderInstallDecision } from "../install-ui/block-render.js";
8
8
  import { enforceProtectedInstall } from "../proxy/enforcement.js";
9
- import { isCiEnv } from "../presentation/mode.js";
9
+ import { isCiEnv, resolvePresentation } from "../presentation/mode.js";
10
+ import { createTheme } from "../presentation/theme.js";
10
11
  import { readProxySessionState } from "../proxy/server.js";
11
12
  import { cleanupSessionSync, createSessionSync, resolveDgPaths } from "../state/index.js";
12
13
  import { classifyPackageManagerInvocation } from "./classify.js";
13
14
  import { buildProxyChildEnv } from "./env.js";
15
+ import { parsePipReportInstallCount } from "./pip-report.js";
14
16
  import { createStreamRedactor, redactSecrets } from "./output-redaction.js";
15
17
  import { resolveRealBinary } from "./resolve-real-binary.js";
16
18
  export const EXIT_INSTALL_BLOCKED = 2;
@@ -122,7 +124,7 @@ async function runWithProductionProxy(plan, args, options) {
122
124
  return {
123
125
  exitCode: EXIT_INSTALL_BLOCKED,
124
126
  stdout: streamedOut(child.stdout, options),
125
- stderr: `${streamedErr(child.stderr, options)}${cacheOnlyNotice(plan.classification.manager)}`
127
+ stderr: `${streamedErr(child.stderr, options)}${cacheOnlyNotice(installOutcome(child.stdout).length > 0)}`
126
128
  };
127
129
  }
128
130
  return {
@@ -136,9 +138,11 @@ async function runWithProductionProxy(plan, args, options) {
136
138
  stopProxyWorker(proxy);
137
139
  }
138
140
  }
139
- export function deriveLiveView(state, phase) {
141
+ export function deriveLiveView(state, phase, resolvedTotal) {
140
142
  const verified = state.decisions.filter((decision) => decision.action === "pass").length;
141
- const flagged = state.decisions.filter((decision) => decision.action === "warn").length;
143
+ const warnDecisions = state.decisions.filter((decision) => decision.action === "warn");
144
+ const flagged = warnDecisions.length;
145
+ const flaggedItems = warnDecisions.map(describeFlaggedWarn);
142
146
  const blocked = state.decisions.find((decision) => decision.action === "block");
143
147
  const current = state.inflight[state.inflight.length - 1];
144
148
  return {
@@ -146,10 +150,51 @@ export function deriveLiveView(state, phase) {
146
150
  total: state.decisions.length + state.inflight.length,
147
151
  verified,
148
152
  flagged,
153
+ ...(flaggedItems.length > 0 ? { flaggedItems } : {}),
154
+ ...(resolvedTotal !== undefined ? { resolvedTotal } : {}),
149
155
  ...(current ? { current } : {}),
150
156
  ...(blocked ? { blocked: describeBlockedInstall(blocked) } : {})
151
157
  };
152
158
  }
159
+ function resolvePipInstallTotal(binary, args, env, register) {
160
+ if (!binary)
161
+ return Promise.resolve(undefined);
162
+ return new Promise((resolve) => {
163
+ let stdout = "";
164
+ let settled = false;
165
+ let timer;
166
+ const finish = (value) => {
167
+ if (settled)
168
+ return;
169
+ settled = true;
170
+ if (timer)
171
+ clearTimeout(timer);
172
+ resolve(value);
173
+ };
174
+ let child;
175
+ try {
176
+ child = spawn(binary, [...args, "--dry-run", "--report", "-", "--quiet"], {
177
+ env,
178
+ stdio: ["ignore", "pipe", "ignore"]
179
+ });
180
+ }
181
+ catch {
182
+ finish(undefined);
183
+ return;
184
+ }
185
+ register(child);
186
+ timer = setTimeout(() => {
187
+ try {
188
+ child.kill();
189
+ }
190
+ catch { /* already exited */ }
191
+ finish(undefined);
192
+ }, 30_000);
193
+ child.stdout?.on("data", (chunk) => { stdout += chunk.toString("utf8"); });
194
+ child.on("error", () => finish(undefined));
195
+ child.on("close", (code) => finish(code === 0 ? parsePipReportInstallCount(stdout) : undefined));
196
+ });
197
+ }
153
198
  export async function runWithProductionProxyLive(plan, args, options, onView) {
154
199
  if (options.onStdout || options.onStderr) {
155
200
  throw new Error("live install mode renders its own UI and owns the terminal; streaming output callbacks are not supported");
@@ -169,8 +214,15 @@ export async function runWithProductionProxyLive(plan, args, options, onView) {
169
214
  cacheDir: `${proxy.session.dir}/pm-cache`
170
215
  });
171
216
  const spawner = options.spawner ?? defaultSpawner;
217
+ let resolvedTotal;
218
+ let dryRunChild;
219
+ if (plan.classification.manager === "pip") {
220
+ void resolvePipInstallTotal(plan.realBinary.path ?? "", args, childEnv, (child) => { dryRunChild = child; })
221
+ .then((count) => { resolvedTotal = count; })
222
+ .catch(() => undefined);
223
+ }
172
224
  const poll = setInterval(() => {
173
- onView(deriveLiveView(readProxySessionState(proxy.session), "scanning"));
225
+ onView(deriveLiveView(readProxySessionState(proxy.session), "scanning", resolvedTotal));
174
226
  }, 90);
175
227
  let finished;
176
228
  try {
@@ -182,9 +234,15 @@ export async function runWithProductionProxyLive(plan, args, options, onView) {
182
234
  }
183
235
  finally {
184
236
  clearInterval(poll);
237
+ if (dryRunChild) {
238
+ try {
239
+ dryRunChild.kill();
240
+ }
241
+ catch { /* already exited */ }
242
+ }
185
243
  }
186
244
  const proxyState = readProxySessionState(proxy.session);
187
- onView(deriveLiveView(proxyState, "done"));
245
+ onView(deriveLiveView(proxyState, "done", resolvedTotal));
188
246
  if (proxyState.decisions.some((decision) => decision.action === "block")) {
189
247
  return { exitCode: EXIT_INSTALL_BLOCKED, stdout: "", stderr: "" };
190
248
  }
@@ -196,7 +254,8 @@ export async function runWithProductionProxyLive(plan, args, options, onView) {
196
254
  stderr: `${finished.stderr}\n ? dg did not check this install — ${plan.classification.manager} exited with an error before any package was fetched.\n`
197
255
  };
198
256
  }
199
- return { exitCode: EXIT_INSTALL_BLOCKED, stdout: installOutcome(finished.stdout), stderr: cacheOnlyNotice(plan.classification.manager) };
257
+ const outcome = installOutcome(finished.stdout);
258
+ return { exitCode: EXIT_INSTALL_BLOCKED, stdout: outcome, stderr: cacheOnlyNotice(outcome.length > 0) };
200
259
  }
201
260
  return { exitCode: finished.exitCode, stdout: installOutcome(finished.stdout), stderr: "" };
202
261
  }
@@ -205,8 +264,10 @@ export async function runWithProductionProxyLive(plan, args, options, onView) {
205
264
  stopProxyWorker(proxy);
206
265
  }
207
266
  }
208
- function cacheOnlyNotice(manager) {
209
- return ` ? dg could not verify this install — no download reached the firewall.\n ${manager} used a local cache or file, or the packages were already installed, so nothing was fetched to check. The install itself ran; these are not covered by per-command protection. Run 'dg scan' to verify your installed packages.\n`;
267
+ function cacheOnlyNotice(installedFresh) {
268
+ const theme = createTheme(resolvePresentation().color);
269
+ const reason = installedFresh ? "used a saved copy" : "already installed";
270
+ return `\n ${theme.paint("muted", `– Nothing was downloaded, so nothing to verify (${reason}). Run dg scan to check installed packages.`)}\n`;
210
271
  }
211
272
  function installOutcome(stdout) {
212
273
  const lines = stdout.split("\n").filter((line) => /^Successfully installed /.test(line) ||
@@ -33,6 +33,9 @@ export function enforceProtectedInstall(request) {
33
33
  policyMode: policy.mode,
34
34
  reason: proxyVerdict.reason ?? evaluation.reason
35
35
  }, proxyVerdict);
36
+ if (baseDecision.cause === "quota-exceeded" && proxyVerdict.quotaBehavior === "pass") {
37
+ return { ...baseDecision, action: "warn", reason: "over monthly quota — installed unverified per your dashboard setting" };
38
+ }
36
39
  if (baseDecision.action !== "block") {
37
40
  return baseDecision;
38
41
  }
@@ -97,6 +100,8 @@ function withOptionalDecisionFields(decision, verdict) {
97
100
  return {
98
101
  ...decision,
99
102
  ...(verdict.dashboardUrl ? { dashboardUrl: verdict.dashboardUrl } : {}),
100
- ...(verdict.unauthenticated ? { unauthenticated: true } : {})
103
+ ...(verdict.unauthenticated ? { unauthenticated: true } : {}),
104
+ ...(verdict.resetsAt ? { resetsAt: verdict.resetsAt } : {}),
105
+ ...(verdict.quotaBehavior ? { quotaBehavior: verdict.quotaBehavior } : {})
101
106
  };
102
107
  }
@@ -16,6 +16,7 @@ import { authorityFor, connectViaUpstreamProxy, selectUpstreamProxy } from "./up
16
16
  import { redactSecrets } from "../launcher/output-redaction.js";
17
17
  import { envAuthToken } from "../auth/env-token.js";
18
18
  import { identityHeaders } from "../api/analyze.js";
19
+ import { dgVersion } from "../commands/version.js";
19
20
  export async function startProductionHttpProxy(options) {
20
21
  const ca = createEphemeralCertificateAuthority(options.session.files.ca);
21
22
  const state = {
@@ -631,6 +632,7 @@ async function lookupVerdict(options, target, sha256, upstream, identity) {
631
632
  method: "POST",
632
633
  headers: {
633
634
  "Content-Type": "application/json",
635
+ "X-Dg-Version": dgVersion(),
634
636
  ...identityHeaders(options.env)
635
637
  },
636
638
  body: JSON.stringify({
@@ -650,11 +652,14 @@ async function lookupVerdict(options, target, sha256, upstream, identity) {
650
652
  signal: controller.signal
651
653
  });
652
654
  if (response.status === 402 || response.status === 429) {
655
+ const body = (await response.json().catch(() => ({})));
653
656
  return {
654
657
  verdict: "block",
655
658
  packageName: artifactDisplayName(identity),
656
659
  cause: "quota-exceeded",
657
- reason: "You've reached your monthly scan limit. Upgrade at westbayberry.com/pricing or wait for it to reset."
660
+ reason: "You've reached your monthly scan limit. Upgrade at westbayberry.com/pricing or wait for it to reset.",
661
+ ...(typeof body.resetsAt === "string" ? { resetsAt: body.resetsAt } : {}),
662
+ quotaBehavior: body.quotaBehavior === "pass" ? "pass" : "block"
658
663
  };
659
664
  }
660
665
  if (response.status === 401) {
@@ -787,7 +792,7 @@ function scanTarballUploadPolicy(env) {
787
792
  };
788
793
  }
789
794
  function installVerdictTimeoutMs(env) {
790
- return parsePositiveInteger(env.DG_INSTALL_VERDICT_TIMEOUT_MS, 30_000);
795
+ return parsePositiveInteger(env.DG_INSTALL_VERDICT_TIMEOUT_MS, 180_000);
791
796
  }
792
797
  function parsePositiveInteger(value, fallback) {
793
798
  if (!value) {
@@ -12,6 +12,7 @@ import { SetupBanner } from "./components/SetupBanner.js";
12
12
  import { useTerminalSize } from "./hooks/useTerminalSize.js";
13
13
  import { scanExitCode } from "./shims.js";
14
14
  import { enterTui, leaveTui, showCursor } from "./alt-screen.js";
15
+ import { formatResetDate } from "../install-ui/block-render.js";
15
16
  export const App = ({ config, userStatus, scanUsage, setupIssues = [], initialView }) => {
16
17
  const { state, scanSelectedProjects, restartSelection } = useScan(config);
17
18
  const { exit } = useApp();
@@ -128,8 +129,8 @@ export const App = ({ config, userStatus, scanUsage, setupIssues = [], initialVi
128
129
  case "selecting":
129
130
  return (_jsx(ProjectSelector, { projects: state.projects, onConfirm: scanSelectedProjects, onCancel: () => { process.exitCode = 0; leaveAltScreen(); exit(); }, userStatus: userStatus }));
130
131
  case "scanning":
131
- return (_jsx(ProgressBar, { value: state.done, total: state.total, label: state.currentBatch.length > 0
132
- ? state.currentBatch[state.currentBatch.length - 1]
132
+ return (_jsx(ProgressBar, { value: state.done, total: state.total, label: state.batchCount > 1 && state.batchIndex >= 1
133
+ ? `batch ${state.batchIndex}/${state.batchCount}`
133
134
  : undefined }));
134
135
  case "results":
135
136
  return (_jsx(InteractiveResultsView, { result: state.result, config: config, durationMs: state.durationMs, onExit: handleResultsExit, onBack: restartSelection ?? undefined, discoveredTotal: state.discoveredTotal, userStatus: userStatus, scanUsage: scanUsage, initialView: initialView }));
@@ -143,7 +144,7 @@ export const App = ({ config, userStatus, scanUsage, setupIssues = [], initialVi
143
144
  hasKey = !!getStoredApiKey();
144
145
  }
145
146
  catch { /* ignore — best-effort */ }
146
- return (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [hasKey ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: "yellow", bold: true, children: "Your session expired." }), _jsx(Text, { children: " " }), _jsxs(Text, { children: ["Run ", _jsx(Text, { color: "cyan", bold: true, children: "dg logout" }), " then ", _jsx(Text, { color: "cyan", bold: true, children: "dg login" }), " to re-authenticate."] })] })) : state.capReason === "prefix_cap" ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: "yellow", bold: true, children: "Too many anonymous devices from your network this month." }), _jsxs(Text, { children: ["Sign in with ", _jsx(Text, { color: "cyan", bold: true, children: "dg login" }), " to keep scanning."] })] })) : (_jsxs(_Fragment, { children: [_jsxs(Text, { color: "yellow", bold: true, children: ["Free monthly limit reached (", state.scansUsed.toLocaleString(), "/", state.maxScans.toLocaleString(), " packages)."] }), _jsxs(Text, { children: ["Upgrade to Pro with ", _jsx(Text, { color: "cyan", bold: true, children: "dg upgrade" }), " for 250k packages/month."] })] })), _jsx(Text, { children: " " }), _jsx(Text, { dimColor: true, children: "[q] quit" })] }));
147
+ return (_jsxs(Box, { flexDirection: "column", paddingLeft: 2, children: [hasKey ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: "yellow", bold: true, children: "Your session expired." }), _jsx(Text, { children: " " }), _jsxs(Text, { children: ["Run ", _jsx(Text, { color: "cyan", bold: true, children: "dg logout" }), " then ", _jsx(Text, { color: "cyan", bold: true, children: "dg login" }), " to re-authenticate."] })] })) : state.capReason === "prefix_cap" ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: "yellow", bold: true, children: "Too many anonymous devices from your network this month." }), _jsxs(Text, { children: ["Sign in with ", _jsx(Text, { color: "cyan", bold: true, children: "dg login" }), " to keep scanning."] })] })) : (_jsxs(_Fragment, { children: [_jsxs(Text, { color: "yellow", bold: true, children: ["Free monthly limit reached (", state.scansUsed.toLocaleString(), "/", state.maxScans.toLocaleString(), " packages)."] }), formatResetDate(state.resetsAt) ? _jsxs(Text, { dimColor: true, children: ["Resets ", formatResetDate(state.resetsAt), "."] }) : null, _jsxs(Text, { children: ["Upgrade to Pro with ", _jsx(Text, { color: "cyan", bold: true, children: "dg upgrade" }), " for 250k packages/month."] })] })), _jsx(Text, { children: " " }), _jsx(Text, { dimColor: true, children: "[q] quit" })] }));
147
148
  }
148
149
  }
149
150
  })();
@@ -47,7 +47,7 @@ function isYankedIncomplete(pkg) {
47
47
  }
48
48
  export function packageBadge(pkg) {
49
49
  if (isYankedIncomplete(pkg))
50
- return { label: "Removed", color: chalk.yellow };
50
+ return { label: "Unverified", color: chalk.yellow };
51
51
  return actionBadge(pkg.action);
52
52
  }
53
53
  const EVIDENCE_LIMIT = 2;
@@ -855,6 +855,10 @@ export const InteractiveResultsView = ({ result, config: _config, durationMs, on
855
855
  }
856
856
  else if (key.return) {
857
857
  setSearchMode(false);
858
+ if (groups.length === 0) {
859
+ setSearchQuery("");
860
+ dispatchView({ type: "MOVE", cursor: 0, viewport: 0 });
861
+ }
858
862
  }
859
863
  else if (key.backspace || key.delete) {
860
864
  setSearchQuery(prev => prev.slice(0, -1));
@@ -1104,7 +1108,7 @@ export const InteractiveResultsView = ({ result, config: _config, durationMs, on
1104
1108
  : chalk.yellow;
1105
1109
  const arrow = level === "summary" ? "\u25BE" : "\u25B8"; // ▾ expanded, ▸ collapsed
1106
1110
  return (_jsxs(Box, { flexDirection: "column", children: [isCursor ? (_jsxs(Text, { backgroundColor: "#1a1a2e", children: [chalk.cyan("\u258C"), " ", chalk.cyan(arrow), " ", ` `, color(pad(label, 8)), chalk.bold(pad(truncate(names, nameCol - 2), nameCol)), lcColor(pad(lcStr, lcCol)), color(scoreStr.padStart(3)), " "] })) : (_jsxs(Text, { children: [` ${chalk.dim(arrow)} `, color(pad(label, 8)), pad(truncate(names, nameCol - 2), nameCol), lcColor(pad(lcStr, lcCol)), color(scoreStr.padStart(3))] })), level === "summary" && (_jsx(FindingsSummary, { group: group, maxWidth: innerWidth - 8, maxLines: globalIdx === view.expandedIndex ? animVisibleLines : undefined }))] }, group.key));
1107
- }), belowCount > 0 && (_jsxs(Text, { dimColor: true, children: [chalk.cyan(" \u2193"), " ", belowCount, " more below"] }))] })] })), _jsx(Text, { dimColor: true, children: chalk.dim("\u2500".repeat(Math.max(20, termCols - 4))) }), _jsxs(Box, { flexDirection: "column", paddingLeft: 1, paddingRight: 1, width: "100%", children: [discoveredTotal !== undefined && discoveredTotal > total && (_jsxs(Text, { dimColor: true, children: ["Scanned ", total, " of ", discoveredTotal, " packages"] })), _jsxs(Box, { justifyContent: "space-between", children: [clean.length > 0 ? (_jsxs(Text, { children: [chalk.green("\u2713"), " ", chalk.green.bold(String(clean.length)), " ", chalk.dim(`package${clean.length !== 1 ? "s" : ""} passed with score 0`), " ", chalk.dim(`\u00b7 ${(durationMs / 1000).toFixed(1)}s`)] })) : (_jsxs(Text, { dimColor: true, children: [(durationMs / 1000).toFixed(1), "s"] })), result.freeScansRemaining !== undefined && (_jsx(Text, { dimColor: true, children: "Free tier \u00B7 dg login for higher scan limits" }))] })] }), _jsx(Text, { dimColor: true, children: chalk.dim("\u2500".repeat(Math.max(20, termCols - 4))) }), searchMode ? (_jsxs(Text, { children: [" ", chalk.bold.cyan("/"), " ", searchQuery, chalk.cyan("\u2588"), " ", chalk.dim("Esc clear")] })) : (_jsxs(Text, { children: [" ", groups.length > 0 && (_jsxs(_Fragment, { children: [chalk.bold.cyan("\u2191\u2193"), " ", chalk.dim("navigate"), " ", chalk.bold.cyan("\u23CE"), " ", chalk.dim("expand"), " ", chalk.bold.cyan("/"), " ", chalk.dim("search"), " "] })), chalk.bold.cyan("l"), " ", chalk.dim("licenses"), " ", chalk.bold.cyan("e"), " ", chalk.dim("export"), " ", onBack && _jsxs(_Fragment, { children: [chalk.bold.cyan("Esc"), " ", chalk.dim("back"), " "] }), chalk.bold.cyan("q"), " ", chalk.dim("quit"), " ", chalk.dim("\u00B7 Ctrl+C or q to exit"), exportMsg && _jsxs(_Fragment, { children: [" ", chalk.green(exportMsg)] })] }))] }));
1111
+ }), belowCount > 0 && (_jsxs(Text, { dimColor: true, children: [chalk.cyan(" \u2193"), " ", belowCount, " more below"] }))] })] })), searchQuery && groups.length === 0 && (_jsx(Text, { dimColor: true, children: ` No flagged packages match "${searchQuery}"` })), _jsx(Text, { dimColor: true, children: chalk.dim("\u2500".repeat(Math.max(20, termCols - 4))) }), _jsxs(Box, { flexDirection: "column", paddingLeft: 1, paddingRight: 1, width: "100%", children: [discoveredTotal !== undefined && discoveredTotal > total && (_jsxs(Text, { dimColor: true, children: ["Scanned ", total, " of ", discoveredTotal, " packages"] })), _jsxs(Box, { justifyContent: "space-between", children: [clean.length > 0 ? (_jsxs(Text, { children: [chalk.green("\u2713"), " ", chalk.green.bold(String(clean.length)), " ", chalk.dim(`package${clean.length !== 1 ? "s" : ""} passed with score 0`), " ", chalk.dim(`\u00b7 ${(durationMs / 1000).toFixed(1)}s`)] })) : (_jsxs(Text, { dimColor: true, children: [(durationMs / 1000).toFixed(1), "s"] })), result.freeScansRemaining !== undefined && (_jsx(Text, { dimColor: true, children: "Free tier \u00B7 dg login for higher scan limits" }))] })] }), _jsx(Text, { dimColor: true, children: chalk.dim("\u2500".repeat(Math.max(20, termCols - 4))) }), searchMode ? (_jsxs(Text, { children: [" ", chalk.bold.cyan("/"), " ", searchQuery, chalk.cyan("\u2588"), " ", chalk.dim("Esc clear")] })) : (_jsxs(Text, { children: [" ", allGroupCount > 0 && (_jsxs(_Fragment, { children: [chalk.bold.cyan("\u2191\u2193"), " ", chalk.dim("navigate"), " ", chalk.bold.cyan("\u23CE"), " ", chalk.dim("expand"), " ", chalk.bold.cyan("/"), " ", chalk.dim("search"), " "] })), chalk.bold.cyan("l"), " ", chalk.dim("licenses"), " ", chalk.bold.cyan("e"), " ", chalk.dim("export"), " ", onBack && _jsxs(_Fragment, { children: [chalk.bold.cyan("Esc"), " ", chalk.dim("back"), " "] }), chalk.bold.cyan("q"), " ", chalk.dim("quit"), " ", chalk.dim("\u00B7 Ctrl+C or q to exit"), exportMsg && _jsxs(_Fragment, { children: [" ", chalk.green(exportMsg)] })] }))] }));
1108
1112
  };
1109
1113
  const T = {
1110
1114
  branch: chalk.dim("\u251C\u2500\u2500"),
@@ -21,9 +21,10 @@ export function truncate(s, max) {
21
21
  export function groupPackages(packages, keyBy = "name") {
22
22
  const map = new Map();
23
23
  for (const pkg of packages) {
24
+ const action = pkg.action ?? "pass";
24
25
  const fingerprint = pkg.findings.length === 0
25
- ? `__clean_${pkg.score}`
26
- : pkg.findings
26
+ ? `${action}|${pkg.name}@${pkg.version ?? ""}|score:${pkg.score}`
27
+ : `${action}|` + pkg.findings
27
28
  .map((f) => `${f.category ?? ""}:${f.severity}`)
28
29
  .sort()
29
30
  .join("|") + `|score:${pkg.score}`;
@@ -9,11 +9,11 @@ function reducer(_state, action) {
9
9
  case "DISCOVERY_PROGRESS":
10
10
  return { phase: "discovering", path: action.path, found: action.found };
11
11
  case "DISCOVERY_COMPLETE":
12
- return { phase: "scanning", done: 0, total: action.total, currentBatch: [] };
12
+ return { phase: "scanning", done: 0, total: action.total, batchIndex: 0, batchCount: 1 };
13
13
  case "DISCOVERY_EMPTY":
14
14
  return { phase: "empty", message: action.message };
15
15
  case "SCAN_PROGRESS":
16
- return { phase: "scanning", done: action.done, total: action.total, currentBatch: action.currentBatch };
16
+ return { phase: "scanning", done: action.done, total: action.total, batchIndex: action.batchIndex, batchCount: action.batchCount };
17
17
  case "SCAN_COMPLETE":
18
18
  return {
19
19
  phase: "results",
@@ -25,7 +25,13 @@ function reducer(_state, action) {
25
25
  case "ERROR":
26
26
  return { phase: "error", error: action.error };
27
27
  case "FREE_CAP_REACHED":
28
- return { phase: "free_cap_reached", scansUsed: action.scansUsed, maxScans: action.maxScans, capReason: action.capReason };
28
+ return {
29
+ phase: "free_cap_reached",
30
+ scansUsed: action.scansUsed,
31
+ maxScans: action.maxScans,
32
+ capReason: action.capReason,
33
+ ...(action.resetsAt ? { resetsAt: action.resetsAt } : {})
34
+ };
29
35
  }
30
36
  }
31
37
  export function useScan(config) {
@@ -83,8 +89,8 @@ async function scanProjects(projects, dispatch) {
83
89
  const base = completed;
84
90
  responses.push(await analyzePackages(packages, {
85
91
  ecosystem,
86
- onProgress: (done, _ecosystemTotal, currentBatch) => {
87
- dispatch({ type: "SCAN_PROGRESS", done: base + done, total, currentBatch: [...currentBatch] });
92
+ onProgress: (progress) => {
93
+ dispatch({ type: "SCAN_PROGRESS", done: base + progress.done, total, batchIndex: progress.batchIndex, batchCount: progress.batchCount });
88
94
  }
89
95
  }));
90
96
  completed = base + packages.length;
@@ -104,7 +110,8 @@ async function scanProjects(projects, dispatch) {
104
110
  type: "FREE_CAP_REACHED",
105
111
  scansUsed: body.scansUsed ?? 0,
106
112
  maxScans: body.maxScans ?? 0,
107
- capReason: body.reason === "prefix_cap" ? "prefix_cap" : "monthly_limit"
113
+ capReason: body.reason === "prefix_cap" ? "prefix_cap" : "monthly_limit",
114
+ ...(typeof body.resetsAt === "string" ? { resetsAt: body.resetsAt } : {})
108
115
  });
109
116
  return;
110
117
  }
@@ -844,7 +844,7 @@ function pathPrecedenceCheck(env, shimDir, functionsPresent) {
844
844
  message: `${shimDir} precedes the real package-manager directories on PATH`
845
845
  };
846
846
  }
847
- function currentShellActivation(env) {
847
+ export function currentShellActivation(env = process.env) {
848
848
  const shell = resolveShell("auto", env);
849
849
  const homeDir = resolveDgPaths(env).homeDir;
850
850
  const rcPath = shellRcPath(homeDir, shell);
@@ -245,44 +245,73 @@ function parsePackageLock(text) {
245
245
  return [malformedLockfileObservation("package-lock.json", new Error("root must be an object"))];
246
246
  }
247
247
  const observations = [];
248
- const packages = isRecord(parsed.packages) ? parsed.packages : {};
249
- for (const [path, rawPackage] of Object.entries(packages)) {
250
- if (path.length === 0 || !isRecord(rawPackage)) {
251
- continue;
252
- }
253
- const name = typeof rawPackage.name === "string" ? rawPackage.name : packageNameFromNodeModulesPath(path);
254
- const version = typeof rawPackage.version === "string" ? rawPackage.version : null;
255
- if (!name) {
256
- continue;
248
+ if (isRecord(parsed.packages)) {
249
+ for (const [path, rawPackage] of Object.entries(parsed.packages)) {
250
+ if (path.length === 0 || !isRecord(rawPackage) || rawPackage.link === true) {
251
+ continue;
252
+ }
253
+ const declaredName = typeof rawPackage.name === "string" ? rawPackage.name : packageNameFromNodeModulesPath(path);
254
+ const alias = npmAliasVersion(stringOrNull(rawPackage.version));
255
+ const name = alias?.name ?? declaredName;
256
+ const version = alias?.version ?? (typeof rawPackage.version === "string" ? rawPackage.version : null);
257
+ if (!name) {
258
+ continue;
259
+ }
260
+ observations.push(lockfileObservation({
261
+ ecosystem: "npm",
262
+ name,
263
+ version,
264
+ requested: path,
265
+ sourceKind: "lockfile",
266
+ resolvedUrl: stringOrNull(rawPackage.resolved),
267
+ integrity: stringOrNull(rawPackage.integrity),
268
+ license: stringOrNull(rawPackage.license)
269
+ }));
257
270
  }
258
- observations.push(lockfileObservation({
259
- ecosystem: "npm",
260
- name,
261
- version,
262
- requested: path,
263
- sourceKind: "lockfile",
264
- resolvedUrl: stringOrNull(rawPackage.resolved),
265
- integrity: stringOrNull(rawPackage.integrity),
266
- license: stringOrNull(rawPackage.license)
267
- }));
271
+ return observations;
268
272
  }
269
- const dependencies = isRecord(parsed.dependencies) ? parsed.dependencies : {};
273
+ if (isRecord(parsed.dependencies)) {
274
+ walkLegacyDependencies(parsed.dependencies, observations, new Set());
275
+ }
276
+ return observations;
277
+ }
278
+ function walkLegacyDependencies(dependencies, observations, seen) {
270
279
  for (const [name, rawPackage] of Object.entries(dependencies)) {
271
- if (!isRecord(rawPackage) || observations.some((observation) => observation.identity.name === name)) {
280
+ if (!isRecord(rawPackage) || rawPackage.bundled === true) {
272
281
  continue;
273
282
  }
274
- observations.push(lockfileObservation({
275
- ecosystem: "npm",
276
- name,
277
- version: stringOrNull(rawPackage.version),
278
- requested: name,
279
- sourceKind: "lockfile",
280
- resolvedUrl: stringOrNull(rawPackage.resolved),
281
- integrity: stringOrNull(rawPackage.integrity),
282
- license: stringOrNull(rawPackage.license)
283
- }));
283
+ const alias = npmAliasVersion(stringOrNull(rawPackage.version));
284
+ const resolvedName = alias?.name ?? name;
285
+ const version = alias?.version ?? stringOrNull(rawPackage.version);
286
+ const key = `${resolvedName}@${version ?? ""}`;
287
+ if (!seen.has(key)) {
288
+ seen.add(key);
289
+ observations.push(lockfileObservation({
290
+ ecosystem: "npm",
291
+ name: resolvedName,
292
+ version,
293
+ requested: name,
294
+ sourceKind: "lockfile",
295
+ resolvedUrl: stringOrNull(rawPackage.resolved),
296
+ integrity: stringOrNull(rawPackage.integrity),
297
+ license: stringOrNull(rawPackage.license)
298
+ }));
299
+ }
300
+ if (isRecord(rawPackage.dependencies)) {
301
+ walkLegacyDependencies(rawPackage.dependencies, observations, seen);
302
+ }
284
303
  }
285
- return observations;
304
+ }
305
+ function npmAliasVersion(version) {
306
+ if (!version || !version.startsWith("npm:")) {
307
+ return null;
308
+ }
309
+ const spec = version.slice(4);
310
+ const at = spec.startsWith("@") ? spec.indexOf("@", 1) : spec.indexOf("@");
311
+ if (at <= 0) {
312
+ return { name: spec, version: null };
313
+ }
314
+ return { name: spec.slice(0, at), version: spec.slice(at + 1) || null };
286
315
  }
287
316
  function parseYarnLock(text) {
288
317
  const observations = [];
@@ -293,22 +322,23 @@ function parseYarnLock(text) {
293
322
  if (!header) {
294
323
  continue;
295
324
  }
325
+ if (header.startsWith("#") || header === "__metadata") {
326
+ continue;
327
+ }
296
328
  const requested = header.split(",")[0]?.trim().replace(/^"|"$/gu, "") ?? header;
297
329
  const name = packageNameFromYarnDescriptor(requested);
298
- if (!name) {
330
+ const version = quotedValue(lines, "version");
331
+ if (!name || !version) {
299
332
  continue;
300
333
  }
301
- const version = quotedValue(lines, "version");
302
- const resolvedUrl = quotedValue(lines, "resolved");
303
- const integrity = quotedValue(lines, "integrity");
304
334
  observations.push(lockfileObservation({
305
335
  ecosystem: "npm",
306
336
  name,
307
337
  version,
308
338
  requested,
309
339
  sourceKind: "lockfile",
310
- resolvedUrl,
311
- integrity,
340
+ resolvedUrl: quotedValue(lines, "resolved"),
341
+ integrity: quotedValue(lines, "integrity") ?? quotedValue(lines, "checksum"),
312
342
  license: null
313
343
  }));
314
344
  }
@@ -317,23 +347,33 @@ function parseYarnLock(text) {
317
347
  function parsePnpmLock(text) {
318
348
  const observations = [];
319
349
  const lines = text.split(/\r?\n/u);
350
+ let inPackages = false;
320
351
  let current = null;
352
+ const flush = () => {
353
+ if (current) {
354
+ observations.push(lockfileObservation(current));
355
+ current = null;
356
+ }
357
+ };
321
358
  for (const line of lines) {
322
- const packageMatch = /^\s{2}['"]?(?:\/)?((?:@[^/\s]+\/)?[^@\s:'"]+)@([^:\s'"]+)['"]?:\s*$/u.exec(line);
323
- if (packageMatch?.[1] && packageMatch[2]) {
324
- if (current) {
325
- observations.push(lockfileObservation(current));
326
- }
327
- current = {
328
- ecosystem: "npm",
329
- name: packageMatch[1],
330
- version: packageMatch[2],
331
- requested: `${packageMatch[1]}@${packageMatch[2]}`,
332
- sourceKind: "lockfile",
333
- resolvedUrl: null,
334
- integrity: null,
335
- license: null
336
- };
359
+ const sectionMatch = /^([A-Za-z][\w-]*):\s*$/u.exec(line);
360
+ if (sectionMatch) {
361
+ flush();
362
+ // The `snapshots:` section keys the resolved peer graph, e.g.
363
+ // `eslint-utils@4.9.1(eslint@9.39.4)` — the peer suffix is not a real
364
+ // registry version, so scanning it yields a false "removed from
365
+ // registry" verdict. `packages:` is the canonical inventory (carries
366
+ // integrity); take identity only from there.
367
+ inPackages = sectionMatch[1] === "packages";
368
+ continue;
369
+ }
370
+ if (!inPackages) {
371
+ continue;
372
+ }
373
+ const keyMatch = /^\s{2}(\S.*?):\s*$/u.exec(line);
374
+ if (keyMatch?.[1]) {
375
+ flush();
376
+ current = parsePnpmPackageKey(keyMatch[1]);
337
377
  continue;
338
378
  }
339
379
  if (!current) {
@@ -354,24 +394,69 @@ function parsePnpmLock(text) {
354
394
  };
355
395
  }
356
396
  }
357
- if (current) {
358
- observations.push(lockfileObservation(current));
359
- }
397
+ flush();
360
398
  return observations;
361
399
  }
400
+ function parsePnpmPackageKey(rawKey) {
401
+ const key = stripQuotes(rawKey.trim());
402
+ if (/(?:file|link|workspace|git\+|git:|https?):/u.test(key)) {
403
+ return null;
404
+ }
405
+ const hadSlash = key.startsWith("/");
406
+ const body = hadSlash ? key.slice(1) : key;
407
+ let name = null;
408
+ let version = null;
409
+ if (hadSlash) {
410
+ // lockfileVersion 5.x keys are /<name>/<version>[_peer]; the version
411
+ // follows the final slash and the name may itself be scoped (two slashes).
412
+ const lastSlash = body.lastIndexOf("/");
413
+ if (lastSlash > 0) {
414
+ name = body.slice(0, lastSlash);
415
+ version = stripPnpmPeerSuffix(body.slice(lastSlash + 1));
416
+ }
417
+ }
418
+ else {
419
+ const atForm = /^((?:@[^/\s]+\/)?[^@\s]+)@(.+)$/u.exec(body);
420
+ if (atForm?.[1] && atForm[2]) {
421
+ name = atForm[1];
422
+ version = stripPnpmPeerSuffix(atForm[2]);
423
+ }
424
+ }
425
+ if (!name || !version) {
426
+ return null;
427
+ }
428
+ return {
429
+ ecosystem: "npm",
430
+ name,
431
+ version,
432
+ requested: `${name}@${version}`,
433
+ sourceKind: "lockfile",
434
+ resolvedUrl: null,
435
+ integrity: null,
436
+ license: null
437
+ };
438
+ }
439
+ function stripPnpmPeerSuffix(version) {
440
+ const peerStart = version.search(/[(_]/u);
441
+ return peerStart === -1 ? version : version.slice(0, peerStart);
442
+ }
362
443
  function parseRequirements(text) {
363
- return text.split(/\r?\n/u)
364
- .map((line) => line.trim())
365
- .filter((line) => line.length > 0 && !line.startsWith("#"))
366
- .map((line) => {
367
- if (REMOTE_SPEC_PREFIXES.some((prefix) => line.toLowerCase().startsWith(prefix))) {
368
- return packageObservation({
444
+ const observations = [];
445
+ for (const logical of joinRequirementContinuations(text.split(/\r?\n/u))) {
446
+ const line = logical.trim();
447
+ if (line.length === 0 || line.startsWith("#")) {
448
+ continue;
449
+ }
450
+ const editable = /^(?:-e|--editable)[=\s]+(.+)$/u.exec(line);
451
+ const target = (editable?.[1] ?? line).trim();
452
+ if (REMOTE_SPEC_PREFIXES.some((prefix) => target.toLowerCase().startsWith(prefix))) {
453
+ observations.push(packageObservation({
369
454
  ecosystem: "pypi",
370
- name: line,
455
+ name: target,
371
456
  version: null,
372
457
  requested: line,
373
458
  sourceKind: "lockfile-url-fallback",
374
- resolvedUrl: line,
459
+ resolvedUrl: target,
375
460
  integrity: null,
376
461
  license: null
377
462
  }, "block", {
@@ -379,15 +464,20 @@ function parseRequirements(text) {
379
464
  title: "Lockfile URL fallback identity",
380
465
  message: "lockfile entry uses a URL without package identity or hash metadata",
381
466
  location: line
382
- });
467
+ }));
468
+ continue;
383
469
  }
384
- const hash = /--hash=([A-Za-z0-9:-]+)/u.exec(line)?.[1] ?? null;
385
- const cleanLine = line.replace(/\s+--hash=[^\s]+/gu, "");
386
- const match = /^([A-Za-z0-9_.-]+)(?:==([^;\s]+))?/u.exec(cleanLine);
470
+ if (line.startsWith("-") || /^\.{0,2}\//u.test(target)) {
471
+ continue;
472
+ }
473
+ const hash = /--hash=([A-Za-z0-9:_-]+)/u.exec(line)?.[1] ?? null;
474
+ const requirement = line.replace(/\s*--hash=[^\s]+/gu, "").trim();
475
+ const match = /^([A-Za-z0-9._-]+)(?:\[[^\]]*\])?(?:\s*==\s*([^;\s]+))?/u.exec(requirement);
387
476
  if (!match?.[1]) {
388
- return blockedUnknownSpec(line);
477
+ observations.push(blockedUnknownSpec(line));
478
+ continue;
389
479
  }
390
- return lockfileObservation({
480
+ observations.push(lockfileObservation({
391
481
  ecosystem: "pypi",
392
482
  name: match[1],
393
483
  version: match[2] ?? null,
@@ -396,8 +486,25 @@ function parseRequirements(text) {
396
486
  resolvedUrl: null,
397
487
  integrity: hash,
398
488
  license: null
399
- });
400
- });
489
+ }));
490
+ }
491
+ return observations;
492
+ }
493
+ function joinRequirementContinuations(lines) {
494
+ const joined = [];
495
+ let buffer = "";
496
+ for (const line of lines) {
497
+ if (line.endsWith("\\")) {
498
+ buffer += `${line.slice(0, -1)} `;
499
+ continue;
500
+ }
501
+ joined.push(buffer + line);
502
+ buffer = "";
503
+ }
504
+ if (buffer.length > 0) {
505
+ joined.push(buffer);
506
+ }
507
+ return joined;
401
508
  }
402
509
  function parseCargoLock(text) {
403
510
  return lockBlocks(text, "[[package]]").map((block) => {
@@ -426,7 +533,7 @@ function parsePoetryLock(text) {
426
533
  requested: `${name}==${version ?? "unknown"}`,
427
534
  sourceKind: "lockfile",
428
535
  resolvedUrl: null,
429
- integrity: null,
536
+ integrity: /hash\s*=\s*"([^"]+)"/u.exec(block)?.[1] ?? null,
430
537
  license: tomlString(block, "license")
431
538
  });
432
539
  }).filter((observation) => observation.identity.name !== "unknown");
@@ -588,7 +695,8 @@ function isExactVersion(version) {
588
695
  }
589
696
  function isSupportedIntegrity(value) {
590
697
  return /^(?:sha256|sha384|sha512)-[A-Za-z0-9+/=]+$/u.test(value)
591
- || /^(?:sha256:)?[a-f0-9]{64}$/iu.test(value);
698
+ || /^(?:sha256:)?[a-f0-9]{64}$/iu.test(value)
699
+ || /^[0-9a-f]+\/[0-9a-f]{64,}$/iu.test(value);
592
700
  }
593
701
  function isUnsafeResolvedUrl(value) {
594
702
  const lower = value.toLowerCase();
@@ -657,13 +765,18 @@ function packageNameFromNodeModulesPath(path) {
657
765
  return first;
658
766
  }
659
767
  function packageNameFromYarnDescriptor(descriptor) {
660
- const value = descriptor.startsWith("@") ? descriptor.slice(1) : descriptor;
661
- const index = value.lastIndexOf("@");
662
- const name = descriptor.startsWith("@") ? `@${value.slice(0, index)}` : value.slice(0, index);
663
- return name || null;
768
+ const scoped = descriptor.startsWith("@");
769
+ const body = scoped ? descriptor.slice(1) : descriptor;
770
+ const at = body.indexOf("@");
771
+ const name = at === -1 ? descriptor : scoped ? `@${body.slice(0, at)}` : body.slice(0, at);
772
+ const spec = at === -1 ? "" : body.slice(at + 1);
773
+ // npm: alias descriptors (`alias@npm:real-pkg@range`) resolve to the alias
774
+ // target — that is the registry artifact actually fetched and scanned.
775
+ const alias = /^npm:((?:@[^/\s]+\/)?[^@\s]+)@/u.exec(spec);
776
+ return alias?.[1] ?? (name || null);
664
777
  }
665
778
  function quotedValue(lines, key) {
666
- const pattern = new RegExp(`^\\s*${key}\\s+\"?([^\"\\n]+)\"?\\s*$`, "u");
779
+ const pattern = new RegExp(`^\\s*${key}:?\\s+"?([^"\\n]+?)"?\\s*$`, "u");
667
780
  for (const line of lines) {
668
781
  const match = pattern.exec(line);
669
782
  if (match?.[1]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@westbayberry/dg",
3
- "version": "2.0.4",
3
+ "version": "2.0.6",
4
4
  "description": "Dependency Guardian supply-chain firewall CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -40,7 +40,7 @@
40
40
  "typescript": "5.8.3",
41
41
  "vitest": "3.1.4"
42
42
  },
43
- "license": "UNLICENSED",
43
+ "license": "Apache-2.0",
44
44
  "private": false,
45
45
  "dependencies": {
46
46
  "chalk": "4.1.2",