Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2201,6 +2201,15 @@ async function runMarkBuild(args: ParsedArgs): Promise<number> {

const buildDirOptions = { framework: stack?.framework ?? null, buildScript: readBuildScript(cwd) };
const dir = resolveBuildDir(cwd, getStringFlag(args.flags, 'dir'), buildDirOptions);
if (dir === null && stack?.framework === 'next' && existsSync(path.join(cwd, '.next'))) {
// A Next.js build that is not a static export writes `.next/`, which holds no page files to mark:
// its documents are produced per request. Said as that, not as a directory that could not be found.
console.warn('mark-build: found .next/, a server-rendered Next.js build with no HTML files to mark.');
console.warn('mark-build: run `npx @patchstack/connect guide` to see what your main layout needs.');
await reportBuildStamp(reported, wirePayload, 'no-pages');
return 0;
}

if (dir === null) {
// Loud, and specific: this runs as a postbuild hook whose output scrolls past, and a build that
// finished with nothing stamped is exactly what a published site with no production marker looks
Expand Down Expand Up @@ -2503,15 +2512,28 @@ async function runCommand(args: ParsedArgs): Promise<number> {
}
}

/**
* Ends the process with `code`.
*
* On Windows the process is left to end on its own once its work is done, because exiting while a
* network connection is still closing aborts Node there with an assertion that reads as a crash. The
* timer is the backstop for anything that would keep it alive, and does not itself keep it alive.
*/
function finish(code: number): void {
if (process.platform !== 'win32') process.exit(code);
process.exitCode = code;
setTimeout(() => process.exit(code), 3000).unref();
}

main()
.then((code) => process.exit(code))
.then((code) => finish(code))
.catch((err: unknown) => {
if (err instanceof PatchstackError) {
const plain = plainErrorMessage(err);
console.error(`${plain ?? err.message} (${err.code})`);
if (plain !== null && verbose) console.error(`Detail: ${err.message}`);
process.exit(1);
return finish(1);
}
console.error('Unexpected error:', err);
process.exit(2);
finish(2);
});
37 changes: 32 additions & 5 deletions src/parsers/consistency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,30 @@ import type { PackageEntry } from '../types.js';
* their absence from a parsed set says nothing about staleness. Returns []
* when package.json is missing or unreadable (nothing to validate against).
*/
/**
* A dependency package.json declares. `aliasOf` is the package an npm alias (`"zod4": "npm:zod@^4"`)
* installs: the lockfile and the installed tree name it by its own name, not by the key it is declared
* under, so either name in a source means the dependency is there.
*/
export interface DeclaredDependency {
name: string;
aliasOf?: string;
}

/** The package an `npm:` alias specifier installs, or null for any other specifier. */
function aliasTarget(spec: unknown): string | null {
if (typeof spec !== 'string' || !spec.startsWith('npm:')) return null;
const target = spec.slice('npm:'.length);
const versionAt = target.lastIndexOf('@');
const name = versionAt > 0 ? target.slice(0, versionAt) : target;
return name.length > 0 ? name : null;
}

export async function readDeclaredDependencyNames(cwd: string): Promise<string[]> {
return (await readDeclaredDependencies(cwd)).map((dependency) => dependency.name);
}

export async function readDeclaredDependencies(cwd: string): Promise<DeclaredDependency[]> {
let raw: string;
try {
raw = await readFile(path.join(cwd, 'package.json'), 'utf8');
Expand All @@ -27,7 +50,7 @@ export async function readDeclaredDependencyNames(cwd: string): Promise<string[]
return [];
}

const names = new Set<string>();
const declared = new Map<string, DeclaredDependency>();
// `optionalDependencies` included: they are installed when the platform supports them, they can be
// vulnerable, and leaving them out meant a lockfile that omitted one still read as complete.
for (const group of ['dependencies', 'devDependencies', 'optionalDependencies'] as const) {
Expand All @@ -39,11 +62,12 @@ export async function readDeclaredDependencyNames(cwd: string): Promise<string[]
if (typeof spec === 'string' && /^(file|link|workspace|portal):/.test(spec)) {
continue;
}
names.add(name);
const aliasOf = aliasTarget(spec);
declared.set(name, aliasOf !== null && aliasOf !== name ? { name, aliasOf } : { name });
}
}

return [...names];
return [...declared.values()];
}

