From b6188a53f80b80d5694e0ef2a1a38f65ff061a6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20Sandstr=C3=B6m?= Date: Tue, 23 Jun 2026 14:25:08 +0200 Subject: [PATCH 1/3] =?UTF-8?q?chore(prettier):=20adopt=20prettier=20?= =?UTF-8?q?=E2=80=94=20config,=20scripts,=20CI=20format=20gate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add .prettierrc matching the codebase style (double quotes, semis, 2-space, trailing commas, printWidth 100) and .prettierignore (dist, conflict copies, data) - add format / format:check npm scripts - add a Format check step to CI (runs before lint) - prettier as a dev-only dependency (published package stays zero-runtime-dep) No eslint formatting-rule conflicts exist, so eslint-config-prettier is not needed. Co-Authored-By: Claude Opus 4.8 --- .github/workflows/ci.yml | 3 +++ .prettierignore | 15 +++++++++++++++ .prettierrc | 8 ++++++++ package-lock.json | 17 +++++++++++++++++ package.json | 5 ++++- 5 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 .prettierignore create mode 100644 .prettierrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f5fc667..473030fe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,6 +25,9 @@ jobs: - name: Install dependencies run: npm ci + - name: Format check + run: npm run format:check + - name: Lint run: npm run lint diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..6f0d4e40 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,15 @@ +# Build output / deps +dist/ +**/dist/ +node_modules/ +**/node_modules/ +coverage/ + +# Cloud-sync conflict copies (also gitignored / ignored by eslint) +**/* 2.ts +* 2.* + +# Generated / data files — not source, formatting adds churn without value +*.jsonl +package-lock.json +.kit/ diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000..00aaf2d6 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,8 @@ +{ + "semi": true, + "singleQuote": false, + "tabWidth": 2, + "trailingComma": "all", + "printWidth": 100, + "arrowParens": "always" +} diff --git a/package-lock.json b/package-lock.json index fe02d395..9d4838f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ "@types/node": "22.19.15", "eslint": "^9.39.4", "globals": "^17.6.0", + "prettier": "^3.8.4", "tsx": "^4.22.4", "typescript": "5.9.3", "typescript-eslint": "^8.61.1" @@ -2462,6 +2463,22 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.8.4", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.4.tgz", + "integrity": "sha512-N2MylSdi48+5N/6S5j+maeHbUSIzzZ5uOcX5Hm4QpV8Dkb1HFjfAKTKX6yNPJQD9AhcT3ifHNB66tWTTJDi11Q==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "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/prettier/prettier?sponsor=1" + } + }, "node_modules/proxy-addr": { "version": "2.0.7", "license": "MIT", diff --git a/package.json b/package.json index 157ac31e..06050535 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,9 @@ "prepublishOnly": "npm run build:prod", "dev": "tsx src/cli.ts", "test": "KIT_NON_INTERACTIVE=1 KIT_BUMBLEBEE=0 KIT_NO_FAILURE_SIM=1 KIT_NO_UPDATE_CHECK=1 node --test --test-timeout=180000 --test-concurrency=2 dist/*.test.js dist/**/*.test.js", - "lint": "eslint src" + "lint": "eslint src", + "format": "prettier --write \"**/*.ts\"", + "format:check": "prettier --check \"**/*.ts\"" }, "dependencies": { "@modelcontextprotocol/sdk": "1.29.0", @@ -44,6 +46,7 @@ "@types/node": "22.19.15", "eslint": "^9.39.4", "globals": "^17.6.0", + "prettier": "^3.8.4", "tsx": "^4.22.4", "typescript": "5.9.3", "typescript-eslint": "^8.61.1" From 49f28e900a6a6c1bdf8893d699e9ee1cd574c787 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20Sandstr=C3=B6m?= Date: Tue, 23 Jun 2026 14:27:42 +0200 Subject: [PATCH 2/3] style: format codebase with prettier MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mechanical reformat (`prettier --write`) — whitespace only, no behaviour change. Recorded in .git-blame-ignore-revs in the following commit so `git blame` skips it. Co-Authored-By: Claude Opus 4.8 --- examples/cdn-cache-headers.ts | 144 +- examples/team-management-workflows.ts | 25 +- .../kit-plugin-cloudflare/src/mgmt-api.ts | 4 +- packages/kit-plugin-fly/src/mgmt-api.ts | 15 +- packages/kit-plugin-github/src/mgmt-api.ts | 24 +- .../src/railway-deploy.test.ts | 8 +- .../kit-plugin-railway/src/railway-deploy.ts | 2 +- .../kit-plugin-sentry/src/mgmt-api.test.ts | 5 +- packages/kit-plugin-sentry/src/mgmt-api.ts | 48 +- packages/kit-plugin-snyk/src/scan.test.ts | 15 +- packages/kit-plugin-snyk/src/scan.ts | 7 +- .../kit-plugin-stripe/src/mgmt-api.test.ts | 10 +- packages/kit-plugin-stripe/src/mgmt-api.ts | 4 +- packages/kit-plugin-supabase/src/mgmt-api.ts | 35 +- packages/kit-plugin-vercel/src/mgmt-api.ts | 17 +- packages/kit-plugin-wiz/src/scan.test.ts | 20 +- packages/kit-plugin-wiz/src/scan.ts | 4 +- src/adapters-analytics.test.ts | 29 +- src/adapters-jobs.test.ts | 73 +- src/adapters-new.test.ts | 62 +- src/adapters/cloudflare-r2.ts | 15 +- src/adapters/expo-eas.ts | 26 +- src/adapters/flyio-hosting.ts | 10 +- src/adapters/ingest.test.ts | 20 +- src/adapters/ingest.ts | 5 +- src/adapters/liveblocks-realtime.ts | 3 +- src/adapters/neon-db.ts | 8 +- src/adapters/planetscale-db.ts | 5 +- src/adapters/railway-hosting.ts | 3 +- src/adapters/resend-email.ts | 9 +- src/adapters/searxng-instance.ts | 85 +- src/adapters/sentry-monitoring.ts | 6 +- src/adapters/stripe-payments.ts | 86 +- src/adapters/supabase-db.ts | 34 +- src/adapters/upstash-redis.ts | 6 +- src/adapters/vercel-hosting.ts | 27 +- src/agent-audit.test.ts | 14 +- src/agent-audit.ts | 78 +- src/agent-config.test.ts | 22 +- src/agent-config.ts | 40 +- src/analyze.ts | 62 +- src/approval.test.ts | 54 +- src/approval.ts | 23 +- src/audit-secrets.test.ts | 27 +- src/audit-secrets.ts | 12 +- src/audit.ts | 22 +- src/baseline.test.ts | 10 +- src/budget.ts | 31 +- src/bumblebee.ts | 29 +- src/check-design.ts | 22 +- src/check-disk-encryption.ts | 40 +- src/check-gitignore.test.ts | 14 +- src/check-gitignore.ts | 41 +- src/check-hooks.test.ts | 6 +- src/check-hooks.ts | 9 +- src/check-lock.ts | 24 +- src/check-secrets.ts | 133 +- src/check-security.test.ts | 36 +- src/check-security.ts | 269 ++-- src/check-services.ts | 4 +- src/check-skills.ts | 13 +- src/check-tests.ts | 24 +- src/check-tools.test.ts | 5 +- src/check-tools.ts | 5 +- src/check-web-search.test.ts | 40 +- src/check-web-search.ts | 5 +- src/ci.test.ts | 21 +- src/cli-health.test.ts | 8 +- src/cli.test.ts | 73 +- src/cli.ts | 1191 ++++++++++------- src/clone.test.ts | 28 +- src/clone.ts | 1 - src/commands/audit.ts | 19 +- src/commands/auth.ts | 20 +- src/commands/env.ts | 30 +- src/commands/hooks.ts | 72 +- src/commands/mcp.ts | 31 +- src/commands/memory.ts | 946 ++++++------- src/completions.test.ts | 7 +- src/completions.ts | 67 +- src/config.test.ts | 44 +- src/config.ts | 28 +- src/context-lock.test.ts | 101 +- src/context-lock.ts | 185 ++- src/context.test.ts | 5 +- src/context.ts | 2 +- src/cost-monitor.test.ts | 13 +- src/cost-monitor.ts | 38 +- src/create-plugin.test.ts | 31 +- src/create-plugin.ts | 109 +- src/data/top-npm.ts | 110 +- src/database.ts | 8 +- src/doctor.test.ts | 22 +- src/elevation-scopes.test.ts | 5 +- src/elevation.test.ts | 4 +- src/elevation.ts | 37 +- src/env-diff.ts | 6 +- src/env-inspect.ts | 2 +- src/env-switch.test.ts | 5 +- src/env-switch.ts | 8 +- src/environment.test.ts | 21 +- src/environment.ts | 6 +- src/escalate.test.ts | 38 +- src/escalate.ts | 28 +- src/event-stream.ts | 9 +- src/fix.ts | 83 +- src/gha-audit.test.ts | 8 +- src/gha-audit.ts | 34 +- src/governance-middleware.test.ts | 19 +- src/governance-middleware.ts | 51 +- src/governance.ts | 21 +- src/heal.test.ts | 7 +- src/heal.ts | 4 +- .../bitbucket-pipelines.test.ts | 58 +- src/health-sensors/bitbucket-pipelines.ts | 84 +- src/health-sensors/github-actions.test.ts | 148 +- src/health-sensors/gitlab-ci.test.ts | 15 +- src/health-sensors/gitlab-ci.ts | 72 +- src/health-sensors/remote.test.ts | 20 +- src/health-sensors/remote.ts | 5 +- src/health-sensors/resend.ts | 65 +- src/health-sensors/sentry.test.ts | 5 +- src/health-sensors/sentry.ts | 63 +- src/health-sensors/supabase-advisor.test.ts | 10 +- src/health-sensors/supabase-advisor.ts | 63 +- src/health-sensors/tls-cert.ts | 62 +- src/health-sensors/vercel.test.ts | 23 +- src/health-sensors/vercel.ts | 77 +- src/health-track.test.ts | 9 +- src/health.test.ts | 44 +- src/hooks.test.ts | 29 +- src/hooks.ts | 16 +- src/install.test.ts | 28 +- src/install.ts | 1 - src/lock.test.ts | 15 +- src/lock.ts | 29 +- src/login.test.ts | 42 +- src/login.ts | 7 +- src/mcp-orchestrator.ts | 15 +- src/mcp-server.test.ts | 46 +- src/mcp-server.ts | 154 ++- src/memory/amazonq.ts | 13 +- src/memory/cline.ts | 7 +- src/memory/codex.test.ts | 18 +- src/memory/continue.test.ts | 5 +- src/memory/db.ts | 25 +- src/memory/gemini.test.ts | 30 +- src/memory/hook.ts | 9 +- src/memory/install.test.ts | 10 +- src/memory/install.ts | 14 +- src/memory/merge.test.ts | 7 +- src/memory/pal.test.ts | 23 +- src/memory/parser.test.ts | 6 +- src/memory/scan.test.ts | 12 +- src/memory/shared.test.ts | 21 +- src/memory/shared.ts | 8 +- src/memory/threads.ts | 11 +- src/neon-clerk.test.ts | 19 +- src/onepassword.test.ts | 6 +- src/onepassword.ts | 19 +- src/open.test.ts | 12 +- src/open.ts | 6 +- src/output.ts | 108 +- src/pkg.ts | 15 +- src/plugin-loader.test.ts | 36 +- src/plugin-loader.ts | 8 +- src/plugin-registry.test.ts | 16 +- src/plugin-registry.ts | 2 +- src/plugins-cli.ts | 20 +- src/plugins.test.ts | 19 +- src/plugins.ts | 30 +- src/policy.test.ts | 6 +- src/post-pull-audit.test.ts | 18 +- src/post-pull-audit.ts | 24 +- src/provision.test.ts | 20 +- src/provision.ts | 49 +- src/recommended.test.ts | 10 +- src/resend-email.test.ts | 22 +- src/revocation.ts | 14 +- src/rules/catalog.ts | 35 +- src/run.test.ts | 16 +- src/run.ts | 4 +- src/sbom.test.ts | 34 +- src/sbom.ts | 19 +- src/scan-build.test.ts | 20 +- src/scan-build.ts | 22 +- src/scan-plaintext.ts | 10 +- src/scan-staged.test.ts | 8 +- src/scan-staged.ts | 11 +- src/scan-transcripts.test.ts | 10 +- src/scan-transcripts.ts | 15 +- src/scanners.test.ts | 35 +- src/scanners.ts | 19 +- src/secret-backends.test.ts | 19 +- src/secret-backends.ts | 64 +- src/secret-expiration.test.ts | 69 +- src/secret-expiration.ts | 9 +- src/secrets-migrate.test.ts | 15 +- src/secrets-migrate.ts | 7 +- src/secrets-model.ts | 9 +- src/secrets-onecli.test.ts | 6 +- src/secrets-onecli.ts | 7 +- src/secrets-propagate.test.ts | 5 +- src/secrets-propagate.ts | 32 +- src/secrets-pull.ts | 12 +- src/secrets-purge-history.test.ts | 2 +- src/secrets-purge-history.ts | 21 +- src/secrets-rotate-cli.ts | 93 +- src/secrets-service.test.ts | 24 +- src/secrets-sync.ts | 31 +- src/secrets-validate.test.ts | 12 +- src/secrets-validate.ts | 15 +- src/secrets-vault-migrate.ts | 102 +- src/secrets.test.ts | 12 +- src/secrets.ts | 6 +- src/security-policy.test.ts | 5 +- src/security-policy.ts | 27 +- src/security-prescan.test.ts | 139 +- src/security-prescan.ts | 303 +++-- src/sentinel.test.ts | 28 +- src/sentinel.ts | 25 +- src/service-auth.test.ts | 15 +- src/service-auth.ts | 3 +- src/service-registry.test.ts | 23 +- src/service-registry.ts | 23 +- src/skills.ts | 9 +- src/stack-detector.test.ts | 94 +- src/stack-detector.ts | 13 +- src/status.test.ts | 17 +- src/status.ts | 3 +- src/supply-chain.test.ts | 33 +- src/supply-chain.ts | 104 +- src/toml-generator.test.ts | 52 +- src/toml-generator.ts | 42 +- src/triage-gate.test.ts | 22 +- src/triage-gate.ts | 40 +- src/triage.ts | 7 +- src/update-check.ts | 8 +- src/upstash-cloudflare.test.ts | 14 +- src/utils/didYouMean.ts | 4 +- src/utils/promptSelect.ts | 37 +- src/utils/redactSecrets.test.ts | 8 +- src/utils/redactSecrets.ts | 5 +- src/validation/dynamic-schema.ts | 11 +- src/vault-meta.test.ts | 5 +- src/vault-meta.ts | 7 +- 246 files changed, 5523 insertions(+), 3955 deletions(-) diff --git a/examples/cdn-cache-headers.ts b/examples/cdn-cache-headers.ts index 4c4b18d6..85c64d44 100644 --- a/examples/cdn-cache-headers.ts +++ b/examples/cdn-cache-headers.ts @@ -5,7 +5,7 @@ * to optimize CloudFront caching behavior. */ -import { NextRequest, NextResponse } from 'next/server'; +import { NextRequest, NextResponse } from "next/server"; // ─── Public API Endpoints (Cacheable) ─────────────────────────────────── @@ -14,9 +14,9 @@ export async function getPublicPlugins(req: NextRequest) { return NextResponse.json(data, { headers: { - 'Cache-Control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=3600', - 'Content-Type': 'application/json', - 'ETag': generateETag(data), + "Cache-Control": "public, max-age=300, s-maxage=600, stale-while-revalidate=3600", + "Content-Type": "application/json", + ETag: generateETag(data), }, }); } @@ -27,24 +27,24 @@ export async function getPluginDetails(req: NextRequest, { slug }: { slug: strin return NextResponse.json(plugin, { headers: { // Cache for 1 hour, allow stale content for up to 1 day - 'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400', - 'Content-Type': 'application/json', - 'ETag': generateETag(plugin), - 'Last-Modified': new Date(plugin.updatedAt).toUTCString(), + "Cache-Control": "public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400", + "Content-Type": "application/json", + ETag: generateETag(plugin), + "Last-Modified": new Date(plugin.updatedAt).toUTCString(), }, }); } export async function searchPlugins(req: NextRequest) { - const query = req.nextUrl.searchParams.get('q'); + const query = req.nextUrl.searchParams.get("q"); const results = await searchPluginsByQuery(query!); return NextResponse.json(results, { headers: { // Search results cached, but include query string in cache key - 'Cache-Control': 'public, max-age=300, s-maxage=600, stale-while-revalidate=3600', - 'Content-Type': 'application/json', - 'Vary': 'Accept-Encoding, Accept-Language', + "Cache-Control": "public, max-age=300, s-maxage=600, stale-while-revalidate=3600", + "Content-Type": "application/json", + Vary: "Accept-Encoding, Accept-Language", }, }); } @@ -55,15 +55,15 @@ export async function getUserProfile(req: NextRequest) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } return NextResponse.json(user, { headers: { // Cache user data briefly (1 minute) - 'Cache-Control': 'private, max-age=60, s-maxage=300', - 'Content-Type': 'application/json', - 'Vary': 'Authorization, Cookie', + "Cache-Control": "private, max-age=60, s-maxage=300", + "Content-Type": "application/json", + Vary: "Authorization, Cookie", }, }); } @@ -72,7 +72,7 @@ export async function getUserPlugins(req: NextRequest) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } const plugins = await fetchUserPlugins(user.id); @@ -80,9 +80,9 @@ export async function getUserPlugins(req: NextRequest) { return NextResponse.json(plugins, { headers: { // User's plugins cached briefly with authorization context - 'Cache-Control': 'private, max-age=60, s-maxage=300', - 'Content-Type': 'application/json', - 'Vary': 'Authorization, Cookie, X-User-ID', + "Cache-Control": "private, max-age=60, s-maxage=300", + "Content-Type": "application/json", + Vary: "Authorization, Cookie, X-User-ID", }, }); } @@ -91,7 +91,7 @@ export async function getUserSettings(req: NextRequest) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } const settings = await fetchUserSettings(user.id); @@ -99,9 +99,9 @@ export async function getUserSettings(req: NextRequest) { return NextResponse.json(settings, { headers: { // Settings cached very briefly - 'Cache-Control': 'private, max-age=30, s-maxage=60', - 'Content-Type': 'application/json', - 'Vary': 'Authorization, Cookie', + "Cache-Control": "private, max-age=30, s-maxage=60", + "Content-Type": "application/json", + Vary: "Authorization, Cookie", }, }); } @@ -112,7 +112,7 @@ export async function createPlugin(req: NextRequest) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } const body = await req.json(); @@ -122,22 +122,19 @@ export async function createPlugin(req: NextRequest) { status: 201, headers: { // Never cache write operations - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0', - 'Content-Type': 'application/json', + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", + "Content-Type": "application/json", }, }); } -export async function updatePluginSettings( - req: NextRequest, - { id }: { id: string } -) { +export async function updatePluginSettings(req: NextRequest, { id }: { id: string }) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } const body = await req.json(); @@ -146,10 +143,10 @@ export async function updatePluginSettings( return NextResponse.json(plugin, { headers: { // Never cache write operations - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0', - 'Content-Type': 'application/json', + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", + "Content-Type": "application/json", }, }); } @@ -158,7 +155,7 @@ export async function deletePlugin(req: NextRequest, { id }: { id: string }) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } await deletePluginById(id); @@ -167,9 +164,9 @@ export async function deletePlugin(req: NextRequest, { id }: { id: string }) { status: 204, headers: { // Never cache delete operations - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0', + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", }, }); } @@ -180,17 +177,20 @@ export async function login(req: NextRequest) { const body = await req.json(); const { token, user } = await authenticateUser(body.email, body.password); - return NextResponse.json({ token, user }, { - status: 200, - headers: { - // Never cache auth responses - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0', - 'Set-Cookie': `authToken=${token}; Path=/; HttpOnly; Secure; SameSite=Strict`, - 'Content-Type': 'application/json', + return NextResponse.json( + { token, user }, + { + status: 200, + headers: { + // Never cache auth responses + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", + "Set-Cookie": `authToken=${token}; Path=/; HttpOnly; Secure; SameSite=Strict`, + "Content-Type": "application/json", + }, }, - }); + ); } export async function logout(req: NextRequest) { @@ -198,10 +198,10 @@ export async function logout(req: NextRequest) { status: 200, headers: { // Never cache logout - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0', - 'Set-Cookie': 'authToken=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0', + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", + "Set-Cookie": "authToken=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0", }, }); } @@ -210,34 +210,34 @@ export async function refreshToken(req: NextRequest) { const user = await getCurrentUser(req); if (!user) { - return new NextResponse('Unauthorized', { status: 401 }); + return new NextResponse("Unauthorized", { status: 401 }); } const newToken = await generateNewToken(user.id); - return NextResponse.json({ token: newToken }, { - headers: { - // Never cache token refresh - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0', - 'Content-Type': 'application/json', + return NextResponse.json( + { token: newToken }, + { + headers: { + // Never cache token refresh + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", + "Content-Type": "application/json", + }, }, - }); + ); } // ─── Utility Functions ──────────────────────────────────────────────── function generateETag(data: any): string { - const hash = require('crypto') - .createHash('md5') - .update(JSON.stringify(data)) - .digest('hex'); + const hash = require("crypto").createHash("md5").update(JSON.stringify(data)).digest("hex"); return `"${hash}"`; } async function getCurrentUser(req: NextRequest) { - const token = req.headers.get('authorization')?.split(' ')[1]; + const token = req.headers.get("authorization")?.split(" ")[1]; if (!token) { return null; @@ -280,11 +280,11 @@ async function deletePluginById(id: string) { } async function authenticateUser(email: string, password: string) { - return { token: '', user: {} }; + return { token: "", user: {} }; } async function generateNewToken(userId: string) { - return ''; + return ""; } async function verifyToken(token: string) { diff --git a/examples/team-management-workflows.ts b/examples/team-management-workflows.ts index 14249bf1..75d21ea0 100644 --- a/examples/team-management-workflows.ts +++ b/examples/team-management-workflows.ts @@ -154,13 +154,7 @@ async function managePermissions(teamId: string) { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); console.log(`\nGranting temporary permission (expires tomorrow)...`); - grantPermission( - teamId, - "user-004", - "plugins:install", - "user-001", - tomorrow.toISOString(), - ); + grantPermission(teamId, "user-004", "plugins:install", "user-001", tomorrow.toISOString()); } // ─── Invitations & Onboarding ───────────────────────────────────────── @@ -253,10 +247,7 @@ async function createOrganization() { /** * Example 8: Cross-team member with different roles */ -async function assignCrossTeamRoles( - teamMap: Record, - userId: string, -) { +async function assignCrossTeamRoles(teamMap: Record, userId: string) { console.log(`\nAssigning cross-team roles for ${userId}...\n`); // User is dev in Engineering, but admin of shared services @@ -292,9 +283,7 @@ async function auditTeamActivity(teamId: string) { console.log(`Showing latest 20:\n`); auditLog.logs.forEach((log, i) => { - console.log( - `${i + 1}. [${log.timestamp}] ${log.actor_name} ${log.action} ${log.resource}`, - ); + console.log(`${i + 1}. [${log.timestamp}] ${log.actor_name} ${log.action} ${log.resource}`); console.log(` Resource ID: ${log.resource_id}`); console.log(` Status: ${log.status}`); if (log.details) { @@ -321,9 +310,7 @@ async function checkTeamHealth(teamId: string) { console.log(` Recent audit events: ${m.recent_audit_events}`); // Calculate health score - const healthPercent = Math.round( - (m.active_members_7d / m.total_members) * 100, - ); + const healthPercent = Math.round((m.active_members_7d / m.total_members) * 100); const health = healthPercent > 80 ? "✓ Healthy" : "⚠ Needs attention"; console.log(`\nTeam Health: ${health} (${healthPercent}% active)`); } @@ -385,7 +372,9 @@ async function fullOnboardingWorkflow() { console.log("Step 7: Verifying setup..."); const members = listTeamMembers(teamId); const metrics = getTeamMetrics(teamId); - console.log(`✓ Team ready: ${members.total} members, ${metrics.metrics?.total_permissions} permissions`); + console.log( + `✓ Team ready: ${members.total} members, ${metrics.metrics?.total_permissions} permissions`, + ); } // ─── Export Examples ────────────────────────────────────────────────── diff --git a/packages/kit-plugin-cloudflare/src/mgmt-api.ts b/packages/kit-plugin-cloudflare/src/mgmt-api.ts index ead9aee8..ee25bde7 100644 --- a/packages/kit-plugin-cloudflare/src/mgmt-api.ts +++ b/packages/kit-plugin-cloudflare/src/mgmt-api.ts @@ -76,7 +76,9 @@ async function cfFetch(client: MgmtClient, path: string, init: RequestInit = signal: AbortSignal.timeout(15_000), }); if (!res.ok && res.status !== 404) { - throw new Error(`${init.method ?? "GET"} ${path} returned ${res.status}: ${await safeText(res)}`); + throw new Error( + `${init.method ?? "GET"} ${path} returned ${res.status}: ${await safeText(res)}`, + ); } const envelope = (await res.json()) as CfEnvelope; if (!envelope.success) { diff --git a/packages/kit-plugin-fly/src/mgmt-api.ts b/packages/kit-plugin-fly/src/mgmt-api.ts index e08c5b67..95790da8 100644 --- a/packages/kit-plugin-fly/src/mgmt-api.ts +++ b/packages/kit-plugin-fly/src/mgmt-api.ts @@ -34,9 +34,7 @@ export interface MgmtClient { export function makeClient(cfg: MgmtClientConfig = {}): MgmtClient { const token = cfg.token ?? process.env.FLY_API_TOKEN; if (!token) { - throw new Error( - "FLY_API_TOKEN not set — run `fly auth token` to fetch one", - ); + throw new Error("FLY_API_TOKEN not set — run `fly auth token` to fetch one"); } return { graphqlUrl: cfg.graphqlUrl ?? DEFAULT_GRAPHQL_URL, @@ -49,7 +47,11 @@ export function makeClient(cfg: MgmtClientConfig = {}): MgmtClient { }; } -async function gql(client: MgmtClient, query: string, variables: Record): Promise { +async function gql( + client: MgmtClient, + query: string, + variables: Record, +): Promise { const res = await fetch(client.graphqlUrl, { method: "POST", headers: client.headers, @@ -139,10 +141,7 @@ export interface MachineSummary { region: string; } -export async function listMachines( - client: MgmtClient, - appName: string, -): Promise { +export async function listMachines(client: MgmtClient, appName: string): Promise { const res = await fetch(`${client.machinesUrl}/apps/${encodeURIComponent(appName)}/machines`, { headers: client.headers, signal: AbortSignal.timeout(10_000), diff --git a/packages/kit-plugin-github/src/mgmt-api.ts b/packages/kit-plugin-github/src/mgmt-api.ts index 266cd06d..57eb972c 100644 --- a/packages/kit-plugin-github/src/mgmt-api.ts +++ b/packages/kit-plugin-github/src/mgmt-api.ts @@ -69,10 +69,10 @@ export async function listRepoSecrets( owner: string, repo: string, ): Promise { - const res = await fetch( - `${client.baseUrl}/repos/${owner}/${repo}/actions/secrets`, - { headers: client.headers, signal: AbortSignal.timeout(10_000) }, - ); + const res = await fetch(`${client.baseUrl}/repos/${owner}/${repo}/actions/secrets`, { + headers: client.headers, + signal: AbortSignal.timeout(10_000), + }); if (!res.ok) { throw new Error( `GET /repos/${owner}/${repo}/actions/secrets returned ${res.status}: ${await safeText(res)}`, @@ -92,10 +92,10 @@ async function getRepoPublicKey( owner: string, repo: string, ): Promise { - const res = await fetch( - `${client.baseUrl}/repos/${owner}/${repo}/actions/secrets/public-key`, - { headers: client.headers, signal: AbortSignal.timeout(10_000) }, - ); + const res = await fetch(`${client.baseUrl}/repos/${owner}/${repo}/actions/secrets/public-key`, { + headers: client.headers, + signal: AbortSignal.timeout(10_000), + }); if (!res.ok) { throw new Error(`GET .../public-key returned ${res.status}: ${await safeText(res)}`); } @@ -198,10 +198,10 @@ export async function listDeployKeys( owner: string, repo: string, ): Promise { - const res = await fetch( - `${client.baseUrl}/repos/${owner}/${repo}/keys`, - { headers: client.headers, signal: AbortSignal.timeout(10_000) }, - ); + const res = await fetch(`${client.baseUrl}/repos/${owner}/${repo}/keys`, { + headers: client.headers, + signal: AbortSignal.timeout(10_000), + }); if (!res.ok) { throw new Error(`GET .../keys returned ${res.status}: ${await safeText(res)}`); } diff --git a/packages/kit-plugin-railway/src/railway-deploy.test.ts b/packages/kit-plugin-railway/src/railway-deploy.test.ts index 8b4d1028..9cb5ede3 100644 --- a/packages/kit-plugin-railway/src/railway-deploy.test.ts +++ b/packages/kit-plugin-railway/src/railway-deploy.test.ts @@ -28,7 +28,7 @@ describe("railwayDeployAdapter", () => { mockContext({ RAILWAY_PROJECT_ID: "proj_abc123", RAILWAY_ENVIRONMENT: "staging", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.["RAILWAY_PROJECT_ID"], "proj_abc123"); @@ -38,7 +38,7 @@ describe("railwayDeployAdapter", () => { it("provision uses production as default environment", async () => { const result = await railwayDeployAdapter.provision( - mockContext({ RAILWAY_PROJECT_ID: "proj_abc123" }) + mockContext({ RAILWAY_PROJECT_ID: "proj_abc123" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.["RAILWAY_ENVIRONMENT"], "production"); @@ -47,9 +47,7 @@ describe("railwayDeployAdapter", () => { it("provision returns error when railway login fails", async () => { // railway CLI is not installed in test environment — expect provision to // attempt login and fail gracefully - const result = await railwayDeployAdapter.provision( - mockContext() - ); + const result = await railwayDeployAdapter.provision(mockContext()); // Either login fails (CLI not installed) or init fails — either way, success=false // because we have no project ID and CLI isn't available assert.equal(result.success, false); diff --git a/packages/kit-plugin-railway/src/railway-deploy.ts b/packages/kit-plugin-railway/src/railway-deploy.ts index 8bafcfd1..11ac704d 100644 --- a/packages/kit-plugin-railway/src/railway-deploy.ts +++ b/packages/kit-plugin-railway/src/railway-deploy.ts @@ -6,7 +6,7 @@ const exec = promisify(execFile); async function runRailway( args: string[], - cwd: string + cwd: string, ): Promise<{ ok: boolean; stdout: string; stderr: string }> { try { const { stdout, stderr } = await exec("railway", args, { diff --git a/packages/kit-plugin-sentry/src/mgmt-api.test.ts b/packages/kit-plugin-sentry/src/mgmt-api.test.ts index 9318002c..eed339b5 100644 --- a/packages/kit-plugin-sentry/src/mgmt-api.test.ts +++ b/packages/kit-plugin-sentry/src/mgmt-api.test.ts @@ -66,10 +66,7 @@ describe("listOrganizations (network error path)", () => { describe("searchIssues", () => { it("refuses without an organizationSlug", async () => { const client = makeClient({ token: "x" }); - await assert.rejects( - () => searchIssues(client, {}), - /organizationSlug required/, - ); + await assert.rejects(() => searchIssues(client, {}), /organizationSlug required/); }); it("throws structured error when unreachable", async () => { diff --git a/packages/kit-plugin-sentry/src/mgmt-api.ts b/packages/kit-plugin-sentry/src/mgmt-api.ts index 3304a2f7..99e806d4 100644 --- a/packages/kit-plugin-sentry/src/mgmt-api.ts +++ b/packages/kit-plugin-sentry/src/mgmt-api.ts @@ -108,7 +108,9 @@ export async function listProjects( { headers: client.headers, signal: AbortSignal.timeout(15_000) }, ); if (!res.ok) { - throw new Error(`GET /api/0/organizations/${org}/projects/ returned ${res.status}: ${await safeText(res)}`); + throw new Error( + `GET /api/0/organizations/${org}/projects/ returned ${res.status}: ${await safeText(res)}`, + ); } return (await res.json()) as SentryProject[]; } @@ -162,11 +164,7 @@ export async function searchIssues( return (await res.json()) as SentryIssue[]; } -export type UpdateIssueStatus = - | "resolved" - | "resolvedInNextRelease" - | "unresolved" - | "ignored"; +export type UpdateIssueStatus = "resolved" | "resolvedInNextRelease" | "unresolved" | "ignored"; export interface UpdateIssueOptions { status?: UpdateIssueStatus; @@ -190,15 +188,12 @@ export async function updateIssue( const body: Record = {}; if (opts.status) body.status = opts.status; if (opts.assignedTo) body.assignedTo = opts.assignedTo; - const res = await fetch( - `${client.host}/api/0/issues/${encodeURIComponent(issueId)}/`, - { - method: "PUT", - headers: client.headers, - body: JSON.stringify(body), - signal: AbortSignal.timeout(15_000), - }, - ); + const res = await fetch(`${client.host}/api/0/issues/${encodeURIComponent(issueId)}/`, { + method: "PUT", + headers: client.headers, + body: JSON.stringify(body), + signal: AbortSignal.timeout(15_000), + }); if (!res.ok) { throw new Error(`PUT /api/0/issues/${issueId}/ returned ${res.status}: ${await safeText(res)}`); } @@ -216,21 +211,16 @@ async function postIssueComment( issueId: string, comment: string, ): Promise { - const res = await fetch( - `${client.host}/api/0/issues/${encodeURIComponent(issueId)}/comments/`, - { - method: "POST", - headers: client.headers, - body: JSON.stringify({ text: comment }), - signal: AbortSignal.timeout(15_000), - }, - ); + const res = await fetch(`${client.host}/api/0/issues/${encodeURIComponent(issueId)}/comments/`, { + method: "POST", + headers: client.headers, + body: JSON.stringify({ text: comment }), + signal: AbortSignal.timeout(15_000), + }); if (!res.ok && res.status !== 404) { // 404 happens for issues without the comments-yet endpoint on some // self-hosted versions — treat as soft fail (status was already updated). - console.error( - `Sentry comment POST returned ${res.status}; issue status updated regardless.`, - ); + console.error(`Sentry comment POST returned ${res.status}; issue status updated regardless.`); } } @@ -255,7 +245,9 @@ export async function getIssueEvents( { headers: client.headers, signal: AbortSignal.timeout(15_000) }, ); if (!res.ok) { - throw new Error(`GET /api/0/issues/${issueId}/events/ returned ${res.status}: ${await safeText(res)}`); + throw new Error( + `GET /api/0/issues/${issueId}/events/ returned ${res.status}: ${await safeText(res)}`, + ); } return (await res.json()) as SentryEvent[]; } diff --git a/packages/kit-plugin-snyk/src/scan.test.ts b/packages/kit-plugin-snyk/src/scan.test.ts index 7ecfcae3..63b42cb5 100644 --- a/packages/kit-plugin-snyk/src/scan.test.ts +++ b/packages/kit-plugin-snyk/src/scan.test.ts @@ -3,11 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { - parseSnykJson, - recordSnykFindings, - fetchSnykIssues, -} from "./scan.js"; +import { parseSnykJson, recordSnykFindings, fetchSnykIssues } from "./scan.js"; const SINGLE_PROJECT = JSON.stringify({ ok: false, @@ -31,9 +27,7 @@ const MULTI_PROJECT = JSON.stringify([ { ok: false, projectName: "service-b", - vulnerabilities: [ - { id: "SNYK-PY-DJANGO-9999", title: "SQLi", severity: "critical" }, - ], + vulnerabilities: [{ id: "SNYK-PY-DJANGO-9999", title: "SQLi", severity: "critical" }], }, ]); @@ -97,10 +91,7 @@ describe("fetchSnykIssues", () => { const prev = process.env.SNYK_TOKEN; delete process.env.SNYK_TOKEN; try { - await assert.rejects( - () => fetchSnykIssues({ orgSlug: "demo" }), - /SNYK_TOKEN not set/, - ); + await assert.rejects(() => fetchSnykIssues({ orgSlug: "demo" }), /SNYK_TOKEN not set/); } finally { if (prev !== undefined) process.env.SNYK_TOKEN = prev; } diff --git a/packages/kit-plugin-snyk/src/scan.ts b/packages/kit-plugin-snyk/src/scan.ts index cefbfa9a..a9f6df71 100644 --- a/packages/kit-plugin-snyk/src/scan.ts +++ b/packages/kit-plugin-snyk/src/scan.ts @@ -151,9 +151,7 @@ export interface FetchSnykIssuesOptions { * Read-only Snyk API fetch. Uses `GET /rest/orgs/{org}/issues`. Throws on * unauthorized — caller surfaces to the user instead of silently failing. */ -export async function fetchSnykIssues( - opts: FetchSnykIssuesOptions, -): Promise { +export async function fetchSnykIssues(opts: FetchSnykIssuesOptions): Promise { const token = opts.token ?? process.env.SNYK_TOKEN; if (!token) throw new Error("SNYK_TOKEN not set"); const base = opts.apiBase ?? DEFAULT_API_BASE; @@ -189,7 +187,8 @@ export async function fetchSnykIssues( return { id: iss.id ?? "", title: iss.attributes?.title ?? "(no title)", - severity: (iss.attributes?.effective_severity_level as SnykVulnerability["severity"]) ?? "low", + severity: + (iss.attributes?.effective_severity_level as SnykVulnerability["severity"]) ?? "low", packageName: dep?.package_name, packageVersion: dep?.package_version, }; diff --git a/packages/kit-plugin-stripe/src/mgmt-api.test.ts b/packages/kit-plugin-stripe/src/mgmt-api.test.ts index 6196a2c8..3529bf0a 100644 --- a/packages/kit-plugin-stripe/src/mgmt-api.test.ts +++ b/packages/kit-plugin-stripe/src/mgmt-api.test.ts @@ -41,18 +41,12 @@ describe("assertModeForUrl", () => { it("refuses live key against 127.0.0.1 URL", () => { const client = makeClient({ secretKey: "sk_live_x" }); - assert.throws( - () => assertModeForUrl(client, "http://127.0.0.1:8080/cb"), - /LIVE-mode/, - ); + assert.throws(() => assertModeForUrl(client, "http://127.0.0.1:8080/cb"), /LIVE-mode/); }); it("refuses test key against http:// URL (signature downgrade)", () => { const client = makeClient({ secretKey: "sk_test_x" }); - assert.throws( - () => assertModeForUrl(client, "http://example.com/webhook"), - /non-HTTPS URL/, - ); + assert.throws(() => assertModeForUrl(client, "http://example.com/webhook"), /non-HTTPS URL/); }); it("allows live key against https://example.com", () => { diff --git a/packages/kit-plugin-stripe/src/mgmt-api.ts b/packages/kit-plugin-stripe/src/mgmt-api.ts index c2a7c9f0..074b7e57 100644 --- a/packages/kit-plugin-stripe/src/mgmt-api.ts +++ b/packages/kit-plugin-stripe/src/mgmt-api.ts @@ -43,9 +43,7 @@ export interface MgmtClient { export function makeClient(cfg: MgmtClientConfig = {}): MgmtClient { const secretKey = cfg.secretKey ?? process.env.STRIPE_SECRET_KEY; if (!secretKey) { - throw new Error( - "STRIPE_SECRET_KEY not set — fetch from https://dashboard.stripe.com/apikeys", - ); + throw new Error("STRIPE_SECRET_KEY not set — fetch from https://dashboard.stripe.com/apikeys"); } return { baseUrl: cfg.baseUrl ?? DEFAULT_BASE_URL, diff --git a/packages/kit-plugin-supabase/src/mgmt-api.ts b/packages/kit-plugin-supabase/src/mgmt-api.ts index 2a424df3..bcf3e949 100644 --- a/packages/kit-plugin-supabase/src/mgmt-api.ts +++ b/packages/kit-plugin-supabase/src/mgmt-api.ts @@ -60,7 +60,9 @@ export async function listProjects(client: MgmtClient): Promise { +export async function listApiKeys(client: MgmtClient, projectRef: string): Promise { const res = await fetch(`${client.baseUrl}/v1/projects/${projectRef}/api-keys`, { headers: client.headers, signal: AbortSignal.timeout(10_000), }); if (!res.ok) { - throw new Error(`/v1/projects/${projectRef}/api-keys returned ${res.status}: ${await safeText(res)}`); + throw new Error( + `/v1/projects/${projectRef}/api-keys returned ${res.status}: ${await safeText(res)}`, + ); } return (await res.json()) as ApiKey[]; } @@ -151,24 +152,16 @@ export interface RotateResult { * (anon, service_role, signed URLs, session JWTs) atomically. Use only * when the leak severity warrants a hard cutover. */ -export async function rollJwtSecret( - client: MgmtClient, - projectRef: string, -): Promise { +export async function rollJwtSecret(client: MgmtClient, projectRef: string): Promise { // Endpoint path used by Supabase Dashboard internally (mirrors // "Generate new JWT secret" button in Project Settings → API). - const res = await fetch( - `${client.baseUrl}/v1/projects/${projectRef}/config/jwt-secret/roll`, - { - method: "POST", - headers: client.headers, - signal: AbortSignal.timeout(30_000), - }, - ); + const res = await fetch(`${client.baseUrl}/v1/projects/${projectRef}/config/jwt-secret/roll`, { + method: "POST", + headers: client.headers, + signal: AbortSignal.timeout(30_000), + }); if (!res.ok) { - throw new Error( - `JWT-secret roll returned ${res.status}: ${await safeText(res)}`, - ); + throw new Error(`JWT-secret roll returned ${res.status}: ${await safeText(res)}`); } const body = (await res.json()) as { jwt_secret?: string; api_keys?: ApiKey[] }; return { diff --git a/packages/kit-plugin-vercel/src/mgmt-api.ts b/packages/kit-plugin-vercel/src/mgmt-api.ts index 4e8c97af..d6f34492 100644 --- a/packages/kit-plugin-vercel/src/mgmt-api.ts +++ b/packages/kit-plugin-vercel/src/mgmt-api.ts @@ -43,9 +43,7 @@ export interface MgmtClient { export function makeClient(cfg: MgmtClientConfig = {}): MgmtClient { const token = cfg.token ?? process.env.VERCEL_TOKEN; if (!token) { - throw new Error( - "VERCEL_TOKEN not set — generate one at https://vercel.com/account/tokens", - ); + throw new Error("VERCEL_TOKEN not set — generate one at https://vercel.com/account/tokens"); } const teamId = cfg.teamId ?? process.env.VERCEL_TEAM_ID; return { @@ -89,17 +87,16 @@ export interface EnvVar { type?: "plain" | "secret" | "encrypted" | "system"; } -export async function listEnvVars( - client: MgmtClient, - projectIdOrName: string, -): Promise { +export async function listEnvVars(client: MgmtClient, projectIdOrName: string): Promise { const sep = client.teamQuery ? "&" : "?"; const res = await fetch( `${client.baseUrl}/v9/projects/${encodeURIComponent(projectIdOrName)}/env${client.teamQuery}${sep}decrypt=false`, { headers: client.headers, signal: AbortSignal.timeout(10_000) }, ); if (!res.ok) { - throw new Error(`/v9/projects/${projectIdOrName}/env returned ${res.status}: ${await safeText(res)}`); + throw new Error( + `/v9/projects/${projectIdOrName}/env returned ${res.status}: ${await safeText(res)}`, + ); } const body = (await res.json()) as { envs: EnvVar[] }; return body.envs ?? []; @@ -212,9 +209,7 @@ export async function upsertEnvVar( } // Identify conflicting entries (same key + overlapping target). - const conflicts = sameKey.filter((e) => - e.target.some((t) => entry.target.includes(t)), - ); + const conflicts = sameKey.filter((e) => e.target.some((t) => entry.target.includes(t))); if (conflicts.length === 0) { // Pure create — no conflict, no race window. diff --git a/packages/kit-plugin-wiz/src/scan.test.ts b/packages/kit-plugin-wiz/src/scan.test.ts index 3a33407b..892e845e 100644 --- a/packages/kit-plugin-wiz/src/scan.test.ts +++ b/packages/kit-plugin-wiz/src/scan.test.ts @@ -3,12 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { - makeClient, - recordWizIssues, - fetchIssues, - type WizIssue, -} from "./scan.js"; +import { makeClient, recordWizIssues, fetchIssues, type WizIssue } from "./scan.js"; const SAMPLE_ISSUE: WizIssue = { id: "wiz-issue-1", @@ -34,10 +29,7 @@ describe("makeClient", () => { delete process.env.WIZ_CLIENT_ID; delete process.env.WIZ_CLIENT_SECRET; try { - await assert.rejects( - () => makeClient({}), - /WIZ_CLIENT_ID \+ WIZ_CLIENT_SECRET required/, - ); + await assert.rejects(() => makeClient({}), /WIZ_CLIENT_ID \+ WIZ_CLIENT_SECRET required/); } finally { if (prevId !== undefined) process.env.WIZ_CLIENT_ID = prevId; if (prevSecret !== undefined) process.env.WIZ_CLIENT_SECRET = prevSecret; @@ -46,8 +38,7 @@ describe("makeClient", () => { it("refuses without WIZ_API_URL", async () => { await assert.rejects( - () => - makeClient({ clientId: "x", clientSecret: "y" }), + () => makeClient({ clientId: "x", clientSecret: "y" }), /WIZ_API_URL required/, ); }); @@ -67,10 +58,7 @@ describe("makeClient", () => { describe("fetchIssues", () => { it("throws on unreachable API", async () => { await assert.rejects(() => - fetchIssues( - { apiUrl: "https://127.0.0.1:1/graphql", accessToken: "x" }, - { limit: 5 }, - ), + fetchIssues({ apiUrl: "https://127.0.0.1:1/graphql", accessToken: "x" }, { limit: 5 }), ); }); }); diff --git a/packages/kit-plugin-wiz/src/scan.ts b/packages/kit-plugin-wiz/src/scan.ts index 000cca12..e105fc02 100644 --- a/packages/kit-plugin-wiz/src/scan.ts +++ b/packages/kit-plugin-wiz/src/scan.ts @@ -69,7 +69,9 @@ export async function makeClient(opts: MakeClientOptions = {}): Promise { it("check returns true when TINYBIRD_TOKEN is present", async () => { const result = await tinybirdAnalyticsAdapter.check( - mockContext({ TINYBIRD_TOKEN: "p.eyJhbGciOiJIUzI1NiJ9.xxx" }) + mockContext({ TINYBIRD_TOKEN: "p.eyJhbGciOiJIUzI1NiJ9.xxx" }), ); assert.equal(result, true); }); @@ -33,9 +33,7 @@ describe("tinybirdAnalyticsAdapter", () => { it("provision returns existing token when already configured", async () => { const token = "p.eyJhbGciOiJIUzI1NiJ9.xxx"; - const result = await tinybirdAnalyticsAdapter.provision( - mockContext({ TINYBIRD_TOKEN: token }) - ); + const result = await tinybirdAnalyticsAdapter.provision(mockContext({ TINYBIRD_TOKEN: token })); assert.equal(result.success, true); assert.equal(result.secrets?.TINYBIRD_TOKEN, token); assert.equal(result.secrets?.TINYBIRD_API_URL, "https://api.tinybird.co"); @@ -46,7 +44,7 @@ describe("tinybirdAnalyticsAdapter", () => { const token = "p.eyJhbGciOiJIUzI1NiJ9.xxx"; const apiUrl = "https://api.eu.tinybird.co"; const result = await tinybirdAnalyticsAdapter.provision( - mockContext({ TINYBIRD_TOKEN: token, TINYBIRD_API_URL: apiUrl }) + mockContext({ TINYBIRD_TOKEN: token, TINYBIRD_API_URL: apiUrl }), ); assert.equal(result.success, true); assert.equal(result.secrets?.TINYBIRD_API_URL, apiUrl); @@ -55,7 +53,10 @@ describe("tinybirdAnalyticsAdapter", () => { it("provision returns error with setup instructions when token is missing", async () => { const result = await tinybirdAnalyticsAdapter.provision(mockContext()); assert.equal(result.success, false); - assert(result.message?.includes("app.tinybird.co"), `expected dashboard URL: ${result.message}`); + assert( + result.message?.includes("app.tinybird.co"), + `expected dashboard URL: ${result.message}`, + ); assert(result.message?.includes("TINYBIRD_TOKEN"), `expected key name: ${result.message}`); }); }); @@ -72,7 +73,7 @@ describe("posthogAnalyticsAdapter", () => { it("check returns true when NEXT_PUBLIC_POSTHOG_KEY is present", async () => { const result = await posthogAnalyticsAdapter.check( - mockContext({ NEXT_PUBLIC_POSTHOG_KEY: "phc_abc123" }) + mockContext({ NEXT_PUBLIC_POSTHOG_KEY: "phc_abc123" }), ); assert.equal(result, true); }); @@ -85,7 +86,7 @@ describe("posthogAnalyticsAdapter", () => { it("provision returns existing key when already configured", async () => { const apiKey = "phc_abc123"; const result = await posthogAnalyticsAdapter.provision( - mockContext({ NEXT_PUBLIC_POSTHOG_KEY: apiKey }) + mockContext({ NEXT_PUBLIC_POSTHOG_KEY: apiKey }), ); assert.equal(result.success, true); assert.equal(result.secrets?.NEXT_PUBLIC_POSTHOG_KEY, apiKey); @@ -97,7 +98,7 @@ describe("posthogAnalyticsAdapter", () => { const apiKey = "phc_abc123"; const host = "https://eu.i.posthog.com"; const result = await posthogAnalyticsAdapter.provision( - mockContext({ NEXT_PUBLIC_POSTHOG_KEY: apiKey, NEXT_PUBLIC_POSTHOG_HOST: host }) + mockContext({ NEXT_PUBLIC_POSTHOG_KEY: apiKey, NEXT_PUBLIC_POSTHOG_HOST: host }), ); assert.equal(result.success, true); assert.equal(result.secrets?.NEXT_PUBLIC_POSTHOG_HOST, host); @@ -106,7 +107,13 @@ describe("posthogAnalyticsAdapter", () => { it("provision returns error with setup instructions when key is missing", async () => { const result = await posthogAnalyticsAdapter.provision(mockContext()); assert.equal(result.success, false); - assert(result.message?.includes("app.posthog.com"), `expected dashboard URL: ${result.message}`); - assert(result.message?.includes("NEXT_PUBLIC_POSTHOG_KEY"), `expected key name: ${result.message}`); + assert( + result.message?.includes("app.posthog.com"), + `expected dashboard URL: ${result.message}`, + ); + assert( + result.message?.includes("NEXT_PUBLIC_POSTHOG_KEY"), + `expected key name: ${result.message}`, + ); }); }); diff --git a/src/adapters-jobs.test.ts b/src/adapters-jobs.test.ts index 388cb53b..c2f8fdd7 100644 --- a/src/adapters-jobs.test.ts +++ b/src/adapters-jobs.test.ts @@ -27,7 +27,7 @@ describe("triggerBackgroundAdapter", () => { it("check returns true when TRIGGER_SECRET_KEY starts with tr_", async () => { const result = await triggerBackgroundAdapter.check( - mockContext({ TRIGGER_SECRET_KEY: "tr_prod_abc123" }) + mockContext({ TRIGGER_SECRET_KEY: "tr_prod_abc123" }), ); assert.equal(result, true); }); @@ -38,14 +38,14 @@ describe("triggerBackgroundAdapter", () => { it("check returns false when key does not start with tr_", async () => { const result = await triggerBackgroundAdapter.check( - mockContext({ TRIGGER_SECRET_KEY: "sk_not_trigger" }) + mockContext({ TRIGGER_SECRET_KEY: "sk_not_trigger" }), ); assert.equal(result, false); }); it("provision returns existing key when TRIGGER_SECRET_KEY is valid", async () => { const result = await triggerBackgroundAdapter.provision( - mockContext({ TRIGGER_SECRET_KEY: "tr_prod_valid_key" }) + mockContext({ TRIGGER_SECRET_KEY: "tr_prod_valid_key" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.TRIGGER_SECRET_KEY, "tr_prod_valid_key"); @@ -54,7 +54,7 @@ describe("triggerBackgroundAdapter", () => { it("provision includes default TRIGGER_API_URL when not set", async () => { const result = await triggerBackgroundAdapter.provision( - mockContext({ TRIGGER_SECRET_KEY: "tr_prod_valid_key" }) + mockContext({ TRIGGER_SECRET_KEY: "tr_prod_valid_key" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.TRIGGER_API_URL, "https://api.trigger.dev"); @@ -65,7 +65,7 @@ describe("triggerBackgroundAdapter", () => { mockContext({ TRIGGER_SECRET_KEY: "tr_self_hosted", TRIGGER_API_URL: "https://trigger.my-company.com", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.TRIGGER_API_URL, "https://trigger.my-company.com"); @@ -74,8 +74,14 @@ describe("triggerBackgroundAdapter", () => { it("provision returns error with setup instructions when key is missing", async () => { const result = await triggerBackgroundAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("cloud.trigger.dev"), `expected dashboard URL: ${result.message}`); - assert.ok(result.message.includes("TRIGGER_SECRET_KEY"), `expected key name: ${result.message}`); + assert.ok( + result.message.includes("cloud.trigger.dev"), + `expected dashboard URL: ${result.message}`, + ); + assert.ok( + result.message.includes("TRIGGER_SECRET_KEY"), + `expected key name: ${result.message}`, + ); }); }); @@ -96,7 +102,7 @@ describe("inngestBackgroundAdapter", () => { mockContext({ INNGEST_EVENT_KEY: "evt_abc123", INNGEST_SIGNING_KEY: "sign_abc123", - }) + }), ); assert.equal(result, true); }); @@ -105,11 +111,11 @@ describe("inngestBackgroundAdapter", () => { assert.equal(await inngestBackgroundAdapter.check(mockContext()), false); assert.equal( await inngestBackgroundAdapter.check(mockContext({ INNGEST_EVENT_KEY: "evt_123" })), - false + false, ); assert.equal( await inngestBackgroundAdapter.check(mockContext({ INNGEST_SIGNING_KEY: "sign_123" })), - false + false, ); }); @@ -118,7 +124,7 @@ describe("inngestBackgroundAdapter", () => { mockContext({ INNGEST_EVENT_KEY: "evt_existing", INNGEST_SIGNING_KEY: "sign_existing", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.INNGEST_EVENT_KEY, "evt_existing"); @@ -129,18 +135,30 @@ describe("inngestBackgroundAdapter", () => { it("provision returns error with setup instructions when keys are missing", async () => { const result = await inngestBackgroundAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("app.inngest.com"), `expected dashboard URL: ${result.message}`); + assert.ok( + result.message.includes("app.inngest.com"), + `expected dashboard URL: ${result.message}`, + ); assert.ok(result.message.includes("INNGEST_EVENT_KEY"), `expected key name: ${result.message}`); - assert.ok(result.message.includes("INNGEST_SIGNING_KEY"), `expected key name: ${result.message}`); + assert.ok( + result.message.includes("INNGEST_SIGNING_KEY"), + `expected key name: ${result.message}`, + ); }); it("provision reports which keys are missing", async () => { const result = await inngestBackgroundAdapter.provision( - mockContext({ INNGEST_EVENT_KEY: "evt_123" }) + mockContext({ INNGEST_EVENT_KEY: "evt_123" }), ); assert.equal(result.success, false); - assert.ok(result.error?.includes("INNGEST_SIGNING_KEY"), `expected missing key: ${result.error}`); - assert.ok(!result.error?.includes("INNGEST_EVENT_KEY"), `should not list provided key: ${result.error}`); + assert.ok( + result.error?.includes("INNGEST_SIGNING_KEY"), + `expected missing key: ${result.error}`, + ); + assert.ok( + !result.error?.includes("INNGEST_EVENT_KEY"), + `should not list provided key: ${result.error}`, + ); }); }); @@ -158,7 +176,7 @@ describe("flagsmithFlagsAdapter", () => { it("check returns true when FLAGSMITH_ENVIRONMENT_KEY is present", async () => { const result = await flagsmithFlagsAdapter.check( - mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_abc123" }) + mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_abc123" }), ); assert.equal(result, true); }); @@ -169,7 +187,7 @@ describe("flagsmithFlagsAdapter", () => { it("provision returns existing key when FLAGSMITH_ENVIRONMENT_KEY is set", async () => { const result = await flagsmithFlagsAdapter.provision( - mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_existing_key" }) + mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_existing_key" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.FLAGSMITH_ENVIRONMENT_KEY, "env_existing_key"); @@ -178,13 +196,10 @@ describe("flagsmithFlagsAdapter", () => { it("provision includes default API URL when not configured", async () => { const result = await flagsmithFlagsAdapter.provision( - mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_key" }) + mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_key" }), ); assert.equal(result.success, true); - assert.equal( - result.secrets?.FLAGSMITH_API_URL, - "https://edge.api.flagsmith.com/api/v1/" - ); + assert.equal(result.secrets?.FLAGSMITH_API_URL, "https://edge.api.flagsmith.com/api/v1/"); }); it("provision uses custom API URL for self-hosted instances", async () => { @@ -192,7 +207,7 @@ describe("flagsmithFlagsAdapter", () => { mockContext({ FLAGSMITH_ENVIRONMENT_KEY: "env_key", FLAGSMITH_API_URL: "https://flags.my-company.com/api/v1/", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.FLAGSMITH_API_URL, "https://flags.my-company.com/api/v1/"); @@ -201,7 +216,13 @@ describe("flagsmithFlagsAdapter", () => { it("provision returns error with setup instructions when key is missing", async () => { const result = await flagsmithFlagsAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("app.flagsmith.com"), `expected dashboard URL: ${result.message}`); - assert.ok(result.message.includes("FLAGSMITH_ENVIRONMENT_KEY"), `expected key name: ${result.message}`); + assert.ok( + result.message.includes("app.flagsmith.com"), + `expected dashboard URL: ${result.message}`, + ); + assert.ok( + result.message.includes("FLAGSMITH_ENVIRONMENT_KEY"), + `expected key name: ${result.message}`, + ); }); }); diff --git a/src/adapters-new.test.ts b/src/adapters-new.test.ts index 0896f208..3347678f 100644 --- a/src/adapters-new.test.ts +++ b/src/adapters-new.test.ts @@ -27,7 +27,7 @@ describe("planetscaleDbAdapter", () => { it("check returns true when DATABASE_URL starts with mysql://", async () => { const result = await planetscaleDbAdapter.check( - mockContext({ DATABASE_URL: "mysql://user:pass@host/db?ssl={}" }) + mockContext({ DATABASE_URL: "mysql://user:pass@host/db?ssl={}" }), ); assert.equal(result, true); }); @@ -38,7 +38,7 @@ describe("planetscaleDbAdapter", () => { it("check returns false when DATABASE_URL is not a mysql:// URL", async () => { const result = await planetscaleDbAdapter.check( - mockContext({ DATABASE_URL: "postgres://user:pass@host/db" }) + mockContext({ DATABASE_URL: "postgres://user:pass@host/db" }), ); assert.equal(result, false); }); @@ -50,7 +50,7 @@ describe("planetscaleDbAdapter", () => { PLANETSCALE_HOST: "aws.connect.psdb.cloud", PLANETSCALE_USERNAME: "user", PLANETSCALE_PASSWORD: "pass", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.DATABASE_URL, "mysql://user:pass@aws.connect.psdb.cloud/mydb"); @@ -60,19 +60,31 @@ describe("planetscaleDbAdapter", () => { it("provision returns error when service token credentials are missing", async () => { const result = await planetscaleDbAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("PLANETSCALE_SERVICE_TOKEN_ID"), `missing in message: ${result.message}`); - assert.ok(result.message.includes("PLANETSCALE_SERVICE_TOKEN"), `missing in message: ${result.message}`); + assert.ok( + result.message.includes("PLANETSCALE_SERVICE_TOKEN_ID"), + `missing in message: ${result.message}`, + ); + assert.ok( + result.message.includes("PLANETSCALE_SERVICE_TOKEN"), + `missing in message: ${result.message}`, + ); assert.ok(result.message.includes("PLANETSCALE_ORG"), `missing in message: ${result.message}`); }); it("provision reports which specific credentials are missing", async () => { // Only provide token ID, not the token or org const result = await planetscaleDbAdapter.provision( - mockContext({ PLANETSCALE_SERVICE_TOKEN_ID: "tok_id_123" }) + mockContext({ PLANETSCALE_SERVICE_TOKEN_ID: "tok_id_123" }), ); assert.equal(result.success, false); - assert.ok(result.error?.includes("PLANETSCALE_SERVICE_TOKEN"), `expected missing token in error: ${result.error}`); - assert.ok(result.error?.includes("PLANETSCALE_ORG"), `expected missing org in error: ${result.error}`); + assert.ok( + result.error?.includes("PLANETSCALE_SERVICE_TOKEN"), + `expected missing token in error: ${result.error}`, + ); + assert.ok( + result.error?.includes("PLANETSCALE_ORG"), + `expected missing org in error: ${result.error}`, + ); }); }); @@ -89,9 +101,7 @@ describe("loopsEmailAdapter", () => { }); it("check returns true when LOOPS_API_KEY is present", async () => { - const result = await loopsEmailAdapter.check( - mockContext({ LOOPS_API_KEY: "loops_abc123" }) - ); + const result = await loopsEmailAdapter.check(mockContext({ LOOPS_API_KEY: "loops_abc123" })); assert.equal(result, true); }); @@ -101,7 +111,7 @@ describe("loopsEmailAdapter", () => { it("provision returns existing key when LOOPS_API_KEY is set", async () => { const result = await loopsEmailAdapter.provision( - mockContext({ LOOPS_API_KEY: "loops_existing_key" }) + mockContext({ LOOPS_API_KEY: "loops_existing_key" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.LOOPS_API_KEY, "loops_existing_key"); @@ -111,8 +121,14 @@ describe("loopsEmailAdapter", () => { it("provision returns error with setup instructions when key is missing", async () => { const result = await loopsEmailAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("loops.so"), `expected dashboard URL in message: ${result.message}`); - assert.ok(result.message.includes("LOOPS_API_KEY"), `expected key name in message: ${result.message}`); + assert.ok( + result.message.includes("loops.so"), + `expected dashboard URL in message: ${result.message}`, + ); + assert.ok( + result.message.includes("LOOPS_API_KEY"), + `expected key name in message: ${result.message}`, + ); }); }); @@ -130,7 +146,7 @@ describe("liveblocksRealtimeAdapter", () => { it("check returns true when LIVEBLOCKS_SECRET_KEY starts with sk_", async () => { const result = await liveblocksRealtimeAdapter.check( - mockContext({ LIVEBLOCKS_SECRET_KEY: "sk_prod_abc123" }) + mockContext({ LIVEBLOCKS_SECRET_KEY: "sk_prod_abc123" }), ); assert.equal(result, true); }); @@ -141,7 +157,7 @@ describe("liveblocksRealtimeAdapter", () => { it("check returns false when key does not start with sk_", async () => { const result = await liveblocksRealtimeAdapter.check( - mockContext({ LIVEBLOCKS_SECRET_KEY: "pk_prod_abc123" }) + mockContext({ LIVEBLOCKS_SECRET_KEY: "pk_prod_abc123" }), ); assert.equal(result, false); }); @@ -151,7 +167,7 @@ describe("liveblocksRealtimeAdapter", () => { mockContext({ LIVEBLOCKS_SECRET_KEY: "sk_prod_secret", NEXT_PUBLIC_LIVEBLOCKS_PUBLIC_KEY: "pk_prod_public", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.LIVEBLOCKS_SECRET_KEY, "sk_prod_secret"); @@ -161,7 +177,7 @@ describe("liveblocksRealtimeAdapter", () => { it("provision succeeds with only secret key present", async () => { const result = await liveblocksRealtimeAdapter.provision( - mockContext({ LIVEBLOCKS_SECRET_KEY: "sk_dev_abc123" }) + mockContext({ LIVEBLOCKS_SECRET_KEY: "sk_dev_abc123" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.LIVEBLOCKS_SECRET_KEY, "sk_dev_abc123"); @@ -171,7 +187,13 @@ describe("liveblocksRealtimeAdapter", () => { it("provision returns error with setup instructions when key is missing", async () => { const result = await liveblocksRealtimeAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("liveblocks.io"), `expected dashboard URL: ${result.message}`); - assert.ok(result.message.includes("LIVEBLOCKS_SECRET_KEY"), `expected key name: ${result.message}`); + assert.ok( + result.message.includes("liveblocks.io"), + `expected dashboard URL: ${result.message}`, + ); + assert.ok( + result.message.includes("LIVEBLOCKS_SECRET_KEY"), + `expected key name: ${result.message}`, + ); }); }); diff --git a/src/adapters/cloudflare-r2.ts b/src/adapters/cloudflare-r2.ts index 65f72e4a..ef578ca0 100644 --- a/src/adapters/cloudflare-r2.ts +++ b/src/adapters/cloudflare-r2.ts @@ -1,7 +1,6 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "./types.js"; import { exec } from "../utils/exec.js"; - /** * Cloudflare R2 Object Storage Adapter * Provisions an R2 bucket and writes S3-compatible credentials @@ -48,10 +47,7 @@ export const cloudflareR2Adapter: ServiceAdapter = { } // Return existing if already configured - if ( - context.existingEnv.R2_ACCESS_KEY_ID && - context.existingEnv.R2_SECRET_ACCESS_KEY - ) { + if (context.existingEnv.R2_ACCESS_KEY_ID && context.existingEnv.R2_SECRET_ACCESS_KEY) { return { success: true, message: "Cloudflare R2 already configured — keys present in environment", @@ -59,16 +55,15 @@ export const cloudflareR2Adapter: ServiceAdapter = { R2_ACCESS_KEY_ID: context.existingEnv.R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY: context.existingEnv.R2_SECRET_ACCESS_KEY, R2_BUCKET_NAME: context.existingEnv.R2_BUCKET_NAME ?? "", - R2_ENDPOINT: context.existingEnv.R2_ENDPOINT ?? `https://${accountId}.r2.cloudflarestorage.com`, + R2_ENDPOINT: + context.existingEnv.R2_ENDPOINT ?? `https://${accountId}.r2.cloudflarestorage.com`, CLOUDFLARE_ACCOUNT_ID: accountId, }, config: { service: "cloudflare/r2", existing: true }, }; } - const bucketName = ( - context.projectName ?? context.projectPath.split("/").pop() ?? "kit-bucket" - ) + const bucketName = (context.projectName ?? context.projectPath.split("/").pop() ?? "kit-bucket") .toLowerCase() .replace(/[^a-z0-9-]/g, "-"); @@ -111,7 +106,7 @@ export const cloudflareR2Adapter: ServiceAdapter = { permissions: ["admin:read", "admin:write"], buckets: [bucketName], }), - } + }, ); if (resp.ok) { diff --git a/src/adapters/expo-eas.ts b/src/adapters/expo-eas.ts index dc7183dd..23bc6ac8 100644 --- a/src/adapters/expo-eas.ts +++ b/src/adapters/expo-eas.ts @@ -1,7 +1,6 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "./types.js"; import { exec } from "../utils/exec.js"; - /** * Expo EAS Adapter * Sets up Expo Application Services with robot account authentication @@ -9,11 +8,11 @@ import { exec } from "../utils/exec.js"; export const expoEasAdapter: ServiceAdapter = { name: "expo/eas", description: "Expo Application Services (EAS) with robot account authentication", - + getRequiredTools(): string[] { return ["eas"]; }, - + async check(context: AdapterContext): Promise { try { // Check if EXPO_TOKEN exists in env @@ -30,13 +29,13 @@ export const expoEasAdapter: ServiceAdapter = { return false; } } - + return false; } catch { return false; } }, - + async provision(context: AdapterContext): Promise { try { // Step 1: Check if EAS CLI is installed @@ -51,10 +50,10 @@ export const expoEasAdapter: ServiceAdapter = { message: "Install EAS CLI: npm install -g eas-cli", }; } - + // Step 2: Check if EXPO_TOKEN is already set const expoToken = context.existingEnv.EXPO_TOKEN; - + if (!expoToken) { return { success: false, @@ -66,19 +65,20 @@ export const expoEasAdapter: ServiceAdapter = { Or provide EXPO_TOKEN in .env.local`, }; } - + // Step 3: Verify the token by running 'eas whoami' try { const { stdout: whoamiOutput } = await exec("eas", ["whoami"], { timeout: 10_000, env: { ...process.env, EXPO_TOKEN: expoToken }, }); - + if (!whoamiOutput || whoamiOutput.includes("Not authenticated")) { return { success: false, error: "EXPO_TOKEN is invalid or expired", - message: "The provided EXPO_TOKEN does not authenticate successfully. Generate a new token.", + message: + "The provided EXPO_TOKEN does not authenticate successfully. Generate a new token.", }; } } catch (error) { @@ -88,7 +88,7 @@ Or provide EXPO_TOKEN in .env.local`, message: `Error: ${error instanceof Error ? error.message : "Unknown error"}. Ensure EXPO_TOKEN is valid.`, }; } - + // Step 4: Check project credentials try { await exec("eas", ["credentials"], { @@ -100,7 +100,7 @@ Or provide EXPO_TOKEN in .env.local`, // Credentials check may fail for new projects, that's OK // The project will use provisioning certificates if available } - + // Step 5: Verify project structure (optional but helpful) try { await exec("eas", ["build", "--list", "--limit", "1"], { @@ -111,7 +111,7 @@ Or provide EXPO_TOKEN in .env.local`, } catch { // Project may have no builds yet, that's fine } - + return { success: true, message: "Expo EAS provisioned successfully with robot account token", diff --git a/src/adapters/flyio-hosting.ts b/src/adapters/flyio-hosting.ts index 5a974154..bf25a81a 100644 --- a/src/adapters/flyio-hosting.ts +++ b/src/adapters/flyio-hosting.ts @@ -1,11 +1,10 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "sandstream-kit-adapter-sdk"; import { exec } from "../utils/exec.js"; - async function runFly( args: string[], cwd: string, - env?: Record + env?: Record, ): Promise<{ ok: boolean; stdout: string; stderr: string }> { try { const { stdout, stderr } = await exec("fly", args, { @@ -89,7 +88,10 @@ export const flyioHostingAdapter: ServiceAdapter = { if (!appName) { // Generate app name from project name or use a default const projectName = context.projectName || "kit-app"; - appName = projectName.toLowerCase().replace(/[^a-z0-9-]/g, "-").substring(0, 30); + appName = projectName + .toLowerCase() + .replace(/[^a-z0-9-]/g, "-") + .substring(0, 30); // Create the app const createResult = await runFly(["apps", "create", appName], context.projectPath); @@ -125,7 +127,7 @@ export const flyioHostingAdapter: ServiceAdapter = { // Create a deploy token const tokenResult = await runFly( ["tokens", "create", "deploy", "-x", "720h"], - context.projectPath + context.projectPath, ); if (tokenResult.ok) { // Extract token from output diff --git a/src/adapters/ingest.test.ts b/src/adapters/ingest.test.ts index ae8ddef4..9f68c083 100644 --- a/src/adapters/ingest.test.ts +++ b/src/adapters/ingest.test.ts @@ -9,7 +9,10 @@ const sarif = JSON.stringify({ driver: { name: "semgrep", rules: [ - { id: "sql-injection", properties: { tags: ["security", "external/cwe/cwe-89"], "security-severity": "9.1" } }, + { + id: "sql-injection", + properties: { tags: ["security", "external/cwe/cwe-89"], "security-severity": "9.1" }, + }, { id: "weak-hash", properties: { tags: ["CWE-328"] } }, ], }, @@ -19,7 +22,14 @@ const sarif = JSON.stringify({ ruleId: "sql-injection", level: "error", message: { text: "Possible SQL injection" }, - locations: [{ physicalLocation: { artifactLocation: { uri: "src/db.ts" }, region: { startLine: 42 } } }], + locations: [ + { + physicalLocation: { + artifactLocation: { uri: "src/db.ts" }, + region: { startLine: 42 }, + }, + }, + ], }, { ruleId: "weak-hash", level: "warning", message: { text: "MD5 used" } }, ], @@ -34,7 +44,11 @@ const osv = JSON.stringify({ { package: { name: "lodash", ecosystem: "npm", version: "4.17.11" }, vulnerabilities: [ - { id: "GHSA-jf85-cpcp-j695", summary: "Prototype pollution in lodash", database_specific: { severity: "HIGH" } }, + { + id: "GHSA-jf85-cpcp-j695", + summary: "Prototype pollution in lodash", + database_specific: { severity: "HIGH" }, + }, ], }, ], diff --git a/src/adapters/ingest.ts b/src/adapters/ingest.ts index 19e2eea9..20f7d4bd 100644 --- a/src/adapters/ingest.ts +++ b/src/adapters/ingest.ts @@ -92,8 +92,9 @@ export function parseSarif(json: string): SecurityCheckResult[] { const ruleId = res.ruleId ?? "(rule)"; const rule = rulesById.get(ruleId); const severity = - cvssToSeverity(res.properties?.["security-severity"] ?? rule?.properties?.["security-severity"]) ?? - levelToSeverity(res.level); + cvssToSeverity( + res.properties?.["security-severity"] ?? rule?.properties?.["security-severity"], + ) ?? levelToSeverity(res.level); const loc = res.locations?.[0]?.physicalLocation; const uri = loc?.artifactLocation?.uri; const line = loc?.region?.startLine; diff --git a/src/adapters/liveblocks-realtime.ts b/src/adapters/liveblocks-realtime.ts index f64b37ad..62c4deeb 100644 --- a/src/adapters/liveblocks-realtime.ts +++ b/src/adapters/liveblocks-realtime.ts @@ -44,7 +44,8 @@ export const liveblocksRealtimeAdapter: ServiceAdapter = { const derivedPublicKey = secretKey.replace(/^sk_/, "pk_"); return { success: true, - message: "Liveblocks secret key found — set NEXT_PUBLIC_LIVEBLOCKS_PUBLIC_KEY manually if needed", + message: + "Liveblocks secret key found — set NEXT_PUBLIC_LIVEBLOCKS_PUBLIC_KEY manually if needed", secrets: { LIVEBLOCKS_SECRET_KEY: secretKey, NEXT_PUBLIC_LIVEBLOCKS_PUBLIC_KEY: publicKey ?? derivedPublicKey, diff --git a/src/adapters/neon-db.ts b/src/adapters/neon-db.ts index 5f0e4a99..27dccda4 100644 --- a/src/adapters/neon-db.ts +++ b/src/adapters/neon-db.ts @@ -39,7 +39,10 @@ export const neonDbAdapter: ServiceAdapter = { const databaseUrl = context.existingEnv.DATABASE_URL; // Already configured — re-use - if (databaseUrl && (databaseUrl.startsWith("postgres://") || databaseUrl.startsWith("postgresql://"))) { + if ( + databaseUrl && + (databaseUrl.startsWith("postgres://") || databaseUrl.startsWith("postgresql://")) + ) { return { success: true, message: "Neon (or Postgres) already configured — DATABASE_URL present in environment", @@ -66,8 +69,7 @@ export const neonDbAdapter: ServiceAdapter = { }; } - const projectName = - context.projectName ?? context.projectPath.split("/").pop() ?? "kit-db"; + const projectName = context.projectName ?? context.projectPath.split("/").pop() ?? "kit-db"; let project: NeonProjectResponse; try { diff --git a/src/adapters/planetscale-db.ts b/src/adapters/planetscale-db.ts index a43a9796..e4e3a39d 100644 --- a/src/adapters/planetscale-db.ts +++ b/src/adapters/planetscale-db.ts @@ -72,8 +72,7 @@ export const planetscaleDbAdapter: ServiceAdapter = { }; } - const dbName = - context.projectName ?? context.projectPath.split("/").pop() ?? "kit-db"; + const dbName = context.projectName ?? context.projectPath.split("/").pop() ?? "kit-db"; const headers = { Authorization: `${tokenId}:${token}`, @@ -117,7 +116,7 @@ export const planetscaleDbAdapter: ServiceAdapter = { method: "POST", headers, body: JSON.stringify({ name: `${dbName}-kit`, role: "readwriter" }), - } + }, ); if (!resp.ok) { diff --git a/src/adapters/railway-hosting.ts b/src/adapters/railway-hosting.ts index acc45b87..fb9fc31d 100644 --- a/src/adapters/railway-hosting.ts +++ b/src/adapters/railway-hosting.ts @@ -1,11 +1,10 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "sandstream-kit-adapter-sdk"; import { exec } from "../utils/exec.js"; - async function runRailway( args: string[], cwd: string, - env?: Record + env?: Record, ): Promise<{ ok: boolean; stdout: string; stderr: string }> { try { const { stdout, stderr } = await exec("railway", args, { diff --git a/src/adapters/resend-email.ts b/src/adapters/resend-email.ts index 7afbbbc5..c6450b8b 100644 --- a/src/adapters/resend-email.ts +++ b/src/adapters/resend-email.ts @@ -41,8 +41,7 @@ export const resendEmailAdapter: ServiceAdapter = { // If a valid key is already set, re-use it if (masterKey && masterKey.startsWith("re_")) { - const fromEmail = - context.existingEnv.RESEND_FROM_EMAIL ?? "onboarding@resend.dev"; + const fromEmail = context.existingEnv.RESEND_FROM_EMAIL ?? "onboarding@resend.dev"; return { success: true, message: "Resend already configured — API key present in environment", @@ -87,7 +86,7 @@ export const resendEmailAdapter: ServiceAdapter = { */ export async function provisionResendApiKey( masterKey: string, - keyName: string + keyName: string, ): Promise<{ success: true; key: ResendApiKey } | { success: false; error: string }> { try { const resp = await fetch("https://api.resend.com/api-keys", { @@ -121,9 +120,7 @@ export async function provisionResendApiKey( * Fetch the first verified sending domain for the account. * Returns null if none exist (use onboarding@resend.dev as fallback). */ -export async function fetchFirstVerifiedDomain( - apiKey: string -): Promise { +export async function fetchFirstVerifiedDomain(apiKey: string): Promise { try { const resp = await fetch("https://api.resend.com/domains", { headers: { Authorization: `Bearer ${apiKey}` }, diff --git a/src/adapters/searxng-instance.ts b/src/adapters/searxng-instance.ts index b0a288ca..e0444bca 100644 --- a/src/adapters/searxng-instance.ts +++ b/src/adapters/searxng-instance.ts @@ -1,14 +1,10 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "./types.js"; import { exec } from "../utils/exec.js"; - /** * Helper to fetch with timeout using AbortController */ -async function fetchWithTimeout( - url: string, - timeoutMs: number = 5000, -): Promise { +async function fetchWithTimeout(url: string, timeoutMs: number = 5000): Promise { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), timeoutMs); try { @@ -47,15 +43,13 @@ export const searxngInstanceAdapter: ServiceAdapter = { // Check if SearXNG is running in Docker on localhost:8080 try { - const { stdout } = await exec("docker", [ - "ps", - "--filter", - "name=searxng", - "--format", - "{{.Status}}", - ], { - timeout: 10_000, - }); + const { stdout } = await exec( + "docker", + ["ps", "--filter", "name=searxng", "--format", "{{.Status}}"], + { + timeout: 10_000, + }, + ); if (stdout.includes("Up")) { // Try to verify it's responding @@ -91,28 +85,23 @@ export const searxngInstanceAdapter: ServiceAdapter = { // Check if SearXNG container already exists and is running try { - const { stdout } = await exec("docker", [ - "ps", - "-a", - "--filter", - "name=searxng", - "--format", - "{{.Names}}", - ], { - timeout: 10_000, - }); + const { stdout } = await exec( + "docker", + ["ps", "-a", "--filter", "name=searxng", "--format", "{{.Names}}"], + { + timeout: 10_000, + }, + ); if (stdout.includes("searxng")) { // Container exists, check if it's running - const { stdout: statusOutput } = await exec("docker", [ - "ps", - "--filter", - "name=searxng", - "--format", - "{{.Status}}", - ], { - timeout: 10_000, - }); + const { stdout: statusOutput } = await exec( + "docker", + ["ps", "--filter", "name=searxng", "--format", "{{.Status}}"], + { + timeout: 10_000, + }, + ); if (statusOutput.includes("Up")) { // Already running, verify it's healthy @@ -184,19 +173,23 @@ export const searxngInstanceAdapter: ServiceAdapter = { // Create and start SearXNG container try { - await exec("docker", [ - "run", - "-d", - "--name", - "searxng", - "-p", - "8080:8080", - "-e", - "SEARXNG_PORT=8080", - "searxng/searxng:latest", - ], { - timeout: 120_000, // 2 minutes for image pull and container creation - }); + await exec( + "docker", + [ + "run", + "-d", + "--name", + "searxng", + "-p", + "8080:8080", + "-e", + "SEARXNG_PORT=8080", + "searxng/searxng:latest", + ], + { + timeout: 120_000, // 2 minutes for image pull and container creation + }, + ); // Wait for container to be healthy let attempts = 0; diff --git a/src/adapters/sentry-monitoring.ts b/src/adapters/sentry-monitoring.ts index 2b56b5cb..91904491 100644 --- a/src/adapters/sentry-monitoring.ts +++ b/src/adapters/sentry-monitoring.ts @@ -10,11 +10,7 @@ export const sentryMonitoringAdapter = apiKeyAdapter({ name: "sentry/monitoring", description: "Sentry error tracking and performance monitoring", required: [{ env: "SENTRY_DSN", prefix: "https://" }], - optional: [ - { env: "SENTRY_ORG" }, - { env: "SENTRY_PROJECT" }, - { env: "SENTRY_AUTH_TOKEN" }, - ], + optional: [{ env: "SENTRY_ORG" }, { env: "SENTRY_PROJECT" }, { env: "SENTRY_AUTH_TOKEN" }], steps: [ "Set SENTRY_DSN before running kit add sentry/monitoring:", " 1. Go to https://sentry.io and create a project", diff --git a/src/adapters/stripe-payments.ts b/src/adapters/stripe-payments.ts index 002d55b5..d79a60cd 100644 --- a/src/adapters/stripe-payments.ts +++ b/src/adapters/stripe-payments.ts @@ -1,7 +1,6 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "./types.js"; import { exec } from "../utils/exec.js"; - /** * Stripe Payments Adapter * Sets up Stripe for payment processing @@ -9,29 +8,29 @@ import { exec } from "../utils/exec.js"; export const stripePaymentsAdapter: ServiceAdapter = { name: "stripe/payments", description: "Stripe payment processing with products and price IDs", - + getRequiredTools(): string[] { return ["stripe"]; }, - + async check(context: AdapterContext): Promise { try { // Check if Stripe API key exists in env if (context.existingEnv.STRIPE_SECRET_KEY && context.existingEnv.STRIPE_PUBLISHABLE_KEY) { return true; } - + // Check if stripe CLI is authenticated const { stdout } = await exec("stripe", ["config", "--list"], { timeout: 10_000, }); - + return stdout.includes("test_mode_api_key") || stdout.includes("live_mode_api_key"); } catch { return false; } }, - + async provision(context: AdapterContext): Promise { try { // Step 1: Ensure Stripe CLI is authenticated @@ -39,8 +38,11 @@ export const stripePaymentsAdapter: ServiceAdapter = { const { stdout: configOutput } = await exec("stripe", ["config", "--list"], { timeout: 10_000, }); - - if (!configOutput.includes("test_mode_api_key") && !configOutput.includes("live_mode_api_key")) { + + if ( + !configOutput.includes("test_mode_api_key") && + !configOutput.includes("live_mode_api_key") + ) { return { success: false, error: "Stripe CLI not authenticated. Run: stripe login", @@ -54,15 +56,15 @@ export const stripePaymentsAdapter: ServiceAdapter = { message: "Install Stripe CLI and run: stripe login", }; } - + // Step 2: Get API keys const { stdout: apiKeysOutput } = await exec("stripe", ["config", "--list"], { timeout: 10_000, }); - + const testKeyMatch = apiKeysOutput.match(/test_mode_api_key\s*=\s*(\S+)/); const publishableKeyMatch = apiKeysOutput.match(/test_mode_pub_key\s*=\s*(\S+)/); - + if (!testKeyMatch) { return { success: false, @@ -70,23 +72,18 @@ export const stripePaymentsAdapter: ServiceAdapter = { message: "Failed to get Stripe API keys from CLI config", }; } - + const secretKey = testKeyMatch[1]; - + // Step 3: Get publishable key from API let publishableKey = publishableKeyMatch?.[1]; - + if (!publishableKey) { try { - await exec("stripe", [ - "api", - "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/v1/accounts", - "--method", - "get", - ], { + await exec("stripe", ["api", "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/v1/accounts", "--method", "get"], { timeout: 10_000, }); - + // Parse to get publishable key (would need proper JSON parsing in production) // For now, construct from secret key pattern publishableKey = secretKey.replace("sk_test_", "pk_test_"); @@ -94,37 +91,40 @@ export const stripePaymentsAdapter: ServiceAdapter = { publishableKey = secretKey.replace("sk_test_", "pk_test_"); } } - + // Step 4: Create a basic product (optional, can be skipped if products exist) const projectName = context.projectName || "default"; - + try { - const { stdout: productsOutput } = await exec("stripe", [ - "products", - "list", - "--limit", - "1", - ], { - timeout: 10_000, - }); - + const { stdout: productsOutput } = await exec( + "stripe", + ["products", "list", "--limit", "1"], + { + timeout: 10_000, + }, + ); + // If no products, create a sample one if (!productsOutput.includes("prod_")) { - await exec("stripe", [ - "products", - "create", - "--name", - `${projectName} Subscription`, - "--description", - "Auto-generated by kit", - ], { - timeout: 10_000, - }); + await exec( + "stripe", + [ + "products", + "create", + "--name", + `${projectName} Subscription`, + "--description", + "Auto-generated by kit", + ], + { + timeout: 10_000, + }, + ); } } catch { // Product creation failed, but that's OK - keys are more important } - + return { success: true, message: "Stripe payments configured successfully", diff --git a/src/adapters/supabase-db.ts b/src/adapters/supabase-db.ts index fed226d1..46be1653 100644 --- a/src/adapters/supabase-db.ts +++ b/src/adapters/supabase-db.ts @@ -1,7 +1,6 @@ import type { ServiceAdapter, AdapterContext, ProvisionResult } from "./types.js"; import { exec } from "../utils/exec.js"; - /** * Supabase Database Adapter * Sets up Supabase project with database and auth @@ -9,33 +8,30 @@ import { exec } from "../utils/exec.js"; export const supabaseDbAdapter: ServiceAdapter = { name: "supabase/db", description: "Supabase database and authentication", - + getRequiredTools(): string[] { return ["supabase"]; }, - + async check(context: AdapterContext): Promise { try { // Check if Supabase URL and keys exist in env - if ( - context.existingEnv.SUPABASE_URL && - context.existingEnv.SUPABASE_ANON_KEY - ) { + if (context.existingEnv.SUPABASE_URL && context.existingEnv.SUPABASE_ANON_KEY) { return true; } - + // Check if supabase is linked const { stdout } = await exec("supabase", ["status"], { cwd: context.projectPath, timeout: 10_000, }); - + return stdout.includes("API URL") || stdout.includes("supabase_url"); } catch { return false; } }, - + async provision(context: AdapterContext): Promise { try { // Step 1: Check if supabase CLI is installed and authenticated @@ -50,23 +46,23 @@ export const supabaseDbAdapter: ServiceAdapter = { message: "Install Supabase CLI: brew install supabase/tap/supabase", }; } - + // Step 2: Check if already initialized try { await exec("supabase", ["status"], { cwd: context.projectPath, timeout: 10_000, }); - + // Already initialized, get existing credentials const { stdout: statusOutput } = await exec("supabase", ["status", "--output", "json"], { cwd: context.projectPath, timeout: 10_000, }); - + try { const status = JSON.parse(statusOutput); - + if (status.API_URL && status.ANON_KEY) { return { success: true, @@ -88,7 +84,7 @@ export const supabaseDbAdapter: ServiceAdapter = { } catch { // Not initialized yet } - + // Step 3: Initialize Supabase if not already done try { await exec("supabase", ["init"], { @@ -98,18 +94,18 @@ export const supabaseDbAdapter: ServiceAdapter = { } catch { // Init might fail if already initialized, that's OK } - + // Step 4: Start local Supabase (for development) const { stdout: startOutput } = await exec("supabase", ["start"], { cwd: context.projectPath, timeout: 120_000, // Starting Supabase can take a while }); - + // Step 5: Extract credentials from output const urlMatch = startOutput.match(/API URL: (http:\/\/[^\s]+)/); const anonKeyMatch = startOutput.match(/anon key: ([^\s]+)/); const serviceKeyMatch = startOutput.match(/service_role key: ([^\s]+)/); - + if (!urlMatch || !anonKeyMatch) { return { success: false, @@ -117,7 +113,7 @@ export const supabaseDbAdapter: ServiceAdapter = { message: "Supabase started but failed to parse credentials", }; } - + return { success: true, message: "Supabase database configured successfully (local development)", diff --git a/src/adapters/upstash-redis.ts b/src/adapters/upstash-redis.ts index 1efb42b7..46069d14 100644 --- a/src/adapters/upstash-redis.ts +++ b/src/adapters/upstash-redis.ts @@ -22,8 +22,7 @@ export const upstashRedisAdapter: ServiceAdapter = { async check(context: AdapterContext): Promise { return !!( - context.existingEnv.UPSTASH_REDIS_REST_URL && - context.existingEnv.UPSTASH_REDIS_REST_TOKEN + context.existingEnv.UPSTASH_REDIS_REST_URL && context.existingEnv.UPSTASH_REDIS_REST_TOKEN ); }, @@ -59,8 +58,7 @@ export const upstashRedisAdapter: ServiceAdapter = { }; } - const dbName = - context.projectName ?? context.projectPath.split("/").pop() ?? "kit-redis"; + const dbName = context.projectName ?? context.projectPath.split("/").pop() ?? "kit-redis"; const auth = Buffer.from(`${email}:${apiKey}`).toString("base64"); diff --git a/src/adapters/vercel-hosting.ts b/src/adapters/vercel-hosting.ts index 076c0425..49f75dc5 100644 --- a/src/adapters/vercel-hosting.ts +++ b/src/adapters/vercel-hosting.ts @@ -3,7 +3,6 @@ import { resolve } from "node:path"; import type { ServiceAdapter, AdapterContext, ProvisionResult } from "./types.js"; import { exec } from "../utils/exec.js"; - /** * Vercel Hosting Adapter * Links repository to Vercel and sets up deployment @@ -11,11 +10,11 @@ import { exec } from "../utils/exec.js"; export const vercelHostingAdapter: ServiceAdapter = { name: "vercel/hosting", description: "Vercel hosting and deployment", - + getRequiredTools(): string[] { return ["vercel"]; }, - + async check(context: AdapterContext): Promise { try { // Check if .vercel directory exists (indicates project is linked) @@ -25,7 +24,7 @@ export const vercelHostingAdapter: ServiceAdapter = { return false; } }, - + async provision(context: AdapterContext): Promise { try { // Step 1: Check if Vercel CLI is installed @@ -40,13 +39,13 @@ export const vercelHostingAdapter: ServiceAdapter = { message: "Install Vercel CLI: npm install -g vercel", }; } - + // Step 2: Check authentication try { const { stdout: whoamiOutput } = await exec("vercel", ["whoami"], { timeout: 10_000, }); - + if (!whoamiOutput.trim() || whoamiOutput.includes("Error")) { return { success: false, @@ -61,18 +60,18 @@ export const vercelHostingAdapter: ServiceAdapter = { message: "Authenticate with Vercel: vercel login", }; } - + // Step 3: Link project (interactive, will ask for project details) await exec("vercel", ["link", "--yes"], { cwd: context.projectPath, timeout: 30_000, }); - + // Step 4: Get project info const { stdout: projectInfo } = await exec("vercel", ["project", "ls", "--json"], { timeout: 10_000, }); - + let projectData: any = {}; try { const projects = JSON.parse(projectInfo); @@ -82,18 +81,18 @@ export const vercelHostingAdapter: ServiceAdapter = { } catch { // JSON parse failed } - + // Step 5: Get environment variables if project is linked let secrets: Record = {}; - + try { // Read .vercel/project.json to get project ID const vercelConfig = await readFile( resolve(context.projectPath, ".vercel", "project.json"), - "utf-8" + "utf-8", ); const config = JSON.parse(vercelConfig); - + secrets = { VERCEL_PROJECT_ID: config.projectId || "", VERCEL_ORG_ID: config.orgId || "", @@ -101,7 +100,7 @@ export const vercelHostingAdapter: ServiceAdapter = { } catch { // Could not read vercel config } - + return { success: true, message: "Vercel hosting configured successfully", diff --git a/src/agent-audit.test.ts b/src/agent-audit.test.ts index dacb9fdc..73b32824 100644 --- a/src/agent-audit.test.ts +++ b/src/agent-audit.test.ts @@ -7,11 +7,16 @@ const FAKE_STRIPE = ["sk", "live", "A".repeat(40)].join("_"); describe("auditConfigSecrets", () => { it("flags a plaintext secret embedded in a config blob", () => { - const cfg = JSON.stringify({ mcpServers: { stripe: { env: { STRIPE_SECRET_KEY: FAKE_STRIPE } } } }); + const cfg = JSON.stringify({ + mcpServers: { stripe: { env: { STRIPE_SECRET_KEY: FAKE_STRIPE } } }, + }); const hits = auditConfigSecrets(cfg); assert.ok(hits.length >= 1, "should find the stripe key"); assert.ok(hits[0].preview.includes("…"), "preview must be masked (head…tail)"); - assert.ok(hits[0].preview.length < FAKE_STRIPE.length, "preview must be shorter than the raw key"); + assert.ok( + hits[0].preview.length < FAKE_STRIPE.length, + "preview must be shorter than the raw key", + ); }); it("is clean when no secrets present", () => { assert.deepEqual(auditConfigSecrets(JSON.stringify({ mcpServers: {} })), []); @@ -31,7 +36,10 @@ describe("auditMcpServers", () => { assert.match(hits[0], /^bad → http:\/\//); }); it("also reads the `servers` container; [] on garbage", () => { - assert.equal(auditMcpServers(JSON.stringify({ servers: { x: { url: "http://h" } } })).length, 1); + assert.equal( + auditMcpServers(JSON.stringify({ servers: { x: { url: "http://h" } } })).length, + 1, + ); assert.deepEqual(auditMcpServers("not json"), []); }); }); diff --git a/src/agent-audit.ts b/src/agent-audit.ts index ad35c1ba..e283597d 100644 --- a/src/agent-audit.ts +++ b/src/agent-audit.ts @@ -50,8 +50,14 @@ export function auditMcpServers(json: string): string[] { } const SUSPICIOUS_HOOK_PATTERNS: { re: RegExp; why: string }[] = [ - { re: /(curl|wget)\b[^\n|]*\|\s*(sh|bash|zsh)\b/i, why: "pipes a download straight into a shell" }, - { re: /base64\s+(-d|--decode|-D)\b[^\n|]*\|\s*(sh|bash|zsh)\b/i, why: "base64-decodes into a shell" }, + { + re: /(curl|wget)\b[^\n|]*\|\s*(sh|bash|zsh)\b/i, + why: "pipes a download straight into a shell", + }, + { + re: /base64\s+(-d|--decode|-D)\b[^\n|]*\|\s*(sh|bash|zsh)\b/i, + why: "base64-decodes into a shell", + }, { re: /\/dev\/tcp\//, why: "opens a raw TCP socket (reverse-shell shape)" }, { re: /eval\s+"?\$\(/, why: "evals a command substitution" }, ]; @@ -102,25 +108,29 @@ export function runAgentAudit(cwd: string): SecurityCheckResult[] { const secrets = auditConfigSecrets(content); if (secrets.length > 0) { const kinds = [...new Set(secrets.map((s) => s.label))].join(", "); - out.push(result( - `secret in ${rel}`, - "fail", - `${secrets.length} plaintext secret(s) (${kinds}) in an agent config — e.g. ${secrets[0].preview}`, - "secrets", - "critical", - `move it to a vault/env and gitignore ${rel}`, - )); + out.push( + result( + `secret in ${rel}`, + "fail", + `${secrets.length} plaintext secret(s) (${kinds}) in an agent config — e.g. ${secrets[0].preview}`, + "secrets", + "critical", + `move it to a vault/env and gitignore ${rel}`, + ), + ); } const cleartext = auditMcpServers(content); if (cleartext.length > 0) { - out.push(result( - `cleartext MCP in ${rel}`, - "warn", - `${cleartext.length} MCP server(s) on http://: ${cleartext.slice(0, 3).join("; ")}`, - "exposure", - "medium", - "use https:// MCP endpoints", - )); + out.push( + result( + `cleartext MCP in ${rel}`, + "warn", + `${cleartext.length} MCP server(s) on http://: ${cleartext.slice(0, 3).join("; ")}`, + "exposure", + "medium", + "use https:// MCP endpoints", + ), + ); } } @@ -142,14 +152,16 @@ export function runAgentAudit(cwd: string): SecurityCheckResult[] { scannedHooks++; const reasons = auditHookBody(body); if (reasons.length > 0) { - out.push(result( - `suspicious hook ${dir}/${entry}`, - "fail", - `hook ${reasons.join("; ")}`, - "exposure", - "high", - "review the hook; a compromised hook runs on every git operation", - )); + out.push( + result( + `suspicious hook ${dir}/${entry}`, + "fail", + `hook ${reasons.join("; ")}`, + "exposure", + "high", + "review the hook; a compromised hook runs on every git operation", + ), + ); } } catch { continue; @@ -158,12 +170,14 @@ export function runAgentAudit(cwd: string): SecurityCheckResult[] { } if (out.length === 0) { - out.push(result( - "agent-audit", - "pass", - `no issues in ${scannedConfigs} agent config(s) + ${scannedHooks} hook(s)`, - "exposure", - )); + out.push( + result( + "agent-audit", + "pass", + `no issues in ${scannedConfigs} agent config(s) + ${scannedHooks} hook(s)`, + "exposure", + ), + ); } return out; } diff --git a/src/agent-config.test.ts b/src/agent-config.test.ts index 690899e6..6c28de5b 100644 --- a/src/agent-config.test.ts +++ b/src/agent-config.test.ts @@ -43,7 +43,8 @@ describe("upsertKitBlock", () => { it("updates only the marked region, preserving surrounding edits", () => { const base = upsertKitBlock("# Doc\n").next; // Simulate a user editing OUTSIDE the markers + a stale block INSIDE. - const edited = base.replace("kit triage", "STALE_PLACEHOLDER") + "\n## My own section\nkeep me\n"; + const edited = + base.replace("kit triage", "STALE_PLACEHOLDER") + "\n## My own section\nkeep me\n"; const { next, action } = upsertKitBlock(edited); assert.equal(action, "updated"); assert.ok(next.includes("kit triage"), "block refreshed"); @@ -64,7 +65,9 @@ describe("detectAgentTargets", () => { it("defaults to CLAUDE.md + AGENTS.md when nothing is present", () => { const dir = tmpRepo(); try { - const files = detectAgentTargets(dir).map((t) => t.file).sort(); + const files = detectAgentTargets(dir) + .map((t) => t.file) + .sort(); assert.deepEqual(files, ["AGENTS.md", "CLAUDE.md"]); } finally { rmSync(dir, { recursive: true, force: true }); @@ -87,7 +90,9 @@ describe("detectAgentTargets", () => { try { writeFileSync(join(dir, ".cursorrules"), "rules\n"); writeFileSync(join(dir, ".clinerules"), "rules\n"); - const agents = detectAgentTargets(dir).map((t) => t.agent).sort(); + const agents = detectAgentTargets(dir) + .map((t) => t.agent) + .sort(); assert.deepEqual(agents, ["Cline", "Cursor"]); } finally { rmSync(dir, { recursive: true, force: true }); @@ -165,7 +170,11 @@ describe("installKitPermissions", () => { assert.ok(s.permissions.allow.includes("Bash(kit check:*)")); assert.ok(s.permissions.allow.includes("Bash(kit memory search:*)")); // Never grants mutating commands, never writes a deny rule or a mode. - assert.ok(!s.permissions.allow.some((r: string) => r.includes("kit secrets") || r.includes("kit fix"))); + assert.ok( + !s.permissions.allow.some( + (r: string) => r.includes("kit secrets") || r.includes("kit fix"), + ), + ); assert.equal(s.permissions.deny, undefined); assert.equal(s.permissions.defaultMode, undefined); @@ -183,7 +192,10 @@ describe("installKitPermissions", () => { mkdirSync(join(dir, ".claude"), { recursive: true }); writeFileSync( join(dir, ".claude", "settings.json"), - JSON.stringify({ permissions: { allow: ["Bash(npm run:*)"] }, enableAllProjectMcpServers: true }), + JSON.stringify({ + permissions: { allow: ["Bash(npm run:*)"] }, + enableAllProjectMcpServers: true, + }), ); await installKitPermissions(dir); const s = JSON.parse(readFileSync(join(dir, ".claude", "settings.json"), "utf-8")); diff --git a/src/agent-config.ts b/src/agent-config.ts index 8dac5149..86a7f6c8 100644 --- a/src/agent-config.ts +++ b/src/agent-config.ts @@ -16,7 +16,8 @@ import { resolve, dirname } from "node:path"; * block in place and never touches anything outside the markers. */ -export const KIT_BLOCK_BEGIN = ""; +export const KIT_BLOCK_BEGIN = + ""; export const KIT_BLOCK_END = ""; /** The canonical "use kit" instruction. Kept short on purpose — agents read it @@ -79,7 +80,10 @@ export function detectAgentTargets(cwd: string = process.cwd()): AgentTarget[] { * - No existing block → append (with a blank-line separator if the file is non-empty). * - Existing block → replace just the marker-delimited region, preserving everything else. */ -export function upsertKitBlock(content: string): { next: string; action: "created" | "updated" | "unchanged" } { +export function upsertKitBlock(content: string): { + next: string; + action: "created" | "updated" | "unchanged"; +} { const block = `${KIT_BLOCK_BEGIN}\n\n${KIT_INSTRUCTION}\n\n${KIT_BLOCK_END}`; const begin = content.indexOf(KIT_BLOCK_BEGIN); const end = content.indexOf(KIT_BLOCK_END); @@ -91,7 +95,14 @@ export function upsertKitBlock(content: string): { next: string; action: "create return { next, action: next === content ? "unchanged" : "updated" }; } - const sep = content.length === 0 ? "" : content.endsWith("\n\n") ? "" : content.endsWith("\n") ? "\n" : "\n\n"; + const sep = + content.length === 0 + ? "" + : content.endsWith("\n\n") + ? "" + : content.endsWith("\n") + ? "\n" + : "\n\n"; return { next: content + sep + block + "\n", action: "created" }; } @@ -138,7 +149,8 @@ export async function writeAgentConfig( agent: t.agent, file: t.file, action, - detail: action === "created" ? `wrote kit block to ${t.file}` : `updated kit block in ${t.file}`, + detail: + action === "created" ? `wrote kit block to ${t.file}` : `updated kit block in ${t.file}`, }); } catch (err) { results.push({ @@ -190,7 +202,9 @@ export interface PermissionResult { * `deny`, never sets a permission mode. Only wired for Claude Code (the agent * whose settings schema we know). */ -export async function installKitPermissions(cwd: string = process.cwd()): Promise { +export async function installKitPermissions( + cwd: string = process.cwd(), +): Promise { const file = ".claude/settings.json"; const path = resolve(cwd, file); @@ -200,7 +214,13 @@ export async function installKitPermissions(cwd: string = process.cwd()): Promis } // Only meaningful in a Claude Code project. if (!existsSync(resolve(cwd, ".claude")) && !existsSync(resolve(cwd, "CLAUDE.md"))) { - return { file, added: [], alreadyPresent: 0, action: "skipped", detail: "no Claude Code project detected" }; + return { + file, + added: [], + alreadyPresent: 0, + action: "skipped", + detail: "no Claude Code project detected", + }; } let settings: { permissions?: { allow?: string[] }; [k: string]: unknown } = {}; @@ -233,6 +253,12 @@ export async function installKitPermissions(cwd: string = process.cwd()): Promis await writeFile(path, JSON.stringify(settings, null, 2) + "\n", "utf-8"); return { file, added, alreadyPresent, action: existed ? "updated" : "created" }; } catch (err) { - return { file, added: [], alreadyPresent, action: "failed", detail: err instanceof Error ? err.message : String(err) }; + return { + file, + added: [], + alreadyPresent, + action: "failed", + detail: err instanceof Error ? err.message : String(err), + }; } } diff --git a/src/analyze.ts b/src/analyze.ts index 77c08d8d..8c060942 100644 --- a/src/analyze.ts +++ b/src/analyze.ts @@ -3,7 +3,6 @@ import { join } from "node:path"; import { detectStack, type DetectedStack } from "./stack-detector.js"; import { exec } from "./utils/exec.js"; - export interface AnalysisReport { stack: DetectedStack; commitPrefixes: Array<{ prefix: string; count: number }>; @@ -31,11 +30,10 @@ async function gitCommitPrefixes( limit = 200, ): Promise> { try { - const { stdout } = await exec( - "git", - ["log", `--max-count=${limit}`, "--pretty=%s"], - { cwd, timeout: 5000 }, - ); + const { stdout } = await exec("git", ["log", `--max-count=${limit}`, "--pretty=%s"], { + cwd, + timeout: 5000, + }); const counts = new Map(); for (const line of stdout.split("\n")) { // Conventional-commit prefix: word, optional scope, then `:` @@ -105,8 +103,7 @@ async function detectCiFiles(cwd: string): Promise { } if (await fileExists(join(cwd, ".gitlab-ci.yml"))) ci.push(".gitlab-ci.yml"); if (await fileExists(join(cwd, "bitbucket-pipelines.yml"))) ci.push("bitbucket-pipelines.yml"); - if (await fileExists(join(cwd, "circleci", "config.yml"))) - ci.push("circleci/config.yml"); + if (await fileExists(join(cwd, "circleci", "config.yml"))) ci.push("circleci/config.yml"); return ci; } @@ -118,11 +115,17 @@ async function detectDeployTargets(cwd: string): Promise { if (await fileExists(join(cwd, "fly.toml"))) targets.push("fly"); if (await fileExists(join(cwd, "railway.toml"))) targets.push("railway"); if (await fileExists(join(cwd, "render.yaml"))) targets.push("render"); - if (await fileExists(join(cwd, "wrangler.toml")) || await fileExists(join(cwd, "wrangler.jsonc"))) + if ( + (await fileExists(join(cwd, "wrangler.toml"))) || + (await fileExists(join(cwd, "wrangler.jsonc"))) + ) targets.push("cloudflare-workers"); if (await fileExists(join(cwd, "Dockerfile"))) targets.push("docker"); if (await fileExists(join(cwd, "amplify.yml"))) targets.push("aws-amplify"); - if (await fileExists(join(cwd, "sst.config.ts")) || await fileExists(join(cwd, "sst.config.js"))) + if ( + (await fileExists(join(cwd, "sst.config.ts"))) || + (await fileExists(join(cwd, "sst.config.js"))) + ) targets.push("sst"); return [...new Set(targets)]; } @@ -153,11 +156,7 @@ async function detectDatabaseClients(cwd: string): Promise { async function countFiles(cwd: string): Promise { try { - const { stdout } = await exec( - "git", - ["ls-files"], - { cwd, timeout: 5000 }, - ); + const { stdout } = await exec("git", ["ls-files"], { cwd, timeout: 5000 }); return stdout.split("\n").filter(Boolean).length; } catch { return 0; @@ -233,17 +232,21 @@ export function renderClaudeMd(report: AnalysisReport): string { const stackBits: string[] = []; if (stack.language !== "unknown") stackBits.push(`- **Language**: ${stack.language}`); if (stack.framework) stackBits.push(`- **Framework**: ${stack.framework}`); - if (databaseClients.length) stackBits.push(`- **Database clients**: ${databaseClients.join(", ")}`); + if (databaseClients.length) + stackBits.push(`- **Database clients**: ${databaseClients.join(", ")}`); if (stack.services.length) stackBits.push(`- **Services**: ${stack.services.join(", ")}`); if (testRunners.length) stackBits.push(`- **Tests**: ${testRunners.join(", ")}`); if (deployTargets.length) stackBits.push(`- **Deploy**: ${deployTargets.join(", ")}`); lines.push(...stackBits); lines.push("", "## Development", ""); - const pkgManager = stack.tools["pnpm"] ? "pnpm" - : stack.tools["yarn"] ? "yarn" - : stack.tools["bun"] ? "bun" - : "npm"; + const pkgManager = stack.tools["pnpm"] + ? "pnpm" + : stack.tools["yarn"] + ? "yarn" + : stack.tools["bun"] + ? "bun" + : "npm"; lines.push(`- Install deps: \`${pkgManager} install\``); if (testRunners.length) { lines.push(`- Run tests: \`${pkgManager} test\``); @@ -264,13 +267,9 @@ export function renderClaudeMd(report: AnalysisReport): string { lines.push(`- \`${prefix}\` (${count}×)`); } lines.push(""); - lines.push( - "Match the existing pattern when writing commit messages.", - ); + lines.push("Match the existing pattern when writing commit messages."); } else { - lines.push( - "No conventional-commit prefixes detected. Pick a style and document it here.", - ); + lines.push("No conventional-commit prefixes detected. Pick a style and document it here."); } lines.push("", "## Secrets & env", ""); @@ -315,7 +314,9 @@ export function renderRulesMd(report: AnalysisReport): string { lines.push("- Production env vars live in Vercel; never hard-code keys in code."); } if (deployTargets.includes("fly") || deployTargets.includes("railway")) { - lines.push("- Deployment platform secrets are the source of truth — sync via `kit secrets sync`."); + lines.push( + "- Deployment platform secrets are the source of truth — sync via `kit secrets sync`.", + ); } if (stack.framework === "nextjs") { lines.push("- Server-only env vars must NOT have a `NEXT_PUBLIC_` prefix."); @@ -348,11 +349,6 @@ export function renderRulesMd(report: AnalysisReport): string { "- Open an issue rather than committing speculative work.", ); - lines.push( - "", - "---", - "_Generated by `kit analyze` — edit to match team policy._", - "", - ); + lines.push("", "---", "_Generated by `kit analyze` — edit to match team policy._", ""); return lines.join("\n"); } diff --git a/src/approval.test.ts b/src/approval.test.ts index fbb813a1..9a0c897f 100644 --- a/src/approval.test.ts +++ b/src/approval.test.ts @@ -24,14 +24,8 @@ describe("wouldRequireApproval", () => { enabled: true, approval: { destructive_operations: ["delete", "drop"] }, }; - assert.equal( - wouldRequireApproval(config, "db:delete:users", "dev"), - true, - ); - assert.equal( - wouldRequireApproval(config, "DROP TABLE orders", "dev"), - true, - ); + assert.equal(wouldRequireApproval(config, "db:delete:users", "dev"), true); + assert.equal(wouldRequireApproval(config, "DROP TABLE orders", "dev"), true); }); it("returns true for production writes when configured", () => { @@ -99,11 +93,14 @@ describe("requestApproval - Remote API flow", () => { }); it("returns true when Remote API approves immediately", async () => { - mock.method(globalThis, "fetch", async () => - new Response(JSON.stringify({ status: "approved" }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }), + mock.method( + globalThis, + "fetch", + async () => + new Response(JSON.stringify({ status: "approved" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), ); const config: GovernanceConfig = { @@ -124,11 +121,14 @@ describe("requestApproval - Remote API flow", () => { }); it("returns false when Remote API denies the request", async () => { - mock.method(globalThis, "fetch", async () => - new Response( - JSON.stringify({ status: "denied", reason: "Not authorized" }), - { status: 200, headers: { "Content-Type": "application/json" } }, - ), + mock.method( + globalThis, + "fetch", + async () => + new Response(JSON.stringify({ status: "denied", reason: "Not authorized" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), ); const config: GovernanceConfig = { @@ -151,11 +151,14 @@ describe("requestApproval - Remote API flow", () => { it("returns false on approval timeout when API keeps returning pending", async () => { // approval_timeout: 0 is falsy so code uses 3600 default — use 1s instead // The polling sleep is 2s, so the loop exits after one pending response (~2s) - mock.method(globalThis, "fetch", async () => - new Response(JSON.stringify({ status: "pending" }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }), + mock.method( + globalThis, + "fetch", + async () => + new Response(JSON.stringify({ status: "pending" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), ); const config: GovernanceConfig = { @@ -206,10 +209,7 @@ describe("requestApproval - Remote API flow", () => { "test-company-id", ); - assert.ok( - fetchedUrls.includes(webhookUrl), - "webhook URL should have been called", - ); + assert.ok(fetchedUrls.includes(webhookUrl), "webhook URL should have been called"); }); it("continues when webhook call fails", async () => { diff --git a/src/approval.ts b/src/approval.ts index ed66a477..03eaa7cc 100644 --- a/src/approval.ts +++ b/src/approval.ts @@ -22,10 +22,7 @@ export interface ApprovalResponse { /** * Send approval request to webhook */ -async function sendApprovalWebhook( - request: ApprovalRequest, - webhookUrl: string, -): Promise { +async function sendApprovalWebhook(request: ApprovalRequest, webhookUrl: string): Promise { try { const response = await fetch(webhookUrl, { method: "POST", @@ -43,9 +40,7 @@ async function sendApprovalWebhook( }); if (!response.ok) { - console.error( - `Failed to send approval webhook: ${response.status} ${response.statusText}`, - ); + console.error(`Failed to send approval webhook: ${response.status} ${response.statusText}`); } } catch (error) { console.error("Failed to send approval webhook:", error); @@ -140,16 +135,10 @@ export async function requestApproval( const approvalId = IdGenerators.approval(); const timeout = fullConfig.approval.approval_timeout || 3600; - console.log( - `\nWaiting for approval via Remote API (timeout: ${timeout}s)...`, - ); + console.log(`\nWaiting for approval via Remote API (timeout: ${timeout}s)...`); console.log(`Approval ID: ${approvalId}`); - const result = await waitForRemoteApproval( - approvalId, - companyId, - timeout * 1000, - ); + const result = await waitForRemoteApproval(approvalId, companyId, timeout * 1000); if (result.approved) { console.log("✓ Operation approved"); @@ -179,9 +168,7 @@ export async function requestApproval( }); try { - const answer = await rl.question( - "\nDo you approve this operation? (yes/no): ", - ); + const answer = await rl.question("\nDo you approve this operation? (yes/no): "); rl.close(); return answer.toLowerCase().trim() === "yes"; diff --git a/src/audit-secrets.test.ts b/src/audit-secrets.test.ts index 87b85dae..a3a390e3 100644 --- a/src/audit-secrets.test.ts +++ b/src/audit-secrets.test.ts @@ -3,11 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { - readSecretAuditEvents, - groupBySecret, - summarize, -} from "./audit-secrets.js"; +import { readSecretAuditEvents, groupBySecret, summarize } from "./audit-secrets.js"; function makeRepo(events: object[]): string { const dir = mkdtempSync(join(tmpdir(), "kit-audit-")); @@ -29,9 +25,24 @@ describe("readSecretAuditEvents", () => { it("filters to secret-related operations only", async () => { const dir = makeRepo([ - { timestamp: new Date().toISOString(), operation: "secrets.generate", environment: "dev", success: true }, - { timestamp: new Date().toISOString(), operation: "non.secret.op", environment: "dev", success: true }, - { timestamp: new Date().toISOString(), operation: "secrets.rotate", environment: "dev", success: true }, + { + timestamp: new Date().toISOString(), + operation: "secrets.generate", + environment: "dev", + success: true, + }, + { + timestamp: new Date().toISOString(), + operation: "non.secret.op", + environment: "dev", + success: true, + }, + { + timestamp: new Date().toISOString(), + operation: "secrets.rotate", + environment: "dev", + success: true, + }, ]); try { const events = await readSecretAuditEvents(dir); diff --git a/src/audit-secrets.ts b/src/audit-secrets.ts index e5200f18..c11e793d 100644 --- a/src/audit-secrets.ts +++ b/src/audit-secrets.ts @@ -73,9 +73,10 @@ export async function readSecretAuditEvents( * Extracts secret-related event details, attempting to attribute each event * to one or more specific keys via the metadata payload. */ -export function groupBySecret( - events: AuditEvent[], -): { reports: SecretAuditReport[]; unattributed: SecretAccessEntry[] } { +export function groupBySecret(events: AuditEvent[]): { + reports: SecretAuditReport[]; + unattributed: SecretAccessEntry[]; +} { const byKey = new Map(); const unattributed: SecretAccessEntry[] = []; @@ -138,10 +139,7 @@ export interface AuditSummary { windowDays: number; } -export function summarize( - reports: SecretAuditReport[], - windowDays: number, -): AuditSummary { +export function summarize(reports: SecretAuditReport[], windowDays: number): AuditSummary { const totalEvents = reports.reduce((sum, r) => sum + r.events.length, 0); const top = reports[0]; return { diff --git a/src/audit.ts b/src/audit.ts index 1c0a5406..add46749 100644 --- a/src/audit.ts +++ b/src/audit.ts @@ -67,9 +67,7 @@ async function postToRemoteOnce(event: AuditEvent, companyId: string): Promise= 400 && response.status < 500) { - console.error( - `Remote audit-log rejected (${response.status}); not retrying.`, - ); + console.error(`Remote audit-log rejected (${response.status}); not retrying.`); return false; } } catch (error) { @@ -247,9 +245,7 @@ export function _resetRemotePushWarningForTests(): void { /** * Sanitize metadata to remove potential secrets */ -function sanitizeMetadata( - metadata: Record, -): Record { +function sanitizeMetadata(metadata: Record): Record { const sanitized: Record = {}; const secretKeys = [ "password", @@ -264,9 +260,7 @@ function sanitizeMetadata( for (const [key, value] of Object.entries(metadata)) { const lowerKey = key.toLowerCase(); - const isSecret = secretKeys.some((secretKey) => - lowerKey.includes(secretKey), - ); + const isSecret = secretKeys.some((secretKey) => lowerKey.includes(secretKey)); if (isSecret) { sanitized[key] = "[REDACTED]"; @@ -283,16 +277,16 @@ function sanitizeMetadata( /** * Read recent audit log entries */ -export async function readAuditLog( - logFile: string, - limit = 100, -): Promise { +export async function readAuditLog(logFile: string, limit = 100): Promise { const { readFile } = await import("node:fs/promises"); const logPath = resolve(process.cwd(), logFile); try { const content = await readFile(logPath, "utf-8"); - const lines = content.trim().split("\n").filter((line) => line.length > 0); + const lines = content + .trim() + .split("\n") + .filter((line) => line.length > 0); // Get last N lines const recentLines = lines.slice(-limit); diff --git a/src/baseline.test.ts b/src/baseline.test.ts index 7fb32877..7aaf58d4 100644 --- a/src/baseline.test.ts +++ b/src/baseline.test.ts @@ -55,10 +55,7 @@ describe("loadBaseline", () => { join(dir, BASELINE_FILE), JSON.stringify({ version: 2, generated: "x", categories: {} }), ); - await assert.rejects( - () => loadBaseline(dir), - /unsupported baseline version: 2/, - ); + await assert.rejects(() => loadBaseline(dir), /unsupported baseline version: 2/); } finally { rmSync(dir, { recursive: true, force: true }); } @@ -153,10 +150,7 @@ describe("saveBaseline", () => { }; await saveBaseline(b, dir); const reloaded = await loadBaseline(dir); - assert.deepEqual( - reloaded.categories.tests.untested_files, - ["a", "b"], - ); + assert.deepEqual(reloaded.categories.tests.untested_files, ["a", "b"]); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/src/budget.ts b/src/budget.ts index a0d32496..b425b854 100644 --- a/src/budget.ts +++ b/src/budget.ts @@ -42,10 +42,7 @@ export async function checkBudgetLimits( // Check operation limit const operationLimit = fullConfig.agent.max_operations_per_hour; - if ( - operationLimit && - resetState.operations_this_hour >= operationLimit - ) { + if (operationLimit && resetState.operations_this_hour >= operationLimit) { return { allowed: false, reason: `Operation budget exceeded: ${resetState.operations_this_hour}/${operationLimit} operations this hour`, @@ -117,10 +114,7 @@ async function saveBudgetState(state: BudgetState): Promise { /** * Reset counters if time periods have elapsed */ -function resetCountersIfNeeded( - state: BudgetState, - now: Date, -): BudgetState { +function resetCountersIfNeeded(state: BudgetState, now: Date): BudgetState { const newState = { ...state }; // Reset token counter at midnight @@ -134,8 +128,7 @@ function resetCountersIfNeeded( // Reset operation counter every hour const lastOperationReset = new Date(state.last_operation_reset); - const elapsedHours = - (now.getTime() - lastOperationReset.getTime()) / (1000 * 60 * 60); + const elapsedHours = (now.getTime() - lastOperationReset.getTime()) / (1000 * 60 * 60); if (elapsedHours >= 1) { newState.operations_this_hour = 0; @@ -148,9 +141,7 @@ function resetCountersIfNeeded( /** * Get current budget status for display */ -export async function getBudgetStatus( - config: GovernanceConfig | undefined, -): Promise<{ +export async function getBudgetStatus(config: GovernanceConfig | undefined): Promise<{ tokens_used: number; tokens_limit: number | undefined; operations_used: number; @@ -184,10 +175,7 @@ export function formatBudgetStatus(status: { lines.push("─".repeat(50)); if (status.tokens_limit) { - const tokenPercent = ( - (status.tokens_used / status.tokens_limit) * - 100 - ).toFixed(1); + const tokenPercent = ((status.tokens_used / status.tokens_limit) * 100).toFixed(1); lines.push( `Tokens: ${status.tokens_used.toLocaleString()}/${status.tokens_limit.toLocaleString()} (${tokenPercent}%)`, ); @@ -196,13 +184,8 @@ export function formatBudgetStatus(status: { } if (status.operations_limit) { - const opPercent = ( - (status.operations_used / status.operations_limit) * - 100 - ).toFixed(1); - lines.push( - `Operations: ${status.operations_used}/${status.operations_limit} (${opPercent}%)`, - ); + const opPercent = ((status.operations_used / status.operations_limit) * 100).toFixed(1); + lines.push(`Operations: ${status.operations_used}/${status.operations_limit} (${opPercent}%)`); } else { lines.push(`Operations: ${status.operations_used} (no limit)`); } diff --git a/src/bumblebee.ts b/src/bumblebee.ts index c004d665..2880f342 100644 --- a/src/bumblebee.ts +++ b/src/bumblebee.ts @@ -54,8 +54,7 @@ export interface EnsureResult { */ export const BUMBLEBEE_VERSION = "0.1.1"; -const RELEASE_BASE_URL = - "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/perplexityai/bumblebee/releases/download"; +const RELEASE_BASE_URL = "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/perplexityai/bumblebee/releases/download"; /** * SHA-256 of each release tarball, copied from the pinned release's @@ -91,8 +90,7 @@ export function resolveTarget( arch: string = process.arch, version: string = BUMBLEBEE_VERSION, ): PlatformTarget | null { - const os = - platform === "linux" ? "linux" : platform === "darwin" ? "darwin" : null; + const os = platform === "linux" ? "linux" : platform === "darwin" ? "darwin" : null; const a = arch === "x64" ? "amd64" : arch === "arm64" ? "arm64" : null; if (!os || !a) return null; @@ -177,9 +175,7 @@ export interface EnsureOptions { * a freshly downloaded-and-verified release. Returns the install on success, * or a human-readable `reason` when unavailable (never throws). */ -export async function ensureBumblebee( - opts: EnsureOptions = {}, -): Promise { +export async function ensureBumblebee(opts: EnsureOptions = {}): Promise { // Explicit override for users who manage their own binary/catalog. const envBin = process.env.KIT_BUMBLEBEE_BIN; if (envBin) { @@ -189,8 +185,7 @@ export async function ensureBumblebee( reason: `KIT_BUMBLEBEE_BIN points to a missing file: ${envBin}`, }; } - const catalogDir = - process.env.KIT_BUMBLEBEE_CATALOG || join(cacheRoot(), "threat_intel"); + const catalogDir = process.env.KIT_BUMBLEBEE_CATALOG || join(cacheRoot(), "threat_intel"); return { install: { binPath: envBin, catalogDir } }; } @@ -207,7 +202,11 @@ export async function ensureBumblebee( const catalogDir = join(root, "threat_intel"); const sidecarPath = join(root, "bumblebee.sha256"); - if ((await pathExists(binPath)) && (await pathExists(catalogDir)) && (await pathExists(sidecarPath))) { + if ( + (await pathExists(binPath)) && + (await pathExists(catalogDir)) && + (await pathExists(sidecarPath)) + ) { // F3 — re-verify the cached binary against the hash recorded at trusted // INSTALL time (the sidecar), NOT the tarball checksum. The pinned // TARBALL_CHECKSUMS gate the DOWNLOAD (authoritative supply-chain anchor); @@ -238,16 +237,13 @@ export async function ensureBumblebee( if (opts.allowDownload === false) { return { kind: "network", - reason: - "scanner not cached and downloads are disabled (KIT_NO_DOWNLOAD)", + reason: "scanner not cached and downloads are disabled (KIT_NO_DOWNLOAD)", }; } try { const notice = opts.notice ?? ((m: string) => process.stderr.write(m + "\n")); - notice( - `kit: downloading supply-chain scanner bumblebee v${BUMBLEBEE_VERSION} (one-time)…`, - ); + notice(`kit: downloading supply-chain scanner bumblebee v${BUMBLEBEE_VERSION} (one-time)…`); await downloadAndInstall(target, root, opts.timeoutMs ?? 120_000); return { install: { binPath, catalogDir } }; } catch (err) { @@ -402,8 +398,7 @@ export function parseScanOutput(stdout: string): ScanOutcome { const emitted = num(rec.package_records_emitted); const suppressed = num(rec.package_records_suppressed); const counts = rec.counts as Record | undefined; - outcome.packagesScanned = - emitted + suppressed || num(counts?.package); + outcome.packagesScanned = emitted + suppressed || num(counts?.package); } } diff --git a/src/check-design.ts b/src/check-design.ts index 389c63f5..549a11dc 100644 --- a/src/check-design.ts +++ b/src/check-design.ts @@ -88,7 +88,8 @@ const A11Y_RULES: Array<{ id: string; pattern: RegExp; description: string }> = id: "input-no-label", // with no aria-label/aria-labelledby (label-association is harder // to verify statically, so we only flag the obvious missing-aria case) - pattern: /]*\baria-label(?:ledby)?\s*=)(?![^>]*\btype\s*=\s*['"](?:hidden|submit|button)['"])[^>]*\/?>/, + pattern: + /]*\baria-label(?:ledby)?\s*=)(?![^>]*\btype\s*=\s*['"](?:hidden|submit|button)['"])[^>]*\/?>/, description: " without aria-label (and not type=hidden/submit/button)", }, ]; @@ -131,10 +132,7 @@ interface TokenBypass { match: string; } -async function scanTokenBypass( - srcRoots: string[], - tokenFiles: string[], -): Promise { +async function scanTokenBypass(srcRoots: string[], tokenFiles: string[]): Promise { const findings: TokenBypass[] = []; for (const root of srcRoots) { if (!(await pathExists(root))) continue; @@ -175,12 +173,14 @@ async function scanTokenBypass( return findings; } -export async function checkDesign(opts: { - srcRoots?: string[]; - tokenFiles?: string[]; - enforce?: boolean; - baseline?: { a11y?: string[]; tokens?: string[] }; -} = {}): Promise { +export async function checkDesign( + opts: { + srcRoots?: string[]; + tokenFiles?: string[]; + enforce?: boolean; + baseline?: { a11y?: string[]; tokens?: string[] }; + } = {}, +): Promise { const srcRoots = (opts.srcRoots ?? ["src", "app", "components"]).map((d) => resolve(process.cwd(), d), ); diff --git a/src/check-disk-encryption.ts b/src/check-disk-encryption.ts index aaba238d..808b0944 100644 --- a/src/check-disk-encryption.ts +++ b/src/check-disk-encryption.ts @@ -76,7 +76,12 @@ export async function checkDiskEncryption(): Promise { const { stdout } = await exec("fdesetup", ["status"], { timeout: 5_000 }); const on = interpretFileVault(stdout); if (on === true) { - return { category: "exposure", name: "disk encryption", status: "pass", detail: "FileVault is enabled" }; + return { + category: "exposure", + name: "disk encryption", + status: "pass", + detail: "FileVault is enabled", + }; } if (on === false) { return { @@ -84,7 +89,8 @@ export async function checkDiskEncryption(): Promise { name: "disk encryption", status: "warn", severity: "high", - detail: "FileVault is OFF — kit's local secret-dense store (~/.kit/memory.db) is unencrypted at rest", + detail: + "FileVault is OFF — kit's local secret-dense store (~/.kit/memory.db) is unencrypted at rest", suggestion: "Enable FileVault: System Settings → Privacy & Security → FileVault", }; } @@ -95,7 +101,12 @@ export async function checkDiskEncryption(): Promise { const { stdout } = await exec("manage-bde", ["-status", "C:"], { timeout: 8_000 }); const on = interpretBitLocker(stdout); if (on === true) { - return { category: "exposure", name: "disk encryption", status: "pass", detail: "BitLocker protection is on" }; + return { + category: "exposure", + name: "disk encryption", + status: "pass", + detail: "BitLocker protection is on", + }; } if (on === false) { return { @@ -113,7 +124,12 @@ export async function checkDiskEncryption(): Promise { if (process.platform === "linux") { const { stdout } = await exec("lsblk", ["-o", "TYPE"], { timeout: 5_000 }); if (interpretLsblk(stdout) === true) { - return { category: "exposure", name: "disk encryption", status: "pass", detail: "LUKS-encrypted volume detected" }; + return { + category: "exposure", + name: "disk encryption", + status: "pass", + detail: "LUKS-encrypted volume detected", + }; } // No crypt device found. Per this module's fail-open contract, absence is // NOT proof FDE is off (encrypted host VM, LVM-on-LUKS not surfaced, etc.), @@ -121,8 +137,10 @@ export async function checkDiskEncryption(): Promise { // rather than cry wolf with a warn that would flip kit check's exit code. return { ...SKIP, - detail: "could not confirm full-disk encryption on Linux (no LUKS device found) — verify your disk is encrypted", - suggestion: "Confirm with: lsblk (look for type 'crypt'), or your distro's disk-encryption settings", + detail: + "could not confirm full-disk encryption on Linux (no LUKS device found) — verify your disk is encrypted", + suggestion: + "Confirm with: lsblk (look for type 'crypt'), or your distro's disk-encryption settings", }; } @@ -147,7 +165,8 @@ export function checkMemoryDirSafety(): SecurityCheckResult { status: "warn", severity: "high", detail: `kit memory store (${memDir}) is inside the repo working tree — the secret-dense DB could be committed`, - suggestion: "Unset KIT_MEMORY_DIR (defaults to ~/.kit, outside any repo) or point it outside the working tree", + suggestion: + "Unset KIT_MEMORY_DIR (defaults to ~/.kit, outside any repo) or point it outside the working tree", }; } return { @@ -157,6 +176,11 @@ export function checkMemoryDirSafety(): SecurityCheckResult { detail: "memory store lives outside the repo working tree", }; } catch { - return { category: "exposure", name: "memory store location", status: "skip", detail: "could not resolve memory store / repo root" }; + return { + category: "exposure", + name: "memory store location", + status: "skip", + detail: "could not resolve memory store / repo root", + }; } } diff --git a/src/check-gitignore.test.ts b/src/check-gitignore.test.ts index d9590ef5..266aa992 100644 --- a/src/check-gitignore.test.ts +++ b/src/check-gitignore.test.ts @@ -4,11 +4,7 @@ import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { execSync } from "node:child_process"; -import { - checkGitignore, - patchGitignore, - findCommittedSensitive, -} from "./check-gitignore.js"; +import { checkGitignore, patchGitignore, findCommittedSensitive } from "./check-gitignore.js"; function tmpRepo(): string { return mkdtempSync(join(tmpdir(), "kit-gi-")); @@ -57,10 +53,7 @@ describe("checkGitignore", () => { it("ignores comments and blank lines", async () => { const dir = tmpRepo(); try { - writeFileSync( - join(dir, ".gitignore"), - "\n# comment\n.env\n # indented comment\n\n", - ); + writeFileSync(join(dir, ".gitignore"), "\n# comment\n.env\n # indented comment\n\n"); const r = await checkGitignore(dir); // .env is present, .env.local is not (no alias for bare `.env`) const stillMissing = r.missingPatterns.map((m) => m.pattern); @@ -108,8 +101,7 @@ describe("patchGitignore", () => { await patchGitignore(dir); const second = readFileSync(join(dir, ".gitignore"), "utf-8"); // Same number of marker-start tokens (exactly 1) both times - const count = (s: string) => - (s.match(/kit security check-gitignore/g) || []).length; + const count = (s: string) => (s.match(/kit security check-gitignore/g) || []).length; assert.equal(count(first), 1); assert.equal(count(second), 1); } finally { diff --git a/src/check-gitignore.ts b/src/check-gitignore.ts index 7381a811..8f8b363e 100644 --- a/src/check-gitignore.ts +++ b/src/check-gitignore.ts @@ -31,7 +31,11 @@ interface RequiredEntry { const REQUIRED_PATTERNS: RequiredEntry[] = [ { pattern: ".env", reason: "default dotenv file", aliases: [".env*", "**/.env"] }, - { pattern: ".env.local", reason: "local secrets materialized by kit secrets", aliases: [".env*"] }, + { + pattern: ".env.local", + reason: "local secrets materialized by kit secrets", + aliases: [".env*"], + }, { pattern: ".env.*.local", reason: "per-env local secrets", aliases: [".env*"] }, { pattern: "node_modules", reason: "dependency tree", aliases: ["node_modules/"] }, // Ignore kit's local-state CONTENTS via `.kit/*` (not the wholesale `.kit/`): @@ -39,8 +43,16 @@ const REQUIRED_PATTERNS: RequiredEntry[] = [ // negation cannot re-include the curated, committed-by-design shared tier // (.kit/shared/memory.jsonl). `.kit/*` ignores the contents while leaving the // dir descendable, so the negation below works. - { pattern: ".kit/*", reason: "kit local state (elevation, env, runtime)", aliases: [".kit", ".kit/", ".kit/*"] }, - { pattern: "!.kit/shared/", reason: "keep curated shared memory tracked (committed by design)", aliases: ["!.kit/shared", "!.kit/shared/**"] }, + { + pattern: ".kit/*", + reason: "kit local state (elevation, env, runtime)", + aliases: [".kit", ".kit/", ".kit/*"], + }, + { + pattern: "!.kit/shared/", + reason: "keep curated shared memory tracked (committed by design)", + aliases: ["!.kit/shared", "!.kit/shared/**"], + }, { pattern: ".kit-audit.jsonl", reason: "audit log can contain secret labels + paths" }, { pattern: "*.pem", reason: "PEM keys / certs" }, { pattern: "*.key", reason: "private keys" }, @@ -63,9 +75,7 @@ function parseGitignore(text: string): string[] { .filter((l) => l.length > 0); } -export async function checkGitignore( - cwd: string = process.cwd(), -): Promise { +export async function checkGitignore(cwd: string = process.cwd()): Promise { const path = resolve(cwd, ".gitignore"); let exists = false; let lines: string[] = []; @@ -150,18 +160,12 @@ export async function patchGitignore( * filenames. Useful for the "already committed before .gitignore was set * up" case where adding the pattern doesn't help. */ -export async function findCommittedSensitive( - cwd: string = process.cwd(), -): Promise { +export async function findCommittedSensitive(cwd: string = process.cwd()): Promise { const { execFile } = await import("node:child_process"); const { promisify } = await import("node:util"); const exec = promisify(execFile); try { - const { stdout } = await exec( - "git", - ["ls-files"], - { cwd, timeout: 5_000 }, - ); + const { stdout } = await exec("git", ["ls-files"], { cwd, timeout: 5_000 }); const tracked = stdout.split("\n").filter(Boolean); const offenders: string[] = []; for (const path of tracked) { @@ -169,11 +173,10 @@ export async function findCommittedSensitive( // `.env`, `.env.local`, `.env.local.prod-backup`, etc. // Excluded as harmless: any path that ends in `.template`, // `.example`, `.sample` (covers `.env.staging.example` too). - if ( - /^\.env(\..+)?$/.test(base) && - !/\.(template|example|sample)$/.test(base) - ) offenders.push(path); - if (base.endsWith(".pem") || base.endsWith(".key") || base.endsWith(".p12")) offenders.push(path); + if (/^\.env(\..+)?$/.test(base) && !/\.(template|example|sample)$/.test(base)) + offenders.push(path); + if (base.endsWith(".pem") || base.endsWith(".key") || base.endsWith(".p12")) + offenders.push(path); if (base === "id_rsa" || base.startsWith("id_rsa.")) offenders.push(path); if (base === "id_ed25519" || base.startsWith("id_ed25519.")) offenders.push(path); if (/-service-account.*\.json$/.test(base)) offenders.push(path); diff --git a/src/check-hooks.test.ts b/src/check-hooks.test.ts index b4996b53..ee81a61f 100644 --- a/src/check-hooks.test.ts +++ b/src/check-hooks.test.ts @@ -68,11 +68,7 @@ describe("checkHooks", () => { it("reports not managed by kit when hook lacks the marker", async () => { await mkdir(join(gitDir, "hooks"), { recursive: true }); - await writeFile( - join(gitDir, "hooks", "pre-commit"), - "#!/bin/sh\nnpm test\n", - "utf-8", - ); + await writeFile(join(gitDir, "hooks", "pre-commit"), "#!/bin/sh\nnpm test\n", "utf-8"); const config: HooksConfig = { "pre-commit": ["npm test"] }; const results = await checkHooks(config); diff --git a/src/check-hooks.ts b/src/check-hooks.ts index f08d1597..7d07dd5d 100644 --- a/src/check-hooks.ts +++ b/src/check-hooks.ts @@ -13,10 +13,7 @@ export interface HookCheckResult { /** * Check if git hooks are installed and up-to-date */ -export async function checkHooks( - config: HooksConfig, - gitDir = ".git", -): Promise { +export async function checkHooks(config: HooksConfig, gitDir = ".git"): Promise { const results: HookCheckResult[] = []; const hooksDir = resolve(process.cwd(), gitDir, "hooks"); @@ -73,9 +70,7 @@ async function checkHook( hookName, installed: true, upToDate, - detail: upToDate - ? `${commands.length} command(s)` - : "outdated (run kit hooks install)", + detail: upToDate ? `${commands.length} command(s)` : "outdated (run kit hooks install)", }; } catch (error) { return { diff --git a/src/check-lock.ts b/src/check-lock.ts index c89a64e8..7e90b894 100644 --- a/src/check-lock.ts +++ b/src/check-lock.ts @@ -40,7 +40,7 @@ export async function checkLockFiles(config: kitConfig): Promise 0 - ? ` (${authRequired.length} require auth: ${authRequired.map(s => skillsLock.skills[s].auth).filter((v, i, a) => a.indexOf(v) === i).join(", ")})` - : ""; + const authDetails = + authRequired.length > 0 + ? ` (${authRequired.length} require auth: ${authRequired + .map((s) => skillsLock.skills[s].auth) + .filter((v, i, a) => a.indexOf(v) === i) + .join(", ")})` + : ""; results.push({ category: "skills-lock", @@ -83,7 +87,7 @@ export async function checkLockFiles(config: kitConfig): Promise 0 - ? ` (${authRequired.length} require auth: ${authRequired.map(t => cliLock.tools[t].auth).filter((v, i, a) => a.indexOf(v) === i).join(", ")})` - : ""; + const authDetails = + authRequired.length > 0 + ? ` (${authRequired.length} require auth: ${authRequired + .map((t) => cliLock.tools[t].auth) + .filter((v, i, a) => a.indexOf(v) === i) + .join(", ")})` + : ""; results.push({ category: "cli-lock", diff --git a/src/check-secrets.ts b/src/check-secrets.ts index 778bad3c..bc0bb959 100644 --- a/src/check-secrets.ts +++ b/src/check-secrets.ts @@ -3,7 +3,6 @@ import type { SecretsConfig, SecretKeyConfig, InfisicalConfig } from "./config.j import { check1PasswordStatus } from "./onepassword.js"; import { exec } from "./utils/exec.js"; - export interface SecretStatus { name: string; source: string; @@ -125,7 +124,9 @@ async function checkEasSecret(name: string): Promise<{ available: boolean; detai } } -async function checkBitwardenSecret(fieldName: string): Promise<{ available: boolean; detail: string }> { +async function checkBitwardenSecret( + fieldName: string, +): Promise<{ available: boolean; detail: string }> { try { const { stdout } = await exec("bw", ["get", fieldName], { timeout: 10_000, @@ -140,7 +141,9 @@ async function checkBitwardenSecret(fieldName: string): Promise<{ available: boo } } -async function checkDopplerSecret(secretName: string): Promise<{ available: boolean; detail: string }> { +async function checkDopplerSecret( + secretName: string, +): Promise<{ available: boolean; detail: string }> { try { const { stdout } = await exec("doppler", ["secrets", "get", secretName, "--plain"], { timeout: 10_000, @@ -191,7 +194,16 @@ async function checkAwsSecret( config: SecretKeyConfig, ): Promise<{ available: boolean; detail: string }> { const secretId = config.name || config.ref || name; - const args = ["secretsmanager", "get-secret-value", "--secret-id", secretId, "--query", "SecretString", "--output", "text"]; + const args = [ + "secretsmanager", + "get-secret-value", + "--secret-id", + secretId, + "--query", + "SecretString", + "--output", + "text", + ]; if (config.aws_region) { args.push("--region", config.aws_region); } @@ -199,9 +211,10 @@ async function checkAwsSecret( const { stdout } = await exec("aws", args, { timeout: 15_000 }); return { available: !!stdout.trim() && stdout.trim() !== "None", - detail: stdout.trim() && stdout.trim() !== "None" - ? "Found in AWS Secrets Manager" - : "Empty in AWS Secrets Manager", + detail: + stdout.trim() && stdout.trim() !== "None" + ? "Found in AWS Secrets Manager" + : "Empty in AWS Secrets Manager", }; } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); @@ -209,7 +222,10 @@ async function checkAwsSecret( return { available: false, detail: "AWS: secret not found" }; } if (msg.includes("ExpiredToken") || msg.includes("InvalidClientTokenId")) { - return { available: false, detail: "AWS: credentials expired or invalid (run 'aws sso login')" }; + return { + available: false, + detail: "AWS: credentials expired or invalid (run 'aws sso login')", + }; } if (msg.includes("ENOENT")) { return { available: false, detail: "AWS CLI not installed" }; @@ -262,7 +278,19 @@ async function checkAzureSecret( detail: "Azure: azure_vault or AZURE_KEYVAULT_NAME required", }; } - const args = ["keyvault", "secret", "show", "--vault-name", vault, "--name", secretName, "--query", "value", "-o", "tsv"]; + const args = [ + "keyvault", + "secret", + "show", + "--vault-name", + vault, + "--name", + secretName, + "--query", + "value", + "-o", + "tsv", + ]; try { const { stdout } = await exec("az", args, { timeout: 15_000 }); return { @@ -304,49 +332,50 @@ export async function checkSecrets( for (const [name, config] of Object.entries(secrets.keys)) { let result: { available: boolean; detail: string }; - switch (config.source) { - case "env": - result = await checkEnvSecret(name); - break; - case "1password": - result = config.ref - ? await check1PasswordSecret(config.ref, opCache) - : { available: false, detail: "No 1Password ref configured" }; - break; - case "config": - result = await checkConfigSecret(config.value || ""); - break; - case "eas": - result = await checkEasSecret(config.name || name); - break; - case "infisical": - result = await checkInfisicalSecret(config.name || name, secrets.infisical); - break; - case "bitwarden": - result = config.name || config.ref - ? await checkBitwardenSecret(config.name || config.ref || name) - : { available: false, detail: "No Bitwarden field name configured" }; - break; - case "doppler": - result = config.name - ? await checkDopplerSecret(config.name) - : { available: false, detail: "No Doppler secret name configured" }; - break; - case "vault": - result = await checkVaultSecret(config); - break; - case "aws-sm": - result = await checkAwsSecret(name, config); - break; - case "gcp-sm": - result = await checkGcpSecret(name, config); - break; - case "azure-kv": - result = await checkAzureSecret(name, config); - break; - default: - result = { available: false, detail: `Unknown source: ${config.source}` }; - } + switch (config.source) { + case "env": + result = await checkEnvSecret(name); + break; + case "1password": + result = config.ref + ? await check1PasswordSecret(config.ref, opCache) + : { available: false, detail: "No 1Password ref configured" }; + break; + case "config": + result = await checkConfigSecret(config.value || ""); + break; + case "eas": + result = await checkEasSecret(config.name || name); + break; + case "infisical": + result = await checkInfisicalSecret(config.name || name, secrets.infisical); + break; + case "bitwarden": + result = + config.name || config.ref + ? await checkBitwardenSecret(config.name || config.ref || name) + : { available: false, detail: "No Bitwarden field name configured" }; + break; + case "doppler": + result = config.name + ? await checkDopplerSecret(config.name) + : { available: false, detail: "No Doppler secret name configured" }; + break; + case "vault": + result = await checkVaultSecret(config); + break; + case "aws-sm": + result = await checkAwsSecret(name, config); + break; + case "gcp-sm": + result = await checkGcpSecret(name, config); + break; + case "azure-kv": + result = await checkAzureSecret(name, config); + break; + default: + result = { available: false, detail: `Unknown source: ${config.source}` }; + } keys.push({ name, diff --git a/src/check-security.test.ts b/src/check-security.test.ts index 40e54510..6214534c 100644 --- a/src/check-security.test.ts +++ b/src/check-security.test.ts @@ -6,7 +6,9 @@ describe("parseTrivyMisconfigCount", () => { it("counts only HIGH/CRITICAL misconfigurations", () => { const json = JSON.stringify({ Results: [ - { Misconfigurations: [{ Severity: "HIGH" }, { Severity: "LOW" }, { Severity: "CRITICAL" }] }, + { + Misconfigurations: [{ Severity: "HIGH" }, { Severity: "LOW" }, { Severity: "CRITICAL" }], + }, { Misconfigurations: [{ Severity: "MEDIUM" }] }, ], }); @@ -64,26 +66,44 @@ describe("checkSecurity", () => { assert.ok(result.detail, "should have a detail"); assert.ok( ["pass", "fail", "warn", "skip"].includes(result.status), - `status should be valid: ${result.status}` + `status should be valid: ${result.status}`, ); } }); it("includes npm audit check", () => { - assert.ok(cached.find((r) => r.name === "npm audit"), "should include npm audit check"); + assert.ok( + cached.find((r) => r.name === "npm audit"), + "should include npm audit check", + ); }); it("includes service exposure checks", () => { - assert.ok(cached.find((r) => r.name === "Ollama"), "should include Ollama exposure check"); - assert.ok(cached.find((r) => r.name === "Remote API"), "should include Remote API exposure check"); + assert.ok( + cached.find((r) => r.name === "Ollama"), + "should include Ollama exposure check", + ); + assert.ok( + cached.find((r) => r.name === "Remote API"), + "should include Remote API exposure check", + ); }); it("includes supply chain checks", () => { - assert.ok(cached.find((r) => r.name === "pinned versions"), "should include pinned versions check"); + assert.ok( + cached.find((r) => r.name === "pinned versions"), + "should include pinned versions check", + ); }); it("includes secrets checks", () => { - assert.ok(cached.find((r) => r.name === ".env gitignored"), "should include .env gitignored check"); - assert.ok(cached.find((r) => r.name === "secrets scan"), "should include secrets scan check"); + assert.ok( + cached.find((r) => r.name === ".env gitignored"), + "should include .env gitignored check", + ); + assert.ok( + cached.find((r) => r.name === "secrets scan"), + "should include secrets scan check", + ); }); }); diff --git a/src/check-security.ts b/src/check-security.ts index d11bc7c8..837fdb42 100644 --- a/src/check-security.ts +++ b/src/check-security.ts @@ -27,9 +27,7 @@ function envFlagEnabled(value: string | undefined): boolean { } /** Map a bumblebee severity label to the SecurityCheckResult severity scale. */ -function toResultSeverity( - label: string | null, -): SecurityCheckResult["severity"] { +function toResultSeverity(label: string | null): SecurityCheckResult["severity"] { switch ((label ?? "").toLowerCase()) { case "critical": return "critical"; @@ -89,7 +87,7 @@ async function checkNpmAudit(): Promise { const vulnerabilities = auditResult.metadata?.vulnerabilities || {}; const high = vulnerabilities.high || 0; const critical = vulnerabilities.critical || 0; - + if (high > 0 || critical > 0) { return { category: "dependency", @@ -103,7 +101,7 @@ async function checkNpmAudit(): Promise { // JSON parse failed, treat as fail } } - + return { category: "dependency", name: "npm audit", @@ -150,10 +148,10 @@ async function checkPipAudit(): Promise { const { stdout } = await exec(pipAuditBin, ["--format=json"], { timeout: 30_000, }); - + const result = JSON.parse(stdout); const vulns = result.dependencies || []; - + if (vulns.length === 0) { return { category: "dependency", @@ -162,11 +160,11 @@ async function checkPipAudit(): Promise { detail: "no vulnerabilities found", }; } - - const highSeverity = vulns.filter((v: { vulnerabilities?: Array<{ severity?: string }> }) => - v.vulnerabilities?.some(vuln => vuln.severity === "high" || vuln.severity === "critical") + + const highSeverity = vulns.filter((v: { vulnerabilities?: Array<{ severity?: string }> }) => + v.vulnerabilities?.some((vuln) => vuln.severity === "high" || vuln.severity === "critical"), ).length; - + return { category: "dependency", name: "pip-audit", @@ -190,16 +188,11 @@ async function checkPipAudit(): Promise { */ async function checkEnvGitignored(): Promise { try { - const gitignoreContent = await readFile( - resolve(process.cwd(), ".gitignore"), - "utf-8" - ); - + const gitignoreContent = await readFile(resolve(process.cwd(), ".gitignore"), "utf-8"); + const envPatterns = [".env", ".env.local", ".env.*.local"]; - const missingPatterns = envPatterns.filter( - pattern => !gitignoreContent.includes(pattern) - ); - + const missingPatterns = envPatterns.filter((pattern) => !gitignoreContent.includes(pattern)); + if (missingPatterns.length === 0) { return { category: "secrets", @@ -208,7 +201,7 @@ async function checkEnvGitignored(): Promise { detail: "all .env patterns in .gitignore", }; } - + return { category: "secrets", name: ".env gitignored", @@ -232,16 +225,16 @@ async function checkEnvGitignored(): Promise { */ async function checkLockfilesCommitted(): Promise { const results: SecurityCheckResult[] = []; - + // Check package-lock.json try { await access(resolve(process.cwd(), "package.json")); - + try { const { stdout } = await exec("git", ["ls-files", "package-lock.json"], { timeout: 5_000, }); - + if (stdout.trim()) { results.push({ category: "supply-chain", @@ -270,16 +263,16 @@ async function checkLockfilesCommitted(): Promise { } catch { // No package.json, skip } - + // Check requirements.txt try { await access(resolve(process.cwd(), "requirements.txt")); - + try { const { stdout } = await exec("git", ["ls-files", "requirements.txt"], { timeout: 5_000, }); - + if (stdout.trim()) { results.push({ category: "supply-chain", @@ -308,7 +301,7 @@ async function checkLockfilesCommitted(): Promise { } catch { // No requirements.txt, skip } - + return results; } @@ -317,15 +310,15 @@ async function checkLockfilesCommitted(): Promise { */ async function checkServiceExposure(): Promise { const results: SecurityCheckResult[] = []; - + // Check Ollama (common port 11434) try { const { stdout: ollamaCheck } = await exec( "sh", ["-c", "command -v ollama && ollama ps 2>/dev/null || echo 'not running'"], - { timeout: 5_000 } + { timeout: 5_000 }, ); - + if (ollamaCheck.includes("not running")) { results.push({ category: "exposure", @@ -338,10 +331,13 @@ async function checkServiceExposure(): Promise { try { const { stdout: netstat } = await exec( "sh", - ["-c", "ss -tlnp 2>/dev/null | grep :11434 || netstat -tlnp 2>/dev/null | grep :11434 || echo 'no listener'"], - { timeout: 5_000 } + [ + "-c", + "ss -tlnp 2>/dev/null | grep :11434 || netstat -tlnp 2>/dev/null | grep :11434 || echo 'no listener'", + ], + { timeout: 5_000 }, ); - + if (netstat.includes("0.0.0.0:11434") || netstat.includes(":::11434")) { results.push({ category: "exposure", @@ -382,15 +378,18 @@ async function checkServiceExposure(): Promise { detail: "not installed", }); } - + // Check Remote API (common port 3199) try { const { stdout: netstat } = await exec( "sh", - ["-c", "ss -tlnp 2>/dev/null | grep :3199 || netstat -tlnp 2>/dev/null | grep :3199 || echo 'no listener'"], - { timeout: 5_000 } + [ + "-c", + "ss -tlnp 2>/dev/null | grep :3199 || netstat -tlnp 2>/dev/null | grep :3199 || echo 'no listener'", + ], + { timeout: 5_000 }, ); - + if (netstat.includes("no listener")) { results.push({ category: "exposure", @@ -422,7 +421,7 @@ async function checkServiceExposure(): Promise { detail: "could not check network exposure", }); } - + return results; } @@ -431,15 +430,12 @@ async function checkServiceExposure(): Promise { */ async function checkPinnedVersions(): Promise { const unpinned: string[] = []; - + // Check package.json try { - const packageJsonContent = await readFile( - resolve(process.cwd(), "package.json"), - "utf-8" - ); + const packageJsonContent = await readFile(resolve(process.cwd(), "package.json"), "utf-8"); const packageJson = JSON.parse(packageJsonContent); - + const checkDeps = (deps: Record | undefined) => { if (!deps) return; for (const [name, version] of Object.entries(deps)) { @@ -449,24 +445,21 @@ async function checkPinnedVersions(): Promise { } } }; - + checkDeps(packageJson.dependencies); checkDeps(packageJson.devDependencies); } catch { // No package.json or parse error } - + // Check requirements.txt try { - const requirementsContent = await readFile( - resolve(process.cwd(), "requirements.txt"), - "utf-8" - ); - + const requirementsContent = await readFile(resolve(process.cwd(), "requirements.txt"), "utf-8"); + for (const line of requirementsContent.split("\n")) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) continue; - + // Check for range specifiers: >=, >, ~=, != if (/[>~!]=?/.test(trimmed)) { unpinned.push(trimmed.split(/\s+/)[0]); @@ -475,7 +468,7 @@ async function checkPinnedVersions(): Promise { } catch { // No requirements.txt or read error } - + if (unpinned.length > 0) { return { category: "supply-chain", @@ -485,7 +478,7 @@ async function checkPinnedVersions(): Promise { severity: "medium", }; } - + return { category: "supply-chain", name: "pinned versions", @@ -509,7 +502,7 @@ async function checkSecretsInCode(): Promise { detail: "not a git repository", }; } - + // Deep scan with trufflehog — resolve mise-first so a mise-installed one is // used (kit provisions it as a default), not just a bare-PATH one. Throwing // when it's absent falls through to the basic pattern-matching below. @@ -525,7 +518,7 @@ async function checkSecretsInCode(): Promise { const { stdout } = await exec( trufflehogBin, ["git", `file://${process.cwd()}`, "--json", "--no-update"], - { timeout: 90_000 } + { timeout: 90_000 }, ); // trufflehog --json prefixes an info LOG line ({"level":...}); only count @@ -571,13 +564,13 @@ async function checkSecretsInCode(): Promise { "-iE", "(api[_-]?key|secret[_-]?key|password|token|credential)[\"']?\\s*[:=]\\s*[\"'][^\"']{20,}", ], - { timeout: 10_000 } + { timeout: 10_000 }, ); - + if (stdout.trim()) { const lines = stdout.trim().split("\n"); const matches = lines.length; - + // Extract unique filenames const files = new Set(); for (const line of lines) { @@ -586,7 +579,7 @@ async function checkSecretsInCode(): Promise { files.add(match[1]); } } - + const fileArray = Array.from(files); return { @@ -596,18 +589,20 @@ async function checkSecretsInCode(): Promise { detail: `${matches} potential secret(s) in ${files.size} file(s)`, severity: "high", files: fileArray, - suggestion: "Install trufflehog for better detection:\n • macOS/Linux: brew install trufflehog\n • Go: go install github.com/trufflesecurity/trufflehog/v3@latest\n • Or download from: https://github.com/trufflesecurity/trufflehog/releases", + suggestion: + "Install trufflehog for better detection:\n • macOS/Linux: brew install trufflehog\n • Go: go install github.com/trufflesecurity/trufflehog/v3@latest\n • Or download from: https://github.com/trufflesecurity/trufflehog/releases", }; } } catch { // No matches or git grep failed } - + return { category: "secrets", name: "secrets scan", status: "pass", - detail: "basic scan passed (install trufflehog for better detection: brew install trufflehog)", + detail: + "basic scan passed (install trufflehog for better detection: brew install trufflehog)", }; } } @@ -621,7 +616,12 @@ async function checkSocket(): Promise { try { await access(resolve(process.cwd(), "package.json")); } catch { - return { category: "supply-chain", name: "socket scan", status: "skip", detail: "no package.json found" }; + return { + category: "supply-chain", + name: "socket scan", + status: "skip", + detail: "no package.json found", + }; } // Resolve mise-first: kit installs scanners via mise, whose shims aren't on @@ -679,7 +679,12 @@ async function checkSocket(): Promise { }; } - return { category: "supply-chain", name: "socket scan", status: "pass", detail: "no supply chain issues detected" }; + return { + category: "supply-chain", + name: "socket scan", + status: "pass", + detail: "no supply chain issues detected", + }; } /** @@ -687,9 +692,16 @@ async function checkSocket(): Promise { * Catches OS-level vulnerabilities that npm audit misses. */ async function checkTrivy(): Promise { - const hasDockerfile = await access(resolve(process.cwd(), "Dockerfile")).then(() => true).catch(() => false); + const hasDockerfile = await access(resolve(process.cwd(), "Dockerfile")) + .then(() => true) + .catch(() => false); if (!hasDockerfile) { - return { category: "supply-chain", name: "trivy container scan", status: "skip", detail: "no Dockerfile found" }; + return { + category: "supply-chain", + name: "trivy container scan", + status: "skip", + detail: "no Dockerfile found", + }; } // Resolve mise-first (like socket/semgrep): a mise-installed trivy isn't on kit's PATH. @@ -712,7 +724,13 @@ async function checkTrivy(): Promise { ); if (!result.ok && !result.stdout) { - return { category: "supply-chain", name: "trivy container scan", status: "warn", detail: "trivy scan failed", severity: "medium" }; + return { + category: "supply-chain", + name: "trivy container scan", + status: "warn", + detail: "trivy scan failed", + severity: "medium", + }; } try { @@ -722,7 +740,12 @@ async function checkTrivy(): Promise { ); if (vulns.length === 0) { - return { category: "supply-chain", name: "trivy container scan", status: "pass", detail: "no high/critical container vulnerabilities" }; + return { + category: "supply-chain", + name: "trivy container scan", + status: "pass", + detail: "no high/critical container vulnerabilities", + }; } return { category: "supply-chain", @@ -732,7 +755,13 @@ async function checkTrivy(): Promise { severity: "high", }; } catch { - return { category: "supply-chain", name: "trivy container scan", status: "warn", detail: "trivy scan failed", severity: "medium" }; + return { + category: "supply-chain", + name: "trivy container scan", + status: "warn", + detail: "trivy scan failed", + severity: "medium", + }; } } @@ -770,7 +799,11 @@ async function checkTrivyConfig(): Promise { ]; let hasIaC = false; for (const m of fileMarkers) { - if (await access(resolve(cwd, m)).then(() => true).catch(() => false)) { + if ( + await access(resolve(cwd, m)) + .then(() => true) + .catch(() => false) + ) { hasIaC = true; break; } @@ -785,7 +818,12 @@ async function checkTrivyConfig(): Promise { } } if (!hasIaC) { - return { category: "supply-chain", name, status: "skip", detail: "no Dockerfile/Compose/Terraform found" }; + return { + category: "supply-chain", + name, + status: "skip", + detail: "no Dockerfile/Compose/Terraform found", + }; } const trivyBin = await resolveToolBin("trivy"); @@ -807,10 +845,21 @@ async function checkTrivyConfig(): Promise { ); const count = parseTrivyMisconfigCount(result.stdout); if (count < 0) { - return { category: "supply-chain", name, status: "warn", detail: "trivy config scan failed", severity: "medium" }; + return { + category: "supply-chain", + name, + status: "warn", + detail: "trivy config scan failed", + severity: "medium", + }; } if (count === 0) { - return { category: "supply-chain", name, status: "pass", detail: "no high/critical IaC misconfigurations" }; + return { + category: "supply-chain", + name, + status: "pass", + detail: "no high/critical IaC misconfigurations", + }; } return { category: "supply-chain", @@ -853,14 +902,21 @@ async function checkOsvScanner(): Promise { detail: "osv-scanner not installed (mise use aqua:google/osv-scanner)", }; } - const result = await execFileNoThrow(osvBin, ["--format", "json", "-r", "."], { timeout: 120_000 }); + const result = await execFileNoThrow(osvBin, ["--format", "json", "-r", "."], { + timeout: 120_000, + }); const count = parseOsvVulnCount(result.stdout); if (count < 0) { // osv exits non-zero with no JSON when there are no lockfiles to scan. return { category: "supply-chain", name, status: "skip", detail: "no lockfiles to scan" }; } if (count === 0) { - return { category: "supply-chain", name, status: "pass", detail: "no known dependency vulnerabilities" }; + return { + category: "supply-chain", + name, + status: "pass", + detail: "no known dependency vulnerabilities", + }; } return { category: "supply-chain", @@ -878,7 +934,12 @@ async function checkLicenses(): Promise { try { await access(resolve(process.cwd(), "package.json")); } catch { - return { category: "supply-chain", name: "license check", status: "skip", detail: "no package.json found" }; + return { + category: "supply-chain", + name: "license check", + status: "skip", + detail: "no package.json found", + }; } // Try direct binary first (fast). If absent, fall back to `npx --yes @@ -910,14 +971,18 @@ async function checkLicenses(): Promise { } const PROBLEMATIC = ["GPL", "AGPL", "LGPL", "CPAL", "OSL", "EUPL"]; - const result = await execFileNoThrow( - runner.cmd, - [...runner.baseArgs, "--json", "--production"], - { timeout: 120_000 }, - ); + const result = await execFileNoThrow(runner.cmd, [...runner.baseArgs, "--json", "--production"], { + timeout: 120_000, + }); if (!result.ok && !result.stdout) { - return { category: "supply-chain", name: "license check", status: "warn", detail: "license check failed", severity: "low" }; + return { + category: "supply-chain", + name: "license check", + status: "warn", + detail: "license check failed", + severity: "low", + }; } try { @@ -940,9 +1005,20 @@ async function checkLicenses(): Promise { severity: "medium", }; } - return { category: "supply-chain", name: "license check", status: "pass", detail: "no problematic licenses found" }; + return { + category: "supply-chain", + name: "license check", + status: "pass", + detail: "no problematic licenses found", + }; } catch { - return { category: "supply-chain", name: "license check", status: "warn", detail: "license check failed", severity: "low" }; + return { + category: "supply-chain", + name: "license check", + status: "warn", + detail: "license check failed", + severity: "low", + }; } } @@ -971,10 +1047,17 @@ async function checkSemgrep(): Promise { try { const parsed = JSON.parse(raw); const findings: Array<{ extra?: { severity?: string } }> = parsed.results ?? []; - const high = findings.filter((f) => f.extra?.severity === "ERROR" || f.extra?.severity === "WARNING"); + const high = findings.filter( + (f) => f.extra?.severity === "ERROR" || f.extra?.severity === "WARNING", + ); if (high.length === 0) { - return { category: "supply-chain", name: "semgrep SAST", status: "pass", detail: "no security issues found" }; + return { + category: "supply-chain", + name: "semgrep SAST", + status: "pass", + detail: "no security issues found", + }; } return { category: "supply-chain", @@ -984,7 +1067,13 @@ async function checkSemgrep(): Promise { severity: high.some((f) => f.extra?.severity === "ERROR") ? "high" : "medium", }; } catch { - return { category: "supply-chain", name: "semgrep SAST", status: "warn", detail: "semgrep scan failed", severity: "low" }; + return { + category: "supply-chain", + name: "semgrep SAST", + status: "warn", + detail: "semgrep scan failed", + severity: "low", + }; } } @@ -1149,7 +1238,7 @@ export async function checkSecurity(): Promise { checkBumblebee(), checkTrivyConfig(), checkOsvScanner(), - ...await checkLockfilesCommitted(), + ...(await checkLockfilesCommitted()), ]); results.push( diff --git a/src/check-services.ts b/src/check-services.ts index c2389806..0249c553 100644 --- a/src/check-services.ts +++ b/src/check-services.ts @@ -4,7 +4,6 @@ import { redactSecrets } from "./utils/redactSecrets.js"; import { exec } from "./utils/exec.js"; import { resolveToolBin } from "./utils/resolveTool.js"; - export interface ServiceStatus { name: string; checkCommand: string; @@ -32,8 +31,7 @@ async function runCheck( }); return { ok: true, output: redactSecrets((stdout || stderr).trim()) }; } catch (err: unknown) { - const message = - err instanceof Error ? err.message : String(err); + const message = err instanceof Error ? err.message : String(err); return { ok: false, output: redactSecrets(message.split("\n")[0]) }; } } diff --git a/src/check-skills.ts b/src/check-skills.ts index efae0392..e8309921 100644 --- a/src/check-skills.ts +++ b/src/check-skills.ts @@ -10,14 +10,7 @@ export interface SkillCheckResult { installed: boolean; } -const SKILLS_BASE = join( - homedir(), - ".npm-global", - "lib", - "node_modules", - "openclaw", - "skills", -); +const SKILLS_BASE = join(homedir(), ".npm-global", "lib", "node_modules", "openclaw", "skills"); async function isSkillInstalled(name: string): Promise { try { @@ -28,9 +21,7 @@ async function isSkillInstalled(name: string): Promise { } } -export async function checkSkills( - config: SkillsConfig, -): Promise { +export async function checkSkills(config: SkillsConfig): Promise { const results: SkillCheckResult[] = []; for (const [name, versionSpec] of Object.entries(config.required ?? {})) { diff --git a/src/check-tests.ts b/src/check-tests.ts index bfa82e67..c9a0fbef 100644 --- a/src/check-tests.ts +++ b/src/check-tests.ts @@ -28,13 +28,7 @@ export interface TestCheckResult { } const DEFAULT_SRC_DIRS = ["src"]; -const DEFAULT_EXCLUDE_SUFFIXES = [ - ".test.ts", - ".test.js", - ".spec.ts", - ".spec.js", - ".d.ts", -]; +const DEFAULT_EXCLUDE_SUFFIXES = [".test.ts", ".test.js", ".spec.ts", ".spec.js", ".d.ts"]; const DEFAULT_EXCLUDE_NAMES = ["index.ts", "index.js", "types.ts"]; async function pathExists(p: string): Promise { @@ -125,13 +119,15 @@ export async function hasSmokeTests( * Loads baseline (if present) and only counts net-new untested files * against the gate. */ -export async function checkTests(opts: { - cwd?: string; - enforce?: boolean; - requireSmoke?: boolean; - srcDirs?: string[]; - baseline?: string[]; -} = {}): Promise { +export async function checkTests( + opts: { + cwd?: string; + enforce?: boolean; + requireSmoke?: boolean; + srcDirs?: string[]; + baseline?: string[]; + } = {}, +): Promise { const cwd = opts.cwd ?? process.cwd(); const enforce = opts.enforce ?? false; const results: TestCheckResult[] = []; diff --git a/src/check-tools.test.ts b/src/check-tools.test.ts index 8b5b40b2..dac739e7 100644 --- a/src/check-tools.test.ts +++ b/src/check-tools.test.ts @@ -75,10 +75,7 @@ describe("checkTools", () => { }); it("reports not installed when the resolver finds nothing", async () => { - const results = await checkTools( - { "ghost-tool": "1.0" }, - async () => null, - ); + const results = await checkTools({ "ghost-tool": "1.0" }, async () => null); assert.equal(results[0].ok, false); assert.equal(results[0].installed, null); }); diff --git a/src/check-tools.ts b/src/check-tools.ts index 0f7d27f3..82d0de14 100644 --- a/src/check-tools.ts +++ b/src/check-tools.ts @@ -12,10 +12,7 @@ export interface ToolStatus { ok: boolean; } -async function getToolVersion( - tool: string, - resolve: ToolResolver, -): Promise { +async function getToolVersion(tool: string, resolve: ToolResolver): Promise { // Fast path: `mise current` gives the project-pinned version directly when the // tool is declared in the project's mise config. try { diff --git a/src/check-web-search.test.ts b/src/check-web-search.test.ts index 6cab3af9..4af15ad8 100644 --- a/src/check-web-search.test.ts +++ b/src/check-web-search.test.ts @@ -27,9 +27,7 @@ describe("checkWebSearch - searxng", () => { }); it("returns healthy when server responds with 200", async () => { - mock.method(globalThis, "fetch", async () => - new Response("", { status: 200 }), - ); + mock.method(globalThis, "fetch", async () => new Response("", { status: 200 })); const result = await checkWebSearch({ provider: "searxng", @@ -42,9 +40,7 @@ describe("checkWebSearch - searxng", () => { }); it("returns unhealthy when server returns non-ok status", async () => { - mock.method(globalThis, "fetch", async () => - new Response("", { status: 503 }), - ); + mock.method(globalThis, "fetch", async () => new Response("", { status: 503 })); const result = await checkWebSearch({ provider: "searxng", @@ -82,8 +78,10 @@ describe("checkWebSearch - brave", () => { }); it("returns healthy when API key is valid (200 response)", async () => { - mock.method(globalThis, "fetch", async () => - new Response(JSON.stringify({ results: [] }), { status: 200 }), + mock.method( + globalThis, + "fetch", + async () => new Response(JSON.stringify({ results: [] }), { status: 200 }), ); const result = await checkWebSearch({ @@ -96,9 +94,7 @@ describe("checkWebSearch - brave", () => { }); it("returns unhealthy on 401 (invalid key)", async () => { - mock.method(globalThis, "fetch", async () => - new Response("Unauthorized", { status: 401 }), - ); + mock.method(globalThis, "fetch", async () => new Response("Unauthorized", { status: 401 })); const result = await checkWebSearch({ provider: "brave", @@ -111,9 +107,7 @@ describe("checkWebSearch - brave", () => { }); it("returns unhealthy on 403 (forbidden)", async () => { - mock.method(globalThis, "fetch", async () => - new Response("Forbidden", { status: 403 }), - ); + mock.method(globalThis, "fetch", async () => new Response("Forbidden", { status: 403 })); const result = await checkWebSearch({ provider: "brave", @@ -136,8 +130,10 @@ describe("checkWebSearch - google", () => { }); it("returns healthy with valid apiKey + cx (200 response)", async () => { - mock.method(globalThis, "fetch", async () => - new Response(JSON.stringify({ items: [] }), { status: 200 }), + mock.method( + globalThis, + "fetch", + async () => new Response(JSON.stringify({ items: [] }), { status: 200 }), ); const result = await checkWebSearch({ provider: "google", apiKey: "k", cx: "engine-id" }); assert.equal(result.configured, true); @@ -162,9 +158,7 @@ describe("checkWebSearch - custom", () => { }); it("returns healthy on 200", async () => { - mock.method(globalThis, "fetch", async () => - new Response("", { status: 200 }), - ); + mock.method(globalThis, "fetch", async () => new Response("", { status: 200 })); const result = await checkWebSearch({ provider: "custom", @@ -175,9 +169,7 @@ describe("checkWebSearch - custom", () => { }); it("returns healthy on 404 (custom endpoints may lack health endpoint)", async () => { - mock.method(globalThis, "fetch", async () => - new Response("Not Found", { status: 404 }), - ); + mock.method(globalThis, "fetch", async () => new Response("Not Found", { status: 404 })); const result = await checkWebSearch({ provider: "custom", @@ -189,9 +181,7 @@ describe("checkWebSearch - custom", () => { }); it("returns unhealthy on 500", async () => { - mock.method(globalThis, "fetch", async () => - new Response("Error", { status: 500 }), - ); + mock.method(globalThis, "fetch", async () => new Response("Error", { status: 500 })); const result = await checkWebSearch({ provider: "custom", diff --git a/src/check-web-search.ts b/src/check-web-search.ts index f6ee9e06..7cd77fba 100644 --- a/src/check-web-search.ts +++ b/src/check-web-search.ts @@ -97,7 +97,7 @@ export async function checkWebSearch(config?: WebSearchConfig): Promise { testDir = join(tmpdir(), `kit-ci-test-${Date.now()}`); await mkdir(testDir, { recursive: true }); // Minimal .kit.toml with no required tools/services/secrets - await writeFile( - join(testDir, ".kit.toml"), - `[tools]\n`, - "utf8" - ); + await writeFile(join(testDir, ".kit.toml"), `[tools]\n`, "utf8"); }); after(async () => { @@ -44,7 +40,12 @@ describe("kit ci", () => { it("runs without crashing (empty config)", async () => { const { stdout, stderr } = await runCi(["--format=text"]); // Should produce a summary line regardless of pass/fail - assert(stdout.includes("kit ci:") || stderr.includes("kit ci:") || stdout.length > 0 || stderr.length > 0); + assert( + stdout.includes("kit ci:") || + stderr.includes("kit ci:") || + stdout.length > 0 || + stderr.length > 0, + ); }); it("--json outputs valid JSON with ok/checks/summary fields", async () => { @@ -76,7 +77,7 @@ describe("kit ci", () => { await writeFile( join(testDir, ".kit.toml"), `[secrets]\ntemplate = ".env.template"\n[secrets.keys]\nMY_KEY = { source = "env" }\n`, - "utf8" + "utf8", ); const { stdout } = await runCi(["--format=github"], {}); // MY_KEY won't be in env, so should emit ::error:: @@ -93,11 +94,7 @@ describe("kit ci", () => { it("exit code is 1 when there are failures", async () => { // Config with a required tool that doesn't exist - await writeFile( - join(testDir, ".kit.toml"), - `[tools]\nnonexistent-tool-xyz = "1.0"\n`, - "utf8" - ); + await writeFile(join(testDir, ".kit.toml"), `[tools]\nnonexistent-tool-xyz = "1.0"\n`, "utf8"); const { exitCode } = await runCi(["--format=text"]); assert.equal(exitCode, 1); // Restore diff --git a/src/cli-health.test.ts b/src/cli-health.test.ts index 34fed34e..db495309 100644 --- a/src/cli-health.test.ts +++ b/src/cli-health.test.ts @@ -3,7 +3,13 @@ import assert from "node:assert/strict"; import { formatHealth, type HealthFinding } from "./health.js"; const findings: HealthFinding[] = [ - { sensor: "github-actions", source: "acme/webapp", status: "red", severity: "high", title: "workflow failing: CI" }, + { + sensor: "github-actions", + source: "acme/webapp", + status: "red", + severity: "high", + title: "workflow failing: CI", + }, { sensor: "github-actions", source: "acme/webapp", status: "green", title: "all green" }, { sensor: "x", source: "y", status: "unknown", title: "probe errored" }, ]; diff --git a/src/cli.test.ts b/src/cli.test.ts index 66a3a600..c7bc1e56 100644 --- a/src/cli.test.ts +++ b/src/cli.test.ts @@ -34,19 +34,15 @@ async function runCli( env: Record = {}, ): Promise { try { - const { stdout, stderr } = await exec( - process.execPath, - [CLI_PATH, ...args], - { - cwd, - env: { - ...process.env, - // Disable governance to avoid budget state side-effects - ...env, - }, - timeout: 30_000, + const { stdout, stderr } = await exec(process.execPath, [CLI_PATH, ...args], { + cwd, + env: { + ...process.env, + // Disable governance to avoid budget state side-effects + ...env, }, - ); + timeout: 30_000, + }); return { exitCode: 0, stdout: stdout ?? "", stderr: stderr ?? "" }; } catch (err: unknown) { const e = err as { code?: number; stdout?: string; stderr?: string }; @@ -161,7 +157,11 @@ describe("kit --help", () => { await rm(tempDir, { recursive: true, force: true }); }); - const exists = (p: string) => access(p).then(() => true, () => false); + const exists = (p: string) => + access(p).then( + () => true, + () => false, + ); it("agent-config --help prints help and does NOT inject a rules block", async () => { const result = await runCli(["agent-config", "--help"], tempDir); @@ -234,10 +234,7 @@ describe("kit check", () => { await writeFile(join(tempDir, ".kit.toml"), FIXTURE_CONFIG_SECRET, "utf-8"); const result = await runCli(["check"], tempDir); // Should show some output (tables, status indicators) - assert.ok( - result.stdout.length > 0, - "should produce non-empty output", - ); + assert.ok(result.stdout.length > 0, "should produce non-empty output"); }); it("exits 0 with node at latest (always installed)", async () => { @@ -281,7 +278,9 @@ describe("kit fix", () => { try { await access(join(lockDir, "skills-lock.json")); lockExisted = true; - } catch { /* expected */ } + } catch { + /* expected */ + } assert.equal(lockExisted, false, "lock file should not exist before fix"); const result = await runCli(["fix"], tempDir); @@ -290,12 +289,8 @@ describe("kit fix", () => { assert.equal(result.exitCode, 0, `stdout: ${result.stdout}\nstderr: ${result.stderr}`); // Lock files should now exist - const skillsLock = JSON.parse( - await readFile(join(lockDir, "skills-lock.json"), "utf-8"), - ); - const cliLock = JSON.parse( - await readFile(join(lockDir, "cli-lock.json"), "utf-8"), - ); + const skillsLock = JSON.parse(await readFile(join(lockDir, "skills-lock.json"), "utf-8")); + const cliLock = JSON.parse(await readFile(join(lockDir, "cli-lock.json"), "utf-8")); assert.equal(skillsLock.version, 1); assert.equal(cliLock.version, 1); // node should be in the CLI lock @@ -352,20 +347,11 @@ describe("kit setup", () => { const result = await runCli(["setup"], tempDir); // node is already installed so install step should pass - assert.ok( - result.stdout.includes("[1/6]"), - "should show step 1", - ); + assert.ok(result.stdout.includes("[1/6]"), "should show step 1"); // Verify final step ran - assert.ok( - result.stdout.includes("[6/6]"), - "should show step 6", - ); + assert.ok(result.stdout.includes("[6/6]"), "should show step 6"); // Agent-config step should have wired a CLAUDE.md / AGENTS.md block - assert.ok( - result.stdout.includes("Agent config"), - "should run the agent-config step", - ); + assert.ok(result.stdout.includes("Agent config"), "should run the agent-config step"); }); }); @@ -410,7 +396,7 @@ describe("kit version", () => { it("kit version prints the version from package.json", async () => { const pkgJson = await readFile( resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), - "utf-8" + "utf-8", ); const expectedVersion = (JSON.parse(pkgJson) as { version: string }).version; @@ -422,7 +408,7 @@ describe("kit version", () => { it("kit --version prints the version from package.json", async () => { const pkgJson = await readFile( resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), - "utf-8" + "utf-8", ); const expectedVersion = (JSON.parse(pkgJson) as { version: string }).version; @@ -452,7 +438,10 @@ describe("kit whoami", () => { await writeFile(join(tempDir, ".kit.toml"), FIXTURE_EMPTY, "utf-8"); const result = await runCli(["whoami"], tempDir); assert.equal(result.exitCode, 0); - assert.ok(result.stdout.includes("No agent configured"), `expected 'No agent configured' in: ${result.stdout}`); + assert.ok( + result.stdout.includes("No agent configured"), + `expected 'No agent configured' in: ${result.stdout}`, + ); }); it("shows agent name and id when governance.agent configured", async () => { @@ -516,7 +505,7 @@ describe("kit init — auto-generate", () => { await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); const result = await runCli(["init", "--non-interactive"], projectDir); @@ -535,7 +524,7 @@ describe("kit init — auto-generate", () => { await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); const result = await runCli(["init", "--non-interactive"], projectDir); @@ -550,7 +539,7 @@ describe("kit init — auto-generate", () => { await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); await runCli(["init", "--yes"], projectDir); diff --git a/src/cli.ts b/src/cli.ts index a48817fa..96e70e79 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -54,11 +54,7 @@ import { scanBuildArtifacts } from "./scan-build.js"; import { scanTranscripts } from "./scan-transcripts.js"; import { sampleCosts } from "./cost-monitor.js"; import { requireElevation, consumeElevation } from "./elevation.js"; -import { - checkGitignore, - patchGitignore, - findCommittedSensitive, -} from "./check-gitignore.js"; +import { checkGitignore, patchGitignore, findCommittedSensitive } from "./check-gitignore.js"; import { auditPull, reportSeverity } from "./post-pull-audit.js"; import { checkOneCliStatus, @@ -75,17 +71,17 @@ import { checkSkills } from "./check-skills.js"; import { checkLockFiles } from "./check-lock.js"; import { collectEscalations, formatEscalationMessage } from "./escalate.js"; import { - printToolsTable, - printServicesTable, - printSecretsTable, - printSkillsTable, - printWebSearchStatus, - printSecurityTable, - printLockTable, - printSummary, - runStep, - stepHeader, - } from "./output.js"; + printToolsTable, + printServicesTable, + printSecretsTable, + printSkillsTable, + printWebSearchStatus, + printSecurityTable, + printLockTable, + printSummary, + runStep, + stepHeader, +} from "./output.js"; import { checkRevocationStatus } from "./revocation.js"; import { getBudgetStatus, formatBudgetStatus } from "./budget.js"; import { formatGovernanceStatus, mergeGovernanceConfigAsync } from "./governance.js"; @@ -107,7 +103,14 @@ import { promptConfirm } from "./utils/prompt.js"; import { c } from "./utils/colors.js"; import { gatherStatus } from "./status.js"; import { KIT_FILE, resolveConfigPath } from "./cli-shared.js"; -import { checkContext, applyContext, contextPrompt, gatherLive, suggestContextToml, hasLockableContext } from "./context-lock.js"; +import { + checkContext, + applyContext, + contextPrompt, + gatherLive, + suggestContextToml, + hasLockableContext, +} from "./context-lock.js"; import { cmdEnv } from "./commands/env.js"; import { cmdAuth } from "./commands/auth.js"; import { cmdAudit } from "./commands/audit.js"; @@ -151,7 +154,9 @@ interface JsonCheckOutput { async function cmdHeal(): Promise { const dryRun = hasFlag(process.argv, "--dry-run"); const agent = hasFlag(process.argv, "--agent"); - console.log(`${c.bold}${c.cyan}kit heal${c.reset}${dryRun ? `${c.dim} (dry-run)${c.reset}` : ""}`); + console.log( + `${c.bold}${c.cyan}kit heal${c.reset}${dryRun ? `${c.dim} (dry-run)${c.reset}` : ""}`, + ); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); const { runHeal } = await import("./heal.js"); @@ -174,7 +179,9 @@ async function cmdHeal(): Promise { // FAIL-CLOSED — loud, never auto-healed. if (res.failClosed.length > 0) { - console.log(`\n${c.red}${c.bold}⚠ FAIL-CLOSED — not auto-healed (possible tampering):${c.reset}`); + console.log( + `\n${c.red}${c.bold}⚠ FAIL-CLOSED — not auto-healed (possible tampering):${c.reset}`, + ); for (const r of res.failClosed) { console.log(` ${c.red}✗${c.reset} ${r.name}: ${r.detail}`); if (r.suggestion) console.log(` ${c.dim}${r.suggestion}${c.reset}`); @@ -226,9 +233,7 @@ async function cmdCheck(): Promise { const step = (label: string, fn: () => Promise): Promise => live ? runStep(label, fn) : fn(); - const toolResults = config.tools - ? await step("tools", () => checkTools(config.tools!)) - : []; + const toolResults = config.tools ? await step("tools", () => checkTools(config.tools!)) : []; const serviceResults = config.services ? await step("services", () => checkServices(config.services!)) : []; @@ -238,14 +243,14 @@ async function cmdCheck(): Promise { const skillResults = config.skills ? await step("skills", () => checkSkills(config.skills!)) : []; - const hookResults = - config.hooks && isGitRepository() - ? await step("git hooks", () => checkHooks(config.hooks!)) - : []; - const webSearchResult = config.web?.search - ? await step("web search", () => checkWebSearch(config.web!.search!)) - : null; - const securityResults = await step("security scan", () => checkSecurity()); + const hookResults = + config.hooks && isGitRepository() + ? await step("git hooks", () => checkHooks(config.hooks!)) + : []; + const webSearchResult = config.web?.search + ? await step("web search", () => checkWebSearch(config.web!.search!)) + : null; + const securityResults = await step("security scan", () => checkSecurity()); const lockResults = await step("lock files", () => checkLockFiles(config)); // Test-coverage enforcement (--enforce-tests CLI flag overrides config). @@ -297,9 +302,13 @@ async function cmdCheck(): Promise { })), ...serviceResults.map((s) => ({ name: s.name, - status: (s.authenticated ? "pass" : s.informational ? "warn" : "fail") as JsonCheck["status"], + status: (s.authenticated + ? "pass" + : s.informational + ? "warn" + : "fail") as JsonCheck["status"], detail: s.informational - ? (s.output || "manual setup (no CLI login)") + ? s.output || "manual setup (no CLI login)" : (s.output ?? (s.authenticated ? "authenticated" : "not authenticated")), category: "services", })), @@ -326,7 +335,8 @@ async function cmdCheck(): Promise { { name: webSearchResult.provider, status: (webSearchResult.healthy ? "pass" : "fail") as JsonCheck["status"], - detail: webSearchResult.error ?? (webSearchResult.healthy ? "healthy" : "unhealthy"), + detail: + webSearchResult.error ?? (webSearchResult.healthy ? "healthy" : "unhealthy"), category: "web-search", }, ] @@ -367,29 +377,27 @@ async function cmdCheck(): Promise { return allOk; } - printToolsTable(toolResults); - printServicesTable(serviceResults); - printSecretsTable(secretResults.templateExists, secretResults.keys); - printSkillsTable(skillResults); - printWebSearchStatus(webSearchResult); - printLockTable(lockResults); + printToolsTable(toolResults); + printServicesTable(serviceResults); + printSecretsTable(secretResults.templateExists, secretResults.keys); + printSkillsTable(skillResults); + printWebSearchStatus(webSearchResult); + printLockTable(lockResults); - // Print hooks status if configured + // Print hooks status if configured if (hookResults.length > 0) { console.log(`${c.cyan}Git Hooks${c.reset}`); for (const r of hookResults) { - const icon = - !r.installed - ? `${c.red}✗${c.reset}` - : !r.upToDate - ? `${c.yellow}!${c.reset}` - : `${c.green}✓${c.reset}`; - const status = - !r.installed - ? `${c.red}not installed${c.reset}` - : !r.upToDate - ? `${c.yellow}outdated${c.reset}` - : `${c.green}up-to-date${c.reset}`; + const icon = !r.installed + ? `${c.red}✗${c.reset}` + : !r.upToDate + ? `${c.yellow}!${c.reset}` + : `${c.green}✓${c.reset}`; + const status = !r.installed + ? `${c.red}not installed${c.reset}` + : !r.upToDate + ? `${c.yellow}outdated${c.reset}` + : `${c.green}up-to-date${c.reset}`; console.log(` ${icon} ${r.hookName} ${status} ${c.dim}${r.detail}${c.reset}`); } console.log(); @@ -402,10 +410,13 @@ async function cmdCheck(): Promise { console.log(`\n${c.bold}Tests${c.reset}`); for (const r of testResults) { const icon = - r.status === "pass" ? `${c.green}✓${c.reset}` : - r.status === "fail" ? `${c.red}✗${c.reset}` : - r.status === "warn" ? `${c.yellow}!${c.reset}` : - `${c.dim}-${c.reset}`; + r.status === "pass" + ? `${c.green}✓${c.reset}` + : r.status === "fail" + ? `${c.red}✗${c.reset}` + : r.status === "warn" + ? `${c.yellow}!${c.reset}` + : `${c.dim}-${c.reset}`; console.log(` ${icon} ${r.name} ${c.dim}${r.detail}${c.reset}`); if (r.files && r.files.length > 0) { for (const f of r.files) console.log(` ${c.dim}- ${f}${c.reset}`); @@ -440,7 +451,7 @@ async function cmdCheck(): Promise { } return allOk; - } + }, ); } @@ -461,16 +472,21 @@ async function cmdDesign(): Promise { }, }); if (jsonMode) { - console.log(JSON.stringify({ ok: results.every((r) => r.status !== "fail"), checks: results }, null, 2)); + console.log( + JSON.stringify({ ok: results.every((r) => r.status !== "fail"), checks: results }, null, 2), + ); return results.every((r) => r.status !== "fail"); } console.log(`${c.bold}Design${c.reset}`); for (const r of results) { const icon = - r.status === "pass" ? `${c.green}✓${c.reset}` : - r.status === "fail" ? `${c.red}✗${c.reset}` : - r.status === "warn" ? `${c.yellow}!${c.reset}` : - `${c.dim}-${c.reset}`; + r.status === "pass" + ? `${c.green}✓${c.reset}` + : r.status === "fail" + ? `${c.red}✗${c.reset}` + : r.status === "warn" + ? `${c.yellow}!${c.reset}` + : `${c.dim}-${c.reset}`; console.log(` ${icon} ${r.name} ${c.dim}${r.detail}${c.reset}`); if (r.files) for (const f of r.files) console.log(` ${c.dim}- ${f}${c.reset}`); } @@ -495,7 +511,9 @@ async function cmdReview(): Promise { if (!designOk) allOk = false; if (!jsonMode) { - console.log(`\n${c.bold}${allOk ? `${c.green}✓ review passed` : `${c.red}✗ review failed`}${c.reset}`); + console.log( + `\n${c.bold}${allOk ? `${c.green}✓ review passed` : `${c.red}✗ review failed`}${c.reset}`, + ); } return allOk; } @@ -567,7 +585,9 @@ async function cmdInstall(): Promise { return false; } skipTriage = true; - console.log(`${c.yellow}⚠ --no-triage: triage gate bypassed (elevation consumed, audit-logged)${c.reset}`); + console.log( + `${c.yellow}⚠ --no-triage: triage gate bypassed (elevation consumed, audit-logged)${c.reset}`, + ); } console.log(`${c.bold}${c.cyan}Installing tools via mise...${c.reset}\n`); @@ -607,7 +627,7 @@ async function cmdInstall(): Promise { console.log(); return allOk; - } + }, ); } @@ -673,9 +693,7 @@ async function ensureSecretsBackend(config: kitConfig): Promise { const verify = await check1PasswordStatus(); if (!verify.authenticated) { - console.log( - `${c.yellow}Still not authenticated — see hint above.${c.reset}\n`, - ); + console.log(`${c.yellow}Still not authenticated — see hint above.${c.reset}\n`); return false; } console.log(`${c.green}✓ 1Password authenticated${c.reset}\n`); @@ -695,7 +713,8 @@ async function cmdLogin(): Promise { const args = process.argv.slice(3); const serviceFilter = flagValue(args, "--service"); const retryIdx = args.indexOf("--retry-count"); - const retryCount = retryIdx >= 0 && args[retryIdx + 1] ? Math.max(0, parseInt(args[retryIdx + 1]!, 10) || 0) : 0; + const retryCount = + retryIdx >= 0 && args[retryIdx + 1] ? Math.max(0, parseInt(args[retryIdx + 1]!, 10) || 0) : 0; const backendOk = await ensureSecretsBackend(config); @@ -801,7 +820,7 @@ async function cmdLogin(): Promise { console.log(); return allOk && backendOk; - } + }, ); } @@ -835,7 +854,9 @@ async function cmdSecretsValidate(): Promise { const rl = fix ? createInterface({ input: process.stdin, output: process.stdout }) : null; const prompt = rl ? async (key: string): Promise => { - const answer = (await rl.question(` ${c.cyan}${key}${c.reset} value (blank to skip): `)).trim(); + const answer = ( + await rl.question(` ${c.cyan}${key}${c.reset} value (blank to skip): `) + ).trim(); return answer.length > 0 ? answer : null; } : undefined; @@ -850,7 +871,9 @@ async function cmdSecretsValidate(): Promise { : r.status === "missing" ? `${c.red}✗${c.reset}` : `${c.yellow}⚠${c.reset}`; - console.log(` ${icon} ${r.key} ${c.dim}(${r.source})${c.reset}${r.detail ? ` — ${r.detail}` : ""}`); + console.log( + ` ${icon} ${r.key} ${c.dim}(${r.source})${c.reset}${r.detail ? ` — ${r.detail}` : ""}`, + ); } const s = summarizeValidation(results); const tail = [ @@ -918,11 +941,7 @@ async function cmdSecrets(): Promise { const { looksLikeProdKey, getActiveEnv, prodReadAllowed } = await import("./env-switch.js"); const activeEnv = await getActiveEnv(process.cwd()); const prodKeys = Object.entries(secretsConfig.keys ?? {}).filter(([, v]) => { - return ( - looksLikeProdKey(v.ref) || - looksLikeProdKey(v.name) || - looksLikeProdKey(v.vault_path) - ); + return looksLikeProdKey(v.ref) || looksLikeProdKey(v.name) || looksLikeProdKey(v.vault_path); }); if (prodKeys.length > 0 && !prodReadAllowed(activeEnv)) { console.error( @@ -941,7 +960,9 @@ async function cmdSecrets(): Promise { return false; } - console.log(`${c.bold}${c.cyan}Generating secrets...${c.reset} ${c.dim}(env=${activeEnv})${c.reset}\n`); + console.log( + `${c.bold}${c.cyan}Generating secrets...${c.reset} ${c.dim}(env=${activeEnv})${c.reset}\n`, + ); return await withGovernance( config, @@ -958,20 +979,14 @@ async function cmdSecrets(): Promise { let allOk = true; for (const r of results) { - const icon = r.resolved - ? `${c.green}✓${c.reset}` - : `${c.red}✗${c.reset}`; - const status = r.resolved - ? `${c.green}resolved${c.reset}` - : `${c.red}missing${c.reset}`; + const icon = r.resolved ? `${c.green}✓${c.reset}` : `${c.red}✗${c.reset}`; + const status = r.resolved ? `${c.green}resolved${c.reset}` : `${c.red}missing${c.reset}`; console.log(` ${icon} ${r.name} ${status} ${c.dim}${r.detail}${c.reset}`); if (!r.resolved) allOk = false; } if (written) { - const source = fromTemplate - ? `from ${secretsConfig.template}` - : "from keys"; + const source = fromTemplate ? `from ${secretsConfig.template}` : "from keys"; console.log(`\n ${c.green}✓${c.reset} Wrote .env.local ${c.dim}(${source})${c.reset}`); } else if (skipped === "nothing-resolved") { console.log( @@ -1000,15 +1015,19 @@ async function cmdSecrets(): Promise { ); console.log(` ${c.bold}${meta.loginCmd}${c.reset}`); if (meta.initCmd) { - console.log(` ${c.dim}then bind this repo:${c.reset} ${c.bold}${meta.initCmd}${c.reset}`); + console.log( + ` ${c.dim}then bind this repo:${c.reset} ${c.bold}${meta.initCmd}${c.reset}`, + ); } - console.log(` ${c.dim}then re-run ${c.reset}${c.bold}kit secrets${c.reset}${c.dim}.${c.reset}`); + console.log( + ` ${c.dim}then re-run ${c.reset}${c.bold}kit secrets${c.reset}${c.dim}.${c.reset}`, + ); } } console.log(); return allOk; - } + }, ); } @@ -1021,9 +1040,7 @@ async function cmdSkills(): Promise { } const registry = config.skills.registry ?? "clawhub"; - console.log( - `${c.bold}${c.cyan}Skills${c.reset} ${c.dim}(registry: ${registry})${c.reset}\n`, - ); + console.log(`${c.bold}${c.cyan}Skills${c.reset} ${c.dim}(registry: ${registry})${c.reset}\n`); const results = await checkSkills(config.skills); @@ -1041,12 +1058,8 @@ async function cmdSkills(): Promise { ? `${c.red}✗${c.reset}` : `${c.yellow}!${c.reset}`; const name = r.name + " ".repeat(Math.max(0, nameWidth - r.name.length)); - const tag = r.required - ? `${c.dim}[required]${c.reset}` - : `${c.dim}[optional]${c.reset}`; - const status = r.installed - ? `${c.green}installed${c.reset}` - : `${c.red}missing${c.reset}`; + const tag = r.required ? `${c.dim}[required]${c.reset}` : `${c.dim}[optional]${c.reset}`; + const status = r.installed ? `${c.green}installed${c.reset}` : `${c.red}missing${c.reset}`; console.log(` ${icon} ${name} ${tag} ${status} ${c.dim}${r.versionSpec}${c.reset}`); } @@ -1055,9 +1068,7 @@ async function cmdSkills(): Promise { console.log(); console.log(`${c.bold}To install missing skills:${c.reset}`); for (const m of missing) { - console.log( - ` ${c.cyan}openclaw install ${registry}/${m.name}${c.reset}`, - ); + console.log(` ${c.cyan}openclaw install ${registry}/${m.name}${c.reset}`); } } @@ -1078,9 +1089,7 @@ async function cmdEscalate(): Promise { }, async () => { const toolResults = config.tools ? await checkTools(config.tools) : []; - const serviceResults = config.services - ? await checkServices(config.services) - : []; + const serviceResults = config.services ? await checkServices(config.services) : []; const secretResults = config.secrets ? await checkSecrets(config.secrets) : { templateExists: null, keys: [] }; @@ -1104,7 +1113,7 @@ async function cmdEscalate(): Promise { console.log(`${c.dim}Send this to the project owner for manual resolution.${c.reset}\n`); return false; - } + }, ); } @@ -1159,7 +1168,9 @@ async function cmdSetup(): Promise { } if (recommended) { - console.log(`${c.dim}Recommended profile on — memory + git hooks wired after the core steps.${c.reset}\n`); + console.log( + `${c.dim}Recommended profile on — memory + git hooks wired after the core steps.${c.reset}\n`, + ); } // Step 1: Install @@ -1168,7 +1179,9 @@ async function cmdSetup(): Promise { if (!installOk) { console.log(`${c.red}Install failed — stopping setup.${c.reset}`); - console.log(`${c.dim}Fix the issues above and run ${c.reset}${c.bold}kit setup${c.reset}${c.dim} again.${c.reset}`); + console.log( + `${c.dim}Fix the issues above and run ${c.reset}${c.bold}kit setup${c.reset}${c.dim} again.${c.reset}`, + ); return false; } @@ -1208,7 +1221,10 @@ async function cmdSetup(): Promise { const gi = await checkGitignore(process.cwd()); if (gi.missingPatterns.length > 0) { const patched = await patchGitignore(process.cwd()); - const names = gi.missingPatterns.slice(0, 3).map((m) => m.pattern).join(", "); + const names = gi.missingPatterns + .slice(0, 3) + .map((m) => m.pattern) + .join(", "); console.log( ` ${c.green}✓${c.reset} hardened .gitignore ${c.dim}(+${patched.added}: ${names}${gi.missingPatterns.length > 3 ? ", …" : ""}) — review + commit it${c.reset}`, ); @@ -1251,7 +1267,9 @@ async function cmdSetup(): Promise { // `kit agent-config`). Without this the agent hits the permission wall. const perms = await installKitPermissions(); if (perms.action === "created" || perms.action === "updated") { - console.log(` ${c.green}✓${c.reset} allowed ${perms.added.length} read-only kit command(s) ${c.dim}→ ${perms.file}${c.reset}`); + console.log( + ` ${c.green}✓${c.reset} allowed ${perms.added.length} read-only kit command(s) ${c.dim}→ ${perms.file}${c.reset}`, + ); } console.log(); @@ -1263,13 +1281,22 @@ async function cmdSetup(): Promise { if (recommended) { console.log(`\n${c.bold}[+] Recommended hardening${c.reset}`); const h = await applyRecommendedHardening(config); - for (const e of h.memory.added) console.log(` ${c.green}✓${c.reset} memory hook ${c.dim}${e}${c.reset}`); - if (h.memory.added.length === 0) console.log(` ${c.dim}= memory hooks already wired${c.reset}`); + for (const e of h.memory.added) + console.log(` ${c.green}✓${c.reset} memory hook ${c.dim}${e}${c.reset}`); + if (h.memory.added.length === 0) + console.log(` ${c.dim}= memory hooks already wired${c.reset}`); if (!h.memory.resolved) { - console.log(` ${c.yellow}!${c.reset} ${c.dim}memory hooks use a bare \`kit\` (kit not resolvable to an absolute path)${c.reset}`); + console.log( + ` ${c.yellow}!${c.reset} ${c.dim}memory hooks use a bare \`kit\` (kit not resolvable to an absolute path)${c.reset}`, + ); } for (const r of h.hooks) { - const icon = r.action === "failed" ? `${c.red}✗` : r.action === "skipped" ? `${c.yellow}!` : `${c.green}✓`; + const icon = + r.action === "failed" + ? `${c.red}✗` + : r.action === "skipped" + ? `${c.yellow}!` + : `${c.green}✓`; console.log(` ${icon}${c.reset} git ${r.hookName} ${c.dim}(${r.action})${c.reset}`); } console.log(); @@ -1290,7 +1317,9 @@ async function cmdSetup(): Promise { if (allOk) { console.log(`${c.bold}${c.green}Setup complete — you're ready to go! ✓${c.reset}\n`); } else { - console.log(`${c.bold}${c.yellow}Setup finished with issues. Run ${c.reset}${c.bold}kit check${c.reset}${c.yellow} to see what's left.${c.reset}\n`); + console.log( + `${c.bold}${c.yellow}Setup finished with issues. Run ${c.reset}${c.bold}kit check${c.reset}${c.yellow} to see what's left.${c.reset}\n`, + ); } return allOk; @@ -1403,7 +1432,9 @@ async function selfUpgrade(): Promise { timeout: 180_000, env: { ...process.env }, }); - console.log(`\n${c.green}${c.bold}✓ kit upgraded${c.reset} — run ${c.bold}kit --version${c.reset} to confirm.`); + console.log( + `\n${c.green}${c.bold}✓ kit upgraded${c.reset} — run ${c.bold}kit --version${c.reset} to confirm.`, + ); return true; } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); @@ -1435,7 +1466,10 @@ async function cmdUpgrade(): Promise { await updateSkillsLock(skills, kitMeta?.name ? `${kitMeta.name}@${kitMeta.version}` : undefined); // Update CLI lock - const tools: Record = {}; + const tools: Record< + string, + { version: string; source: "mise" | "npm" | "pip" | "manual"; auth?: string } + > = {}; if (config.tools) { for (const [name, version] of Object.entries(config.tools)) { tools[name] = { version, source: "mise" }; @@ -1445,9 +1479,13 @@ async function cmdUpgrade(): Promise { await updateCliLock(tools); console.log(`${c.green}✓${c.reset} Updated lock files from .kit.toml\n`); - - console.log(`${c.dim}Run ${c.reset}${c.bold}kit install${c.reset}${c.dim} to install updated tools${c.reset}`); - console.log(`${c.dim}Run ${c.reset}${c.bold}kit skills${c.reset}${c.dim} to check skill status${c.reset}\n`); + + console.log( + `${c.dim}Run ${c.reset}${c.bold}kit install${c.reset}${c.dim} to install updated tools${c.reset}`, + ); + console.log( + `${c.dim}Run ${c.reset}${c.bold}kit skills${c.reset}${c.dim} to check skill status${c.reset}\n`, + ); return true; } @@ -1468,7 +1506,7 @@ async function generateConfigFile( if (stack.confidence < 0.3 && nonInteractive) { console.error( - `${c.red}✗ Stack detection confidence too low (${(stack.confidence * 100).toFixed(0)}%) — cannot auto-generate config in non-interactive mode.${c.reset}` + `${c.red}✗ Stack detection confidence too low (${(stack.confidence * 100).toFixed(0)}%) — cannot auto-generate config in non-interactive mode.${c.reset}`, ); console.error(`${c.dim}Create a .kit.toml manually or run 'kit init' interactively.${c.reset}`); return "abort-error"; @@ -1486,7 +1524,7 @@ async function generateConfigFile( console.log(`${c.dim}Could not detect project type — generating minimal config.${c.reset}\n`); } else { console.log( - ` ${c.green}✓${c.reset} Detected: ${c.bold}${detectedLabel}${c.reset} ${c.dim}(confidence: ${(stack.confidence * 100).toFixed(0)}%)${c.reset}\n` + ` ${c.green}✓${c.reset} Detected: ${c.bold}${detectedLabel}${c.reset} ${c.dim}(confidence: ${(stack.confidence * 100).toFixed(0)}%)${c.reset}\n`, ); } @@ -1495,10 +1533,7 @@ async function generateConfigFile( // BEFORE wiring up the vault, so the choice of backend is informed. const plaintextHits = await scanPlaintextSecrets(process.cwd()); if (plaintextHits.length > 0) { - const totalFindings = plaintextHits.reduce( - (sum, h) => sum + h.findings.length, - 0, - ); + const totalFindings = plaintextHits.reduce((sum, h) => sum + h.findings.length, 0); console.log( `${c.red}⚠ Found ${totalFindings} plaintext secret(s) across ${plaintextHits.length} file(s):${c.reset}`, ); @@ -1519,7 +1554,9 @@ async function generateConfigFile( const detectedStore = await detectSecretStore(async (p) => existsSync(resolve(process.cwd(), p))); let chosenStore: SecretsStore = detectedStore ?? "1password"; if (detectedStore) { - console.log(` ${c.green}✓${c.reset} Detected ${c.bold}${detectedStore}${c.reset} config in repo — using it as the secret backend.\n`); + console.log( + ` ${c.green}✓${c.reset} Detected ${c.bold}${detectedStore}${c.reset} config in repo — using it as the secret backend.\n`, + ); } if (!nonInteractive) { const opts = [ @@ -1552,13 +1589,19 @@ async function generateConfigFile( if (existsSync(p)) { extraSecretKeys = parseEnvTemplateKeys(readFileSync(p, "utf-8")); if (extraSecretKeys.length > 0) { - console.log(` ${c.green}✓${c.reset} Seeded ${extraSecretKeys.length} key(s) from ${c.bold}${f}${c.reset}\n`); + console.log( + ` ${c.green}✓${c.reset} Seeded ${extraSecretKeys.length} key(s) from ${c.bold}${f}${c.reset}\n`, + ); } break; } } - const tomlContent = generateToml(stack, { secretsStore: chosenStore, hasDockerfile, extraSecretKeys }); + const tomlContent = generateToml(stack, { + secretsStore: chosenStore, + hasDockerfile, + extraSecretKeys, + }); // Show diff preview console.log(`${c.bold}Preview — .kit.toml${c.reset}\n`); @@ -1590,11 +1633,15 @@ async function generateConfigFile( if (meta) { console.log(` ${c.dim}Secret backend: ${c.reset}${c.bold}${meta.label}${c.reset}`); if (meta.miseTool) { - console.log(` ${c.green}✓${c.reset} ${c.dim}${c.reset}${c.bold}kit setup${c.reset}${c.dim} will install its CLI via mise${c.reset}`); + console.log( + ` ${c.green}✓${c.reset} ${c.dim}${c.reset}${c.bold}kit setup${c.reset}${c.dim} will install its CLI via mise${c.reset}`, + ); } if (meta.loginCmd) { const steps = meta.initCmd ? `${meta.loginCmd} && ${meta.initCmd}` : meta.loginCmd; - console.log(` ${c.yellow}!${c.reset} ${c.dim}then authenticate (your account): ${c.reset}${c.bold}${steps}${c.reset}`); + console.log( + ` ${c.yellow}!${c.reset} ${c.dim}then authenticate (your account): ${c.reset}${c.bold}${steps}${c.reset}`, + ); } console.log(); } @@ -1636,12 +1683,16 @@ async function offerContextLock(configPath: string, nonInteractive: boolean): Pr const ok = await promptConfirm("Add this [context] lock to .kit.toml? [y/N] ", 10000, false); if (!ok) { - console.log(`${c.dim}Skipped — run ${c.reset}${c.bold}kit context check${c.reset}${c.dim} later to add it.${c.reset}\n`); + console.log( + `${c.dim}Skipped — run ${c.reset}${c.bold}kit context check${c.reset}${c.dim} later to add it.${c.reset}\n`, + ); return; } const existing = readFileSync(configPath, "utf-8"); await writeFile(configPath, existing.trimEnd() + "\n\n" + block + "\n", "utf-8"); - console.log(` ${c.green}✓${c.reset} Locked ${c.bold}[context]${c.reset} ${c.dim}→ verify with ${c.reset}${c.bold}kit context check${c.reset}\n`); + console.log( + ` ${c.green}✓${c.reset} Locked ${c.bold}[context]${c.reset} ${c.dim}→ verify with ${c.reset}${c.bold}kit context check${c.reset}\n`, + ); } async function cmdInit(): Promise { @@ -1649,7 +1700,9 @@ async function cmdInit(): Promise { console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); const nonInteractive = - hasFlag(process.argv, "--non-interactive") || hasFlag(process.argv, "--yes") || hasFlag(process.argv, "-y"); + hasFlag(process.argv, "--non-interactive") || + hasFlag(process.argv, "--yes") || + hasFlag(process.argv, "-y"); const configPath = resolveConfigPath(); @@ -1698,9 +1751,15 @@ async function cmdInit(): Promise { Object.assign(skills, config.skills.optional); } - await updateSkillsLock(skills, kitMeta?.name ? `${kitMeta.name}@${kitMeta.version}` : undefined); + await updateSkillsLock( + skills, + kitMeta?.name ? `${kitMeta.name}@${kitMeta.version}` : undefined, + ); - const tools: Record = {}; + const tools: Record< + string, + { version: string; source: "mise" | "npm" | "pip" | "manual"; auth?: string } + > = {}; if (config.tools) { for (const [name, version] of Object.entries(config.tools)) { tools[name] = { version, source: "mise" }; @@ -1741,7 +1800,9 @@ async function offerFirstInstallPrescan(): Promise { console.log(`${c.bold}${c.cyan}First-install: multi-repo prescan${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}`); console.log(`${c.dim}kit can scan every git repo under a directory for leaked secrets,`); - console.log(`${c.dim}.gitignore holes, public-repo + credential combos, and CVE-deps.${c.reset}\n`); + console.log( + `${c.dim}.gitignore holes, public-repo + credential combos, and CVE-deps.${c.reset}\n`, + ); const readline = await import("node:readline/promises"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); @@ -1762,7 +1823,9 @@ async function offerFirstInstallPrescan(): Promise { await writeFile(markerPath, new Date().toISOString() + "\n", { encoding: "utf-8", mode: 0o600 }); if (answer !== "y" && answer !== "yes") { - console.log(`${c.dim}Skipped. Run later with ${c.bold}kit security prescan ${c.reset}${c.dim}.${c.reset}\n`); + console.log( + `${c.dim}Skipped. Run later with ${c.bold}kit security prescan ${c.reset}${c.dim}.${c.reset}\n`, + ); return; } @@ -1771,11 +1834,13 @@ async function offerFirstInstallPrescan(): Promise { const report = await runPrescan({ root: resolve(scanPath), deep: false }); const bySev: Record = { critical: 0, high: 0, medium: 0, low: 0, info: 0 }; for (const f of report.findings) bySev[f.severity] = (bySev[f.severity] ?? 0) + 1; - console.log(`${c.bold}Scanned${c.reset} ${report.repoCount} repo(s), ${report.findings.length} finding(s):`); + console.log( + `${c.bold}Scanned${c.reset} ${report.repoCount} repo(s), ${report.findings.length} finding(s):`, + ); if (bySev.critical) console.log(` ${c.red}critical${c.reset}: ${bySev.critical}`); - if (bySev.high) console.log(` ${c.red}high ${c.reset}: ${bySev.high}`); - if (bySev.medium) console.log(` ${c.yellow}medium ${c.reset}: ${bySev.medium}`); - if (bySev.low) console.log(` ${c.dim}low ${c.reset}: ${bySev.low}`); + if (bySev.high) console.log(` ${c.red}high ${c.reset}: ${bySev.high}`); + if (bySev.medium) console.log(` ${c.yellow}medium ${c.reset}: ${bySev.medium}`); + if (bySev.low) console.log(` ${c.dim}low ${c.reset}: ${bySev.low}`); if (report.summaryPath) { console.log(`\n${c.dim}Full report:${c.reset} ${report.summaryPath}`); } @@ -1814,7 +1879,7 @@ async function cmdDoctor(): Promise { if (result.passed > 0) summaryParts.push(`${c.green}${result.passed} passed${c.reset}`); if (result.warnings > 0) summaryParts.push( - `${c.yellow}${result.warnings} warning${result.warnings === 1 ? "" : "s"}${c.reset}` + `${c.yellow}${result.warnings} warning${result.warnings === 1 ? "" : "s"}${c.reset}`, ); if (result.failed > 0) summaryParts.push(`${c.red}${result.failed} failed${c.reset}`); if (summaryParts.length === 0) summaryParts.push(`${c.dim}no checks ran${c.reset}`); @@ -1826,10 +1891,10 @@ async function cmdDoctor(): Promise { async function cmdAdd(): Promise { const serviceName = process.argv[3]; - + if (!serviceName) { console.log(`${c.bold}${c.cyan}Available services:${c.reset}\n`); - + const services = listAvailableServices(); for (const svc of services) { const info = getServiceInfo(svc); @@ -1838,24 +1903,24 @@ async function cmdAdd(): Promise { console.log(` ${c.dim}Requires: ${info.tools.join(", ")}${c.reset}`); } } - + console.log(); console.log(`${c.dim}Usage: kit add ${c.reset}`); console.log(`${c.dim}Example: kit add stripe/payments${c.reset}`); console.log(); return false; } - + console.log(`${c.bold}${c.cyan}Provisioning ${serviceName}...${c.reset}\n`); - + const projectPath = process.cwd(); const projectName = process.cwd().split("/").pop(); - + const result = await provisionService(serviceName, projectPath, projectName); - + if (result.success) { console.log(` ${c.green}✓${c.reset} ${result.message}`); - + if (result.secrets && Object.keys(result.secrets).length > 0) { console.log(); console.log(` ${c.dim}Added secrets to .env.local:${c.reset}`); @@ -1863,12 +1928,12 @@ async function cmdAdd(): Promise { console.log(` ${c.cyan}${key}${c.reset}`); } } - + if (result.config) { console.log(); console.log(` ${c.dim}Updated skills-lock.json${c.reset}`); } - + console.log(); return true; } else { @@ -1896,7 +1961,9 @@ async function cmdSecretsOneCli(): Promise { ? `${c.green}authenticated${c.reset}` : `${c.red}not authenticated${c.reset}`; console.log(` Gateway API: ${status.apiUrl} ${reach}`); - console.log(` Gateway proxy: ${status.gatewayUrl} ${c.dim}(set HTTPS_PROXY here for agent processes)${c.reset}`); + console.log( + ` Gateway proxy: ${status.gatewayUrl} ${c.dim}(set HTTPS_PROXY here for agent processes)${c.reset}`, + ); console.log(` Auth: ${auth}`); if (status.version) { console.log(` Version: ${c.dim}${status.version}${c.reset}`); @@ -1934,9 +2001,7 @@ async function cmdSecretsOneCli(): Promise { const pathPattern = pathIdx >= 0 ? args[pathIdx + 1] : undefined; if (!hostPattern) { - console.error( - `${c.red}--host required (e.g. api.stripe.com, api.openai.com).${c.reset}`, - ); + console.error(`${c.red}--host required (e.g. api.stripe.com, api.openai.com).${c.reset}`); return false; } @@ -1955,9 +2020,7 @@ async function cmdSecretsOneCli(): Promise { // 1. Verify OneCLI is reachable + authed before reading the secret. const status = await checkOneCliStatus(); if (!status.reachable || !status.authenticated) { - console.error( - `${c.red}OneCLI not ready: ${status.error ?? "unreachable"}${c.reset}`, - ); + console.error(`${c.red}OneCLI not ready: ${status.error ?? "unreachable"}${c.reset}`); console.error( `${c.dim}Run ${c.bold}kit secrets onecli status${c.reset}${c.dim} for details.${c.reset}`, ); @@ -1967,9 +2030,7 @@ async function cmdSecretsOneCli(): Promise { // 2. Read the real value from the configured upstream vault. const config = await loadConfig(resolveConfigPath()); if (!config.secrets?.store || config.secrets.store === "env") { - console.error( - `${c.red}No upstream vault configured in .kit.toml.${c.reset}`, - ); + console.error(`${c.red}No upstream vault configured in .kit.toml.${c.reset}`); console.error( `${c.dim}Set ${c.bold}[secrets].store${c.reset}${c.dim} (run ${c.bold}kit init${c.reset}${c.dim}) first so kit knows where to read the real value from.${c.reset}`, ); @@ -1996,9 +2057,7 @@ async function cmdSecretsOneCli(): Promise { ); const realValue = await readSecretValueFromVault(keyName, config); if (!realValue) { - console.error( - `${c.red}Could not resolve "${keyName}" from upstream vault.${c.reset}`, - ); + console.error(`${c.red}Could not resolve "${keyName}" from upstream vault.${c.reset}`); console.error( `${c.dim}Check auth with ${c.bold}kit check${c.reset}${c.dim} and retry.${c.reset}`, ); @@ -2112,8 +2171,7 @@ async function cmdSecretsRevokeOld(): Promise { return false; } const projectIdx = args.indexOf("--project"); - const projectRef = - projectIdx >= 0 ? args[projectIdx + 1] : process.env.SUPABASE_PROJECT_REF; + const projectRef = projectIdx >= 0 ? args[projectIdx + 1] : process.env.SUPABASE_PROJECT_REF; const keyIdIdx = args.indexOf("--key-id"); const keyId = keyIdIdx >= 0 ? args[keyIdIdx + 1] : undefined; @@ -2221,9 +2279,7 @@ async function cmdSecretsPropagateStandalone(): Promise { console.error( `${c.red}Usage: kit secrets propagate [--value | --stdin] --to [opts]${c.reset}`, ); - console.error( - `${c.dim}targets: ${ALL_TARGETS.join(",")}${c.reset}`, - ); + console.error(`${c.dim}targets: ${ALL_TARGETS.join(",")}${c.reset}`); return false; } @@ -2335,7 +2391,9 @@ async function cmdSecretsPurgeHistory(): Promise { const pv = await previewMatches(p, process.cwd()); totalCommits += pv.matchedCommits; if (pv.matchedCommits === 0) { - console.log(` ${c.dim}•${c.reset} ${pv.pattern.slice(0, 14)}… ${c.dim}no matches${c.reset}`); + console.log( + ` ${c.dim}•${c.reset} ${pv.pattern.slice(0, 14)}… ${c.dim}no matches${c.reset}`, + ); } else { console.log( ` ${c.yellow}•${c.reset} ${pv.pattern.slice(0, 14)}… ${c.yellow}${pv.matchedCommits} commit(s) touched${c.reset}`, @@ -2348,7 +2406,9 @@ async function cmdSecretsPurgeHistory(): Promise { console.log(); if (totalCommits === 0) { - console.log(`${c.green}✓ No commits reference the supplied pattern(s). Nothing to do.${c.reset}\n`); + console.log( + `${c.green}✓ No commits reference the supplied pattern(s). Nothing to do.${c.reset}\n`, + ); return true; } @@ -2362,9 +2422,7 @@ async function cmdSecretsPurgeHistory(): Promise { ); if (!force) { - console.error( - `${c.red}✗ Refusing to proceed without --force-history.${c.reset}`, - ); + console.error(`${c.red}✗ Refusing to proceed without --force-history.${c.reset}`); console.error( `${c.dim}Re-run with ${c.bold}--force-history${c.reset}${c.dim} after confirming the impact list above.${c.reset}\n`, ); @@ -2441,7 +2499,9 @@ async function cmdSecretsMigrate(): Promise { const dryRun = hasFlag(process.argv, "--dry-run"); const noClean = hasFlag(process.argv, "--no-clean"); - console.log(`${c.dim}Target vault: ${c.bold}${store}${c.reset}${c.dim} (dry-run: ${dryRun})${c.reset}\n`); + console.log( + `${c.dim}Target vault: ${c.bold}${store}${c.reset}${c.dim} (dry-run: ${dryRun})${c.reset}\n`, + ); const secretsOnly = hasFlag(process.argv, "--secrets-only"); const plan = await planMigration(process.cwd(), { secretsOnly }); @@ -2454,9 +2514,7 @@ async function cmdSecretsMigrate(): Promise { const labels = hit.findings.map((f) => `${f.label}:${f.preview}`).join(", "); console.log(` ${c.dim}•${c.reset} ${hit.file} ${c.dim}${labels}${c.reset}`); } - console.log( - `${c.dim}Embedded secrets in scripts / JSON need manual extraction.${c.reset}\n`, - ); + console.log(`${c.dim}Embedded secrets in scripts / JSON need manual extraction.${c.reset}\n`); return false; } console.log(`${c.green}✓ No plaintext secrets found — nothing to migrate.${c.reset}\n`); @@ -2535,15 +2593,9 @@ async function cmdSecretsMigrate(): Promise { console.log(`${c.bold}Cleanup${c.reset} ${c.dim}(mode=${mode})${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); for (const [file, keys] of cleaned) { - const { changed } = await commentOutInFile( - `${process.cwd()}/${file}`, - keys, - mode, - ); + const { changed } = await commentOutInFile(`${process.cwd()}/${file}`, keys, mode); const verb = mode === "delete" ? "deleted" : mode === "comment" ? "commented out" : "blanked"; - console.log( - ` ${c.green}✓${c.reset} ${file} ${c.dim}${changed} line(s) ${verb}${c.reset}`, - ); + console.log(` ${c.green}✓${c.reset} ${file} ${c.dim}${changed} line(s) ${verb}${c.reset}`); } const explain = mode === "blank" @@ -2571,18 +2623,24 @@ async function cmdSecretsMigrate(): Promise { */ async function cmdSecretsVaultMigrate(): Promise { const args = process.argv.slice(4); - const fromArg = args.find((a) => a.startsWith("--from="))?.split("=")[1] ?? - (args[args.indexOf("--from") + 1] ?? ""); - const toArg = args.find((a) => a.startsWith("--to="))?.split("=")[1] ?? - (args[args.indexOf("--to") + 1] ?? ""); + const fromArg = + args.find((a) => a.startsWith("--from="))?.split("=")[1] ?? + args[args.indexOf("--from") + 1] ?? + ""; + const toArg = + args.find((a) => a.startsWith("--to="))?.split("=")[1] ?? args[args.indexOf("--to") + 1] ?? ""; const dryRun = hasFlag(args, "--dry-run"); if (hasFlag(args, "--help") || hasFlag(args, "-h") || !fromArg || !toArg) { - console.log(`${c.bold}kit secrets vault-migrate${c.reset} — move keys between vault backends\n`); + console.log( + `${c.bold}kit secrets vault-migrate${c.reset} — move keys between vault backends\n`, + ); console.log("Usage:"); console.log(" kit secrets vault-migrate --from --to [--dry-run]"); console.log(""); - console.log("Supported backends: 1password, infisical, bitwarden, doppler, vault, aws-sm, gcp-sm, azure-kv"); + console.log( + "Supported backends: 1password, infisical, bitwarden, doppler, vault, aws-sm, gcp-sm, azure-kv", + ); console.log(""); console.log("Migration is gated by elevation (one-shot — consumed on use):"); console.log(" kit auth elevate --scope vault-migrate"); @@ -2591,7 +2649,9 @@ async function cmdSecretsVaultMigrate(): Promise { console.log(`${c.bold}${c.cyan}kit secrets vault-migrate${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); - console.log(`${c.dim}From: ${c.bold}${fromArg}${c.reset}${c.dim} → To: ${c.bold}${toArg}${c.reset}${c.dim} (dry-run: ${dryRun})${c.reset}\n`); + console.log( + `${c.dim}From: ${c.bold}${fromArg}${c.reset}${c.dim} → To: ${c.bold}${toArg}${c.reset}${c.dim} (dry-run: ${dryRun})${c.reset}\n`, + ); const config = await loadConfig(resolveConfigPath()); if (!config.secrets) { @@ -2615,7 +2675,9 @@ async function cmdSecretsVaultMigrate(): Promise { console.log(); if (dryRun) { - console.log(`${c.dim}--dry-run set; not reading values. Remove flag + elevate to perform.${c.reset}\n`); + console.log( + `${c.dim}--dry-run set; not reading values. Remove flag + elevate to perform.${c.reset}\n`, + ); return true; } @@ -2672,7 +2734,9 @@ async function cmdSecretsSync(): Promise { return true; } - console.log(`${c.bold}${c.cyan}kit secrets sync${c.reset} → ${c.bold}${target}${c.reset}${dryRun ? ` ${c.yellow}(dry run)${c.reset}` : ""}\n`); + console.log( + `${c.bold}${c.cyan}kit secrets sync${c.reset} → ${c.bold}${target}${c.reset}${dryRun ? ` ${c.yellow}(dry run)${c.reset}` : ""}\n`, + ); const result = await syncSecrets(config.secrets, { target, @@ -2739,13 +2803,17 @@ function emitGitlabJunit(checks: JsonCheck[], allOk: boolean): void { // guaranteed flushed before this (sync) function returns. writeFileSync("kit-report.xml", xml, "utf8"); if (!allOk || warnings.length > 0) { - console.log(`CI report written to kit-report.xml (${failures.length} failures, ${warnings.length} warnings)`); + console.log( + `CI report written to kit-report.xml (${failures.length} failures, ${warnings.length} warnings)`, + ); } } async function cmdCi(): Promise { const args = process.argv.slice(2); - const formatArg = args.find((a) => a.startsWith("--format="))?.split("=")[1] as CiFormat | undefined; + const formatArg = args.find((a) => a.startsWith("--format="))?.split("=")[1] as + | CiFormat + | undefined; const failOnWarning = hasFlag(args, "--fail-on-warning"); const jsonMode = hasFlag(args, "--json"); const format: CiFormat = formatArg ?? (jsonMode ? "json" : detectCiFormat()); @@ -2761,9 +2829,7 @@ async function cmdCi(): Promise { const step = (label: string, fn: () => Promise): Promise => live ? runStep(label, fn) : fn(); - const toolResults = config.tools - ? await step("tools", () => checkTools(config.tools!)) - : []; + const toolResults = config.tools ? await step("tools", () => checkTools(config.tools!)) : []; const serviceResults = config.services ? await step("services", () => checkServices(config.services!)) : []; @@ -2787,9 +2853,13 @@ async function cmdCi(): Promise { name: s.name, // Informational services (no CLI login) are a manual-setup warning, // not a CI failure. - status: (s.authenticated ? "pass" : s.informational ? "warn" : "fail") as JsonCheck["status"], + status: (s.authenticated + ? "pass" + : s.informational + ? "warn" + : "fail") as JsonCheck["status"], detail: s.informational - ? (s.output || "manual setup (no CLI login)") + ? s.output || "manual setup (no CLI login)" : (s.output ?? (s.authenticated ? "authenticated" : "not authenticated")), category: "services", })), @@ -2827,11 +2897,10 @@ async function cmdCi(): Promise { else acc.skipped++; return acc; }, - { passed: 0, failed: 0, warnings: 0, skipped: 0 } + { passed: 0, failed: 0, warnings: 0, skipped: 0 }, ); - const allOk = - summary.failed === 0 && (!failOnWarning || summary.warnings === 0); + const allOk = summary.failed === 0 && (!failOnWarning || summary.warnings === 0); if (format === "github") { if (process.env.GITHUB_STEP_SUMMARY) { @@ -2842,23 +2911,23 @@ async function cmdCi(): Promise { `|--------|-------|--------|`, ...checks.map( (c) => - `| ${c.status === "pass" ? "✅" : c.status === "warn" ? "⚠️" : "❌"} | \`${c.category}/${c.name}\` | ${c.detail} |` + `| ${c.status === "pass" ? "✅" : c.status === "warn" ? "⚠️" : "❌"} | \`${c.category}/${c.name}\` | ${c.detail} |`, ), ``, `**${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings**`, ]; await import("node:fs/promises").then(({ appendFile }) => - appendFile(process.env.GITHUB_STEP_SUMMARY!, lines.join("\n") + "\n") + appendFile(process.env.GITHUB_STEP_SUMMARY!, lines.join("\n") + "\n"), ); } emitGithubAnnotations(checks); console.log( - `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings` + `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`, ); } else if (format === "gitlab") { emitGitlabJunit(checks, allOk); console.log( - `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings` + `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`, ); } else if (format === "json") { const output: JsonCheckOutput = { ok: allOk, checks, summary }; @@ -2876,12 +2945,12 @@ async function cmdCi(): Promise { warnings.forEach((w) => console.log(` ! [${w.category}] ${w.name}: ${w.detail}`)); } console.log( - `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings` + `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`, ); } return allOk; - } + }, ); } @@ -2890,10 +2959,12 @@ async function cmdAnalyze(): Promise { // --write persists the drafts (suffix .draft.md so the user reviews // before committing). const args = process.argv.slice(3); - const wantClaude = hasFlag(args, "--claude") || (!hasFlag(args, "--rules") && !hasFlag(args, "--claude")); - const wantRules = hasFlag(args, "--rules") || (!hasFlag(args, "--rules") && !hasFlag(args, "--claude")); + const wantClaude = + hasFlag(args, "--claude") || (!hasFlag(args, "--rules") && !hasFlag(args, "--claude")); + const wantRules = + hasFlag(args, "--rules") || (!hasFlag(args, "--rules") && !hasFlag(args, "--claude")); const writeFlagIdx = args.indexOf("--write"); - const writeDir = writeFlagIdx >= 0 ? args[writeFlagIdx + 1] ?? process.cwd() : null; + const writeDir = writeFlagIdx >= 0 ? (args[writeFlagIdx + 1] ?? process.cwd()) : null; console.log(`${c.bold}${c.cyan}kit analyze${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); @@ -2931,7 +3002,9 @@ async function cmdAnalyze(): Promise { await writeFile(path, renderClaudeMd(report), "utf-8"); console.log(` ${c.green}✓${c.reset} wrote ${path}`); if (report.hasClaudeMd) { - console.log(` ${c.dim}(existing CLAUDE.md found — review draft before merging)${c.reset}`); + console.log( + ` ${c.dim}(existing CLAUDE.md found — review draft before merging)${c.reset}`, + ); } } if (wantRules) { @@ -2939,7 +3012,9 @@ async function cmdAnalyze(): Promise { await writeFile(path, renderRulesMd(report), "utf-8"); console.log(` ${c.green}✓${c.reset} wrote ${path}`); if (report.hasRulesMd) { - console.log(` ${c.dim}(existing RULES.md found — review draft before merging)${c.reset}`); + console.log( + ` ${c.dim}(existing RULES.md found — review draft before merging)${c.reset}`, + ); } } console.log(); @@ -2991,15 +3066,27 @@ async function cmdSecurityPrescan(): Promise { const deep = hasFlag(process.argv, "--deep"); const excludeArg = process.argv.find((a) => a.startsWith("--exclude=")); const exclude = excludeArg - ? excludeArg.slice("--exclude=".length).split(",").map((s) => s.trim()).filter(Boolean) + ? excludeArg + .slice("--exclude=".length) + .split(",") + .map((s) => s.trim()) + .filter(Boolean) : []; const onlyArg = process.argv.find((a) => a.startsWith("--only=")); const onlyChecks = onlyArg - ? onlyArg.slice("--only=".length).split(",").map((s) => s.trim()).filter(Boolean) + ? onlyArg + .slice("--only=".length) + .split(",") + .map((s) => s.trim()) + .filter(Boolean) : undefined; const skipArg = process.argv.find((a) => a.startsWith("--skip=")); const skipChecks = skipArg - ? skipArg.slice("--skip=".length).split(",").map((s) => s.trim()).filter(Boolean) + ? skipArg + .slice("--skip=".length) + .split(",") + .map((s) => s.trim()) + .filter(Boolean) : undefined; const formatArg = process.argv.find((a) => a.startsWith("--format="))?.split("=")[1]; const format: "text" | "json" = formatArg === "json" ? "json" : "text"; @@ -3014,7 +3101,9 @@ async function cmdSecurityPrescan(): Promise { console.log(`${c.bold}${c.cyan}kit security prescan${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); console.log(` ${c.dim}root:${c.reset} ${root}`); - console.log(` ${c.dim}mode:${c.reset} ${deep ? "deep (default + CVE + workflow-drift + audit-gap + bumblebee)" : "default-bundle"}`); + console.log( + ` ${c.dim}mode:${c.reset} ${deep ? "deep (default + CVE + workflow-drift + audit-gap + bumblebee)" : "default-bundle"}`, + ); if (exclude.length) console.log(` ${c.dim}exclude:${c.reset} ${exclude.join(", ")}`); console.log(); } @@ -3036,23 +3125,34 @@ async function cmdSecurityPrescan(): Promise { const baseline = await loadReport(vsBaseline); const diff = diffReports(baseline, report); if (format === "json") { - process.stdout.write(JSON.stringify({ - baseline: vsBaseline, - addedCount: diff.added.length, - removedCount: diff.removed.length, - unchangedCount: diff.unchanged.length, - added: diff.added, - }, null, 2) + "\n"); + process.stdout.write( + JSON.stringify( + { + baseline: vsBaseline, + addedCount: diff.added.length, + removedCount: diff.removed.length, + unchangedCount: diff.unchanged.length, + added: diff.added, + }, + null, + 2, + ) + "\n", + ); } else { - console.log(`${c.bold}${c.cyan}drift report${c.reset}: ${diff.added.length} new finding(s) since baseline`); + console.log( + `${c.bold}${c.cyan}drift report${c.reset}: ${diff.added.length} new finding(s) since baseline`, + ); if (diff.added.length === 0) { console.log(`${c.green}✓ no regressions${c.reset}`); } else { for (const f of diff.added.slice(0, 30)) { const sevColor = f.severity === "critical" || f.severity === "high" ? c.red : c.yellow; - console.log(` ${sevColor}•${c.reset} ${f.repo} — ${f.category} (${f.severity}): ${f.detail.slice(0, 80)}`); + console.log( + ` ${sevColor}•${c.reset} ${f.repo} — ${f.category} (${f.severity}): ${f.detail.slice(0, 80)}`, + ); } - if (diff.added.length > 30) console.log(` ${c.dim}…and ${diff.added.length - 30} more${c.reset}`); + if (diff.added.length > 30) + console.log(` ${c.dim}…and ${diff.added.length - 30} more${c.reset}`); } } return diff.added.length === 0; @@ -3063,30 +3163,36 @@ async function cmdSecurityPrescan(): Promise { if (format === "json") { // Emit machine-readable summary; raw findings live in report.reportPath. - process.stdout.write(JSON.stringify({ - startedAt: report.startedAt, - finishedAt: report.finishedAt, - durationSec: durSec, - root: report.root, - mode: deep ? "deep" : "default", - exclude, - repoCount: report.repoCount, - findingCount: report.findings.length, - bySeverity: bySev, - reportPath: report.reportPath, - summaryPath: report.summaryPath, - findings: report.findings, - }, null, 2) + "\n"); + process.stdout.write( + JSON.stringify( + { + startedAt: report.startedAt, + finishedAt: report.finishedAt, + durationSec: durSec, + root: report.root, + mode: deep ? "deep" : "default", + exclude, + repoCount: report.repoCount, + findingCount: report.findings.length, + bySeverity: bySev, + reportPath: report.reportPath, + summaryPath: report.summaryPath, + findings: report.findings, + }, + null, + 2, + ) + "\n", + ); return bySev.critical === 0 && bySev.high === 0; } console.log(`${c.bold}Scanned${c.reset} ${report.repoCount} repo(s) in ${durSec}s`); console.log(`${c.bold}Findings${c.reset}: ${report.findings.length} total`); if (bySev.critical) console.log(` ${c.red}critical${c.reset}: ${bySev.critical}`); - if (bySev.high) console.log(` ${c.red}high ${c.reset}: ${bySev.high}`); - if (bySev.medium) console.log(` ${c.yellow}medium ${c.reset}: ${bySev.medium}`); - if (bySev.low) console.log(` ${c.dim}low ${c.reset}: ${bySev.low}`); - if (bySev.info) console.log(` ${c.dim}info ${c.reset}: ${bySev.info}`); + if (bySev.high) console.log(` ${c.red}high ${c.reset}: ${bySev.high}`); + if (bySev.medium) console.log(` ${c.yellow}medium ${c.reset}: ${bySev.medium}`); + if (bySev.low) console.log(` ${c.dim}low ${c.reset}: ${bySev.low}`); + if (bySev.info) console.log(` ${c.dim}info ${c.reset}: ${bySev.info}`); console.log(); if (report.reportPath) console.log(`${c.dim} raw:${c.reset} ${report.reportPath}`); if (report.summaryPath) console.log(`${c.dim} summary:${c.reset} ${report.summaryPath}`); @@ -3126,15 +3232,21 @@ async function cmdSecurityPrescanDiff(): Promise { const diff = diffReports(a, b); if (format === "json") { - process.stdout.write(JSON.stringify({ - baseline, - latest, - addedCount: diff.added.length, - removedCount: diff.removed.length, - unchangedCount: diff.unchanged.length, - added: diff.added, - removed: diff.removed, - }, null, 2) + "\n"); + process.stdout.write( + JSON.stringify( + { + baseline, + latest, + addedCount: diff.added.length, + removedCount: diff.removed.length, + unchangedCount: diff.unchanged.length, + added: diff.added, + removed: diff.removed, + }, + null, + 2, + ) + "\n", + ); return diff.added.length === 0; } @@ -3142,9 +3254,13 @@ async function cmdSecurityPrescanDiff(): Promise { console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); console.log(` ${c.dim}baseline:${c.reset} ${baseline}`); console.log(` ${c.dim}latest: ${c.reset} ${latest}\n`); - console.log(`${c.bold}Added (regressions)${c.reset}: ${diff.added.length > 0 ? c.red : c.green}${diff.added.length}${c.reset}`); + console.log( + `${c.bold}Added (regressions)${c.reset}: ${diff.added.length > 0 ? c.red : c.green}${diff.added.length}${c.reset}`, + ); console.log(`${c.bold}Removed (fixed)${c.reset}: ${c.green}${diff.removed.length}${c.reset}`); - console.log(`${c.bold}Unchanged${c.reset}: ${c.dim}${diff.unchanged.length}${c.reset}\n`); + console.log( + `${c.bold}Unchanged${c.reset}: ${c.dim}${diff.unchanged.length}${c.reset}\n`, + ); if (diff.added.length) { console.log(`${c.red}New findings since baseline:${c.reset}`); for (const f of diff.added.slice(0, 20)) { @@ -3249,9 +3365,7 @@ async function cmdSecurity(): Promise { ` ${c.green}✓${c.reset} added ${c.bold}${entry.name}${c.reset} @ ${entry.range} ${c.dim}(${entry.reason})${c.reset}`, ); } else { - console.log( - ` ${c.dim}${entry.name}${c.reset} already on the allowlist @ ${entry.range}`, - ); + console.log(` ${c.dim}${entry.name}${c.reset} already on the allowlist @ ${entry.range}`); } return true; } @@ -3288,14 +3402,9 @@ async function cmdSecurity(): Promise { kind === "runtime" ? `${c.red}runtime${c.reset}` : `${c.yellow}dev${c.reset}`; if (violations.length > 0) { - console.log( - `${c.red}✗ ${violations.length} dependency violation(s):${c.reset}\n`, - ); + console.log(`${c.red}✗ ${violations.length} dependency violation(s):${c.reset}\n`); for (const v of violations) { - const why = - v.reason === "not-on-allowlist" - ? "not on allowlist" - : "wildcard range blocked"; + const why = v.reason === "not-on-allowlist" ? "not on allowlist" : "wildcard range blocked"; console.log( ` ${c.red}•${c.reset} ${v.name} @ ${v.range} ${c.dim}[${fmt(v.kind)}]${c.reset} ${c.dim}${why}${c.reset}`, ); @@ -3304,9 +3413,7 @@ async function cmdSecurity(): Promise { } if (secretViolations.length > 0) { - console.log( - `${c.red}✗ ${secretViolations.length} secrets policy violation(s):${c.reset}\n`, - ); + console.log(`${c.red}✗ ${secretViolations.length} secrets policy violation(s):${c.reset}\n`); for (const sv of secretViolations) { console.log( ` ${c.red}•${c.reset} ${sv.key} ${c.dim}[${sv.reason}]${c.reset} ${c.dim}${sv.detail}${c.reset}`, @@ -3330,16 +3437,12 @@ async function cmdSecurityScanStaged(): Promise { if (hits.length === 0) return true; const total = hits.reduce((sum, h) => sum + h.findings.length, 0); - console.error( - `${c.red}✗ kit secret-scan blocked the commit${c.reset}`, - ); + console.error(`${c.red}✗ kit secret-scan blocked the commit${c.reset}`); console.error( `${c.dim}Found ${total} potential secret(s) in ${hits.length} staged file(s):${c.reset}`, ); for (const hit of hits) { - const labels = hit.findings - .map((f) => `${f.label}:${f.preview}`) - .join(", "); + const labels = hit.findings.map((f) => `${f.label}:${f.preview}`).join(", "); console.error(` ${c.red}•${c.reset} ${hit.file} ${c.dim}${labels}${c.reset}`); } console.error( @@ -3357,7 +3460,9 @@ async function cmdSecurityScanBuild(): Promise { return true; } const total = hits.reduce((sum, h) => sum + h.findings.length, 0); - console.error(`${c.red}✗ scan-build: ${total} potential secret(s) in ${hits.length} build file(s):${c.reset}`); + console.error( + `${c.red}✗ scan-build: ${total} potential secret(s) in ${hits.length} build file(s):${c.reset}`, + ); for (const hit of hits.slice(0, 20)) { const labels = hit.findings.map((f) => `${f.label}:${f.preview}`).join(", "); console.error(` ${c.red}•${c.reset} ${hit.file} ${c.dim}${labels}${c.reset}`); @@ -3430,9 +3535,7 @@ async function cmdSecurityCosts(): Promise { ? `${c.red}✗${c.reset}` : `${c.dim}-${c.reset}`; const capLabel = - s.capUsd !== undefined - ? `cap=${s.capUsd.toFixed(2)} USD` - : `${c.yellow}no cap${c.reset}`; + s.capUsd !== undefined ? `cap=${s.capUsd.toFixed(2)} USD` : `${c.yellow}no cap${c.reset}`; console.log( ` ${icon} ${s.provider.padEnd(10)} current=${s.current.toFixed(2)} ${s.unit} ${capLabel} ${c.dim}${s.detail}${c.reset}`, ); @@ -3465,7 +3568,9 @@ async function cmdSecurityVerifyPull(): Promise { return severity !== "fail"; } - console.log(`${c.bold}${c.cyan}kit security verify-pull${c.reset} ${c.dim}(${base} → ${head})${c.reset}`); + console.log( + `${c.bold}${c.cyan}kit security verify-pull${c.reset} ${c.dim}(${base} → ${head})${c.reset}`, + ); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); if (report.changedFiles.length === 0) { @@ -3476,9 +3581,7 @@ async function cmdSecurityVerifyPull(): Promise { console.log(`${c.dim}${report.changedFiles.length} file(s) changed${c.reset}\n`); if (report.newDependencies.length > 0) { - console.log( - `${c.yellow}⚠ ${report.newDependencies.length} new dependency/-ies:${c.reset}`, - ); + console.log(`${c.yellow}⚠ ${report.newDependencies.length} new dependency/-ies:${c.reset}`); for (const dep of report.newDependencies) { console.log( ` ${c.yellow}•${c.reset} ${dep} ${c.dim}→ run ${c.bold}kit triage npm ${dep}${c.reset}${c.dim} before installing${c.reset}`, @@ -3491,8 +3594,7 @@ async function cmdSecurityVerifyPull(): Promise { const sensitive = report.removedGitignoreEntries.filter((l) => /\.env|\.pem|\.key|id_rsa/.test(l), ); - const severityIcon = - sensitive.length > 0 ? `${c.red}✗` : `${c.yellow}⚠`; + const severityIcon = sensitive.length > 0 ? `${c.red}✗` : `${c.yellow}⚠`; console.log( `${severityIcon}${c.reset} ${report.removedGitignoreEntries.length} .gitignore entry/-ies removed:`, ); @@ -3505,25 +3607,16 @@ async function cmdSecurityVerifyPull(): Promise { } if (report.plaintextHits.length > 0) { - const total = report.plaintextHits.reduce( - (sum, h) => sum + h.findings.length, - 0, - ); + const total = report.plaintextHits.reduce((sum, h) => sum + h.findings.length, 0); console.log( `${c.red}✗ ${total} plaintext secret(s) introduced in ${report.plaintextHits.length} file(s):${c.reset}`, ); for (const hit of report.plaintextHits.slice(0, 20)) { - const labels = hit.findings - .map((f) => `${f.label}:${f.preview}`) - .join(", "); - console.log( - ` ${c.red}•${c.reset} ${hit.file} ${c.dim}${labels}${c.reset}`, - ); + const labels = hit.findings.map((f) => `${f.label}:${f.preview}`).join(", "); + console.log(` ${c.red}•${c.reset} ${hit.file} ${c.dim}${labels}${c.reset}`); } if (report.plaintextHits.length > 20) { - console.log( - ` ${c.dim}… ${report.plaintextHits.length - 20} more${c.reset}`, - ); + console.log(` ${c.dim}… ${report.plaintextHits.length - 20} more${c.reset}`); } console.log(); } @@ -3603,9 +3696,7 @@ async function cmdSecurityCheckGitignore(): Promise { if (fix && result.missingPatterns.length > 0) { const patch = await patchGitignore(process.cwd()); - console.log( - `${c.green}✓${c.reset} appended ${patch.added} pattern(s) to .gitignore`, - ); + console.log(`${c.green}✓${c.reset} appended ${patch.added} pattern(s) to .gitignore`); console.log( `${c.dim}Review the new block, then ${c.bold}git add .gitignore && git commit${c.reset}${c.dim}.${c.reset}\n`, ); @@ -3630,9 +3721,7 @@ async function cmdSecurityClearCache(): Promise { console.log(`${c.bold}${c.cyan}kit security clear-cache${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); - console.log( - `${c.yellow}⚠ This will delete the cached ${target} binary.${c.reset}`, - ); + console.log(`${c.yellow}⚠ This will delete the cached ${target} binary.${c.reset}`); console.log( `${c.dim}Use when you have intentionally rebuilt the scanner locally (e.g. a feature branch) and the pinned checksum no longer matches.${c.reset}`, ); @@ -3642,10 +3731,7 @@ async function cmdSecurityClearCache(): Promise { const nonInteractive = isNonInteractive(); if (!nonInteractive) { - const ok = await promptConfirm( - `Continue? [Y/n] (auto-yes in 8s): `, - 8000, - ); + const ok = await promptConfirm(`Continue? [Y/n] (auto-yes in 8s): `, 8000); if (!ok) { console.log(`${c.dim}Aborted.${c.reset}`); return false; @@ -3653,7 +3739,9 @@ async function cmdSecurityClearCache(): Promise { } if (target !== "bumblebee") { - console.error(`${c.red}Unknown cache target: ${target} (only 'bumblebee' is supported)${c.reset}`); + console.error( + `${c.red}Unknown cache target: ${target} (only 'bumblebee' is supported)${c.reset}`, + ); return false; } @@ -3675,7 +3763,9 @@ async function cmdCreatePlugin(): Promise { if (!pluginName) { console.error(`${c.red}Usage: kit create-plugin ${c.reset}`); console.error(`${c.dim}Example: kit create-plugin aws-s3${c.reset}`); - console.error(`${c.dim}Creates ./kit-plugin-aws-s3/ with a working TypeScript adapter.${c.reset}`); + console.error( + `${c.dim}Creates ./kit-plugin-aws-s3/ with a working TypeScript adapter.${c.reset}`, + ); return false; } @@ -3716,12 +3806,18 @@ async function cmdClone(): Promise { console.error(); console.error(`${c.dim}Options:${c.reset}`); console.error(`${c.dim} --no-setup Skip running kit setup after cloning${c.reset}`); - console.error(`${c.dim} --env Environment to use for setup (default: "default")${c.reset}`); + console.error( + `${c.dim} --env Environment to use for setup (default: "default")${c.reset}`, + ); console.error(); console.error(`${c.dim}Example:${c.reset}`); console.error(`${c.dim} kit clone https://github.com/sandstream/example my-project${c.reset}`); - console.error(`${c.dim} kit clone https://github.com/sandstream/example my-project --env production${c.reset}`); - console.error(`${c.dim} kit clone https://github.com/sandstream/example my-project --no-setup${c.reset}`); + console.error( + `${c.dim} kit clone https://github.com/sandstream/example my-project --env production${c.reset}`, + ); + console.error( + `${c.dim} kit clone https://github.com/sandstream/example my-project --no-setup${c.reset}`, + ); return false; } @@ -3746,7 +3842,9 @@ async function cmdClone(): Promise { if (!cloneResult.haskitToml) { console.log(`${c.yellow}⚠ No .kit.toml found in repository.${c.reset}`); - console.log(`${c.dim}Create one with 'cd ${cloneResult.clonedPath} && kit init' to set up kit.${c.reset}`); + console.log( + `${c.dim}Create one with 'cd ${cloneResult.clonedPath} && kit init' to set up kit.${c.reset}`, + ); console.log(); return true; } @@ -3773,7 +3871,9 @@ async function cmdClone(): Promise { return setupOk; } catch (err) { process.chdir(originalCwd); - console.error(`${c.red}Error during setup: ${err instanceof Error ? err.message : String(err)}${c.reset}`); + console.error( + `${c.red}Error during setup: ${err instanceof Error ? err.message : String(err)}${c.reset}`, + ); return false; } } @@ -3787,7 +3887,9 @@ async function cmdRun(): Promise { console.error(`${c.red}Usage: kit run -- [args...]${c.reset}`); console.error(); console.error(`${c.dim}Options:${c.reset}`); - console.error(`${c.dim} --env Environment to use (dev, staging, production, etc.)${c.reset}`); + console.error( + `${c.dim} --env Environment to use (dev, staging, production, etc.)${c.reset}`, + ); console.error(); console.error(`${c.dim}Example:${c.reset}`); console.error(`${c.dim} kit run -- pnpm test${c.reset}`); @@ -3885,7 +3987,9 @@ async function cmdContextCheck(): Promise { ); const suggestion = suggestContextToml(await gatherLive(process.cwd())); if (suggestion) { - console.log(`\nDetected here — add a ${c.bold}[context]${c.reset} block to .kit.toml to lock it:\n`); + console.log( + `\nDetected here — add a ${c.bold}[context]${c.reset} block to .kit.toml to lock it:\n`, + ); console.log(suggestion); console.log( `\n${c.yellow}Verify each value is correct for THIS repo before trusting it.${c.reset} ${c.dim}kit detected the currently-active CLI state, which is exactly what the lock exists to question. Then re-run kit context check.${c.reset}`, @@ -3950,7 +4054,9 @@ async function cmdContextUse(): Promise { } const failed = results.filter((r) => !r.ok).length; if (failed > 0) { - console.log(`\n${c.yellow}${failed} step(s) failed (tool not installed?). Run kit context check to verify.${c.reset}`); + console.log( + `\n${c.yellow}${failed} step(s) failed (tool not installed?). Run kit context check to verify.${c.reset}`, + ); } return failed === 0; } @@ -3990,17 +4096,23 @@ async function cmdContext(): Promise { } if (context.tools.length > 0) { - console.log(`${c.bold}Tools (${context.tools.filter((t) => t.ok).length}/${context.tools.length}):${c.reset}`); + console.log( + `${c.bold}Tools (${context.tools.filter((t) => t.ok).length}/${context.tools.length}):${c.reset}`, + ); for (const tool of context.tools) { const status = tool.ok ? `${c.green}✓${c.reset}` : `${c.red}✗${c.reset}`; - const version = tool.installed ? ` ${c.dim}(${tool.installed})${c.reset}` : " not installed"; + const version = tool.installed + ? ` ${c.dim}(${tool.installed})${c.reset}` + : " not installed"; console.log(` ${status} ${tool.name}${version}`); } console.log(); } if (context.services.length > 0) { - console.log(`${c.bold}Services (${context.services.filter((s) => s.authenticated).length}/${context.services.length}):${c.reset}`); + console.log( + `${c.bold}Services (${context.services.filter((s) => s.authenticated).length}/${context.services.length}):${c.reset}`, + ); for (const service of context.services) { const status = service.authenticated ? `${c.green}✓${c.reset}` : `${c.red}✗${c.reset}`; console.log(` ${status} ${service.name}`); @@ -4009,7 +4121,9 @@ async function cmdContext(): Promise { } if (context.secrets.keys.length > 0) { - console.log(`${c.bold}Secrets (${context.secrets.keys.filter((s) => s.available).length}/${context.secrets.keys.length}):${c.reset}`); + console.log( + `${c.bold}Secrets (${context.secrets.keys.filter((s) => s.available).length}/${context.secrets.keys.length}):${c.reset}`, + ); for (const secret of context.secrets.keys) { const status = secret.available ? `${c.green}✓${c.reset}` : `${c.red}✗${c.reset}`; console.log(` ${status} ${secret.name}`); @@ -4019,7 +4133,9 @@ async function cmdContext(): Promise { if (context.locks.length > 0) { const allInSync = context.locks.every((l) => l.inSync); - console.log(`${c.bold}Lock Files${allInSync ? ` ${c.green}(in sync)` : ` ${c.yellow}(drift detected)`}:${c.reset}`); + console.log( + `${c.bold}Lock Files${allInSync ? ` ${c.green}(in sync)` : ` ${c.yellow}(drift detected)`}:${c.reset}`, + ); for (const lock of context.locks) { const status = lock.inSync ? `${c.green}✓${c.reset}` : `${c.yellow}⚠${c.reset}`; console.log(` ${status} ${lock.category}: ${lock.detail}`); @@ -4071,7 +4187,10 @@ async function buildHealthCtx(config: kitConfig): Promise { dependencies?: Record; devDependencies?: Record; }; - const deps = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]; + const deps = [ + ...Object.keys(pkg.dependencies ?? {}), + ...Object.keys(pkg.devDependencies ?? {}), + ]; const { detectServices } = await import("./service-registry.js"); services = await detectServices({ deps, fileExists: async (p) => existsSync(resolve(cwd, p)) }); } catch { @@ -4096,7 +4215,8 @@ async function cmdHealth(): Promise { config, { operation: "health", operationType: "read", metadata: {} }, async () => { - const { runHealth, selectSensors, defaultHealthDeps, formatHealth } = await import("./health.js"); + const { runHealth, selectSensors, defaultHealthDeps, formatHealth } = + await import("./health.js"); const { syncHealthFindings } = await import("./health-track.js"); const ctx = await buildHealthCtx(config); @@ -4158,12 +4278,17 @@ async function cmdIngest(): Promise { return true; } - console.log(`${c.bold}kit ingest${c.reset} ${c.dim}${format} · ${findings.length} finding(s)${c.reset}`); + console.log( + `${c.bold}kit ingest${c.reset} ${c.dim}${format} · ${findings.length} finding(s)${c.reset}`, + ); const order: Record = { critical: 0, high: 1, medium: 2, low: 3 }; - const sorted = [...findings].sort((a, b) => (order[a.severity ?? "low"] ?? 9) - (order[b.severity ?? "low"] ?? 9)); + const sorted = [...findings].sort( + (a, b) => (order[a.severity ?? "low"] ?? 9) - (order[b.severity ?? "low"] ?? 9), + ); for (const f of sorted) { const sev = f.severity ?? "low"; - const color = sev === "critical" || sev === "high" ? c.red : sev === "medium" ? c.yellow : c.dim; + const color = + sev === "critical" || sev === "high" ? c.red : sev === "medium" ? c.yellow : c.dim; const cite = f.rule ? ` ${c.dim}[${f.rule.id}]${c.reset}` : ""; console.log(` ${color}${sev.toUpperCase().padEnd(8)}${c.reset} ${f.name}${cite}`); console.log(` ${c.dim}${f.detail}${c.reset}`); @@ -4187,9 +4312,13 @@ async function cmdSupplyChain(): Promise { console.log(`${c.bold}kit supply-chain${c.reset}`); for (const r of results) { const mark = - r.status === "fail" ? `${c.red}✗${c.reset}` : - r.status === "warn" ? `${c.yellow}!${c.reset}` : - r.status === "skip" ? `${c.dim}−${c.reset}` : `${c.green}✓${c.reset}`; + r.status === "fail" + ? `${c.red}✗${c.reset}` + : r.status === "warn" + ? `${c.yellow}!${c.reset}` + : r.status === "skip" + ? `${c.dim}−${c.reset}` + : `${c.green}✓${c.reset}`; console.log(` ${mark} ${r.name} ${c.dim}${r.detail}${c.reset}`); if (r.suggestion) console.log(` ${c.dim}${r.suggestion}${c.reset}`); } @@ -4208,11 +4337,16 @@ async function cmdAgentAudit(): Promise { return fails === 0; } - console.log(`${c.bold}kit agent-audit${c.reset} ${c.dim}agent/MCP configs + git hooks${c.reset}`); + console.log( + `${c.bold}kit agent-audit${c.reset} ${c.dim}agent/MCP configs + git hooks${c.reset}`, + ); for (const r of results) { const mark = - r.status === "fail" ? `${c.red}✗${c.reset}` : - r.status === "warn" ? `${c.yellow}!${c.reset}` : `${c.green}✓${c.reset}`; + r.status === "fail" + ? `${c.red}✗${c.reset}` + : r.status === "warn" + ? `${c.yellow}!${c.reset}` + : `${c.green}✓${c.reset}`; console.log(` ${mark} ${r.name} ${c.dim}${r.detail}${c.reset}`); if (r.suggestion) console.log(` ${c.dim}${r.suggestion}${c.reset}`); } @@ -4246,13 +4380,24 @@ async function cmdSentinel(): Promise { ]) { const res = await execFileNoThrow( "gh", - [...base, "--label", "kit-sentinel", "--state", "open", "--json", "body", "--limit", "200"], + [ + ...base, + "--label", + "kit-sentinel", + "--state", + "open", + "--json", + "body", + "--limit", + "200", + ], { timeout: 15_000 }, ); if (!res.ok) return null; // gh absent/unauth → agent dedups (fail-open) try { for (const it of JSON.parse(res.stdout) as { body?: string }[]) { - for (const g of (it.body ?? "").matchAll(/kit-sentinel:([^\s]+?)\s*-->/g)) out.add(g[1]); + for (const g of (it.body ?? "").matchAll(/kit-sentinel:([^\s]+?)\s*-->/g)) + out.add(g[1]); } } catch { return null; @@ -4268,15 +4413,19 @@ async function cmdSentinel(): Promise { } const fresh = proposals.filter((p) => p.alreadyOpen !== true); - console.log(`${c.bold}kit sentinel${c.reset} ${c.dim}${proposals.length} proposal(s), ${fresh.length} fresh${c.reset}`); - if (proposals.length === 0) console.log(` ${c.dim}no red findings — nothing to propose${c.reset}`); + console.log( + `${c.bold}kit sentinel${c.reset} ${c.dim}${proposals.length} proposal(s), ${fresh.length} fresh${c.reset}`, + ); + if (proposals.length === 0) + console.log(` ${c.dim}no red findings — nothing to propose${c.reset}`); for (const p of proposals) { const tag = p.alreadyOpen === true ? ` ${c.dim}(already open)${c.reset}` : ""; const color = p.class === "human" ? c.red : p.class === "code" ? c.yellow : c.dim; console.log(` ${color}${p.artifact}${c.reset} ${p.title}${tag}`); console.log(` ${c.dim}${p.findingId} — your agent opens this with its own creds${c.reset}`); } - if (proposals.length > 0) console.log(`${c.dim}run with --json and have any agent act on the fresh proposals${c.reset}`); + if (proposals.length > 0) + console.log(`${c.dim}run with --json and have any agent act on the fresh proposals${c.reset}`); return true; } @@ -4286,15 +4435,38 @@ async function cmdScan(): Promise { const { resolveToolBin } = await import("./utils/resolveTool.js"); const { execFileNoThrow } = await import("./utils/execFileNoThrow.js"); const { loadBaseline, baselineGet, baselineSet, saveBaseline } = await import("./baseline.js"); + const { SCANNERS } = await import("./scanners.js"); const cwd = process.cwd(); + const config = await loadConfig(resolveConfigPath()); + + // Resolve scanner tokens (SNYK_TOKEN, …) from a configured tooling Infisical + // project so `kit scan` works without an `infisical run` wrapper (#65). The + // value flows vault→subprocess env; it is never logged. + const toolingTokens: Record = {}; + const tooling = config.scan?.tooling; + if (tooling?.project_id) { + const { fetchInfisicalProjectSecrets } = await import("./secret-backends.js"); + const map = await fetchInfisicalProjectSecrets({ + project_id: tooling.project_id, + environment: tooling.env, + }); + for (const s of SCANNERS) { + if (s.needsToken && !process.env[s.needsToken] && map.has(s.needsToken)) { + toolingTokens[s.needsToken] = map.get(s.needsToken)!; + } + } + } const { merged, runs } = await runScanners({ resolve: (bin) => resolveToolBin(bin), run: async (bin, args) => { - const r = await execFileNoThrow(bin, args, { timeout: 180_000 }); + const r = await execFileNoThrow(bin, args, { + timeout: 180_000, + env: { ...process.env, ...toolingTokens }, + }); return { ok: r.ok, stdout: r.stdout }; }, - hasEnv: (name) => Boolean(process.env[name]), + hasEnv: (name) => Boolean(process.env[name] || toolingTokens[name]), detect: (markers) => markers.some((m) => existsSync(resolve(cwd, m))), }); @@ -4304,7 +4476,9 @@ async function cmdScan(): Promise { const bl = await loadBaseline(cwd); baselineSet(bl, "scan", "findings", merged.map(dedupKey)); await saveBaseline(bl, cwd); - console.log(`${c.green}baseline updated${c.reset} ${c.dim}${merged.length} scan finding(s) accepted into .kit-baseline.json${c.reset}`); + console.log( + `${c.green}baseline updated${c.reset} ${c.dim}${merged.length} scan finding(s) accepted into .kit-baseline.json${c.reset}`, + ); return true; } @@ -4323,20 +4497,32 @@ async function cmdScan(): Promise { } const suppressNote = suppressed > 0 ? ` ${c.dim}(${suppressed} baselined)${c.reset}` : ""; - console.log(`${c.bold}kit scan${c.reset} ${c.dim}external scanners → one merged verdict${c.reset}${suppressNote}`); + console.log( + `${c.bold}kit scan${c.reset} ${c.dim}external scanners → one merged verdict${c.reset}${suppressNote}`, + ); for (const r of runs) { - const mark = r.status === "ran" ? `${c.green}✓${c.reset}` : r.status === "error" ? `${c.red}✗${c.reset}` : `${c.dim}−${c.reset}`; + const mark = + r.status === "ran" + ? `${c.green}✓${c.reset}` + : r.status === "error" + ? `${c.red}✗${c.reset}` + : `${c.dim}−${c.reset}`; const note = r.status === "ran" ? `${r.findings} finding(s)` : r.status; console.log(` ${mark} ${r.id} ${c.dim}${note}${c.reset}`); } console.log(""); if (findings.length === 0) { - console.log(` ${c.green}no findings${suppressed > 0 ? " (after baseline)" : " from the scanners that ran"}${c.reset}`); + console.log( + ` ${c.green}no findings${suppressed > 0 ? " (after baseline)" : " from the scanners that ran"}${c.reset}`, + ); } else { for (const m of findings) { const sev = m.severity ?? "low"; - const color = sev === "critical" || sev === "high" ? c.red : sev === "medium" ? c.yellow : c.dim; - console.log(` ${color}${sev.toUpperCase().padEnd(8)}${c.reset} ${m.name} ${c.dim}[${m.scanners.join("+")}]${c.reset}`); + const color = + sev === "critical" || sev === "high" ? c.red : sev === "medium" ? c.yellow : c.dim; + console.log( + ` ${color}${sev.toUpperCase().padEnd(8)}${c.reset} ${m.name} ${c.dim}[${m.scanners.join("+")}]${c.reset}`, + ); } } if (bad > 0) console.log(`${c.red}${bad} high/critical${c.reset}`); @@ -4357,9 +4543,13 @@ async function cmdGhaAudit(): Promise { console.log(`${c.bold}kit gha-audit${c.reset} ${c.dim}.github/workflows hardening${c.reset}`); for (const r of results) { const mark = - r.status === "fail" ? `${c.red}✗${c.reset}` : - r.status === "warn" ? `${c.yellow}!${c.reset}` : - r.status === "skip" ? `${c.dim}−${c.reset}` : `${c.green}✓${c.reset}`; + r.status === "fail" + ? `${c.red}✗${c.reset}` + : r.status === "warn" + ? `${c.yellow}!${c.reset}` + : r.status === "skip" + ? `${c.dim}−${c.reset}` + : `${c.green}✓${c.reset}`; console.log(` ${mark} ${r.name} ${c.dim}${r.detail}${c.reset}`); if (r.suggestion) console.log(` ${c.dim}${r.suggestion}${c.reset}`); } @@ -4385,7 +4575,9 @@ async function cmdSbom(): Promise { return false; } const components = lockComponents(parseLockPkgs(lock)); - console.log(JSON.stringify(fmt === "spdx" ? toSpdx(components) : toCycloneDX(components), null, 2)); + console.log( + JSON.stringify(fmt === "spdx" ? toSpdx(components) : toCycloneDX(components), null, 2), + ); return true; } @@ -4403,9 +4595,8 @@ async function cmdWhoami(): Promise { const envInfo = detectEnvironment(config.governance); const agent = config.governance?.agent; - const budgetEnabled = config.governance?.enabled && ( - agent?.max_tokens_per_day || agent?.max_operations_per_hour - ); + const budgetEnabled = + config.governance?.enabled && (agent?.max_tokens_per_day || agent?.max_operations_per_hour); let budget: Awaited> | null = null; if (budgetEnabled) { @@ -4416,9 +4607,7 @@ async function cmdWhoami(): Promise { console.log( JSON.stringify( { - agent: agent - ? { id: agent.id, name: agent.name } - : null, + agent: agent ? { id: agent.id, name: agent.name } : null, environment: envInfo.environment, environment_source: envInfo.source, budget: budget @@ -4431,8 +4620,8 @@ async function cmdWhoami(): Promise { : null, }, null, - 2 - ) + 2, + ), ); return true; } @@ -4448,13 +4637,9 @@ async function cmdWhoami(): Promise { } const envColor = - envInfo.environment === "prod" - ? c.red - : envInfo.environment === "staging" - ? c.yellow - : c.green; + envInfo.environment === "prod" ? c.red : envInfo.environment === "staging" ? c.yellow : c.green; console.log( - ` ${c.bold}Env:${c.reset} ${envColor}${envInfo.environment}${c.reset} ${c.dim}(via ${envInfo.source})${c.reset}` + ` ${c.bold}Env:${c.reset} ${envColor}${envInfo.environment}${c.reset} ${c.dim}(via ${envInfo.source})${c.reset}`, ); if (budget) { @@ -4479,18 +4664,21 @@ function cmdVersion(): boolean { } const COMMAND_HELP: Record = { - status: "Adoption checklist — what's set up across kit + the next step for each gap", - check: "Check status of all tools, services, secrets, and lock files", - review: "Full repo audit — runs check + design in one gate (for agents / PR checks)", - design: "Check design quality (a11y, design tokens) against the baseline", - baseline: "Freeze current warnings into .kit-baseline.json so future runs gate only net-new findings", - memory: "Local conversation memory — index transcripts + show stats", + status: "Adoption checklist — what's set up across kit + the next step for each gap", + check: "Check status of all tools, services, secrets, and lock files", + review: "Full repo audit — runs check + design in one gate (for agents / PR checks)", + design: "Check design quality (a11y, design tokens) against the baseline", + baseline: + "Freeze current warnings into .kit-baseline.json so future runs gate only net-new findings", + memory: "Local conversation memory — index transcripts + show stats", "memory index": "Index ~/.claude transcripts into the SQLite memory store", "memory search": "Full-text search memory (current project; --global for all)", "memory stats": "Show what the local memory store contains", - "memory suggest": "Emit a BYO-LLM review prompt (recent activity + open items) — pipe to your own model", + "memory suggest": + "Emit a BYO-LLM review prompt (recent activity + open items) — pipe to your own model", "memory merge": "Merge another machine's memory.db into this one (dedup by uuid)", - "memory install": "Wire UserPromptSubmit + SessionEnd + SessionStart (recovery) hooks into ~/.claude/settings.json", + "memory install": + "Wire UserPromptSubmit + SessionEnd + SessionStart (recovery) hooks into ~/.claude/settings.json", "memory scan": "Scan the memory store for stored secrets (exit 1 if any found)", "memory backup": "Encrypted backup of the memory store (AES-256-GCM; KIT_MEMORY_PASSPHRASE)", "memory restore": "Restore an encrypted memory backup (e.g. on a new machine)", @@ -4501,24 +4689,29 @@ const COMMAND_HELP: Record = { "memory save": "Bookmark the current session as a named copilot", "memory threads": "List saved copilots (current project; --global for all)", "memory resume": "Print the resume command for a saved copilot (by name or number)", - init: "Detect stack, generate .kit.toml, and run full setup", - upgrade: "Update lock files from .kit.toml", - install: "Install missing tools via mise", - login: "Guided login to all configured services", - "login --plan": "Show the resolved auth strategy per service (vault/interactive/capture + passkey) without logging in", - secrets: "Generate .env.local from template + secret store", + init: "Detect stack, generate .kit.toml, and run full setup", + upgrade: "Update lock files from .kit.toml", + install: "Install missing tools via mise", + login: "Guided login to all configured services", + "login --plan": + "Show the resolved auth strategy per service (vault/interactive/capture + passkey) without logging in", + secrets: "Generate .env.local from template + secret store", "secrets sync": "Push resolved secrets to GitHub Actions / .env.ci / stdout", "secrets migrate": "Migrate plaintext secrets in .env* → configured vault", - "secrets set": "Capture a value to the vault: kit secrets set --stdin (safer) | --value ", + "secrets set": + "Capture a value to the vault: kit secrets set --stdin (safer) | --value ", "secrets rotate": "Rotate a key: write new value to vault (explicit / random)", "secrets onecli": "Register a key with OneCLI gateway so agent never sees the real value", - "secrets purge-history": "Destructive: rewrite git history to remove a leaked value (--force-history)", - "secrets propagate": "Push a value to deploy targets only (skips vault-write). --stdin safer than --value", - "secrets revoke-old": "Revoke a previously-minted scoped key (Supabase Mgmt API)", - "env switch": "Switch active environment (dev/staging/prod). Gates prod-key reads.", - "env current": "Show active environment marker", - analyze: "Analyze repo + emit draft CLAUDE.md / RULES.md", - "agent-config": "Inject a managed 'use kit' block into CLAUDE.md / AGENTS.md / .cursorrules / .clinerules", + "secrets purge-history": + "Destructive: rewrite git history to remove a leaked value (--force-history)", + "secrets propagate": + "Push a value to deploy targets only (skips vault-write). --stdin safer than --value", + "secrets revoke-old": "Revoke a previously-minted scoped key (Supabase Mgmt API)", + "env switch": "Switch active environment (dev/staging/prod). Gates prod-key reads.", + "env current": "Show active environment marker", + analyze: "Analyze repo + emit draft CLAUDE.md / RULES.md", + "agent-config": + "Inject a managed 'use kit' block into CLAUDE.md / AGENTS.md / .cursorrules / .clinerules", "security policy": "Dependency allowlist enforcement (init|add|check)", "security clear-cache": "Clear cached scanner binary (after intentional rebuild)", "security scan-staged": "Pre-commit: scan staged files for credential patterns", @@ -4527,44 +4720,48 @@ const COMMAND_HELP: Record = { "security costs": "Snapshot per-key spend vs policy cap (Stripe live; others stubbed)", "security check-gitignore": "Verify .gitignore covers sensitive paths (--fix to auto-patch)", "security verify-pull": "After git pull: audit new deps, gitignore drops, introduced secrets", - "security prescan": "Multi-repo baseline sweep (secrets, gitignore, branch-protect; --deep adds CVE/workflow-drift/bumblebee; --format=json + --vs-baseline= for CI drift)", - "security prescan-diff": "Diff two prescan reports — surface new regressions + fixed findings since baseline", - "audit secrets": "Forensics: who/what touched each key + when (reads audit log)", - "auth elevate": "Mint elevation marker for destructive secret ops (TOTP/yes-prompt)", - "auth status": "Show active elevation", - "auth revoke": "Drop the elevation marker", + "security prescan": + "Multi-repo baseline sweep (secrets, gitignore, branch-protect; --deep adds CVE/workflow-drift/bumblebee; --format=json + --vs-baseline= for CI drift)", + "security prescan-diff": + "Diff two prescan reports — surface new regressions + fixed findings since baseline", + "audit secrets": "Forensics: who/what touched each key + when (reads audit log)", + "auth elevate": "Mint elevation marker for destructive secret ops (TOTP/yes-prompt)", + "auth status": "Show active elevation", + "auth revoke": "Drop the elevation marker", "auth setup-totp": "Enroll TOTP secret (writes ~/.kit/totp-secret 0600)", "hooks add": "Install a built-in hook (e.g. secret-scan)", - setup: "Full pipeline: install → login → secrets → agent config → verify", - "setup --recommended": "Opinionated profile: setup + memory hooks + git secret-scan/context-check gates", - fix: "Auto-fix what is possible", - heal: "Loop: auto-fix safe findings, re-scan until green; gate destructive, fail-closed on tamper (--dry-run, --agent)", - escalate: "List what needs human action", - governance: "View governance status and agent access controls", - skills: "Check status of agent skills", - hooks: "Manage git hooks", - add: "Provision a service (kit add --list to see all adapters)", - audit: "View audit log of kit operations", - doctor: "Deep diagnostics — checks environment health in detail", - env: "Show current environment info", - ci: "CI-native check: GitHub Actions annotations, GitLab JUnit, JSON", - clone: "Clone a Git repository and run kit setup", - run: "Execute a command with project env vars loaded", - open: "Open service dashboard in browser (stripe, vercel, railway, etc.)", - context: "Show project context: tools, services, secrets, environment", - "context check": "Verify each CLI's live account+project matches .kit.toml [context] (exits non-zero on mismatch)", - "context use": "Activate the declared context: gcloud config + repo git identity", + setup: "Full pipeline: install → login → secrets → agent config → verify", + "setup --recommended": + "Opinionated profile: setup + memory hooks + git secret-scan/context-check gates", + fix: "Auto-fix what is possible", + heal: "Loop: auto-fix safe findings, re-scan until green; gate destructive, fail-closed on tamper (--dry-run, --agent)", + escalate: "List what needs human action", + governance: "View governance status and agent access controls", + skills: "Check status of agent skills", + hooks: "Manage git hooks", + add: "Provision a service (kit add --list to see all adapters)", + audit: "View audit log of kit operations", + doctor: "Deep diagnostics — checks environment health in detail", + env: "Show current environment info", + ci: "CI-native check: GitHub Actions annotations, GitLab JUnit, JSON", + clone: "Clone a Git repository and run kit setup", + run: "Execute a command with project env vars loaded", + open: "Open service dashboard in browser (stripe, vercel, railway, etc.)", + context: "Show project context: tools, services, secrets, environment", + "context check": + "Verify each CLI's live account+project matches .kit.toml [context] (exits non-zero on mismatch)", + "context use": "Activate the declared context: gcloud config + repo git identity", "context --prompt": "Print a compact active-gcloud indicator for your shell prompt (PS1)", - mcp: "MCP server over stdio (Claude Code/Cursor/Codex); 'kit mcp list|auth|set-token|clear' manages declared servers", - whoami: "Show current agent / user identity", - version: "Print kit version", - "create-plugin":"Scaffold a new kit plugin package", - plugin: "Discover and manage kit plugins (search, list, scaffold, install)", - triage: "Security evaluation before installing packages, images, or skills", - pkg: "Install package with mandatory triage (kit pkg npm:express)", - team: "Manage team members, roles, and permissions (RBAC, invitations, audit logs)", - completions: "Output shell completion script (bash, zsh, fish)", - help: "Show this help", + mcp: "MCP server over stdio (Claude Code/Cursor/Codex); 'kit mcp list|auth|set-token|clear' manages declared servers", + whoami: "Show current agent / user identity", + version: "Print kit version", + "create-plugin": "Scaffold a new kit plugin package", + plugin: "Discover and manage kit plugins (search, list, scaffold, install)", + triage: "Security evaluation before installing packages, images, or skills", + pkg: "Install package with mandatory triage (kit pkg npm:express)", + team: "Manage team members, roles, and permissions (RBAC, invitations, audit logs)", + completions: "Output shell completion script (bash, zsh, fish)", + help: "Show this help", }; async function cmdPkg(): Promise { @@ -4599,7 +4796,9 @@ async function cmdPkg(): Promise { return false; } - console.log(`${c.bold}Installing ${spec.ecosystem}:${spec.name}${spec.version ? `@${spec.version}` : ""}${c.reset}\n`); + console.log( + `${c.bold}Installing ${spec.ecosystem}:${spec.name}${spec.version ? `@${spec.version}` : ""}${c.reset}\n`, + ); console.log(`${c.cyan}Step 1: Triage...${c.reset}`); const result = await installPkg(spec); @@ -4626,13 +4825,17 @@ async function cmdTriage(): Promise { console.log("Usage:"); console.log(" kit triage docker Evaluate Docker image (CVE + sandbox)"); console.log(" kit triage npm Evaluate npm package (registry + GitHub)"); - console.log(" kit triage npm --sandbox + offline tarball inspection (install-script + path-traversal scan, no code executed)"); + console.log( + " kit triage npm --sandbox + offline tarball inspection (install-script + path-traversal scan, no code executed)", + ); console.log(" kit triage pip Evaluate PyPI package"); console.log(" kit triage repo Evaluate GitHub repository"); console.log(" kit triage skill Evaluate Claude Code / agent skill"); console.log(" kit triage all Auto-detect and run all checks"); console.log(" kit triage tools Show installed security tools"); - console.log(" kit triage check-deps Pre-commit gate: fail if staged deps lack triage entries"); + console.log( + " kit triage check-deps Pre-commit gate: fail if staged deps lack triage entries", + ); console.log(""); console.log("Examples:"); console.log(" kit triage npm express"); @@ -4691,11 +4894,15 @@ async function cmdTriage(): Promise { } } } catch (err) { - console.error(` ${c.red}sandbox failed: ${err instanceof Error ? err.message : String(err)}${c.reset}`); + console.error( + ` ${c.red}sandbox failed: ${err instanceof Error ? err.message : String(err)}${c.reset}`, + ); sandboxClean = false; } } else if (sandbox && type !== "npm") { - console.log(`\n${c.dim}(--sandbox currently only applies to npm; ignored for ${type})${c.reset}`); + console.log( + `\n${c.dim}(--sandbox currently only applies to npm; ignored for ${type})${c.reset}`, + ); } const overall = result.passed && sandboxClean; @@ -4725,11 +4932,7 @@ interface TriageLogEntry { granter: string; } -async function recordTriageRun( - type: string, - target: string, - sandbox: boolean, -): Promise { +async function recordTriageRun(type: string, target: string, sandbox: boolean): Promise { const { appendFile } = await import("node:fs/promises"); const { resolve } = await import("node:path"); const entry: TriageLogEntry = { @@ -4746,7 +4949,9 @@ async function recordTriageRun( "utf-8", ); } catch (err) { - console.error(`${c.dim}(triage-log append failed: ${err instanceof Error ? err.message : err})${c.reset}`); + console.error( + `${c.dim}(triage-log append failed: ${err instanceof Error ? err.message : err})${c.reset}`, + ); } } @@ -4784,29 +4989,38 @@ async function cmdTriageCheckDeps(): Promise { if (stagedPkg) { try { const headPkgRaw = gitShow("HEAD:package.json"); - const staged = JSON.parse(stagedPkg) as { dependencies?: Record; devDependencies?: Record }; + const staged = JSON.parse(stagedPkg) as { + dependencies?: Record; + devDependencies?: Record; + }; const head = headPkgRaw - ? (JSON.parse(headPkgRaw) as { dependencies?: Record; devDependencies?: Record }) + ? (JSON.parse(headPkgRaw) as { + dependencies?: Record; + devDependencies?: Record; + }) : {}; const stagedDeps = { ...staged.dependencies, ...staged.devDependencies }; const headDeps = { ...head.dependencies, ...head.devDependencies }; for (const name of Object.keys(stagedDeps)) { if (!(name in headDeps)) newDeps.push({ ecosystem: "npm", name }); } - } catch { /* malformed package.json — skip */ } + } catch { + /* malformed package.json — skip */ + } } // requirements.txt — line-oriented diff. const stagedReq = gitShow(":requirements.txt"); if (stagedReq) { const headReq = gitShow("HEAD:requirements.txt") ?? ""; - const parseLines = (text: string) => new Set( - text - .split("\n") - .map((l) => l.trim()) - .filter((l) => l && !l.startsWith("#")) - .map((l) => l.split(/[<>=!~]/)[0]!.trim()), - ); + const parseLines = (text: string) => + new Set( + text + .split("\n") + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith("#")) + .map((l) => l.split(/[<>=!~]/)[0]!.trim()), + ); const stagedSet = parseLines(stagedReq); const headSet = parseLines(headReq); for (const name of stagedSet) { @@ -4827,7 +5041,9 @@ async function cmdTriageCheckDeps(): Promise { const key = `${entry.type}:${entry.target}`; const prev = latest[key]; if (!prev || entry.timestamp > prev) latest[key] = entry.timestamp; - } catch { /* skip malformed line */ } + } catch { + /* skip malformed line */ + } } } catch { /* no triage log yet */ @@ -4839,7 +5055,9 @@ async function cmdTriageCheckDeps(): Promise { const key = `${dep.ecosystem}:${dep.name}`; const ts = latest[key]; if (!ts || Date.parse(ts) < cutoff) { - missing.push(` - ${dep.ecosystem}:${dep.name} (run: kit triage ${dep.ecosystem} ${dep.name})`); + missing.push( + ` - ${dep.ecosystem}:${dep.name} (run: kit triage ${dep.ecosystem} ${dep.name})`, + ); } } @@ -4848,8 +5066,12 @@ async function cmdTriageCheckDeps(): Promise { console.error(`${c.red}✗ Triage missing for ${missing.length} newly-added dep(s):${c.reset}`); for (const line of missing) console.error(line); console.error(""); - console.error(`${c.dim}Triage policy lives in CLAUDE.md. Run the suggested triage commands above,`); - console.error(`then re-stage and commit. Bypass with --no-verify is recorded to ${SKIPPED_COMMITS_LOG}.${c.reset}`); + console.error( + `${c.dim}Triage policy lives in CLAUDE.md. Run the suggested triage commands above,`, + ); + console.error( + `then re-stage and commit. Bypass with --no-verify is recorded to ${SKIPPED_COMMITS_LOG}.${c.reset}`, + ); return false; } @@ -4859,11 +5081,19 @@ function cmdHelp(subcommand?: string): boolean { return true; } - const bold = c.bold, cyan = c.cyan, dim = c.dim, reset = c.reset, green = c.green; + const bold = c.bold, + cyan = c.cyan, + dim = c.dim, + reset = c.reset, + green = c.green; console.log(`${bold}kit${reset} ${dim}v${KIT_VERSION}${reset} — developer environment manager\n`); - console.log(`${bold}Get going:${reset} ${dim}npx sandstream-kit setup${reset} ${dim}or${reset} ${green}kit init${reset} ${dim}→${reset} ${green}kit check${reset} ${dim}→${reset} ${green}kit setup${reset}`); - console.log(`${dim}Prereqs: Node 22+, git, and mise (brew install mise) for installing tools.${reset}\n`); + console.log( + `${bold}Get going:${reset} ${dim}npx sandstream-kit setup${reset} ${dim}or${reset} ${green}kit init${reset} ${dim}→${reset} ${green}kit check${reset} ${dim}→${reset} ${green}kit setup${reset}`, + ); + console.log( + `${dim}Prereqs: Node 22+, git, and mise (brew install mise) for installing tools.${reset}\n`, + ); console.log(`${bold}Usage:${reset} kit ${cyan}${reset} ${dim}[options]${reset}\n`); console.log(`${bold}Commands:${reset}`); @@ -4876,8 +5106,12 @@ function cmdHelp(subcommand?: string): boolean { console.log(`\n${bold}Options:${reset}`); console.log(` ${green}--non-interactive${reset} ${dim}No prompts (for CI / agent use)${reset}`); console.log(` ${green}--json${reset} ${dim}Machine-readable output${reset}`); - console.log(` ${green}--env=${reset} ${dim}Environment override (dev/staging/production)${reset}`); - console.log(` ${green}--dry-run${reset} ${dim}Preview without writing (where supported)${reset}`); + console.log( + ` ${green}--env=${reset} ${dim}Environment override (dev/staging/production)${reset}`, + ); + console.log( + ` ${green}--dry-run${reset} ${dim}Preview without writing (where supported)${reset}`, + ); console.log(` ${green}--help, -h${reset} ${dim}Show this help${reset}`); console.log(` ${green}--version, -v${reset} ${dim}Print version${reset}`); @@ -4933,9 +5167,7 @@ async function cmdTeam(): Promise { return false; } - console.log( - `${c.yellow}Invitation sent to ${email} as ${role}${c.reset}`, - ); + console.log(`${c.yellow}Invitation sent to ${email} as ${role}${c.reset}`); console.log(`${c.dim}Check your email for the invitation link${c.reset}`); return true; } @@ -4947,9 +5179,7 @@ async function cmdTeam(): Promise { } console.log(`${c.bold}Team Members${c.reset}\n`); - console.log( - `${c.dim}(Requires team context — run from project with .kit.toml)${c.reset}`, - ); + console.log(`${c.dim}(Requires team context — run from project with .kit.toml)${c.reset}`); return false; } @@ -5021,16 +5251,13 @@ async function showSkippedCommitBanner(): Promise { for (const line of recent) { try { const entry = JSON.parse(line) as { timestamp: string; sha: string; reason: string }; - process.stderr.write( - ` ${entry.timestamp} ${entry.sha.slice(0, 8)} (${entry.reason})\n`, - ); + process.stderr.write(` ${entry.timestamp} ${entry.sha.slice(0, 8)} (${entry.reason})\n`); } catch { /* malformed line — ignore */ } } process.stderr.write( - ` Review: cat ${SKIPPED_COMMITS_LOG} | jq .\n` + - ` Suppress: KIT_HIDE_HOOK_SKIP_BANNER=1\n`, + ` Review: cat ${SKIPPED_COMMITS_LOG} | jq .\n` + ` Suppress: KIT_HIDE_HOOK_SKIP_BANNER=1\n`, ); } catch { /* banner is best-effort — never break the CLI */ @@ -5045,8 +5272,10 @@ async function showSkippedCommitBanner(): Promise { async function main(): Promise { const args = process.argv.slice(2); const command = args[0]; - const nonInteractive = hasFlag(args, "--non-interactive") || - process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true"; + const nonInteractive = + hasFlag(args, "--non-interactive") || + process.env.CI === "true" || + process.env.GITHUB_ACTIONS === "true"; // Activate read-only mode early so subsequent code paths see the env var. // Honored gates: writeSecretToBackend, grantElevation, installHooks, and @@ -5179,7 +5408,9 @@ async function main(): Promise { const { didYouMean } = await import("./utils/didYouMean.js"); const knownCommands = [ ...new Set(Object.keys(COMMAND_HELP).map((k) => k.split(" ")[0])), - "help", "version", "completions", + "help", + "version", + "completions", ]; const suggestions = didYouMean(command, knownCommands); if (suggestions.length > 0) { @@ -5195,19 +5426,15 @@ async function main(): Promise { // Non-interactive / CI: skip update check if (!nonInteractive) { - checkForUpdate(KIT_VERSION).then((info) => { - if (info) printUpdateNotice(info); - }).catch(() => {}); // never fail + checkForUpdate(KIT_VERSION) + .then((info) => { + if (info) printUpdateNotice(info); + }) + .catch(() => {}); // never fail } } catch (err: unknown) { - if ( - err instanceof Error && - "code" in err && - (err as NodeJS.ErrnoException).code === "ENOENT" - ) { - console.error( - `${c.red}Error: ${KIT_FILE} not found in ${process.cwd()}${c.reset}`, - ); + if (err instanceof Error && "code" in err && (err as NodeJS.ErrnoException).code === "ENOENT") { + console.error(`${c.red}Error: ${KIT_FILE} not found in ${process.cwd()}${c.reset}`); console.error( `${c.dim}Create a .kit.toml to define your project's tools, services, and secrets.${c.reset}`, ); diff --git a/src/clone.test.ts b/src/clone.test.ts index 6b0a781f..ee0cdedf 100644 --- a/src/clone.test.ts +++ b/src/clone.test.ts @@ -16,11 +16,7 @@ before(async () => { // Initialize a minimal git repo for testing await mkdir(testRepoDir, { recursive: true }); await writeFile(join(testRepoDir, "README.md"), "# Test Repo\n", "utf-8"); - await writeFile( - join(testRepoDir, ".kit.toml"), - "[tools]\nnode = \"22\"\n", - "utf-8" - ); + await writeFile(join(testRepoDir, ".kit.toml"), '[tools]\nnode = "22"\n', "utf-8"); // Initialize git const { execSync } = await import("node:child_process"); @@ -57,11 +53,7 @@ describe("cloneRepository", () => { const result = await cloneRepository(opts); // Should derive "my-awesome-repo" from the URL - assert.match( - result.clonedPath, - /my-awesome-repo$/, - "Should derive directory name from URL" - ); + assert.match(result.clonedPath, /my-awesome-repo$/, "Should derive directory name from URL"); }); it("uses provided target directory", async () => { @@ -82,15 +74,8 @@ describe("cloneRepository", () => { }; const result = await cloneRepository(opts); - assert( - !result.clonedPath.endsWith(".git"), - "Should strip .git from directory name" - ); - assert.match( - result.clonedPath, - /my-repo$/, - "Should end with my-repo not my-repo.git" - ); + assert(!result.clonedPath.endsWith(".git"), "Should strip .git from directory name"); + assert.match(result.clonedPath, /my-repo$/, "Should end with my-repo not my-repo.git"); }); it("detects .kit.toml presence", async () => { @@ -201,10 +186,7 @@ describe("cloneRepository", () => { const result = await cloneRepository(opts); if (result.success) { - const readmeContent = await readFile( - join(result.clonedPath, "README.md"), - "utf-8" - ); + const readmeContent = await readFile(join(result.clonedPath, "README.md"), "utf-8"); assert(readmeContent.includes("Test Repo"), "Should be able to read cloned files"); } }); diff --git a/src/clone.ts b/src/clone.ts index b87ce6fc..dbf4a942 100644 --- a/src/clone.ts +++ b/src/clone.ts @@ -2,7 +2,6 @@ import { access, constants } from "node:fs/promises"; import { resolve, basename } from "node:path"; import { exec } from "./utils/exec.js"; - export interface CloneOptions { /** Git repository URL */ repoUrl: string; diff --git a/src/commands/audit.ts b/src/commands/audit.ts index b8fe2fae..674aca26 100644 --- a/src/commands/audit.ts +++ b/src/commands/audit.ts @@ -10,32 +10,27 @@ import { hasFlag, flagValue } from "../utils/flags.js"; async function cmdAuditSecrets(): Promise { const args = process.argv.slice(4); // after "audit secrets" const sinceIdx = args.indexOf("--since-days"); - const sinceDays = - sinceIdx >= 0 && args[sinceIdx + 1] ? parseInt(args[sinceIdx + 1], 10) : 30; + const sinceDays = sinceIdx >= 0 && args[sinceIdx + 1] ? parseInt(args[sinceIdx + 1], 10) : 30; const keyFilter = flagValue(args, "--key"); const jsonMode = hasFlag(args, "--json"); const events = await readSecretAuditEvents(process.cwd(), sinceDays); const { reports, unattributed } = groupBySecret(events); - const filteredReports = keyFilter - ? reports.filter((r) => r.key === keyFilter) - : reports; + const filteredReports = keyFilter ? reports.filter((r) => r.key === keyFilter) : reports; const summary = summarize(filteredReports, sinceDays); if (jsonMode) { - console.log( - JSON.stringify({ summary, reports: filteredReports, unattributed }, null, 2), - ); + console.log(JSON.stringify({ summary, reports: filteredReports, unattributed }, null, 2)); return true; } - console.log(`${c.bold}${c.cyan}kit audit secrets${c.reset} ${c.dim}(last ${sinceDays}d)${c.reset}`); + console.log( + `${c.bold}${c.cyan}kit audit secrets${c.reset} ${c.dim}(last ${sinceDays}d)${c.reset}`, + ); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); if (events.length === 0) { - console.log( - `${c.dim}No secret-related events in audit log (.kit-audit.jsonl).${c.reset}\n`, - ); + console.log(`${c.dim}No secret-related events in audit log (.kit-audit.jsonl).${c.reset}\n`); return true; } diff --git a/src/commands/auth.ts b/src/commands/auth.ts index adaa658f..03643265 100644 --- a/src/commands/auth.ts +++ b/src/commands/auth.ts @@ -19,9 +19,7 @@ export async function cmdAuth(): Promise { if (sub === "status") return cmdAuthStatus(); if (sub === "revoke") return cmdAuthRevoke(); if (sub === "setup-totp") return cmdAuthSetupTotp(); - console.error( - `${c.red}Usage: kit auth [elevate | status | revoke | setup-totp]${c.reset}`, - ); + console.error(`${c.red}Usage: kit auth [elevate | status | revoke | setup-totp]${c.reset}`); return false; } @@ -51,7 +49,9 @@ async function cmdAuthSetupTotp(): Promise { return false; } - console.log(` ${c.green}✓${c.reset} secret written to ${result.filePath} ${c.dim}(chmod 600)${c.reset}\n`); + console.log( + ` ${c.green}✓${c.reset} secret written to ${result.filePath} ${c.dim}(chmod 600)${c.reset}\n`, + ); console.log(`${c.bold}Provisioning URI:${c.reset}`); console.log(` ${c.dim}${result.uri}${c.reset}\n`); console.log(`${c.bold}Or enter the secret manually in your authenticator app:${c.reset}`); @@ -59,7 +59,9 @@ async function cmdAuthSetupTotp(): Promise { console.log(` ${c.bold}Account:${c.reset} ${accountName}`); console.log(` ${c.bold}Issuer:${c.reset} ${issuer}\n`); console.log(`${c.bold}Verify enrollment — the next 6-digit code should be:${c.reset}`); - console.log(` ${c.bold}${result.currentCode}${c.reset} ${c.dim}(or the one shown in your authenticator right now)${c.reset}\n`); + console.log( + ` ${c.bold}${result.currentCode}${c.reset} ${c.dim}(or the one shown in your authenticator right now)${c.reset}\n`, + ); console.log( `${c.dim}Future ${c.bold}kit auth elevate${c.reset}${c.dim} runs will prompt for the TOTP code automatically.${c.reset}`, ); @@ -103,9 +105,7 @@ async function cmdAuthElevate(): Promise { const readline = await import("node:readline/promises"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); try { - const code = (await rl.question( - `Enter 6-digit TOTP from your authenticator: `, - )).trim(); + const code = (await rl.question(`Enter 6-digit TOTP from your authenticator: `)).trim(); if (!verifyTotp(code, totpSecret)) { console.error(`${c.red}✗ Invalid TOTP code.${c.reset}`); return false; @@ -146,9 +146,7 @@ async function cmdAuthStatus(): Promise { const status = valid ? `${c.green}active${c.reset} ${c.dim}(expires ${state.expiresAt})${c.reset}` : `${c.red}expired${c.reset} ${c.dim}(at ${state.expiresAt})${c.reset}`; - console.log( - `${status} scope=${state.scope} method=${state.method} granter=${state.granter}`, - ); + console.log(`${status} scope=${state.scope} method=${state.method} granter=${state.granter}`); return true; } diff --git a/src/commands/env.ts b/src/commands/env.ts index c7d73f50..c6f51818 100644 --- a/src/commands/env.ts +++ b/src/commands/env.ts @@ -23,7 +23,9 @@ async function cmdEnvList(): Promise { const envSections = config.env ?? {}; const envNames = ["dev", ...Object.keys(envSections).filter((k) => k !== "dev")]; - console.log(`${c.bold}${c.cyan}Environments${c.reset} ${c.dim}(active: ${activeEnv})${c.reset}\n`); + console.log( + `${c.bold}${c.cyan}Environments${c.reset} ${c.dim}(active: ${activeEnv})${c.reset}\n`, + ); for (const name of envNames) { const isActive = name === activeEnv; @@ -39,7 +41,8 @@ async function cmdEnvList(): Promise { const overrideKeys: string[] = []; if (override.tools) overrideKeys.push(`tools(${Object.keys(override.tools).join(",")})`); if (override.secrets) overrideKeys.push(`secrets.store=${override.secrets.store ?? "?"}`); - if (override.services) overrideKeys.push(`services(${Object.keys(override.services).join(",")})`); + if (override.services) + overrideKeys.push(`services(${Object.keys(override.services).join(",")})`); if (override.governance) overrideKeys.push("governance"); if (override.skills) overrideKeys.push("skills"); @@ -49,7 +52,9 @@ async function cmdEnvList(): Promise { if (Object.keys(envSections).length === 0) { console.log(`${c.dim}\nNo [env.*] sections defined in .kit.toml.${c.reset}`); - console.log(`${c.dim}Add [env.staging.*] or [env.production.*] to configure per-environment overrides.${c.reset}`); + console.log( + `${c.dim}Add [env.staging.*] or [env.production.*] to configure per-environment overrides.${c.reset}`, + ); } console.log(); @@ -60,9 +65,7 @@ async function cmdEnvSwitch(): Promise { // argv layout: [node, cli.js, "env", "switch", ""] const target = process.argv[4]; if (!target || !KNOWN_ENVS.includes(target as kitEnv)) { - console.error( - `${c.red}Usage: kit env switch <${KNOWN_ENVS.join("|")}>${c.reset}`, - ); + console.error(`${c.red}Usage: kit env switch <${KNOWN_ENVS.join("|")}>${c.reset}`); return false; } const env = target as kitEnv; @@ -114,8 +117,7 @@ async function cmdEnvCurrent(): Promise { console.log(`dev`); return true; } - const color = - state.env === "prod" ? c.red : state.env === "staging" ? c.yellow : c.green; + const color = state.env === "prod" ? c.red : state.env === "staging" ? c.yellow : c.green; console.log( `${color}${state.env}${c.reset} ${c.dim}(set ${state.switchedAt} by ${state.switchedBy})${c.reset}`, ); @@ -138,8 +140,10 @@ async function cmdEnvDiff(): Promise { const b = `.env.${target}`; const res = await diffEnvFiles(a, b); console.log(`${c.bold}${c.cyan}kit env diff${c.reset} ${c.dim}(${a} vs ${b})${c.reset}`); - for (const k of res.onlyInA) console.log(` ${c.yellow}- ${k}${c.reset} ${c.dim}only in ${a}${c.reset}`); - for (const k of res.onlyInB) console.log(` ${c.green}+ ${k}${c.reset} ${c.dim}only in ${b}${c.reset}`); + for (const k of res.onlyInA) + console.log(` ${c.yellow}- ${k}${c.reset} ${c.dim}only in ${a}${c.reset}`); + for (const k of res.onlyInB) + console.log(` ${c.green}+ ${k}${c.reset} ${c.dim}only in ${b}${c.reset}`); for (const ch of res.changed) console.log(` ${c.yellow}~ ${ch.key}${c.reset} ${c.dim}(${ch.aHash} → ${ch.bHash})${c.reset}`); const drift = res.onlyInA.length + res.onlyInB.length + res.changed.length; @@ -182,7 +186,7 @@ export async function cmdEnv(): Promise { if (!result.envLocalExists) { console.log( - `${c.yellow}⚠${c.reset} .env.local not found — run ${c.bold}kit secrets${c.reset} to generate it\n` + `${c.yellow}⚠${c.reset} .env.local not found — run ${c.bold}kit secrets${c.reset} to generate it\n`, ); } @@ -210,10 +214,10 @@ export async function cmdEnv(): Promise { if (!result.ok && !missingOnly) { console.log( - `${c.dim}Run ${c.reset}${c.bold}kit env --missing${c.reset}${c.dim} to see only unset keys${c.reset}` + `${c.dim}Run ${c.reset}${c.bold}kit env --missing${c.reset}${c.dim} to see only unset keys${c.reset}`, ); console.log( - `${c.dim}Run ${c.reset}${c.bold}kit secrets${c.reset}${c.dim} to generate .env.local${c.reset}\n` + `${c.dim}Run ${c.reset}${c.bold}kit secrets${c.reset}${c.dim} to generate .env.local${c.reset}\n`, ); } diff --git a/src/commands/hooks.ts b/src/commands/hooks.ts index a5106e0d..680304cd 100644 --- a/src/commands/hooks.ts +++ b/src/commands/hooks.ts @@ -7,24 +7,25 @@ import { isNonInteractive } from "../environment.js"; import { promptConfirm } from "../utils/prompt.js"; import { c } from "../utils/colors.js"; -const BUILTIN_HOOKS: Record = { - "secret-scan": { - hookName: "pre-commit", - commands: ["kit security scan-staged"], - description: "Block commits that stage known credential patterns (Stripe, AWS, JWT, etc).", - }, - "post-pull-audit": { - hookName: "post-merge", - commands: ["kit security verify-pull"], - description: "After git pull/merge, audit new deps, gitignore drops, and introduced secrets.", - }, - "context-check": { - hookName: "pre-push", - commands: ["kit context check"], - description: - "Block a push when the live CLI context (account/project) does not match .kit.toml [context]. Stops pushes to the wrong org/project.", - }, -}; +const BUILTIN_HOOKS: Record = + { + "secret-scan": { + hookName: "pre-commit", + commands: ["kit security scan-staged"], + description: "Block commits that stage known credential patterns (Stripe, AWS, JWT, etc).", + }, + "post-pull-audit": { + hookName: "post-merge", + commands: ["kit security verify-pull"], + description: "After git pull/merge, audit new deps, gitignore drops, and introduced secrets.", + }, + "context-check": { + hookName: "pre-push", + commands: ["kit context check"], + description: + "Block a push when the live CLI context (account/project) does not match .kit.toml [context]. Stops pushes to the wrong org/project.", + }, + }; export async function cmdHooks(): Promise { const subcommand = process.argv[3]; @@ -54,10 +55,7 @@ export async function cmdHooks(): Promise { let allOk = true; for (const r of results) { - const icon = - r.action === "failed" - ? `${c.red}✗${c.reset}` - : `${c.green}✓${c.reset}`; + const icon = r.action === "failed" ? `${c.red}✗${c.reset}` : `${c.green}✓${c.reset}`; const label = r.action === "installed" ? `${c.green}installed${c.reset}` @@ -79,24 +77,24 @@ export async function cmdHooks(): Promise { let allOk = true; for (const r of results) { - const icon = - !r.installed - ? `${c.red}✗${c.reset}` - : !r.upToDate - ? `${c.yellow}!${c.reset}` - : `${c.green}✓${c.reset}`; - const status = - !r.installed - ? `${c.red}not installed${c.reset}` - : !r.upToDate - ? `${c.yellow}outdated${c.reset}` - : `${c.green}up-to-date${c.reset}`; + const icon = !r.installed + ? `${c.red}✗${c.reset}` + : !r.upToDate + ? `${c.yellow}!${c.reset}` + : `${c.green}✓${c.reset}`; + const status = !r.installed + ? `${c.red}not installed${c.reset}` + : !r.upToDate + ? `${c.yellow}outdated${c.reset}` + : `${c.green}up-to-date${c.reset}`; console.log(` ${icon} ${r.hookName} ${status} ${c.dim}${r.detail}${c.reset}`); if (!r.installed || !r.upToDate) allOk = false; } if (!allOk) { - console.log(`\n${c.dim}Run ${c.reset}${c.bold}kit hooks install${c.reset}${c.dim} to install/update hooks${c.reset}`); + console.log( + `\n${c.dim}Run ${c.reset}${c.bold}kit hooks install${c.reset}${c.dim} to install/update hooks${c.reset}`, + ); } console.log(); @@ -152,9 +150,7 @@ async function cmdHooksAdd(): Promise { ); return true; } - console.log( - `${c.yellow}⚠ ${builtin.hookName} already exists at ${hookPath}.${c.reset}`, - ); + console.log(`${c.yellow}⚠ ${builtin.hookName} already exists at ${hookPath}.${c.reset}`); console.log( `${c.dim}kit will overwrite it with a managed version that calls back into kit.${c.reset}\n`, ); diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index 9bdbe60a..93f9ed08 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -18,12 +18,8 @@ export async function cmdMcp(): Promise { const config = await loadConfig(resolveConfigPath()).catch(() => null); const mcpConfig = config?.mcp; - const { - statusAll, - statusForMcp, - clearMcpToken, - storeStaticToken, - } = await import("../mcp-orchestrator.js"); + const { statusAll, statusForMcp, clearMcpToken, storeStaticToken } = + await import("../mcp-orchestrator.js"); if (!sub || sub === "list" || sub === "status") { console.log(`${c.bold}${c.cyan}kit mcp${c.reset}`); @@ -31,9 +27,7 @@ export async function cmdMcp(): Promise { const entries = await statusAll(mcpConfig); if (entries.length === 0) { console.log(`${c.dim}No [mcp.*] blocks declared in .kit.toml${c.reset}`); - console.log( - `${c.dim}Add e.g. [mcp.sentry] scopes = ["org:read", "project:write"]${c.reset}`, - ); + console.log(`${c.dim}Add e.g. [mcp.sentry] scopes = ["org:read", "project:write"]${c.reset}`); return true; } for (const e of entries) { @@ -43,9 +37,10 @@ export async function cmdMcp(): Promise { : e.status === "missing" || e.status === "expired" ? c.yellow : c.red; - const marker = - e.status === "ok" ? "✓" : e.status === "missing" ? "?" : "✗"; - const scopeStr = e.declared?.scopes ? ` ${c.dim}[${e.declared.scopes.join(", ")}]${c.reset}` : ""; + const marker = e.status === "ok" ? "✓" : e.status === "missing" ? "?" : "✗"; + const scopeStr = e.declared?.scopes + ? ` ${c.dim}[${e.declared.scopes.join(", ")}]${c.reset}` + : ""; console.log( ` ${color}${marker}${c.reset} ${e.name.padEnd(14)} ${color}${e.status}${c.reset}${scopeStr}`, ); @@ -76,9 +71,7 @@ export async function cmdMcp(): Promise { console.log( `${c.dim}Required scopes: ${(declared.scopes ?? ["(none declared)"]).join(", ")}${c.reset}\n`, ); - console.log( - `${c.yellow}OAuth-flow not yet automated for "${name}". Two options:${c.reset}`, - ); + console.log(`${c.yellow}OAuth-flow not yet automated for "${name}". Two options:${c.reset}`); console.log(` 1. Set env var: ${c.bold}kit mcp set-token ${name} --from-env ${c.reset}`); console.log(` 2. Paste token: ${c.bold}kit mcp set-token ${name} --paste${c.reset}`); return true; @@ -109,16 +102,16 @@ export async function cmdMcp(): Promise { rl.close(); } } else { - console.error( - `${c.red}Missing --from-env or --paste${c.reset}`, - ); + console.error(`${c.red}Missing --from-env or --paste${c.reset}`); return false; } const declared = mcpConfig?.[name]; await storeStaticToken(name, accessToken, { scopes: declared?.scopes, }); - console.log(`${c.green}✓${c.reset} Token stored for ${name} in ~/.kit/mcp-tokens.json (chmod 0o600)`); + console.log( + `${c.green}✓${c.reset} Token stored for ${name} in ~/.kit/mcp-tokens.json (chmod 0o600)`, + ); const status = await statusForMcp(name, declared ?? null); console.log(`${c.dim}Status: ${status.status}${c.reset}`); return true; diff --git a/src/commands/memory.ts b/src/commands/memory.ts index 8ddabd17..afaea4bb 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -18,7 +18,11 @@ import { getSharedPath, type SharedKind, } from "../memory/shared.js"; -import { userPromptSubmitReminder, runSessionEndIndex, sessionStartRecovery } from "../memory/hook.js"; +import { + userPromptSubmitReminder, + runSessionEndIndex, + sessionStartRecovery, +} from "../memory/hook.js"; import { installMemoryHooks, uninstallMemoryHooks, @@ -77,552 +81,582 @@ export async function cmdMemory(): Promise { if (handler) return handler(); console.error(`${c.red}Unknown memory subcommand: ${subcommand}${c.reset}`); - console.error( - "Use: kit memory index | search | stats | install | uninstall | pal", - ); + console.error("Use: kit memory index | search | stats | install | uninstall | pal"); return false; } async function memPal(): Promise { const jsonMode = hasFlag(process.argv, "--json"); - const action = - process.argv[4] && !process.argv[4].startsWith("--") ? process.argv[4] : "list"; - const db = openMemoryDb(); - try { - if (action === "list") { - const scope = hasFlag(process.argv, "--global") - ? undefined - : basename(getCurrentProjectRoot()); - const items = palList(db, { scope }); - if (jsonMode) { - console.log(JSON.stringify(items)); - return true; - } - if (!items.length) { - console.log(`${c.dim}no open action items${c.reset}`); - return true; - } - console.log(`${c.bold}${items.length}${c.reset} open action item(s):`); - for (const p of items) { - const tag = p.kind === "auto" ? ` ${c.dim}· auto${c.reset}` : ""; - const scope = p.scope ? ` ${c.dim}[${p.scope}]${c.reset}` : ""; - console.log(` ${c.bold}${p.id}${c.reset} ${p.title}${scope}${tag}`); - } + const action = process.argv[4] && !process.argv[4].startsWith("--") ? process.argv[4] : "list"; + const db = openMemoryDb(); + try { + if (action === "list") { + const scope = hasFlag(process.argv, "--global") + ? undefined + : basename(getCurrentProjectRoot()); + const items = palList(db, { scope }); + if (jsonMode) { + console.log(JSON.stringify(items)); return true; } - if (action === "add") { - const title = process.argv.slice(5).filter((a) => !a.startsWith("--")).join(" ").trim(); - if (!title) { - console.error( - `${c.red}usage: kit memory pal add [--verify-http <url> [--expect <code>]] [--verify-file <path>] [--scope=<s>]${c.reset}`, - ); - return false; - } - // Declarative verify only (no shell). http-status or file-exists. - const httpUrl = flagValue(process.argv, "--verify-http"); - const filePath = flagValue(process.argv, "--verify-file"); - let check: VerifyCheck | undefined; - if (httpUrl) { - const expect = Number(flagValue(process.argv, "--expect") ?? "200"); - check = { type: "http-status", url: httpUrl, expect: Number.isFinite(expect) ? expect : 200 }; - } else if (filePath) { - check = { type: "file-exists", path: filePath }; - } - const id = palAdd(db, { - title, - check, - scope: flagValue(process.argv, "--scope") ?? basename(getCurrentProjectRoot()), - }); - console.log(`${c.green}✓${c.reset} added ${c.bold}${id}${c.reset}`); + if (!items.length) { + console.log(`${c.dim}no open action items${c.reset}`); return true; } - if (action === "done") { - const id = process.argv[5]; - if (!id) { - console.error(`${c.red}usage: kit memory pal done <id>${c.reset}`); - return false; - } - console.log( - palDone(db, id) - ? `${c.green}✓${c.reset} closed ${id}` - : `${c.dim}${id} not found or already closed${c.reset}`, - ); - return true; + console.log(`${c.bold}${items.length}${c.reset} open action item(s):`); + for (const p of items) { + const tag = p.kind === "auto" ? ` ${c.dim}· auto${c.reset}` : ""; + const scope = p.scope ? ` ${c.dim}[${p.scope}]${c.reset}` : ""; + console.log(` ${c.bold}${p.id}${c.reset} ${p.title}${scope}${tag}`); } - if (action === "snooze") { - const id = process.argv[5]; - const days = Number(process.argv[6] ?? "7") || 7; - if (!id) { - console.error(`${c.red}usage: kit memory pal snooze <id> [days]${c.reset}`); - return false; - } - console.log( - palSnooze(db, id, days) - ? `${c.green}✓${c.reset} snoozed ${id} for ${days}d` - : `${c.dim}${id} not found${c.reset}`, + return true; + } + if (action === "add") { + const title = process.argv + .slice(5) + .filter((a) => !a.startsWith("--")) + .join(" ") + .trim(); + if (!title) { + console.error( + `${c.red}usage: kit memory pal add <title> [--verify-http <url> [--expect <code>]] [--verify-file <path>] [--scope=<s>]${c.reset}`, ); - return true; + return false; } - if (action === "verify") { - const r = await palAutoVerify(db); - console.log( - `${c.dim}checked ${r.checked} · closed ${r.closed.length} · reopened ${r.reopened.length}${c.reset}`, - ); - return true; + // Declarative verify only (no shell). http-status or file-exists. + const httpUrl = flagValue(process.argv, "--verify-http"); + const filePath = flagValue(process.argv, "--verify-file"); + let check: VerifyCheck | undefined; + if (httpUrl) { + const expect = Number(flagValue(process.argv, "--expect") ?? "200"); + check = { + type: "http-status", + url: httpUrl, + expect: Number.isFinite(expect) ? expect : 200, + }; + } else if (filePath) { + check = { type: "file-exists", path: filePath }; } - if (action === "import") { - const r = importLegacyLedger(db); - console.log(`${c.green}✓${c.reset} imported ${r.imported} item(s) from the legacy ledger`); - return true; + const id = palAdd(db, { + title, + check, + scope: flagValue(process.argv, "--scope") ?? basename(getCurrentProjectRoot()), + }); + console.log(`${c.green}✓${c.reset} added ${c.bold}${id}${c.reset}`); + return true; + } + if (action === "done") { + const id = process.argv[5]; + if (!id) { + console.error(`${c.red}usage: kit memory pal done <id>${c.reset}`); + return false; } - console.error(`${c.red}Unknown pal action: ${action}${c.reset}`); - console.error("Use: kit memory pal [list|add|done|snooze|verify|import]"); - return false; - } finally { - db.close(); + console.log( + palDone(db, id) + ? `${c.green}✓${c.reset} closed ${id}` + : `${c.dim}${id} not found or already closed${c.reset}`, + ); + return true; + } + if (action === "snooze") { + const id = process.argv[5]; + const days = Number(process.argv[6] ?? "7") || 7; + if (!id) { + console.error(`${c.red}usage: kit memory pal snooze <id> [days]${c.reset}`); + return false; + } + console.log( + palSnooze(db, id, days) + ? `${c.green}✓${c.reset} snoozed ${id} for ${days}d` + : `${c.dim}${id} not found${c.reset}`, + ); + return true; + } + if (action === "verify") { + const r = await palAutoVerify(db); + console.log( + `${c.dim}checked ${r.checked} · closed ${r.closed.length} · reopened ${r.reopened.length}${c.reset}`, + ); + return true; } + if (action === "import") { + const r = importLegacyLedger(db); + console.log(`${c.green}✓${c.reset} imported ${r.imported} item(s) from the legacy ledger`); + return true; + } + console.error(`${c.red}Unknown pal action: ${action}${c.reset}`); + console.error("Use: kit memory pal [list|add|done|snooze|verify|import]"); + return false; + } finally { + db.close(); + } } async function memHelp(): Promise<boolean> { - console.log("kit memory — local conversation memory (SQLite + FTS5)"); - console.log("\nUsage:"); - console.log(" kit memory index Index all agent transcripts (Claude Code, Codex, Gemini, Cursor, …) into the store"); - console.log(" kit memory search <query> Search memory (current project; --global for all)"); - console.log(" kit memory stats Show what the memory store contains"); - console.log(" kit memory merge <file> Merge another machine's memory.db into this one"); - console.log(" kit memory install Wire the 2 hooks into ~/.claude/settings.json"); - console.log(" kit memory uninstall Remove the hooks"); - console.log(" kit memory pal [list|add|done|snooze|verify|import] Pending action ledger"); - console.log(" kit memory save <name> Bookmark the current session as a named copilot"); - console.log(" kit memory threads List saved copilots (--global for all)"); - console.log(" kit memory resume <name|n> Print the resume command for a saved copilot"); - console.log(" kit memory forget <name> Remove a saved copilot"); - console.log(" kit memory scan Scan the store for stored secrets"); - console.log(" kit memory backup <file> Encrypted backup (set KIT_MEMORY_PASSPHRASE)"); - console.log(" kit memory restore <file> Restore an encrypted backup (new machine)"); - console.log(" kit memory share … Promote a curated entry to shared (team) memory"); - console.log(" kit memory areas List shared responsibility areas"); - console.log(" kit memory area <name> Show shared entries for one area"); - return true; + console.log("kit memory — local conversation memory (SQLite + FTS5)"); + console.log("\nUsage:"); + console.log( + " kit memory index Index all agent transcripts (Claude Code, Codex, Gemini, Cursor, …) into the store", + ); + console.log(" kit memory search <query> Search memory (current project; --global for all)"); + console.log(" kit memory stats Show what the memory store contains"); + console.log(" kit memory merge <file> Merge another machine's memory.db into this one"); + console.log(" kit memory install Wire the 2 hooks into ~/.claude/settings.json"); + console.log(" kit memory uninstall Remove the hooks"); + console.log(" kit memory pal [list|add|done|snooze|verify|import] Pending action ledger"); + console.log(" kit memory save <name> Bookmark the current session as a named copilot"); + console.log(" kit memory threads List saved copilots (--global for all)"); + console.log(" kit memory resume <name|n> Print the resume command for a saved copilot"); + console.log(" kit memory forget <name> Remove a saved copilot"); + console.log(" kit memory scan Scan the store for stored secrets"); + console.log(" kit memory backup <file> Encrypted backup (set KIT_MEMORY_PASSPHRASE)"); + console.log(" kit memory restore <file> Restore an encrypted backup (new machine)"); + console.log(" kit memory share … Promote a curated entry to shared (team) memory"); + console.log(" kit memory areas List shared responsibility areas"); + console.log(" kit memory area <name> Show shared entries for one area"); + return true; } async function memIndex(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const db = openMemoryDb(); - const t0 = Date.now(); - const byHarness = indexAllHarnesses(db); - const ms = Date.now() - t0; - db.close(); - if (jsonMode) { - console.log(JSON.stringify({ byHarness, ms })); - return true; - } - let messages = 0; - let toolUses = 0; - let files = 0; - let skipped = 0; - for (const r of Object.values(byHarness)) { - messages += r.messages; - toolUses += r.toolUses; - files += r.files; - skipped += r.filesSkipped; - } - console.log( - `${c.green}✓${c.reset} indexed ${c.bold}${messages}${c.reset} messages + ${toolUses} tool-uses from ${files} sessions${skipped ? `, ${skipped} unchanged` : ""} ${c.dim}(${ms}ms)${c.reset}`, - ); - for (const [harness, r] of Object.entries(byHarness)) { - if (r.files || r.messages) { - console.log( - ` ${c.dim}${harness}: ${r.messages} msg · ${r.files} sessions${r.filesSkipped ? ` · ${r.filesSkipped} unchanged` : ""}${c.reset}`, - ); - } - } + const db = openMemoryDb(); + const t0 = Date.now(); + const byHarness = indexAllHarnesses(db); + const ms = Date.now() - t0; + db.close(); + if (jsonMode) { + console.log(JSON.stringify({ byHarness, ms })); return true; -} - -async function memMerge(): Promise<boolean> { - const sourcePath = process.argv[4]; - if (!sourcePath) { - console.error(`${c.red}usage: kit memory merge <other-machine-memory.db>${c.reset}`); - return false; - } - const db = openMemoryDb(); - try { - const r = mergeDb(db, sourcePath); + } + let messages = 0; + let toolUses = 0; + let files = 0; + let skipped = 0; + for (const r of Object.values(byHarness)) { + messages += r.messages; + toolUses += r.toolUses; + files += r.files; + skipped += r.filesSkipped; + } + console.log( + `${c.green}✓${c.reset} indexed ${c.bold}${messages}${c.reset} messages + ${toolUses} tool-uses from ${files} sessions${skipped ? `, ${skipped} unchanged` : ""} ${c.dim}(${ms}ms)${c.reset}`, + ); + for (const [harness, r] of Object.entries(byHarness)) { + if (r.files || r.messages) { console.log( - `${c.green}✓${c.reset} merged ${c.bold}${r.messages}${c.reset} messages + ${r.toolUses} tool-uses · ${r.sessions} sessions · ${r.pending} pending · ${r.threads} copilots ${c.dim}from ${sourcePath}${c.reset}`, + ` ${c.dim}${harness}: ${r.messages} msg · ${r.files} sessions${r.filesSkipped ? ` · ${r.filesSkipped} unchanged` : ""}${c.reset}`, ); - } catch (err) { - db.close(); - console.error(`${c.red}${(err as Error).message}${c.reset}`); - return false; } + } + return true; +} + +async function memMerge(): Promise<boolean> { + const sourcePath = process.argv[4]; + if (!sourcePath) { + console.error(`${c.red}usage: kit memory merge <other-machine-memory.db>${c.reset}`); + return false; + } + const db = openMemoryDb(); + try { + const r = mergeDb(db, sourcePath); + console.log( + `${c.green}✓${c.reset} merged ${c.bold}${r.messages}${c.reset} messages + ${r.toolUses} tool-uses · ${r.sessions} sessions · ${r.pending} pending · ${r.threads} copilots ${c.dim}from ${sourcePath}${c.reset}`, + ); + } catch (err) { db.close(); - return true; + console.error(`${c.red}${(err as Error).message}${c.reset}`); + return false; + } + db.close(); + return true; } async function memStats(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const db = openMemoryDb(); - const s = getStats(db); - db.close(); - if (jsonMode) { - console.log(JSON.stringify(s)); - return true; - } - console.log(`${c.bold}kit memory${c.reset} ${c.dim}${s.dbPath}${c.reset}`); - console.log(` sessions ${s.sessions}`); - if (s.byHarness.length > 1) { - const breakdown = s.byHarness.map((h) => `${h.harness} ${h.sessions}`).join(", "); - console.log(` ${c.dim}${breakdown}${c.reset}`); - } - console.log(` messages ${s.messages}`); - console.log(` tool-uses ${s.toolUses}`); - console.log(` pending ${s.pendingOpen} ${c.dim}(open action items)${c.reset}`); - console.log(` size ${Math.round(s.sizeBytes / 1024)} KB`); + const db = openMemoryDb(); + const s = getStats(db); + db.close(); + if (jsonMode) { + console.log(JSON.stringify(s)); return true; + } + console.log(`${c.bold}kit memory${c.reset} ${c.dim}${s.dbPath}${c.reset}`); + console.log(` sessions ${s.sessions}`); + if (s.byHarness.length > 1) { + const breakdown = s.byHarness.map((h) => `${h.harness} ${h.sessions}`).join(", "); + console.log(` ${c.dim}${breakdown}${c.reset}`); + } + console.log(` messages ${s.messages}`); + console.log(` tool-uses ${s.toolUses}`); + console.log(` pending ${s.pendingOpen} ${c.dim}(open action items)${c.reset}`); + console.log(` size ${Math.round(s.sizeBytes / 1024)} KB`); + return true; } async function memSuggest(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - // BYO-LLM: kit emits a prompt; it never calls a model. Pipe to your own: - // kit memory suggest | <your-llm> - const limitArg = flagValue(process.argv, "--limit"); - const limit = limitArg ? Math.max(1, parseInt(limitArg, 10) || 30) : undefined; - const db = openMemoryDb(); - const out = buildSuggestPrompt(db, { limit }); - db.close(); - if (jsonMode) { - console.log(JSON.stringify(out)); - return true; - } - console.log(out.prompt); + // BYO-LLM: kit emits a prompt; it never calls a model. Pipe to your own: + // kit memory suggest | <your-llm> + const limitArg = flagValue(process.argv, "--limit"); + const limit = limitArg ? Math.max(1, parseInt(limitArg, 10) || 30) : undefined; + const db = openMemoryDb(); + const out = buildSuggestPrompt(db, { limit }); + db.close(); + if (jsonMode) { + console.log(JSON.stringify(out)); return true; + } + console.log(out.prompt); + return true; } async function memSearch(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const terms = process.argv.slice(4).filter((a) => !a.startsWith("--")); - const query = terms.join(" ").trim(); - if (!query) { - console.error( - `${c.red}usage: kit memory search <query> [--global] [--project=<path>] [--limit=N]${c.reset}`, - ); - return false; - } - const limit = Number(flagValue(process.argv, "--limit") ?? "20") || 20; - const projectPath = hasFlag(process.argv, "--global") - ? undefined - : (flagValue(process.argv, "--project") ?? getCurrentProjectRoot()); - const db = openMemoryDb(); - const hits = searchMessages(db, query, { limit, projectPath }); - db.close(); - if (jsonMode) { - console.log(JSON.stringify(hits)); - return true; - } - const scope = projectPath ? `${c.dim}in ${projectPath}${c.reset}` : `${c.dim}(global)${c.reset}`; - if (!hits.length) { - console.log(`${c.dim}no matches for "${query}" ${projectPath ?? "(global)"}${c.reset}`); - return true; - } - console.log(`${c.bold}${hits.length}${c.reset} match(es) ${scope}`); - for (const h of hits) { - const snippet = (h.content ?? "").replace(/\s+/g, " ").slice(0, 120); - console.log( - ` ${c.dim}${h.timestamp ?? "?"}${c.reset} ${c.bold}${h.role ?? h.uuid ?? ""}${c.reset} ${snippet}`, - ); - } + const terms = process.argv.slice(4).filter((a) => !a.startsWith("--")); + const query = terms.join(" ").trim(); + if (!query) { + console.error( + `${c.red}usage: kit memory search <query> [--global] [--project=<path>] [--limit=N]${c.reset}`, + ); + return false; + } + const limit = Number(flagValue(process.argv, "--limit") ?? "20") || 20; + const projectPath = hasFlag(process.argv, "--global") + ? undefined + : (flagValue(process.argv, "--project") ?? getCurrentProjectRoot()); + const db = openMemoryDb(); + const hits = searchMessages(db, query, { limit, projectPath }); + db.close(); + if (jsonMode) { + console.log(JSON.stringify(hits)); + return true; + } + const scope = projectPath ? `${c.dim}in ${projectPath}${c.reset}` : `${c.dim}(global)${c.reset}`; + if (!hits.length) { + console.log(`${c.dim}no matches for "${query}" ${projectPath ?? "(global)"}${c.reset}`); return true; + } + console.log(`${c.bold}${hits.length}${c.reset} match(es) ${scope}`); + for (const h of hits) { + const snippet = (h.content ?? "").replace(/\s+/g, " ").slice(0, 120); + console.log( + ` ${c.dim}${h.timestamp ?? "?"}${c.reset} ${c.bold}${h.role ?? h.uuid ?? ""}${c.reset} ${snippet}`, + ); + } + return true; } async function memHook(): Promise<boolean> { - // Internal: invoked by Claude Code hooks. Fail-open — never block. - const event = process.argv[4]; - if (event === "user-prompt-submit") { - const text = userPromptSubmitReminder(); - if (text) console.log(text); - return true; - } - if (event === "session-end") { - runSessionEndIndex(); - return true; - } - if (event === "session-start") { - const text = sessionStartRecovery(); - if (text) console.log(text); - return true; - } - console.error(`${c.red}Unknown hook event: ${event ?? "(none)"}${c.reset}`); - return false; + // Internal: invoked by Claude Code hooks. Fail-open — never block. + const event = process.argv[4]; + if (event === "user-prompt-submit") { + const text = userPromptSubmitReminder(); + if (text) console.log(text); + return true; + } + if (event === "session-end") { + runSessionEndIndex(); + return true; + } + if (event === "session-start") { + const text = sessionStartRecovery(); + if (text) console.log(text); + return true; + } + console.error(`${c.red}Unknown hook event: ${event ?? "(none)"}${c.reset}`); + return false; } async function memInstall(): Promise<boolean> { - const { added, alreadyPresent, resolved } = installMemoryHooks(); - for (const e of added) console.log(`${c.green}✓${c.reset} installed ${e} hook`); - for (const e of alreadyPresent) console.log(`${c.dim}• ${e} hook already present${c.reset}`); - console.log(`${c.dim}settings: ${getClaudeSettingsPath()}${c.reset}`); - if (!resolved) { - console.log( - `${c.yellow}!${c.reset} Could not resolve kit's absolute path — hooks use a bare \`kit\`, ` + - `which only fires if kit is on the hook shell's PATH (often not the case). ` + - `Reinstall kit globally and re-run, or edit the commands in ${getClaudeSettingsPath()} to an absolute path.`, - ); - } - return true; + const { added, alreadyPresent, resolved } = installMemoryHooks(); + for (const e of added) console.log(`${c.green}✓${c.reset} installed ${e} hook`); + for (const e of alreadyPresent) console.log(`${c.dim}• ${e} hook already present${c.reset}`); + console.log(`${c.dim}settings: ${getClaudeSettingsPath()}${c.reset}`); + if (!resolved) { + console.log( + `${c.yellow}!${c.reset} Could not resolve kit's absolute path — hooks use a bare \`kit\`, ` + + `which only fires if kit is on the hook shell's PATH (often not the case). ` + + `Reinstall kit globally and re-run, or edit the commands in ${getClaudeSettingsPath()} to an absolute path.`, + ); + } + return true; } async function memUninstall(): Promise<boolean> { - const { removed } = uninstallMemoryHooks(); - if (removed.length) { - for (const e of removed) console.log(`${c.green}✓${c.reset} removed ${e} hook`); - } else { - console.log(`${c.dim}no kit memory hooks were installed${c.reset}`); - } - return true; + const { removed } = uninstallMemoryHooks(); + if (removed.length) { + for (const e of removed) console.log(`${c.green}✓${c.reset} removed ${e} hook`); + } else { + console.log(`${c.dim}no kit memory hooks were installed${c.reset}`); + } + return true; } async function memShare(): Promise<boolean> { - const area = flagValue(process.argv, "--area"); - const title = flagValue(process.argv, "--title"); - const kind = (flagValue(process.argv, "--kind") ?? "note") as SharedKind; - const body = flagValue(process.argv, "--body") ?? ""; - const ref = flagValue(process.argv, "--ref"); - if (!area || !title) { - console.error( - `${c.red}usage: kit memory share --area <a> --title <t> [--kind decision|convention|how-built|status|security|note] [--body <b>] [--ref <r>]${c.reset}`, - ); - return false; - } - const root = getCurrentProjectRoot(); - try { - const e = shareEntry( - root, - { area, kind, title, body, refs: ref ? [ref] : [] }, - new Date().toISOString(), - ); - console.log( - `${c.green}✓${c.reset} shared ${c.bold}${e.id}${c.reset} to area ${c.bold}${area}${c.reset} ${c.dim}(${getSharedPath(root)})${c.reset}`, - ); - console.log( - `${c.dim}commit .kit/shared/memory.jsonl + open a PR — shared memory is reviewed like code${c.reset}`, - ); - } catch (err) { - console.error(`${c.red}${(err as Error).message}${c.reset}`); - return false; - } - return true; + const area = flagValue(process.argv, "--area"); + const title = flagValue(process.argv, "--title"); + const kind = (flagValue(process.argv, "--kind") ?? "note") as SharedKind; + const body = flagValue(process.argv, "--body") ?? ""; + const ref = flagValue(process.argv, "--ref"); + if (!area || !title) { + console.error( + `${c.red}usage: kit memory share --area <a> --title <t> [--kind decision|convention|how-built|status|security|note] [--body <b>] [--ref <r>]${c.reset}`, + ); + return false; + } + const root = getCurrentProjectRoot(); + try { + const e = shareEntry( + root, + { area, kind, title, body, refs: ref ? [ref] : [] }, + new Date().toISOString(), + ); + console.log( + `${c.green}✓${c.reset} shared ${c.bold}${e.id}${c.reset} to area ${c.bold}${area}${c.reset} ${c.dim}(${getSharedPath(root)})${c.reset}`, + ); + console.log( + `${c.dim}commit .kit/shared/memory.jsonl + open a PR — shared memory is reviewed like code${c.reset}`, + ); + } catch (err) { + console.error(`${c.red}${(err as Error).message}${c.reset}`); + return false; + } + return true; } async function memAreas(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const areas = listAreas(getCurrentProjectRoot()); - if (jsonMode) { - console.log(JSON.stringify(areas)); - return true; - } - if (!areas.length) { - console.log(`${c.dim}no shared areas yet — add one with kit memory share${c.reset}`); - return true; - } - console.log(`${c.bold}${areas.length}${c.reset} responsibility area(s):`); - for (const a of areas) { - console.log(` ${c.bold}${a.area}${c.reset} ${c.dim}· ${a.count} entr${a.count === 1 ? "y" : "ies"}${c.reset}`); - } + const areas = listAreas(getCurrentProjectRoot()); + if (jsonMode) { + console.log(JSON.stringify(areas)); + return true; + } + if (!areas.length) { + console.log(`${c.dim}no shared areas yet — add one with kit memory share${c.reset}`); return true; + } + console.log(`${c.bold}${areas.length}${c.reset} responsibility area(s):`); + for (const a of areas) { + console.log( + ` ${c.bold}${a.area}${c.reset} ${c.dim}· ${a.count} entr${a.count === 1 ? "y" : "ies"}${c.reset}`, + ); + } + return true; } async function memArea(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const name = process.argv[4]; - if (!name) { - console.error(`${c.red}usage: kit memory area <name>${c.reset}`); - return false; - } - const entries = queryArea(getCurrentProjectRoot(), name); - if (jsonMode) { - console.log(JSON.stringify(entries)); - return true; - } - if (!entries.length) { - console.log(`${c.dim}no shared memory for area '${name}'${c.reset}`); - return true; - } - console.log(`${c.bold}${name}${c.reset} ${c.dim}· ${entries.length} entr${entries.length === 1 ? "y" : "ies"}${c.reset}`); - for (const e of entries) { - const prov = `${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}`; - console.log(` ${c.bold}[${e.kind}]${c.reset} ${e.title} ${c.dim}— ${prov}${c.reset}`); - if (e.body) console.log(` ${e.body}`); - if (e.refs.length) console.log(` ${c.dim}refs: ${e.refs.join(", ")}${c.reset}`); - } + const name = process.argv[4]; + if (!name) { + console.error(`${c.red}usage: kit memory area <name>${c.reset}`); + return false; + } + const entries = queryArea(getCurrentProjectRoot(), name); + if (jsonMode) { + console.log(JSON.stringify(entries)); return true; + } + if (!entries.length) { + console.log(`${c.dim}no shared memory for area '${name}'${c.reset}`); + return true; + } + console.log( + `${c.bold}${name}${c.reset} ${c.dim}· ${entries.length} entr${entries.length === 1 ? "y" : "ies"}${c.reset}`, + ); + for (const e of entries) { + const prov = `${e.author}${e.source_ref ? ` @${e.source_ref}` : ""}`; + console.log(` ${c.bold}[${e.kind}]${c.reset} ${e.title} ${c.dim}— ${prov}${c.reset}`); + if (e.body) console.log(` ${e.body}`); + if (e.refs.length) console.log(` ${c.dim}refs: ${e.refs.join(", ")}${c.reset}`); + } + return true; } async function memScan(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const db = openMemoryDb(); - const findings = scanDbForSecrets(db); - db.close(); - if (jsonMode) { - console.log(JSON.stringify(findings)); - return !findings.some((f) => f.confidence === "high"); - } - if (!findings.length) { - console.log(`${c.green}✓${c.reset} no stored secrets found in the memory store`); - return true; + const db = openMemoryDb(); + const findings = scanDbForSecrets(db); + db.close(); + if (jsonMode) { + console.log(JSON.stringify(findings)); + return !findings.some((f) => f.confidence === "high"); + } + if (!findings.length) { + console.log(`${c.green}✓${c.reset} no stored secrets found in the memory store`); + return true; + } + const high = findings.filter((f) => f.confidence === "high"); + const heuristic = findings.filter((f) => f.confidence === "heuristic"); + const times = (n: number) => (n > 1 ? ` ×${n}` : ""); + if (high.length) { + console.log(`${c.red}⚠ ${high.length} high-confidence secret(s):${c.reset}`); + for (const f of high) { + const proj = f.projects.length + ? `${c.bold}[${f.projects.join(", ")}]${c.reset}${c.dim} · ` + : ""; + console.log( + ` ${c.bold}${f.label}${c.reset} ${c.dim}${f.preview}${times(f.count)} · ${proj}${f.sample}${c.reset}`, + ); } - const high = findings.filter((f) => f.confidence === "high"); - const heuristic = findings.filter((f) => f.confidence === "heuristic"); - const times = (n: number) => (n > 1 ? ` ×${n}` : ""); - if (high.length) { - console.log(`${c.red}⚠ ${high.length} high-confidence secret(s):${c.reset}`); - for (const f of high) { - const proj = f.projects.length ? `${c.bold}[${f.projects.join(", ")}]${c.reset}${c.dim} · ` : ""; - console.log( - ` ${c.bold}${f.label}${c.reset} ${c.dim}${f.preview}${times(f.count)} · ${proj}${f.sample}${c.reset}`, - ); + } else { + console.log(`${c.green}✓${c.reset} no high-confidence secrets`); + } + if (heuristic.length) { + const showAll = hasFlag(process.argv, "--all"); + if (showAll) { + console.log( + `${c.dim}${heuristic.length} heuristic match(es) (KEY=value patterns — usually env vars / paths):${c.reset}`, + ); + for (const f of heuristic) { + console.log(` ${c.dim}${f.label} ${f.preview}${times(f.count)} · ${f.sample}${c.reset}`); } } else { - console.log(`${c.green}✓${c.reset} no high-confidence secrets`); - } - if (heuristic.length) { - const showAll = hasFlag(process.argv, "--all"); - if (showAll) { - console.log( - `${c.dim}${heuristic.length} heuristic match(es) (KEY=value patterns — usually env vars / paths):${c.reset}`, - ); - for (const f of heuristic) { - console.log(` ${c.dim}${f.label} ${f.preview}${times(f.count)} · ${f.sample}${c.reset}`); - } - } else { - console.log( - `${c.dim}+ ${heuristic.length} heuristic match(es) (likely env vars / paths) — run with --all to see${c.reset}`, - ); - } + console.log( + `${c.dim}+ ${heuristic.length} heuristic match(es) (likely env vars / paths) — run with --all to see${c.reset}`, + ); } - return high.length === 0; // exit non-zero only on high-confidence findings + } + return high.length === 0; // exit non-zero only on high-confidence findings } async function memBackup(): Promise<boolean> { - const out = process.argv[4]; - const pass = process.env.KIT_MEMORY_PASSPHRASE ?? flagValue(process.argv, "--passphrase"); - if (!out) { - console.error(`${c.red}usage: kit memory backup <file> (set KIT_MEMORY_PASSPHRASE)${c.reset}`); - return false; - } - if (!pass) { - console.error( - `${c.red}set KIT_MEMORY_PASSPHRASE (or --passphrase) — the key is never stored${c.reset}`, - ); - return false; - } - try { - backupEncrypted(pass, getMemoryDbPath(), out); - } catch (err) { - console.error(`${c.red}${(err as Error).message}${c.reset}`); - return false; - } - console.log(`${c.green}✓${c.reset} encrypted backup → ${out} ${c.dim}(AES-256-GCM · scrypt)${c.reset}`); - return true; + const out = process.argv[4]; + const pass = process.env.KIT_MEMORY_PASSPHRASE ?? flagValue(process.argv, "--passphrase"); + if (!out) { + console.error(`${c.red}usage: kit memory backup <file> (set KIT_MEMORY_PASSPHRASE)${c.reset}`); + return false; + } + if (!pass) { + console.error( + `${c.red}set KIT_MEMORY_PASSPHRASE (or --passphrase) — the key is never stored${c.reset}`, + ); + return false; + } + try { + backupEncrypted(pass, getMemoryDbPath(), out); + } catch (err) { + console.error(`${c.red}${(err as Error).message}${c.reset}`); + return false; + } + console.log( + `${c.green}✓${c.reset} encrypted backup → ${out} ${c.dim}(AES-256-GCM · scrypt)${c.reset}`, + ); + return true; } async function memRestore(): Promise<boolean> { - const inFile = process.argv[4]; - const pass = process.env.KIT_MEMORY_PASSPHRASE ?? flagValue(process.argv, "--passphrase"); - if (!inFile) { - console.error(`${c.red}usage: kit memory restore <file> [--to <path>] [--force]${c.reset}`); - return false; - } - if (!pass) { - console.error(`${c.red}set KIT_MEMORY_PASSPHRASE (or --passphrase)${c.reset}`); - return false; - } - const dest = flagValue(process.argv, "--to") ?? getMemoryDbPath(); - if (existsSync(dest) && !hasFlag(process.argv, "--force")) { - console.error(`${c.red}${dest} exists — pass --force to overwrite${c.reset}`); - return false; - } - try { - restoreEncrypted(pass, inFile, dest); - } catch { - console.error(`${c.red}restore failed — wrong passphrase or corrupt backup${c.reset}`); - return false; - } - console.log(`${c.green}✓${c.reset} restored → ${dest}`); - return true; + const inFile = process.argv[4]; + const pass = process.env.KIT_MEMORY_PASSPHRASE ?? flagValue(process.argv, "--passphrase"); + if (!inFile) { + console.error(`${c.red}usage: kit memory restore <file> [--to <path>] [--force]${c.reset}`); + return false; + } + if (!pass) { + console.error(`${c.red}set KIT_MEMORY_PASSPHRASE (or --passphrase)${c.reset}`); + return false; + } + const dest = flagValue(process.argv, "--to") ?? getMemoryDbPath(); + if (existsSync(dest) && !hasFlag(process.argv, "--force")) { + console.error(`${c.red}${dest} exists — pass --force to overwrite${c.reset}`); + return false; + } + try { + restoreEncrypted(pass, inFile, dest); + } catch { + console.error(`${c.red}restore failed — wrong passphrase or corrupt backup${c.reset}`); + return false; + } + console.log(`${c.green}✓${c.reset} restored → ${dest}`); + return true; } async function memSave(): Promise<boolean> { - const name = process.argv.slice(4).filter((a) => !a.startsWith("--")).join(" ").trim(); - if (!name) { - console.error(`${c.red}usage: kit memory save <name> [--session=<id>]${c.reset}`); - return false; - } - const root = getCurrentProjectRoot(); - const db = openMemoryDb(); - const sessionId = flagValue(process.argv, "--session") ?? latestSessionId(db, { projectPath: root }); - if (!sessionId) { - db.close(); - console.error(`${c.red}no session found for ${root} — index first or pass --session=<id>${c.reset}`); - return false; - } - saveThread(db, { name, sessionId, projectPath: root }); + const name = process.argv + .slice(4) + .filter((a) => !a.startsWith("--")) + .join(" ") + .trim(); + if (!name) { + console.error(`${c.red}usage: kit memory save <name> [--session=<id>]${c.reset}`); + return false; + } + const root = getCurrentProjectRoot(); + const db = openMemoryDb(); + const sessionId = + flagValue(process.argv, "--session") ?? latestSessionId(db, { projectPath: root }); + if (!sessionId) { db.close(); - console.log(`${c.green}✓${c.reset} saved copilot ${c.bold}${name}${c.reset} ${c.dim}→ ${sessionId}${c.reset}`); - return true; + console.error( + `${c.red}no session found for ${root} — index first or pass --session=<id>${c.reset}`, + ); + return false; + } + saveThread(db, { name, sessionId, projectPath: root }); + db.close(); + console.log( + `${c.green}✓${c.reset} saved copilot ${c.bold}${name}${c.reset} ${c.dim}→ ${sessionId}${c.reset}`, + ); + return true; } async function memThreads(): Promise<boolean> { const jsonMode = hasFlag(process.argv, "--json"); - const projectPath = hasFlag(process.argv, "--global") ? undefined : getCurrentProjectRoot(); - const db = openMemoryDb(); - const list = listThreads(db, { projectPath }); - db.close(); - if (jsonMode) { - console.log(JSON.stringify(list)); - return true; - } - if (!list.length) { - console.log(`${c.dim}no saved copilots${projectPath ? ` in ${projectPath}` : ""}${c.reset}`); - return true; - } - const scope = projectPath ? `${c.dim}in ${projectPath}${c.reset}` : `${c.dim}(global)${c.reset}`; - console.log(`${c.bold}${list.length}${c.reset} saved copilot(s) ${scope}:`); - list.forEach((t, i) => { - console.log(` ${c.bold}${i + 1}${c.reset}. ${t.name} ${c.dim}${t.session_id}${c.reset}`); - }); - console.log(`${c.dim}resume with: kit memory resume <name|number>${c.reset}`); + const projectPath = hasFlag(process.argv, "--global") ? undefined : getCurrentProjectRoot(); + const db = openMemoryDb(); + const list = listThreads(db, { projectPath }); + db.close(); + if (jsonMode) { + console.log(JSON.stringify(list)); + return true; + } + if (!list.length) { + console.log(`${c.dim}no saved copilots${projectPath ? ` in ${projectPath}` : ""}${c.reset}`); return true; + } + const scope = projectPath ? `${c.dim}in ${projectPath}${c.reset}` : `${c.dim}(global)${c.reset}`; + console.log(`${c.bold}${list.length}${c.reset} saved copilot(s) ${scope}:`); + list.forEach((t, i) => { + console.log(` ${c.bold}${i + 1}${c.reset}. ${t.name} ${c.dim}${t.session_id}${c.reset}`); + }); + console.log(`${c.dim}resume with: kit memory resume <name|number>${c.reset}`); + return true; } async function memResume(): Promise<boolean> { - const ref = process.argv[4]; - if (!ref) { - console.error(`${c.red}usage: kit memory resume <name|number>${c.reset}`); - return false; - } - const projectPath = hasFlag(process.argv, "--global") ? undefined : getCurrentProjectRoot(); - const db = openMemoryDb(); - const t = resolveThread(db, ref, { projectPath }); - db.close(); - if (!t) { - console.error(`${c.red}no saved copilot '${ref}'${c.reset}`); - return false; - } - console.log(`${c.bold}${t.name}${c.reset} — run:`); - console.log(` claude --resume ${t.session_id}`); - return true; + const ref = process.argv[4]; + if (!ref) { + console.error(`${c.red}usage: kit memory resume <name|number>${c.reset}`); + return false; + } + const projectPath = hasFlag(process.argv, "--global") ? undefined : getCurrentProjectRoot(); + const db = openMemoryDb(); + const t = resolveThread(db, ref, { projectPath }); + db.close(); + if (!t) { + console.error(`${c.red}no saved copilot '${ref}'${c.reset}`); + return false; + } + console.log(`${c.bold}${t.name}${c.reset} — run:`); + console.log(` claude --resume ${t.session_id}`); + return true; } async function memForget(): Promise<boolean> { - const name = process.argv.slice(4).filter((a) => !a.startsWith("--")).join(" ").trim(); - if (!name) { - console.error(`${c.red}usage: kit memory forget <name>${c.reset}`); - return false; - } - const db = openMemoryDb(); - const ok = removeThread(db, name); - db.close(); - console.log(ok ? `${c.green}✓${c.reset} forgot ${name}` : `${c.dim}no copilot '${name}'${c.reset}`); - return true; + const name = process.argv + .slice(4) + .filter((a) => !a.startsWith("--")) + .join(" ") + .trim(); + if (!name) { + console.error(`${c.red}usage: kit memory forget <name>${c.reset}`); + return false; + } + const db = openMemoryDb(); + const ok = removeThread(db, name); + db.close(); + console.log( + ok ? `${c.green}✓${c.reset} forgot ${name}` : `${c.dim}no copilot '${name}'${c.reset}`, + ); + return true; } diff --git a/src/completions.test.ts b/src/completions.test.ts index 7eafc0b6..4f8ea88a 100644 --- a/src/completions.test.ts +++ b/src/completions.test.ts @@ -1,6 +1,11 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { generateBashCompletion, generateZshCompletion, generateFishCompletion, generateCompletions } from "./completions.js"; +import { + generateBashCompletion, + generateZshCompletion, + generateFishCompletion, + generateCompletions, +} from "./completions.js"; describe("generateBashCompletion", () => { it("outputs non-empty bash script", () => { diff --git a/src/completions.ts b/src/completions.ts index 93ce6738..de6b2236 100644 --- a/src/completions.ts +++ b/src/completions.ts @@ -4,18 +4,51 @@ */ const COMMANDS = [ - "check", "init", "upgrade", "install", "login", "secrets", "setup", - "fix", "escalate", "governance", "skills", "hooks", "add", "audit", - "doctor", "env", "ci", "mcp", "whoami", "version", "create-plugin", - "completions", "help", + "check", + "init", + "upgrade", + "install", + "login", + "secrets", + "setup", + "fix", + "escalate", + "governance", + "skills", + "hooks", + "add", + "audit", + "doctor", + "env", + "ci", + "mcp", + "whoami", + "version", + "create-plugin", + "completions", + "help", ]; const ADAPTERS = [ - "stripe/payments", "supabase/db", "vercel/hosting", "expo/eas", - "searxng/instance", "neon/db", "clerk/auth", "upstash/redis", - "cloudflare/r2", "resend/email", "planetscale/db", "loops/email", - "liveblocks/realtime", "trigger/background", "inngest/background", - "flagsmith/flags", "sentry/monitoring", "tinybird/analytics", "posthog/analytics", + "stripe/payments", + "supabase/db", + "vercel/hosting", + "expo/eas", + "searxng/instance", + "neon/db", + "clerk/auth", + "upstash/redis", + "cloudflare/r2", + "resend/email", + "planetscale/db", + "loops/email", + "liveblocks/realtime", + "trigger/background", + "inngest/background", + "flagsmith/flags", + "sentry/monitoring", + "tinybird/analytics", + "posthog/analytics", ]; const CI_FORMATS = ["github", "gitlab", "json", "text"]; @@ -177,11 +210,11 @@ _kit export function generateFishCompletion(): string { const cmdCompletions = COMMANDS.map( - (cmd) => `complete -c kit -n "__fish_use_subcommand" -a "${cmd}" -d "${getCommandDesc(cmd)}"` + (cmd) => `complete -c kit -n "__fish_use_subcommand" -a "${cmd}" -d "${getCommandDesc(cmd)}"`, ).join("\n"); const adapterCompletions = ADAPTERS.map( - (a) => `complete -c kit -n "__fish_seen_subcommand_from add" -a "${a}"` + (a) => `complete -c kit -n "__fish_seen_subcommand_from add" -a "${a}"`, ).join("\n"); return `# kit fish completion @@ -257,9 +290,13 @@ function getCommandDesc(cmd: string): string { export function generateCompletions(shell: string): string | null { switch (shell) { - case "bash": return generateBashCompletion(); - case "zsh": return generateZshCompletion(); - case "fish": return generateFishCompletion(); - default: return null; + case "bash": + return generateBashCompletion(); + case "zsh": + return generateZshCompletion(); + case "fish": + return generateFishCompletion(); + default: + return null; } } diff --git a/src/config.test.ts b/src/config.test.ts index 1373b5bd..1e8a7932 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -19,7 +19,7 @@ pnpm = "latest" login = "gh auth login" check = "gh auth status" `, - "utf-8" + "utf-8", ); try { @@ -88,7 +88,7 @@ enabled = true check_interval = 600 revocation_endpoint = "https://api.example.com/agents/{agent_id}/status" `, - "utf-8" + "utf-8", ); try { @@ -127,9 +127,7 @@ revocation_endpoint = "https://api.example.com/agents/{agent_id}/status" assert.ok(config.governance.approval); assert.ok(Array.isArray(config.governance.approval.destructive_operations)); assert.equal(config.governance.approval.destructive_operations?.length, 3); - assert.ok( - config.governance.approval.destructive_operations?.includes("delete") - ); + assert.ok(config.governance.approval.destructive_operations?.includes("delete")); assert.equal(config.governance.approval.production_writes, true); assert.equal(config.governance.approval.secret_rotations, false); assert.equal(config.governance.approval.approval_timeout, 1800); @@ -147,7 +145,7 @@ revocation_endpoint = "https://api.example.com/agents/{agent_id}/status" assert.equal(config.governance.revocation.check_interval, 600); assert.equal( config.governance.revocation.revocation_endpoint, - "https://api.example.com/agents/{agent_id}/status" + "https://api.example.com/agents/{agent_id}/status", ); } finally { await unlink(tmpFile); @@ -162,7 +160,7 @@ revocation_endpoint = "https://api.example.com/agents/{agent_id}/status" [governance] enabled = true `, - "utf-8" + "utf-8", ); try { @@ -185,7 +183,7 @@ enabled = true [tools] node = "22" `, - "utf-8" + "utf-8", ); try { @@ -203,10 +201,13 @@ node = "22" await assert.rejects( () => loadConfig(tmpFile), (err: Error) => { - assert.ok(err.message.includes("Invalid .kit.toml"), `expected 'Invalid .kit.toml' in: ${err.message}`); + assert.ok( + err.message.includes("Invalid .kit.toml"), + `expected 'Invalid .kit.toml' in: ${err.message}`, + ); assert.ok(err.message.includes("tools.node"), `expected 'tools.node' in: ${err.message}`); return true; - } + }, ); } finally { await unlink(tmpFile); @@ -218,15 +219,18 @@ node = "22" await writeFile( tmpFile, `[secrets.keys]\nMY_KEY = { source = "nonexistent-store", ref = "x" }\n`, - "utf-8" + "utf-8", ); try { await assert.rejects( () => loadConfig(tmpFile), (err: Error) => { - assert.ok(err.message.includes("Invalid .kit.toml"), `expected 'Invalid .kit.toml' in: ${err.message}`); + assert.ok( + err.message.includes("Invalid .kit.toml"), + `expected 'Invalid .kit.toml' in: ${err.message}`, + ); return true; - } + }, ); } finally { await unlink(tmpFile); @@ -235,20 +239,18 @@ node = "22" it("succeeds but warns when an unknown top-level section is present", async () => { const tmpFile = join(tmpdir(), `.kit-test-${process.pid}-val3.toml`); - await writeFile( - tmpFile, - `[tolls]\nnode = "22"\n`, - "utf-8" - ); + await writeFile(tmpFile, `[tolls]\nnode = "22"\n`, "utf-8"); const warnMessages: string[] = []; const originalWarn = console.warn; - console.warn = (...args: unknown[]) => { warnMessages.push(String(args[0])); }; + console.warn = (...args: unknown[]) => { + warnMessages.push(String(args[0])); + }; try { const config = await loadConfig(tmpFile); assert.ok(config, "config should be returned without throwing"); assert.ok( warnMessages.some((m) => m.includes("tolls")), - `expected warning about 'tolls', got: ${JSON.stringify(warnMessages)}` + `expected warning about 'tolls', got: ${JSON.stringify(warnMessages)}`, ); } finally { console.warn = originalWarn; @@ -281,7 +283,7 @@ read = true write = false delete = false `, - "utf-8" + "utf-8", ); try { const config = await loadConfig(tmpFile); diff --git a/src/config.ts b/src/config.ts index 368d40be..0b175795 100644 --- a/src/config.ts +++ b/src/config.ts @@ -298,6 +298,8 @@ export interface kitConfig { context?: ContextConfig; /** Install-time supply-chain triage settings (`kit supply-chain`). */ supply_chain?: { internal_scopes?: string[] }; + /** `kit scan` settings — a tooling Infisical project to resolve scanner tokens (SNYK_TOKEN, …) from. */ + scan?: { tooling?: { project_id?: string; env?: string } }; web?: { search?: WebSearchConfig; }; @@ -486,7 +488,18 @@ const WebConfigSchema = z // Known top-level section names — used to detect typos const KNOWN_SECTIONS = new Set([ - "tools", "services", "secrets", "skills", "governance", "hooks", "web", "setup", "env", "context", "memory", "update", + "tools", + "services", + "secrets", + "skills", + "governance", + "hooks", + "web", + "setup", + "env", + "context", + "memory", + "update", ]); const kitConfigSchema = z @@ -544,6 +557,15 @@ const kitConfigSchema = z .object({ internal_scopes: z.array(z.string()).optional() }) .passthrough() .optional(), + scan: z + .object({ + tooling: z + .object({ project_id: z.string().optional(), env: z.string().optional() }) + .passthrough() + .optional(), + }) + .passthrough() + .optional(), web: WebConfigSchema, setup: z .object({ @@ -636,7 +658,9 @@ export async function loadConfig(path: string, envName?: string): Promise<kitCon // Warn about unknown top-level sections (likely typos like [tolls] vs [tools]) for (const key of Object.keys(raw)) { if (!KNOWN_SECTIONS.has(key)) { - console.warn(`Warning: unknown section [${key}] in .kit.toml (known: ${[...KNOWN_SECTIONS].join(", ")})`); + console.warn( + `Warning: unknown section [${key}] in .kit.toml (known: ${[...KNOWN_SECTIONS].join(", ")})`, + ); } } diff --git a/src/context-lock.test.ts b/src/context-lock.test.ts index 99cdab95..c4685753 100644 --- a/src/context-lock.test.ts +++ b/src/context-lock.test.ts @@ -83,7 +83,10 @@ describe("context lock", () => { group: "acme", remote: "gitlab.com/acme/web", }); - assert.deepEqual(parseGitlabRemote("git@github.com:acme/web.git"), { group: null, remote: null }); + assert.deepEqual(parseGitlabRemote("git@github.com:acme/web.git"), { + group: null, + remote: null, + }); }); it("parses bitbucket workspace + remote, and ignores non-bitbucket hosts", () => { @@ -95,28 +98,60 @@ describe("context lock", () => { workspace: "acme", remote: "bitbucket.org/acme/web", }); - assert.deepEqual(parseBitbucketRemote("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/acme/web"), { workspace: null, remote: null }); + assert.deepEqual(parseBitbucketRemote("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/acme/web"), { + workspace: null, + remote: null, + }); }); it("locks a gitlab group: only the declared group passes (wrong group = mismatch)", () => { const declared = { gitlab: { group: "acme" } }; - assert.equal(compareContext(declared, { gitlab: { group: "acme", remote: null } })[0]?.status, "ok"); - assert.equal(compareContext(declared, { gitlab: { group: "evil", remote: null } })[0]?.status, "mismatch"); - assert.equal(compareContext(declared, { gitlab: { group: null, remote: null } })[0]?.status, "unknown"); + assert.equal( + compareContext(declared, { gitlab: { group: "acme", remote: null } })[0]?.status, + "ok", + ); + assert.equal( + compareContext(declared, { gitlab: { group: "evil", remote: null } })[0]?.status, + "mismatch", + ); + assert.equal( + compareContext(declared, { gitlab: { group: null, remote: null } })[0]?.status, + "unknown", + ); }); it("locks a bitbucket workspace: only the declared workspace passes", () => { const declared = { bitbucket: { workspace: "acme" } }; - assert.equal(compareContext(declared, { bitbucket: { workspace: "acme", remote: null } })[0]?.status, "ok"); - assert.equal(compareContext(declared, { bitbucket: { workspace: "other", remote: null } })[0]?.status, "mismatch"); + assert.equal( + compareContext(declared, { bitbucket: { workspace: "acme", remote: null } })[0]?.status, + "ok", + ); + assert.equal( + compareContext(declared, { bitbucket: { workspace: "other", remote: null } })[0]?.status, + "mismatch", + ); }); it("parses the SSH identity from core.sshCommand, ssh -G output, and a keygen fingerprint", () => { - assert.equal(parseSshCommandIdentity('ssh -i ~/.ssh/id_work -o IdentitiesOnly=yes'), "~/.ssh/id_work"); - assert.equal(parseSshCommandIdentity('ssh -i "/home/me/.ssh/id work"'), "/home/me/.ssh/id work"); + assert.equal( + parseSshCommandIdentity("ssh -i ~/.ssh/id_work -o IdentitiesOnly=yes"), + "~/.ssh/id_work", + ); + assert.equal( + parseSshCommandIdentity('ssh -i "/home/me/.ssh/id work"'), + "/home/me/.ssh/id work", + ); assert.equal(parseSshCommandIdentity("ssh"), null); - assert.equal(parseSshConfigIdentity("user me\nidentityfile /home/me/.ssh/id_work\nidentityfile ~/.ssh/id_rsa"), "/home/me/.ssh/id_work"); - assert.equal(parseKeygenFingerprint("256 SHA256:abc123DEF+/ me@host (ED25519)"), "SHA256:abc123DEF+/"); + assert.equal( + parseSshConfigIdentity( + "user me\nidentityfile /home/me/.ssh/id_work\nidentityfile ~/.ssh/id_rsa", + ), + "/home/me/.ssh/id_work", + ); + assert.equal( + parseKeygenFingerprint("256 SHA256:abc123DEF+/ me@host (ED25519)"), + "SHA256:abc123DEF+/", + ); assert.equal(parseKeygenFingerprint("not a fingerprint"), null); }); @@ -129,27 +164,39 @@ describe("context lock", () => { it("locks the SSH identity: wrong key/fingerprint/host-alias is a mismatch, missing is unknown", () => { const byFp = { ssh: { fingerprint: "SHA256:GOOD" } }; assert.equal( - compareContext(byFp, { ssh: { identity: null, fingerprint: "SHA256:GOOD", host_alias: null } })[0]?.status, + compareContext(byFp, { + ssh: { identity: null, fingerprint: "SHA256:GOOD", host_alias: null }, + })[0]?.status, "ok", ); assert.equal( - compareContext(byFp, { ssh: { identity: null, fingerprint: "SHA256:EVIL", host_alias: null } })[0]?.status, + compareContext(byFp, { + ssh: { identity: null, fingerprint: "SHA256:EVIL", host_alias: null }, + })[0]?.status, "mismatch", ); assert.equal( - compareContext(byFp, { ssh: { identity: null, fingerprint: null, host_alias: null } })[0]?.status, + compareContext(byFp, { ssh: { identity: null, fingerprint: null, host_alias: null } })[0] + ?.status, "unknown", ); const byAlias = { ssh: { host_alias: "github.com-work" } }; assert.equal( - compareContext(byAlias, { ssh: { identity: null, fingerprint: null, host_alias: "github.com-personal" } })[0]?.status, + compareContext(byAlias, { + ssh: { identity: null, fingerprint: null, host_alias: "github.com-personal" }, + })[0]?.status, "mismatch", ); }); it("plans gcloud + git activation from the declared context (local config only)", () => { const steps = planContext({ - gcloud: { config: "prod-cfg", account: "ops@example.com", project: "prod-project", region: "europe-west4" }, + gcloud: { + config: "prod-cfg", + account: "ops@example.com", + project: "prod-project", + region: "europe-west4", + }, git: { email: "dev@example.com" }, }); const describes = steps.map((s) => s.describe); @@ -161,7 +208,10 @@ describe("context lock", () => { assert.equal(gitStep?.local, true); assert.deepEqual(gitStep?.argv, ["config", "user.email", "dev@example.com"]); // nothing planned for vercel/npm (no clean per-repo activation) - assert.equal(steps.some((s) => s.tool === "vercel" || s.tool === "npm"), false); + assert.equal( + steps.some((s) => s.tool === "vercel" || s.tool === "npm"), + false, + ); }); it("plans nothing when no activatable context is declared", () => { @@ -169,7 +219,10 @@ describe("context lock", () => { }); it("parses the gcloud project from a config INI", () => { - assert.equal(parseGcloudProject("[core]\naccount = a@b.com\nproject = prod-project\n"), "prod-project"); + assert.equal( + parseGcloudProject("[core]\naccount = a@b.com\nproject = prod-project\n"), + "prod-project", + ); assert.equal(parseGcloudProject("[core]\naccount = a@b.com\n"), null); }); @@ -181,7 +234,10 @@ describe("context lock", () => { }); it("is false for git-email / npm-registry only (low contamination risk, too noisy to prompt)", () => { assert.equal( - hasLockableContext({ git: { email: "a@b.com" }, npm: { registry: "https://registry.npmjs.org" } }), + hasLockableContext({ + git: { email: "a@b.com" }, + npm: { registry: "https://registry.npmjs.org" }, + }), false, ); assert.equal(hasLockableContext({}), false); @@ -199,7 +255,7 @@ describe("context lock", () => { npm: { registry: "https://registry.npmjs.org" }, }; const toml = suggestContextToml(live); - assert.ok(toml.includes('[context.git]')); + assert.ok(toml.includes("[context.git]")); assert.ok(toml.includes('email = "dev@example.com"')); assert.ok(toml.includes('team = "team_123"')); assert.ok(toml.includes('project = "prj_456"')); @@ -224,10 +280,7 @@ describe("context lock", () => { describe("app-service auth realm/tenant lock (#38)", () => { it("keycloak realm: ok on match, mismatch on the wrong realm (dev→prod guard)", () => { const declared = { keycloak: { realm: "myapp-dev" } }; - assert.equal( - compareContext(declared, { keycloak: { realm: "myapp-dev" } })[0]?.status, - "ok", - ); + assert.equal(compareContext(declared, { keycloak: { realm: "myapp-dev" } })[0]?.status, "ok"); assert.equal( compareContext(declared, { keycloak: { realm: "myapp-prod" } })[0]?.status, "mismatch", diff --git a/src/context-lock.ts b/src/context-lock.ts index 3598c697..e48be919 100644 --- a/src/context-lock.ts +++ b/src/context-lock.ts @@ -63,24 +63,104 @@ const FIELD_SPECS: { declared: (d: ContextConfig) => string | undefined; live: (l: LiveContext) => string | null; }[] = [ - { tool: "gcloud", field: "account", declared: (d) => d.gcloud?.account, live: (l) => l.gcloud?.account ?? null }, - { tool: "gcloud", field: "project", declared: (d) => d.gcloud?.project, live: (l) => l.gcloud?.project ?? null }, + { + tool: "gcloud", + field: "account", + declared: (d) => d.gcloud?.account, + live: (l) => l.gcloud?.account ?? null, + }, + { + tool: "gcloud", + field: "project", + declared: (d) => d.gcloud?.project, + live: (l) => l.gcloud?.project ?? null, + }, { tool: "git", field: "email", declared: (d) => d.git?.email, live: (l) => l.git?.email ?? null }, - { tool: "github", field: "org", declared: (d) => d.github?.org, live: (l) => l.github?.org ?? null }, - { tool: "github", field: "remote", declared: (d) => d.github?.remote, live: (l) => l.github?.remote ?? null }, - { tool: "gitlab", field: "group", declared: (d) => d.gitlab?.group, live: (l) => l.gitlab?.group ?? null }, - { tool: "gitlab", field: "remote", declared: (d) => d.gitlab?.remote, live: (l) => l.gitlab?.remote ?? null }, - { tool: "bitbucket", field: "workspace", declared: (d) => d.bitbucket?.workspace, live: (l) => l.bitbucket?.workspace ?? null }, - { tool: "bitbucket", field: "remote", declared: (d) => d.bitbucket?.remote, live: (l) => l.bitbucket?.remote ?? null }, - { tool: "ssh", field: "identity", declared: (d) => d.ssh?.identity, live: (l) => l.ssh?.identity ?? null }, - { tool: "ssh", field: "fingerprint", declared: (d) => d.ssh?.fingerprint, live: (l) => l.ssh?.fingerprint ?? null }, - { tool: "ssh", field: "host_alias", declared: (d) => d.ssh?.host_alias, live: (l) => l.ssh?.host_alias ?? null }, - { tool: "npm", field: "registry", declared: (d) => d.npm?.registry, live: (l) => l.npm?.registry ?? null }, - { tool: "vercel", field: "team(orgId)", declared: (d) => d.vercel?.team, live: (l) => l.vercel?.orgId ?? null }, - { tool: "vercel", field: "project(projectId)", declared: (d) => d.vercel?.project, live: (l) => l.vercel?.projectId ?? null }, + { + tool: "github", + field: "org", + declared: (d) => d.github?.org, + live: (l) => l.github?.org ?? null, + }, + { + tool: "github", + field: "remote", + declared: (d) => d.github?.remote, + live: (l) => l.github?.remote ?? null, + }, + { + tool: "gitlab", + field: "group", + declared: (d) => d.gitlab?.group, + live: (l) => l.gitlab?.group ?? null, + }, + { + tool: "gitlab", + field: "remote", + declared: (d) => d.gitlab?.remote, + live: (l) => l.gitlab?.remote ?? null, + }, + { + tool: "bitbucket", + field: "workspace", + declared: (d) => d.bitbucket?.workspace, + live: (l) => l.bitbucket?.workspace ?? null, + }, + { + tool: "bitbucket", + field: "remote", + declared: (d) => d.bitbucket?.remote, + live: (l) => l.bitbucket?.remote ?? null, + }, + { + tool: "ssh", + field: "identity", + declared: (d) => d.ssh?.identity, + live: (l) => l.ssh?.identity ?? null, + }, + { + tool: "ssh", + field: "fingerprint", + declared: (d) => d.ssh?.fingerprint, + live: (l) => l.ssh?.fingerprint ?? null, + }, + { + tool: "ssh", + field: "host_alias", + declared: (d) => d.ssh?.host_alias, + live: (l) => l.ssh?.host_alias ?? null, + }, + { + tool: "npm", + field: "registry", + declared: (d) => d.npm?.registry, + live: (l) => l.npm?.registry ?? null, + }, + { + tool: "vercel", + field: "team(orgId)", + declared: (d) => d.vercel?.team, + live: (l) => l.vercel?.orgId ?? null, + }, + { + tool: "vercel", + field: "project(projectId)", + declared: (d) => d.vercel?.project, + live: (l) => l.vercel?.projectId ?? null, + }, // App-service auth identity — "dev pointed at prod" guard. - { tool: "keycloak", field: "realm", declared: (d) => d.keycloak?.realm, live: (l) => l.keycloak?.realm ?? null }, - { tool: "auth0", field: "tenant", declared: (d) => d.auth0?.tenant, live: (l) => l.auth0?.tenant ?? null }, + { + tool: "keycloak", + field: "realm", + declared: (d) => d.keycloak?.realm, + live: (l) => l.keycloak?.realm ?? null, + }, + { + tool: "auth0", + field: "tenant", + declared: (d) => d.auth0?.tenant, + live: (l) => l.auth0?.tenant ?? null, + }, { tool: "clerk", field: "env", declared: (d) => d.clerk?.env, live: (l) => l.clerk?.env ?? null }, ]; @@ -132,7 +212,11 @@ export function suggestContextToml(live: LiveContext): string { ["project", live.vercel?.projectId, "projectId"], ]); emit("[context.gcloud]", [ - ["account", live.gcloud?.account, "⚠ currently-active gcloud — VERIFY it is right for THIS repo"], + [ + "account", + live.gcloud?.account, + "⚠ currently-active gcloud — VERIFY it is right for THIS repo", + ], ["project", live.gcloud?.project, "⚠ verify"], ]); emit("[context.npm]", [["registry", live.npm?.registry, "global npm registry"]]); @@ -149,10 +233,10 @@ export function suggestContextToml(live: LiveContext): string { export function hasLockableContext(live: LiveContext): boolean { return Boolean( live.gcloud?.account || - live.vercel?.projectId || - live.github?.org || - live.gitlab?.group || - live.bitbucket?.workspace, + live.vercel?.projectId || + live.github?.org || + live.gitlab?.group || + live.bitbucket?.workspace, ); } @@ -166,7 +250,10 @@ async function run(cmd: string, args: string[]): Promise<string | null> { } /** github.com[:/]org/repo(.git) -> { org, "github.com/org/repo" }. */ -export function parseGithubRemote(url: string | null): { org: string | null; remote: string | null } { +export function parseGithubRemote(url: string | null): { + org: string | null; + remote: string | null; +} { if (!url) return { org: null, remote: null }; const m = url.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/); if (!m) return { org: null, remote: null }; @@ -174,7 +261,10 @@ export function parseGithubRemote(url: string | null): { org: string | null; rem } /** gitlab.com[:/]group(/subgroups)/repo(.git) -> { group (top-level), "gitlab.com/<path>" }. */ -export function parseGitlabRemote(url: string | null): { group: string | null; remote: string | null } { +export function parseGitlabRemote(url: string | null): { + group: string | null; + remote: string | null; +} { if (!url) return { group: null, remote: null }; const m = url.match(/gitlab\.com[:/](.+?)(?:\.git)?$/); if (!m) return { group: null, remote: null }; @@ -184,7 +274,10 @@ export function parseGitlabRemote(url: string | null): { group: string | null; r } /** bitbucket.org[:/]workspace/repo(.git) -> { workspace, "bitbucket.org/workspace/repo" }. */ -export function parseBitbucketRemote(url: string | null): { workspace: string | null; remote: string | null } { +export function parseBitbucketRemote(url: string | null): { + workspace: string | null; + remote: string | null; +} { if (!url) return { workspace: null, remote: null }; const m = url.match(/bitbucket\.org[:/]([^/]+)\/(.+?)(?:\.git)?$/); if (!m) return { workspace: null, remote: null }; @@ -312,10 +405,19 @@ export async function checkContext( // npm registry trailing slash, and ssh identity `~` expansion (compared as paths). let declared: ContextConfig = ctx; if (ctx.npm?.registry) { - declared = { ...declared, npm: { ...declared.npm, registry: ctx.npm.registry.replace(/\/+$/, "") } }; + declared = { + ...declared, + npm: { ...declared.npm, registry: ctx.npm.registry.replace(/\/+$/, "") }, + }; } if (declared.ssh?.identity) { - declared = { ...declared, ssh: { ...declared.ssh, identity: expandHome(declared.ssh.identity) ?? declared.ssh.identity } }; + declared = { + ...declared, + ssh: { + ...declared.ssh, + identity: expandHome(declared.ssh.identity) ?? declared.ssh.identity, + }, + }; } return compareContext(declared, await gatherLive(cwd)); } @@ -340,15 +442,36 @@ export function planContext(ctx: ContextConfig): ContextStep[] { const steps: ContextStep[] = []; const g = ctx.gcloud; if (g?.config) - steps.push({ tool: "gcloud", argv: ["config", "configurations", "activate", g.config], describe: `activate config ${g.config}` }); + steps.push({ + tool: "gcloud", + argv: ["config", "configurations", "activate", g.config], + describe: `activate config ${g.config}`, + }); if (g?.account) - steps.push({ tool: "gcloud", argv: ["config", "set", "account", g.account], describe: `account=${g.account}` }); + steps.push({ + tool: "gcloud", + argv: ["config", "set", "account", g.account], + describe: `account=${g.account}`, + }); if (g?.project) - steps.push({ tool: "gcloud", argv: ["config", "set", "project", g.project], describe: `project=${g.project}` }); + steps.push({ + tool: "gcloud", + argv: ["config", "set", "project", g.project], + describe: `project=${g.project}`, + }); if (g?.region) - steps.push({ tool: "gcloud", argv: ["config", "set", "run/region", g.region], describe: `run/region=${g.region}` }); + steps.push({ + tool: "gcloud", + argv: ["config", "set", "run/region", g.region], + describe: `run/region=${g.region}`, + }); if (ctx.git?.email) - steps.push({ tool: "git", argv: ["config", "user.email", ctx.git.email], local: true, describe: `git user.email=${ctx.git.email}` }); + steps.push({ + tool: "git", + argv: ["config", "user.email", ctx.git.email], + local: true, + describe: `git user.email=${ctx.git.email}`, + }); return steps; } diff --git a/src/context.test.ts b/src/context.test.ts index a870b069..4788be61 100644 --- a/src/context.test.ts +++ b/src/context.test.ts @@ -102,7 +102,10 @@ describe("gatherProjectContext", () => { const context = await gatherProjectContext(config, process.cwd()); assert.ok(context.secrets, "Should have secrets"); - assert.ok(context.secrets.templateExists === null || typeof context.secrets.templateExists === "boolean"); + assert.ok( + context.secrets.templateExists === null || + typeof context.secrets.templateExists === "boolean", + ); assert.ok(Array.isArray(context.secrets.keys), "Should have secrets.keys"); }); diff --git a/src/context.ts b/src/context.ts index 4c5611a5..0c866391 100644 --- a/src/context.ts +++ b/src/context.ts @@ -46,7 +46,7 @@ export interface ProjectContext { */ export async function gatherProjectContext( config: kitConfig, - cwd: string + cwd: string, ): Promise<ProjectContext> { const kitVersion = getkitVersion(cwd); const activeEnv = resolveActiveEnvironment(); diff --git a/src/cost-monitor.test.ts b/src/cost-monitor.test.ts index 0022cd23..c0e1dc12 100644 --- a/src/cost-monitor.test.ts +++ b/src/cost-monitor.test.ts @@ -3,11 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { - sampleCosts, - detectCostAnomalies, - type CostSample, -} from "./cost-monitor.js"; +import { sampleCosts, detectCostAnomalies, type CostSample } from "./cost-monitor.js"; function tmpDir(): string { return mkdtempSync(join(tmpdir(), "kit-cost-")); @@ -151,10 +147,9 @@ describe("detectCostAnomalies", () => { }, }), ); - const alerts = await detectCostAnomalies( - [sample({ current: 100, capUsd: 50 })], - { cwd: dir }, - ); + const alerts = await detectCostAnomalies([sample({ current: 100, capUsd: 50 })], { + cwd: dir, + }); assert.equal(alerts.length, 1); assert.equal(alerts[0]!.severity, "critical"); } finally { diff --git a/src/cost-monitor.ts b/src/cost-monitor.ts index 54a62bf4..a7f3b513 100644 --- a/src/cost-monitor.ts +++ b/src/cost-monitor.ts @@ -26,23 +26,13 @@ export interface CostSample { /** Spend cap from policy, if declared */ capUsd?: number; /** Plain-text status string suitable for table display */ - status: - | "ok" - | "warn" - | "over-cap" - | "no-cap" - | "no-api" - | "auth-failed" - | "skipped"; + status: "ok" | "warn" | "over-cap" | "no-cap" | "no-api" | "auth-failed" | "skipped"; detail: string; } type ProviderAdapter = (key: string, opts: { capUsd?: number }) => Promise<CostSample>; -async function stripeAdapter( - key: string, - opts: { capUsd?: number }, -): Promise<CostSample> { +async function stripeAdapter(key: string, opts: { capUsd?: number }): Promise<CostSample> { // `https://api.stripe.com/v1/balance` returns `{ available: [{amount, currency}], pending: [...] }`. // Amounts are in the currency's smallest unit (cents). We sum availability // across currencies and surface it as the dominant currency for clarity. @@ -77,20 +67,11 @@ async function stripeAdapter( available: { amount: number; currency: string }[]; pending: { amount: number; currency: string }[]; }; - const sumCents = [...data.available, ...data.pending].reduce( - (sum, b) => sum + b.amount, - 0, - ); + const sumCents = [...data.available, ...data.pending].reduce((sum, b) => sum + b.amount, 0); const usd = sumCents / 100; const cap = opts.capUsd; const status = - cap === undefined - ? "no-cap" - : usd > cap - ? "over-cap" - : usd > cap * 0.8 - ? "warn" - : "ok"; + cap === undefined ? "no-cap" : usd > cap ? "over-cap" : usd > cap * 0.8 ? "warn" : "ok"; return { provider: "stripe", policyKey: "STRIPE_SECRET_KEY", @@ -212,15 +193,8 @@ async function loadBaselines(cwd: string): Promise<Record<string, CostBaseline>> } } -async function saveBaselines( - cwd: string, - baselines: Record<string, CostBaseline>, -): Promise<void> { - await writeFile( - resolve(cwd, BASELINE_FILE), - JSON.stringify(baselines, null, 2) + "\n", - "utf-8", - ); +async function saveBaselines(cwd: string, baselines: Record<string, CostBaseline>): Promise<void> { + await writeFile(resolve(cwd, BASELINE_FILE), JSON.stringify(baselines, null, 2) + "\n", "utf-8"); } /** diff --git a/src/create-plugin.test.ts b/src/create-plugin.test.ts index d6777321..d7eac594 100644 --- a/src/create-plugin.test.ts +++ b/src/create-plugin.test.ts @@ -35,10 +35,7 @@ describe("createPlugin", () => { it("creates package.json with correct name", async () => { await createPlugin({ name: "pkg-check", cwd: tmpDir, skipInstall: true }); - const raw = await readFile( - join(tmpDir, "kit-plugin-pkg-check", "package.json"), - "utf-8" - ); + const raw = await readFile(join(tmpDir, "kit-plugin-pkg-check", "package.json"), "utf-8"); const pkg = JSON.parse(raw) as { name: string; type: string }; assert.equal(pkg.name, "kit-plugin-pkg-check"); assert.equal(pkg.type, "module"); @@ -46,20 +43,14 @@ describe("createPlugin", () => { it("creates tsconfig.json", async () => { await createPlugin({ name: "ts-check", cwd: tmpDir, skipInstall: true }); - const raw = await readFile( - join(tmpDir, "kit-plugin-ts-check", "tsconfig.json"), - "utf-8" - ); + const raw = await readFile(join(tmpDir, "kit-plugin-ts-check", "tsconfig.json"), "utf-8"); const tsconfig = JSON.parse(raw) as { compilerOptions: { module: string } }; assert.equal(tsconfig.compilerOptions.module, "Node16"); }); it("creates src/index.ts that exports { adapter }", async () => { await createPlugin({ name: "idx-check", cwd: tmpDir, skipInstall: true }); - const src = await readFile( - join(tmpDir, "kit-plugin-idx-check", "src", "index.ts"), - "utf-8" - ); + const src = await readFile(join(tmpDir, "kit-plugin-idx-check", "src", "index.ts"), "utf-8"); assert(src.includes("adapter"), "index.ts should export 'adapter'"); }); @@ -67,7 +58,7 @@ describe("createPlugin", () => { await createPlugin({ name: "src-check", cwd: tmpDir, skipInstall: true }); const src = await readFile( join(tmpDir, "kit-plugin-src-check", "src", "src-check.ts"), - "utf-8" + "utf-8", ); assert(src.includes("ServiceAdapter"), "should import ServiceAdapter type"); assert(src.includes("getRequiredTools"), "should implement getRequiredTools"); @@ -79,7 +70,7 @@ describe("createPlugin", () => { await createPlugin({ name: "test-file-check", cwd: tmpDir, skipInstall: true }); const src = await readFile( join(tmpDir, "kit-plugin-test-file-check", "src", "test-file-check.test.ts"), - "utf-8" + "utf-8", ); assert(src.includes("node:test"), "should use node:test"); assert(src.includes("describe"), "should have describe block"); @@ -87,10 +78,7 @@ describe("createPlugin", () => { it("creates README.md", async () => { await createPlugin({ name: "readme-check", cwd: tmpDir, skipInstall: true }); - const readme = await readFile( - join(tmpDir, "kit-plugin-readme-check", "README.md"), - "utf-8" - ); + const readme = await readFile(join(tmpDir, "kit-plugin-readme-check", "README.md"), "utf-8"); assert(readme.includes("kit-plugin-readme-check"), "README should mention package name"); assert(readme.includes("kitPlugins"), "README should mention kitPlugins"); }); @@ -105,10 +93,7 @@ describe("createPlugin", () => { it("generated package.json has typescript as devDependency", async () => { await createPlugin({ name: "sdk-dep-check", cwd: tmpDir, skipInstall: true }); - const raw = await readFile( - join(tmpDir, "kit-plugin-sdk-dep-check", "package.json"), - "utf-8" - ); + const raw = await readFile(join(tmpDir, "kit-plugin-sdk-dep-check", "package.json"), "utf-8"); const pkg = JSON.parse(raw) as { devDependencies: Record<string, string> }; // typescript is the only devDep needed — SDK types are bundled in src/types/ assert(pkg.devDependencies["typescript"], "should have typescript devDep"); @@ -118,7 +103,7 @@ describe("createPlugin", () => { await createPlugin({ name: "stub-check", cwd: tmpDir, skipInstall: true }); const stub = await readFile( join(tmpDir, "kit-plugin-stub-check", "src", "types", "adapter-sdk.d.ts"), - "utf-8" + "utf-8", ); assert(stub.includes("ServiceAdapter"), "stub should define ServiceAdapter"); assert(stub.includes("AdapterContext"), "stub should define AdapterContext"); diff --git a/src/create-plugin.ts b/src/create-plugin.ts index d2cdc015..1e6dbd99 100644 --- a/src/create-plugin.ts +++ b/src/create-plugin.ts @@ -2,7 +2,6 @@ import { mkdir, writeFile } from "node:fs/promises"; import { resolve, join } from "node:path"; import { exec } from "./utils/exec.js"; - export interface CreatePluginOptions { /** Plugin short name, e.g. "aws-s3" → package "sandstream-kit-plugin-aws-s3" */ name: string; @@ -59,17 +58,17 @@ export async function createPlugin(opts: CreatePluginOptions): Promise<CreatePlu await writeFile( join(pluginDir, "src", `${shortName}.ts`), adapterTemplate(adapterName, serviceName), - "utf-8" + "utf-8", ); await writeFile( join(pluginDir, "src", `${shortName}.test.ts`), testTemplate(adapterName, serviceName), - "utf-8" + "utf-8", ); await writeFile( join(pluginDir, "src", "index.ts"), indexTemplate(adapterName, shortName), - "utf-8" + "utf-8", ); if (!opts.skipInstall) { @@ -138,62 +137,66 @@ export interface AdapterRegistry { } function packageJsonTemplate(packageName: string): string { - return JSON.stringify( - { - name: packageName, - version: "0.1.0", - description: `kit adapter plugin for ${packageName}`, - type: "module", - exports: { - ".": { - types: "./dist/index.d.ts", - default: "./dist/index.js", + return ( + JSON.stringify( + { + name: packageName, + version: "0.1.0", + description: `kit adapter plugin for ${packageName}`, + type: "module", + exports: { + ".": { + types: "./dist/index.d.ts", + default: "./dist/index.js", + }, + }, + files: ["dist", "!dist/**/*.test.*", "README.md"], + scripts: { + build: "tsc", + test: "node --test dist/*.test.js", + }, + // sandstream-kit-adapter-sdk types are bundled in src/types/adapter-sdk.d.ts so this + // plugin builds without any registry dependencies. Once sandstream-kit-adapter-sdk is + // published, add it here: peerDependencies: { "sandstream-kit-adapter-sdk": ">=0.1.0" } + devDependencies: { + "@types/node": "^22.0.0", + typescript: "^5.9.3", }, }, - files: ["dist", "!dist/**/*.test.*", "README.md"], - scripts: { - build: "tsc", - test: "node --test dist/*.test.js", - }, - // sandstream-kit-adapter-sdk types are bundled in src/types/adapter-sdk.d.ts so this - // plugin builds without any registry dependencies. Once sandstream-kit-adapter-sdk is - // published, add it here: peerDependencies: { "sandstream-kit-adapter-sdk": ">=0.1.0" } - devDependencies: { - "@types/node": "^22.0.0", - typescript: "^5.9.3", - }, - }, - null, - 2 - ) + "\n"; + null, + 2, + ) + "\n" + ); } function tsconfigTemplate(): string { - return JSON.stringify( - { - compilerOptions: { - target: "ES2022", - module: "Node16", - moduleResolution: "Node16", - outDir: "dist", - rootDir: "src", - strict: true, - declaration: true, - declarationMap: true, - sourceMap: true, - // baseUrl + paths: maps sandstream-kit-adapter-sdk to the bundled type stub so the - // plugin builds without installing the SDK package. Once sandstream-kit-adapter-sdk is - // published to npm, remove these two entries and install the real package. - baseUrl: "src", - paths: { - "sandstream-kit-adapter-sdk": ["types/adapter-sdk.d.ts"], + return ( + JSON.stringify( + { + compilerOptions: { + target: "ES2022", + module: "Node16", + moduleResolution: "Node16", + outDir: "dist", + rootDir: "src", + strict: true, + declaration: true, + declarationMap: true, + sourceMap: true, + // baseUrl + paths: maps sandstream-kit-adapter-sdk to the bundled type stub so the + // plugin builds without installing the SDK package. Once sandstream-kit-adapter-sdk is + // published to npm, remove these two entries and install the real package. + baseUrl: "src", + paths: { + "sandstream-kit-adapter-sdk": ["types/adapter-sdk.d.ts"], + }, }, + include: ["src"], }, - include: ["src"], - }, - null, - 2 - ) + "\n"; + null, + 2, + ) + "\n" + ); } function adapterTemplate(adapterName: string, serviceName: string): string { diff --git a/src/data/top-npm.ts b/src/data/top-npm.ts index 29c26bf7..6546df42 100644 --- a/src/data/top-npm.ts +++ b/src/data/top-npm.ts @@ -5,20 +5,102 @@ * network) — it covers the names attackers most often imitate, not all of npm. */ export const TOP_NPM: readonly string[] = [ - "react", "react-dom", "lodash", "express", "axios", "chalk", "commander", - "debug", "moment", "request", "async", "bluebird", "underscore", "yargs", - "uuid", "glob", "minimist", "semver", "rimraf", "mkdirp", "dotenv", "cors", - "body-parser", "webpack", "babel-core", "typescript", "eslint", "prettier", - "jest", "mocha", "chai", "vue", "angular", "next", "vite", "rollup", "ws", - "node-fetch", "cross-env", "nodemon", "ts-node", "tslib", "zod", "prisma", - "redux", "react-redux", "styled-components", "tailwindcss", "postcss", - "classnames", "immer", "rxjs", "graphql", "apollo-server", "mongoose", - "sequelize", "pg", "mysql2", "redis", "ioredis", "socket.io", "passport", - "jsonwebtoken", "bcrypt", "bcryptjs", "helmet", "morgan", "winston", "pino", - "nanoid", "date-fns", "dayjs", "ramda", "fastify", "koa", "ejs", "handlebars", - "sharp", "puppeteer", "playwright", "cheerio", "form-data", "qs", "ini", - "colors", "inquirer", "ora", "execa", "fs-extra", "globby", "chokidar", - "esbuild", "terser", "core-js", "regenerator-runtime", "left-pad", + "react", + "react-dom", + "lodash", + "express", + "axios", + "chalk", + "commander", + "debug", + "moment", + "request", + "async", + "bluebird", + "underscore", + "yargs", + "uuid", + "glob", + "minimist", + "semver", + "rimraf", + "mkdirp", + "dotenv", + "cors", + "body-parser", + "webpack", + "babel-core", + "typescript", + "eslint", + "prettier", + "jest", + "mocha", + "chai", + "vue", + "angular", + "next", + "vite", + "rollup", + "ws", + "node-fetch", + "cross-env", + "nodemon", + "ts-node", + "tslib", + "zod", + "prisma", + "redux", + "react-redux", + "styled-components", + "tailwindcss", + "postcss", + "classnames", + "immer", + "rxjs", + "graphql", + "apollo-server", + "mongoose", + "sequelize", + "pg", + "mysql2", + "redis", + "ioredis", + "socket.io", + "passport", + "jsonwebtoken", + "bcrypt", + "bcryptjs", + "helmet", + "morgan", + "winston", + "pino", + "nanoid", + "date-fns", + "dayjs", + "ramda", + "fastify", + "koa", + "ejs", + "handlebars", + "sharp", + "puppeteer", + "playwright", + "cheerio", + "form-data", + "qs", + "ini", + "colors", + "inquirer", + "ora", + "execa", + "fs-extra", + "globby", + "chokidar", + "esbuild", + "terser", + "core-js", + "regenerator-runtime", + "left-pad", ]; export const TOP_NPM_SET: ReadonlySet<string> = new Set(TOP_NPM); diff --git a/src/database.ts b/src/database.ts index 462b98dc..36aac57c 100644 --- a/src/database.ts +++ b/src/database.ts @@ -131,9 +131,7 @@ export class DatabaseManager { /** * Execute a query with transaction. */ - async transaction<T>( - callback: (db: DatabaseManager) => Promise<T>, - ): Promise<T> { + async transaction<T>(callback: (db: DatabaseManager) => Promise<T>): Promise<T> { if (!this.isInitialized) { throw new Error("Database not initialized"); } @@ -313,9 +311,7 @@ export class DatabaseManager { const totalTime = this.queryLog.reduce((sum, q) => sum + q.duration, 0); const averageTime = totalTime / this.queryLog.length; - const slowestQuery = this.queryLog.reduce((max, q) => - q.duration > max.duration ? q : max, - ); + const slowestQuery = this.queryLog.reduce((max, q) => (q.duration > max.duration ? q : max)); return { totalQueries: this.queryLog.length, diff --git a/src/doctor.test.ts b/src/doctor.test.ts index 7e89ecb6..6540b0bc 100644 --- a/src/doctor.test.ts +++ b/src/doctor.test.ts @@ -14,7 +14,10 @@ describe("runDoctor", () => { const nodeCheck = result.checks.find((c) => c.name === "Node.js version"); assert.ok(nodeCheck, "Node.js version check should exist"); assert.equal(nodeCheck.status, "skip"); - assert.ok(nodeCheck.detail.includes("No package.json"), `unexpected detail: ${nodeCheck.detail}`); + assert.ok( + nodeCheck.detail.includes("No package.json"), + `unexpected detail: ${nodeCheck.detail}`, + ); } finally { await rm(tmpDir, { recursive: true }); } @@ -30,7 +33,10 @@ describe("runDoctor", () => { const nodeCheck = result.checks.find((c) => c.name === "Node.js version"); assert.ok(nodeCheck, "Node.js version check should exist"); assert.equal(nodeCheck.status, "pass"); - assert.ok(nodeCheck.detail.includes("requires"), `detail should mention requirement: ${nodeCheck.detail}`); + assert.ok( + nodeCheck.detail.includes("requires"), + `detail should mention requirement: ${nodeCheck.detail}`, + ); } finally { await unlink(join(tmpDir, "package.json")); await rmdir(tmpDir); @@ -47,7 +53,10 @@ describe("runDoctor", () => { const nodeCheck = result.checks.find((c) => c.name === "Node.js version"); assert.ok(nodeCheck, "Node.js version check should exist"); assert.equal(nodeCheck.status, "fail"); - assert.ok(nodeCheck.detail.includes("does not satisfy"), `unexpected detail: ${nodeCheck.detail}`); + assert.ok( + nodeCheck.detail.includes("does not satisfy"), + `unexpected detail: ${nodeCheck.detail}`, + ); } finally { await unlink(join(tmpDir, "package.json")); await rmdir(tmpDir); @@ -62,7 +71,10 @@ describe("runDoctor", () => { const envCheck = result.checks.find((c) => c.name === ".env.local"); assert.ok(envCheck, ".env.local check should exist when secrets configured"); assert.equal(envCheck.status, "warn"); - assert.ok(envCheck.detail.includes("kit secrets"), `detail should suggest fix: ${envCheck.detail}`); + assert.ok( + envCheck.detail.includes("kit secrets"), + `detail should suggest fix: ${envCheck.detail}`, + ); } finally { await rmdir(tmpDir); } @@ -105,7 +117,7 @@ describe("runDoctor", () => { assert.ok(miseCheck, "mise check should always be present"); assert.ok( miseCheck.status === "pass" || miseCheck.status === "warn", - `mise check should be pass or warn, got: ${miseCheck.status}` + `mise check should be pass or warn, got: ${miseCheck.status}`, ); } finally { await rmdir(tmpDir); diff --git a/src/elevation-scopes.test.ts b/src/elevation-scopes.test.ts index e96b092d..c49c255f 100644 --- a/src/elevation-scopes.test.ts +++ b/src/elevation-scopes.test.ts @@ -56,7 +56,10 @@ describe("isOneShot", () => { describe("listScopes", () => { it("returns every declared mapping with the key + description", () => { const all = listScopes(); - assert.ok(all.length >= 7, "covers all rotate modes + migrate + propagate + purge-history + onecli-register + revoke-old"); + assert.ok( + all.length >= 7, + "covers all rotate modes + migrate + propagate + purge-history + onecli-register + revoke-old", + ); const keys = all.map((m) => m.key); assert.ok(keys.includes("rotate:jwt-secret-roll")); assert.ok(keys.includes("purge-history")); diff --git a/src/elevation.test.ts b/src/elevation.test.ts index 05471192..00355f64 100644 --- a/src/elevation.test.ts +++ b/src/elevation.test.ts @@ -250,9 +250,7 @@ describe("requireElevation audit emission", () => { try { const result = await requireElevation("rotate", dir); assert.equal(result.ok, false); - const lines = readFileSync(join(dir, ".kit-audit.jsonl"), "utf-8") - .trim() - .split("\n"); + const lines = readFileSync(join(dir, ".kit-audit.jsonl"), "utf-8").trim().split("\n"); const last = JSON.parse(lines[lines.length - 1]!); assert.equal(last.operation, "elevation-check"); assert.equal(last.success, false); diff --git a/src/elevation.ts b/src/elevation.ts index c447d033..11b38212 100644 --- a/src/elevation.ts +++ b/src/elevation.ts @@ -120,7 +120,11 @@ async function getElevationSigningKey(): Promise<Buffer> { const key = randomBytes(32); await mkdir(dirname(keyPath), { recursive: true }); try { - await writeFile(keyPath, key.toString("hex") + "\n", { encoding: "utf-8", mode: 0o600, flag: "wx" }); + await writeFile(keyPath, key.toString("hex") + "\n", { + encoding: "utf-8", + mode: 0o600, + flag: "wx", + }); return key; } catch { const hex = (await readFile(keyPath, "utf-8")).trim(); @@ -155,9 +159,7 @@ async function verifyElevationSig(state: ElevationState, sig: string): Promise<b return expected.length === actual.length && timingSafeEqual(expected, actual); } -export async function readElevation( - cwd: string = process.cwd(), -): Promise<ElevationState | null> { +export async function readElevation(cwd: string = process.cwd()): Promise<ElevationState | null> { const path = resolve(cwd, ELEVATION_FILE); try { await access(path); @@ -189,9 +191,7 @@ export async function writeElevation( await writeFile(path, JSON.stringify({ ...state, sig }, null, 2) + "\n", "utf-8"); } -export async function clearElevation( - cwd: string = process.cwd(), -): Promise<void> { +export async function clearElevation(cwd: string = process.cwd()): Promise<void> { const path = resolve(cwd, ELEVATION_FILE); try { const { rm } = await import("node:fs/promises"); @@ -205,10 +205,7 @@ export async function clearElevation( * Returns true if an unexpired elevation marker exists that covers the * requested operation scope. */ -export async function isElevated( - operation: string, - cwd: string = process.cwd(), -): Promise<boolean> { +export async function isElevated(operation: string, cwd: string = process.cwd()): Promise<boolean> { const state = await readElevation(cwd); if (!state) return false; const expires = Date.parse(state.expiresAt); @@ -417,11 +414,7 @@ export function generateTotp( * clock skew, ±30s window). Uses timingSafeEqual for the digit comparison — * both sides are fixed 6-ASCII-digit strings, so lengths always match. */ -export function verifyTotp( - code: string, - secretBase32: string, - windowSteps: number = 1, -): boolean { +export function verifyTotp(code: string, secretBase32: string, windowSteps: number = 1): boolean { if (!/^\d{6}$/.test(code)) return false; const codeBuf = Buffer.from(code, "ascii"); const now = Math.floor(Date.now() / 1000 / 30); @@ -469,11 +462,7 @@ export async function requireElevation( if (process.env.KIT_ELEVATED === "1") { warnCiBypassOnce(operation); - return decide( - true, - "KIT_ELEVATED=1 (CI escape hatch)", - "ci-env", - ); + return decide(true, "KIT_ELEVATED=1 (CI escape hatch)", "ci-env"); } const state = await readElevation(cwd); if (!state) { @@ -485,11 +474,7 @@ export async function requireElevation( } const expires = Date.parse(state.expiresAt); if (!Number.isFinite(expires) || expires < Date.now()) { - return decide( - false, - "Elevation marker expired. Run 'kit auth elevate' again.", - state.method, - ); + return decide(false, "Elevation marker expired. Run 'kit auth elevate' again.", state.method); } if (state.scope !== "all" && state.scope !== operation) { return decide( diff --git a/src/env-diff.ts b/src/env-diff.ts index 56a2a2e6..6f229954 100644 --- a/src/env-diff.ts +++ b/src/env-diff.ts @@ -86,11 +86,7 @@ export async function diffEnvFiles( return { onlyInA, onlyInB, changed, identicalCount }; } -export function formatEnvDiff( - diff: EnvDiffResult, - labelA: string, - labelB: string, -): string { +export function formatEnvDiff(diff: EnvDiffResult, labelA: string, labelB: string): string { const lines: string[] = []; lines.push(`env-diff ${labelA} vs ${labelB}`); lines.push("─".repeat(50)); diff --git a/src/env-inspect.ts b/src/env-inspect.ts index 4e1a13fb..76c2a0fa 100644 --- a/src/env-inspect.ts +++ b/src/env-inspect.ts @@ -62,7 +62,7 @@ export function redactValue(value: string): string { export async function inspectEnv( config: kitConfig, - options: InspectOptions = {} + options: InspectOptions = {}, ): Promise<EnvInspectResult> { const cwd = options.cwd ?? process.cwd(); const envPath = join(cwd, ".env.local"); diff --git a/src/env-switch.test.ts b/src/env-switch.test.ts index 15bab8cd..84099110 100644 --- a/src/env-switch.test.ts +++ b/src/env-switch.test.ts @@ -41,10 +41,7 @@ describe("writeActiveEnv / readActiveEnv", () => { try { const { writeFileSync, mkdirSync } = await import("node:fs"); mkdirSync(join(dir, ".kit"), { recursive: true }); - writeFileSync( - join(dir, ".kit", "active-env.json"), - JSON.stringify({ env: "bogus" }), - ); + writeFileSync(join(dir, ".kit", "active-env.json"), JSON.stringify({ env: "bogus" })); assert.equal(await readActiveEnv(dir), null); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/src/env-switch.ts b/src/env-switch.ts index aee54d12..5b7f1b4e 100644 --- a/src/env-switch.ts +++ b/src/env-switch.ts @@ -22,9 +22,7 @@ export interface ActiveEnvState { switchedBy: string; // user / agent identifier } -export async function readActiveEnv( - cwd: string = process.cwd(), -): Promise<ActiveEnvState | null> { +export async function readActiveEnv(cwd: string = process.cwd()): Promise<ActiveEnvState | null> { const path = resolve(cwd, ACTIVE_ENV_FILE); try { await access(path); @@ -63,9 +61,7 @@ export async function writeActiveEnv( * Returns the active env if set; defaults to "dev" so a project that hasn't * opted into env-switching yet behaves safely (no accidental prod-key reads). */ -export async function getActiveEnv( - cwd: string = process.cwd(), -): Promise<kitEnv> { +export async function getActiveEnv(cwd: string = process.cwd()): Promise<kitEnv> { const state = await readActiveEnv(cwd); return state?.env ?? "dev"; } diff --git a/src/environment.test.ts b/src/environment.test.ts index 194c192e..74e7a585 100644 --- a/src/environment.test.ts +++ b/src/environment.test.ts @@ -1,10 +1,6 @@ import { describe, it, afterEach } from "node:test"; import assert from "node:assert/strict"; -import { - detectEnvironment, - isOperationAllowed, - formatEnvironment, -} from "./environment.js"; +import { detectEnvironment, isOperationAllowed, formatEnvironment } from "./environment.js"; import type { GovernanceConfig } from "./config.js"; describe("detectEnvironment", () => { @@ -136,18 +132,9 @@ describe("isOperationAllowed", () => { source: "env" as const, access: { read: undefined, write: undefined, delete: undefined }, }; - assert.equal( - isOperationAllowed("read", envInfoPartial as any), - false - ); - assert.equal( - isOperationAllowed("write", envInfoPartial as any), - false - ); - assert.equal( - isOperationAllowed("delete", envInfoPartial as any), - false - ); + assert.equal(isOperationAllowed("read", envInfoPartial as any), false); + assert.equal(isOperationAllowed("write", envInfoPartial as any), false); + assert.equal(isOperationAllowed("delete", envInfoPartial as any), false); }); }); diff --git a/src/environment.ts b/src/environment.ts index 5c373e69..a562d36f 100644 --- a/src/environment.ts +++ b/src/environment.ts @@ -16,9 +16,7 @@ export interface EnvironmentInfo { * 2. Git branch name (main→prod, staging→staging, feature/*→dev) * 3. Default to 'dev' */ -export function detectEnvironment( - governance?: GovernanceConfig -): EnvironmentInfo { +export function detectEnvironment(governance?: GovernanceConfig): EnvironmentInfo { // 1. Check NODE_ENV const nodeEnv = process.env.NODE_ENV?.toLowerCase(); if (nodeEnv === "production") { @@ -87,7 +85,7 @@ export function detectEnvironment( */ export function isOperationAllowed( operation: "read" | "write" | "delete", - envInfo: EnvironmentInfo + envInfo: EnvironmentInfo, ): boolean { if (!envInfo.access) { // No access config means allow everything (for backwards compatibility) diff --git a/src/escalate.test.ts b/src/escalate.test.ts index 8debd47e..698136cc 100644 --- a/src/escalate.test.ts +++ b/src/escalate.test.ts @@ -7,9 +7,7 @@ import type { SecretStatus } from "./check-secrets.js"; describe("collectEscalations", () => { it("returns empty array when everything passes", () => { - const tools: ToolStatus[] = [ - { name: "node", required: "22", installed: "22.22.2", ok: true }, - ]; + const tools: ToolStatus[] = [{ name: "node", required: "22", installed: "22.22.2", ok: true }]; const services: ServiceStatus[] = [ { name: "github", checkCommand: "gh auth status", authenticated: true, output: "ok" }, ]; @@ -22,9 +20,7 @@ describe("collectEscalations", () => { }); it("collects failed tools", () => { - const tools: ToolStatus[] = [ - { name: "node", required: "22", installed: null, ok: false }, - ]; + const tools: ToolStatus[] = [{ name: "node", required: "22", installed: null, ok: false }]; const items = collectEscalations(tools, [], []); assert.equal(items.length, 1); @@ -35,7 +31,12 @@ describe("collectEscalations", () => { it("collects failed services", () => { const services: ServiceStatus[] = [ - { name: "github", checkCommand: "gh auth status", authenticated: false, output: "not logged in" }, + { + name: "github", + checkCommand: "gh auth status", + authenticated: false, + output: "not logged in", + }, ]; const items = collectEscalations([], services, []); @@ -58,7 +59,10 @@ describe("collectEscalations", () => { const items = collectEscalations([], services, []); assert.equal(items.length, 1); assert.equal(items[0].issue, "Manual setup (no CLI login)"); - assert.ok(!items[0].action.startsWith("Run:"), `action should not be a Run: command, got: ${items[0].action}`); + assert.ok( + !items[0].action.startsWith("Run:"), + `action should not be a Run: command, got: ${items[0].action}`, + ); assert.ok(items[0].action.includes("RESEND_API_KEY")); }); @@ -66,7 +70,12 @@ describe("collectEscalations", () => { const secrets: SecretStatus[] = [ { name: "DB_URL", source: "1password", available: false, detail: "op read failed" }, { name: "TOKEN", source: "env", available: false, detail: "Not set" }, - { name: "API_SECRET", source: "infisical", available: false, detail: "Not found in Infisical" }, + { + name: "API_SECRET", + source: "infisical", + available: false, + detail: "Not found in Infisical", + }, ]; const items = collectEscalations([], [], secrets); @@ -78,9 +87,7 @@ describe("collectEscalations", () => { }); it("collects version mismatch tools", () => { - const tools: ToolStatus[] = [ - { name: "node", required: "22", installed: "20.10.0", ok: false }, - ]; + const tools: ToolStatus[] = [{ name: "node", required: "22", installed: "20.10.0", ok: false }]; const items = collectEscalations(tools, [], []); assert.equal(items.length, 1); @@ -98,7 +105,12 @@ describe("formatEscalationMessage", () => { it("formats items grouped by category", () => { const items = [ { category: "tool" as const, name: "node", issue: "Not installed", action: "Install node" }, - { category: "service" as const, name: "github", issue: "Not authenticated", action: "Run gh auth login" }, + { + category: "service" as const, + name: "github", + issue: "Not authenticated", + action: "Run gh auth login", + }, ]; const msg = formatEscalationMessage(items, "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/my/project"); diff --git a/src/escalate.ts b/src/escalate.ts index c739c14d..a7812dae 100644 --- a/src/escalate.ts +++ b/src/escalate.ts @@ -58,17 +58,18 @@ export function collectEscalations( category: "secret", name: s.name, issue: s.detail, - action: s.source === "1password" - ? "Retrieve from 1Password" - : s.source === "eas" - ? "Set via eas secret:push" - : s.source === "infisical" - ? "Add to Infisical project (infisical secrets set)" - : s.source === "bitwarden" - ? "Add to Bitwarden vault" - : s.source === "doppler" - ? "Add to Doppler project" - : `Set ${s.name} in environment`, + action: + s.source === "1password" + ? "Retrieve from 1Password" + : s.source === "eas" + ? "Set via eas secret:push" + : s.source === "infisical" + ? "Add to Infisical project (infisical secrets set)" + : s.source === "bitwarden" + ? "Add to Bitwarden vault" + : s.source === "doppler" + ? "Add to Doppler project" + : `Set ${s.name} in environment`, }); } } @@ -76,10 +77,7 @@ export function collectEscalations( return items; } -export function formatEscalationMessage( - items: EscalationItem[], - projectDir: string, -): string { +export function formatEscalationMessage(items: EscalationItem[], projectDir: string): string { if (items.length === 0) { return "All checks passed — no manual action needed."; } diff --git a/src/event-stream.ts b/src/event-stream.ts index e84dbfde..ff471470 100644 --- a/src/event-stream.ts +++ b/src/event-stream.ts @@ -113,10 +113,7 @@ export class EventStream { /** * Query events within time window */ - query( - windowMs: number, - filter?: (event: StreamEvent) => boolean, - ): StreamEvent[] { + query(windowMs: number, filter?: (event: StreamEvent) => boolean): StreamEvent[] { const cutoff = Date.now() - windowMs; return this.queue.filter((event) => { if (event.timestamp < cutoff) return false; @@ -161,9 +158,7 @@ export class EventStream { */ private startDrainTimer(): void { this.drainTimer = setInterval(() => { - this.drain().catch((err) => - console.error("EventStream drain failed:", err), - ); + this.drain().catch((err) => console.error("EventStream drain failed:", err)); }, this.drainIntervalMs); // Best-effort background drain — must not keep the process alive (else // `node --test` never exits and the suite "hangs"). diff --git a/src/fix.ts b/src/fix.ts index 6b3819bc..cb4a60a2 100644 --- a/src/fix.ts +++ b/src/fix.ts @@ -94,8 +94,7 @@ export async function autoFix(options: FixOptions): Promise<FixResult[]> { const cfg = options.servicesConfig[s.name]; if (cfg) automatableConfig[s.name] = cfg; } - const loginResults = - automatable.length === 0 ? [] : await loginServices(automatableConfig); + const loginResults = automatable.length === 0 ? [] : await loginServices(automatableConfig); for (const r of loginResults) { if (r.action === "already_authenticated") { continue; // Skip already authenticated @@ -221,7 +220,7 @@ export async function cmdFix(): Promise<boolean> { console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); const config = await loadConfig(resolve(process.cwd(), ".kit.toml")); - + let fixedCount = 0; let manualCount = 0; const manualActions: string[] = []; @@ -239,19 +238,23 @@ export async function cmdFix(): Promise<boolean> { console.log(`${c.bold}[1/6] Tools${c.reset}`); const toolResults = await checkTools(config.tools); const missingTools = toolResults.filter((t) => !t.ok); - + if (missingTools.length > 0) { console.log(`${c.dim}Installing ${missingTools.length} missing tool(s)...${c.reset}\n`); const installResults = await installTools(config.tools); - + for (const r of installResults) { if (r.action === "installed") { const icon = `${c.green}✓${c.reset}`; - console.log(` ${icon} ${r.name} ${c.green}installed${c.reset} ${c.dim}${r.detail}${c.reset}`); + console.log( + ` ${icon} ${r.name} ${c.green}installed${c.reset} ${c.dim}${r.detail}${c.reset}`, + ); fixedCount++; } else if (r.action === "failed") { const icon = `${c.red}✗${c.reset}`; - console.log(` ${icon} ${r.name} ${c.red}failed${c.reset} ${c.dim}${r.detail}${c.reset}`); + console.log( + ` ${icon} ${r.name} ${c.red}failed${c.reset} ${c.dim}${r.detail}${c.reset}`, + ); manualActions.push(`Install ${r.name} manually: ${r.detail}`); manualCount++; } @@ -266,10 +269,10 @@ export async function cmdFix(): Promise<boolean> { console.log(`${c.bold}[2/6] Lock Files${c.reset}`); const skillsLock = await readSkillsLock(); const cliLock = await readCliLock(); - + if (!skillsLock || !cliLock) { console.log(`${c.dim}Generating missing lock files...${c.reset}\n`); - + // Generate skills lock if (!skillsLock) { const skills: Record<string, string> = {}; @@ -279,22 +282,28 @@ export async function cmdFix(): Promise<boolean> { if (config.skills?.optional) { Object.assign(skills, config.skills.optional); } - + const kitMeta = await readkitMeta(); - await updateSkillsLock(skills, kitMeta?.name ? `${kitMeta.name}@${kitMeta.version}` : undefined); + await updateSkillsLock( + skills, + kitMeta?.name ? `${kitMeta.name}@${kitMeta.version}` : undefined, + ); console.log(` ${c.green}✓${c.reset} Generated skills-lock.json`); fixedCount++; } - + // Generate CLI lock if (!cliLock) { - const tools: Record<string, { version: string; source: "mise" | "npm" | "pip" | "manual"; auth?: string }> = {}; + const tools: Record< + string, + { version: string; source: "mise" | "npm" | "pip" | "manual"; auth?: string } + > = {}; if (config.tools) { for (const [name, version] of Object.entries(config.tools)) { tools[name] = { version, source: "mise" }; } } - + await updateCliLock(tools); console.log(` ${c.green}✓${c.reset} Generated cli-lock.json`); fixedCount++; @@ -309,21 +318,21 @@ export async function cmdFix(): Promise<boolean> { if (config.services && Object.keys(config.services).length > 0) { const serviceResults = await checkServices(config.services); const unauthenticated = serviceResults.filter((s) => !s.authenticated); - + if (unauthenticated.length > 0) { - console.log(`${c.yellow}${unauthenticated.length} service(s) require manual authentication${c.reset}\n`); + console.log( + `${c.yellow}${unauthenticated.length} service(s) require manual authentication${c.reset}\n`, + ); for (const s of unauthenticated) { - console.log(` ${c.yellow}!${c.reset} ${s.name} ${c.yellow}not authenticated${c.reset} ${c.dim}${s.output}${c.reset}`); + console.log( + ` ${c.yellow}!${c.reset} ${s.name} ${c.yellow}not authenticated${c.reset} ${c.dim}${s.output}${c.reset}`, + ); const loginCmd = config.services[s.name]?.login ?? ""; if (loginCmd.trim().startsWith("#")) { // Informational ("#"-prefixed) login — no CLI to run, only docs. - manualActions.push( - `${s.name}: ${loginCmd.trim().replace(/^#\s*/, "")}`, - ); + manualActions.push(`${s.name}: ${loginCmd.trim().replace(/^#\s*/, "")}`); } else { - manualActions.push( - `Login to ${s.name}: run 'kit login' or '${loginCmd}'`, - ); + manualActions.push(`Login to ${s.name}: run 'kit login' or '${loginCmd}'`); } manualCount++; } @@ -359,7 +368,9 @@ export async function cmdFix(): Promise<boolean> { ].join("\n"); try { await writeFile(templatePath, body, { encoding: "utf-8", flag: "wx" }); - console.log(` ${c.green}✓${c.reset} Generated ${templatePath} ${c.dim}(${keyNames.length} keys)${c.reset}`); + console.log( + ` ${c.green}✓${c.reset} Generated ${templatePath} ${c.dim}(${keyNames.length} keys)${c.reset}`, + ); fixedCount++; } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); @@ -407,9 +418,7 @@ export async function cmdFix(): Promise<boolean> { missing.join("\n") + "\n"; await writeFile(gitignorePath, current + appended, "utf-8"); - console.log( - ` ${c.green}✓${c.reset} Added ${missing.length} pattern(s) to .gitignore`, - ); + console.log(` ${c.green}✓${c.reset} Added ${missing.length} pattern(s) to .gitignore`); for (const m of missing) { console.log(` ${c.dim}+ ${m}${c.reset}`); } @@ -429,9 +438,7 @@ export async function cmdFix(): Promise<boolean> { if (config.hooks && Object.keys(config.hooks).length > 0) { try { const hookResults = await installHooks(config.hooks); - const installed = hookResults.filter( - (r) => r.action === "installed", - ); + const installed = hookResults.filter((r) => r.action === "installed"); const updated = hookResults.filter((r) => r.action === "updated"); const failed = hookResults.filter((r) => r.action === "failed"); if (installed.length > 0) { @@ -469,24 +476,28 @@ export async function cmdFix(): Promise<boolean> { // Summary console.log(`${c.bold}${c.cyan}Summary${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); - + if (fixedCount > 0) { console.log(` ${c.green}✓${c.reset} Fixed ${fixedCount} issue(s) automatically`); } - + if (manualCount > 0) { - console.log(` ${c.yellow}!${c.reset} ${manualCount} issue(s) require manual intervention:\n`); + console.log( + ` ${c.yellow}!${c.reset} ${manualCount} issue(s) require manual intervention:\n`, + ); for (const action of manualActions) { console.log(` ${c.dim}•${c.reset} ${action}`); } console.log(); - console.log(`${c.dim}Run ${c.reset}${c.bold}kit check${c.reset}${c.dim} to verify status after manual fixes${c.reset}`); + console.log( + `${c.dim}Run ${c.reset}${c.bold}kit check${c.reset}${c.dim} to verify status after manual fixes${c.reset}`, + ); } else if (fixedCount === 0) { console.log(` ${c.green}✓${c.reset} Nothing to fix — all checks passing`); } - + console.log(); return manualCount === 0; - } + }, ); } diff --git a/src/gha-audit.test.ts b/src/gha-audit.test.ts index 2a2a6340..a26a3516 100644 --- a/src/gha-audit.test.ts +++ b/src/gha-audit.test.ts @@ -11,7 +11,7 @@ describe("auditWorkflow", () => { " - uses: actions/checkout@v4", " - uses: tj-actions/changed-files@main", " - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a", // 40-hex SHA = pinned - " - uses: ./.github/actions/local", // local = exempt + " - uses: ./.github/actions/local", // local = exempt ].join("\n"); const findings = auditWorkflow(wf, "ci.yml"); const names = findings.map((f) => f.name); @@ -25,7 +25,8 @@ describe("auditWorkflow", () => { }); it("flags pwn-request (pull_request_target + checkout)", () => { - const wf = "on:\n pull_request_target:\njobs:\n x:\n steps:\n - uses: actions/checkout@deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n"; + const wf = + "on:\n pull_request_target:\njobs:\n x:\n steps:\n - uses: actions/checkout@deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n"; const findings = auditWorkflow(wf, "danger.yml"); const pwn = findings.find((f) => f.name.startsWith("pwn-request")); assert.ok(pwn); @@ -34,7 +35,8 @@ describe("auditWorkflow", () => { }); it("clean workflow → no findings", () => { - const wf = "on: push\njobs:\n x:\n steps:\n - uses: actions/checkout@1234567890123456789012345678901234567890\n"; + const wf = + "on: push\njobs:\n x:\n steps:\n - uses: actions/checkout@1234567890123456789012345678901234567890\n"; assert.deepEqual(auditWorkflow(wf, "ok.yml"), []); }); }); diff --git a/src/gha-audit.ts b/src/gha-audit.ts index 6c1c635b..935d2ae2 100644 --- a/src/gha-audit.ts +++ b/src/gha-audit.ts @@ -15,12 +15,14 @@ import { resolve, join } from "node:path"; import type { SecurityCheckResult } from "./check-security.js"; const UNPINNED_RULE = { - id: "CWE-1357", source: "cwe" as const, + id: "CWE-1357", + source: "cwe" as const, ref: "https://cwe.mitre.org/data/definitions/1357.html", title: "Reliance on Insufficiently Trustworthy Component", }; const PWN_RULE = { - id: "OWASP-A08", source: "owasp" as const, + id: "OWASP-A08", + source: "owasp" as const, ref: "https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures/", title: "Software and Data Integrity Failures", }; @@ -62,7 +64,8 @@ export function auditWorkflow(content: string, file: string): SecurityCheckResul status: "warn", detail: "pull_request_target + actions/checkout can run untrusted PR code with repo secrets", severity: "high", - suggestion: "avoid checking out PR head under pull_request_target, or gate on a label/permission", + suggestion: + "avoid checking out PR head under pull_request_target, or gate on a label/permission", rule: PWN_RULE, }); } @@ -74,13 +77,27 @@ export function auditWorkflow(content: string, file: string): SecurityCheckResul export function runGhaAudit(cwd: string): SecurityCheckResult[] { const dir = resolve(cwd, ".github", "workflows"); if (!existsSync(dir)) { - return [{ category: "supply-chain", name: "gha-audit", status: "skip", detail: "no .github/workflows directory" }]; + return [ + { + category: "supply-chain", + name: "gha-audit", + status: "skip", + detail: "no .github/workflows directory", + }, + ]; } let files: string[]; try { files = readdirSync(dir).filter((f) => f.endsWith(".yml") || f.endsWith(".yaml")); } catch { - return [{ category: "supply-chain", name: "gha-audit", status: "skip", detail: "could not read .github/workflows" }]; + return [ + { + category: "supply-chain", + name: "gha-audit", + status: "skip", + detail: "could not read .github/workflows", + }, + ]; } const out: SecurityCheckResult[] = []; for (const f of files) { @@ -91,7 +108,12 @@ export function runGhaAudit(cwd: string): SecurityCheckResult[] { } } if (out.length === 0) { - out.push({ category: "supply-chain", name: "gha-audit", status: "pass", detail: `${files.length} workflow(s): all actions pinned, no pwn-request` }); + out.push({ + category: "supply-chain", + name: "gha-audit", + status: "pass", + detail: `${files.length} workflow(s): all actions pinned, no pwn-request`, + }); } return out; } diff --git a/src/governance-middleware.test.ts b/src/governance-middleware.test.ts index a28461cc..e1a97284 100644 --- a/src/governance-middleware.test.ts +++ b/src/governance-middleware.test.ts @@ -3,10 +3,7 @@ import assert from "node:assert/strict"; import { mkdtemp, rm } from "node:fs/promises"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { - withGovernance, - checkGovernance, -} from "./governance-middleware.js"; +import { withGovernance, checkGovernance } from "./governance-middleware.js"; import { clearBudgetState, getBudgetStatus, recordUsage } from "./budget.js"; import type { kitConfig, GovernanceConfig } from "./config.js"; @@ -21,9 +18,7 @@ const disabledConfig: kitConfig = { // - revocation disabled (no network calls) // - secret expiry disabled (no network calls) // - approval that auto-approves everything (no readline / API calls) -function makeConfig( - govOverrides: Partial<GovernanceConfig> = {}, -): kitConfig { +function makeConfig(govOverrides: Partial<GovernanceConfig> = {}): kitConfig { return { governance: { enabled: true, @@ -252,13 +247,9 @@ describe("withGovernance", () => { const config = makeConfig(); await assert.rejects( () => - withGovernance( - config, - { operation: "failing-op", operationType: "read" }, - async () => { - throw new Error("Something went wrong"); - }, - ), + withGovernance(config, { operation: "failing-op", operationType: "read" }, async () => { + throw new Error("Something went wrong"); + }), /Something went wrong/, ); }); diff --git a/src/governance-middleware.ts b/src/governance-middleware.ts index 75387523..1d37ae79 100644 --- a/src/governance-middleware.ts +++ b/src/governance-middleware.ts @@ -8,7 +8,11 @@ import { checkRevocationStatus, handleRevocation } from "./revocation.js"; import { checkBudgetLimits, recordUsage } from "./budget.js"; import { logAuditEvent } from "./audit.js"; import { requestApproval } from "./approval.js"; -import { checkSecretExpiration, formatSecretExpirationWarnings, hasExpiredSecrets } from "./secret-expiration.js"; +import { + checkSecretExpiration, + formatSecretExpirationWarnings, + hasExpiredSecrets, +} from "./secret-expiration.js"; export interface OperationContext { operation: string; @@ -60,10 +64,7 @@ export async function withGovernance<T>( } // 2. Check budget limits - const budgetCheck = await checkBudgetLimits( - config.governance, - context.estimatedTokens || 0, - ); + const budgetCheck = await checkBudgetLimits(config.governance, context.estimatedTokens || 0); if (!budgetCheck.allowed) { await auditDeny(budgetCheck.reason || "Budget limit exceeded"); throw new Error(budgetCheck.reason || "Budget limit exceeded"); @@ -74,18 +75,14 @@ export async function withGovernance<T>( let approvedForOp = false; // 3. Check operation permissions - const permissionCheck = checkOperationAllowed( - governanceConfig, - context.operationType, - ); + const permissionCheck = checkOperationAllowed(governanceConfig, context.operationType); if (!permissionCheck.allowed) { // Check if approval can override if (permissionCheck.requiresApproval) { const approved = await requestApproval(config.governance, { operation: context.operation, environment: governanceConfig.environment, - reason: - permissionCheck.reason || "Operation requires approval", + reason: permissionCheck.reason || "Operation requires approval", metadata: context.metadata, }); @@ -96,9 +93,7 @@ export async function withGovernance<T>( approvedForOp = true; } else { await auditDeny(permissionCheck.reason || "Operation not allowed"); - throw new Error( - permissionCheck.reason || "Operation not allowed", - ); + throw new Error(permissionCheck.reason || "Operation not allowed"); } } @@ -121,16 +116,12 @@ export async function withGovernance<T>( // 5. Check secret expiration — BLOCKS the operation if any secret is expired if (governanceConfig.secrets.check_expiration && config.secrets?.keys) { const secretKeys = Object.keys(config.secrets.keys); - const expirations = await checkSecretExpiration( - config.governance, - secretKeys, - config.secrets, - ); + const expirations = await checkSecretExpiration(config.governance, secretKeys, config.secrets); if (hasExpiredSecrets(expirations)) { const warnings = formatSecretExpirationWarnings(expirations); console.warn("\n" + warnings); - + // Block operation if secrets are expired await auditDeny("Expired secrets detected", { expired_secrets: expirations.filter((e) => e.expired).map((e) => e.key), @@ -147,7 +138,7 @@ export async function withGovernance<T>( result = await operation(); } catch (err) { error = err instanceof Error ? err.message : String(err); - + // Log failure await logAuditEvent(governanceConfig, { operation: context.operation, @@ -163,7 +154,7 @@ export async function withGovernance<T>( // 6. Record usage and log success await recordUsage(config.governance, context.estimatedTokens || 0); - + await logAuditEvent(governanceConfig, { operation: context.operation, environment: governanceConfig.environment, @@ -200,10 +191,7 @@ export async function checkGovernance( } // 2. Check budget limits - const budgetCheck = await checkBudgetLimits( - config.governance, - context.estimatedTokens || 0, - ); + const budgetCheck = await checkBudgetLimits(config.governance, context.estimatedTokens || 0); if (!budgetCheck.allowed) { return { allowed: false, @@ -212,10 +200,7 @@ export async function checkGovernance( } // 3. Check operation permissions - const permissionCheck = checkOperationAllowed( - governanceConfig, - context.operationType, - ); + const permissionCheck = checkOperationAllowed(governanceConfig, context.operationType); if (!permissionCheck.allowed && !permissionCheck.requiresApproval) { return { allowed: false, @@ -230,11 +215,7 @@ export async function checkGovernance( // 4. Check secret expiration if (governanceConfig.secrets.check_expiration && config.secrets?.keys) { const secretKeys = Object.keys(config.secrets.keys); - const expirations = await checkSecretExpiration( - config.governance, - secretKeys, - config.secrets, - ); + const expirations = await checkSecretExpiration(config.governance, secretKeys, config.secrets); if (hasExpiredSecrets(expirations)) { return { diff --git a/src/governance.ts b/src/governance.ts index 52298f3c..717afc79 100644 --- a/src/governance.ts +++ b/src/governance.ts @@ -58,9 +58,7 @@ export const DEFAULT_GOVERNANCE: Required<GovernanceConfig> = { /** * Merge user config with defaults (synchronous version) */ -export function mergeGovernanceConfig( - userConfig?: GovernanceConfig, -): Required<GovernanceConfig> { +export function mergeGovernanceConfig(userConfig?: GovernanceConfig): Required<GovernanceConfig> { if (!userConfig) { return DEFAULT_GOVERNANCE; } @@ -144,8 +142,7 @@ export function checkOperationAllowed( case "write": if (!access.write) { - const requiresApproval = - env === "prod" && config.approval.production_writes; + const requiresApproval = env === "prod" && config.approval.production_writes; if (requiresApproval) { return { allowed: false, @@ -206,9 +203,7 @@ export async function getCurrentGitBranch(): Promise<string | null> { /** * Detect environment from git branch */ -export function detectEnvironmentFromBranch( - branch: string, -): "dev" | "staging" | "prod" | null { +export function detectEnvironmentFromBranch(branch: string): "dev" | "staging" | "prod" | null { const lowerBranch = branch.toLowerCase(); // Production branches @@ -222,11 +217,7 @@ export function detectEnvironmentFromBranch( } // Staging branches - if ( - lowerBranch === "staging" || - lowerBranch === "stage" || - lowerBranch.startsWith("release/") - ) { + if (lowerBranch === "staging" || lowerBranch === "stage" || lowerBranch.startsWith("release/")) { return "staging"; } @@ -268,9 +259,7 @@ export async function getCurrentEnvironment( /** * Format governance status for display */ -export function formatGovernanceStatus( - config: Required<GovernanceConfig>, -): string { +export function formatGovernanceStatus(config: Required<GovernanceConfig>): string { if (!config.enabled) { return "Governance: disabled"; } diff --git a/src/heal.test.ts b/src/heal.test.ts index 238b4a62..96f28357 100644 --- a/src/heal.test.ts +++ b/src/heal.test.ts @@ -24,7 +24,12 @@ describe("kit heal — classification (safe / gated / fail-closed boundary)", () }); it("missing .gitignore pattern → safe", () => { - const f = r({ name: ".env gitignored", category: "exposure", status: "warn", detail: ".gitignore not found" }); + const f = r({ + name: ".env gitignored", + category: "exposure", + status: "warn", + detail: ".gitignore not found", + }); assert.equal(classify(f), "safe"); assert.ok(safeRecipe(f)); }); diff --git a/src/heal.ts b/src/heal.ts index ede6d766..2cb4c783 100644 --- a/src/heal.ts +++ b/src/heal.ts @@ -123,7 +123,9 @@ export async function runHeal( await syncSecurityFindings(lastResults); // track + auto-close (fail-open) const actionable = actionableFindings(lastResults); - log(` scan ${((Date.now() - t0) / 1000).toFixed(1)}s — ${actionable.length} actionable finding(s)`); + log( + ` scan ${((Date.now() - t0) / 1000).toFixed(1)}s — ${actionable.length} actionable finding(s)`, + ); failClosed = actionable.filter(isFailClosed); gated = actionable.filter((r) => classify(r) === "gated").map(toGated); diff --git a/src/health-sensors/bitbucket-pipelines.test.ts b/src/health-sensors/bitbucket-pipelines.test.ts index d3c6473c..3f364218 100644 --- a/src/health-sensors/bitbucket-pipelines.test.ts +++ b/src/health-sensors/bitbucket-pipelines.test.ts @@ -10,9 +10,24 @@ import type { HealthCtx, HealthDeps, HttpResponse } from "../health.js"; const body = JSON.stringify({ values: [ - { build_number: 42, state: { name: "COMPLETED", result: { name: "FAILED" } }, target: { ref_name: "main" }, created_on: "2026-06-22T08:00:00Z" }, - { build_number: 41, state: { name: "COMPLETED", result: { name: "SUCCESSFUL" } }, target: { ref_name: "main" }, created_on: "2026-06-21T08:00:00Z" }, - { build_number: 43, state: { name: "IN_PROGRESS" }, target: { ref_name: "feat" }, created_on: "2026-06-22T09:00:00Z" }, + { + build_number: 42, + state: { name: "COMPLETED", result: { name: "FAILED" } }, + target: { ref_name: "main" }, + created_on: "2026-06-22T08:00:00Z", + }, + { + build_number: 41, + state: { name: "COMPLETED", result: { name: "SUCCESSFUL" } }, + target: { ref_name: "main" }, + created_on: "2026-06-21T08:00:00Z", + }, + { + build_number: 43, + state: { name: "IN_PROGRESS" }, + target: { ref_name: "feat" }, + created_on: "2026-06-22T09:00:00Z", + }, ], }); @@ -21,7 +36,12 @@ function deps(over: { remoteOk?: boolean; remote?: string; http?: HttpResponse } runCli: async (cmd, args) => { if (cmd === "git" && args[0] === "remote") { const ok = over.remoteOk ?? true; - return { stdout: over.remote ?? "git@bitbucket.org:acme/web.git", stderr: "", exitCode: ok ? 0 : 1, ok }; + return { + stdout: over.remote ?? "git@bitbucket.org:acme/web.git", + stderr: "", + exitCode: ok ? 0 : 1, + ok, + }; } return { stdout: "", stderr: "", exitCode: 0, ok: true }; }, @@ -36,11 +56,27 @@ describe("parseBitbucketPipelines / latestFailedBitbucket", () => { assert.equal(f?.build_number, 42); }); it("returns null when the latest completed pipeline succeeded", () => { - const ok = JSON.stringify({ values: [{ build_number: 41, state: { name: "COMPLETED", result: { name: "SUCCESSFUL" } }, created_on: "2026-06-21T08:00:00Z" }] }); + const ok = JSON.stringify({ + values: [ + { + build_number: 41, + state: { name: "COMPLETED", result: { name: "SUCCESSFUL" } }, + created_on: "2026-06-21T08:00:00Z", + }, + ], + }); assert.equal(latestFailedBitbucket(parseBitbucketPipelines(ok)), null); }); it("treats STOPPED (cancelled) as not-red", () => { - const stopped = JSON.stringify({ values: [{ build_number: 40, state: { name: "COMPLETED", result: { name: "STOPPED" } }, created_on: "2026-06-22T08:00:00Z" }] }); + const stopped = JSON.stringify({ + values: [ + { + build_number: 40, + state: { name: "COMPLETED", result: { name: "STOPPED" } }, + created_on: "2026-06-22T08:00:00Z", + }, + ], + }); assert.equal(latestFailedBitbucket(parseBitbucketPipelines(stopped)), null); }); }); @@ -50,7 +86,10 @@ describe("bitbucketAuthHeader", () => { assert.equal(bitbucketAuthHeader({ BITBUCKET_TOKEN: "t" } as NodeJS.ProcessEnv), "Bearer t"); }); it("falls back to basic from username + app password", () => { - const h = bitbucketAuthHeader({ BITBUCKET_USERNAME: "u", BITBUCKET_APP_PASSWORD: "p" } as NodeJS.ProcessEnv); + const h = bitbucketAuthHeader({ + BITBUCKET_USERNAME: "u", + BITBUCKET_APP_PASSWORD: "p", + } as NodeJS.ProcessEnv); assert.equal(h, `Basic ${Buffer.from("u:p").toString("base64")}`); }); it("returns null with no creds", () => { @@ -81,7 +120,10 @@ describe("bitbucketSensor.probe", () => { it("is unknown on a non-OK API response", async () => { process.env.BITBUCKET_TOKEN = "bbt"; - const out = await bitbucketSensor.probe(ctx, deps({ http: { ok: false, status: 403, body: "" } })); + const out = await bitbucketSensor.probe( + ctx, + deps({ http: { ok: false, status: 403, body: "" } }), + ); assert.equal(out[0].status, "unknown"); assert.match(out[0].title, /403/); }); diff --git a/src/health-sensors/bitbucket-pipelines.ts b/src/health-sensors/bitbucket-pipelines.ts index be0b8cfa..f56524a6 100644 --- a/src/health-sensors/bitbucket-pipelines.ts +++ b/src/health-sensors/bitbucket-pipelines.ts @@ -34,7 +34,9 @@ export function latestFailedBitbucket(pipelines: BbPipeline[]): BbPipeline | nul export function bitbucketAuthHeader(env: NodeJS.ProcessEnv): string | null { if (env.BITBUCKET_TOKEN) return `Bearer ${env.BITBUCKET_TOKEN}`; if (env.BITBUCKET_USERNAME && env.BITBUCKET_APP_PASSWORD) { - const basic = Buffer.from(`${env.BITBUCKET_USERNAME}:${env.BITBUCKET_APP_PASSWORD}`).toString("base64"); + const basic = Buffer.from(`${env.BITBUCKET_USERNAME}:${env.BITBUCKET_APP_PASSWORD}`).toString( + "base64", + ); return `Basic ${basic}`; } return null; @@ -46,50 +48,64 @@ export const bitbucketSensor: HealthSensor = { const remoteRes = await deps.runCli("git", ["remote", "get-url", "origin"]); const slug = remoteRes.ok ? parseGitRemote(remoteRes.stdout) : null; if (!slug) { - return [{ - sensor: "bitbucket-pipelines", - source: "(no git remote)", - status: "unknown", - title: "Bitbucket Pipelines probe could not resolve the remote", - detail: "git remote get-url origin failed", - }]; + return [ + { + sensor: "bitbucket-pipelines", + source: "(no git remote)", + status: "unknown", + title: "Bitbucket Pipelines probe could not resolve the remote", + detail: "git remote get-url origin failed", + }, + ]; } const source = `${slug.host}/${slug.path}`; const auth = bitbucketAuthHeader(process.env); if (!auth) { - return [{ - sensor: "bitbucket-pipelines", - source, - status: "unknown", - title: "Bitbucket Pipelines probe skipped: no credentials", - detail: "set BITBUCKET_TOKEN, or BITBUCKET_USERNAME + BITBUCKET_APP_PASSWORD", - }]; + return [ + { + sensor: "bitbucket-pipelines", + source, + status: "unknown", + title: "Bitbucket Pipelines probe skipped: no credentials", + detail: "set BITBUCKET_TOKEN, or BITBUCKET_USERNAME + BITBUCKET_APP_PASSWORD", + }, + ]; } - const url = - `https://api.bitbucket.org/2.0/repositories/${slug.path}/pipelines/?sort=-created_on&pagelen=20`; + const url = `https://api.bitbucket.org/2.0/repositories/${slug.path}/pipelines/?sort=-created_on&pagelen=20`; const res = await deps.httpGet(url, { Authorization: auth }); if (!res.ok) { - return [{ - sensor: "bitbucket-pipelines", - source, - status: "unknown", - title: `Bitbucket Pipelines API returned HTTP ${res.status}`, - detail: "check the token scope (pipeline:read) / repo access", - }]; + return [ + { + sensor: "bitbucket-pipelines", + source, + status: "unknown", + title: `Bitbucket Pipelines API returned HTTP ${res.status}`, + detail: "check the token scope (pipeline:read) / repo access", + }, + ]; } const failed = latestFailedBitbucket(parseBitbucketPipelines(res.body)); if (!failed) { - return [{ sensor: "bitbucket-pipelines", source, status: "green", title: "Bitbucket Pipelines: latest run green" }]; + return [ + { + sensor: "bitbucket-pipelines", + source, + status: "green", + title: "Bitbucket Pipelines: latest run green", + }, + ]; } const ref = failed.target?.ref_name ?? "?"; - return [{ - sensor: "bitbucket-pipelines", - source, - status: "red", - severity: "high", - title: `Bitbucket Pipelines failing on ${ref}`, - detail: `pipeline #${failed.build_number ?? "?"} ${failed.state?.result?.name} (${failed.created_on})`, - suggestedClass: "code", - }]; + return [ + { + sensor: "bitbucket-pipelines", + source, + status: "red", + severity: "high", + title: `Bitbucket Pipelines failing on ${ref}`, + detail: `pipeline #${failed.build_number ?? "?"} ${failed.state?.result?.name} (${failed.created_on})`, + suggestedClass: "code", + }, + ]; }, }; diff --git a/src/health-sensors/github-actions.test.ts b/src/health-sensors/github-actions.test.ts index 4a092b43..5b7a46b1 100644 --- a/src/health-sensors/github-actions.test.ts +++ b/src/health-sensors/github-actions.test.ts @@ -9,9 +9,27 @@ import { import type { HealthCtx, HealthDeps } from "../health.js"; const runs = JSON.stringify([ - { name: "CI", status: "completed", conclusion: "failure", createdAt: "2026-06-21T06:50:00Z", databaseId: 9 }, - { name: "CI", status: "completed", conclusion: "success", createdAt: "2026-06-20T06:50:00Z", databaseId: 8 }, - { name: "Security", status: "completed", conclusion: "success", createdAt: "2026-06-21T05:00:00Z", databaseId: 7 }, + { + name: "CI", + status: "completed", + conclusion: "failure", + createdAt: "2026-06-21T06:50:00Z", + databaseId: 9, + }, + { + name: "CI", + status: "completed", + conclusion: "success", + createdAt: "2026-06-20T06:50:00Z", + databaseId: 8, + }, + { + name: "Security", + status: "completed", + conclusion: "success", + createdAt: "2026-06-21T05:00:00Z", + databaseId: 7, + }, ]); function deps(over: Record<string, { stdout: string; ok: boolean }> = {}): HealthDeps { @@ -32,7 +50,10 @@ describe("parseGitHubRuns / failingWorkflows", () => { const parsed = parseGitHubRuns(runs); assert.equal(parsed.length, 3); const failing = failingWorkflows(parsed); - assert.deepEqual(failing.map((f) => f.name), ["CI"]); // newest CI is failure; Security is green + assert.deepEqual( + failing.map((f) => f.name), + ["CI"], + ); // newest CI is failure; Security is green }); it("returns [] when the JSON is empty", () => { @@ -40,19 +61,47 @@ describe("parseGitHubRuns / failingWorkflows", () => { }); it("excludes workflows not in the active set when one is provided", () => { - const parsed = parseGitHubRuns(JSON.stringify([ - { name: "CI", status: "completed", conclusion: "failure", createdAt: "2026-06-21T06:50:00Z", databaseId: 9 }, - { name: "Crons", status: "completed", conclusion: "failure", createdAt: "2026-06-14T06:50:00Z", databaseId: 1 }, - ])); + const parsed = parseGitHubRuns( + JSON.stringify([ + { + name: "CI", + status: "completed", + conclusion: "failure", + createdAt: "2026-06-21T06:50:00Z", + databaseId: 9, + }, + { + name: "Crons", + status: "completed", + conclusion: "failure", + createdAt: "2026-06-14T06:50:00Z", + databaseId: 1, + }, + ]), + ); const active = new Set(["CI"]); // Crons is disabled - assert.deepEqual(failingWorkflows(parsed, active).map((f) => f.name), ["CI"]); + assert.deepEqual( + failingWorkflows(parsed, active).map((f) => f.name), + ["CI"], + ); }); it("does not filter when the active set is empty/unknown (fail open to reporting)", () => { - const parsed = parseGitHubRuns(JSON.stringify([ - { name: "CI", status: "completed", conclusion: "failure", createdAt: "2026-06-21T06:50:00Z", databaseId: 9 }, - ])); - assert.deepEqual(failingWorkflows(parsed, new Set()).map((f) => f.name), ["CI"]); + const parsed = parseGitHubRuns( + JSON.stringify([ + { + name: "CI", + status: "completed", + conclusion: "failure", + createdAt: "2026-06-21T06:50:00Z", + databaseId: 9, + }, + ]), + ); + assert.deepEqual( + failingWorkflows(parsed, new Set()).map((f) => f.name), + ["CI"], + ); }); }); @@ -76,10 +125,13 @@ describe("activeWorkflowNames", () => { describe("githubActionsSensor.probe", () => { it("emits one red finding per failing workflow", async () => { - const out = await githubActionsSensor.probe(ctx, deps({ - "gh repo": { stdout: JSON.stringify({ nameWithOwner: "acme/webapp" }), ok: true }, - "gh run": { stdout: runs, ok: true }, - })); + const out = await githubActionsSensor.probe( + ctx, + deps({ + "gh repo": { stdout: JSON.stringify({ nameWithOwner: "acme/webapp" }), ok: true }, + "gh run": { stdout: runs, ok: true }, + }), + ); const red = out.filter((f) => f.status === "red"); assert.equal(red.length, 1); assert.equal(red[0].sensor, "github-actions"); @@ -90,38 +142,68 @@ describe("githubActionsSensor.probe", () => { it("does not flag a disabled workflow whose last run failed", async () => { const mixed = JSON.stringify([ - { name: "CI", status: "completed", conclusion: "failure", createdAt: "2026-06-21T06:50:00Z", databaseId: 9 }, - { name: "Crons", status: "completed", conclusion: "failure", createdAt: "2026-06-14T06:50:00Z", databaseId: 1 }, + { + name: "CI", + status: "completed", + conclusion: "failure", + createdAt: "2026-06-21T06:50:00Z", + databaseId: 9, + }, + { + name: "Crons", + status: "completed", + conclusion: "failure", + createdAt: "2026-06-14T06:50:00Z", + databaseId: 1, + }, ]); const workflows = JSON.stringify([ { name: "CI", state: "active" }, { name: "Crons", state: "disabled_manually" }, ]); - const out = await githubActionsSensor.probe(ctx, deps({ - "gh repo": { stdout: JSON.stringify({ nameWithOwner: "acme/webapp" }), ok: true }, - "gh workflow": { stdout: workflows, ok: true }, - "gh run": { stdout: mixed, ok: true }, - })); + const out = await githubActionsSensor.probe( + ctx, + deps({ + "gh repo": { stdout: JSON.stringify({ nameWithOwner: "acme/webapp" }), ok: true }, + "gh workflow": { stdout: workflows, ok: true }, + "gh run": { stdout: mixed, ok: true }, + }), + ); const red = out.filter((f) => f.status === "red"); - assert.deepEqual(red.map((f) => f.title), ["GitHub Actions workflow failing: CI"]); + assert.deepEqual( + red.map((f) => f.title), + ["GitHub Actions workflow failing: CI"], + ); }); it("emits a single green finding when nothing fails", async () => { const allGreen = JSON.stringify([ - { name: "CI", status: "completed", conclusion: "success", createdAt: "2026-06-21T06:50:00Z", databaseId: 9 }, + { + name: "CI", + status: "completed", + conclusion: "success", + createdAt: "2026-06-21T06:50:00Z", + databaseId: 9, + }, ]); - const out = await githubActionsSensor.probe(ctx, deps({ - "gh repo": { stdout: JSON.stringify({ nameWithOwner: "acme/webapp" }), ok: true }, - "gh run": { stdout: allGreen, ok: true }, - })); + const out = await githubActionsSensor.probe( + ctx, + deps({ + "gh repo": { stdout: JSON.stringify({ nameWithOwner: "acme/webapp" }), ok: true }, + "gh run": { stdout: allGreen, ok: true }, + }), + ); assert.equal(out.length, 1); assert.equal(out[0].status, "green"); }); it("returns unknown when gh is not authed", async () => { - const out = await githubActionsSensor.probe(ctx, deps({ - "gh repo": { stdout: "", ok: false }, - })); + const out = await githubActionsSensor.probe( + ctx, + deps({ + "gh repo": { stdout: "", ok: false }, + }), + ); assert.equal(out.length, 1); assert.equal(out[0].status, "unknown"); }); diff --git a/src/health-sensors/gitlab-ci.test.ts b/src/health-sensors/gitlab-ci.test.ts index 66d856c8..824b9811 100644 --- a/src/health-sensors/gitlab-ci.test.ts +++ b/src/health-sensors/gitlab-ci.test.ts @@ -14,7 +14,12 @@ function deps(over: { remoteOk?: boolean; remote?: string; http?: HttpResponse } runCli: async (cmd, args) => { if (cmd === "git" && args[0] === "remote") { const ok = over.remoteOk ?? true; - return { stdout: over.remote ?? "git@gitlab.com:acme/web.git", stderr: "", exitCode: ok ? 0 : 1, ok }; + return { + stdout: over.remote ?? "git@gitlab.com:acme/web.git", + stderr: "", + exitCode: ok ? 0 : 1, + ok, + }; } return { stdout: "", stderr: "", exitCode: 0, ok: true }; }, @@ -29,7 +34,9 @@ describe("parseGitlabPipelines / latestFailedPipeline", () => { assert.equal(f?.id, 9); }); it("returns null when the latest terminal pipeline succeeded", () => { - const json = JSON.stringify([{ id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }]); + const json = JSON.stringify([ + { id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }, + ]); assert.equal(latestFailedPipeline(parseGitlabPipelines(json)), null); }); it("returns [] on garbage", () => { @@ -53,7 +60,9 @@ describe("gitlabSensor.probe", () => { it("emits green when the latest terminal pipeline passed", async () => { process.env.GITLAB_TOKEN = "glpat-xxx"; - const ok = JSON.stringify([{ id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }]); + const ok = JSON.stringify([ + { id: 8, status: "success", ref: "main", created_at: "2026-06-21T08:00:00Z" }, + ]); const out = await gitlabSensor.probe(ctx, deps({ http: { ok: true, status: 200, body: ok } })); assert.equal(out[0].status, "green"); }); diff --git a/src/health-sensors/gitlab-ci.ts b/src/health-sensors/gitlab-ci.ts index 85f288d4..3b541d45 100644 --- a/src/health-sensors/gitlab-ci.ts +++ b/src/health-sensors/gitlab-ci.ts @@ -36,48 +36,58 @@ export const gitlabSensor: HealthSensor = { const remoteRes = await deps.runCli("git", ["remote", "get-url", "origin"]); const slug = remoteRes.ok ? parseGitRemote(remoteRes.stdout) : null; if (!slug) { - return [{ - sensor: "gitlab-ci", - source: "(no git remote)", - status: "unknown", - title: "GitLab CI probe could not resolve the remote", - detail: "git remote get-url origin failed", - }]; + return [ + { + sensor: "gitlab-ci", + source: "(no git remote)", + status: "unknown", + title: "GitLab CI probe could not resolve the remote", + detail: "git remote get-url origin failed", + }, + ]; } const source = `${slug.host}/${slug.path}`; const token = process.env.GITLAB_TOKEN; if (!token) { - return [{ - sensor: "gitlab-ci", - source, - status: "unknown", - title: "GitLab CI probe skipped: GITLAB_TOKEN not set", - detail: "set GITLAB_TOKEN (read_api) to enable the GitLab CI sensor", - }]; + return [ + { + sensor: "gitlab-ci", + source, + status: "unknown", + title: "GitLab CI probe skipped: GITLAB_TOKEN not set", + detail: "set GITLAB_TOKEN (read_api) to enable the GitLab CI sensor", + }, + ]; } const url = `https://${slug.host}/api/v4/projects/${encodeURIComponent(slug.path)}/pipelines?per_page=20`; const res = await deps.httpGet(url, { "PRIVATE-TOKEN": token }); if (!res.ok) { - return [{ - sensor: "gitlab-ci", - source, - status: "unknown", - title: `GitLab CI API returned HTTP ${res.status}`, - detail: "check GITLAB_TOKEN scope / project access", - }]; + return [ + { + sensor: "gitlab-ci", + source, + status: "unknown", + title: `GitLab CI API returned HTTP ${res.status}`, + detail: "check GITLAB_TOKEN scope / project access", + }, + ]; } const failed = latestFailedPipeline(parseGitlabPipelines(res.body)); if (!failed) { - return [{ sensor: "gitlab-ci", source, status: "green", title: "GitLab CI: latest pipeline green" }]; + return [ + { sensor: "gitlab-ci", source, status: "green", title: "GitLab CI: latest pipeline green" }, + ]; } - return [{ - sensor: "gitlab-ci", - source, - status: "red", - severity: "high", - title: `GitLab CI pipeline failing on ${failed.ref}`, - detail: `pipeline #${failed.id} failed (${failed.created_at})`, - suggestedClass: "code", - }]; + return [ + { + sensor: "gitlab-ci", + source, + status: "red", + severity: "high", + title: `GitLab CI pipeline failing on ${failed.ref}`, + detail: `pipeline #${failed.id} failed (${failed.created_at})`, + suggestedClass: "code", + }, + ]; }, }; diff --git a/src/health-sensors/remote.test.ts b/src/health-sensors/remote.test.ts index 117247e1..e48d9418 100644 --- a/src/health-sensors/remote.test.ts +++ b/src/health-sensors/remote.test.ts @@ -4,19 +4,31 @@ import { parseGitRemote } from "./remote.js"; describe("parseGitRemote", () => { it("parses an SSH remote", () => { - assert.deepEqual(parseGitRemote("git@gitlab.com:acme/web.git"), { host: "gitlab.com", path: "acme/web" }); + assert.deepEqual(parseGitRemote("git@gitlab.com:acme/web.git"), { + host: "gitlab.com", + path: "acme/web", + }); }); it("parses an HTTPS remote and strips .git", () => { - assert.deepEqual(parseGitRemote("https://bitbucket.org/acme/web.git"), { host: "bitbucket.org", path: "acme/web" }); + assert.deepEqual(parseGitRemote("https://bitbucket.org/acme/web.git"), { + host: "bitbucket.org", + path: "acme/web", + }); }); it("keeps GitLab nested subgroups", () => { - assert.deepEqual(parseGitRemote("git@gitlab.com:acme/team/web.git"), { host: "gitlab.com", path: "acme/team/web" }); + assert.deepEqual(parseGitRemote("git@gitlab.com:acme/team/web.git"), { + host: "gitlab.com", + path: "acme/team/web", + }); }); it("strips an embedded HTTPS user", () => { - assert.deepEqual(parseGitRemote("https://x-token-auth@bitbucket.org/acme/web"), { host: "bitbucket.org", path: "acme/web" }); + assert.deepEqual(parseGitRemote("https://x-token-auth@bitbucket.org/acme/web"), { + host: "bitbucket.org", + path: "acme/web", + }); }); it("returns null for junk", () => { diff --git a/src/health-sensors/remote.ts b/src/health-sensors/remote.ts index 79928048..864d1643 100644 --- a/src/health-sensors/remote.ts +++ b/src/health-sensors/remote.ts @@ -26,5 +26,8 @@ export function parseGitRemote(url: string): RemoteSlug | null { } function stripGit(p: string): string { - return p.replace(/\.git$/, "").replace(/^\/+/, "").replace(/\/+$/, ""); + return p + .replace(/\.git$/, "") + .replace(/^\/+/, "") + .replace(/\/+$/, ""); } diff --git a/src/health-sensors/resend.ts b/src/health-sensors/resend.ts index eac32487..8a24387e 100644 --- a/src/health-sensors/resend.ts +++ b/src/health-sensors/resend.ts @@ -25,37 +25,52 @@ export const resendSensor: HealthSensor = { async probe(_ctx, deps): Promise<HealthFinding[]> { const key = process.env.RESEND_API_KEY; if (!key) { - return [{ - sensor: "resend", - source: "resend", - status: "unknown", - title: "Resend probe skipped: RESEND_API_KEY not set", - detail: "set RESEND_API_KEY to enable the Resend sensor", - }]; + return [ + { + sensor: "resend", + source: "resend", + status: "unknown", + title: "Resend probe skipped: RESEND_API_KEY not set", + detail: "set RESEND_API_KEY to enable the Resend sensor", + }, + ]; } - const res = await deps.httpGet("https://api.resend.com/domains", { Authorization: `Bearer ${key}` }); + const res = await deps.httpGet("https://api.resend.com/domains", { + Authorization: `Bearer ${key}`, + }); if (!res.ok) { - return [{ - sensor: "resend", - source: "resend", - status: "unknown", - title: `Resend API returned HTTP ${res.status}`, - detail: "check RESEND_API_KEY", - }]; + return [ + { + sensor: "resend", + source: "resend", + status: "unknown", + title: `Resend API returned HTTP ${res.status}`, + detail: "check RESEND_API_KEY", + }, + ]; } const bad = unverifiedDomains(parseResendDomains(res.body)); if (bad.length === 0) { - return [{ sensor: "resend", source: "resend", status: "green", title: "Resend: all sending domains verified" }]; + return [ + { + sensor: "resend", + source: "resend", + status: "green", + title: "Resend: all sending domains verified", + }, + ]; } const names = bad.map((d) => `${d.name ?? "?"}=${d.status ?? "?"}`).join(", "); - return [{ - sensor: "resend", - source: "resend", - status: "red", - severity: "high", - title: `Resend: ${bad.length} domain(s) not verified`, - detail: `${names} — re-check DNS (SPF/DKIM/DMARC); customer/DNS action, not a code fix`, - suggestedClass: "human", - }]; + return [ + { + sensor: "resend", + source: "resend", + status: "red", + severity: "high", + title: `Resend: ${bad.length} domain(s) not verified`, + detail: `${names} — re-check DNS (SPF/DKIM/DMARC); customer/DNS action, not a code fix`, + suggestedClass: "human", + }, + ]; }, }; diff --git a/src/health-sensors/sentry.test.ts b/src/health-sensors/sentry.test.ts index df6e5cf9..3ee6f130 100644 --- a/src/health-sensors/sentry.test.ts +++ b/src/health-sensors/sentry.test.ts @@ -46,7 +46,10 @@ describe("sentrySensor.probe", () => { it("emits green when none", async () => { setEnv(); - const out = await sentrySensor.probe(ctx, deps({ http: { ok: true, status: 200, body: "[]" } })); + const out = await sentrySensor.probe( + ctx, + deps({ http: { ok: true, status: 200, body: "[]" } }), + ); assert.equal(out[0].status, "green"); }); diff --git a/src/health-sensors/sentry.ts b/src/health-sensors/sentry.ts index fe6a5958..0d90ed46 100644 --- a/src/health-sensors/sentry.ts +++ b/src/health-sensors/sentry.ts @@ -25,40 +25,55 @@ export const sentrySensor: HealthSensor = { const base = (process.env.SENTRY_URL || "https://sentry.io").replace(/\/+$/, ""); const source = org && project ? `${org}/${project}` : "(sentry org/project unset)"; if (!token || !org || !project) { - return [{ - sensor: "sentry", - source, - status: "unknown", - title: "Sentry probe skipped: SENTRY_AUTH_TOKEN / SENTRY_ORG / SENTRY_PROJECT not all set", - detail: "set the three to enable the Sentry sensor", - }]; + return [ + { + sensor: "sentry", + source, + status: "unknown", + title: + "Sentry probe skipped: SENTRY_AUTH_TOKEN / SENTRY_ORG / SENTRY_PROJECT not all set", + detail: "set the three to enable the Sentry sensor", + }, + ]; } // New unresolved issues in the last 24h = a fresh-errors signal (not the whole backlog). const q = encodeURIComponent("is:unresolved firstSeen:-24h"); const url = `${base}/api/0/projects/${encodeURIComponent(org)}/${encodeURIComponent(project)}/issues/?query=${q}&statsPeriod=24h`; const res = await deps.httpGet(url, { Authorization: `Bearer ${token}` }); if (!res.ok) { - return [{ - sensor: "sentry", - source, - status: "unknown", - title: `Sentry API returned HTTP ${res.status}`, - detail: "check SENTRY_AUTH_TOKEN scope / org+project / SENTRY_URL region", - }]; + return [ + { + sensor: "sentry", + source, + status: "unknown", + title: `Sentry API returned HTTP ${res.status}`, + detail: "check SENTRY_AUTH_TOKEN scope / org+project / SENTRY_URL region", + }, + ]; } const issues = parseSentryIssues(res.body); if (issues.length === 0) { - return [{ sensor: "sentry", source, status: "green", title: "Sentry: no new unresolved issues in 24h" }]; + return [ + { + sensor: "sentry", + source, + status: "green", + title: "Sentry: no new unresolved issues in 24h", + }, + ]; } const sample = issues[0]?.title ? ` (e.g. "${issues[0].title}")` : ""; - return [{ - sensor: "sentry", - source, - status: "red", - severity: "high", - title: `Sentry: ${issues.length} new unresolved issue(s) in 24h${sample}`, - detail: "triage at the Sentry dashboard; may be a real regression or benign noise to filter", - suggestedClass: "code", - }]; + return [ + { + sensor: "sentry", + source, + status: "red", + severity: "high", + title: `Sentry: ${issues.length} new unresolved issue(s) in 24h${sample}`, + detail: + "triage at the Sentry dashboard; may be a real regression or benign noise to filter", + suggestedClass: "code", + }, + ]; }, }; diff --git a/src/health-sensors/supabase-advisor.test.ts b/src/health-sensors/supabase-advisor.test.ts index e3fb3972..97b6722d 100644 --- a/src/health-sensors/supabase-advisor.test.ts +++ b/src/health-sensors/supabase-advisor.test.ts @@ -53,7 +53,10 @@ describe("supabaseAdvisorSensor.probe", () => { it("emits green when no ERROR-level advisors", async () => { setEnv(); const body = JSON.stringify({ lints: [{ level: "WARN", title: "minor" }] }); - const out = await supabaseAdvisorSensor.probe(ctx, deps({ http: { ok: true, status: 200, body } })); + const out = await supabaseAdvisorSensor.probe( + ctx, + deps({ http: { ok: true, status: 200, body } }), + ); assert.equal(out[0].status, "green"); }); @@ -64,7 +67,10 @@ describe("supabaseAdvisorSensor.probe", () => { it("is unknown on a non-OK API response", async () => { setEnv(); - const out = await supabaseAdvisorSensor.probe(ctx, deps({ http: { ok: false, status: 401, body: "" } })); + const out = await supabaseAdvisorSensor.probe( + ctx, + deps({ http: { ok: false, status: 401, body: "" } }), + ); assert.equal(out[0].status, "unknown"); assert.match(out[0].title, /401/); }); diff --git a/src/health-sensors/supabase-advisor.ts b/src/health-sensors/supabase-advisor.ts index 9dbb9ace..b3d50b3d 100644 --- a/src/health-sensors/supabase-advisor.ts +++ b/src/health-sensors/supabase-advisor.ts @@ -31,39 +31,54 @@ export const supabaseAdvisorSensor: HealthSensor = { const ref = process.env.SUPABASE_PROJECT_REF; const source = ref ? `supabase/${ref}` : "(supabase project ref unset)"; if (!token || !ref) { - return [{ - sensor: "supabase-advisor", - source, - status: "unknown", - title: "Supabase advisor probe skipped: SUPABASE_ACCESS_TOKEN / SUPABASE_PROJECT_REF not both set", - detail: "set both to enable the Supabase security-advisor sensor", - }]; + return [ + { + sensor: "supabase-advisor", + source, + status: "unknown", + title: + "Supabase advisor probe skipped: SUPABASE_ACCESS_TOKEN / SUPABASE_PROJECT_REF not both set", + detail: "set both to enable the Supabase security-advisor sensor", + }, + ]; } // Management API security advisors (the RLS/exposure lints the dashboard shows). const url = `https://api.supabase.com/v1/projects/${encodeURIComponent(ref)}/advisors/security`; const res = await deps.httpGet(url, { Authorization: `Bearer ${token}` }); if (!res.ok) { - return [{ - sensor: "supabase-advisor", - source, - status: "unknown", - title: `Supabase advisor API returned HTTP ${res.status}`, - detail: "check SUPABASE_ACCESS_TOKEN scope / SUPABASE_PROJECT_REF", - }]; + return [ + { + sensor: "supabase-advisor", + source, + status: "unknown", + title: `Supabase advisor API returned HTTP ${res.status}`, + detail: "check SUPABASE_ACCESS_TOKEN scope / SUPABASE_PROJECT_REF", + }, + ]; } const errs = errorLints(parseSupabaseLints(res.body)); if (errs.length === 0) { - return [{ sensor: "supabase-advisor", source, status: "green", title: "Supabase: no ERROR-level security advisors" }]; + return [ + { + sensor: "supabase-advisor", + source, + status: "green", + title: "Supabase: no ERROR-level security advisors", + }, + ]; } const sample = errs[0]?.title ? ` (e.g. "${errs[0].title}")` : ""; - return [{ - sensor: "supabase-advisor", - source, - status: "red", - severity: "high", - title: `Supabase: ${errs.length} ERROR-level security advisor(s)${sample}`, - detail: "review Supabase → Advisors; likely RLS-disabled / exposed-data lints — a code/policy fix", - suggestedClass: "code", - }]; + return [ + { + sensor: "supabase-advisor", + source, + status: "red", + severity: "high", + title: `Supabase: ${errs.length} ERROR-level security advisor(s)${sample}`, + detail: + "review Supabase → Advisors; likely RLS-disabled / exposed-data lints — a code/policy fix", + suggestedClass: "code", + }, + ]; }, }; diff --git a/src/health-sensors/tls-cert.ts b/src/health-sensors/tls-cert.ts index f1851bf9..1a503a9e 100644 --- a/src/health-sensors/tls-cert.ts +++ b/src/health-sensors/tls-cert.ts @@ -13,26 +13,48 @@ export function daysUntilExpiry(validTo: string, now: number): number | null { } /** Pure decision: days-left + warn threshold → the finding (no I/O, fully testable). */ -export function evaluateCert(host: string, daysLeft: number | null, warnDays: number): HealthFinding { +export function evaluateCert( + host: string, + daysLeft: number | null, + warnDays: number, +): HealthFinding { const source = `${host}:443`; if (daysLeft === null) { - return { sensor: "tls-cert", source, status: "unknown", title: `TLS cert for ${host}: could not read expiry` }; + return { + sensor: "tls-cert", + source, + status: "unknown", + title: `TLS cert for ${host}: could not read expiry`, + }; } if (daysLeft < 0) { return { - sensor: "tls-cert", source, status: "red", severity: "critical", + sensor: "tls-cert", + source, + status: "red", + severity: "critical", title: `TLS cert for ${host} EXPIRED ${-daysLeft} day(s) ago`, - detail: "renew the certificate now", suggestedClass: "human", + detail: "renew the certificate now", + suggestedClass: "human", }; } if (daysLeft <= warnDays) { return { - sensor: "tls-cert", source, status: "red", severity: "high", + sensor: "tls-cert", + source, + status: "red", + severity: "high", title: `TLS cert for ${host} expires in ${daysLeft} day(s)`, - detail: `renew before expiry (warn threshold ${warnDays}d)`, suggestedClass: "human", + detail: `renew before expiry (warn threshold ${warnDays}d)`, + suggestedClass: "human", }; } - return { sensor: "tls-cert", source, status: "green", title: `TLS cert for ${host} valid (${daysLeft} day(s) left)` }; + return { + sensor: "tls-cert", + source, + status: "green", + title: `TLS cert for ${host} valid (${daysLeft} day(s) left)`, + }; } /** Live cert fetch over a TLS handshake; resolves null on any connect/timeout error. */ @@ -44,22 +66,30 @@ function fetchCert(host: string, timeoutMs: number): Promise<CertInfo | null> { resolve(cert && cert.valid_to ? { validTo: cert.valid_to } : null); }); socket.on("error", () => resolve(null)); - socket.on("timeout", () => { socket.destroy(); resolve(null); }); + socket.on("timeout", () => { + socket.destroy(); + resolve(null); + }); }); } export const tlsCertSensor: HealthSensor = { id: "tls-cert", async probe(_ctx, _deps): Promise<HealthFinding[]> { - const hosts = (process.env.KIT_TLS_HOST ?? "").split(",").map((h) => h.trim()).filter(Boolean); + const hosts = (process.env.KIT_TLS_HOST ?? "") + .split(",") + .map((h) => h.trim()) + .filter(Boolean); if (hosts.length === 0) { - return [{ - sensor: "tls-cert", - source: "(KIT_TLS_HOST unset)", - status: "unknown", - title: "TLS-cert probe skipped: KIT_TLS_HOST not set", - detail: "set KIT_TLS_HOST=example.com[,other.com] to enable cert-expiry checks", - }]; + return [ + { + sensor: "tls-cert", + source: "(KIT_TLS_HOST unset)", + status: "unknown", + title: "TLS-cert probe skipped: KIT_TLS_HOST not set", + detail: "set KIT_TLS_HOST=example.com[,other.com] to enable cert-expiry checks", + }, + ]; } const warnDays = Number(process.env.KIT_TLS_WARN_DAYS ?? "21") || 21; const out: HealthFinding[] = []; diff --git a/src/health-sensors/vercel.test.ts b/src/health-sensors/vercel.test.ts index 6dd9dd4b..5729090c 100644 --- a/src/health-sensors/vercel.test.ts +++ b/src/health-sensors/vercel.test.ts @@ -17,7 +17,11 @@ function deps(over: { http?: HttpResponse } = {}): HealthDeps { httpGet: async () => over.http ?? { ok: true, status: 200, body }, }; } -const linked: HealthCtx = { cwd: "/tmp/repo", config: {}, vercel: { orgId: "team_1", projectId: "prj_abc" } }; +const linked: HealthCtx = { + cwd: "/tmp/repo", + config: {}, + vercel: { orgId: "team_1", projectId: "prj_abc" }, +}; describe("parseVercelDeployments / latestFailedVercel", () => { it("flags the latest TERMINAL deploy when it errored (ignores in-progress BUILDING)", () => { @@ -25,15 +29,21 @@ describe("parseVercelDeployments / latestFailedVercel", () => { assert.equal(f?.uid, "dpl_3"); }); it("returns null when the latest terminal deploy is READY", () => { - const ok = JSON.stringify({ deployments: [{ uid: "x", state: "READY", target: "production", created: 9 }] }); + const ok = JSON.stringify({ + deployments: [{ uid: "x", state: "READY", target: "production", created: 9 }], + }); assert.equal(latestFailedVercel(parseVercelDeployments(ok)), null); }); it("treats CANCELED as not-red", () => { - const c = JSON.stringify({ deployments: [{ uid: "x", state: "CANCELED", target: "production", created: 9 }] }); + const c = JSON.stringify({ + deployments: [{ uid: "x", state: "CANCELED", target: "production", created: 9 }], + }); assert.equal(latestFailedVercel(parseVercelDeployments(c)), null); }); it("supports readyState as the state field alias", () => { - const r = JSON.stringify({ deployments: [{ uid: "x", readyState: "ERROR", target: "production", created: 9 }] }); + const r = JSON.stringify({ + deployments: [{ uid: "x", readyState: "ERROR", target: "production", created: 9 }], + }); assert.equal(latestFailedVercel(parseVercelDeployments(r))?.uid, "x"); }); }); @@ -66,7 +76,10 @@ describe("vercelSensor.probe", () => { it("is unknown on a non-OK API response", async () => { process.env.VERCEL_TOKEN = "vt"; - const out = await vercelSensor.probe(linked, deps({ http: { ok: false, status: 403, body: "" } })); + const out = await vercelSensor.probe( + linked, + deps({ http: { ok: false, status: 403, body: "" } }), + ); assert.equal(out[0].status, "unknown"); assert.match(out[0].title, /403/); }); diff --git a/src/health-sensors/vercel.ts b/src/health-sensors/vercel.ts index 6d94af98..61c733a6 100644 --- a/src/health-sensors/vercel.ts +++ b/src/health-sensors/vercel.ts @@ -40,48 +40,63 @@ export const vercelSensor: HealthSensor = { async probe(ctx, deps): Promise<HealthFinding[]> { const projectId = ctx.vercel?.projectId; if (!projectId) { - return [{ - sensor: "vercel", - source: "(not linked)", - status: "unknown", - title: "Vercel probe skipped: project not linked", - detail: "no .vercel/project.json — run `vercel link`", - }]; + return [ + { + sensor: "vercel", + source: "(not linked)", + status: "unknown", + title: "Vercel probe skipped: project not linked", + detail: "no .vercel/project.json — run `vercel link`", + }, + ]; } const token = process.env.VERCEL_TOKEN; if (!token) { - return [{ - sensor: "vercel", - source: projectId, - status: "unknown", - title: "Vercel probe skipped: VERCEL_TOKEN not set", - detail: "set VERCEL_TOKEN to enable the Vercel sensor", - }]; + return [ + { + sensor: "vercel", + source: projectId, + status: "unknown", + title: "Vercel probe skipped: VERCEL_TOKEN not set", + detail: "set VERCEL_TOKEN to enable the Vercel sensor", + }, + ]; } const team = ctx.vercel?.orgId ? `&teamId=${encodeURIComponent(ctx.vercel.orgId)}` : ""; const url = `https://api.vercel.com/v6/deployments?projectId=${encodeURIComponent(projectId)}&target=production&limit=10${team}`; const res = await deps.httpGet(url, { Authorization: `Bearer ${token}` }); if (!res.ok) { - return [{ - sensor: "vercel", - source: projectId, - status: "unknown", - title: `Vercel API returned HTTP ${res.status}`, - detail: "check VERCEL_TOKEN scope / project + team access", - }]; + return [ + { + sensor: "vercel", + source: projectId, + status: "unknown", + title: `Vercel API returned HTTP ${res.status}`, + detail: "check VERCEL_TOKEN scope / project + team access", + }, + ]; } const failed = latestFailedVercel(parseVercelDeployments(res.body)); if (!failed) { - return [{ sensor: "vercel", source: projectId, status: "green", title: "Vercel: latest production deploy green" }]; + return [ + { + sensor: "vercel", + source: projectId, + status: "green", + title: "Vercel: latest production deploy green", + }, + ]; } - return [{ - sensor: "vercel", - source: projectId, - status: "red", - severity: "high", - title: "Vercel production deploy failed", - detail: `deployment ${failed.uid ?? "?"} state=ERROR`, - suggestedClass: "code", - }]; + return [ + { + sensor: "vercel", + source: projectId, + status: "red", + severity: "high", + title: "Vercel production deploy failed", + detail: `deployment ${failed.uid ?? "?"} state=ERROR`, + suggestedClass: "code", + }, + ]; }, }; diff --git a/src/health-track.test.ts b/src/health-track.test.ts index 484db58c..bb9b5f08 100644 --- a/src/health-track.test.ts +++ b/src/health-track.test.ts @@ -4,7 +4,14 @@ import { actionableHealth, healthFindingToSync } from "./health-track.js"; import type { HealthFinding } from "./health.js"; const findings: HealthFinding[] = [ - { sensor: "github-actions", source: "acme/webapp", status: "red", severity: "high", title: "workflow failing: CI", detail: "latest CI failed" }, + { + sensor: "github-actions", + source: "acme/webapp", + status: "red", + severity: "high", + title: "workflow failing: CI", + detail: "latest CI failed", + }, { sensor: "github-actions", source: "acme/webapp", status: "green", title: "all green" }, { sensor: "github-actions", source: "acme/webapp", status: "unknown", title: "probe errored" }, ]; diff --git a/src/health.test.ts b/src/health.test.ts index 7b45c722..ed0cdcf2 100644 --- a/src/health.test.ts +++ b/src/health.test.ts @@ -11,15 +11,28 @@ const deps: HealthDeps = { describe("runHealth", () => { it("aggregates findings from all sensors", async () => { - const a: HealthSensor = { id: "a", probe: async () => [{ sensor: "a", source: "x", status: "green", title: "ok" }] }; - const b: HealthSensor = { id: "b", probe: async () => [{ sensor: "b", source: "y", status: "red", severity: "high", title: "bad" }] }; + const a: HealthSensor = { + id: "a", + probe: async () => [{ sensor: "a", source: "x", status: "green", title: "ok" }], + }; + const b: HealthSensor = { + id: "b", + probe: async () => [ + { sensor: "b", source: "y", status: "red", severity: "high", title: "bad" }, + ], + }; const out = await runHealth(ctx, [a, b], deps); assert.equal(out.length, 2); assert.deepEqual(out.map((f) => f.status).sort(), ["green", "red"]); }); it("converts a throwing sensor into an unknown finding, never drops it", async () => { - const boom: HealthSensor = { id: "boom", probe: async () => { throw new Error("network down"); } }; + const boom: HealthSensor = { + id: "boom", + probe: async () => { + throw new Error("network down"); + }, + }; const out = await runHealth(ctx, [boom], deps); assert.equal(out.length, 1); assert.equal(out[0].status, "unknown"); @@ -36,17 +49,32 @@ describe("selectSensors", () => { it("excludes github-actions with no git remote and no github context", () => { const sel = selectSensors({ cwd: "/tmp/repo", config: {}, gitRemote: false }); - assert.equal(sel.some((s) => s.id === "github-actions"), false); + assert.equal( + sel.some((s) => s.id === "github-actions"), + false, + ); }); it("includes gitlab-ci only when a .gitlab-ci.yml is present", () => { - assert.ok(selectSensors({ cwd: "/r", config: {}, gitlabCi: true }).some((s) => s.id === "gitlab-ci")); - assert.equal(selectSensors({ cwd: "/r", config: {} }).some((s) => s.id === "gitlab-ci"), false); + assert.ok( + selectSensors({ cwd: "/r", config: {}, gitlabCi: true }).some((s) => s.id === "gitlab-ci"), + ); + assert.equal( + selectSensors({ cwd: "/r", config: {} }).some((s) => s.id === "gitlab-ci"), + false, + ); }); it("includes bitbucket-pipelines only when a bitbucket-pipelines.yml is present", () => { - assert.ok(selectSensors({ cwd: "/r", config: {}, bitbucketPipelines: true }).some((s) => s.id === "bitbucket-pipelines")); - assert.equal(selectSensors({ cwd: "/r", config: {} }).some((s) => s.id === "bitbucket-pipelines"), false); + assert.ok( + selectSensors({ cwd: "/r", config: {}, bitbucketPipelines: true }).some( + (s) => s.id === "bitbucket-pipelines", + ), + ); + assert.equal( + selectSensors({ cwd: "/r", config: {} }).some((s) => s.id === "bitbucket-pipelines"), + false, + ); }); it("registry has all three CI sensors and defaultHealthDeps exposes runCli + httpGet", () => { diff --git a/src/hooks.test.ts b/src/hooks.test.ts index 507c3ab0..e81053a9 100644 --- a/src/hooks.test.ts +++ b/src/hooks.test.ts @@ -32,9 +32,7 @@ describe("installHooks", () => { // + post-commit detector). Assert against the named hook from config. const preCommit = results.find((r) => r.hookName === "pre-commit"); assert.ok(preCommit, "pre-commit result present"); - assert.ok( - preCommit.action === "installed" || preCommit.action === "updated", - ); + assert.ok(preCommit.action === "installed" || preCommit.action === "updated"); assert.ok(existsSync(join(testGitDir, "hooks", "pre-commit"))); // The bypass detector also writes a post-commit hook unconditionally. assert.ok(existsSync(join(testGitDir, "hooks", "post-commit"))); @@ -71,18 +69,12 @@ describe("installHooks", () => { assert.ok(existsSync(join(testGitDir, "hooks", "pre-push"))); // Verify pre-commit has both commands - const preCommitContent = await readFile( - join(testGitDir, "hooks", "pre-commit"), - "utf-8", - ); + const preCommitContent = await readFile(join(testGitDir, "hooks", "pre-commit"), "utf-8"); assert.ok(preCommitContent.includes("npm run lint")); assert.ok(preCommitContent.includes("npm run typecheck")); // Verify pre-push has audit command - const prePushContent = await readFile( - join(testGitDir, "hooks", "pre-push"), - "utf-8", - ); + const prePushContent = await readFile(join(testGitDir, "hooks", "pre-push"), "utf-8"); assert.ok(prePushContent.includes("npm audit --audit-level=high")); }); @@ -92,10 +84,7 @@ describe("installHooks", () => { }; await installHooks(config, testGitDir); - const content = await readFile( - join(testGitDir, "hooks", "pre-commit"), - "utf-8", - ); + const content = await readFile(join(testGitDir, "hooks", "pre-commit"), "utf-8"); // Numbered step markers (▶ / ✓ / ✗) for each of the 2 commands assert.ok(content.includes("▶ [1/2] npm run build")); @@ -138,10 +127,7 @@ describe("installHooks", () => { const results2 = await installHooks(config2, testGitDir); assert.equal(results2[0].action, "updated"); - const content = await readFile( - join(testGitDir, "hooks", "pre-commit"), - "utf-8", - ); + const content = await readFile(join(testGitDir, "hooks", "pre-commit"), "utf-8"); assert.ok(content.includes("echo new")); assert.ok(!content.includes("echo old")); }); @@ -172,10 +158,7 @@ describe("installHooks", () => { await installHooks(config, testGitDir); - const content = await readFile( - join(testGitDir, "hooks", "pre-commit"), - "utf-8", - ); + const content = await readFile(join(testGitDir, "hooks", "pre-commit"), "utf-8"); assert.ok(content.includes("# Generated by kit")); }); }); diff --git a/src/hooks.ts b/src/hooks.ts index c4438dc9..b853c8a7 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -108,9 +108,7 @@ export async function installHooks( * — but we can guarantee a forensic trail and a stderr banner on the next * `kit` command in the repo. */ -async function installBypassDetector( - hooksDir: string, -): Promise<HookInstallResult[]> { +async function installBypassDetector(hooksDir: string): Promise<HookInstallResult[]> { const results: HookInstallResult[] = []; const preCommitDetectorPath = resolve(hooksDir, "pre-commit"); @@ -132,11 +130,7 @@ async function installBypassDetector( await chmod(preCommitDetectorPath, 0o755); } } else { - await writeFile( - preCommitDetectorPath, - `#!/bin/sh\n${sentinelWriter}\nexit 0\n`, - "utf-8", - ); + await writeFile(preCommitDetectorPath, `#!/bin/sh\n${sentinelWriter}\nexit 0\n`, "utf-8"); await chmod(preCommitDetectorPath, 0o755); } results.push({ @@ -164,11 +158,7 @@ async function installBypassDetector( await chmod(postCommitDetectorPath, 0o755); } } else { - await writeFile( - postCommitDetectorPath, - `#!/bin/sh\n${detectorScript}\nexit 0\n`, - "utf-8", - ); + await writeFile(postCommitDetectorPath, `#!/bin/sh\n${detectorScript}\nexit 0\n`, "utf-8"); await chmod(postCommitDetectorPath, 0o755); } results.push({ diff --git a/src/install.test.ts b/src/install.test.ts index a68e57f0..9b5e175f 100644 --- a/src/install.test.ts +++ b/src/install.test.ts @@ -14,9 +14,7 @@ function makeDeps(overrides: Partial<InstallDeps> = {}): InstallDeps { describe("installTools", () => { it("returns already_ok for tools that pass checkTools", async () => { const deps = makeDeps({ - checkTools: async () => [ - { name: "node", required: "22", installed: "22.22.2", ok: true }, - ], + checkTools: async () => [{ name: "node", required: "22", installed: "22.22.2", ok: true }], }); const results = await installTools({ node: "22" }, deps); @@ -55,9 +53,7 @@ describe("installTools", () => { it("returns failed when mise install throws", async () => { const deps = makeDeps({ - checkTools: async () => [ - { name: "bun", required: "1", installed: null, ok: false }, - ], + checkTools: async () => [{ name: "bun", required: "1", installed: null, ok: false }], miseInstall: async () => ({ ok: false, detail: "mise: plugin not found", @@ -120,8 +116,14 @@ describe("installTools", () => { it("triage-blocked tool is NOT installed (watertight gate)", async () => { let miseCalled = false; const deps = makeDeps({ - checkTools: async () => [{ name: "aqua:aquasecurity/trivy", required: "latest", installed: null, ok: false }], - gateInstall: async (tool) => ({ tool, decision: "blocked", reason: "triage did not pass (repo ...): typosquat" }), + checkTools: async () => [ + { name: "aqua:aquasecurity/trivy", required: "latest", installed: null, ok: false }, + ], + gateInstall: async (tool) => ({ + tool, + decision: "blocked", + reason: "triage did not pass (repo ...): typosquat", + }), miseInstall: async () => { miseCalled = true; return { ok: true, detail: "installed" }; @@ -139,7 +141,12 @@ describe("installTools", () => { let gateCalled = false; const deps = makeDeps({ checkTools: async (tools) => - Object.keys(tools).map((name) => ({ name, required: "latest", installed: null, ok: false })), + Object.keys(tools).map((name) => ({ + name, + required: "latest", + installed: null, + ok: false, + })), gateInstall: async (tool) => { gateCalled = true; return { tool, decision: "blocked", reason: "would block" }; @@ -175,7 +182,8 @@ describe("miseErrorDetail", () => { }); it("surfaces the real mise ERROR line instead of the generic Command failed", () => { - const stderr = "mise ERROR error parsing config file: ~/repo/.mise.toml\nmise ERROR Version: 2026.6.11"; + const stderr = + "mise ERROR error parsing config file: ~/repo/.mise.toml\nmise ERROR Version: 2026.6.11"; const detail = miseErrorDetail("Command failed: mise install node@24", stderr); assert.equal(detail, "error parsing config file: ~/repo/.mise.toml"); }); diff --git a/src/install.ts b/src/install.ts index 4d66182a..12e5cabe 100644 --- a/src/install.ts +++ b/src/install.ts @@ -3,7 +3,6 @@ import { checkTools, type ToolStatus } from "./check-tools.js"; import { gateInstall, type GateVerdict } from "./triage-gate.js"; import { exec } from "./utils/exec.js"; - export interface InstallResult { name: string; /** `blocked` = triage gate refused this install (watertight, fail-closed). */ diff --git a/src/lock.test.ts b/src/lock.test.ts index ecd6c058..e61e0974 100644 --- a/src/lock.test.ts +++ b/src/lock.test.ts @@ -235,10 +235,7 @@ describe("checkLockStatus", () => { }); it("reports out-of-sync when lock files are missing", async () => { - const status = await checkLockStatus( - { "skill-a": "1.0.0" }, - { node: "22" }, - ); + const status = await checkLockStatus({ "skill-a": "1.0.0" }, { node: "22" }); assert.equal(status.skillsLockExists, false); assert.equal(status.cliLockExists, false); @@ -252,10 +249,7 @@ describe("checkLockStatus", () => { await updateSkillsLock({ "skill-a": "1.0.0" }); await updateCliLock({ node: { version: "22.0.0", source: "mise" } }); - const status = await checkLockStatus( - { "skill-a": "1.0.0" }, - { node: "22" }, - ); + const status = await checkLockStatus({ "skill-a": "1.0.0" }, { node: "22" }); assert.equal(status.skillsLockExists, true); assert.equal(status.cliLockExists, true); @@ -268,10 +262,7 @@ describe("checkLockStatus", () => { it("identifies missing skills when only some are in the lock", async () => { await updateSkillsLock({ "skill-a": "1.0.0" }); - const status = await checkLockStatus( - { "skill-a": "1.0.0", "skill-b": "2.0.0" }, - {}, - ); + const status = await checkLockStatus({ "skill-a": "1.0.0", "skill-b": "2.0.0" }, {}); assert.equal(status.skillsInSync, false); assert.deepEqual(status.missingSkills, ["skill-b"]); diff --git a/src/lock.ts b/src/lock.ts index 16b32c5e..ab276f22 100644 --- a/src/lock.ts +++ b/src/lock.ts @@ -69,7 +69,7 @@ async function ensurekitDir(): Promise<void> { */ export async function readSkillsLock(): Promise<SkillsLock | null> { const lockPath = resolve(getkitDir(), SKILLS_LOCK_FILE); - + if (!existsSync(lockPath)) { return null; } @@ -89,7 +89,7 @@ export async function readSkillsLock(): Promise<SkillsLock | null> { export async function writeSkillsLock(lock: SkillsLock): Promise<void> { await ensurekitDir(); const lockPath = resolve(getkitDir(), SKILLS_LOCK_FILE); - + try { const content = JSON.stringify(lock, null, 2) + "\n"; await writeFile(lockPath, content, "utf-8"); @@ -104,7 +104,7 @@ export async function writeSkillsLock(lock: SkillsLock): Promise<void> { */ export async function readCliLock(): Promise<CliLock | null> { const lockPath = resolve(getkitDir(), CLI_LOCK_FILE); - + if (!existsSync(lockPath)) { return null; } @@ -124,7 +124,7 @@ export async function readCliLock(): Promise<CliLock | null> { export async function writeCliLock(lock: CliLock): Promise<void> { await ensurekitDir(); const lockPath = resolve(getkitDir(), CLI_LOCK_FILE); - + try { const content = JSON.stringify(lock, null, 2) + "\n"; await writeFile(lockPath, content, "utf-8"); @@ -139,7 +139,7 @@ export async function writeCliLock(lock: CliLock): Promise<void> { */ export async function readkitMeta(): Promise<kitMeta | null> { const metaPath = resolve(getkitDir(), KIT_META_FILE); - + if (!existsSync(metaPath)) { return null; } @@ -159,7 +159,7 @@ export async function readkitMeta(): Promise<kitMeta | null> { export async function writekitMeta(meta: kitMeta): Promise<void> { await ensurekitDir(); const metaPath = resolve(getkitDir(), KIT_META_FILE); - + try { const content = JSON.stringify(meta, null, 2) + "\n"; await writeFile(metaPath, content, "utf-8"); @@ -189,7 +189,10 @@ function computeSkillHash(source: string, version: string): string { * - "get-convex/agent-skills" → github * - "./local/path" → local */ -function parseSkillVersion(skillName: string, version: string): { +function parseSkillVersion( + skillName: string, + version: string, +): { source: string; sourceType: SkillLockEntry["sourceType"]; auth?: string; @@ -234,10 +237,10 @@ function parseSkillVersion(skillName: string, version: string): { */ export async function updateSkillsLock( skills: Record<string, string>, - kit?: string + kit?: string, ): Promise<void> { const existing = await readSkillsLock(); - + const lock: SkillsLock = { version: 1, kit: kit || existing?.kit, @@ -253,7 +256,7 @@ export async function updateSkillsLock( for (const [name, version] of Object.entries(skills)) { const parsed = parseSkillVersion(name, version); const existingEntry = lock.skills[name]; - + lock.skills[name] = { source: parsed.source, sourceType: parsed.sourceType, @@ -270,10 +273,10 @@ export async function updateSkillsLock( * Update CLI lock with installed tools */ export async function updateCliLock( - tools: Record<string, { version: string; source: CliLockEntry["source"]; auth?: string }> + tools: Record<string, { version: string; source: CliLockEntry["source"]; auth?: string }>, ): Promise<void> { const existing = await readCliLock(); - + const lock: CliLock = { version: 1, tools: {}, @@ -311,7 +314,7 @@ export interface LockStatus { export async function checkLockStatus( configSkills: Record<string, string>, - configTools: Record<string, string> + configTools: Record<string, string>, ): Promise<LockStatus> { const skillsLock = await readSkillsLock(); const cliLock = await readCliLock(); diff --git a/src/login.test.ts b/src/login.test.ts index 8cb57584..c9581ac0 100644 --- a/src/login.test.ts +++ b/src/login.test.ts @@ -21,7 +21,12 @@ describe("loginServices", () => { it("skips already authenticated services", async () => { const deps = makeDeps({ checkServices: async () => [ - { name: "github", checkCommand: "gh auth status", authenticated: true, output: "Logged in as octocat" }, + { + name: "github", + checkCommand: "gh auth status", + authenticated: true, + output: "Logged in as octocat", + }, ], }); @@ -38,7 +43,12 @@ describe("loginServices", () => { }; const deps = makeDeps({ checkServices: async () => [ - { name: "custom", checkCommand: "custom check", authenticated: false, output: "Not logged in" }, + { + name: "custom", + checkCommand: "custom check", + authenticated: false, + output: "Not logged in", + }, ], }); @@ -114,7 +124,12 @@ describe("loginServices", () => { const deps = makeDeps({ checkServices: async () => [ - { name: "supabase", checkCommand: "supabase projects list", authenticated: false, output: "" }, + { + name: "supabase", + checkCommand: "supabase projects list", + authenticated: false, + output: "", + }, ], runLink: async (cmd) => { linkCalls.push(cmd); @@ -140,7 +155,12 @@ describe("loginServices", () => { const deps = makeDeps({ checkServices: async () => [ - { name: "supabase", checkCommand: "supabase projects list", authenticated: false, output: "" }, + { + name: "supabase", + checkCommand: "supabase projects list", + authenticated: false, + output: "", + }, ], runLink: async () => ({ ok: false, detail: "Project not found" }), }); @@ -161,7 +181,12 @@ describe("loginServices", () => { const deps = makeDeps({ checkServices: async () => [ - { name: "github", checkCommand: "gh auth status", authenticated: true, output: "Logged in" }, + { + name: "github", + checkCommand: "gh auth status", + authenticated: true, + output: "Logged in", + }, { name: "vercel", checkCommand: "vercel whoami", authenticated: false, output: "" }, { name: "stripe", checkCommand: "stripe config --list", authenticated: false, output: "" }, ], @@ -194,7 +219,12 @@ describe("loginServices", () => { ].join("\n"); const deps = makeDeps({ checkServices: async () => [ - { name: "stripe", checkCommand: "stripe config --list", authenticated: true, output: stripeDump }, + { + name: "stripe", + checkCommand: "stripe config --list", + authenticated: true, + output: stripeDump, + }, ], }); diff --git a/src/login.ts b/src/login.ts index 9c832c8c..dfca5daa 100644 --- a/src/login.ts +++ b/src/login.ts @@ -11,12 +11,7 @@ const exec = promisify(execFile); export interface LoginResult { name: string; - action: - | "already_authenticated" - | "logged_in" - | "login_unverified" - | "manual" - | "failed"; + action: "already_authenticated" | "logged_in" | "login_unverified" | "manual" | "failed"; detail: string; } diff --git a/src/mcp-orchestrator.ts b/src/mcp-orchestrator.ts index 1e456df5..0bba098d 100644 --- a/src/mcp-orchestrator.ts +++ b/src/mcp-orchestrator.ts @@ -96,12 +96,7 @@ export async function clearMcpToken(name: string): Promise<void> { await writeTokenStore(store); } -export type McpAuthStatus = - | "ok" - | "expired" - | "missing" - | "scope-mismatch" - | "unconfigured"; +export type McpAuthStatus = "ok" | "expired" | "missing" | "scope-mismatch" | "unconfigured"; export interface McpStatusEntry { name: string; @@ -177,16 +172,12 @@ export async function statusAll(config: McpConfig | undefined): Promise<McpStatu export async function resolveMcpToken(name: string): Promise<string> { const token = await getMcpToken(name); if (!token) { - throw new Error( - `No MCP token for "${name}". Run 'kit mcp auth ${name}' first.`, - ); + throw new Error(`No MCP token for "${name}". Run 'kit mcp auth ${name}' first.`); } if (token.expiresAt) { const exp = Date.parse(token.expiresAt); if (Number.isFinite(exp) && exp < Date.now()) { - throw new Error( - `MCP token for "${name}" expired ${token.expiresAt}. Re-authorize.`, - ); + throw new Error(`MCP token for "${name}" expired ${token.expiresAt}. Re-authorize.`); } } return token.accessToken; diff --git a/src/mcp-server.test.ts b/src/mcp-server.test.ts index e277ee27..fab284f1 100644 --- a/src/mcp-server.test.ts +++ b/src/mcp-server.test.ts @@ -35,10 +35,7 @@ async function createTestClient(): Promise<{ client: Client; cleanup: () => Prom const server = createMcpServer(); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client( - { name: "test-client", version: "1.0.0" }, - { capabilities: {} }, - ); + const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} }); await server.connect(serverTransport); await client.connect(clientTransport); @@ -138,7 +135,10 @@ describe("kit_check", () => { const { client, cleanup } = await createTestClient(); try { const result = await client.callTool({ name: "kit_check", arguments: { cwd: tempDir } }); - const data = parseResult(result) as { ok: boolean; secrets: Array<{ name: string; available: boolean }> }; + const data = parseResult(result) as { + ok: boolean; + secrets: Array<{ name: string; available: boolean }>; + }; assert.equal(data.ok, false); assert.equal(data.secrets[0].name, "MISSING_VAR"); assert.equal(data.secrets[0].available, false); @@ -188,7 +188,10 @@ describe("kit_fix", () => { const { client, cleanup } = await createTestClient(); try { const result = await client.callTool({ name: "kit_fix", arguments: {} }); - const data = parseResult(result) as { ok: boolean; actions: Array<{ name: string; action: string }> }; + const data = parseResult(result) as { + ok: boolean; + actions: Array<{ name: string; action: string }>; + }; assert.equal(data.ok, true); const names = data.actions.map((a) => a.name); assert.ok(names.includes("skills-lock.json"), "skills-lock.json not generated"); @@ -242,7 +245,10 @@ describe("kit_add", () => { }); const data = parseResult(result) as { success: boolean; error?: string }; assert.equal(data.success, false); - assert.ok(data.error?.includes("Unknown service"), `Expected unknown service error, got: ${data.error}`); + assert.ok( + data.error?.includes("Unknown service"), + `Expected unknown service error, got: ${data.error}`, + ); } finally { await cleanup(); } @@ -359,7 +365,10 @@ describe("kit_install", () => { const { client, cleanup } = await createTestClient(); try { const result = await client.callTool({ name: "kit_install", arguments: { cwd: tempDir } }); - const data = parseResult(result) as { ok: boolean; results: Array<{ name: string; action: string }> }; + const data = parseResult(result) as { + ok: boolean; + results: Array<{ name: string; action: string }>; + }; assert.equal(data.ok, true); const node = data.results.find((r) => r.name === "node"); assert.ok(node, "node not in results"); @@ -453,15 +462,15 @@ MISSING_KEY = { source = "env" } }; assert.ok( data.keys.every((k) => !k.set), - "missing_only should only return unset keys" + "missing_only should only return unset keys", ); assert.ok( data.keys.some((k) => k.name === "MISSING_KEY"), - "MISSING_KEY should be in result" + "MISSING_KEY should be in result", ); assert.ok( !data.keys.some((k) => k.name === "SECRET"), - "SECRET is set — should not appear with missing_only" + "SECRET is set — should not appear with missing_only", ); } finally { await writeFile(join(tempDir, ".kit.toml"), FIXTURE_EMPTY, "utf-8"); @@ -492,7 +501,7 @@ describe("kit_init", () => { await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); const { client, cleanup } = await createTestClient(); @@ -509,7 +518,10 @@ describe("kit_init", () => { }; assert.equal(data.detectedStack.language, "typescript"); assert.equal(data.detectedStack.framework, "nextjs"); - assert.ok(data.generatedConfig.includes("[tools]"), `expected [tools]: ${data.generatedConfig}`); + assert.ok( + data.generatedConfig.includes("[tools]"), + `expected [tools]: ${data.generatedConfig}`, + ); assert.equal(data.written, false, "dry_run=true should not write"); } finally { await cleanup(); @@ -522,7 +534,7 @@ describe("kit_init", () => { await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); const { client, cleanup } = await createTestClient(); @@ -552,7 +564,7 @@ describe("kit_init", () => { await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); const { client, cleanup } = await createTestClient(); @@ -575,12 +587,12 @@ describe("kit_init", () => { it("does not overwrite existing .kit.toml", async () => { const projectDir = join(tempDir, "existing-proj"); await mkdir(projectDir, { recursive: true }); - const original = "# existing\n[tools]\nnode = \"18\"\n"; + const original = '# existing\n[tools]\nnode = "18"\n'; await writeFile(join(projectDir, ".kit.toml"), original, "utf-8"); await writeFile( join(projectDir, "package.json"), JSON.stringify({ dependencies: { next: "14.0.0" } }), - "utf-8" + "utf-8", ); const { client, cleanup } = await createTestClient(); diff --git a/src/mcp-server.ts b/src/mcp-server.ts index eb23eb10..8404ea85 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -36,10 +36,7 @@ function configPath(cwd?: string): string { } export function createMcpServer(): McpServer { - const server = new McpServer( - { name: "kit", version: "0.1.0" }, - { capabilities: { tools: {} } }, - ); + const server = new McpServer({ name: "kit", version: "0.1.0" }, { capabilities: { tools: {} } }); // One registrar per tool — keeps this composition flat (was a 774-line // function). Each register_* attaches its tool to the server. @@ -86,8 +83,7 @@ function register_kit_check(server: McpServer): void { ? await checkSecrets(config.secrets) : { templateExists: null, keys: [] }; const skillResults = config.skills ? await checkSkills(config.skills) : []; - const hookResults = - config.hooks && isGitRepository() ? await checkHooks(config.hooks) : []; + const hookResults = config.hooks && isGitRepository() ? await checkHooks(config.hooks) : []; const webSearchResult = config.web?.search ? await checkWebSearch(config.web.search) : null; const securityResults = await checkSecurity(); const lockResults = await checkLockFiles(config); @@ -132,7 +128,6 @@ function register_kit_check(server: McpServer): void { } }, ); - } function register_kit_install(server: McpServer): void { @@ -146,7 +141,12 @@ function register_kit_install(server: McpServer): void { const config = await loadConfig(configPath(cwd)); if (!config.tools || Object.keys(config.tools).length === 0) { return { - content: [{ type: "text" as const, text: JSON.stringify({ installed: [], message: "No tools configured" }) }], + content: [ + { + type: "text" as const, + text: JSON.stringify({ installed: [], message: "No tools configured" }), + }, + ], }; } @@ -168,7 +168,6 @@ function register_kit_install(server: McpServer): void { } }, ); - } function register_kit_login(server: McpServer): void { @@ -184,7 +183,12 @@ function register_kit_login(server: McpServer): void { const config = await loadConfig(configPath(cwd)); if (!config.services || Object.keys(config.services).length === 0) { return { - content: [{ type: "text" as const, text: JSON.stringify({ results: [], message: "No services configured" }) }], + content: [ + { + type: "text" as const, + text: JSON.stringify({ results: [], message: "No services configured" }), + }, + ], }; } @@ -206,7 +210,6 @@ function register_kit_login(server: McpServer): void { } }, ); - } function register_kit_secrets(server: McpServer): void { @@ -220,7 +223,12 @@ function register_kit_secrets(server: McpServer): void { const config = await loadConfig(configPath(cwd)); if (!config.secrets) { return { - content: [{ type: "text" as const, text: JSON.stringify({ written: [], message: "No secrets configured" }) }], + content: [ + { + type: "text" as const, + text: JSON.stringify({ written: [], message: "No secrets configured" }), + }, + ], }; } @@ -246,7 +254,6 @@ function register_kit_secrets(server: McpServer): void { } }, ); - } function register_kit_fix(server: McpServer): void { @@ -284,18 +291,29 @@ function register_kit_fix(server: McpServer): void { }; const meta = await readkitMeta(); await updateSkillsLock(skills, meta?.name ? `${meta.name}@${meta.version}` : undefined); - actions.push({ name: "skills-lock.json", action: "generated", detail: "Created skills-lock.json" }); + actions.push({ + name: "skills-lock.json", + action: "generated", + detail: "Created skills-lock.json", + }); } if (!cliLock) { - const tools: Record<string, { version: string; source: "mise" | "npm" | "pip" | "manual" }> = {}; + const tools: Record< + string, + { version: string; source: "mise" | "npm" | "pip" | "manual" } + > = {}; if (config.tools) { for (const [name, version] of Object.entries(config.tools)) { tools[name] = { version, source: "mise" }; } } await updateCliLock(tools); - actions.push({ name: "cli-lock.json", action: "generated", detail: "Created cli-lock.json" }); + actions.push({ + name: "cli-lock.json", + action: "generated", + detail: "Created cli-lock.json", + }); } const ok = actions.every((a) => a.action !== "failed"); @@ -315,7 +333,6 @@ function register_kit_fix(server: McpServer): void { } }, ); - } function register_kit_add(server: McpServer): void { @@ -324,8 +341,13 @@ function register_kit_add(server: McpServer): void { "kit_add", `Provision a service integration for the project. Available services: ${listAvailableServices().join(", ")}. Writes generated secrets to .env.local and returns provisioning result.`, { - service: z.string().describe(`Service adapter name (e.g. ${listAvailableServices().slice(0, 3).join(", ")})`), - project_name: z.string().optional().describe("Project name (used by some adapters for resource naming)"), + service: z + .string() + .describe(`Service adapter name (e.g. ${listAvailableServices().slice(0, 3).join(", ")})`), + project_name: z + .string() + .optional() + .describe("Project name (used by some adapters for resource naming)"), cwd: z.string().optional().describe("Working directory"), }, async ({ service, project_name, cwd }) => { @@ -364,7 +386,6 @@ function register_kit_add(server: McpServer): void { } }, ); - } function register_kit_env(server: McpServer): void { @@ -373,8 +394,14 @@ function register_kit_env(server: McpServer): void { "kit_env", "Inspect environment variables from .env.local. Returns each key's set/missing status. Values are redacted by default.", { - show_values: z.boolean().optional().describe("Return actual values (default: false, values are redacted)"), - missing_only: z.boolean().optional().describe("Return only keys that are not set in .env.local"), + show_values: z + .boolean() + .optional() + .describe("Return actual values (default: false, values are redacted)"), + missing_only: z + .boolean() + .optional() + .describe("Return only keys that are not set in .env.local"), cwd: z.string().optional().describe("Working directory"), }, async ({ show_values, missing_only, cwd }) => { @@ -409,7 +436,6 @@ function register_kit_env(server: McpServer): void { } }, ); - } function register_kit_init(server: McpServer): void { @@ -465,7 +491,7 @@ function register_kit_init(server: McpServer): void { : ".kit.toml generated successfully", }, null, - 2 + 2, ), }, ], @@ -478,7 +504,6 @@ function register_kit_init(server: McpServer): void { } }, ); - } function register_kit_ci(server: McpServer): void { @@ -565,7 +590,7 @@ function register_kit_ci(server: McpServer): void { else acc.skipped++; return acc; }, - { passed: 0, failed: 0, warnings: 0, skipped: 0 } + { passed: 0, failed: 0, warnings: 0, skipped: 0 }, ); const ok = summary.failed === 0 && (!fail_on_warning || summary.warnings === 0); @@ -576,17 +601,30 @@ function register_kit_ci(server: McpServer): void { const lines: string[] = []; for (const c of checks) { if (c.status === "fail") lines.push(`::error::${c.category}/${c.name}: ${c.detail}`); - else if (c.status === "warn") lines.push(`::warning::${c.category}/${c.name}: ${c.detail}`); + else if (c.status === "warn") + lines.push(`::warning::${c.category}/${c.name}: ${c.detail}`); } - lines.push(`kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`); + lines.push( + `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`, + ); text = lines.join("\n"); } else if (format === "text") { const failures = checks.filter((c) => c.status === "fail"); const warnings = checks.filter((c) => c.status === "warn"); const lines: string[] = []; - if (failures.length) lines.push("FAILURES:", ...failures.map((f) => ` ✗ [${f.category}] ${f.name}: ${f.detail}`)); - if (warnings.length) lines.push("WARNINGS:", ...warnings.map((w) => ` ! [${w.category}] ${w.name}: ${w.detail}`)); - lines.push(`kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`); + if (failures.length) + lines.push( + "FAILURES:", + ...failures.map((f) => ` ✗ [${f.category}] ${f.name}: ${f.detail}`), + ); + if (warnings.length) + lines.push( + "WARNINGS:", + ...warnings.map((w) => ` ! [${w.category}] ${w.name}: ${w.detail}`), + ); + lines.push( + `kit ci: ${summary.passed} passed, ${summary.failed} failed, ${summary.warnings} warnings`, + ); text = lines.join("\n"); } else { text = JSON.stringify(result, null, 2); @@ -602,9 +640,8 @@ function register_kit_ci(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_run(server: McpServer): void { @@ -613,7 +650,9 @@ function register_kit_run(server: McpServer): void { "kit_run", "Execute a command with project environment variables loaded from .env.local. Useful for running tests, scripts, and build commands with proper secrets and config in scope.", { - command: z.string().describe("Command to execute (with arguments, e.g., 'pnpm test --watch')"), + command: z + .string() + .describe("Command to execute (with arguments, e.g., 'pnpm test --watch')"), cwd: z.string().optional().describe("Working directory (defaults to process.cwd())"), }, async ({ command, cwd }) => { @@ -649,9 +688,8 @@ function register_kit_run(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_context(server: McpServer): void { @@ -682,9 +720,8 @@ function register_kit_context(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_configure(server: McpServer): void { @@ -729,9 +766,8 @@ function register_kit_configure(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_adapter_check(server: McpServer): void { @@ -740,12 +776,14 @@ function register_kit_adapter_check(server: McpServer): void { "kit_adapter_check", "Check status and compatibility of installed adapters. Returns adapter health and compatibility information.", { - adapter: z.string().optional().describe("Specific adapter to check (checks all if not specified)"), + adapter: z + .string() + .optional() + .describe("Specific adapter to check (checks all if not specified)"), cwd: z.string().optional().describe("Project directory"), }, async ({ adapter, cwd }) => { try { - return { content: [ { @@ -755,7 +793,9 @@ function register_kit_adapter_check(server: McpServer): void { adapters_checked: adapter ? [adapter] : ["all"], status: "healthy", compatibility: "latest", - message: adapter ? `Adapter ${adapter} is compatible` : "All adapters are compatible", + message: adapter + ? `Adapter ${adapter} is compatible` + : "All adapters are compatible", }, null, 2, @@ -769,9 +809,8 @@ function register_kit_adapter_check(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_adapter_install(server: McpServer): void { @@ -812,9 +851,8 @@ function register_kit_adapter_install(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_workflow_execute(server: McpServer): void { @@ -830,7 +868,6 @@ function register_kit_workflow_execute(server: McpServer): void { }, async ({ workflow, params, dryRun = false, cwd }) => { try { - return { content: [ { @@ -861,9 +898,8 @@ function register_kit_workflow_execute(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_skill_marketplace(server: McpServer): void { @@ -872,14 +908,16 @@ function register_kit_skill_marketplace(server: McpServer): void { "kit_skill_marketplace", "Browse, search, and install skills from kit skill marketplace. Discover community skills and integrations.", { - action: z.enum(["list", "search", "install", "info", "ratings"]).optional().describe("Marketplace action"), + action: z + .enum(["list", "search", "install", "info", "ratings"]) + .optional() + .describe("Marketplace action"), query: z.string().optional().describe("Search query or skill name"), category: z.string().optional().describe("Filter by category"), cwd: z.string().optional().describe("Project directory"), }, async ({ action = "list", query, category, cwd }) => { try { - return { content: [ { @@ -908,9 +946,8 @@ function register_kit_skill_marketplace(server: McpServer): void { isError: true, }; } - } + }, ); - } function register_kit_agent_governance(server: McpServer): void { @@ -919,14 +956,16 @@ function register_kit_agent_governance(server: McpServer): void { "kit_agent_governance", "Configure governance policies, permissions, and access controls for agents. Define agent capabilities and restrictions.", { - action: z.enum(["list", "create", "update", "delete", "assign"]).optional().describe("Governance action"), + action: z + .enum(["list", "create", "update", "delete", "assign"]) + .optional() + .describe("Governance action"), policy: z.string().optional().describe("Policy name or ID"), rules: z.record(z.string(), z.any()).optional().describe("Policy rules and constraints"), cwd: z.string().optional().describe("Project directory"), }, async ({ action = "list", policy, rules, cwd }) => { try { - return { content: [ { @@ -961,7 +1000,6 @@ function register_kit_agent_governance(server: McpServer): void { isError: true, }; } - } + }, ); - } diff --git a/src/memory/amazonq.ts b/src/memory/amazonq.ts index 1de36e6a..e0b0ce53 100644 --- a/src/memory/amazonq.ts +++ b/src/memory/amazonq.ts @@ -70,11 +70,7 @@ interface ConversationState { history?: HistoryEntry[]; } -function indexConversation( - db: DatabaseSync, - key: string, - value: string, -): { messages: number } { +function indexConversation(db: DatabaseSync, key: string, value: string): { messages: number } { let state: ConversationState; try { state = JSON.parse(value) as ConversationState; @@ -146,9 +142,10 @@ export function indexAmazonQSessions(db: DatabaseSync): IndexResult { try { let rows: { key: string; value: string }[]; try { - rows = src - .prepare("SELECT key, value FROM conversations") - .all() as unknown as { key: string; value: string }[]; + rows = src.prepare("SELECT key, value FROM conversations").all() as unknown as { + key: string; + value: string; + }[]; } catch { markFileIndexed(db, dbPath, mtimeMs, st.size); // table absent / differs → fail-safe return result; diff --git a/src/memory/cline.ts b/src/memory/cline.ts index b63732c3..dc5e8060 100644 --- a/src/memory/cline.ts +++ b/src/memory/cline.ts @@ -28,7 +28,12 @@ function vscodeGlobalStorage(): string { case "darwin": return join(home, "Library", "Application Support", "Code", "User", "globalStorage"); case "win32": - return join(process.env.APPDATA ?? join(home, "AppData", "Roaming"), "Code", "User", "globalStorage"); + return join( + process.env.APPDATA ?? join(home, "AppData", "Roaming"), + "Code", + "User", + "globalStorage", + ); default: return join(home, ".config", "Code", "User", "globalStorage"); } diff --git a/src/memory/codex.test.ts b/src/memory/codex.test.ts index 08d5b53d..03b7d065 100644 --- a/src/memory/codex.test.ts +++ b/src/memory/codex.test.ts @@ -23,12 +23,20 @@ describe("memory codex parser", () => { JSON.stringify({ timestamp: "2026-03-31T11:05:00Z", type: "response_item", - payload: { type: "message", role: "developer", content: [{ type: "input_text", text: "system permissions noise" }] }, + payload: { + type: "message", + role: "developer", + content: [{ type: "input_text", text: "system permissions noise" }], + }, }), JSON.stringify({ timestamp: "2026-03-31T11:05:10Z", type: "response_item", - payload: { type: "message", role: "user", content: [{ type: "input_text", text: "october pricing question" }] }, + payload: { + type: "message", + role: "user", + content: [{ type: "input_text", text: "october pricing question" }], + }, }), JSON.stringify({ timestamp: "2026-03-31T11:05:20Z", @@ -38,7 +46,11 @@ describe("memory codex parser", () => { JSON.stringify({ timestamp: "2026-03-31T11:05:21Z", type: "response_item", - payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: "here is the answer" }] }, + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "here is the answer" }], + }, }), ].join("\n"); writeFileSync(join(dir, "rollout-2026-03-31T11-04-40-sess-xyz.jsonl"), lines); diff --git a/src/memory/continue.test.ts b/src/memory/continue.test.ts index 3506ffab..cfbcb74b 100644 --- a/src/memory/continue.test.ts +++ b/src/memory/continue.test.ts @@ -67,7 +67,10 @@ describe("memory continue parser", () => { assert.equal(searchMessages(db, "december").length, 1); // project-scoped recall works because cwd was set from workspaceDirectory - assert.equal(searchMessages(db, "assistant", { projectPath: "/Users/me/dev/widget" }).length, 1); + assert.equal( + searchMessages(db, "assistant", { projectPath: "/Users/me/dev/widget" }).length, + 1, + ); db.close(); }); diff --git a/src/memory/db.ts b/src/memory/db.ts index d1123108..448eb2a2 100644 --- a/src/memory/db.ts +++ b/src/memory/db.ts @@ -16,13 +16,7 @@ import { DatabaseSync } from "node:sqlite"; import { homedir } from "node:os"; import { join } from "node:path"; import { existsSync, mkdirSync, chmodSync, statSync } from "node:fs"; -import type { - MemoryStats, - MessageInput, - SearchHit, - SessionInput, - ToolUseInput, -} from "./types.js"; +import type { MemoryStats, MessageInput, SearchHit, SessionInput, ToolUseInput } from "./types.js"; export const SCHEMA_VERSION = 3; @@ -132,12 +126,7 @@ CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages BEGIN END; `; -function ensureColumn( - db: DatabaseSync, - table: string, - column: string, - decl: string, -): void { +function ensureColumn(db: DatabaseSync, table: string, column: string, decl: string): void { const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]; if (!cols.some((col) => col.name === column)) { db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${decl}`); @@ -256,9 +245,9 @@ export function insertMessage(db: DatabaseSync, m: MessageInput): boolean { m.version ?? null, ); if (Number(res.changes) > 0) { - db.prepare( - "UPDATE sessions SET message_count = message_count + 1 WHERE session_id = ?", - ).run(m.sessionId); + db.prepare("UPDATE sessions SET message_count = message_count + 1 WHERE session_id = ?").run( + m.sessionId, + ); return true; } return false; @@ -382,9 +371,7 @@ export function getStats(db: DatabaseSync): MemoryStats { sessions: count("SELECT COUNT(*) AS n FROM sessions"), messages: count("SELECT COUNT(*) AS n FROM messages"), toolUses: count("SELECT COUNT(*) AS n FROM tool_uses"), - pendingOpen: count( - "SELECT COUNT(*) AS n FROM pending_actions WHERE status = 'open'", - ), + pendingOpen: count("SELECT COUNT(*) AS n FROM pending_actions WHERE status = 'open'"), dbPath, sizeBytes, byHarness, diff --git a/src/memory/gemini.test.ts b/src/memory/gemini.test.ts index 5891cc24..f321aa3d 100644 --- a/src/memory/gemini.test.ts +++ b/src/memory/gemini.test.ts @@ -20,9 +20,27 @@ describe("memory gemini parser", () => { writeFileSync( join(projDir, "logs.json"), JSON.stringify([ - { sessionId: "sess-1", messageId: 0, timestamp: "2026-04-01T09:00:00Z", type: "user", message: "november roadmap question" }, - { sessionId: "sess-1", messageId: 1, timestamp: "2026-04-01T09:00:05Z", type: "gemini", message: "logged model reply" }, - { sessionId: "sess-1", messageId: 2, timestamp: "2026-04-01T09:00:10Z", type: "user", message: "" }, + { + sessionId: "sess-1", + messageId: 0, + timestamp: "2026-04-01T09:00:00Z", + type: "user", + message: "november roadmap question", + }, + { + sessionId: "sess-1", + messageId: 1, + timestamp: "2026-04-01T09:00:05Z", + type: "gemini", + message: "logged model reply", + }, + { + sessionId: "sess-1", + messageId: 2, + timestamp: "2026-04-01T09:00:10Z", + type: "user", + message: "", + }, ]), ); @@ -60,9 +78,9 @@ describe("memory gemini parser", () => { assert.equal(res.messages, 4); assert.equal(getStats(db).messages, 4); - const harnesses = db - .prepare("SELECT DISTINCT harness FROM sessions") - .all() as { harness: string }[]; + const harnesses = db.prepare("SELECT DISTINCT harness FROM sessions").all() as { + harness: string; + }[]; assert.ok(harnesses.every((h) => h.harness === "gemini")); assert.equal(searchMessages(db, "november").length, 1); diff --git a/src/memory/hook.ts b/src/memory/hook.ts index 3c277b8b..8d33b109 100644 --- a/src/memory/hook.ts +++ b/src/memory/hook.ts @@ -85,10 +85,11 @@ export function sessionStartRecovery(opts: { limit?: number } = {}): string { if (text) lines.push(` · ${who}: ${text}`); } if (openItems.length > 0) { - const titles = openItems.slice(0, 3).map((p) => `${p.id} ${p.title}`).join("; "); - lines.push( - `Open action items blocked on you: ${titles}${openItems.length > 3 ? " …" : ""}.`, - ); + const titles = openItems + .slice(0, 3) + .map((p) => `${p.id} ${p.title}`) + .join("; "); + lines.push(`Open action items blocked on you: ${titles}${openItems.length > 3 ? " …" : ""}.`); } if (recent.length > 0 || openItems.length > 0) { lines.push("Run `kit memory search <terms>` to pull more of what was actually said."); diff --git a/src/memory/install.test.ts b/src/memory/install.test.ts index 57395ccf..931d0891 100644 --- a/src/memory/install.test.ts +++ b/src/memory/install.test.ts @@ -63,7 +63,11 @@ describe("memory hook installer", () => { installMemoryHooks(); const res2 = installMemoryHooks(); assert.deepEqual(res2.added, []); - assert.deepEqual(res2.alreadyPresent.sort(), ["SessionEnd", "SessionStart", "UserPromptSubmit"]); + assert.deepEqual(res2.alreadyPresent.sort(), [ + "SessionEnd", + "SessionStart", + "UserPromptSubmit", + ]); const s = JSON.parse(readFileSync(settingsPath, "utf8")); const ours = s.hooks.UserPromptSubmit.filter((g: { hooks: { command: string }[] }) => g.hooks.some((h) => h.command.endsWith("memory hook user-prompt-submit")), @@ -77,7 +81,9 @@ describe("memory hook installer", () => { settingsPath, JSON.stringify({ hooks: { - UserPromptSubmit: [{ hooks: [{ type: "command", command: "kit memory hook user-prompt-submit" }] }], + UserPromptSubmit: [ + { hooks: [{ type: "command", command: "kit memory hook user-prompt-submit" }] }, + ], }, }), ); diff --git a/src/memory/install.ts b/src/memory/install.ts index c7d0e987..1800abdc 100644 --- a/src/memory/install.ts +++ b/src/memory/install.ts @@ -71,9 +71,11 @@ function groupsHaveHook(groups: HookGroup[], sub: string): boolean { return groups.some((g) => g.hooks?.some((h) => h.command.endsWith(suffix))); } -export function installMemoryHooks( - path: string = getClaudeSettingsPath(), -): { added: string[]; alreadyPresent: string[]; resolved: boolean } { +export function installMemoryHooks(path: string = getClaudeSettingsPath()): { + added: string[]; + alreadyPresent: string[]; + resolved: boolean; +} { const s = readSettings(path); const hooks = (s.hooks ??= {}); const prefix = kitHookInvocation(); @@ -93,9 +95,9 @@ export function installMemoryHooks( return { added, alreadyPresent, resolved }; } -export function uninstallMemoryHooks( - path: string = getClaudeSettingsPath(), -): { removed: string[] } { +export function uninstallMemoryHooks(path: string = getClaudeSettingsPath()): { + removed: string[]; +} { const s = readSettings(path); if (!s.hooks) return { removed: [] }; const removed: string[] = []; diff --git a/src/memory/merge.test.ts b/src/memory/merge.test.ts index 03f68183..a465e0c3 100644 --- a/src/memory/merge.test.ts +++ b/src/memory/merge.test.ts @@ -15,7 +15,12 @@ describe("memory merge", () => { // A source brain (e.g. an old laptop) const src = openMemoryDb(srcPath); upsertSession(src, { sessionId: "s1", harness: "codex" }); - insertMessage(src, { uuid: "a", sessionId: "s1", type: "user", content: "from the old laptop" }); + insertMessage(src, { + uuid: "a", + sessionId: "s1", + type: "user", + content: "from the old laptop", + }); insertMessage(src, { uuid: "b", sessionId: "s1", type: "assistant", content: "reply" }); palAdd(src, { title: "old todo", scope: "proj" }); src.exec("PRAGMA wal_checkpoint(TRUNCATE)"); // flush WAL so readOnly open sees it all diff --git a/src/memory/pal.test.ts b/src/memory/pal.test.ts index 0db82f54..75006811 100644 --- a/src/memory/pal.test.ts +++ b/src/memory/pal.test.ts @@ -58,8 +58,14 @@ describe("PAL — pending actions", () => { const present = join(tmp, "present"); writeFileSync(present, "x"); const missing = join(tmp, "missing"); - const passes = palAdd(db, { title: "passing check", check: { type: "file-exists", path: present } }); - const fails = palAdd(db, { title: "failing check", check: { type: "file-exists", path: missing } }); + const passes = palAdd(db, { + title: "passing check", + check: { type: "file-exists", path: present }, + }); + const fails = palAdd(db, { + title: "failing check", + check: { type: "file-exists", path: missing }, + }); let r = await palAutoVerify(db); assert.deepEqual(r.closed, []); // first pass: streak = 1 assert.equal(palList(db).length, 2); @@ -77,7 +83,10 @@ describe("PAL — pending actions", () => { const tmp = mkdtempSync(join(tmpdir(), "kit-pal-")); const artifact = join(tmp, "artifact"); writeFileSync(artifact, "x"); - const id = palAdd(db, { title: "regressing check", check: { type: "file-exists", path: artifact } }); + const id = palAdd(db, { + title: "regressing check", + check: { type: "file-exists", path: artifact }, + }); palDone(db, id); // force-close assert.equal(palList(db, { status: "closed" }).length, 1); rmSync(artifact); // artifact gone -> the check now fails @@ -105,7 +114,13 @@ describe("PAL — pending actions", () => { verify: "false", pass_streak: 1, }), - JSON.stringify({ id: "bbbb", ts: "2026-06-02", status: "done", repo: "app-b", title: "cert fixed" }), + JSON.stringify({ + id: "bbbb", + ts: "2026-06-02", + status: "done", + repo: "app-b", + title: "cert fixed", + }), ].join("\n"), ); const r = importLegacyLedger(db, led); diff --git a/src/memory/parser.test.ts b/src/memory/parser.test.ts index 4a5c1970..08c9b2bb 100644 --- a/src/memory/parser.test.ts +++ b/src/memory/parser.test.ts @@ -4,11 +4,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { openMemoryDb, getStats, searchMessages } from "./db.js"; -import { - extractText, - extractToolUses, - indexClaudeTranscripts, -} from "./parser.js"; +import { extractText, extractToolUses, indexClaudeTranscripts } from "./parser.js"; describe("memory parser — content extraction", () => { it("returns strings unchanged", () => { diff --git a/src/memory/scan.test.ts b/src/memory/scan.test.ts index 6b8aeba7..b8168222 100644 --- a/src/memory/scan.test.ts +++ b/src/memory/scan.test.ts @@ -9,14 +9,22 @@ describe("memory secret-scan", () => { upsertSession(db, { sessionId: "s1", harness: "claude-code" }); const fake = "sk_live_" + "A".repeat(24); // synthetic, non-real insertMessage(db, { uuid: "u1", sessionId: "s1", type: "user", content: `the key is ${fake}` }); - insertMessage(db, { uuid: "u2", sessionId: "s1", type: "user", content: "totally clean message" }); + insertMessage(db, { + uuid: "u2", + sessionId: "s1", + type: "user", + content: "totally clean message", + }); const findings = scanDbForSecrets(db); assert.equal(findings.length, 1); assert.equal(findings[0]?.label, "stripe-key"); assert.equal(findings[0]?.confidence, "high"); assert.equal(findings[0]?.count, 1); assert.match(findings[0]?.sample ?? "", /^messages#\d+\.content$/); - assert.ok(!findings[0]?.preview.includes("A".repeat(24)), "preview is masked, not the raw secret"); + assert.ok( + !findings[0]?.preview.includes("A".repeat(24)), + "preview is masked, not the raw secret", + ); db.close(); }); diff --git a/src/memory/shared.test.ts b/src/memory/shared.test.ts index 9234d177..9a1d9412 100644 --- a/src/memory/shared.test.ts +++ b/src/memory/shared.test.ts @@ -24,7 +24,13 @@ describe("shared project memory (Track D)", () => { const r = root(); const e = shareEntry( r, - { area: "stripe", kind: "decision", title: "use Connect", body: "platform model", refs: ["PR #12"] }, + { + area: "stripe", + kind: "decision", + title: "use Connect", + body: "platform model", + refs: ["PR #12"], + }, "2026-06-16T00:00:00Z", ); assert.match(e.id, /^[0-9a-f]{6}$/); @@ -43,7 +49,12 @@ describe("shared project memory (Track D)", () => { const r = root(); const fake = "sk_live_" + "B".repeat(24); assert.throws( - () => shareEntry(r, { area: "stripe", kind: "note", title: "key", body: `the key is ${fake}` }, "t"), + () => + shareEntry( + r, + { area: "stripe", kind: "note", title: "key", body: `the key is ${fake}` }, + "t", + ), /secret/, ); assert.equal(readShared(r).length, 0); @@ -65,7 +76,11 @@ describe("shared project memory (Track D)", () => { it("searches across entries", () => { const r = root(); - shareEntry(r, { area: "whatsapp", kind: "how-built", title: "scheduling bot", body: "runs on cron" }, "t1"); + shareEntry( + r, + { area: "whatsapp", kind: "how-built", title: "scheduling bot", body: "runs on cron" }, + "t1", + ); assert.equal(searchShared(r, "cron").length, 1); assert.equal(searchShared(r, "stripe").length, 0); rmSync(r, { recursive: true, force: true }); diff --git a/src/memory/shared.ts b/src/memory/shared.ts index f50c39c4..a11153e1 100644 --- a/src/memory/shared.ts +++ b/src/memory/shared.ts @@ -20,13 +20,7 @@ import { existsSync, readFileSync, appendFileSync, mkdirSync } from "node:fs"; import { join, dirname } from "node:path"; import { findSecrets } from "../utils/redactSecrets.js"; -export type SharedKind = - | "decision" - | "convention" - | "how-built" - | "status" - | "security" - | "note"; +export type SharedKind = "decision" | "convention" | "how-built" | "status" | "security" | "note"; export interface SharedEntry { id: string; diff --git a/src/memory/threads.ts b/src/memory/threads.ts index b5e06a18..1b7cec62 100644 --- a/src/memory/threads.ts +++ b/src/memory/threads.ts @@ -36,10 +36,7 @@ export function saveThread(db: DatabaseSync, input: SaveThreadInput): void { ).run(input.name, input.sessionId, input.summary ?? null, input.projectPath ?? null); } -export function listThreads( - db: DatabaseSync, - opts: { projectPath?: string } = {}, -): SavedThread[] { +export function listThreads(db: DatabaseSync, opts: { projectPath?: string } = {}): SavedThread[] { if (opts.projectPath) { return db .prepare("SELECT * FROM saved_threads WHERE project_path = ? ORDER BY saved_at DESC") @@ -75,9 +72,9 @@ export function latestSessionId( ) .get(opts.projectPath, `${opts.projectPath}/%`) as { session_id: string } | undefined; } else { - row = db - .prepare("SELECT session_id FROM messages ORDER BY timestamp DESC LIMIT 1") - .get() as { session_id: string } | undefined; + row = db.prepare("SELECT session_id FROM messages ORDER BY timestamp DESC LIMIT 1").get() as + | { session_id: string } + | undefined; } return row?.session_id; } diff --git a/src/neon-clerk.test.ts b/src/neon-clerk.test.ts index f3dcdbde..fa0e4ac8 100644 --- a/src/neon-clerk.test.ts +++ b/src/neon-clerk.test.ts @@ -21,14 +21,14 @@ describe("neonDbAdapter", () => { it("check returns true when DATABASE_URL starts with postgresql://", async () => { const result = await neonDbAdapter.check( - mockContext({ DATABASE_URL: "postgresql://user:pass@ep-xxx.us-east-2.aws.neon.tech/neondb" }) + mockContext({ DATABASE_URL: "postgresql://user:pass@ep-xxx.us-east-2.aws.neon.tech/neondb" }), ); assert.equal(result, true); }); it("check returns true when DATABASE_URL starts with postgres://", async () => { const result = await neonDbAdapter.check( - mockContext({ DATABASE_URL: "postgres://user:pass@host/db" }) + mockContext({ DATABASE_URL: "postgres://user:pass@host/db" }), ); assert.equal(result, true); }); @@ -40,7 +40,7 @@ describe("neonDbAdapter", () => { it("check returns false when DATABASE_URL is not postgres", async () => { const result = await neonDbAdapter.check( - mockContext({ DATABASE_URL: "mysql://user:pass@host/db" }) + mockContext({ DATABASE_URL: "mysql://user:pass@host/db" }), ); assert.equal(result, false); }); @@ -57,7 +57,10 @@ describe("neonDbAdapter", () => { it("provision returns error with setup instructions when NEON_API_KEY is missing", async () => { const result = await neonDbAdapter.provision(mockContext()); assert.equal(result.success, false); - assert(result.message?.includes("console.neon.tech"), `expected dashboard URL: ${result.message}`); + assert( + result.message?.includes("console.neon.tech"), + `expected dashboard URL: ${result.message}`, + ); assert(result.message?.includes("NEON_API_KEY"), `expected key name: ${result.message}`); }); }); @@ -77,7 +80,7 @@ describe("clerkAuthAdapter", () => { mockContext({ CLERK_SECRET_KEY: "sk_test_xxx", NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: "pk_test_xxx", - }) + }), ); assert.equal(result, true); }); @@ -88,9 +91,7 @@ describe("clerkAuthAdapter", () => { }); it("check returns false when only one key is present", async () => { - const result = await clerkAuthAdapter.check( - mockContext({ CLERK_SECRET_KEY: "sk_test_xxx" }) - ); + const result = await clerkAuthAdapter.check(mockContext({ CLERK_SECRET_KEY: "sk_test_xxx" })); assert.equal(result, false); }); @@ -99,7 +100,7 @@ describe("clerkAuthAdapter", () => { mockContext({ CLERK_SECRET_KEY: "sk_test_xxx", NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: "pk_test_xxx", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.CLERK_SECRET_KEY, "sk_test_xxx"); diff --git a/src/onepassword.test.ts b/src/onepassword.test.ts index 738d8c65..957354d5 100644 --- a/src/onepassword.test.ts +++ b/src/onepassword.test.ts @@ -1,10 +1,6 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { - check1PasswordStatus, - validate1PasswordRef, - generate1PasswordRef, -} from "./onepassword.js"; +import { check1PasswordStatus, validate1PasswordRef, generate1PasswordRef } from "./onepassword.js"; describe("onepassword", () => { describe("validate1PasswordRef", () => { diff --git a/src/onepassword.ts b/src/onepassword.ts index 10cb0436..1dd332c3 100644 --- a/src/onepassword.ts +++ b/src/onepassword.ts @@ -1,6 +1,5 @@ import { exec } from "./utils/exec.js"; - export interface OnePasswordStatus { installed: boolean; authenticated: boolean; @@ -164,15 +163,11 @@ export async function list1PasswordVaults(): Promise<OnePasswordVault[]> { /** * List items in a specific vault */ -export async function list1PasswordItems( - vaultId: string, -): Promise<OnePasswordItem[]> { +export async function list1PasswordItems(vaultId: string): Promise<OnePasswordItem[]> { try { - const { stdout } = await exec( - "op", - ["item", "list", "--vault", vaultId, "--format=json"], - { timeout: 10000 }, - ); + const { stdout } = await exec("op", ["item", "list", "--vault", vaultId, "--format=json"], { + timeout: 10000, + }); const items = JSON.parse(stdout) as OnePasswordItem[]; return items; } catch { @@ -184,11 +179,7 @@ export async function list1PasswordItems( * Generate a reference string for a 1Password item * Helps users construct proper ref strings for config */ -export function generate1PasswordRef( - vault: string, - item: string, - field?: string, -): string { +export function generate1PasswordRef(vault: string, item: string, field?: string): string { if (field) { return `op://${vault}/${item}/${field}`; } diff --git a/src/open.test.ts b/src/open.test.ts index 7d8c9f3d..81669744 100644 --- a/src/open.test.ts +++ b/src/open.test.ts @@ -18,8 +18,14 @@ describe("openService", () => { it("lists all services", () => { const services = listServices(); assert.ok(services.length > 0, "Should have at least one service"); - assert.ok(services.some((s) => s.name === "stripe"), "Should include stripe"); - assert.ok(services.some((s) => s.name === "vercel"), "Should include vercel"); + assert.ok( + services.some((s) => s.name === "stripe"), + "Should include stripe", + ); + assert.ok( + services.some((s) => s.name === "vercel"), + "Should include vercel", + ); }); it("finds service by name (case insensitive)", () => { @@ -130,7 +136,7 @@ describe("openService", () => { assert.ok(service.docUrl, `Service ${service.name} should have docUrl`); assert.ok( typeof service.dashboardUrl === "function", - `Service ${service.name} should have dashboardUrl function` + `Service ${service.name} should have dashboardUrl function`, ); } }); diff --git a/src/open.ts b/src/open.ts index 4436372e..897d5e8a 100644 --- a/src/open.ts +++ b/src/open.ts @@ -23,7 +23,9 @@ const SERVICES: ServiceDashboard[] = [ docUrl: "https://supabase.com/docs", dashboardUrl: (env) => { const ref = env.SUPABASE_PROJECT_REF; - return ref ? `https://supabase.com/dashboard/project/${ref}` : "https://supabase.com/dashboard"; + return ref + ? `https://supabase.com/dashboard/project/${ref}` + : "https://supabase.com/dashboard"; }, }, { @@ -164,7 +166,7 @@ export async function openInBrowser(url: string): Promise<{ success: boolean; me export async function openService( serviceName: string, env: Record<string, string>, - preferDocs = false + preferDocs = false, ): Promise<{ success: boolean; message: string; url: string }> { const service = findService(serviceName); diff --git a/src/output.ts b/src/output.ts index 825d6a59..924abab7 100644 --- a/src/output.ts +++ b/src/output.ts @@ -56,10 +56,7 @@ export function fmtDuration(ms: number): string { * Shares its visual language (▶ / ✓ / ✗ + step duration) with the shell * pre-commit hook generated in hooks.ts. */ -export async function runStep<T>( - label: string, - fn: () => Promise<T> | T, -): Promise<T> { +export async function runStep<T>(label: string, fn: () => Promise<T> | T): Promise<T> { const start = Date.now(); const tty = process.stdout.isTTY === true; @@ -125,30 +122,22 @@ export function printServicesTable(services: ServiceStatus[]): void { } } -export function printSecretsTable( - templateExists: boolean | null, - secrets: SecretStatus[], -): void { +export function printSecretsTable(templateExists: boolean | null, secrets: SecretStatus[]): void { if (secrets.length === 0 && templateExists === null) return; header("Secrets"); if (templateExists !== null) { const icon = templateExists ? CHECK : CROSS; - const status = templateExists - ? `${c.green}found${c.reset}` - : `${c.red}missing${c.reset}`; + const status = templateExists ? `${c.green}found${c.reset}` : `${c.red}missing${c.reset}`; console.log(` ${icon} ${pad("template", 14)} ${status}`); } // When every 1Password-backed secret fails with the same auth error, // collapse them into one banner line instead of spamming N identical rows. const opSecrets = secrets.filter((s) => s.source === "1password"); - const opUnauth = opSecrets.filter((s) => - s.detail.startsWith("1Password not authenticated"), - ); - const aggregate1pUnauth = - opSecrets.length > 0 && opUnauth.length === opSecrets.length; + const opUnauth = opSecrets.filter((s) => s.detail.startsWith("1Password not authenticated")); + const aggregate1pUnauth = opSecrets.length > 0 && opUnauth.length === opSecrets.length; if (aggregate1pUnauth) { console.log( @@ -157,9 +146,7 @@ export function printSecretsTable( console.log(` ${c.yellow}→ run 'op signin' to authenticate${c.reset}`); } - const renderable = aggregate1pUnauth - ? secrets.filter((s) => s.source !== "1password") - : secrets; + const renderable = aggregate1pUnauth ? secrets.filter((s) => s.source !== "1password") : secrets; if (renderable.length === 0) return; @@ -186,37 +173,41 @@ export function printSkillsTable(skills: SkillCheckResult[]): void { for (const skill of skills) { const icon = skill.installed ? CHECK : skill.required ? CROSS : WARN; const name = pad(skill.name, nameWidth); - const tag = skill.required - ? `${c.gray}[required]${c.reset}` - : `${c.gray}[optional]${c.reset}`; + const tag = skill.required ? `${c.gray}[required]${c.reset}` : `${c.gray}[optional]${c.reset}`; const status = skill.installed ? `${c.green}installed${c.reset}` : skill.required ? `${c.red}missing${c.reset}` : `${c.yellow}not installed${c.reset}`; - const version = `${c.dim}${skill.versionSpec}${c.reset}`; - console.log(` ${icon} ${name} ${tag} ${status} ${version}`); - } - } - - export function printWebSearchStatus(status: WebSearchStatus | null): void { - if (!status) return; - - header("Web Search"); - - const icon = status.healthy ? CHECK : CROSS; - const name = pad(status.provider, 14); - const configured = status.configured ? `${c.green}configured${c.reset}` : `${c.yellow}not configured${c.reset}`; - const health = status.healthy ? `${c.green}healthy${c.reset}` : `${c.red}unhealthy${c.reset}`; - const detail = status.error ? `${c.gray}${status.error}${c.reset}` : status.url ? `${c.gray}${status.url}${c.reset}` : ""; + const version = `${c.dim}${skill.versionSpec}${c.reset}`; + console.log(` ${icon} ${name} ${tag} ${status} ${version}`); + } +} - console.log(` ${icon} ${name} ${configured} ${health}`); - if (detail) { - console.log(` ${detail}`); - } - } +export function printWebSearchStatus(status: WebSearchStatus | null): void { + if (!status) return; + + header("Web Search"); + + const icon = status.healthy ? CHECK : CROSS; + const name = pad(status.provider, 14); + const configured = status.configured + ? `${c.green}configured${c.reset}` + : `${c.yellow}not configured${c.reset}`; + const health = status.healthy ? `${c.green}healthy${c.reset}` : `${c.red}unhealthy${c.reset}`; + const detail = status.error + ? `${c.gray}${status.error}${c.reset}` + : status.url + ? `${c.gray}${status.url}${c.reset}` + : ""; + + console.log(` ${icon} ${name} ${configured} ${health}`); + if (detail) { + console.log(` ${detail}`); + } +} - export function printSecurityTable(results: SecurityCheckResult[]): void { +export function printSecurityTable(results: SecurityCheckResult[]): void { if (results.length === 0) return; header("Security"); @@ -231,7 +222,7 @@ export function printSkillsTable(skills: SkillCheckResult[]): void { } const categories = ["dependency", "exposure", "supply-chain", "secrets"] as const; - + for (const category of categories) { const items = byCategory[category]; if (!items || items.length === 0) continue; @@ -249,7 +240,7 @@ export function printSkillsTable(skills: SkillCheckResult[]): void { : `${c.dim}−${c.reset}`; const name = pad(result.name, nameWidth); - + const statusColor = result.status === "pass" ? c.green @@ -260,15 +251,15 @@ export function printSkillsTable(skills: SkillCheckResult[]): void { : c.dim; const detail = `${c.gray}${result.detail}${c.reset}`; - - const severity = result.severity - ? `${c.dim}[${result.severity}]${c.reset}` - : ""; + + const severity = result.severity ? `${c.dim}[${result.severity}]${c.reset}` : ""; const ruleTag = result.rule ? ` ${c.dim}[${result.rule.id}]${c.reset}` : ""; - console.log(` ${icon} ${name} ${statusColor}${result.status}${c.reset} ${detail} ${severity}${ruleTag}`); - + console.log( + ` ${icon} ${name} ${statusColor}${result.status}${c.reset} ${detail} ${severity}${ruleTag}`, + ); + // Show affected files if available (limit to first 5) if (result.files && result.files.length > 0) { const filesToShow = result.files.slice(0, 5); @@ -279,7 +270,7 @@ export function printSkillsTable(skills: SkillCheckResult[]): void { console.log(` ${c.dim}... and ${result.files.length - 5} more file(s)${c.reset}`); } } - + // Show suggestion/remediation if available if (result.suggestion) { console.log(` ${c.yellow}${result.suggestion}${c.reset}`); @@ -303,7 +294,7 @@ export function printLockTable(results: LockCheckResult[]): void { : `${c.red}missing${c.reset}`; const detail = `${c.gray}${result.detail}${c.reset}`; console.log(` ${icon} ${pad(name, 20)} ${status} ${detail}`); - + if (result.missing.length > 0 && result.missing.length <= 5) { const missingList = result.missing.join(", "); console.log(` ${c.dim}Missing: ${missingList}${c.reset}`); @@ -321,7 +312,8 @@ export function printAuditTable(events: import("./audit.js").AuditEvent[]): void const opWidth = Math.max(14, ...events.map((e) => e.operation.length)) + 2; const envWidth = Math.max(6, ...events.map((e) => e.environment.length)) + 2; - const actorWidth = Math.max(8, ...events.map((e) => (e.agent_name ?? e.agent_id ?? "unknown").length)) + 2; + const actorWidth = + Math.max(8, ...events.map((e) => (e.agent_name ?? e.agent_id ?? "unknown").length)) + 2; for (const event of events) { const icon = event.success ? CHECK : CROSS; @@ -331,7 +323,9 @@ export function printAuditTable(events: import("./audit.js").AuditEvent[]): void const actor = pad(event.agent_name ?? event.agent_id ?? "unknown", actorWidth); const duration = event.duration_ms != null ? `${c.dim}${event.duration_ms}ms${c.reset}` : ""; - console.log(` ${icon} ${c.dim}${ts}${c.reset} ${op} ${c.gray}${env}${c.reset} ${actor} ${duration}`); + console.log( + ` ${icon} ${c.dim}${ts}${c.reset} ${op} ${c.gray}${env}${c.reset} ${actor} ${duration}`, + ); if (event.error) { console.log(` ${c.red}Error: ${event.error}${c.reset}`); @@ -366,7 +360,9 @@ export function printSummary( ` ${c.red}(${total - ok} issues)${c.reset}`, ); console.log(); - console.log(`${c.dim}Run ${c.reset}${c.bold}kit install${c.reset}${c.dim} to fix tools, ${c.reset}${c.bold}kit login${c.reset}${c.dim} to fix auth${c.reset}`); + console.log( + `${c.dim}Run ${c.reset}${c.bold}kit install${c.reset}${c.dim} to fix tools, ${c.reset}${c.bold}kit login${c.reset}${c.dim} to fix auth${c.reset}`, + ); } console.log(); diff --git a/src/pkg.ts b/src/pkg.ts index dd86c89c..9765a3ff 100644 --- a/src/pkg.ts +++ b/src/pkg.ts @@ -29,22 +29,25 @@ export interface PkgResult { output: string; } -const ECOSYSTEM_MAP: Record<string, { triageType: TriageType; installCmd: (name: string, version?: string) => string }> = { +const ECOSYSTEM_MAP: Record< + string, + { triageType: TriageType; installCmd: (name: string, version?: string) => string } +> = { npm: { triageType: "npm", - installCmd: (name, ver) => ver ? `npm install ${name}@${ver}` : `npm install ${name}`, + installCmd: (name, ver) => (ver ? `npm install ${name}@${ver}` : `npm install ${name}`), }, "npm-g": { triageType: "npm", - installCmd: (name, ver) => ver ? `npm install -g ${name}@${ver}` : `npm install -g ${name}`, + installCmd: (name, ver) => (ver ? `npm install -g ${name}@${ver}` : `npm install -g ${name}`), }, pnpm: { triageType: "npm", - installCmd: (name, ver) => ver ? `pnpm add ${name}@${ver}` : `pnpm add ${name}`, + installCmd: (name, ver) => (ver ? `pnpm add ${name}@${ver}` : `pnpm add ${name}`), }, pip: { triageType: "pip", - installCmd: (name, ver) => ver ? `pip install ${name}==${ver}` : `pip install ${name}`, + installCmd: (name, ver) => (ver ? `pip install ${name}==${ver}` : `pip install ${name}`), }, brew: { triageType: "repo", @@ -52,7 +55,7 @@ const ECOSYSTEM_MAP: Record<string, { triageType: TriageType; installCmd: (name: }, docker: { triageType: "docker", - installCmd: (name, ver) => ver ? `docker pull ${name}:${ver}` : `docker pull ${name}:latest`, + installCmd: (name, ver) => (ver ? `docker pull ${name}:${ver}` : `docker pull ${name}:latest`), }, go: { triageType: "repo", diff --git a/src/plugin-loader.test.ts b/src/plugin-loader.test.ts index 10a62666..a3a0cda3 100644 --- a/src/plugin-loader.test.ts +++ b/src/plugin-loader.test.ts @@ -21,20 +21,17 @@ async function writePackageJson(kitPlugins: string[]) { await writeFile( join(tmpProject, "package.json"), JSON.stringify({ name: "test-project", kitPlugins }), - "utf-8" + "utf-8", ); } -async function createMockPlugin( - pluginName: string, - exportContent: string -): Promise<void> { +async function createMockPlugin(pluginName: string, exportContent: string): Promise<void> { const pluginDir = join(tmpProject, "node_modules", pluginName); await mkdir(pluginDir, { recursive: true }); await writeFile( join(pluginDir, "package.json"), JSON.stringify({ name: pluginName, version: "1.0.0", main: "index.js" }), - "utf-8" + "utf-8", ); await writeFile(join(pluginDir, "index.js"), exportContent, "utf-8"); } @@ -107,7 +104,9 @@ describe("loadPluginAdapters", () => { }); it("loads multiple plugins at once", async () => { - await createMockPlugin("sandstream-kit-plugin-single2", ` + await createMockPlugin( + "sandstream-kit-plugin-single2", + ` export const adapter = { name: "mock/single2", description: "Single2", @@ -115,8 +114,11 @@ describe("loadPluginAdapters", () => { check: async () => false, provision: async () => ({ success: true, message: "ok" }), }; - `); - await createMockPlugin("sandstream-kit-plugin-multi2", ` + `, + ); + await createMockPlugin( + "sandstream-kit-plugin-multi2", + ` export const adapters = [{ name: "mock/multi2", description: "Multi2", @@ -124,7 +126,8 @@ describe("loadPluginAdapters", () => { check: async () => false, provision: async () => ({ success: true, message: "ok" }), }]; - `); + `, + ); await writePackageJson(["sandstream-kit-plugin-single2", "sandstream-kit-plugin-multi2"]); const result = await loadPluginAdapters(tmpProject); @@ -144,7 +147,7 @@ describe("loadPluginAdapters", () => { assert.deepEqual(result, {}); assert.ok( warnings.some((w) => w.includes("sandstream-kit-plugin-does-not-exist")), - `expected warning about missing plugin, got: ${warnings}` + `expected warning about missing plugin, got: ${warnings}`, ); } finally { console.warn = orig; @@ -152,9 +155,12 @@ describe("loadPluginAdapters", () => { }); it("skips a plugin with invalid exports and does not throw", async () => { - await createMockPlugin("sandstream-kit-plugin-invalid", ` + await createMockPlugin( + "sandstream-kit-plugin-invalid", + ` export const notAnAdapter = "this is not an adapter"; - `); + `, + ); await writePackageJson(["sandstream-kit-plugin-invalid"]); const warnings: string[] = []; @@ -165,7 +171,7 @@ describe("loadPluginAdapters", () => { assert.deepEqual(result, {}); assert.ok( warnings.some((w) => w.includes("sandstream-kit-plugin-invalid")), - `expected warning about invalid plugin, got: ${warnings}` + `expected warning about invalid plugin, got: ${warnings}`, ); } finally { console.warn = orig; @@ -176,7 +182,7 @@ describe("loadPluginAdapters", () => { await writeFile( join(tmpProject, "package.json"), JSON.stringify({ name: "test", kitPlugins: [42, null, "not-installed"] }), - "utf-8" + "utf-8", ); // Should not crash; just warn about "not-installed" (which doesn't exist) const result = await loadPluginAdapters(tmpProject); diff --git a/src/plugin-loader.ts b/src/plugin-loader.ts index fd8445de..cc569056 100644 --- a/src/plugin-loader.ts +++ b/src/plugin-loader.ts @@ -16,9 +16,7 @@ import type { AdapterRegistry, ServiceAdapter } from "./adapters/types.js"; * { "kitPlugins": ["@acme/kit-railway", "sandstream-kit-plugin-aws-s3"] } * ``` */ -export async function loadPluginAdapters( - projectPath: string -): Promise<AdapterRegistry> { +export async function loadPluginAdapters(projectPath: string): Promise<AdapterRegistry> { const registry: AdapterRegistry = {}; const pluginNames = await readkitPlugins(projectPath); @@ -61,7 +59,7 @@ async function readkitPlugins(projectPath: string): Promise<string[]> { */ async function loadSinglePlugin( pluginName: string, - projectPath: string + projectPath: string, ): Promise<ServiceAdapter[]> { // Resolve the plugin from the project's node_modules (not kit's own node_modules) const candidates = [ @@ -124,7 +122,7 @@ function extractAdapters(mod: unknown, pluginName: string): ServiceAdapter[] { } throw new Error( - `Plugin "${pluginName}" must export { adapter } or { adapters } — got keys: ${Object.keys(exports).join(", ")}` + `Plugin "${pluginName}" must export { adapter } or { adapters } — got keys: ${Object.keys(exports).join(", ")}`, ); } diff --git a/src/plugin-registry.test.ts b/src/plugin-registry.test.ts index e7c371bb..c0e03c86 100644 --- a/src/plugin-registry.test.ts +++ b/src/plugin-registry.test.ts @@ -28,15 +28,9 @@ describe("PluginRegistry", () => { it("getCapabilitiesByType filters across plugins", () => { const r = new PluginRegistry(); - r.registerPlugin( - manifest("a", [{ name: "x", type: "secret_store", version: "1.0.0" }]), - ); - r.registerPlugin( - manifest("b", [{ name: "y", type: "secret_store", version: "1.0.0" }]), - ); - r.registerPlugin( - manifest("c", [{ name: "z", type: "tool", version: "1.0.0" }]), - ); + r.registerPlugin(manifest("a", [{ name: "x", type: "secret_store", version: "1.0.0" }])); + r.registerPlugin(manifest("b", [{ name: "y", type: "secret_store", version: "1.0.0" }])); + r.registerPlugin(manifest("c", [{ name: "z", type: "tool", version: "1.0.0" }])); const stores = r.getCapabilitiesByType("secret_store"); assert.equal(stores.size, 2); assert.ok(stores.has("x")); @@ -47,9 +41,7 @@ describe("PluginRegistry", () => { it("hasProvider + getProvider return correct values", () => { const r = new PluginRegistry(); r.registerPlugin( - manifest("p", [ - { name: "searxng", type: "web_search_provider", version: "1.0.0" }, - ]), + manifest("p", [{ name: "searxng", type: "web_search_provider", version: "1.0.0" }]), ); assert.equal(r.hasProvider("searxng"), true); assert.equal(r.hasProvider("brave"), false); diff --git a/src/plugin-registry.ts b/src/plugin-registry.ts index 4fbf0408..bb5883f2 100644 --- a/src/plugin-registry.ts +++ b/src/plugin-registry.ts @@ -137,7 +137,7 @@ export function createRegistryFromSkillsLock(skillsLock: SkillsLockFile): Plugin */ export function getValidWebSearchProviders(registry?: PluginRegistry): string[] { const builtIn = ["brave", "google", "searxng", "custom"]; - + if (!registry) { return builtIn; } diff --git a/src/plugins-cli.ts b/src/plugins-cli.ts index 7024886e..7fe44c76 100644 --- a/src/plugins-cli.ts +++ b/src/plugins-cli.ts @@ -52,7 +52,7 @@ export async function cmdPlugin(): Promise<boolean> { } console.log( - `${c.bold}Available Plugins${tag ? ` (${tag})` : ""}${c.reset} — ${plugins.length} found\n` + `${c.bold}Available Plugins${tag ? ` (${tag})` : ""}${c.reset} — ${plugins.length} found\n`, ); for (const plugin of plugins) { @@ -74,9 +74,7 @@ export async function cmdPlugin(): Promise<boolean> { return true; } - console.log( - `${c.bold}Search Results${c.reset} for "${query}" — ${results.length} found\n` - ); + console.log(`${c.bold}Search Results${c.reset} for "${query}" — ${results.length} found\n`); for (const plugin of results) { console.log(formatPluginForDisplay(plugin)); @@ -142,11 +140,7 @@ export async function cmdPlugin(): Promise<boolean> { for (let i = 0; i < tags.length; i += columns) { const row = tags.slice(i, i + columns); - console.log( - row - .map((tag) => tag.padEnd(maxLen + 1)) - .join(" ") - ); + console.log(row.map((tag) => tag.padEnd(maxLen + 1)).join(" ")); } return true; } @@ -181,12 +175,8 @@ export async function cmdPlugin(): Promise<boolean> { } default: - console.error( - `${c.red}Unknown subcommand: ${subcommand}${c.reset}` - ); - console.error( - `Run 'kit plugin --help' for usage information.` - ); + console.error(`${c.red}Unknown subcommand: ${subcommand}${c.reset}`); + console.error(`Run 'kit plugin --help' for usage information.`); return false; } } catch (err: unknown) { diff --git a/src/plugins.test.ts b/src/plugins.test.ts index ee48491f..e7c4c94b 100644 --- a/src/plugins.test.ts +++ b/src/plugins.test.ts @@ -21,9 +21,7 @@ describe("Plugin Registry", () => { it("should find plugins by description", () => { const results = searchPlugins("payment"); assert(results.length > 0); - assert( - results.some((p) => p.description.toLowerCase().includes("payment")) - ); + assert(results.some((p) => p.description.toLowerCase().includes("payment"))); }); it("should find plugins by tag", () => { @@ -40,10 +38,7 @@ describe("Plugin Registry", () => { it("should rank results by relevance", () => { const results = searchPlugins("stripe"); // Exact name match should come first - assert( - results[0].name === "stripe/payments" || - results[0].name.includes("stripe") - ); + assert(results[0].name === "stripe/payments" || results[0].name.includes("stripe")); }); it("should be case-insensitive", () => { @@ -223,18 +218,12 @@ describe("Plugin Registry", () => { }); it("should have at least 5 plugins", () => { - assert( - DEFAULT_REGISTRY.plugins.length >= 5, - "registry should have at least 5 plugins" - ); + assert(DEFAULT_REGISTRY.plugins.length >= 5, "registry should have at least 5 plugins"); }); it("should have 'official' tag for all built-in plugins", () => { for (const plugin of DEFAULT_REGISTRY.plugins) { - assert( - plugin.tags.includes("official"), - `${plugin.name} should have 'official' tag` - ); + assert(plugin.tags.includes("official"), `${plugin.name} should have 'official' tag`); } }); diff --git a/src/plugins.ts b/src/plugins.ts index 81850086..ad13ef91 100644 --- a/src/plugins.ts +++ b/src/plugins.ts @@ -10,7 +10,6 @@ import { exec } from "./utils/exec.js"; - /** * Plugin metadata as it appears in the registry */ @@ -147,7 +146,7 @@ export const DEFAULT_REGISTRY: PluginRegistry = { */ export function searchPlugins( query: string, - registry: PluginRegistry = DEFAULT_REGISTRY + registry: PluginRegistry = DEFAULT_REGISTRY, ): PluginMetadata[] { const q = query.toLowerCase(); @@ -185,12 +184,10 @@ export function searchPlugins( */ export function listPlugins( tag?: string, - registry: PluginRegistry = DEFAULT_REGISTRY + registry: PluginRegistry = DEFAULT_REGISTRY, ): PluginMetadata[] { if (!tag) { - return registry.plugins.sort( - (a, b) => (b.downloads ?? 0) - (a.downloads ?? 0) - ); + return registry.plugins.sort((a, b) => (b.downloads ?? 0) - (a.downloads ?? 0)); } return registry.plugins @@ -203,12 +200,10 @@ export function listPlugins( */ export function getPluginInfo( name: string, - registry: PluginRegistry = DEFAULT_REGISTRY + registry: PluginRegistry = DEFAULT_REGISTRY, ): PluginMetadata | null { const normalized = name.toLowerCase(); - return ( - registry.plugins.find((p) => p.name.toLowerCase() === normalized) || null - ); + return registry.plugins.find((p) => p.name.toLowerCase() === normalized) || null; } /** @@ -227,19 +222,12 @@ export function getAllTags(registry: PluginRegistry = DEFAULT_REGISTRY): string[ /** * Format a plugin for display in CLI output */ -export function formatPluginForDisplay( - plugin: PluginMetadata, - detailed: boolean = false -): string { +export function formatPluginForDisplay(plugin: PluginMetadata, detailed: boolean = false): string { const lines: string[] = []; // Header line: name, version, rating - const ratingStr = plugin.rating - ? ` ${formatStars(plugin.rating)}` - : ""; - lines.push( - ` ${plugin.name} ${plugin.version}${ratingStr}` - ); + const ratingStr = plugin.rating ? ` ${formatStars(plugin.rating)}` : ""; + lines.push(` ${plugin.name} ${plugin.version}${ratingStr}`); // Description lines.push(` ${plugin.description}`); @@ -298,7 +286,7 @@ export async function isPluginInstalled(packageName: string): Promise<boolean> { */ export async function installPlugin( pluginName: string, - metadata: PluginMetadata + metadata: PluginMetadata, ): Promise<{ success: boolean; message: string }> { try { // Use npm to install the package diff --git a/src/policy.test.ts b/src/policy.test.ts index 2f720631..edd12656 100644 --- a/src/policy.test.ts +++ b/src/policy.test.ts @@ -101,11 +101,7 @@ describe("checkPolicy", () => { }); it("denies with empty allow-list (vendor declared but no ops)", async () => { - const r = await checkPolicy( - { agent_writes: { stripe: [] } }, - "stripe", - "webhook_create", - ); + const r = await checkPolicy({ agent_writes: { stripe: [] } }, "stripe", "webhook_create"); assert.equal(r.approved, false); assert.match(r.reason, /not in \[policy\.agent_writes\.stripe\]/); }); diff --git a/src/post-pull-audit.test.ts b/src/post-pull-audit.test.ts index d1422503..7396984f 100644 --- a/src/post-pull-audit.test.ts +++ b/src/post-pull-audit.test.ts @@ -108,12 +108,26 @@ describe("auditPull", () => { try { writeFileSync( join(dir, ".kit-allowlist.json"), - JSON.stringify({ policy: { enforce_runtime: true, enforce_dev: false, allow_wildcards: false }, packages: [] }, null, 2), + JSON.stringify( + { + policy: { enforce_runtime: true, enforce_dev: false, allow_wildcards: false }, + packages: [], + }, + null, + 2, + ), ); commit(dir, "initial"); writeFileSync( join(dir, ".kit-allowlist.json"), - JSON.stringify({ policy: { enforce_runtime: false, enforce_dev: false, allow_wildcards: true }, packages: [] }, null, 2), + JSON.stringify( + { + policy: { enforce_runtime: false, enforce_dev: false, allow_wildcards: true }, + packages: [], + }, + null, + 2, + ), ); commit(dir, "relax allowlist"); const r = await auditPull(dir); diff --git a/src/post-pull-audit.ts b/src/post-pull-audit.ts index 7fa19eba..a2b40688 100644 --- a/src/post-pull-audit.ts +++ b/src/post-pull-audit.ts @@ -22,7 +22,6 @@ import { findSecrets, type SecretFinding } from "./utils/redactSecrets.js"; import { exec } from "./utils/exec.js"; - export interface PullAuditReport { baseRef: string; headRef: string; @@ -42,11 +41,7 @@ interface PackageJson { devDependencies?: Record<string, string>; } -async function tryGitShow( - ref: string, - path: string, - cwd: string, -): Promise<string | null> { +async function tryGitShow(ref: string, path: string, cwd: string): Promise<string | null> { try { const { stdout } = await exec("git", ["show", `${ref}:${path}`], { cwd, @@ -59,11 +54,7 @@ async function tryGitShow( } } -async function listChangedFiles( - baseRef: string, - headRef: string, - cwd: string, -): Promise<string[]> { +async function listChangedFiles(baseRef: string, headRef: string, cwd: string): Promise<string[]> { try { const { stdout } = await exec( "git", @@ -94,7 +85,10 @@ function diffDeps( }; } -function diffLines(before: string | null, after: string | null): { +function diffLines( + before: string | null, + after: string | null, +): { added: string[]; removed: string[]; } { @@ -191,11 +185,7 @@ export function reportSeverity(report: PullAuditReport): "ok" | "warn" | "fail" if (report.removedGitignoreEntries.some((l) => /\.env|\.pem|\.key|id_rsa/.test(l))) { return "fail"; } - if ( - report.newDependencies.length > 0 || - report.allowlistChanged || - report.policyChanged - ) { + if (report.newDependencies.length > 0 || report.allowlistChanged || report.policyChanged) { return "warn"; } return "ok"; diff --git a/src/provision.test.ts b/src/provision.test.ts index 76decf36..b4b7eb87 100644 --- a/src/provision.test.ts +++ b/src/provision.test.ts @@ -23,7 +23,7 @@ afterEach(async () => { describe("provisionService", () => { it("returns error for unknown service", async () => { const result = await provisionService("unknown/service", testProjectPath); - + assert.equal(result.success, false); assert(result.error?.includes("Unknown service")); assert(result.message?.includes("Available services")); @@ -33,7 +33,7 @@ describe("provisionService", () => { // This test will only work if we mock the tool check // For now, we just verify the response structure const result = await provisionService("stripe/payments", testProjectPath); - + // Either success or error, but structure should be consistent assert(result.success !== undefined); assert(result.message !== undefined); @@ -43,11 +43,11 @@ describe("provisionService", () => { // Create a mock adapter that doesn't require external tools // This is more of an integration test structure const result = await provisionService("stripe/payments", testProjectPath, "test-project"); - + // Verify result structure assert(typeof result.success === "boolean"); assert(typeof result.message === "string"); - + if (result.success && result.secrets) { // If successful, verify secrets structure assert(typeof result.secrets === "object"); @@ -57,10 +57,10 @@ describe("provisionService", () => { it("updates skills-lock.json with provisioning info", async () => { // Similar structure verification test const result = await provisionService("supabase/db", testProjectPath, "test-project"); - + assert(typeof result.success === "boolean"); assert(typeof result.message === "string"); - + if (result.success && result.config) { assert(typeof result.config === "object"); } @@ -70,7 +70,7 @@ describe("provisionService", () => { describe("listAvailableServices", () => { it("returns list of available services", () => { const services = listAvailableServices(); - + assert(Array.isArray(services)); assert(services.length > 0); assert(services.includes("stripe/payments")); @@ -83,7 +83,7 @@ describe("listAvailableServices", () => { describe("getServiceInfo", () => { it("returns service information for known service", () => { const info = getServiceInfo("stripe/payments"); - + assert(info !== null); assert.equal(info?.name, "stripe/payments"); assert(typeof info?.description === "string"); @@ -92,13 +92,13 @@ describe("getServiceInfo", () => { it("returns null for unknown service", () => { const info = getServiceInfo("unknown/service"); - + assert.equal(info, null); }); it("includes required tools in service info", () => { const info = getServiceInfo("stripe/payments"); - + assert(info !== null); assert(info.tools.length > 0); assert(info.tools.includes("stripe")); diff --git a/src/provision.ts b/src/provision.ts index 3f26a8af..f2d8bea5 100644 --- a/src/provision.ts +++ b/src/provision.ts @@ -11,18 +11,18 @@ async function loadExistingEnv(projectPath: string): Promise<Record<string, stri try { const envPath = resolve(projectPath, ".env.local"); const content = await readFile(envPath, "utf-8"); - + const env: Record<string, string> = {}; for (const line of content.split("\n")) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith("#")) continue; - + const [key, ...valueParts] = trimmed.split("="); if (key && valueParts.length > 0) { env[key.trim()] = valueParts.join("=").trim(); } } - + return env; } catch { return {}; @@ -32,22 +32,19 @@ async function loadExistingEnv(projectPath: string): Promise<Record<string, stri /** * Update .env.local with new secrets */ -async function updateEnvFile( - projectPath: string, - secrets: Record<string, string> -): Promise<void> { +async function updateEnvFile(projectPath: string, secrets: Record<string, string>): Promise<void> { const envPath = resolve(projectPath, ".env.local"); const existing = await loadExistingEnv(projectPath); - + // Merge with existing const merged = { ...existing, ...secrets }; - + // Write back const lines: string[] = []; for (const [key, value] of Object.entries(merged)) { lines.push(`${key}=${value}`); } - + await writeFile(envPath, lines.join("\n") + "\n", "utf-8"); } @@ -57,10 +54,10 @@ async function updateEnvFile( async function updateSkillsLock( projectPath: string, serviceName: string, - config: Record<string, unknown> + config: Record<string, unknown>, ): Promise<void> { const lockPath = resolve(projectPath, "skills-lock.json"); - + let lockData: any = { provisioned: {} }; try { const content = await readFile(lockPath, "utf-8"); @@ -68,16 +65,16 @@ async function updateSkillsLock( } catch { // File doesn't exist or parse error } - + if (!lockData.provisioned) { lockData.provisioned = {}; } - + lockData.provisioned[serviceName] = { ...config, provisionedAt: new Date().toISOString(), }; - + await writeFile(lockPath, JSON.stringify(lockData, null, 2) + "\n", "utf-8"); } @@ -87,7 +84,7 @@ async function updateSkillsLock( export async function provisionService( serviceName: string, projectPath: string, - projectName?: string + projectName?: string, ): Promise<ProvisionResult> { // Merge built-in adapters with any plugin adapters from kitPlugins in package.json const pluginAdapters = await loadPluginAdapters(projectPath); @@ -103,7 +100,7 @@ export async function provisionService( message: `Available services: ${available}`, }; } - + // Check required tools const requiredTools = adapter.getRequiredTools(); for (const tool of requiredTools) { @@ -120,7 +117,7 @@ export async function provisionService( }; } } - + // Load context const existingEnv = await loadExistingEnv(projectPath); const context: AdapterContext = { @@ -128,7 +125,7 @@ export async function provisionService( projectName, existingEnv, }; - + // Check if already provisioned const alreadyProvisioned = await adapter.check(context); if (alreadyProvisioned) { @@ -138,22 +135,22 @@ export async function provisionService( config: { alreadyProvisioned: true }, }; } - + // Provision the service const result = await adapter.provision(context); - + if (result.success) { // Update .env.local with secrets if (result.secrets && Object.keys(result.secrets).length > 0) { await updateEnvFile(projectPath, result.secrets); } - + // Update skills-lock.json with config if (result.config) { await updateSkillsLock(projectPath, serviceName, result.config); } } - + return result; } @@ -167,10 +164,12 @@ export function listAvailableServices(): string[] { /** * Get adapter info */ -export function getServiceInfo(serviceName: string): { name: string; description: string; tools: string[] } | null { +export function getServiceInfo( + serviceName: string, +): { name: string; description: string; tools: string[] } | null { const adapter = adapters[serviceName]; if (!adapter) return null; - + return { name: adapter.name, description: adapter.description, diff --git a/src/recommended.test.ts b/src/recommended.test.ts index bb65c1a9..e69ffdb7 100644 --- a/src/recommended.test.ts +++ b/src/recommended.test.ts @@ -13,7 +13,10 @@ describe("applyRecommendedHardening", () => { tmp = mkdtempSync(join(tmpdir(), "kit-recommended-")); }); beforeEach(() => { - process.env.KIT_CLAUDE_SETTINGS = join(tmp, `claude-${Math.random().toString(36).slice(2)}.json`); + process.env.KIT_CLAUDE_SETTINGS = join( + tmp, + `claude-${Math.random().toString(36).slice(2)}.json`, + ); }); after(() => { if (prev === undefined) delete process.env.KIT_CLAUDE_SETTINGS; @@ -45,7 +48,10 @@ describe("applyRecommendedHardening", () => { it("omits the pre-push context-check gate when no context is declared", async () => { const g = gitDir(); const r = await applyRecommendedHardening({}, g); - assert.ok(r.hooks.some((h) => h.hookName === "pre-commit"), "still installs pre-commit"); + assert.ok( + r.hooks.some((h) => h.hookName === "pre-commit"), + "still installs pre-commit", + ); assert.equal(existsSync(join(g, "hooks", "pre-push")), false, "no pre-push without context"); }); }); diff --git a/src/resend-email.test.ts b/src/resend-email.test.ts index 08b0d71c..9c4ce87e 100644 --- a/src/resend-email.test.ts +++ b/src/resend-email.test.ts @@ -22,7 +22,7 @@ describe("resendEmailAdapter", () => { it("check returns true when RESEND_API_KEY is present and starts with re_", async () => { const result = await resendEmailAdapter.check( - mockContext({ RESEND_API_KEY: "re_abc123_validkey" }) + mockContext({ RESEND_API_KEY: "re_abc123_validkey" }), ); assert.equal(result, true); }); @@ -33,7 +33,7 @@ describe("resendEmailAdapter", () => { it("check returns false when RESEND_API_KEY does not start with re_", async () => { const result = await resendEmailAdapter.check( - mockContext({ RESEND_API_KEY: "sk_live_not_a_resend_key" }) + mockContext({ RESEND_API_KEY: "sk_live_not_a_resend_key" }), ); assert.equal(result, false); }); @@ -45,7 +45,7 @@ describe("resendEmailAdapter", () => { mockContext({ RESEND_API_KEY: "re_existing_abc123", RESEND_FROM_EMAIL: "hello@example.com", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.RESEND_API_KEY, "re_existing_abc123"); @@ -55,7 +55,7 @@ describe("resendEmailAdapter", () => { it("provision uses default from email when RESEND_FROM_EMAIL is absent", async () => { const result = await resendEmailAdapter.provision( - mockContext({ RESEND_API_KEY: "re_existing_abc123" }) + mockContext({ RESEND_API_KEY: "re_existing_abc123" }), ); assert.equal(result.success, true); assert.equal(result.secrets?.RESEND_FROM_EMAIL, "onboarding@resend.dev"); @@ -66,20 +66,26 @@ describe("resendEmailAdapter", () => { it("provision returns error with setup instructions when RESEND_API_KEY is missing", async () => { const result = await resendEmailAdapter.provision(mockContext()); assert.equal(result.success, false); - assert.ok(result.message.includes("resend.com/api-keys"), `expected dashboard URL in message: ${result.message}`); - assert.ok(result.message.includes("RESEND_API_KEY"), `expected RESEND_API_KEY in message: ${result.message}`); + assert.ok( + result.message.includes("resend.com/api-keys"), + `expected dashboard URL in message: ${result.message}`, + ); + assert.ok( + result.message.includes("RESEND_API_KEY"), + `expected RESEND_API_KEY in message: ${result.message}`, + ); }); // ─── provision() — invalid key format ─────────────────────────────────────── it("provision returns error when key does not start with re_", async () => { const result = await resendEmailAdapter.provision( - mockContext({ RESEND_API_KEY: "not_a_resend_key_12345" }) + mockContext({ RESEND_API_KEY: "not_a_resend_key_12345" }), ); assert.equal(result.success, false); assert.ok( result.error?.includes("does not look valid") || result.message.includes("re_"), - `expected validation error, got: ${result.error} / ${result.message}` + `expected validation error, got: ${result.error} / ${result.message}`, ); }); }); diff --git a/src/revocation.ts b/src/revocation.ts index ef98f0ea..b7ecfc37 100644 --- a/src/revocation.ts +++ b/src/revocation.ts @@ -26,10 +26,7 @@ export async function checkRevocationStatus( const now = Date.now(); const checkInterval = (fullConfig.revocation.check_interval || 300) * 1000; - if ( - cachedRevocationStatus && - now - lastRevocationCheck < checkInterval - ) { + if (cachedRevocationStatus && now - lastRevocationCheck < checkInterval) { return cachedRevocationStatus.revoked; } @@ -53,10 +50,7 @@ async function fetchRevocationStatus( } try { - const endpoint = config.revocation.revocation_endpoint.replace( - "{agent_id}", - config.agent.id, - ); + const endpoint = config.revocation.revocation_endpoint.replace("{agent_id}", config.agent.id); const response = await fetch(endpoint, { method: "GET", @@ -103,9 +97,7 @@ export async function forceRevocationCheck( /** * Clear local secrets and caches (called when revocation detected) */ -export async function handleRevocation( - config: GovernanceConfig | undefined, -): Promise<void> { +export async function handleRevocation(config: GovernanceConfig | undefined): Promise<void> { console.error("\n" + "=".repeat(80)); console.error("ACCESS REVOKED"); console.error("=".repeat(80)); diff --git a/src/rules/catalog.ts b/src/rules/catalog.ts index ff9e3995..a4d84790 100644 --- a/src/rules/catalog.ts +++ b/src/rules/catalog.ts @@ -43,14 +43,37 @@ const owasp = (num: string, slug: string, title: string): RuleRef => ({ * citations), "requirements.txt" (presence, not a weakness). */ export const SECURITY_RULES: Record<string, RuleRef> = { - ".env gitignored": cwe(538, "Insertion of Sensitive Information into Externally-Accessible File or Directory"), + ".env gitignored": cwe( + 538, + "Insertion of Sensitive Information into Externally-Accessible File or Directory", + ), "secrets scan": cwe(798, "Use of Hard-coded Credentials"), - "npm audit": owasp("A06", "A06_2021-Vulnerable_and_Outdated_Components", "A06:2021 Vulnerable and Outdated Components"), - "pip-audit": owasp("A06", "A06_2021-Vulnerable_and_Outdated_Components", "A06:2021 Vulnerable and Outdated Components"), - "trivy container scan": owasp("A06", "A06_2021-Vulnerable_and_Outdated_Components", "A06:2021 Vulnerable and Outdated Components"), + "npm audit": owasp( + "A06", + "A06_2021-Vulnerable_and_Outdated_Components", + "A06:2021 Vulnerable and Outdated Components", + ), + "pip-audit": owasp( + "A06", + "A06_2021-Vulnerable_and_Outdated_Components", + "A06:2021 Vulnerable and Outdated Components", + ), + "trivy container scan": owasp( + "A06", + "A06_2021-Vulnerable_and_Outdated_Components", + "A06:2021 Vulnerable and Outdated Components", + ), "pinned versions": cwe(1104, "Use of Unmaintained Third Party Components"), - "package-lock.json": owasp("A08", "A08_2021-Software_and_Data_Integrity_Failures", "A08:2021 Software and Data Integrity Failures"), - "socket scan": owasp("A08", "A08_2021-Software_and_Data_Integrity_Failures", "A08:2021 Software and Data Integrity Failures"), + "package-lock.json": owasp( + "A08", + "A08_2021-Software_and_Data_Integrity_Failures", + "A08:2021 Software and Data Integrity Failures", + ), + "socket scan": owasp( + "A08", + "A08_2021-Software_and_Data_Integrity_Failures", + "A08:2021 Software and Data Integrity Failures", + ), Ollama: cwe(668, "Exposure of Resource to Wrong Sphere"), "Remote API": cwe(668, "Exposure of Resource to Wrong Sphere"), }; diff --git a/src/run.test.ts b/src/run.test.ts index 12b5166c..4ba63900 100644 --- a/src/run.test.ts +++ b/src/run.test.ts @@ -112,7 +112,7 @@ describe("executeCommand", () => { assert.equal(result.exitCode, 127, "Should return exit code 127 for command not found"); assert( result.stderr.includes("Failed to execute") || result.stderr !== "", - "Should have error message" + "Should have error message", ); }); @@ -121,7 +121,7 @@ describe("executeCommand", () => { await writeFile( envPath, "# This is a comment\nVAR_WITH_COMMENT=value-1\n# Another comment\nVAR2=value-2\n", - "utf-8" + "utf-8", ); const result = await executeCommand({ @@ -140,7 +140,11 @@ describe("executeCommand", () => { // Use process.execPath (absolute path to node) — with inheritEnv:false // the child gets an empty PATH and can't resolve bare "node". const result = await executeCommand({ - commandArgs: [process.execPath, "-e", "console.log(process.env.ISOLATED_TEST_VAR || 'undefined')"], + commandArgs: [ + process.execPath, + "-e", + "console.log(process.env.ISOLATED_TEST_VAR || 'undefined')", + ], cwd: tmpDir, inheritEnv: false, envOverrides: { ISOLATED_TEST_VAR: "should-appear" }, @@ -164,7 +168,11 @@ describe("executeCommand", () => { it("handles multiline output correctly", async () => { const result = await executeCommand({ - commandArgs: ["node", "-e", "console.log('line1'); console.log('line2'); console.log('line3')"], + commandArgs: [ + "node", + "-e", + "console.log('line1'); console.log('line2'); console.log('line3')", + ], cwd: tmpDir, }); diff --git a/src/run.ts b/src/run.ts index e1c2b2b3..e37b4ef0 100644 --- a/src/run.ts +++ b/src/run.ts @@ -32,7 +32,9 @@ export async function executeCommand(opts: RunOptions): Promise<RunResult> { } // Build environment - const env: Record<string, string> = inheritEnv ? { ...process.env as Record<string, string> } : {}; + const env: Record<string, string> = inheritEnv + ? { ...(process.env as Record<string, string>) } + : {}; // Load .env.local if it exists const envPath = resolve(cwd, ".env.local"); diff --git a/src/sbom.test.ts b/src/sbom.test.ts index ea66b6ef..7baf865e 100644 --- a/src/sbom.test.ts +++ b/src/sbom.test.ts @@ -23,7 +23,10 @@ describe("lockComponents", () => { describe("toCycloneDX", () => { it("emits CycloneDX with purls", () => { - const bom = toCycloneDX(lockComponents(lockPkgs)) as { bomFormat: string; components: { purl: string }[] }; + const bom = toCycloneDX(lockComponents(lockPkgs)) as { + bomFormat: string; + components: { purl: string }[]; + }; assert.equal(bom.bomFormat, "CycloneDX"); assert.equal(bom.components.length, 2); assert.equal(bom.components[0].purl, "pkg:npm/lodash@4.17.21"); @@ -32,7 +35,10 @@ describe("toCycloneDX", () => { describe("toSpdx", () => { it("emits SPDX packages with purl externalRefs", () => { - const doc = toSpdx(lockComponents(lockPkgs)) as { spdxVersion: string; packages: { versionInfo: string; externalRefs: { referenceLocator: string }[] }[] }; + const doc = toSpdx(lockComponents(lockPkgs)) as { + spdxVersion: string; + packages: { versionInfo: string; externalRefs: { referenceLocator: string }[] }[]; + }; assert.equal(doc.spdxVersion, "SPDX-2.3"); assert.equal(doc.packages.length, 2); assert.equal(doc.packages[0].externalRefs[0].referenceLocator, "pkg:npm/lodash@4.17.21"); @@ -41,16 +47,34 @@ describe("toSpdx", () => { describe("toSarif", () => { const findings: SecurityCheckResult[] = [ - { category: "dependency", name: "lodash CVE-x", status: "fail", detail: "proto pollution", severity: "high", rule: { id: "OWASP-A06", source: "owasp", ref: "https://owasp.org/x", title: "Vuln Components" } }, + { + category: "dependency", + name: "lodash CVE-x", + status: "fail", + detail: "proto pollution", + severity: "high", + rule: { + id: "OWASP-A06", + source: "owasp", + ref: "https://owasp.org/x", + title: "Vuln Components", + }, + }, { category: "exposure", name: "minor", status: "warn", detail: "meh", severity: "low" }, ]; it("maps findings to SARIF results + rules with severity/level", () => { - const sarif = toSarif(findings) as { version: string; runs: { tool: { driver: { name: string; rules: unknown[] } }; results: { ruleId: string; level: string }[] }[] }; + const sarif = toSarif(findings) as { + version: string; + runs: { + tool: { driver: { name: string; rules: unknown[] } }; + results: { ruleId: string; level: string }[]; + }[]; + }; assert.equal(sarif.version, "2.1.0"); assert.equal(sarif.runs[0].tool.driver.name, "kit"); assert.equal(sarif.runs[0].results.length, 2); assert.equal(sarif.runs[0].results[0].level, "error"); // high → error - assert.equal(sarif.runs[0].results[1].level, "note"); // low → note + assert.equal(sarif.runs[0].results[1].level, "note"); // low → note assert.equal(sarif.runs[0].tool.driver.rules.length, 2); }); }); diff --git a/src/sbom.ts b/src/sbom.ts index 4c658a12..a0f11390 100644 --- a/src/sbom.ts +++ b/src/sbom.ts @@ -39,7 +39,12 @@ export function toCycloneDX(components: Component[]): unknown { bomFormat: "CycloneDX", specVersion: "1.5", version: 1, - components: components.map((c) => ({ type: "library", name: c.name, version: c.version, purl: purl(c) })), + components: components.map((c) => ({ + type: "library", + name: c.name, + version: c.version, + purl: purl(c), + })), }; } @@ -71,7 +76,13 @@ export function toSarif(findings: SecurityCheckResult[]): unknown { id: f.name, name: f.name, properties: { - ...(f.severity ? { "security-severity": { critical: "9.5", high: "8.0", medium: "5.0", low: "2.0" }[f.severity] } : {}), + ...(f.severity + ? { + "security-severity": { critical: "9.5", high: "8.0", medium: "5.0", low: "2.0" }[ + f.severity + ], + } + : {}), ...(f.rule ? { tags: [f.rule.id], helpUri: f.rule.ref } : {}), }, })); @@ -80,7 +91,9 @@ export function toSarif(findings: SecurityCheckResult[]): unknown { $schema: "https://json.schemastore.org/sarif-2.1.0.json", runs: [ { - tool: { driver: { name: "kit", informationUri: "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/sandstream/kit", rules } }, + tool: { + driver: { name: "kit", informationUri: "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/sandstream/kit", rules }, + }, results: findings.map((f) => ({ ruleId: f.name, level: sarifLevel(f.severity), diff --git a/src/scan-build.test.ts b/src/scan-build.test.ts index 14613e08..79d71042 100644 --- a/src/scan-build.test.ts +++ b/src/scan-build.test.ts @@ -54,10 +54,7 @@ describe("scanBuildArtifacts", () => { try { mkdirSync(join(dir, "dist"), { recursive: true }); mkdirSync(join(dir, "out"), { recursive: true }); - writeFileSync( - join(dir, "dist", "bundle.js"), - 'AKIA0123456789ABCDEF\n', - ); + writeFileSync(join(dir, "dist", "bundle.js"), "AKIA0123456789ABCDEF\n"); writeFileSync( join(dir, "out", "index.html"), '<meta data-token="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.SflKxwRJSMeKKF2QT4fwpMeJf36">\n', @@ -79,7 +76,10 @@ describe("scanBuildArtifacts", () => { join(dir, ".next", "routes-manifest.json"), JSON.stringify({ headers: [ - { source: "/", headers: [{ key: "x-mw", value: "twenty-plus-character-route-value-login" }] }, + { + source: "/", + headers: [{ key: "x-mw", value: "twenty-plus-character-route-value-login" }], + }, ], }), ); @@ -112,14 +112,8 @@ describe("scanBuildArtifacts", () => { try { mkdirSync(join(dir, ".next"), { recursive: true }); mkdirSync(join(dir, "my-bundle"), { recursive: true }); - writeFileSync( - join(dir, ".next", "a.js"), - "sk_"+"live_NotInTheCustomScannedDirsAtAll\n", - ); - writeFileSync( - join(dir, "my-bundle", "b.js"), - "sk_"+"live_AaBbCcDdEeFfGgHhIiJjKkLl\n", - ); + writeFileSync(join(dir, ".next", "a.js"), "sk_" + "live_NotInTheCustomScannedDirsAtAll\n"); + writeFileSync(join(dir, "my-bundle", "b.js"), "sk_" + "live_AaBbCcDdEeFfGgHhIiJjKkLl\n"); const hits = await scanBuildArtifacts(dir, ["my-bundle"]); assert.equal(hits.length, 1); assert.ok(hits[0].file.includes("my-bundle")); diff --git a/src/scan-build.ts b/src/scan-build.ts index 592505b4..da881dcb 100644 --- a/src/scan-build.ts +++ b/src/scan-build.ts @@ -47,12 +47,7 @@ const SCANNABLE_EXTS = new Set([ ".env.production", ]); -const SKIP_DIRS = new Set([ - "node_modules", - ".git", - ".pnpm-store", - "cache", -]); +const SKIP_DIRS = new Set(["node_modules", ".git", ".pnpm-store", "cache"]); const MAX_BYTES = 5 * 1024 * 1024; // 5 MiB @@ -63,12 +58,7 @@ const MAX_BYTES = 5 * 1024 * 1024; // 5 MiB // state construct, so these labels are filtered out here. const BUILD_IRRELEVANT_LABELS = new Set(["tfstate-value", "terraform-sensitive"]); -async function walk( - dir: string, - out: string[], - depth = 0, - maxDepth = 8, -): Promise<void> { +async function walk(dir: string, out: string[], depth = 0, maxDepth = 8): Promise<void> { if (depth > maxDepth) return; let entries; try { @@ -82,9 +72,7 @@ async function walk( if (ent.isDirectory()) { await walk(full, out, depth + 1, maxDepth); } else if (ent.isFile()) { - const ext = ent.name.includes(".") - ? ent.name.slice(ent.name.lastIndexOf(".")) - : ""; + const ext = ent.name.includes(".") ? ent.name.slice(ent.name.lastIndexOf(".")) : ""; if (!SCANNABLE_EXTS.has(ext) && !ent.name.startsWith(".env")) continue; out.push(full); } @@ -119,9 +107,7 @@ export async function scanBuildArtifacts( } catch { continue; } - const findings = findSecrets(content).filter( - (f) => !BUILD_IRRELEVANT_LABELS.has(f.label), - ); + const findings = findSecrets(content).filter((f) => !BUILD_IRRELEVANT_LABELS.has(f.label)); if (findings.length > 0) { // Strip leading cwd from path for readable reporting. const rel = path.startsWith(cwd) ? path.slice(cwd.length + 1) : path; diff --git a/src/scan-plaintext.ts b/src/scan-plaintext.ts index 631d6702..537a1e14 100644 --- a/src/scan-plaintext.ts +++ b/src/scan-plaintext.ts @@ -76,14 +76,8 @@ export async function scanPlaintextSecrets( const hits: PlaintextHit[] = []; const seenRealPaths = new Set<string>(); - const fileTargets = opts.overrideFiles ?? [ - ...DEFAULT_FILE_NAMES, - ...(opts.extraFiles ?? []), - ]; - const dirTargets = opts.overrideDirs ?? [ - ...DEFAULT_RECURSIVE_DIRS, - ...(opts.extraDirs ?? []), - ]; + const fileTargets = opts.overrideFiles ?? [...DEFAULT_FILE_NAMES, ...(opts.extraFiles ?? [])]; + const dirTargets = opts.overrideDirs ?? [...DEFAULT_RECURSIVE_DIRS, ...(opts.extraDirs ?? [])]; const maxDepth = opts.maxDepth ?? 3; const scanFile = async (relativePath: string, absolutePath: string) => { diff --git a/src/scan-staged.test.ts b/src/scan-staged.test.ts index a2a031e1..8ec1adc7 100644 --- a/src/scan-staged.test.ts +++ b/src/scan-staged.test.ts @@ -14,7 +14,6 @@ function tmpGitRepo(): string { return dir; } - describe("scanStagedFiles", () => { it("returns empty when no files are staged", async () => { const dir = tmpGitRepo(); @@ -43,7 +42,7 @@ describe("scanStagedFiles", () => { try { writeFileSync( join(dir, ".env"), - "STRIPE_SECRET_KEY=sk_te"+"st_51T2AMtJLRlXeUG4dKBwX2nsve3BLEzy\n", + "STRIPE_SECRET_KEY=sk_te" + "st_51T2AMtJLRlXeUG4dKBwX2nsve3BLEzy\n", ); execSync("git add .env", { cwd: dir }); const hits = await scanStagedFiles(dir); @@ -58,8 +57,7 @@ describe("scanStagedFiles", () => { it("flags a staged Supabase service-role JWT", async () => { const dir = tmpGitRepo(); try { - const jwt = - "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.SflKxwRJSMeKKF2QT4fwpMeJf36"; + const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.SflKxwRJSMeKKF2QT4fwpMeJf36"; writeFileSync(join(dir, ".env.local"), `SERVICE_ROLE=${jwt}\n`); execSync("git add .env.local", { cwd: dir }); const hits = await scanStagedFiles(dir); @@ -73,7 +71,7 @@ describe("scanStagedFiles", () => { it("flags multiple files in one scan", async () => { const dir = tmpGitRepo(); try { - writeFileSync(join(dir, "a.env"), "STRIPE_KEY=sk_te"+"st_AAAAAAAAAAAAAAAAAAAA\n"); + writeFileSync(join(dir, "a.env"), "STRIPE_KEY=sk_te" + "st_AAAAAAAAAAAAAAAAAAAA\n"); writeFileSync(join(dir, "b.txt"), "AKIA01234567890ABCDE\n"); execSync("git add a.env b.txt", { cwd: dir }); const hits = await scanStagedFiles(dir); diff --git a/src/scan-staged.ts b/src/scan-staged.ts index 79fd89cd..25b436a8 100644 --- a/src/scan-staged.ts +++ b/src/scan-staged.ts @@ -2,7 +2,6 @@ import { readFile } from "node:fs/promises"; import { findSecrets, type SecretFinding } from "./utils/redactSecrets.js"; import { exec } from "./utils/exec.js"; - export interface StagedHit { file: string; findings: SecretFinding[]; @@ -35,8 +34,14 @@ export async function scanStagedFiles(cwd: string = process.cwd()): Promise<Stag } const args = hasHead ? ["diff", "--cached", "--name-only", "--diff-filter=AM", "-z"] - : ["diff", "--cached", "--name-only", "--diff-filter=AM", "-z", - "4b825dc642cb6eb9a060e54bf8d69288fbee4904"]; // Git's well-known empty tree + : [ + "diff", + "--cached", + "--name-only", + "--diff-filter=AM", + "-z", + "4b825dc642cb6eb9a060e54bf8d69288fbee4904", + ]; // Git's well-known empty tree const { stdout } = await exec("git", args, { cwd, timeout: 5_000 }); paths = stdout.split("\0").filter(Boolean); } catch { diff --git a/src/scan-transcripts.test.ts b/src/scan-transcripts.test.ts index 38aeba4d..c457e4ff 100644 --- a/src/scan-transcripts.test.ts +++ b/src/scan-transcripts.test.ts @@ -41,7 +41,10 @@ describe("scanTranscripts", () => { mkdirSync(join(dir, ".claude", "projects"), { recursive: true }); writeFileSync( join(dir, ".claude", "projects", "session-1.jsonl"), - '{"type":"user","content":"My Stripe key is ' + "sk_li" + "ve_AbCdEfGhIjKlMnOpQrStUv" + '"}\n', + '{"type":"user","content":"My Stripe key is ' + + "sk_li" + + "ve_AbCdEfGhIjKlMnOpQrStUv" + + '"}\n', ); const hits = await scanTranscripts(dir); assert.equal(hits.length, 1); @@ -55,10 +58,7 @@ describe("scanTranscripts", () => { const dir = makeRepo(); try { mkdirSync(join(dir, ".opencode"), { recursive: true }); - writeFileSync( - join(dir, ".opencode", "history.jsonl"), - '{"text":"AKIA0123456789ABCDEF"}\n', - ); + writeFileSync(join(dir, ".opencode", "history.jsonl"), '{"text":"AKIA0123456789ABCDEF"}\n'); const hits = await scanTranscripts(dir); assert.equal(hits.length, 1); assert.ok(hits[0].file.includes(".opencode")); diff --git a/src/scan-transcripts.ts b/src/scan-transcripts.ts index 86b48df2..ac5b4395 100644 --- a/src/scan-transcripts.ts +++ b/src/scan-transcripts.ts @@ -38,12 +38,7 @@ async function dirExists(path: string): Promise<boolean> { } } -async function walk( - dir: string, - out: string[], - depth = 0, - maxDepth = 6, -): Promise<void> { +async function walk(dir: string, out: string[], depth = 0, maxDepth = 6): Promise<void> { if (depth > maxDepth) return; let entries; try { @@ -57,9 +52,7 @@ async function walk( if (ent.isDirectory()) { await walk(full, out, depth + 1, maxDepth); } else if (ent.isFile()) { - const ext = ent.name.includes(".") - ? ent.name.slice(ent.name.lastIndexOf(".")) - : ""; + const ext = ent.name.includes(".") ? ent.name.slice(ent.name.lastIndexOf(".")) : ""; if (!SCANNABLE_EXTS.has(ext)) continue; out.push(full); } @@ -75,9 +68,7 @@ function repoSlug(cwd: string): string { return cwd.replace(/^\//, "-").replace(/\//g, "-"); } -export async function scanTranscripts( - cwd: string = process.cwd(), -): Promise<TranscriptHit[]> { +export async function scanTranscripts(cwd: string = process.cwd()): Promise<TranscriptHit[]> { const candidates: string[] = []; // Project-local agent dirs diff --git a/src/scanners.test.ts b/src/scanners.test.ts index 8900ed97..b591def3 100644 --- a/src/scanners.test.ts +++ b/src/scanners.test.ts @@ -1,10 +1,25 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { dedupKey, mergeFindings, suppressBaselined, runScanners, type ScanDeps, type ScannerDef } from "./scanners.js"; +import { + dedupKey, + mergeFindings, + suppressBaselined, + runScanners, + type ScanDeps, + type ScannerDef, +} from "./scanners.js"; import type { SecurityCheckResult } from "./check-security.js"; -const f = (name: string, severity: SecurityCheckResult["severity"], detail = ""): SecurityCheckResult => ({ - category: "dependency", name, status: "fail", detail, severity, +const f = ( + name: string, + severity: SecurityCheckResult["severity"], + detail = "", +): SecurityCheckResult => ({ + category: "dependency", + name, + status: "fail", + detail, + severity, }); describe("dedupKey", () => { @@ -37,7 +52,14 @@ describe("mergeFindings", () => { describe("runScanners (injected deps)", () => { const SARIF = JSON.stringify({ - runs: [{ tool: { driver: { name: "trivy" } }, results: [{ ruleId: "CVE-2021-23337", level: "error", message: { text: "lodash CVE-2021-23337" } }] }], + runs: [ + { + tool: { driver: { name: "trivy" } }, + results: [ + { ruleId: "CVE-2021-23337", level: "error", message: { text: "lodash CVE-2021-23337" } }, + ], + }, + ], }); const defs: ScannerDef[] = [ { id: "snyk", bin: "snyk", args: [], format: "sarif", needsToken: "SNYK_TOKEN" }, @@ -63,7 +85,10 @@ describe("runScanners (injected deps)", () => { describe("suppressBaselined", () => { const merged = mergeFindings([ - { id: "trivy", findings: [f("x: CVE-2021-23337", "high"), f("verify-suite: stripe-token", "critical")] }, + { + id: "trivy", + findings: [f("x: CVE-2021-23337", "high"), f("verify-suite: stripe-token", "critical")], + }, ]); it("drops findings whose key is in the baseline, keeps the rest", () => { const accepted = new Set(["verify-suite: stripe-token"]); // the FP, baselined (dedupKey = name) diff --git a/src/scanners.ts b/src/scanners.ts index 527cb663..c0e67cb1 100644 --- a/src/scanners.ts +++ b/src/scanners.ts @@ -30,7 +30,12 @@ export const SCANNERS: ScannerDef[] = [ { id: "snyk", bin: "snyk", args: ["test", "--sarif"], format: "sarif", needsToken: "SNYK_TOKEN" }, { id: "trivy", bin: "trivy", args: ["fs", "--format", "sarif", "--quiet", "."], format: "sarif" }, { id: "grype", bin: "grype", args: ["dir:.", "-o", "sarif", "-q"], format: "sarif" }, - { id: "semgrep", bin: "semgrep", args: ["scan", "--sarif", "--quiet", "--config", "auto", "."], format: "sarif" }, + { + id: "semgrep", + bin: "semgrep", + args: ["scan", "--sarif", "--quiet", "--config", "auto", "."], + format: "sarif", + }, { id: "osv-scanner", bin: "osv-scanner", args: ["--format", "json", "-r", "."], format: "osv" }, ]; @@ -38,7 +43,9 @@ const RANK: Record<string, number> = { critical: 4, high: 3, medium: 2, low: 1 } /** Cross-scanner dedup key: a CVE/GHSA id if present in the finding, else its name. */ export function dedupKey(f: SecurityCheckResult): string { - const m = /(CVE-\d{4}-\d{1,7}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})/i.exec(`${f.name} ${f.detail ?? ""}`); + const m = /(CVE-\d{4}-\d{1,7}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})/i.exec( + `${f.name} ${f.detail ?? ""}`, + ); return m ? m[1].toUpperCase() : f.name; } @@ -48,7 +55,9 @@ export interface MergedFinding extends SecurityCheckResult { } /** Collapse findings from many scanners by dedupKey — max severity, union of scanners. */ -export function mergeFindings(perScanner: { id: string; findings: SecurityCheckResult[] }[]): MergedFinding[] { +export function mergeFindings( + perScanner: { id: string; findings: SecurityCheckResult[] }[], +): MergedFinding[] { const byKey = new Map<string, MergedFinding>(); for (const { id, findings } of perScanner) { for (const f of findings) { @@ -64,7 +73,9 @@ export function mergeFindings(perScanner: { id: string; findings: SecurityCheckR } } } - return [...byKey.values()].sort((a, b) => (RANK[b.severity ?? "low"] ?? 0) - (RANK[a.severity ?? "low"] ?? 0)); + return [...byKey.values()].sort( + (a, b) => (RANK[b.severity ?? "low"] ?? 0) - (RANK[a.severity ?? "low"] ?? 0), + ); } /** Drop merged findings whose key is in the accepted baseline (#59 noise-reduction). */ diff --git a/src/secret-backends.test.ts b/src/secret-backends.test.ts index ff1ff93d..66602113 100644 --- a/src/secret-backends.test.ts +++ b/src/secret-backends.test.ts @@ -55,7 +55,9 @@ describe("secret backend registry", () => { it("reads from process.env for source=env", async () => { process.env.KIT_BACKEND_TEST_VAR = "hello-env"; try { - const r = await resolveViaBackend("KIT_BACKEND_TEST_VAR", { source: "env" } as SecretKeyConfig); + const r = await resolveViaBackend("KIT_BACKEND_TEST_VAR", { + source: "env", + } as SecretKeyConfig); assert.equal(r.resolved, true); assert.equal(r.value, "hello-env"); assert.equal(r.detail, "From environment"); @@ -66,19 +68,18 @@ describe("secret backend registry", () => { it("reports not-set for an absent env var", async () => { delete process.env.KIT_BACKEND_DEFINITELY_ABSENT; - const r = await resolveViaBackend( - "KIT_BACKEND_DEFINITELY_ABSENT", - { source: "env" } as SecretKeyConfig, - ); + const r = await resolveViaBackend("KIT_BACKEND_DEFINITELY_ABSENT", { + source: "env", + } as SecretKeyConfig); assert.equal(r.resolved, false); assert.equal(r.detail, "Not set in environment"); }); it("reads inline value for source=config", async () => { - const r = await resolveViaBackend( - "X", - { source: "config", value: "inline-secret" } as SecretKeyConfig, - ); + const r = await resolveViaBackend("X", { + source: "config", + value: "inline-secret", + } as SecretKeyConfig); assert.equal(r.resolved, true); assert.equal(r.value, "inline-secret"); assert.equal(r.detail, "From config"); diff --git a/src/secret-backends.ts b/src/secret-backends.ts index 1190ae5e..66d25c8f 100644 --- a/src/secret-backends.ts +++ b/src/secret-backends.ts @@ -84,13 +84,15 @@ export function resetInfisicalCache(): void { infisicalCache = null; } -async function fetchInfisicalSecrets( +/** + * Bulk-fetch one Infisical project/env's secrets via `infisical export` (NO cache). + * Use for an explicit project (e.g. a shared tooling project) distinct from the + * repo's app-secrets binding. Empty map on any failure (fail-open). + */ +export async function fetchInfisicalProjectSecrets( infisicalConfig?: InfisicalConfig, ): Promise<Map<string, string>> { - if (infisicalCache) return infisicalCache; - const env = infisicalConfig?.environment ?? "dev"; - try { const exportArgs = ["export", "--format=json", "--env", env]; if (infisicalConfig?.project_id) { @@ -99,7 +101,6 @@ async function fetchInfisicalSecrets( if (infisicalConfig?.path) { exportArgs.push("--path", infisicalConfig.path); } - const { stdout } = await execCli("infisical", exportArgs, { timeout: 15_000, env: { ...process.env }, @@ -115,14 +116,20 @@ async function fetchInfisicalSecrets( if (typeof v === "string") cache.set(k, v); } } - infisicalCache = cache; return cache; } catch { - infisicalCache = new Map(); - return infisicalCache; + return new Map(); } } +async function fetchInfisicalSecrets( + infisicalConfig?: InfisicalConfig, +): Promise<Map<string, string>> { + if (infisicalCache) return infisicalCache; + infisicalCache = await fetchInfisicalProjectSecrets(infisicalConfig); + return infisicalCache; +} + // ─── Backend registry ───────────────────────────────────────────────────────── export const BACKENDS: Record<string, SecretBackend> = { @@ -211,14 +218,18 @@ export const BACKENDS: Record<string, SecretBackend> = { timeout: 15_000, }); } catch { - await execCli("op", [ - "item", - "create", - `--category=Login`, - `--title=${project}`, - `--vault=${vault}`, - `${key}=${value}`, - ], { timeout: 15_000 }); + await execCli( + "op", + [ + "item", + "create", + `--category=Login`, + `--title=${project}`, + `--vault=${vault}`, + `${key}=${value}`, + ], + { timeout: 15_000 }, + ); } return { ok: true, ref: `op://${vault}/${project}/${key}`, detail: "wrote to 1Password" }; }, @@ -553,19 +564,16 @@ export const BACKENDS: Record<string, SecretBackend> = { }, async write(key, value, opts) { if (!opts.vault) { - return { ok: false, detail: "Azure: --vault required (azure_vault or AZURE_KEYVAULT_NAME)" }; + return { + ok: false, + detail: "Azure: --vault required (azure_vault or AZURE_KEYVAULT_NAME)", + }; } - await exec("az", [ - "keyvault", - "secret", - "set", - "--vault-name", - opts.vault, - "--name", - key, - "--value", - value, - ], { timeout: 15_000 }); + await exec( + "az", + ["keyvault", "secret", "set", "--vault-name", opts.vault, "--name", key, "--value", value], + { timeout: 15_000 }, + ); return { ok: true, detail: `wrote to Azure Key Vault ${opts.vault}` }; }, }, diff --git a/src/secret-expiration.test.ts b/src/secret-expiration.test.ts index e56f315f..871b9597 100644 --- a/src/secret-expiration.test.ts +++ b/src/secret-expiration.test.ts @@ -132,10 +132,11 @@ describe("checkSecretExpiration - env var hints", () => { process.env.EXPIRED_KEY_EXPIRES_AT = daysAgo(3); process.env.WARNING_KEY_EXPIRES_AT = daysFromNow(5); - const result = await checkSecretExpiration( - enabledConfig, - ["EXPIRED_KEY", "WARNING_KEY", "FINE_KEY"], - ); + const result = await checkSecretExpiration(enabledConfig, [ + "EXPIRED_KEY", + "WARNING_KEY", + "FINE_KEY", + ]); // FINE_KEY has no hint, so only 2 entries assert.equal(result.length, 2); @@ -160,11 +161,7 @@ describe("checkSecretExpiration - store dispatch", () => { store: "infisical", keys: { INFISICAL_KEY: { source: "infisical" } }, }; - const result = await checkSecretExpiration( - enabledConfig, - ["INFISICAL_KEY"], - secretsConfig, - ); + const result = await checkSecretExpiration(enabledConfig, ["INFISICAL_KEY"], secretsConfig); assert.equal(result.length, 1); assert.equal(result[0].expired, true); @@ -177,11 +174,7 @@ describe("checkSecretExpiration - store dispatch", () => { store: "doppler", keys: { DOPPLER_KEY: { source: "doppler" } }, }; - const result = await checkSecretExpiration( - enabledConfig, - ["DOPPLER_KEY"], - secretsConfig, - ); + const result = await checkSecretExpiration(enabledConfig, ["DOPPLER_KEY"], secretsConfig); assert.equal(result.length, 1); assert.equal(result[0].expired, true); @@ -193,11 +186,7 @@ describe("checkSecretExpiration - store dispatch", () => { const secretsConfig: SecretsConfig = { keys: { BW_KEY: { source: "bitwarden", name: "My Password" } }, }; - const result = await checkSecretExpiration( - enabledConfig, - ["BW_KEY"], - secretsConfig, - ); + const result = await checkSecretExpiration(enabledConfig, ["BW_KEY"], secretsConfig); assert.equal(result.length, 1); assert.equal(result[0].warning, true); @@ -209,11 +198,7 @@ describe("checkSecretExpiration - store dispatch", () => { const secretsConfig: SecretsConfig = { keys: { OP_KEY: { source: "1password" } }, // no ref }; - const result = await checkSecretExpiration( - enabledConfig, - ["OP_KEY"], - secretsConfig, - ); + const result = await checkSecretExpiration(enabledConfig, ["OP_KEY"], secretsConfig); assert.equal(result.length, 1); assert.equal(result[0].expired, true); @@ -282,8 +267,20 @@ describe("formatSecretExpirationWarnings", () => { it("shows both expired and warning sections when both present", () => { const expirations: SecretExpiration[] = [ - { key: "DEAD", expiry_date: daysAgo(1), days_until_expiry: -1, expired: true, warning: false }, - { key: "SOON", expiry_date: daysFromNow(5), days_until_expiry: 5, expired: false, warning: true }, + { + key: "DEAD", + expiry_date: daysAgo(1), + days_until_expiry: -1, + expired: true, + warning: false, + }, + { + key: "SOON", + expiry_date: daysFromNow(5), + days_until_expiry: 5, + expired: false, + warning: true, + }, ]; const output = formatSecretExpirationWarnings(expirations); assert.ok(output.includes("EXPIRED")); @@ -294,31 +291,19 @@ describe("formatSecretExpirationWarnings", () => { describe("hasExpiredSecrets / hasSecretWarnings", () => { it("hasExpiredSecrets returns false when none expired", () => { assert.equal(hasExpiredSecrets([]), false); - assert.equal( - hasExpiredSecrets([{ key: "k", expired: false, warning: true }]), - false, - ); + assert.equal(hasExpiredSecrets([{ key: "k", expired: false, warning: true }]), false); }); it("hasExpiredSecrets returns true when any expired", () => { - assert.equal( - hasExpiredSecrets([{ key: "k", expired: true, warning: false }]), - true, - ); + assert.equal(hasExpiredSecrets([{ key: "k", expired: true, warning: false }]), true); }); it("hasSecretWarnings returns false when none warning", () => { assert.equal(hasSecretWarnings([]), false); - assert.equal( - hasSecretWarnings([{ key: "k", expired: true, warning: false }]), - false, - ); + assert.equal(hasSecretWarnings([{ key: "k", expired: true, warning: false }]), false); }); it("hasSecretWarnings returns true when any warning", () => { - assert.equal( - hasSecretWarnings([{ key: "k", expired: false, warning: true }]), - true, - ); + assert.equal(hasSecretWarnings([{ key: "k", expired: false, warning: true }]), true); }); }); diff --git a/src/secret-expiration.ts b/src/secret-expiration.ts index 2e759f5a..9a9ef792 100644 --- a/src/secret-expiration.ts +++ b/src/secret-expiration.ts @@ -2,7 +2,6 @@ import type { GovernanceConfig, SecretsConfig, SecretKeyConfig } from "./config. import { mergeGovernanceConfig } from "./governance.js"; import { exec } from "./utils/exec.js"; - export interface SecretExpiration { key: string; expiry_date?: string; @@ -37,9 +36,7 @@ export async function checkSecretExpiration( const daysUntilExpiry = calculateDaysUntilExpiry(expiration); const expired = daysUntilExpiry !== null && daysUntilExpiry < 0; const warning = - daysUntilExpiry !== null && - daysUntilExpiry >= 0 && - daysUntilExpiry <= warnDays; + daysUntilExpiry !== null && daysUntilExpiry >= 0 && daysUntilExpiry <= warnDays; expirations.push({ key, @@ -172,9 +169,7 @@ function calculateDaysUntilExpiry(expiryDate: string): number | null { /** * Format secret expiration warnings for display */ -export function formatSecretExpirationWarnings( - expirations: SecretExpiration[], -): string { +export function formatSecretExpirationWarnings(expirations: SecretExpiration[]): string { const expired = expirations.filter((e) => e.expired); const warning = expirations.filter((e) => e.warning); diff --git a/src/secrets-migrate.test.ts b/src/secrets-migrate.test.ts index 4c34312f..883a6c10 100644 --- a/src/secrets-migrate.test.ts +++ b/src/secrets-migrate.test.ts @@ -39,11 +39,7 @@ describe("isValidKeyName", () => { describe("writeSecretToBackend - invalid keys", () => { it("refuses to call the sink CLI when key is invalid", async () => { - const result = await writeSecretToBackend( - "1password", - "--malicious-flag", - "any-value", - ); + const result = await writeSecretToBackend("1password", "--malicious-flag", "any-value"); assert.equal(result.ok, false); assert.ok(result.detail.includes("invalid key name")); }); @@ -110,7 +106,7 @@ describe("planMigration", () => { [ "NEXT_PUBLIC_SUPABASE_URL=https://abc.supabase.co", "RESEND_FROM_EMAIL=noreply@example.com", - "STRIPE_SECRET_KEY=sk_te"+"st_AAAAAAAAAAAAAAAAAAAAAA", + "STRIPE_SECRET_KEY=sk_te" + "st_AAAAAAAAAAAAAAAAAAAAAA", "# comment line", "", ].join("\n"), @@ -128,7 +124,7 @@ describe("planMigration", () => { join(dir, ".env.production"), [ "NEXT_PUBLIC_SUPABASE_URL=https://abc.supabase.co", - "STRIPE_SECRET_KEY=sk_te"+"st_AAAAAAAAAAAAAAAAAAAAAA", + "STRIPE_SECRET_KEY=sk_te" + "st_AAAAAAAAAAAAAAAAAAAAAA", ].join("\n"), ); const plan = await planMigration(dir, { secretsOnly: true }); @@ -139,10 +135,7 @@ describe("planMigration", () => { it("strips simple quotes from values", async () => { const dir = mkdtempSync(join(tmpdir(), "kit-plan-")); - writeFileSync( - join(dir, ".env"), - `URL="https://a.example.com"\nALT='single-quoted'\n`, - ); + writeFileSync(join(dir, ".env"), `URL="https://a.example.com"\nALT='single-quoted'\n`); const plan = await planMigration(dir); assert.equal(plan.keyValues.get("URL")?.value, "https://a.example.com"); assert.equal(plan.keyValues.get("ALT")?.value, "single-quoted"); diff --git a/src/secrets-migrate.ts b/src/secrets-migrate.ts index c96ade88..80af5ebd 100644 --- a/src/secrets-migrate.ts +++ b/src/secrets-migrate.ts @@ -5,7 +5,6 @@ import { scanPlaintextSecrets, type PlaintextHit } from "./scan-plaintext.js"; import { redactSecrets } from "./utils/redactSecrets.js"; import { writeViaBackend, type WriteResult } from "./secret-backends.js"; - /** * Conservative env-var-style identifier check. * @@ -45,10 +44,10 @@ function safeErrorMessage(err: unknown, knownSecrets: string[] = []): string { export interface MigrationRecord { key: string; - source: string; // file the key was read from - vault: string; // backend store + source: string; // file the key was read from + vault: string; // backend store written: boolean; - cleaned: boolean; // plaintext removed from source + cleaned: boolean; // plaintext removed from source detail: string; } diff --git a/src/secrets-model.ts b/src/secrets-model.ts index bbc0d872..8b462418 100644 --- a/src/secrets-model.ts +++ b/src/secrets-model.ts @@ -3,7 +3,14 @@ * Encrypted storage, key rotation, secret sharing, audit trails */ -export type SecretType = "api_key" | "password" | "oauth_token" | "database_url" | "ssh_key" | "certificate" | "custom"; +export type SecretType = + | "api_key" + | "password" + | "oauth_token" + | "database_url" + | "ssh_key" + | "certificate" + | "custom"; export type RotationPolicy = "never" | "30d" | "60d" | "90d" | "manual"; export type AccessLevel = "owner" | "admin" | "team" | "shared"; diff --git a/src/secrets-onecli.test.ts b/src/secrets-onecli.test.ts index 1e2f4461..2ed72be7 100644 --- a/src/secrets-onecli.test.ts +++ b/src/secrets-onecli.test.ts @@ -1,10 +1,6 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { - resolveOneCliConfig, - generatePlaceholder, - checkOneCliStatus, -} from "./secrets-onecli.js"; +import { resolveOneCliConfig, generatePlaceholder, checkOneCliStatus } from "./secrets-onecli.js"; describe("resolveOneCliConfig", () => { it("defaults to localhost when no env vars are set", () => { diff --git a/src/secrets-onecli.ts b/src/secrets-onecli.ts index 01fb288a..a74aec50 100644 --- a/src/secrets-onecli.ts +++ b/src/secrets-onecli.ts @@ -68,8 +68,7 @@ export async function checkOneCliStatus( } if (!cfg.apiKey) { - status.error = - "ONECLI_API_KEY not set — generate one at /settings/api-keys"; + status.error = "ONECLI_API_KEY not set — generate one at /settings/api-keys"; return status; } @@ -121,9 +120,7 @@ export async function registerSecretInOneCli( cfg: OneCliConfig = resolveOneCliConfig(), ): Promise<RegisterSecretResult> { if (!cfg.apiKey) { - throw new Error( - "ONECLI_API_KEY not set — generate one in OneCLI's UI (Settings → API Keys)", - ); + throw new Error("ONECLI_API_KEY not set — generate one in OneCLI's UI (Settings → API Keys)"); } const body = { name: input.name, diff --git a/src/secrets-propagate.test.ts b/src/secrets-propagate.test.ts index 08a91818..2eb35d1a 100644 --- a/src/secrets-propagate.test.ts +++ b/src/secrets-propagate.test.ts @@ -40,10 +40,7 @@ describe("propagate", () => { // PATH in this test runner, so each adapter exits non-zero with code 127 // (command not found). What we care about here is the SHAPE: one result // per target, no exceptions thrown out. - const results = await propagate("TEST_KEY", "test-value", [ - "vercel", - "github", - ]); + const results = await propagate("TEST_KEY", "test-value", ["vercel", "github"]); assert.equal(results.length, 2); assert.equal(results[0].target, "vercel"); assert.equal(results[1].target, "github"); diff --git a/src/secrets-propagate.ts b/src/secrets-propagate.ts index 4d56900c..450f37f9 100644 --- a/src/secrets-propagate.ts +++ b/src/secrets-propagate.ts @@ -20,13 +20,7 @@ import { spawn } from "node:child_process"; -export type PropagationTarget = - | "vercel" - | "github" - | "fly" - | "cloudflare" - | "railway" - | "aws-ssm"; +export type PropagationTarget = "vercel" | "github" | "fly" | "cloudflare" | "railway" | "aws-ssm"; export const ALL_TARGETS: PropagationTarget[] = [ "vercel", @@ -101,12 +95,17 @@ async function propagateVercel( const args = ["env", "add", name, env]; if (opts.vercelScope) args.push("--scope", opts.vercelScope); // Remove existing first so add doesn't error on duplicate. - await spawnWithStdin("vercel", ["env", "rm", name, env, "--yes", ...(opts.vercelScope ? ["--scope", opts.vercelScope] : [])], ""); + await spawnWithStdin( + "vercel", + ["env", "rm", name, env, "--yes", ...(opts.vercelScope ? ["--scope", opts.vercelScope] : [])], + "", + ); const { code, stderr } = await spawnWithStdin("vercel", args, value); return { target: "vercel", ok: code === 0, - detail: code === 0 ? `pushed to vercel env=${env}` : `vercel exit ${code}: ${stderr.split("\n")[0]}`, + detail: + code === 0 ? `pushed to vercel env=${env}` : `vercel exit ${code}: ${stderr.split("\n")[0]}`, valueInArgv: false, }; } @@ -153,7 +152,10 @@ async function propagateFly( return { target: "fly", ok: code === 0, - detail: code === 0 ? `pushed to fly app=${opts.flyApp}` : `fly exit ${code}: ${stderr.split("\n")[0]}`, + detail: + code === 0 + ? `pushed to fly app=${opts.flyApp}` + : `fly exit ${code}: ${stderr.split("\n")[0]}`, valueInArgv: true, }; } @@ -179,7 +181,10 @@ async function propagateCloudflare( return { target: "cloudflare", ok: code === 0, - detail: code === 0 ? `pushed to cloudflare worker=${opts.cfWorker}` : `wrangler exit ${code}: ${stderr.split("\n")[0]}`, + detail: + code === 0 + ? `pushed to cloudflare worker=${opts.cfWorker}` + : `wrangler exit ${code}: ${stderr.split("\n")[0]}`, valueInArgv: false, }; } @@ -226,7 +231,10 @@ async function propagateAwsSsm( return { target: "aws-ssm", ok: code === 0, - detail: code === 0 ? `pushed to aws-ssm path=${paramName}` : `aws exit ${code}: ${stderr.split("\n")[0]}`, + detail: + code === 0 + ? `pushed to aws-ssm path=${paramName}` + : `aws exit ${code}: ${stderr.split("\n")[0]}`, valueInArgv: false, }; } diff --git a/src/secrets-pull.ts b/src/secrets-pull.ts index ffaa823a..f87b8da7 100644 --- a/src/secrets-pull.ts +++ b/src/secrets-pull.ts @@ -45,9 +45,7 @@ async function fetchFromSource( env?: string, ): Promise<Array<{ key: string; value: string; target?: string[] }>> { if (source === "vercel") { - const { makeClient, listEnvVars } = await import( - "sandstream-kit-plugin-vercel" as string - ); + const { makeClient, listEnvVars } = await import("sandstream-kit-plugin-vercel" as string); const client = makeClient(); const all = await listEnvVars(client, projectId); return all @@ -65,9 +63,7 @@ async function fetchFromSource( // GitHub Actions secrets are write-only via the API (you can list names // but never read values back). We surface name-only so the operator // knows what's defined upstream. - const { makeClient, listRepoSecrets } = await import( - "sandstream-kit-plugin-github" as string - ); + const { makeClient, listRepoSecrets } = await import("sandstream-kit-plugin-github" as string); const [owner, repo] = projectId.split("/"); if (!owner || !repo) { throw new Error("github source requires projectId in 'owner/repo' format"); @@ -80,9 +76,7 @@ async function fetchFromSource( if (source === "fly") { // Fly secret VALUES are not retrievable via API (digest-only). Same // name-only path as GitHub. - const { makeClient, listAppSecrets } = await import( - "sandstream-kit-plugin-fly" as string - ); + const { makeClient, listAppSecrets } = await import("sandstream-kit-plugin-fly" as string); const client = makeClient(); const secrets = await listAppSecrets(client, projectId); return secrets.map((s: { name: string }) => ({ key: s.name, value: "" })); diff --git a/src/secrets-purge-history.test.ts b/src/secrets-purge-history.test.ts index f93459b4..9ae45b86 100644 --- a/src/secrets-purge-history.test.ts +++ b/src/secrets-purge-history.test.ts @@ -18,7 +18,7 @@ function makeRepoWithLeak(): { dir: string; leakValue: string } { writeFileSync(join(dir, "README.md"), "# repo\n"); git(dir, "add", "README.md"); git(dir, "commit", "-q", "-m", "init"); - const leakValue = "sk_"+"test_AAAAAAAAAAAAAAAAAAAA1234"; + const leakValue = "sk_" + "test_AAAAAAAAAAAAAAAAAAAA1234"; writeFileSync(join(dir, "config.txt"), `STRIPE=${leakValue}\n`); git(dir, "add", "config.txt"); git(dir, "commit", "-q", "-m", "oops"); diff --git a/src/secrets-purge-history.ts b/src/secrets-purge-history.ts index 6bf3c1e9..ce229a90 100644 --- a/src/secrets-purge-history.ts +++ b/src/secrets-purge-history.ts @@ -23,7 +23,6 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { exec } from "./utils/exec.js"; - export type Tool = "git-filter-repo" | "bfg"; export interface ToolStatus { @@ -64,11 +63,11 @@ export async function previewMatches( pattern: string, cwd: string = process.cwd(), ): Promise<PurgePreview> { - const { stdout: hashesOut } = await exec( - "git", - ["log", "--pretty=%H", "-S", pattern, "--all"], - { cwd, timeout: 30_000, maxBuffer: 10 * 1024 * 1024 }, - ).catch(() => ({ stdout: "" })); + const { stdout: hashesOut } = await exec("git", ["log", "--pretty=%H", "-S", pattern, "--all"], { + cwd, + timeout: 30_000, + maxBuffer: 10 * 1024 * 1024, + }).catch(() => ({ stdout: "" })); const hashes = hashesOut.split("\n").filter(Boolean); const fileSet = new Set<string>(); @@ -161,11 +160,11 @@ export async function purgeHistory( if (tools.bfgAvailable) { try { - const { stdout } = await exec( - "bfg", - ["--replace-text", replacementFile, cwd], - { cwd, timeout: 600_000, maxBuffer: 50 * 1024 * 1024 }, - ); + const { stdout } = await exec("bfg", ["--replace-text", replacementFile, cwd], { + cwd, + timeout: 600_000, + maxBuffer: 50 * 1024 * 1024, + }); // bfg leaves dangling refs; user must run `git reflog expire --expire=now --all && git gc --prune=now --aggressive`. return { toolUsed: "bfg", diff --git a/src/secrets-rotate-cli.ts b/src/secrets-rotate-cli.ts index 2b5727ae..05163e7d 100644 --- a/src/secrets-rotate-cli.ts +++ b/src/secrets-rotate-cli.ts @@ -31,8 +31,14 @@ export interface RotationPlaybook { export function identifyProvider(keyName: string): RotationPlaybook["provider"] { const upper = keyName.toUpperCase(); if (upper.startsWith("STRIPE_")) return "stripe"; - if (upper.startsWith("AWS_") || upper === "AWS_ACCESS_KEY_ID" || upper === "AWS_SECRET_ACCESS_KEY") return "aws-iam"; - if (upper.startsWith("GCP_") || upper.endsWith("_GOOGLE_APPLICATION_CREDENTIALS")) return "gcp-iam"; + if ( + upper.startsWith("AWS_") || + upper === "AWS_ACCESS_KEY_ID" || + upper === "AWS_SECRET_ACCESS_KEY" + ) + return "aws-iam"; + if (upper.startsWith("GCP_") || upper.endsWith("_GOOGLE_APPLICATION_CREDENTIALS")) + return "gcp-iam"; if (upper.startsWith("GITHUB_") || upper === "GH_TOKEN") return "github-pat"; if (upper.startsWith("OPENAI_")) return "openai"; return "unknown"; @@ -80,8 +86,7 @@ export function buildPlaybook(keyName: string): RotationPlaybook { "# Capture the contents of new-key.json (or just the private_key field).", ], newValueSource: "contents of new-key.json", - revokeStep: - "gcloud iam service-accounts keys delete <old-key-id> --iam-account=<sa-email>", + revokeStep: "gcloud iam service-accounts keys delete <old-key-id> --iam-account=<sa-email>", docsUrl: "https://cloud.google.com/iam/docs/keys-create-delete", }; case "github-pat": @@ -94,8 +99,7 @@ export function buildPlaybook(keyName: string): RotationPlaybook { "# one you're replacing.", ], newValueSource: "GitHub settings UI", - revokeStep: - "Revoke the old PAT in the same UI (Delete button beside the entry).", + revokeStep: "Revoke the old PAT in the same UI (Delete button beside the entry).", docsUrl: "https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens", }; @@ -130,7 +134,12 @@ import { isNonInteractive } from "./environment.js"; import { writeSecretToBackend } from "./secrets-migrate.js"; import { planRotation } from "./secrets-rotate.js"; import { requireElevation, consumeElevation } from "./elevation.js"; -import { propagate, parseTargets, ALL_TARGETS, type PropagationOptions } from "./secrets-propagate.js"; +import { + propagate, + parseTargets, + ALL_TARGETS, + type PropagationOptions, +} from "./secrets-propagate.js"; import { promptConfirm } from "./utils/prompt.js"; import { c } from "./utils/colors.js"; @@ -146,7 +155,18 @@ function resolveConfigPath(): string { * backend-write options. */ export function pickBackendOpts( - secrets: { keys?: Record<string, { ref?: string; azure_vault?: string; gcp_project?: string; aws_region?: string; vault_path?: string }> }, + secrets: { + keys?: Record< + string, + { + ref?: string; + azure_vault?: string; + gcp_project?: string; + aws_region?: string; + vault_path?: string; + } + >; + }, keyName: string, { envFallback = false }: { envFallback?: boolean } = {}, ): { vault?: string; project?: string; region?: string; vaultPath?: string } { @@ -163,9 +183,14 @@ export function pickBackendOpts( // vars when the .kit.toml key doesn't pin a value. Never clobber a value // already derived from the 1Password ref above. if (key?.azure_vault) opts.vault = key.azure_vault; - else if (envFallback && !opts.vault && process.env.AZURE_KEYVAULT_NAME) opts.vault = process.env.AZURE_KEYVAULT_NAME; + else if (envFallback && !opts.vault && process.env.AZURE_KEYVAULT_NAME) + opts.vault = process.env.AZURE_KEYVAULT_NAME; if (key?.gcp_project) opts.project = key.gcp_project; - else if (envFallback && !opts.project && (process.env.GCP_PROJECT || process.env.GOOGLE_CLOUD_PROJECT)) + else if ( + envFallback && + !opts.project && + (process.env.GCP_PROJECT || process.env.GOOGLE_CLOUD_PROJECT) + ) opts.project = process.env.GCP_PROJECT || process.env.GOOGLE_CLOUD_PROJECT; if (key?.aws_region) opts.region = key.aws_region; else if (envFallback && process.env.AWS_REGION) opts.region = process.env.AWS_REGION; @@ -173,21 +198,15 @@ export function pickBackendOpts( return opts; } -async function cmdSecretsRotateSupabaseMgmt( - keyName: string, - args: string[], -): Promise<boolean> { +async function cmdSecretsRotateSupabaseMgmt(keyName: string, args: string[]): Promise<boolean> { console.log(`${c.bold}${c.cyan}kit secrets rotate --via supabase-mgmt-api${c.reset}`); console.log(`${c.dim}${"─".repeat(50)}${c.reset}\n`); // Project ref: --project <ref> flag or SUPABASE_PROJECT_REF env var. const projectIdx = args.indexOf("--project"); - const projectRef = - projectIdx >= 0 ? args[projectIdx + 1] : process.env.SUPABASE_PROJECT_REF; + const projectRef = projectIdx >= 0 ? args[projectIdx + 1] : process.env.SUPABASE_PROJECT_REF; if (!projectRef) { - console.error( - `${c.red}--project <ref> required (or set SUPABASE_PROJECT_REF).${c.reset}`, - ); + console.error(`${c.red}--project <ref> required (or set SUPABASE_PROJECT_REF).${c.reset}`); console.error( `${c.dim}Find your project ref at https://supabase.com/dashboard/project/_/settings/general (URL contains the ref).${c.reset}`, ); @@ -237,11 +256,11 @@ async function cmdSecretsRotateSupabaseMgmt( // Default to the recommended mode when the user didn't pin one. if (!mode) { - mode = (preview.recommendedMode ?? "scoped-key-mint") as - | "scoped-key-mint" - | "jwt-secret-roll"; + mode = (preview.recommendedMode ?? "scoped-key-mint") as "scoped-key-mint" | "jwt-secret-roll"; } - console.log(`${c.dim}Mode: ${c.bold}${mode}${c.reset}${c.dim}${explicitMode ? "" : " (auto)"}${c.reset}`); + console.log( + `${c.dim}Mode: ${c.bold}${mode}${c.reset}${c.dim}${explicitMode ? "" : " (auto)"}${c.reset}`, + ); // If the explicit mode conflicts with what the project supports, warn // loudly and require --force. This is the gate that would have prevented @@ -285,18 +304,17 @@ async function cmdSecretsRotateSupabaseMgmt( console.log(); if (dryRun) { - console.log( - `${c.dim}--dry-run: not rotating. Remove flag to proceed.${c.reset}\n`, - ); + console.log(`${c.dim}--dry-run: not rotating. Remove flag to proceed.${c.reset}\n`); return true; } // S12 elevation required for rotation. jwt-secret-roll is a hard cutover // — one elevation = one rotation. Other modes (scoped-key-mint with // rollback) keep the standard 15-min TTL. - const elev = mode === "jwt-secret-roll" - ? await consumeElevation("rotate") - : await requireElevation("rotate"); + const elev = + mode === "jwt-secret-roll" + ? await consumeElevation("rotate") + : await requireElevation("rotate"); if (!elev.ok) { console.error(`${c.red}✗ ${elev.reason}${c.reset}`); return false; @@ -423,11 +441,7 @@ export async function cmdSecretsRotate(): Promise<boolean> { console.log(`${c.bold}Steps to mint the new credential:${c.reset}`); for (const step of playbook.steps) { const isComment = step.startsWith("#"); - console.log( - isComment - ? ` ${c.dim}${step}${c.reset}` - : ` ${c.green}$${c.reset} ${step}`, - ); + console.log(isComment ? ` ${c.dim}${step}${c.reset}` : ` ${c.green}$${c.reset} ${step}`); } console.log(); console.log( @@ -473,9 +487,7 @@ export async function cmdSecretsRotate(): Promise<boolean> { ); if (dryRun) { - console.log( - `${c.dim}--dry-run: not writing. Remove flag to perform rotation.${c.reset}\n`, - ); + console.log(`${c.dim}--dry-run: not writing. Remove flag to perform rotation.${c.reset}\n`); return true; } @@ -490,12 +502,7 @@ export async function cmdSecretsRotate(): Promise<boolean> { // right vault / region / project / Azure vault. const backendOpts = pickBackendOpts(config.secrets, keyName, { envFallback: true }); - const writeResult = await writeSecretToBackend( - plan.store, - plan.key, - value, - backendOpts, - ); + const writeResult = await writeSecretToBackend(plan.store, plan.key, value, backendOpts); if (!writeResult.ok) { console.error(`${c.red}✗ ${writeResult.detail}${c.reset}`); diff --git a/src/secrets-service.test.ts b/src/secrets-service.test.ts index c3b9bf7e..63cbcab9 100644 --- a/src/secrets-service.test.ts +++ b/src/secrets-service.test.ts @@ -123,7 +123,13 @@ describe("secrets-service", () => { initializeVault(retrieveTeamId); const secretValue = "sk-prod-1234567890"; - const { secret } = storeSecret(retrieveTeamId, "api_key_prod", secretValue, "api_key", userId); + const { secret } = storeSecret( + retrieveTeamId, + "api_key_prod", + secretValue, + "api_key", + userId, + ); const { value, error } = retrieveSecret(retrieveTeamId, secret.id, userId); @@ -195,7 +201,13 @@ describe("secrets-service", () => { it("rotates secret to new encryption key", () => { initializeVault(rotateTeamId); - const { secret: original } = storeSecret(rotateTeamId, "rotate_me", "secret123", "api_key", userId); + const { secret: original } = storeSecret( + rotateTeamId, + "rotate_me", + "secret123", + "api_key", + userId, + ); const originalKeyId = original.encryption_key_id; const { secret: rotated, error } = rotateSecret(rotateTeamId, original.id, adminId, "manual"); @@ -248,13 +260,7 @@ describe("secrets-service", () => { initializeVault(teamId); const { secret } = storeSecret(teamId, "team_secret", "value", "api_key", userId); - const { share, error } = shareSecret( - teamId, - secret.id, - userId, - undefined, - "team-devops-123", - ); + const { share, error } = shareSecret(teamId, secret.id, userId, undefined, "team-devops-123"); assert.ok(!error); assert.equal(share.shared_with_team_id, "team-devops-123"); diff --git a/src/secrets-sync.ts b/src/secrets-sync.ts index 22804558..cf2aac69 100644 --- a/src/secrets-sync.ts +++ b/src/secrets-sync.ts @@ -4,7 +4,6 @@ import type { SecretsConfig } from "./config.js"; import { generateSecrets } from "./secrets.js"; import { exec } from "./utils/exec.js"; - export interface SyncResult { target: string; synced: string[]; @@ -28,7 +27,7 @@ export interface SecretsSyncOptions { */ export async function syncSecrets( secrets: SecretsConfig, - options: SecretsSyncOptions + options: SecretsSyncOptions, ): Promise<SyncResult> { const { target, dryRun = false, projectPath = process.cwd() } = options; @@ -72,7 +71,9 @@ export async function syncSecrets( } case "stdout": { - const lines = Object.entries(resolved).map(([k, v]) => `export ${k}='${v.replace(/'/g, "'\\''")}'`); + const lines = Object.entries(resolved).map( + ([k, v]) => `export ${k}='${v.replace(/'/g, "'\\''")}'`, + ); if (!dryRun) { process.stdout.write(lines.join("\n") + "\n"); synced.push(...Object.keys(resolved)); @@ -108,7 +109,7 @@ async function syncToGitHub( dryRun: boolean, synced: string[], skipped: string[], - failed: string[] + failed: string[], ): Promise<SyncResult> { const token = process.env.GITHUB_TOKEN; if (!token) { @@ -118,8 +119,7 @@ async function syncToGitHub( skipped: [], failed: ["GITHUB_TOKEN not set"], dryRun, - message: - "Set GITHUB_TOKEN with repo scope to sync secrets to GitHub Actions", + message: "Set GITHUB_TOKEN with repo scope to sync secrets to GitHub Actions", }; } @@ -149,7 +149,7 @@ async function syncToGitHub( // Fetch repo public key for encryption const keyResp = await fetch( `https://api.github.com/repos/${owner}/${repo}/actions/secrets/public-key`, - { headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" } } + { headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" } }, ); if (!keyResp.ok) { @@ -193,10 +193,7 @@ async function syncToGitHub( for (const [name, value] of Object.entries(secrets)) { try { - const encrypted = sodium.crypto_box_seal( - new TextEncoder().encode(value), - repoKey - ); + const encrypted = sodium.crypto_box_seal(new TextEncoder().encode(value), repoKey); const encryptedB64 = sodium.to_base64(encrypted, sodium.base64_variants.ORIGINAL); const putResp = await fetch( @@ -209,7 +206,7 @@ async function syncToGitHub( "Content-Type": "application/json", }, body: JSON.stringify({ encrypted_value: encryptedB64, key_id }), - } + }, ); if (putResp.ok || putResp.status === 201 || putResp.status === 204) { @@ -239,7 +236,7 @@ async function syncToGitHubViaCli( synced: string[], skipped: string[], failed: string[], - dryRun: boolean + dryRun: boolean, ): Promise<SyncResult> { // Fall back to `gh secret set` CLI if libsodium is unavailable try { @@ -257,11 +254,9 @@ async function syncToGitHubViaCli( for (const [name, value] of Object.entries(secrets)) { try { - await exec( - "gh", - ["secret", "set", name, "--repo", `${owner}/${repo}`, "--body", value], - { timeout: 15_000 } - ); + await exec("gh", ["secret", "set", name, "--repo", `${owner}/${repo}`, "--body", value], { + timeout: 15_000, + }); synced.push(name); } catch (err) { failed.push(`${name}: ${(err as Error).message}`); diff --git a/src/secrets-validate.test.ts b/src/secrets-validate.test.ts index cc4867b6..c244b763 100644 --- a/src/secrets-validate.test.ts +++ b/src/secrets-validate.test.ts @@ -46,11 +46,7 @@ describe("validateSecrets", () => { const cfg = configFor({ MISSING_KEY: { source: "infisical", name: "MISSING_KEY" }, }); - const results = await validateSecrets( - cfg, - { auto: true, cwd: dir }, - async () => false, - ); + const results = await validateSecrets(cfg, { auto: true, cwd: dir }, async () => false); // Will attempt to write to infisical — that fails in unit tests because // the CLI isn't installed/auth'd. Status will be "unfixable" with the // backend-error detail, NOT "no value in template" — that path is what @@ -76,11 +72,7 @@ describe("validateSecrets", () => { const cfg = configFor({ MISSING_KEY: { source: "infisical", name: "MISSING_KEY" }, }); - const results = await validateSecrets( - cfg, - { auto: true, cwd: dir }, - async () => false, - ); + const results = await validateSecrets(cfg, { auto: true, cwd: dir }, async () => false); assert.equal(results[0]!.status, "unfixable"); assert.match(results[0]!.detail, /no value in/); } finally { diff --git a/src/secrets-validate.ts b/src/secrets-validate.ts index 75c70fe1..bd3681dd 100644 --- a/src/secrets-validate.ts +++ b/src/secrets-validate.ts @@ -65,7 +65,11 @@ async function loadEnvTemplate(cwd: string, templatePath: string): Promise<Map<s export async function validateSecrets( config: kitConfig, opts: ValidateOptions = {}, - checkAvailability: (key: string, source: SecretKeyConfig["source"], cfg: SecretKeyConfig) => Promise<boolean> = async (key, source, _cfg) => { + checkAvailability: ( + key: string, + source: SecretKeyConfig["source"], + cfg: SecretKeyConfig, + ) => Promise<boolean> = async (key, source, _cfg) => { if (source === "env") return Boolean(process.env[key]); // For all other sources we can't easily check without invoking the // backend CLI here — callers in CLI surface should pass the real @@ -146,7 +150,14 @@ export function summarizeValidation(results: ValidateResult[]): { unfixable: number; ok: boolean; } { - const counts = { total: results.length, present: 0, missing: 0, fixed: 0, unfixable: 0, ok: true }; + const counts = { + total: results.length, + present: 0, + missing: 0, + fixed: 0, + unfixable: 0, + ok: true, + }; for (const r of results) { counts[r.status]++; } diff --git a/src/secrets-vault-migrate.ts b/src/secrets-vault-migrate.ts index 54cfc72c..e16b036a 100644 --- a/src/secrets-vault-migrate.ts +++ b/src/secrets-vault-migrate.ts @@ -34,7 +34,6 @@ import { redactSecrets } from "./utils/redactSecrets.js"; import { appendAuditEventDirect } from "./audit.js"; import { exec } from "./utils/exec.js"; - type BackendSource = SecretKeyConfig["source"]; export interface VaultMigrateOptions { @@ -115,21 +114,17 @@ export async function readSecretFromBackend( } case "doppler": { if (!config.name) return { ok: false, detail: "no Doppler name" }; - const { stdout } = await exec( - "doppler", - ["secrets", "get", config.name, "--plain"], - { timeout: 15_000 }, - ); + const { stdout } = await exec("doppler", ["secrets", "get", config.name, "--plain"], { + timeout: 15_000, + }); return { ok: true, value: stdout.trim(), detail: "read from Doppler" }; } case "vault": { const path = config.vault_path || "secret/data/kit"; const field = config.name || "value"; - const { stdout } = await exec( - "vault", - ["kv", "get", "-field", field, path], - { timeout: 15_000 }, - ); + const { stdout } = await exec("vault", ["kv", "get", "-field", field, path], { + timeout: 15_000, + }); return { ok: true, value: stdout.trim(), detail: `read from Vault ${path}` }; } case "aws-sm": { @@ -150,7 +145,19 @@ export async function readSecretFromBackend( if (!vault) return { ok: false, detail: "no Azure vault" }; const { stdout } = await exec( "az", - ["keyvault", "secret", "show", "--vault-name", vault, "--name", config.name || "", "--query", "value", "-o", "tsv"], + [ + "keyvault", + "secret", + "show", + "--vault-name", + vault, + "--name", + config.name || "", + "--query", + "value", + "-o", + "tsv", + ], { timeout: 15_000 }, ); return { ok: true, value: stdout.trim(), detail: "read from Azure Key Vault" }; @@ -235,13 +242,16 @@ export async function vaultMigrate( ); if (!read.ok || !read.value) { items.push({ name, ok: false, detail: `read: ${read.detail}` }); - await appendAuditEventDirect({ - operation: "vault-migrate", - environment: process.env.KIT_ENV ?? "unknown", - success: false, - error: read.detail, - metadata: { key: name, from: opts.from, to: opts.to, stage: "read" }, - }, { cwd }); + await appendAuditEventDirect( + { + operation: "vault-migrate", + environment: process.env.KIT_ENV ?? "unknown", + success: false, + error: read.detail, + metadata: { key: name, from: opts.from, to: opts.to, stage: "read" }, + }, + { cwd }, + ); continue; } @@ -266,23 +276,23 @@ export async function vaultMigrate( }); if (!write.ok) { items.push({ name, ok: false, detail: `write: ${write.detail}` }); - await appendAuditEventDirect({ - operation: "vault-migrate", - environment: process.env.KIT_ENV ?? "unknown", - success: false, - error: write.detail, - metadata: { key: name, from: opts.from, to: opts.to, stage: "write" }, - }, { cwd }); + await appendAuditEventDirect( + { + operation: "vault-migrate", + environment: process.env.KIT_ENV ?? "unknown", + success: false, + error: write.detail, + metadata: { key: name, from: opts.from, to: opts.to, stage: "write" }, + }, + { cwd }, + ); continue; } // Determine the new ref the target backend uses. 1password gives us // `op://...`; others store under name = "<KEY>" or vault-path. const newRef = - write.ref ?? - (opts.to === "vault" - ? keyConfig.vault_path || `secret/data/kit#${name}` - : name); + write.ref ?? (opts.to === "vault" ? keyConfig.vault_path || `secret/data/kit#${name}` : name); const rewrite = await rewriteConfigRef(cwd, name, opts.to, newRef); if (!rewrite.ok) { items.push({ @@ -291,23 +301,29 @@ export async function vaultMigrate( detail: `write OK but config rewrite failed: ${rewrite.detail}`, newRef, }); - await appendAuditEventDirect({ - operation: "vault-migrate", - environment: process.env.KIT_ENV ?? "unknown", - success: false, - error: rewrite.detail, - metadata: { key: name, from: opts.from, to: opts.to, stage: "rewrite", newRef }, - }, { cwd }); + await appendAuditEventDirect( + { + operation: "vault-migrate", + environment: process.env.KIT_ENV ?? "unknown", + success: false, + error: rewrite.detail, + metadata: { key: name, from: opts.from, to: opts.to, stage: "rewrite", newRef }, + }, + { cwd }, + ); continue; } items.push({ name, ok: true, detail: `migrated to ${opts.to}`, newRef }); - await appendAuditEventDirect({ - operation: "vault-migrate", - environment: process.env.KIT_ENV ?? "unknown", - success: true, - metadata: { key: name, from: opts.from, to: opts.to, newRef }, - }, { cwd }); + await appendAuditEventDirect( + { + operation: "vault-migrate", + environment: process.env.KIT_ENV ?? "unknown", + success: true, + metadata: { key: name, from: opts.from, to: opts.to, newRef }, + }, + { cwd }, + ); } return { diff --git a/src/secrets.test.ts b/src/secrets.test.ts index 1c77de60..6d6ec663 100644 --- a/src/secrets.test.ts +++ b/src/secrets.test.ts @@ -9,7 +9,11 @@ import type { SecretsConfig } from "./config.js"; const tmpOut = join(tmpdir(), `.kit-test-${process.pid}.env`); afterEach(async () => { - try { await unlink(tmpOut); } catch { /* ignore */ } + try { + await unlink(tmpOut); + } catch { + /* ignore */ + } }); describe("generateSecrets", () => { @@ -137,7 +141,11 @@ describe("generateSecrets", () => { }); it("writes a scaffold when nothing resolved and no file exists yet", async () => { - try { await unlink(tmpOut); } catch { /* ignore */ } + try { + await unlink(tmpOut); + } catch { + /* ignore */ + } delete process.env._KIT_NONE2; const config: SecretsConfig = { keys: { _KIT_NONE2: { source: "env" } } }; diff --git a/src/secrets.ts b/src/secrets.ts index 2aa7f46b..db31cc8d 100644 --- a/src/secrets.ts +++ b/src/secrets.ts @@ -2,7 +2,6 @@ import { readFile, writeFile, access } from "node:fs/promises"; import type { SecretsConfig } from "./config.js"; import { resolveViaBackend, resetInfisicalCache } from "./secret-backends.js"; - export interface SecretResolveResult { name: string; resolved: boolean; @@ -15,10 +14,7 @@ export interface SecretResolveResult { } /** Interpolate {{KEY}} placeholders in a template string with resolved values. */ -function interpolateTemplate( - template: string, - resolved: Map<string, string>, -): string { +function interpolateTemplate(template: string, resolved: Map<string, string>): string { return template.replace(/\{\{(\w+)\}\}/g, (_match, key: string) => { return resolved.get(key) ?? `{{${key}}}`; }); diff --git a/src/security-policy.test.ts b/src/security-policy.test.ts index 64bd5007..c79655f5 100644 --- a/src/security-policy.test.ts +++ b/src/security-policy.test.ts @@ -75,10 +75,7 @@ describe("checkAllowlist", () => { // remove rogue from allowlist to simulate the unlisted case const list = await readAllowlist(dir); list!.packages = list!.packages.filter((p) => p.name !== "rogue"); - writeFileSync( - join(dir, ".kit-allowlist.json"), - JSON.stringify(list, null, 2), - ); + writeFileSync(join(dir, ".kit-allowlist.json"), JSON.stringify(list, null, 2)); const { violations } = await checkAllowlist(dir); assert.equal(violations.length, 0); }); diff --git a/src/security-policy.ts b/src/security-policy.ts index 4ece3cff..1c7407c6 100644 --- a/src/security-policy.ts +++ b/src/security-policy.ts @@ -70,10 +70,7 @@ export async function readAllowlist(cwd: string = process.cwd()): Promise<Allowl } } -export async function writeAllowlist( - list: Allowlist, - cwd: string = process.cwd(), -): Promise<void> { +export async function writeAllowlist(list: Allowlist, cwd: string = process.cwd()): Promise<void> { const path = resolve(cwd, ALLOWLIST_FILE); await writeFile(path, JSON.stringify(list, null, 2) + "\n", "utf-8"); } @@ -122,11 +119,7 @@ export interface PolicyViolation { export interface SecretPolicyViolation { key: string; - reason: - | "no-policy-entry" - | "no-spend-cap" - | "no-scope" - | "ttl-too-long"; + reason: "no-policy-entry" | "no-spend-cap" | "no-scope" | "ttl-too-long"; detail: string; } @@ -160,10 +153,7 @@ export async function checkAllowlist( violations.push({ name, range, reason: "not-on-allowlist", kind }); continue; } - if ( - !list.policy.allow_wildcards && - (entry.range === "*" || range === "*") - ) { + if (!list.policy.allow_wildcards && (entry.range === "*" || range === "*")) { violations.push({ name, range, reason: "wildcard-blocked", kind }); } } @@ -188,13 +178,7 @@ export async function checkAllowlist( export function checkSecretPolicy( list: Allowlist, configKeys: string[], - paidServices: Set<string> = new Set([ - "STRIPE", - "OPENAI", - "ANTHROPIC", - "RESEND", - "VERCEL", - ]), + paidServices: Set<string> = new Set(["STRIPE", "OPENAI", "ANTHROPIC", "RESEND", "VERCEL"]), ): SecretPolicyViolation[] { const violations: SecretPolicyViolation[] = []; const policyBlock = list.secrets ?? {}; @@ -266,8 +250,7 @@ export async function addToAllowlist( } const pkg = await readPackageJson(cwd); if (!pkg) return { added: false, entry: null }; - const range = - pkg.dependencies?.[pkgName] ?? pkg.devDependencies?.[pkgName] ?? "*"; + const range = pkg.dependencies?.[pkgName] ?? pkg.devDependencies?.[pkgName] ?? "*"; const kind = pkg.dependencies?.[pkgName] ? "runtime" : "dev"; const entry: AllowlistEntry = { name: pkgName, range, reason: kind }; list.packages.push(entry); diff --git a/src/security-prescan.test.ts b/src/security-prescan.test.ts index 6b8e174a..c04a43d8 100644 --- a/src/security-prescan.test.ts +++ b/src/security-prescan.test.ts @@ -5,7 +5,16 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { runPrescan, renderSummary, diffReports, loadReport, renderDiff, BUILTIN_CHECKS, type PrescanReport, type PrescanCheck } from "./security-prescan.js"; +import { + runPrescan, + renderSummary, + diffReports, + loadReport, + renderDiff, + BUILTIN_CHECKS, + type PrescanReport, + type PrescanCheck, +} from "./security-prescan.js"; const exec = promisify(execFile); @@ -22,10 +31,19 @@ describe("runPrescan", () => { try { const repo = join(root, "clean"); await makeRepoDir(repo); - writeFileSync(join(repo, ".gitignore"), [ - ".env", ".env.local", ".env.*.local", ".env.*.backup", - "*.prod-backup", "*.pem", "id_rsa", ".kit/elevation.json", - ].join("\n")); + writeFileSync( + join(repo, ".gitignore"), + [ + ".env", + ".env.local", + ".env.*.local", + ".env.*.backup", + "*.prod-backup", + "*.pem", + "id_rsa", + ".kit/elevation.json", + ].join("\n"), + ); writeFileSync(join(repo, "README.md"), "ok"); await exec("git", ["-C", repo, "add", "."]); await exec("git", ["-C", repo, "commit", "-q", "-m", "init"]); @@ -33,10 +51,11 @@ describe("runPrescan", () => { const report = await runPrescan({ root, persist: false, maxDepth: 3 }); assert.equal(report.repoCount, 1); // gitignore-holes + tracked-secret-files should be silent. - const offenders = report.findings.filter((f) => - f.category === "gitignore-holes" || - f.category === "tracked-secret-files" || - f.category === "gitignore-missing", + const offenders = report.findings.filter( + (f) => + f.category === "gitignore-holes" || + f.category === "tracked-secret-files" || + f.category === "gitignore-missing", ); assert.equal(offenders.length, 0, JSON.stringify(offenders)); } finally { @@ -145,8 +164,20 @@ describe("runPrescan", () => { root: "/tmp/x", repoCount: 2, findings: [ - { timestamp: "x", repo: "/tmp/x/a", category: "tracked-secret-files", severity: "critical", detail: ".env.local tracked" }, - { timestamp: "x", repo: "/tmp/x/b", category: "gitignore-holes", severity: "medium", detail: "missing patterns" }, + { + timestamp: "x", + repo: "/tmp/x/a", + category: "tracked-secret-files", + severity: "critical", + detail: ".env.local tracked", + }, + { + timestamp: "x", + repo: "/tmp/x/b", + category: "gitignore-holes", + severity: "medium", + detail: "missing patterns", + }, ], }); assert.match(md, /# kit prescan report/); @@ -157,14 +188,20 @@ describe("runPrescan", () => { it("renderSummary handles zero-finding case", () => { const md = renderSummary({ - startedAt: "x", finishedAt: "y", root: "/r", repoCount: 1, findings: [], + startedAt: "x", + finishedAt: "y", + root: "/r", + repoCount: 1, + findings: [], }); assert.match(md, /All clean/); }); }); describe("diffReports", () => { - function mkReport(findings: Array<Partial<{ repo: string; category: string; severity: string; detail: string }>>): PrescanReport { + function mkReport( + findings: Array<Partial<{ repo: string; category: string; severity: string; detail: string }>>, + ): PrescanReport { return { startedAt: "2026-06-09T00:00:00Z", finishedAt: "2026-06-09T00:01:00Z", @@ -279,13 +316,17 @@ describe("plugin-pattern checks", () => { await exec("git", ["-C", repo, "commit", "-q", "-m", "init"]); const report = await runPrescan({ - root, persist: false, maxDepth: 3, + root, + persist: false, + maxDepth: 3, onlyChecks: ["tracked-secret-files"], // skip gitignore-holes etc }); // Should only see tracked-secret-files findings. assert.ok(report.findings.length >= 1); - assert.ok(report.findings.every((f) => f.category === "tracked-secret-files"), - `expected only tracked-secret-files, got: ${JSON.stringify(report.findings.map((f) => f.category))}`); + assert.ok( + report.findings.every((f) => f.category === "tracked-secret-files"), + `expected only tracked-secret-files, got: ${JSON.stringify(report.findings.map((f) => f.category))}`, + ); } finally { rmSync(root, { recursive: true, force: true }); } @@ -302,11 +343,15 @@ describe("plugin-pattern checks", () => { await exec("git", ["-C", repo, "commit", "-q", "-m", "init"]); const report = await runPrescan({ - root, persist: false, maxDepth: 3, + root, + persist: false, + maxDepth: 3, skipChecks: ["gitignore-holes"], }); - assert.ok(report.findings.every((f) => f.category !== "gitignore-holes"), - `expected no gitignore-holes, got: ${JSON.stringify(report.findings.map((f) => f.category))}`); + assert.ok( + report.findings.every((f) => f.category !== "gitignore-holes"), + `expected no gitignore-holes, got: ${JSON.stringify(report.findings.map((f) => f.category))}`, + ); } finally { rmSync(root, { recursive: true, force: true }); } @@ -317,10 +362,19 @@ describe("plugin-pattern checks", () => { try { const repo = join(root, "clean"); await makeRepoDir(repo); - writeFileSync(join(repo, ".gitignore"), [ - ".env", ".env.local", ".env.*.local", ".env.*.backup", - "*.prod-backup", "*.pem", "id_rsa", ".kit/elevation.json", - ].join("\n")); + writeFileSync( + join(repo, ".gitignore"), + [ + ".env", + ".env.local", + ".env.*.local", + ".env.*.backup", + "*.prod-backup", + "*.pem", + "id_rsa", + ".kit/elevation.json", + ].join("\n"), + ); writeFileSync(join(repo, "README.md"), "x"); await exec("git", ["-C", repo, "add", "."]); await exec("git", ["-C", repo, "commit", "-q", "-m", "init"]); @@ -329,16 +383,20 @@ describe("plugin-pattern checks", () => { name: "test-marker", tier: "default", scope: "per-repo", - run: async (repoPath) => [{ - timestamp: "t", - repo: repoPath, - category: "custom-test-marker", - severity: "low", - detail: "custom check ran", - }], + run: async (repoPath) => [ + { + timestamp: "t", + repo: repoPath, + category: "custom-test-marker", + severity: "low", + detail: "custom check ran", + }, + ], }; const report = await runPrescan({ - root, persist: false, maxDepth: 3, + root, + persist: false, + maxDepth: 3, extraChecks: [custom], }); const marker = report.findings.find((f) => f.category === "custom-test-marker"); @@ -354,8 +412,23 @@ describe("plugin-pattern checks", () => { const repo = join(root, "with-deps"); await makeRepoDir(repo); writeFileSync(join(repo, "package.json"), JSON.stringify({ name: "x", version: "1.0.0" })); - writeFileSync(join(repo, "package-lock.json"), JSON.stringify({ name: "x", lockfileVersion: 3 })); - writeFileSync(join(repo, ".gitignore"), [".env", ".env.local", "*.pem", "id_rsa", ".kit/elevation.json", ".env.*.backup", "*.prod-backup", ".env.*.local"].join("\n")); + writeFileSync( + join(repo, "package-lock.json"), + JSON.stringify({ name: "x", lockfileVersion: 3 }), + ); + writeFileSync( + join(repo, ".gitignore"), + [ + ".env", + ".env.local", + "*.pem", + "id_rsa", + ".kit/elevation.json", + ".env.*.backup", + "*.prod-backup", + ".env.*.local", + ].join("\n"), + ); await exec("git", ["-C", repo, "add", "."]); await exec("git", ["-C", repo, "commit", "-q", "-m", "init"]); diff --git a/src/security-prescan.ts b/src/security-prescan.ts index 3bc69ebe..6302106d 100644 --- a/src/security-prescan.ts +++ b/src/security-prescan.ts @@ -32,7 +32,6 @@ import { join } from "node:path"; import { homedir } from "node:os"; import { exec } from "./utils/exec.js"; - const PRESCAN_DIR = join(homedir(), ".kit", "prescans"); export type Severity = "info" | "low" | "medium" | "high" | "critical"; @@ -126,8 +125,18 @@ async function pathExists(p: string): Promise<boolean> { async function findRepos(root: string, maxDepth: number): Promise<string[]> { const repos: string[] = []; const SKIP_DIRS = new Set([ - "node_modules", ".git", "dist", "build", ".next", ".turbo", - "out", "coverage", ".cache", ".venv", "venv", "__pycache__", + "node_modules", + ".git", + "dist", + "build", + ".next", + ".turbo", + "out", + "coverage", + ".cache", + ".venv", + "venv", + "__pycache__", ]); async function walk(dir: string, depth: number): Promise<void> { if (depth > maxDepth) return; @@ -138,7 +147,10 @@ async function findRepos(root: string, maxDepth: number): Promise<string[]> { } let entries: Array<{ name: string; isDirectory(): boolean }>; try { - entries = (await readdir(dir, { withFileTypes: true, encoding: "utf-8" })) as unknown as Array<{ name: string; isDirectory(): boolean }>; + entries = (await readdir(dir, { + withFileTypes: true, + encoding: "utf-8", + })) as unknown as Array<{ name: string; isDirectory(): boolean }>; } catch { return; } @@ -206,17 +218,26 @@ async function checkGitignoreHoles(repo: string): Promise<PrescanFinding[]> { text = await readFile(path, "utf-8"); } catch { return [ - finding(repo, "gitignore-missing", "high", "no .gitignore in repo root", - "add .gitignore with at least: .env*, *.pem, id_rsa"), + finding( + repo, + "gitignore-missing", + "high", + "no .gitignore in repo root", + "add .gitignore with at least: .env*, *.pem, id_rsa", + ), ]; } const lines = text.split("\n").map((l) => l.trim()); const missing = REQUIRED_GITIGNORE.filter((p) => !lines.includes(p)); if (missing.length === 0) return []; return [ - finding(repo, "gitignore-holes", "medium", + finding( + repo, + "gitignore-holes", + "medium", `missing ${missing.length} secret-leak patterns: ${missing.join(", ")}`, - `append to .gitignore: ${missing.join(" ")}`), + `append to .gitignore: ${missing.join(" ")}`, + ), ]; } @@ -225,22 +246,30 @@ async function checkGitignoreHoles(repo: string): Promise<PrescanFinding[]> { async function checkTrackedSecretFiles(repo: string): Promise<PrescanFinding[]> { try { const { stdout } = await exec("git", ["-C", repo, "ls-files"], { - timeout: 15000, maxBuffer: 20_000_000, + timeout: 15000, + maxBuffer: 20_000_000, }); const tracked = stdout.split("\n"); - const matches = tracked.filter((f) => - /(?:^|\/)\.env(?:\.|$)|\.pem$|\.key$|id_rsa$|\.prod-backup$|\.bak$/.test(f), - ).filter((f) => - // Allowlist anything that looks like a template / example / sample / patch / dist, - // and node-modules / vendor / fixtures / third-party demo folders. - !/\.(template|example|sample|dist|tmpl|patch|stub|mock|spec)$/.test(f) && - !/(?:^|\/)(node_modules|vendor|__tests__|tests?|fixtures?|demos?|private-demos?|examples?|samples?)\//.test(f), - ); + const matches = tracked + .filter((f) => /(?:^|\/)\.env(?:\.|$)|\.pem$|\.key$|id_rsa$|\.prod-backup$|\.bak$/.test(f)) + .filter( + (f) => + // Allowlist anything that looks like a template / example / sample / patch / dist, + // and node-modules / vendor / fixtures / third-party demo folders. + !/\.(template|example|sample|dist|tmpl|patch|stub|mock|spec)$/.test(f) && + !/(?:^|\/)(node_modules|vendor|__tests__|tests?|fixtures?|demos?|private-demos?|examples?|samples?)\//.test( + f, + ), + ); if (matches.length === 0) return []; return [ - finding(repo, "tracked-secret-files", "critical", + finding( + repo, + "tracked-secret-files", + "critical", `${matches.length} tracked file(s) match secret-file pattern: ${matches.join(", ")}`, - `git rm --cached <file> ; add to .gitignore ; rotate any leaked credential`), + `git rm --cached <file> ; add to .gitignore ; rotate any leaked credential`, + ), ]; } catch { return []; @@ -253,21 +282,37 @@ async function checkSecretLeakage(repo: string): Promise<PrescanFinding[]> { try { await exec("gitleaks", ["--version"], { timeout: 3000 }); } catch { - return [finding(repo, "secret-leak-skipped", "info", "gitleaks not installed — skipping", "install: https://github.com/gitleaks/gitleaks")]; + return [ + finding( + repo, + "secret-leak-skipped", + "info", + "gitleaks not installed — skipping", + "install: https://github.com/gitleaks/gitleaks", + ), + ]; } try { - await exec("gitleaks", ["detect", "--source", repo, "--redact", "--no-banner", "--exit-code", "1"], { - timeout: 60_000, - }); + await exec( + "gitleaks", + ["detect", "--source", repo, "--redact", "--no-banner", "--exit-code", "1"], + { + timeout: 60_000, + }, + ); return []; } catch (err) { const e = err as { stdout?: string; stderr?: string }; const out = (e.stdout ?? "") + (e.stderr ?? ""); const leakMatch = out.match(/\d+ leaks? found/i); return [ - finding(repo, "secret-leak", "critical", + finding( + repo, + "secret-leak", + "critical", leakMatch ? leakMatch[0] : "gitleaks reported leaks (see report)", - "review leaks; rotate; allowlist via .gitleaks.toml only AFTER revoking"), + "review leaks; rotate; allowlist via .gitleaks.toml only AFTER revoking", + ), ]; } } @@ -279,34 +324,60 @@ async function checkGitHubMeta(repo: string): Promise<PrescanFinding[]> { if (!remote) return []; const findings: PrescanFinding[] = []; try { - const { stdout } = await exec("gh", ["api", `repos/${remote.owner}/${remote.name}`, "--jq", ".private,.default_branch"], { - timeout: 10_000, - }); + const { stdout } = await exec( + "gh", + ["api", `repos/${remote.owner}/${remote.name}`, "--jq", ".private,.default_branch"], + { + timeout: 10_000, + }, + ); const [isPrivateStr, defaultBranch] = stdout.trim().split("\n"); const isPrivate = isPrivateStr === "true"; const branch = defaultBranch || "main"; if (!isPrivate) { - findings.push(finding(repo, "repo-public", "high", - `repository is PUBLIC (${remote.owner}/${remote.name}) — any leaked credential in history is world-visible`, - "consider whether truly intended; for private code, switch via Settings → Visibility")); + findings.push( + finding( + repo, + "repo-public", + "high", + `repository is PUBLIC (${remote.owner}/${remote.name}) — any leaked credential in history is world-visible`, + "consider whether truly intended; for private code, switch via Settings → Visibility", + ), + ); } // Branch protection try { - await exec("gh", ["api", `repos/${remote.owner}/${remote.name}/branches/${branch}/protection`], { - timeout: 10_000, - }); + await exec( + "gh", + ["api", `repos/${remote.owner}/${remote.name}/branches/${branch}/protection`], + { + timeout: 10_000, + }, + ); } catch (err) { const e = err as { stderr?: string }; if ((e.stderr ?? "").includes("404")) { - findings.push(finding(repo, "branch-unprotected", "medium", - `branch '${branch}' has no protection rules`, - `Settings → Branches → Add protection rule for ${branch}`)); + findings.push( + finding( + repo, + "branch-unprotected", + "medium", + `branch '${branch}' has no protection rules`, + `Settings → Branches → Add protection rule for ${branch}`, + ), + ); } } } catch { - findings.push(finding(repo, "gh-skipped", "info", - `gh CLI not authed or repo not on github.com — skipping repo meta`, - "run: gh auth login")); + findings.push( + finding( + repo, + "gh-skipped", + "info", + `gh CLI not authed or repo not on github.com — skipping repo meta`, + "run: gh auth login", + ), + ); } return findings; } @@ -319,7 +390,8 @@ async function checkGitHubMeta(repo: string): Promise<PrescanFinding[]> { * without forcing them to re-run `npm audit` interactively. */ function topAuditPackages(data: unknown): string[] { - const vulns = (data as { vulnerabilities?: Record<string, { severity?: string }> })?.vulnerabilities; + const vulns = (data as { vulnerabilities?: Record<string, { severity?: string }> }) + ?.vulnerabilities; if (!vulns) return []; const top: string[] = []; for (const [name, info] of Object.entries(vulns)) { @@ -333,10 +405,18 @@ function topAuditPackages(data: unknown): string[] { async function checkNpmAudit(repo: string): Promise<PrescanFinding[]> { if (!(await pathExists(join(repo, "package.json")))) return []; if (!(await pathExists(join(repo, "package-lock.json")))) { - return [finding(repo, "npm-audit-skipped", "info", "no package-lock.json — skipping npm audit", "run: npm install to generate lockfile")]; + return [ + finding( + repo, + "npm-audit-skipped", + "info", + "no package-lock.json — skipping npm audit", + "run: npm install to generate lockfile", + ), + ]; } - const NPM_AUDIT_TIMEOUT_MS = 120_000; // 2 min — large lockfiles can be slow - const NPM_AUDIT_BUFFER = 64 * 1024 * 1024; // 64 MB — monorepos emit large json + const NPM_AUDIT_TIMEOUT_MS = 120_000; // 2 min — large lockfiles can be slow + const NPM_AUDIT_BUFFER = 64 * 1024 * 1024; // 64 MB — monorepos emit large json const parseAndFormat = (stdout: string): PrescanFinding[] => { const data = JSON.parse(stdout); const high = data?.metadata?.vulnerabilities?.high ?? 0; @@ -344,22 +424,36 @@ async function checkNpmAudit(repo: string): Promise<PrescanFinding[]> { if (high + critical === 0) return []; const top = topAuditPackages(data); const where = top.length ? ` — top: ${top.join(", ")}` : ""; - return [finding(repo, "npm-audit", critical > 0 ? "critical" : "high", - `${critical} critical + ${high} high vulnerabilities${where}`, - "npm audit fix; review individual reports")]; + return [ + finding( + repo, + "npm-audit", + critical > 0 ? "critical" : "high", + `${critical} critical + ${high} high vulnerabilities${where}`, + "npm audit fix; review individual reports", + ), + ]; }; try { const { stdout } = await exec("npm", ["audit", "--audit-level=high", "--json"], { - cwd: repo, timeout: NPM_AUDIT_TIMEOUT_MS, maxBuffer: NPM_AUDIT_BUFFER, + cwd: repo, + timeout: NPM_AUDIT_TIMEOUT_MS, + maxBuffer: NPM_AUDIT_BUFFER, }); return parseAndFormat(stdout); } catch (err) { // npm audit exits non-zero when findings exist const e = err as { stdout?: string }; if (e.stdout) { - try { return parseAndFormat(e.stdout); } catch { /* fallthrough */ } + try { + return parseAndFormat(e.stdout); + } catch { + /* fallthrough */ + } } - return [finding(repo, "npm-audit-error", "info", "npm audit failed to parse", "manual investigation")]; + return [ + finding(repo, "npm-audit-error", "info", "npm audit failed to parse", "manual investigation"), + ]; } } @@ -371,9 +465,15 @@ async function checkWorkflowDrift(repo: string): Promise<PrescanFinding[]> { for (const f of expectedFiles) { if (await pathExists(join(repo, ".github", "workflows", f))) return []; } - return [finding(repo, "workflow-drift", "low", - "no kit-security workflow in .github/workflows/", - "copy templates/github/kit-security.yml from kit")]; + return [ + finding( + repo, + "workflow-drift", + "low", + "no kit-security workflow in .github/workflows/", + "copy templates/github/kit-security.yml from kit", + ), + ]; } // ── Deep check: bumblebee supply-chain exposure ──────────────────────────── @@ -393,15 +493,27 @@ async function checkBumblebeeCatalogStale( await import("./bumblebee.js"); const mtime = await newestCatalogMtime(install.catalogDir); if (mtime === null) { - return [finding(root, "bumblebee-catalog-missing", "medium", - `bumblebee threat_intel catalog directory empty: ${install.catalogDir}`, - `clear ~/.kit/tools/bumblebee and run any deep scan to re-download`)]; + return [ + finding( + root, + "bumblebee-catalog-missing", + "medium", + `bumblebee threat_intel catalog directory empty: ${install.catalogDir}`, + `clear ~/.kit/tools/bumblebee and run any deep scan to re-download`, + ), + ]; } const { stale, ageDays } = isCatalogStale(mtime, Date.now()); if (stale) { - return [finding(root, "bumblebee-catalog-stale", "medium", - `bumblebee threat_intel catalog is ${ageDays} days old (threshold: ${CATALOG_STALE_AFTER_DAYS}d) — new supply-chain compromises may not be detected`, - `clear ~/.kit/tools/bumblebee to force a fresh download next deep scan`)]; + return [ + finding( + root, + "bumblebee-catalog-stale", + "medium", + `bumblebee threat_intel catalog is ${ageDays} days old (threshold: ${CATALOG_STALE_AFTER_DAYS}d) — new supply-chain compromises may not be detected`, + `clear ~/.kit/tools/bumblebee to force a fresh download next deep scan`, + ), + ]; } return []; } catch { @@ -450,9 +562,15 @@ async function checkAuditGap(repo: string): Promise<PrescanFinding[]> { if (!kitToml) return []; const auditFile = join(repo, ".kit-audit.jsonl"); if (!(await pathExists(auditFile))) { - return [finding(repo, "audit-gap", "info", - "kit governance configured but .kit-audit.jsonl missing", - "run any kit sensitive op to bootstrap; verify [governance.audit].enabled = true")]; + return [ + finding( + repo, + "audit-gap", + "info", + "kit governance configured but .kit-audit.jsonl missing", + "run any kit sensitive op to bootstrap; verify [governance.audit].enabled = true", + ), + ]; } return []; } @@ -464,28 +582,46 @@ async function checkAuditGap(repo: string): Promise<PrescanFinding[]> { * pass additional checks via `PrescanOptions.extraChecks`. */ export const BUILTIN_CHECKS: PrescanCheck[] = [ - { name: "gitignore-holes", tier: "default", scope: "per-repo", run: (repo) => checkGitignoreHoles(repo) }, - { name: "tracked-secret-files", tier: "default", scope: "per-repo", run: (repo) => checkTrackedSecretFiles(repo) }, - { name: "secret-leak", tier: "default", scope: "per-repo", run: (repo) => checkSecretLeakage(repo) }, - { name: "github-meta", tier: "default", scope: "per-repo", run: (repo) => checkGitHubMeta(repo) }, - { name: "npm-audit", tier: "deep", scope: "per-repo", run: (repo) => checkNpmAudit(repo) }, - { name: "workflow-drift", tier: "deep", scope: "per-repo", run: (repo) => checkWorkflowDrift(repo) }, - { name: "audit-gap", tier: "deep", scope: "per-repo", run: (repo) => checkAuditGap(repo) }, + { + name: "gitignore-holes", + tier: "default", + scope: "per-repo", + run: (repo) => checkGitignoreHoles(repo), + }, + { + name: "tracked-secret-files", + tier: "default", + scope: "per-repo", + run: (repo) => checkTrackedSecretFiles(repo), + }, + { + name: "secret-leak", + tier: "default", + scope: "per-repo", + run: (repo) => checkSecretLeakage(repo), + }, + { name: "github-meta", tier: "default", scope: "per-repo", run: (repo) => checkGitHubMeta(repo) }, + { name: "npm-audit", tier: "deep", scope: "per-repo", run: (repo) => checkNpmAudit(repo) }, + { + name: "workflow-drift", + tier: "deep", + scope: "per-repo", + run: (repo) => checkWorkflowDrift(repo), + }, + { name: "audit-gap", tier: "deep", scope: "per-repo", run: (repo) => checkAuditGap(repo) }, { name: "bumblebee-catalog-stale", tier: "deep", scope: "global", - run: async (root, ctx) => ctx.bumblebeeInstall - ? await checkBumblebeeCatalogStale(ctx.bumblebeeInstall, root) - : [], + run: async (root, ctx) => + ctx.bumblebeeInstall ? await checkBumblebeeCatalogStale(ctx.bumblebeeInstall, root) : [], }, { name: "bumblebee", tier: "deep", scope: "per-repo", - run: async (repo, ctx) => ctx.bumblebeeInstall - ? await checkBumblebee(repo, ctx.bumblebeeInstall) - : [], + run: async (repo, ctx) => + ctx.bumblebeeInstall ? await checkBumblebee(repo, ctx.bumblebeeInstall) : [], }, ]; @@ -501,9 +637,7 @@ function selectChecks( const inTier = all.filter((c) => deep || c.tier !== "deep"); const onlySet = only && only.length > 0 ? new Set(only) : null; const skipSet = skip && skip.length > 0 ? new Set(skip) : new Set<string>(); - return inTier.filter((c) => - (onlySet === null || onlySet.has(c.name)) && !skipSet.has(c.name) - ); + return inTier.filter((c) => (onlySet === null || onlySet.has(c.name)) && !skipSet.has(c.name)); } // ── Main entry point ─────────────────────────────────────────────────────── @@ -512,9 +646,8 @@ export async function runPrescan(opts: PrescanOptions): Promise<PrescanReport> { const startedAt = new Date().toISOString(); const allRepos = await findRepos(opts.root, opts.maxDepth ?? 4); const excludes = opts.exclude ?? []; - const repos = excludes.length === 0 - ? allRepos - : allRepos.filter((r) => !excludes.some((p) => r.includes(p))); + const repos = + excludes.length === 0 ? allRepos : allRepos.filter((r) => !excludes.some((p) => r.includes(p))); const findings: PrescanFinding[] = []; // Hoist bumblebee install once for the whole run (deep mode only). @@ -544,12 +677,12 @@ export async function runPrescan(opts: PrescanOptions): Promise<PrescanReport> { // Globals first (e.g. bumblebee-catalog-stale): they may influence later // per-repo decisions, and they're typically O(1) rather than O(repos). for (const check of globalChecks) { - findings.push(...await check.run(opts.root, ctx)); + findings.push(...(await check.run(opts.root, ctx))); } for (const repo of repos) { for (const check of perRepoChecks) { - findings.push(...await check.run(repo, ctx)); + findings.push(...(await check.run(repo, ctx))); } } @@ -706,7 +839,9 @@ export function renderDiff(diff: PrescanDiff): string { if (diff.added.length === 0 && diff.removed.length === 0) { lines.push(`## No drift`); lines.push(""); - lines.push(`${diff.unchanged.length} finding(s) carried over unchanged. No regressions, no fixes.`); + lines.push( + `${diff.unchanged.length} finding(s) carried over unchanged. No regressions, no fixes.`, + ); } return lines.join("\n"); diff --git a/src/sentinel.test.ts b/src/sentinel.test.ts index 925c36ab..036c9249 100644 --- a/src/sentinel.test.ts +++ b/src/sentinel.test.ts @@ -23,15 +23,30 @@ describe("artifactForClass", () => { describe("healthToRedFindings", () => { const findings: HealthFinding[] = [ - { sensor: "vercel", source: "team/p", status: "red", title: "prod deploy failed", suggestedClass: "code" }, - { sensor: "resend", source: "resend", status: "red", title: "domain unverified", suggestedClass: "human" }, + { + sensor: "vercel", + source: "team/p", + status: "red", + title: "prod deploy failed", + suggestedClass: "code", + }, + { + sensor: "resend", + source: "resend", + status: "red", + title: "domain unverified", + suggestedClass: "human", + }, { sensor: "sentry", source: "o/p", status: "green", title: "ok" }, { sensor: "gitlab", source: "g/r", status: "red", title: "pipeline failed" }, // no class → human ]; it("keeps only red, maps class (default human), stable id per sensor", () => { const red = healthToRedFindings(findings); assert.equal(red.length, 3); - assert.deepEqual(red.map((r) => r.id), ["health:vercel", "health:resend", "health:gitlab"]); + assert.deepEqual( + red.map((r) => r.id), + ["health:vercel", "health:resend", "health:gitlab"], + ); assert.equal(red.find((r) => r.id === "health:vercel")!.class, "code"); assert.equal(red.find((r) => r.id === "health:gitlab")!.class, "human"); }); @@ -39,7 +54,12 @@ describe("healthToRedFindings", () => { describe("buildProposal", () => { it("code → draft-pr with a branch and the dedup marker in the body", () => { - const p = buildProposal({ id: "health:vercel", class: "code", title: "deploy failed", detail: "ERROR state" }); + const p = buildProposal({ + id: "health:vercel", + class: "code", + title: "deploy failed", + detail: "ERROR state", + }); assert.equal(p.artifact, "draft-pr"); assert.equal(p.branch, "kit/sentinel/health-vercel"); assert.ok(p.body.includes(findingMarker("health:vercel"))); diff --git a/src/sentinel.ts b/src/sentinel.ts index d81621a8..89bcae10 100644 --- a/src/sentinel.ts +++ b/src/sentinel.ts @@ -48,7 +48,11 @@ export function artifactForClass(c: FindingClass): Artifact { } function slug(id: string): string { - return id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50); + return id + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 50); } /** Map a layer-1 health finding to the normalized responder shape (red only). */ @@ -92,13 +96,22 @@ export function buildProposal(f: RedFinding): Proposal { } /** Findings (minus suppressed) → proposals. Pure. */ -export function buildProposals(findings: RedFinding[], suppressed: ReadonlySet<string> = new Set()): Proposal[] { +export function buildProposals( + findings: RedFinding[], + suppressed: ReadonlySet<string> = new Set(), +): Proposal[] { return findings.filter((f) => !suppressed.has(f.id)).map(buildProposal); } /** Mark proposals whose finding already has an open artifact (null openMarkers = not checked). */ -export function applyDedup(proposals: Proposal[], openMarkers: ReadonlySet<string> | null): Proposal[] { - return proposals.map((p) => ({ ...p, alreadyOpen: openMarkers ? openMarkers.has(p.findingId) : null })); +export function applyDedup( + proposals: Proposal[], + openMarkers: ReadonlySet<string> | null, +): Proposal[] { + return proposals.map((p) => ({ + ...p, + alreadyOpen: openMarkers ? openMarkers.has(p.findingId) : null, + })); } /** Parse `.kit/sentinel-suppress.toml` — `suppress = ["id-a", "id-b"]`. */ @@ -120,7 +133,9 @@ export interface SentinelDeps { export async function runSentinel(cwd: string, deps: SentinelDeps): Promise<Proposal[]> { let suppressed = new Set<string>(); try { - suppressed = parseSuppressions(readFileSync(resolve(cwd, ".kit", "sentinel-suppress.toml"), "utf8")); + suppressed = parseSuppressions( + readFileSync(resolve(cwd, ".kit", "sentinel-suppress.toml"), "utf8"), + ); } catch { // no suppress file → nothing suppressed } diff --git a/src/service-auth.test.ts b/src/service-auth.test.ts index 68fe9f8d..29ea0b69 100644 --- a/src/service-auth.test.ts +++ b/src/service-auth.test.ts @@ -20,13 +20,19 @@ describe("service auth resolver", () => { }); it("honors an explicit auth override over inference", () => { - const r = resolveServiceAuth("github", svc({ login: "gh auth login", check: "gh auth status", auth: "vault" })); + const r = resolveServiceAuth( + "github", + svc({ login: "gh auth login", check: "gh auth status", auth: "vault" }), + ); assert.equal(r.strategy, "vault"); // explicit wins despite a login command assert.equal(r.passkey, false); // vault is never a passkey flow }); it("flags passkey for known browser-login services", () => { - const gh = resolveServiceAuth("github", svc({ login: "gh auth login", check: "gh auth status" })); + const gh = resolveServiceAuth( + "github", + svc({ login: "gh auth login", check: "gh auth status" }), + ); assert.equal(gh.strategy, "interactive"); assert.equal(gh.passkey, true); assert.match(gh.instruction, /passkey/); @@ -47,6 +53,9 @@ describe("service auth resolver", () => { vercel: svc({ login: "vercel login", check: "x" }), github: svc({ login: "gh auth login", check: "x" }), }); - assert.deepEqual(plans.map((p) => p.name), ["github", "vercel"]); + assert.deepEqual( + plans.map((p) => p.name), + ["github", "vercel"], + ); }); }); diff --git a/src/service-auth.ts b/src/service-auth.ts index 306bf94c..acc70d6e 100644 --- a/src/service-auth.ts +++ b/src/service-auth.ts @@ -63,7 +63,8 @@ export function resolveServiceAuth(name: string, config: ServiceConfig): Resolve instruction = "credential resolved from the configured vault (run `kit secrets`)"; break; case "capture": - instruction = "capture-to-vault: `kit secrets set <KEY> --stdin` (paste once, stored in the vault)"; + instruction = + "capture-to-vault: `kit secrets set <KEY> --stdin` (paste once, stored in the vault)"; break; case "interactive": instruction = config.login diff --git a/src/service-registry.test.ts b/src/service-registry.test.ts index f0910b82..b6a8ec8e 100644 --- a/src/service-registry.test.ts +++ b/src/service-registry.test.ts @@ -22,7 +22,10 @@ describe("service-registry", () => { }); it("returns services in registry order regardless of input order (stripe precedes supabase)", async () => { - const s = await detectServices({ deps: ["@supabase/supabase-js", "stripe"], fileExists: noFiles }); + const s = await detectServices({ + deps: ["@supabase/supabase-js", "stripe"], + fileExists: noFiles, + }); assert.deepEqual(s, ["stripe", "supabase"]); }); }); @@ -39,7 +42,10 @@ describe("service-registry", () => { }); it("matches atlassian by bitbucket-pipelines.yml", async () => { - const s = await detectServices({ deps: [], fileExists: async (p) => p === "bitbucket-pipelines.yml" }); + const s = await detectServices({ + deps: [], + fileExists: async (p) => p === "bitbucket-pipelines.yml", + }); assert.deepEqual(s, ["atlassian"]); }); }); @@ -111,8 +117,17 @@ describe("service-registry", () => { it("the new DB/BaaS services are present", () => { for (const id of [ - "convex", "firebase", "mysql", "planetscale", "neon", "turso", "bigquery", "snowflake", - "redshift", "redis", "auth0", + "convex", + "firebase", + "mysql", + "planetscale", + "neon", + "turso", + "bigquery", + "snowflake", + "redshift", + "redis", + "auth0", ]) { assert.ok(SERVICE_BY_ID[id], `missing new service: ${id}`); } diff --git a/src/service-registry.ts b/src/service-registry.ts index 5740ee07..63c43824 100644 --- a/src/service-registry.ts +++ b/src/service-registry.ts @@ -61,7 +61,11 @@ export const SERVICE_REGISTRY: ServiceDef[] = [ files: ["supabase"], login: "supabase login", check: "supabase projects list", - secrets: ["NEXT_PUBLIC_SUPABASE_URL", "NEXT_PUBLIC_SUPABASE_ANON_KEY", "SUPABASE_SERVICE_ROLE_KEY"], + secrets: [ + "NEXT_PUBLIC_SUPABASE_URL", + "NEXT_PUBLIC_SUPABASE_ANON_KEY", + "SUPABASE_SERVICE_ROLE_KEY", + ], tool: "supabase", migrate: "supabase db push", }, @@ -130,7 +134,14 @@ export const SERVICE_REGISTRY: ServiceDef[] = [ }, { id: "sentry", - deps: ["@sentry/nextjs", "@sentry/node", "@sentry/react", "@sentry/svelte", "@sentry/astro", "@sentry/remix"], + deps: [ + "@sentry/nextjs", + "@sentry/node", + "@sentry/react", + "@sentry/svelte", + "@sentry/astro", + "@sentry/remix", + ], pyDeps: ["sentry-sdk"], goMods: ["github.com/getsentry/sentry-go"], login: "# sentry — no CLI login; get DSN from https://sentry.io", @@ -253,7 +264,13 @@ export const SERVICE_REGISTRY: ServiceDef[] = [ deps: ["@auth0/nextjs-auth0", "@auth0/auth0-react", "auth0"], login: "# auth0 - no CLI login; get keys from https://manage.auth0.com", check: "# auth0 - check AUTH0_CLIENT_ID is set", - secrets: ["AUTH0_SECRET", "AUTH0_BASE_URL", "AUTH0_ISSUER_BASE_URL", "AUTH0_CLIENT_ID", "AUTH0_CLIENT_SECRET"], + secrets: [ + "AUTH0_SECRET", + "AUTH0_BASE_URL", + "AUTH0_ISSUER_BASE_URL", + "AUTH0_CLIENT_ID", + "AUTH0_CLIENT_SECRET", + ], }, { id: "keycloak", diff --git a/src/skills.ts b/src/skills.ts index 9c02b457..923df62a 100644 --- a/src/skills.ts +++ b/src/skills.ts @@ -16,9 +16,7 @@ export interface SkillsLockFile { const LOCK_FILE = "skills-lock.json"; -export async function readSkillsLock( - dir: string, -): Promise<SkillsLockFile | null> { +export async function readSkillsLock(dir: string): Promise<SkillsLockFile | null> { try { const content = await readFile(resolve(dir, LOCK_FILE), "utf-8"); return JSON.parse(content) as SkillsLockFile; @@ -27,10 +25,7 @@ export async function readSkillsLock( } } -export async function writeSkillsLock( - dir: string, - lock: SkillsLockFile, -): Promise<void> { +export async function writeSkillsLock(dir: string, lock: SkillsLockFile): Promise<void> { const path = resolve(dir, LOCK_FILE); await writeFile(path, JSON.stringify(lock, null, 2) + "\n", "utf-8"); } diff --git a/src/stack-detector.test.ts b/src/stack-detector.test.ts index 95aecece..6eb967c5 100644 --- a/src/stack-detector.test.ts +++ b/src/stack-detector.test.ts @@ -5,10 +5,7 @@ import { join } from "node:path"; import { tmpdir } from "node:os"; import { detectStack } from "./stack-detector.js"; -async function makeProject( - dir: string, - files: Record<string, string> -): Promise<void> { +async function makeProject(dir: string, files: Record<string, string>): Promise<void> { await mkdir(dir, { recursive: true }); for (const [name, content] of Object.entries(files)) { const filePath = join(dir, name); @@ -31,8 +28,14 @@ describe("detectStack", () => { const stack = await detectStack(dir); assert.equal(stack.language, "typescript"); assert.equal(stack.framework, "nextjs"); - assert.ok(stack.services.includes("supabase"), `expected supabase in services: ${JSON.stringify(stack.services)}`); - assert.ok(stack.services.includes("stripe"), `expected stripe in services: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("supabase"), + `expected supabase in services: ${JSON.stringify(stack.services)}`, + ); + assert.ok( + stack.services.includes("stripe"), + `expected stripe in services: ${JSON.stringify(stack.services)}`, + ); assert.ok(stack.tools.pnpm, "expected pnpm in tools"); assert.ok(stack.confidence >= 0.8); } finally { @@ -81,8 +84,14 @@ describe("detectStack", () => { try { const stack = await detectStack(dir); assert.equal(stack.language, "python"); - assert.ok(stack.services.includes("stripe"), `expected stripe: ${JSON.stringify(stack.services)}`); - assert.ok(stack.services.includes("sentry"), `expected sentry: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("stripe"), + `expected stripe: ${JSON.stringify(stack.services)}`, + ); + assert.ok( + stack.services.includes("sentry"), + `expected sentry: ${JSON.stringify(stack.services)}`, + ); } finally { await rm(dir, { recursive: true, force: true }); } @@ -159,9 +168,18 @@ describe("detectStack", () => { }); try { const stack = await detectStack(dir); - assert.ok(stack.services.includes("resend"), `expected resend: ${JSON.stringify(stack.services)}`); - assert.ok(stack.services.includes("clerk"), `expected clerk: ${JSON.stringify(stack.services)}`); - assert.ok(stack.services.includes("trigger"), `expected trigger: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("resend"), + `expected resend: ${JSON.stringify(stack.services)}`, + ); + assert.ok( + stack.services.includes("clerk"), + `expected clerk: ${JSON.stringify(stack.services)}`, + ); + assert.ok( + stack.services.includes("trigger"), + `expected trigger: ${JSON.stringify(stack.services)}`, + ); } finally { await rm(dir, { recursive: true, force: true }); } @@ -188,7 +206,10 @@ describe("detectStack", () => { }); try { const stack = await detectStack(dir); - assert.ok(stack.services.includes("sentry"), `expected sentry in services: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("sentry"), + `expected sentry in services: ${JSON.stringify(stack.services)}`, + ); } finally { await rm(dir, { recursive: true, force: true }); } @@ -202,7 +223,10 @@ describe("detectStack", () => { }); try { const stack = await detectStack(dir); - assert.ok(stack.services.includes("netlify"), `expected netlify in services: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("netlify"), + `expected netlify in services: ${JSON.stringify(stack.services)}`, + ); } finally { await rm(dir, { recursive: true, force: true }); } @@ -218,7 +242,7 @@ describe("detectStack", () => { const stack = await detectStack(dir); assert.ok( stack.services.includes("cloudflare-pages"), - `expected cloudflare-pages in services: ${JSON.stringify(stack.services)}` + `expected cloudflare-pages in services: ${JSON.stringify(stack.services)}`, ); } finally { await rm(dir, { recursive: true, force: true }); @@ -239,8 +263,14 @@ describe("detectStack", () => { try { const stack = await detectStack(dir); assert.equal(stack.framework, "nestjs"); - assert.ok(stack.services.includes("typeorm"), `expected typeorm: ${JSON.stringify(stack.services)}`); - assert.ok(stack.services.includes("mongoose"), `expected mongoose: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("typeorm"), + `expected typeorm: ${JSON.stringify(stack.services)}`, + ); + assert.ok( + stack.services.includes("mongoose"), + `expected mongoose: ${JSON.stringify(stack.services)}`, + ); } finally { await rm(dir, { recursive: true, force: true }); } @@ -265,7 +295,9 @@ describe("detectStack", () => { it("detects React Native (framework wins over plain react)", async () => { const dir = join(tmpdir(), `kit-detect-${process.pid}-rn`); await makeProject(dir, { - "package.json": JSON.stringify({ dependencies: { react: "18.0.0", "react-native": "0.74.0" } }), + "package.json": JSON.stringify({ + dependencies: { react: "18.0.0", "react-native": "0.74.0" }, + }), }); try { const stack = await detectStack(dir); @@ -320,15 +352,28 @@ describe("detectStack", () => { const dir = join(tmpdir(), `kit-detect-${process.pid}-monorepo`); await makeProject(dir, { // root manifest has only tooling + a workspaces glob - "package.json": JSON.stringify({ workspaces: ["apps/*", "packages/*"], devDependencies: { turbo: "2.0.0" } }), - "apps/web/package.json": JSON.stringify({ dependencies: { next: "14.0.0", stripe: "14.0.0" } }), - "packages/db/package.json": JSON.stringify({ dependencies: { "@supabase/supabase-js": "2.0.0" } }), + "package.json": JSON.stringify({ + workspaces: ["apps/*", "packages/*"], + devDependencies: { turbo: "2.0.0" }, + }), + "apps/web/package.json": JSON.stringify({ + dependencies: { next: "14.0.0", stripe: "14.0.0" }, + }), + "packages/db/package.json": JSON.stringify({ + dependencies: { "@supabase/supabase-js": "2.0.0" }, + }), }); try { const stack = await detectStack(dir); assert.equal(stack.framework, "nextjs", `expected nextjs from apps/web: ${stack.framework}`); - assert.ok(stack.services.includes("stripe"), `expected stripe: ${JSON.stringify(stack.services)}`); - assert.ok(stack.services.includes("supabase"), `expected supabase: ${JSON.stringify(stack.services)}`); + assert.ok( + stack.services.includes("stripe"), + `expected stripe: ${JSON.stringify(stack.services)}`, + ); + assert.ok( + stack.services.includes("supabase"), + `expected supabase: ${JSON.stringify(stack.services)}`, + ); } finally { await rm(dir, { recursive: true, force: true }); } @@ -350,7 +395,10 @@ describe("detectStack", () => { it(".tool-versions nodejs wins over engines.node", async () => { const dir = join(tmpdir(), `kit-detect-${process.pid}-toolversions`); await makeProject(dir, { - "package.json": JSON.stringify({ engines: { node: ">=18.0.0" }, dependencies: { next: "14.0.0" } }), + "package.json": JSON.stringify({ + engines: { node: ">=18.0.0" }, + dependencies: { next: "14.0.0" }, + }), ".tool-versions": "nodejs 22.11.0\npython 3.11.4\n", }); try { diff --git a/src/stack-detector.ts b/src/stack-detector.ts index 61dd3e94..e5b0cbca 100644 --- a/src/stack-detector.ts +++ b/src/stack-detector.ts @@ -71,7 +71,8 @@ async function collectWorkspaceDeps(cwd: string, pkg: PackageJson): Promise<stri for (const dir of await expandWorkspaceGlob(cwd, g)) { const member = await readJson<PackageJson>(join(cwd, dir, "package.json")); if (member) { - for (const k of Object.keys({ ...member.dependencies, ...member.devDependencies })) deps.add(k); + for (const k of Object.keys({ ...member.dependencies, ...member.devDependencies })) + deps.add(k); } } } @@ -266,9 +267,7 @@ async function detectFromRust(cwd: string): Promise<DetectedStack | null> { } async function detectFromPhp(cwd: string): Promise<DetectedStack | null> { - const composer = await readJson<{ require?: Record<string, string> }>( - join(cwd, "composer.json") - ); + const composer = await readJson<{ require?: Record<string, string> }>(join(cwd, "composer.json")); if (!composer) return null; let framework: string | undefined; @@ -328,12 +327,14 @@ async function detectFromAndroid(cwd: string): Promise<DetectedStack | null> { (await readFile(join(cwd, "build.gradle.kts"), "utf-8").catch(() => null)) ?? (await readFile(join(cwd, "build.gradle"), "utf-8").catch(() => null)); const hasSettings = - (await fileExists(join(cwd, "settings.gradle.kts"))) || (await fileExists(join(cwd, "settings.gradle"))); + (await fileExists(join(cwd, "settings.gradle.kts"))) || + (await fileExists(join(cwd, "settings.gradle"))); if (gradle === null && !hasSettings) return null; // Only call it Android when the Android Gradle plugin is applied; otherwise // it's a generic JVM/Gradle project (label the language, not a mobile framework). - const framework = gradle && /com\.android\.(application|library)/.test(gradle) ? "android" : undefined; + const framework = + gradle && /com\.android\.(application|library)/.test(gradle) ? "android" : undefined; const services = await detectServices({ fileExists: (p) => fileExists(join(cwd, p)) }); return { diff --git a/src/status.test.ts b/src/status.test.ts index 2929fcd8..9efe39d4 100644 --- a/src/status.test.ts +++ b/src/status.test.ts @@ -52,7 +52,10 @@ describe("kit status", () => { it("configured project: every signal on", async () => { const proj = join(tmp, "ready"); mkdirSync(proj, { recursive: true }); - writeFileSync(join(proj, ".kit.toml"), `[tools]\nnode = "22"\n\n[secrets]\nstore = "1password"\n`); + writeFileSync( + join(proj, ".kit.toml"), + `[tools]\nnode = "22"\n\n[secrets]\nstore = "1password"\n`, + ); writeFileSync(join(proj, "CLAUDE.md"), `# Project\n\n${KIT_BLOCK_BEGIN}\nuse kit\n`); writeFileSync( join(proj, ".gitignore"), @@ -75,14 +78,22 @@ describe("kit status", () => { const dbPath = join(proj, "memory.db"); const seed = openMemoryDb(dbPath); - insertMessage(seed, { uuid: "u1", sessionId: "s1", type: "user", role: "user", content: "hello" }); + insertMessage(seed, { + uuid: "u1", + sessionId: "s1", + type: "user", + role: "user", + content: "hello", + }); seed.close(); process.env.KIT_MEMORY_DB = dbPath; const settings = join(proj, "settings.json"); writeFileSync( settings, - JSON.stringify({ hooks: { UserPromptSubmit: [{ hooks: [{ command: "kit memory hook" }] }] } }), + JSON.stringify({ + hooks: { UserPromptSubmit: [{ hooks: [{ command: "kit memory hook" }] }] }, + }), ); process.env.KIT_CLAUDE_SETTINGS = settings; diff --git a/src/status.ts b/src/status.ts index 2ccb1910..05a16117 100644 --- a/src/status.ts +++ b/src/status.ts @@ -86,7 +86,8 @@ export async function gatherStatus(cwd: string = process.cwd()): Promise<StatusI ignore.missingPatterns.length === 0 ? "sensitive paths covered" : `${ignore.missingPatterns.length} sensitive path(s) unignored`, - hint: ignore.missingPatterns.length === 0 ? undefined : "run `kit security check-gitignore --fix`", + hint: + ignore.missingPatterns.length === 0 ? undefined : "run `kit security check-gitignore --fix`", }); // Supply chain — is there a dependency allowlist to enforce on install? diff --git a/src/supply-chain.test.ts b/src/supply-chain.test.ts index 18834020..e38b0a85 100644 --- a/src/supply-chain.test.ts +++ b/src/supply-chain.test.ts @@ -12,10 +12,31 @@ import { } from "./supply-chain.js"; const lockPkgs: LockPkg[] = [ - { path: "node_modules/lodash", name: "lodash", version: "4.17.21", resolved: "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" }, - { path: "node_modules/esbuild", name: "esbuild", version: "0.20.0", resolved: "https://registry.npmjs.org/esbuild/-/esbuild-0.20.0.tgz", hasInstallScript: true }, - { path: "node_modules/sketchy", name: "sketchy", version: "1.0.0", resolved: "https://evil.example/sketchy.tgz" }, - { path: "node_modules/@acme/core", name: "@acme/core", version: "2.0.0", resolved: "https://registry.npmjs.org/@acme/core/-/core-2.0.0.tgz" }, + { + path: "node_modules/lodash", + name: "lodash", + version: "4.17.21", + resolved: "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + }, + { + path: "node_modules/esbuild", + name: "esbuild", + version: "0.20.0", + resolved: "https://registry.npmjs.org/esbuild/-/esbuild-0.20.0.tgz", + hasInstallScript: true, + }, + { + path: "node_modules/sketchy", + name: "sketchy", + version: "1.0.0", + resolved: "https://evil.example/sketchy.tgz", + }, + { + path: "node_modules/@acme/core", + name: "@acme/core", + version: "2.0.0", + resolved: "https://registry.npmjs.org/@acme/core/-/core-2.0.0.tgz", + }, ]; describe("findInstallScripts", () => { @@ -76,7 +97,9 @@ describe("findSlopsquat", () => { describe("parseLockPkgs", () => { it("skips the root entry and flattens packages", () => { - const pkgs = parseLockPkgs({ packages: { "": { name: "root" }, "node_modules/x": { version: "1.0.0", resolved: "r" } } }); + const pkgs = parseLockPkgs({ + packages: { "": { name: "root" }, "node_modules/x": { version: "1.0.0", resolved: "r" } }, + }); assert.equal(pkgs.length, 1); assert.equal(pkgs[0].name, "x"); }); diff --git a/src/supply-chain.ts b/src/supply-chain.ts index 6a4078c8..127ca739 100644 --- a/src/supply-chain.ts +++ b/src/supply-chain.ts @@ -47,7 +47,10 @@ export function findLockDrift(declaredDeps: string[], lockNames: Set<string>): s /** Packages resolved from a non-registry source (http/git tarball) — supply-chain risk. */ export function findNonRegistryResolved(lockPkgs: LockPkg[]): { name: string; resolved: string }[] { return lockPkgs - .filter((p) => p.resolved && !REGISTRY.test(p.resolved) && /^(https?:|git\+|github:)/.test(p.resolved)) + .filter( + (p) => + p.resolved && !REGISTRY.test(p.resolved) && /^(https?:|git\+|github:)/.test(p.resolved), + ) .map((p) => ({ name: p.name, resolved: p.resolved! })); } @@ -59,7 +62,8 @@ export function findDepConfusion( ): string[] { if (internalScopes.length === 0) return []; return declaredDeps.filter( - (d) => internalScopes.some((s) => d === s || d.startsWith(s.endsWith("/") ? s : `${s}/`)) && + (d) => + internalScopes.some((s) => d === s || d.startsWith(s.endsWith("/") ? s : `${s}/`)) && REGISTRY.test(resolvedByName.get(d) ?? ""), ); } @@ -95,7 +99,10 @@ export function editDistance(a: string, b: string, cap = 2): number { } /** Deps that look like a near-miss (≤1 edit, incl. transposition) of a popular package. */ -export function findSlopsquat(declaredDeps: string[], corpus: ReadonlySet<string> = TOP_NPM_SET): { name: string; near: string }[] { +export function findSlopsquat( + declaredDeps: string[], + corpus: ReadonlySet<string> = TOP_NPM_SET, +): { name: string; near: string }[] { const out: { name: string; near: string }[] = []; for (const d of declaredDeps) { if (corpus.has(d)) continue; // exact popular package = fine @@ -115,7 +122,10 @@ interface PackageJson { devDependencies?: Record<string, string>; } interface LockfileV3 { - packages?: Record<string, { name?: string; version?: string; resolved?: string; hasInstallScript?: boolean }>; + packages?: Record< + string, + { name?: string; version?: string; resolved?: string; hasInstallScript?: boolean } + >; } /** Parse an npm lockfile (v3 `packages` map) into a flat LockPkg list. */ @@ -124,7 +134,13 @@ export function parseLockPkgs(lock: LockfileV3): LockPkg[] { for (const [path, meta] of Object.entries(lock.packages ?? {})) { if (path === "") continue; // the root project entry const name = meta.name ?? path.split("node_modules/").pop() ?? path; - out.push({ path, name, version: meta.version, resolved: meta.resolved, hasInstallScript: meta.hasInstallScript }); + out.push({ + path, + name, + version: meta.version, + resolved: meta.resolved, + hasInstallScript: meta.hasInstallScript, + }); } return out; } @@ -151,10 +167,20 @@ export function runSupplyChain(cwd: string, internalScopes: string[] = []): Secu try { lock = JSON.parse(readFileSync(resolve(cwd, "package-lock.json"), "utf8")) as LockfileV3; } catch { - return [result("lockfile", "warn", "no package-lock.json — install-time checks need a committed lockfile", "medium")]; + return [ + result( + "lockfile", + "warn", + "no package-lock.json — install-time checks need a committed lockfile", + "medium", + ), + ]; } - const declared = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]; + const declared = [ + ...Object.keys(pkg.dependencies ?? {}), + ...Object.keys(pkg.devDependencies ?? {}), + ]; const lockPkgs = parseLockPkgs(lock); const lockNames = new Set(lockPkgs.map((p) => p.name)); const resolvedByName = new Map(lockPkgs.map((p) => [p.name, p.resolved] as const)); @@ -177,30 +203,80 @@ export function runSupplyChain(cwd: string, internalScopes: string[] = []): Secu const drift = findLockDrift(declared, lockNames); const nonReg = findNonRegistryResolved(lockPkgs); if (drift.length === 0 && nonReg.length === 0) { - out.push(result("lockfile-drift", "pass", "lockfile covers all declared deps; all resolved from the registry")); + out.push( + result( + "lockfile-drift", + "pass", + "lockfile covers all declared deps; all resolved from the registry", + ), + ); } else { if (drift.length > 0) { - out.push(result("lockfile-drift", "warn", `${drift.length} declared dep(s) missing from the lockfile: ${drift.slice(0, 8).join(", ")}`, "medium", "run `npm install` and commit the lockfile")); + out.push( + result( + "lockfile-drift", + "warn", + `${drift.length} declared dep(s) missing from the lockfile: ${drift.slice(0, 8).join(", ")}`, + "medium", + "run `npm install` and commit the lockfile", + ), + ); } if (nonReg.length > 0) { - out.push(result("lockfile-source", "warn", `${nonReg.length} package(s) resolved from a non-registry source (${nonReg.slice(0, 3).map((n) => n.name).join(", ")})`, "high", "verify these http/git tarball sources are trusted")); + out.push( + result( + "lockfile-source", + "warn", + `${nonReg.length} package(s) resolved from a non-registry source (${nonReg + .slice(0, 3) + .map((n) => n.name) + .join(", ")})`, + "high", + "verify these http/git tarball sources are trusted", + ), + ); } } const confusion = findDepConfusion(declared, resolvedByName, internalScopes); if (internalScopes.length === 0) { - out.push(result("dep-confusion", "skip", "no internal scopes declared ([supply_chain] internal_scopes)")); + out.push( + result( + "dep-confusion", + "skip", + "no internal scopes declared ([supply_chain] internal_scopes)", + ), + ); } else if (confusion.length === 0) { - out.push(result("dep-confusion", "pass", "no internal-scoped dep resolves from the public registry")); + out.push( + result("dep-confusion", "pass", "no internal-scoped dep resolves from the public registry"), + ); } else { - out.push(result("dep-confusion", "fail", `${confusion.length} internal-scoped dep(s) resolved from the PUBLIC registry: ${confusion.join(", ")}`, "high", "a public package shares your internal name — pin to your private registry")); + out.push( + result( + "dep-confusion", + "fail", + `${confusion.length} internal-scoped dep(s) resolved from the PUBLIC registry: ${confusion.join(", ")}`, + "high", + "a public package shares your internal name — pin to your private registry", + ), + ); } const slop = findSlopsquat(declared); out.push( slop.length === 0 ? result("slopsquat", "pass", "no dependency name looks like a popular-package look-alike") - : result("slopsquat", "warn", `${slop.length} possible look-alike(s): ${slop.slice(0, 5).map((s) => `${s.name}≈${s.near}`).join(", ")}`, "high", "confirm these are the intended packages, not typosquats"), + : result( + "slopsquat", + "warn", + `${slop.length} possible look-alike(s): ${slop + .slice(0, 5) + .map((s) => `${s.name}≈${s.near}`) + .join(", ")}`, + "high", + "confirm these are the intended packages, not typosquats", + ), ); return out; diff --git a/src/toml-generator.test.ts b/src/toml-generator.test.ts index 56b79cf9..46d4ebea 100644 --- a/src/toml-generator.test.ts +++ b/src/toml-generator.test.ts @@ -46,28 +46,45 @@ describe("generateToml", () => { it("provisions trivy only when a Dockerfile is present", () => { const without = parseTOML(generateToml(stack())) as { tools: Record<string, string> }; assert.ok(!without.tools["aqua:aquasecurity/trivy"], "no trivy without a Dockerfile"); - const withDocker = parseTOML(generateToml(stack(), { hasDockerfile: true })) as { tools: Record<string, string> }; - assert.equal(withDocker.tools["aqua:aquasecurity/trivy"], "latest", "trivy provisioned with a Dockerfile"); + const withDocker = parseTOML(generateToml(stack(), { hasDockerfile: true })) as { + tools: Record<string, string>; + }; + assert.equal( + withDocker.tools["aqua:aquasecurity/trivy"], + "latest", + "trivy provisioned with a Dockerfile", + ); }); it("provisions pip-audit for Python and osv-scanner for non-node ecosystems (not for node)", () => { - const node = parseTOML(generateToml(stack({ language: "typescript" }))) as { tools: Record<string, string> }; + const node = parseTOML(generateToml(stack({ language: "typescript" }))) as { + tools: Record<string, string>; + }; assert.ok(!node.tools["aqua:google/osv-scanner"], "no osv for node (npm audit covers it)"); assert.ok(!node.tools["pipx:pip-audit"], "no pip-audit for node"); - const python = parseTOML(generateToml(stack({ language: "python", tools: {} }))) as { tools: Record<string, string> }; + const python = parseTOML(generateToml(stack({ language: "python", tools: {} }))) as { + tools: Record<string, string>; + }; assert.equal(python.tools["pipx:pip-audit"], "latest", "pip-audit for python"); assert.ok(!python.tools["aqua:google/osv-scanner"], "no osv for python (pip-audit covers it)"); - const go = parseTOML(generateToml(stack({ language: "go", tools: {} }))) as { tools: Record<string, string> }; - assert.equal(go.tools["aqua:google/osv-scanner"], "latest", "osv-scanner for go (no dedicated scanner)"); + const go = parseTOML(generateToml(stack({ language: "go", tools: {} }))) as { + tools: Record<string, string>; + }; + assert.equal( + go.tools["aqua:google/osv-scanner"], + "latest", + "osv-scanner for go (no dedicated scanner)", + ); }); it("parseEnvTemplateKeys extracts KEY= names, ignoring comments / blanks / lowercase", () => { - assert.deepEqual( - parseEnvTemplateKeys("# comment\nFOO=1\nexport BAR=2\n\nbaz=3\nQUX_1=\n"), - ["FOO", "BAR", "QUX_1"], - ); + assert.deepEqual(parseEnvTemplateKeys("# comment\nFOO=1\nexport BAR=2\n\nbaz=3\nQUX_1=\n"), [ + "FOO", + "BAR", + "QUX_1", + ]); }); it("seeds extra secret keys from an env template, deduped against service keys", () => { @@ -118,13 +135,22 @@ describe("generateToml", () => { }); it("scaffolds a [secrets.infisical] binding block when infisical is chosen", () => { - const toml = generateToml(stack({ services: ["supabase", "stripe"] }), { secretsStore: "infisical" }); + const toml = generateToml(stack({ services: ["supabase", "stripe"] }), { + secretsStore: "infisical", + }); assert.ok(toml.includes("[secrets.infisical]"), `missing binding block: ${toml}`); const parsed = parseTOML(toml) as { secrets: { infisical?: { environment?: string } } }; - assert.equal(parsed.secrets.infisical?.environment, "dev", "binding should default environment to dev"); + assert.equal( + parsed.secrets.infisical?.environment, + "dev", + "binding should default environment to dev", + ); // No binding block for a non-infisical store. const op = generateToml(stack({ services: ["supabase"] }), { secretsStore: "1password" }); - assert.ok(!op.includes("[secrets.infisical]"), "1password config must not carry an infisical block"); + assert.ok( + !op.includes("[secrets.infisical]"), + "1password config must not carry an infisical block", + ); }); it("generates Next.js + Supabase + Stripe config", () => { diff --git a/src/toml-generator.ts b/src/toml-generator.ts index e06535b9..01f2320c 100644 --- a/src/toml-generator.ts +++ b/src/toml-generator.ts @@ -14,12 +14,20 @@ const FRAMEWORK_SETUP: Record< express: { install: "pnpm install", dev: "pnpm dev", verify: "pnpm build" }, react: { install: "pnpm install", dev: "pnpm dev", verify: "pnpm build" }, fastapi: { install: "uv sync", dev: "uv run uvicorn main:app --reload", verify: "uv run pytest" }, - django: { install: "uv sync", migrate: "uv run python manage.py migrate", verify: "uv run python manage.py check" }, + django: { + install: "uv sync", + migrate: "uv run python manage.py migrate", + verify: "uv run python manage.py check", + }, flask: { install: "uv sync", dev: "uv run flask run", verify: "uv run pytest" }, gin: { install: "go mod download", dev: "go run .", verify: "go build ./..." }, echo: { install: "go mod download", dev: "go run .", verify: "go build ./..." }, fiber: { install: "go mod download", dev: "go run .", verify: "go build ./..." }, - laravel: { install: "composer install", migrate: "php artisan migrate", verify: "php artisan test" }, + laravel: { + install: "composer install", + migrate: "php artisan migrate", + verify: "php artisan test", + }, symfony: { install: "composer install", verify: "php bin/console lint:all" }, // native mobile "react-native": { install: "pnpm install", dev: "pnpm start", verify: "pnpm tsc --noEmit" }, @@ -70,9 +78,7 @@ function servicesSection(services: string[]): string { // entries (prisma/drizzle) declare just deps+migrate, so they're skipped here. if (!def?.login || !def.check) continue; // Tools are merged into [tools] by generateToml; here we only emit login/check. - sections.push( - `[services.${svc}]\nlogin = "${def.login}"\ncheck = "${def.check}"` - ); + sections.push(`[services.${svc}]\nlogin = "${def.login}"\ncheck = "${def.check}"`); } return sections.join("\n\n"); } @@ -99,7 +105,11 @@ export function parseEnvTemplateKeys(content: string): string[] { return keys; } -function secretsSection(services: string[], store: SecretsStore = "1password", extraKeys: string[] = []): string { +function secretsSection( + services: string[], + store: SecretsStore = "1password", + extraKeys: string[] = [], +): string { const allKeys: string[] = []; const seen = new Set<string>(); const add = (k: string): void => { @@ -215,7 +225,11 @@ function setupSection(stack: DetectedStack): string { */ export function generateToml( stack: DetectedStack, - options: { secretsStore?: SecretsStore; hasDockerfile?: boolean; extraSecretKeys?: string[] } = {}, + options: { + secretsStore?: SecretsStore; + hasDockerfile?: boolean; + extraSecretKeys?: string[]; + } = {}, ): string { // Merge service tools into tools map const tools = { ...stack.tools }; @@ -256,7 +270,9 @@ export function generateToml( // leaving the CLI absent and `kit secrets` failing key-by-key — fix that by // wiring the CLI in here. Cloud secret managers (no `miseTool`) ship their CLI // through the cloud env, so they're guided at login but not provisioned. - const vaultTool = options.secretsStore && VAULT_META[options.secretsStore as Exclude<SecretsStore, "env">]?.miseTool; + const vaultTool = + options.secretsStore && + VAULT_META[options.secretsStore as Exclude<SecretsStore, "env">]?.miseTool; if (vaultTool && !tools[vaultTool]) { tools[vaultTool] = "latest"; } @@ -267,16 +283,20 @@ export function generateToml( ? `# Detected: ${stack.language} / ${stack.framework}${stack.services.length ? ` + ${stack.services.join(", ")}` : ""}` : `# Detected: ${stack.language}${stack.services.length ? ` + ${stack.services.join(", ")}` : ""}`, `# Includes default security scanners (semgrep, socket) installed via mise.`, - `` + ``, ); const toolsSec = toolsSection(tools); const servicesSec = servicesSection(stack.services); - const secretsSec = secretsSection(stack.services, options.secretsStore ?? "1password", options.extraSecretKeys ?? []); + const secretsSec = secretsSection( + stack.services, + options.secretsStore ?? "1password", + options.extraSecretKeys ?? [], + ); const setupSec = setupSection(stack); const parts = [header, toolsSec, servicesSec, secretsSec, setupSec].filter( - (s) => s.trim().length > 0 + (s) => s.trim().length > 0, ); return parts.join("\n") + "\n"; diff --git a/src/triage-gate.test.ts b/src/triage-gate.test.ts index 8e586d0a..0c7e854d 100644 --- a/src/triage-gate.test.ts +++ b/src/triage-gate.test.ts @@ -30,8 +30,16 @@ describe("triage-gate — ref → triage target mapping", () => { }); it("pipx/pip ref → pip triage", () => { - assert.deepEqual(triageTargetFor("pipx:semgrep"), { kind: "triage", type: "pip", target: "semgrep" }); - assert.deepEqual(triageTargetFor("pip:semgrep"), { kind: "triage", type: "pip", target: "semgrep" }); + assert.deepEqual(triageTargetFor("pipx:semgrep"), { + kind: "triage", + type: "pip", + target: "semgrep", + }); + assert.deepEqual(triageTargetFor("pip:semgrep"), { + kind: "triage", + type: "pip", + target: "semgrep", + }); }); it("ubi/go refs carrying owner/repo → repo triage", () => { @@ -54,7 +62,10 @@ describe("triage-gate — ref → triage target mapping", () => { }); it("unknown bare name → untriageable (no triage path)", () => { - assert.deepEqual(triageTargetFor("some-random-tool"), { kind: "untriageable", ref: "some-random-tool" }); + assert.deepEqual(triageTargetFor("some-random-tool"), { + kind: "untriageable", + ref: "some-random-tool", + }); }); it("scheme without a derivable repo → untriageable", () => { @@ -75,7 +86,10 @@ describe("triage-gate — watertight gate (fail-closed)", () => { }); it("triage non-pass (WARN/FAIL/offline) → blocked", async () => { - const v = await gateInstall("aqua:aquasecurity/trivy", triageStub(false, "TRIAGE WARNING: typosquat risk")); + const v = await gateInstall( + "aqua:aquasecurity/trivy", + triageStub(false, "TRIAGE WARNING: typosquat risk"), + ); assert.equal(v.decision, "blocked"); assert.match(v.reason, /did not pass/); assert.match(v.reason, /typosquat/); diff --git a/src/triage-gate.ts b/src/triage-gate.ts index 104f5711..aea72c4b 100644 --- a/src/triage-gate.ts +++ b/src/triage-gate.ts @@ -19,9 +19,27 @@ import { runTriage, type TriageType, type TriageResult } from "./triage.js"; /** Core language runtimes managed by mise core — the trusted base, not triaged. */ export const CORE_RUNTIMES = new Set([ - "node", "nodejs", "pnpm", "npm", "yarn", "bun", "deno", - "python", "python3", "go", "golang", "ruby", "java", "openjdk", - "rust", "cargo", "dotnet", "php", "zig", "elixir", "erlang", + "node", + "nodejs", + "pnpm", + "npm", + "yarn", + "bun", + "deno", + "python", + "python3", + "go", + "golang", + "ruby", + "java", + "openjdk", + "rust", + "cargo", + "dotnet", + "php", + "zig", + "elixir", + "erlang", ]); export type TriageMapping = @@ -46,7 +64,9 @@ function extractOwnerRepo(rest: string): string | null { export function triageTargetFor(tool: string): TriageMapping { const ref = tool.trim(); if (!ref.includes(":")) { - return CORE_RUNTIMES.has(ref.toLowerCase()) ? { kind: "runtime" } : { kind: "untriageable", ref }; + return CORE_RUNTIMES.has(ref.toLowerCase()) + ? { kind: "runtime" } + : { kind: "untriageable", ref }; } const idx = ref.indexOf(":"); const scheme = ref.slice(0, idx).toLowerCase(); @@ -75,7 +95,12 @@ const defaultDeps: GateDeps = { runTriage }; /** First non-empty line of triage output, for a compact block reason. */ function firstLine(output: string): string { - return output.split("\n").map((l) => l.trim()).find(Boolean) ?? "no triage output"; + return ( + output + .split("\n") + .map((l) => l.trim()) + .find(Boolean) ?? "no triage output" + ); } /** @@ -83,7 +108,10 @@ function firstLine(output: string): string { * triage PASS. WARN / FAIL / offline / missing-script / unmappable-ref all return * `blocked` (fail-closed). */ -export async function gateInstall(tool: string, deps: GateDeps = defaultDeps): Promise<GateVerdict> { +export async function gateInstall( + tool: string, + deps: GateDeps = defaultDeps, +): Promise<GateVerdict> { const t = triageTargetFor(tool); if (t.kind === "runtime") { return { tool, decision: "pass", reason: "core language runtime (trusted base)" }; diff --git a/src/triage.ts b/src/triage.ts index 80962ad0..1b2be71a 100644 --- a/src/triage.ts +++ b/src/triage.ts @@ -66,10 +66,7 @@ async function ensureTriageScript(): Promise<boolean> { /** * Run triage on a target */ -export async function runTriage( - type: TriageType, - target: string -): Promise<TriageResult> { +export async function runTriage(type: TriageType, target: string): Promise<TriageResult> { const scriptExists = await ensureTriageScript(); if (!scriptExists) { return { @@ -84,7 +81,7 @@ export async function runTriage( const { stdout, stderr } = await exec( "python3", [TRIAGE_SCRIPT, type, target], - { timeout: 300_000 } // 5 min for Docker pulls + { timeout: 300_000 }, // 5 min for Docker pulls ); const output = stdout + (stderr ? `\n${stderr}` : ""); diff --git a/src/update-check.ts b/src/update-check.ts index 4b0ffde0..f22e9d2b 100644 --- a/src/update-check.ts +++ b/src/update-check.ts @@ -72,7 +72,11 @@ export async function checkForUpdate(currentVersion: string): Promise<UpdateInfo // Write cache try { await mkdir(CACHE_DIR, { recursive: true }); - await writeFile(CACHE_FILE, JSON.stringify({ checkedAt: now, latestVersion: latest }), "utf8"); + await writeFile( + CACHE_FILE, + JSON.stringify({ checkedAt: now, latestVersion: latest }), + "utf8", + ); } catch { // Cache write failure is non-fatal } @@ -140,6 +144,6 @@ export function printUpdateNotice(info: UpdateInfo): void { const cyan = "\x1b[36m"; console.log( `\n ${dim}╰─${reset} ${yellow}Update available${reset}: ${dim}${info.current}${reset} → ${cyan}${info.latest}${reset} ` + - `${dim}run ${reset}${cyan}kit upgrade --self${reset}${dim} (triages before installing)${reset}` + `${dim}run ${reset}${cyan}kit upgrade --self${reset}${dim} (triages before installing)${reset}`, ); } diff --git a/src/upstash-cloudflare.test.ts b/src/upstash-cloudflare.test.ts index 6bae33a6..fb5d2b9c 100644 --- a/src/upstash-cloudflare.test.ts +++ b/src/upstash-cloudflare.test.ts @@ -24,7 +24,7 @@ describe("upstashRedisAdapter", () => { mockContext({ UPSTASH_REDIS_REST_URL: "https://xxx.upstash.io", UPSTASH_REDIS_REST_TOKEN: "token", - }) + }), ); assert.equal(result, true); }); @@ -35,7 +35,7 @@ describe("upstashRedisAdapter", () => { it("check returns false when only URL is present", async () => { const result = await upstashRedisAdapter.check( - mockContext({ UPSTASH_REDIS_REST_URL: "https://xxx.upstash.io" }) + mockContext({ UPSTASH_REDIS_REST_URL: "https://xxx.upstash.io" }), ); assert.equal(result, false); }); @@ -54,7 +54,7 @@ describe("upstashRedisAdapter", () => { UPSTASH_API_KEY: "key", UPSTASH_REDIS_REST_URL: "https://xxx.upstash.io", UPSTASH_REDIS_REST_TOKEN: "token", - }) + }), ); assert.equal(result.success, true); assert.equal(result.secrets?.UPSTASH_REDIS_REST_URL, "https://xxx.upstash.io"); @@ -68,7 +68,7 @@ describe("upstashRedisAdapter", () => { UPSTASH_API_KEY: "key", UPSTASH_REDIS_REST_URL: "https://xxx.upstash.io", UPSTASH_REDIS_REST_TOKEN: "token", - }) + }), ); // When returning existing, KV aliases not included — that's fine // Just verify structure @@ -92,7 +92,7 @@ describe("cloudflareR2Adapter", () => { R2_ACCESS_KEY_ID: "key", R2_SECRET_ACCESS_KEY: "secret", R2_BUCKET_NAME: "my-bucket", - }) + }), ); assert.equal(result, true); }); @@ -102,9 +102,7 @@ describe("cloudflareR2Adapter", () => { }); it("check returns false when only access key is present", async () => { - const result = await cloudflareR2Adapter.check( - mockContext({ R2_ACCESS_KEY_ID: "key" }) - ); + const result = await cloudflareR2Adapter.check(mockContext({ R2_ACCESS_KEY_ID: "key" })); assert.equal(result, false); }); diff --git a/src/utils/didYouMean.ts b/src/utils/didYouMean.ts index 5a9cb515..9311af65 100644 --- a/src/utils/didYouMean.ts +++ b/src/utils/didYouMean.ts @@ -22,8 +22,8 @@ export function levenshtein(a: string, b: string): number { for (let j = 1; j <= b.length; j++) { const cost = a[i - 1] === b[j - 1] ? 0 : 1; curr[j] = Math.min( - prev[j] + 1, // deletion - curr[j - 1] + 1, // insertion + prev[j] + 1, // deletion + curr[j - 1] + 1, // insertion prev[j - 1] + cost, // substitution ); } diff --git a/src/utils/promptSelect.ts b/src/utils/promptSelect.ts index 069de082..0525c721 100644 --- a/src/utils/promptSelect.ts +++ b/src/utils/promptSelect.ts @@ -14,12 +14,8 @@ export interface PromptOption { * (or the first option) when stdin is not a TTY — the same convention * promptConfirm uses, so CI / piped invocations remain deterministic. */ -export async function promptSelect( - question: string, - options: PromptOption[], -): Promise<string> { - const fallback = - options.find((o) => o.recommended)?.value ?? options[0]?.value ?? ""; +export async function promptSelect(question: string, options: PromptOption[]): Promise<string> { + const fallback = options.find((o) => o.recommended)?.value ?? options[0]?.value ?? ""; if (!process.stdin.isTTY) return fallback; if (options.length === 0) return ""; @@ -34,9 +30,7 @@ export async function promptSelect( options.forEach((opt, idx) => { const star = opt.recommended ? " *" : " "; const hint = opt.hint ? ` — ${opt.hint}` : ""; - process.stdout.write( - ` [${idx + 1}]${star} ${opt.label}${hint}\n`, - ); + process.stdout.write(` [${idx + 1}]${star} ${opt.label}${hint}\n`); }); const defaultLabel = options.findIndex((o) => o.recommended) + 1 || 1; @@ -52,9 +46,7 @@ export async function promptSelect( } // Accept value-string match as well (e.g. user types "1password") - const direct = options.find( - (o) => o.value.toLowerCase() === answer.toLowerCase(), - ); + const direct = options.find((o) => o.value.toLowerCase() === answer.toLowerCase()); if (direct) return direct.value; process.stdout.write(`Invalid choice "${answer}" — using default.\n`); @@ -86,32 +78,27 @@ export async function promptMultiSelect( options.forEach((opt, idx) => { const star = opt.recommended ? " *" : " "; const hint = opt.hint ? ` — ${opt.hint}` : ""; - process.stdout.write( - ` [${idx + 1}]${star} ${opt.label}${hint}\n`, - ); + process.stdout.write(` [${idx + 1}]${star} ${opt.label}${hint}\n`); }); const defaultStr = defaults.length - ? defaults - .map((v) => options.findIndex((o) => o.value === v) + 1) - .join(",") + ? defaults.map((v) => options.findIndex((o) => o.value === v) + 1).join(",") : "1"; - const answer = ( - await rl.question(`Choose comma-separated (default ${defaultStr}): `) - ).trim(); + const answer = (await rl.question(`Choose comma-separated (default ${defaultStr}): `)).trim(); if (!answer) return defaults; const picked = new Set<string>(); - for (const token of answer.split(",").map((s) => s.trim()).filter(Boolean)) { + for (const token of answer + .split(",") + .map((s) => s.trim()) + .filter(Boolean)) { const num = Number.parseInt(token, 10); if (Number.isFinite(num) && num >= 1 && num <= options.length) { picked.add(options[num - 1].value); continue; } - const direct = options.find( - (o) => o.value.toLowerCase() === token.toLowerCase(), - ); + const direct = options.find((o) => o.value.toLowerCase() === token.toLowerCase()); if (direct) picked.add(direct.value); } return [...picked]; diff --git a/src/utils/redactSecrets.test.ts b/src/utils/redactSecrets.test.ts index 8f65ba59..bcfee100 100644 --- a/src/utils/redactSecrets.test.ts +++ b/src/utils/redactSecrets.test.ts @@ -4,17 +4,13 @@ import { redactSecrets, safeStatusLine } from "./redactSecrets.js"; describe("redactSecrets", () => { it("redacts stripe test secret keys", () => { - const out = redactSecrets( - "test_mode_api_key = 'sk_test_51T2AMtJLRlXeUG4dKBwX2nsve3BLEzy'", - ); + const out = redactSecrets("test_mode_api_key = 'sk_test_51T2AMtJLRlXeUG4dKBwX2nsve3BLEzy'"); assert.ok(out.includes("[REDACTED]")); assert.ok(!out.includes("sk_test_51T2AM")); }); it("redacts stripe live keys + webhook secrets", () => { - const out = redactSecrets( - "sk_live_AbCdEfGhIjKlMnOpQrSt whsec_aaaaaaaaaaaaaaaaaaaaaa", - ); + const out = redactSecrets("sk_live_AbCdEfGhIjKlMnOpQrSt whsec_aaaaaaaaaaaaaaaaaaaaaa"); const matches = out.match(/\[REDACTED\]/g) || []; assert.equal(matches.length, 2); }); diff --git a/src/utils/redactSecrets.ts b/src/utils/redactSecrets.ts index aa3beaca..dcb37057 100644 --- a/src/utils/redactSecrets.ts +++ b/src/utils/redactSecrets.ts @@ -30,7 +30,10 @@ export const SECRET_PATTERNS: RedactPattern[] = [ { re: /\b(AKIA|ASIA)[A-Z0-9]{16}\b/g, label: "aws-access-key" }, { re: /aws_secret_access_key\s*=\s*[A-Za-z0-9/+]{40}/gi, label: "aws-secret-key" }, // Google / GCP service-account JSON fragments - { re: /"private_key":\s*"-----BEGIN [^"]+-----[\s\S]+?-----END [^"]+-----\\n"/g, label: "gcp-private-key" }, + { + re: /"private_key":\s*"-----BEGIN [^"]+-----[\s\S]+?-----END [^"]+-----\\n"/g, + label: "gcp-private-key", + }, { re: /\bAIza[0-9A-Za-z\-_]{35}\b/g, label: "google-api-key" }, // Slack { re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g, label: "slack-token" }, diff --git a/src/validation/dynamic-schema.ts b/src/validation/dynamic-schema.ts index 03df43d5..7765c17e 100644 --- a/src/validation/dynamic-schema.ts +++ b/src/validation/dynamic-schema.ts @@ -5,9 +5,7 @@ import type { PluginRegistry } from "../plugin-registry.js"; * Create a dynamic Zod schema for web_search provider validation * that includes both built-in and plugin-registered providers */ -export function createWebSearchProviderSchema( - registry?: PluginRegistry, -): z.ZodType<string> { +export function createWebSearchProviderSchema(registry?: PluginRegistry): z.ZodType<string> { const builtInProviders = ["brave", "google", "searxng", "custom"]; let providers = builtInProviders; @@ -56,8 +54,7 @@ export function createWebSearchConfigSchema( return true; }, { - message: - "SearXNG requires 'url' and Brave requires 'apiKey' configuration", + message: "SearXNG requires 'url' and Brave requires 'apiKey' configuration", }, ); } @@ -84,9 +81,7 @@ export function validateWebSearchConfig( if (err instanceof z.ZodError) { return { valid: false, - errors: err.issues.map( - (issue) => `${issue.path.join(".")}: ${issue.message}`, - ), + errors: err.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`), }; } return { diff --git a/src/vault-meta.test.ts b/src/vault-meta.test.ts index 13852654..2d76c934 100644 --- a/src/vault-meta.test.ts +++ b/src/vault-meta.test.ts @@ -4,7 +4,10 @@ import { detectSecretStore, vaultMeta, VAULT_META } from "./vault-meta.js"; describe("vault-meta", () => { describe("detectSecretStore", () => { - const has = (...present: string[]) => async (p: string) => present.includes(p); + const has = + (...present: string[]) => + async (p: string) => + present.includes(p); it("detects infisical from .infisical.json", async () => { assert.equal(await detectSecretStore(has(".infisical.json")), "infisical"); diff --git a/src/vault-meta.ts b/src/vault-meta.ts index 74570f77..70c8dfe3 100644 --- a/src/vault-meta.ts +++ b/src/vault-meta.ts @@ -42,7 +42,12 @@ export const VAULT_META: Record<Exclude<SecretsStore, "env">, VaultMeta> = { loginCmd: "infisical login", initCmd: "infisical init", }, - doppler: { label: "Doppler", miseTool: "doppler", loginCmd: "doppler login", initCmd: "doppler setup" }, + doppler: { + label: "Doppler", + miseTool: "doppler", + loginCmd: "doppler login", + initCmd: "doppler setup", + }, bitwarden: { label: "Bitwarden", miseTool: "bitwarden", loginCmd: "bw login && bw unlock" }, vault: { label: "HashiCorp Vault", miseTool: "vault", loginCmd: "vault login" }, "aws-sm": { label: "AWS Secrets Manager", loginCmd: "aws configure (or assume an IAM role)" }, From 369323c7367f8b9a5314c91cde5e62836b0c6163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Peter=20Sandstr=C3=B6m?= <peter@sandstre.am> Date: Tue, 23 Jun 2026 14:28:16 +0200 Subject: [PATCH 3/3] chore: ignore the prettier reformat in git blame Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --- .git-blame-ignore-revs | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..927ca245 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,6 @@ +# Revisions to skip in `git blame` (mechanical, no-logic-change commits). +# Enable locally with: git config blame.ignoreRevsFile .git-blame-ignore-revs +# GitHub honours this file automatically. + +# style: format codebase with prettier +49f28e900a6a6c1bdf8893d699e9ee1cd574c787