/**
Expand All @@ -52,9 +76,12 @@ export async function readDeclaredDependencyNames(cwd: string): Promise<string[]
* e.g. `npm install` planted a package-lock.json once and the platform's
* native package manager (bun on Lovable) never updates it again.
*/
export function missingDependencies(declared: string[], packages: PackageEntry[]): string[] {
export function missingDependencies(declared: Array<string | DeclaredDependency>, packages: PackageEntry[]): string[] {
const present = new Set(packages.map((entry) => entry.name));
return declared.filter((name) => !present.has(name));
return declared
.map((dependency) => (typeof dependency === 'string' ? { name: dependency } : dependency))
.filter(({ name, aliasOf }: DeclaredDependency) => !present.has(name) && !(aliasOf !== undefined && present.has(aliasOf)))
.map(({ name }) => name);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/parsers/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { access } from 'node:fs/promises';
import path from 'node:path';
import { PatchstackError, type Manifest, type PackageEntry } from '../types.js';
import { disagreements, missingDependencies, readDeclaredDependencyNames } from './consistency.js';
import { disagreements, missingDependencies, readDeclaredDependencies, type DeclaredDependency } from './consistency.js';
import { parseBunLockfile } from './bun.js';
import { parseNpmLockfile } from './npm.js';
import { walkNodeModules } from './node_modules.js';
Expand Down Expand Up @@ -87,7 +87,7 @@ export async function scanLockfile(cwd: string): Promise<Manifest> {
// package-lock.json once on a bun-managed platform (Lovable), and the native
// dependency flow never updates it again. Trusting it would freeze the
// manifest and the build fingerprint while the real dependency set drifts.
const declared = await readDeclaredDependencyNames(cwd);
const declared = await readDeclaredDependencies(cwd);
const warnings: string[] = [];
let firstParsed: { packages: PackageEntry[]; filename: string } | null = null;
// The installed tree, if some lockfile already routed us to it (a `bun.lockb` cannot be read, so it
Expand Down Expand Up @@ -192,7 +192,7 @@ function manifestWith(packages: PackageEntry[], warnings: string[]): Manifest {
function otherCompleteSources(
all: Array<{ packages: PackageEntry[]; filename: string }>,
current: { filename: string },
declared: string[],
declared: DeclaredDependency[],
): Array<{ packages: PackageEntry[]; filename: string }> {
return all.filter(
(source) => source.filename !== current.filename && missingDependencies(declared, source.packages).length === 0,
Expand Down
15 changes: 14 additions & 1 deletion src/protect/install/reporting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { join } from 'node:path';

import { reportingState, explainReportingState } from '../reporting-state.js';
import type { VerifyCheck } from './types.js';
import { read, hasResolvableCredential, isSiteUuid, findSiteUuidUp } from './util.js';
import { read, hasResolvableCredential, envFileNamingCredential, isSiteUuid, findSiteUuidUp } from './util.js';

/**
* The site identity the guard would run with, resolved the way the guard resolves it.
Expand Down Expand Up @@ -101,6 +101,19 @@ export function reportingChecks(cwd: string, env: Record<string, string | undefi
'settled answer. This also only judges the environment it ran in — a deployment may set an ' +
'opt-out this machine cannot see.',
});
} else if (state === 'unavailable-no-credential' && envFileNamingCredential(cwd) !== null) {
// No credential in this command's environment, and one in a file the app's framework loads at
// start. Calling reporting off would describe this command, not the app.
const file = envFileNamingCredential(cwd);
checks.push({
group: 'reporting',
label: `detection reporting cannot be judged from here (the key is set in ${file}, which this command does not load)`,
ok: true,
unverifiable: true,
hint:
`an app whose framework loads ${file} has the key and reports; one that does not load it has no ` +
'key and reports nothing. Read `protection.detectionReporting` in the running app for the settled answer.',
});
} else {
// Decided before the rule origin mattered, so this is the state, not a guess. Said in the label
// because a passing check does not print its hint, and an opt-out is a choice rather than a fault.
Expand Down
18 changes: 18 additions & 0 deletions src/protect/install/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,24 @@ export function hasResolvableCredential(
return false;
}

/**
* The env file in this project that sets a Patchstack credential, if one does.
*
* A file like this is loaded by the app's framework when the app starts, not by this command, so a key
* that lives only there is in the running app's environment and absent from this one. Only whether it
* is set is read; the value is not.
*/
export function envFileNamingCredential(cwd: string): string | null {
for (const file of ['.env.production.local', '.env.local', '.env.production', '.env']) {
try {
if (/^[ \t]*(?:export[ \t]+)?PATCHSTACK_(?:API_KEY|PULSE_AUTH)[ \t]*=[ \t]*\S/m.test(read(join(cwd, file)))) return file;
} catch {
// Absent or unreadable — the next candidate.
}
}
return null;
}

const SITE_UUID_PLACEHOLDER = '__PATCHSTACK_SITE_UUID__';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

Expand Down
25 changes: 25 additions & 0 deletions tests/bin-invocation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,31 @@ describe.skipIf(!built)('the packaged bin, invoked as npm invokes it', () => {
}
}

it('says a Next.js server build has no pages to mark, rather than that no build was found', () => {
const dir = mkdtempSync(path.join(tmpdir(), 'ps-next-mark-'));
try {
writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'probe', version: '1.0.0', dependencies: { next: '16.0.0' } }));
writeFileSync(
path.join(dir, 'package-lock.json'),
JSON.stringify({
name: 'probe',
version: '1.0.0',
lockfileVersion: 3,
packages: { '': { name: 'probe', version: '1.0.0', dependencies: { next: '16.0.0' } }, 'node_modules/next': { version: '16.0.0' } },
}),
);
mkdirSync(path.join(dir, '.next'));

const result = spawnSync(process.execPath, [bin, 'mark-build'], { cwd: dir, encoding: 'utf8' });

expect(result.status).toBe(0);
expect(result.stderr).toContain('found .next/, a server-rendered Next.js build');
expect(result.stderr).not.toContain('no build output directory found');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

it('prints its help through a symlinked path', () => {
const { stdout } = runThroughSymlink(['--help']);

Expand Down
20 changes: 19 additions & 1 deletion tests/parsers/bun-and-source-selection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { join } from 'node:path';
import { parseBunLockfile } from '../../src/parsers/bun.js';
import { walkNodeModules } from '../../src/parsers/node_modules.js';
import { scanLockfile } from '../../src/parsers/index.js';
import { disagreements, readDeclaredDependencyNames } from '../../src/parsers/consistency.js';
import { disagreements, missingDependencies, readDeclaredDependencies, readDeclaredDependencyNames } from '../../src/parsers/consistency.js';
import { extractName } from '../../src/parsers/yarn.js';

/**
Expand Down Expand Up @@ -267,6 +267,24 @@ describe('what counts as a declared dependency', () => {
expect((await readDeclaredDependencyNames(cwd)).sort()).toEqual(['a', 'b']);
});

it('finds an npm alias under the name of the package it installs', async () => {
// "zod4": "npm:zod@^4" is installed and locked as `zod`, so a list that names `zod` has it.
const cwd = project({
'package.json': JSON.stringify({
name: 'probe',
dependencies: { zod4: 'npm:zod@^4.4.3', scoped: 'npm:@scope/real@1.0.0', a: '^1.0.0' },
}),
});
const declared = await readDeclaredDependencies(cwd);

expect(declared).toEqual([{ name: 'zod4', aliasOf: 'zod' }, { name: 'scoped', aliasOf: '@scope/real' }, { name: 'a' }]);
const entry = (name: string) => ({ name, version: '1.0.0' });
expect(missingDependencies(declared, [entry('zod'), entry('@scope/real'), entry('a')])).toEqual([]);
// A source that lists the alias under its declared key has it too.
expect(missingDependencies(declared, [entry('zod4'), entry('scoped'), entry('a')])).toEqual([]);
expect(missingDependencies(declared, [entry('a')])).toEqual(['zod4', 'scoped']);
});

it('still excludes a non-registry specifier', async () => {
// The lockfile parsers skip those, so their absence says nothing about staleness.
const cwd = project({
Expand Down
24 changes: 24 additions & 0 deletions tests/protect-check-reporting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,30 @@ const find = (checks: ReturnType<typeof reportingChecks>, fragment: string) => {
return hit!;
};

describe('a key that lives in an env file', () => {
it('is not called missing, because the app loads that file and this command does not', () => {
const dir = project({ siteUuid: UUID });
writeFileSync(join(dir, '.env'), 'OTHER=1\nPATCHSTACK_API_KEY=example-not-a-key\n');

const checks = reportingChecks(dir, {});
const reporting = find(checks, 'cannot be judged from here');

expect(reporting.ok).toBe(true);
expect(reporting.unverifiable).toBe(true);
expect(reporting.label).toContain('.env');
// The file is named; what it holds is not.
expect(JSON.stringify(checks)).not.toContain('example-not-a-key');
expect(checks.some((c) => c.label.includes('reporting is off'))).toBe(false);
});

it('still says there is no credential when the env file only mentions the name', () => {
const dir = project({ siteUuid: UUID });
writeFileSync(join(dir, '.env'), '# PATCHSTACK_API_KEY=\nPATCHSTACK_API_KEY=\n');

expect(find(reportingChecks(dir, {}), 'reporting is off').label).toContain('unavailable-no-credential');
});
});

describe('what it can answer', () => {
it('says an app is not enrolled, and what that costs', () => {
const checks = reportingChecks(project(), {});
Expand Down