diff --git a/CHANGELOG.md b/CHANGELOG.md index 0179b22b..04fa3633 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [1.15.0] - 2026-06-23 + +### Added +- **`kit health` completes connected-service sensor coverage: Supabase advisor + TLS-cert.** The Supabase sensor probes the Management API security advisors (`GET /v1/projects/:ref/advisors/security` with `SUPABASE_ACCESS_TOKEN` + `SUPABASE_PROJECT_REF`) and goes red (class `code`) on ERROR-level lints (RLS-disabled / exposed-data); selected when `supabase` is a detected service. The TLS-cert sensor checks certificate expiry for the host(s) in `KIT_TLS_HOST` (warn window `KIT_TLS_WARN_DAYS`, default 21) over a native TLS handshake — red (critical) when already expired, red (high) within the window, green otherwise. Both report `unknown`, never a false `green`. Pure parsers/evaluators are unit-tested; live API/handshake smoke is pending real creds. (#51) +- **Context-lock now covers app-service auth identity: Keycloak realm, Auth0 tenant, Clerk environment.** `[context.keycloak] realm`, `[context.auth0] tenant`, and `[context.clerk] env` join the lock table; `kit context check` reads the live value from the app's env (`KEYCLOAK_REALM`, `AUTH0_DOMAIN`/`AUTH0_TENANT`, and the `pk_live_`/`pk_test_` prefix of `CLERK_PUBLISHABLE_KEY`) and verifies it matches the declared one — a "dev pointed at prod" guard (a prod Clerk key in a dev checkout is a mismatch, not a silent pass). One data row each; the lock stays data-driven. (#38) +- **`Redacted` secret wrapper (`src/utils/redacted.ts`).** A value held in a module-private WeakMap that masks as `` through `String()`, `JSON.stringify`, `util.inspect`/`console.log`, and object-key enumeration; the only path to the value is the explicit `.expose()`, so secret reads stay grep-able. Borrowed from Effect's `Redacted` pattern (the pattern, not the framework). (#46) + ## [1.14.1] - 2026-06-22 ### Fixed diff --git a/package-lock.json b/package-lock.json index 8ed7d3e8..634aac80 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "1.14.1", + "version": "1.15.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "1.14.1", + "version": "1.15.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index f35e2a03..d040d86a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "1.14.1", + "version": "1.15.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/src/config.ts b/src/config.ts index 7bf69243..7323f22e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -266,6 +266,14 @@ export interface ContextConfig { ssh?: { identity?: string; fingerprint?: string; host_alias?: string }; git?: { email?: string }; npm?: { registry?: string }; + /** + * App-service auth identity — guards "dev pointed at prod". Declares which + * Keycloak realm / Auth0 tenant / Clerk environment this repo must run against; + * `kit context check` reads the live value from the app's env and verifies it. + */ + keycloak?: { realm?: string }; + auth0?: { tenant?: string }; + clerk?: { env?: string }; } /** [setup] — project bootstrap commands run by `kit setup`. install/verify run @@ -524,6 +532,9 @@ const kitConfigSchema = z .optional(), git: z.object({ email: z.string().optional() }).passthrough().optional(), npm: z.object({ registry: z.string().optional() }).passthrough().optional(), + keycloak: z.object({ realm: z.string().optional() }).passthrough().optional(), + auth0: z.object({ tenant: z.string().optional() }).passthrough().optional(), + clerk: z.object({ env: z.string().optional() }).passthrough().optional(), }) .passthrough() .optional(), diff --git a/src/context-lock.test.ts b/src/context-lock.test.ts index f3942c23..99cdab95 100644 --- a/src/context-lock.test.ts +++ b/src/context-lock.test.ts @@ -13,6 +13,7 @@ import { parseGcloudProject, suggestContextToml, hasLockableContext, + clerkEnvFromKey, type LiveContext, } from "./context-lock.js"; @@ -219,3 +220,44 @@ 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-prod" } })[0]?.status, + "mismatch", + ); + }); + + it("auth0 tenant: unknown when the live tenant can't be read", () => { + const declared = { auth0: { tenant: "myapp.eu.auth0.com" } }; + const f = compareContext(declared, { auth0: { tenant: null } })[0]; + assert.equal(f?.status, "unknown"); + assert.equal(f?.tool, "auth0"); + }); + + it("clerk env: mismatch when a prod (live) key is used where test is declared", () => { + const declared = { clerk: { env: "test" } }; + assert.equal(compareContext(declared, { clerk: { env: "test" } })[0]?.status, "ok"); + assert.equal(compareContext(declared, { clerk: { env: "live" } })[0]?.status, "mismatch"); + }); + + it("undeclared auth services are not checked", () => { + assert.equal(compareContext({}, { keycloak: { realm: "anything" } }).length, 0); + }); +}); + +describe("clerkEnvFromKey", () => { + it("extracts live/test from a publishable key; null otherwise", () => { + assert.equal(clerkEnvFromKey("pk_live_abc123"), "live"); + assert.equal(clerkEnvFromKey("pk_test_abc123"), "test"); + assert.equal(clerkEnvFromKey("sk_live_nope"), null); + assert.equal(clerkEnvFromKey(null), null); + assert.equal(clerkEnvFromKey(""), null); + }); +}); diff --git a/src/context-lock.ts b/src/context-lock.ts index ebcbb9bd..3598c697 100644 --- a/src/context-lock.ts +++ b/src/context-lock.ts @@ -37,6 +37,9 @@ export interface LiveContext { ssh?: { identity: string | null; fingerprint: string | null; host_alias: string | null }; npm?: { registry: string | null }; vercel?: { orgId: string | null; projectId: string | null }; + keycloak?: { realm: string | null }; + auth0?: { tenant: string | null }; + clerk?: { env: string | null }; } function field( @@ -75,6 +78,10 @@ const FIELD_SPECS: { { 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: "clerk", field: "env", declared: (d) => d.clerk?.env, live: (l) => l.clerk?.env ?? null }, ]; /** @@ -225,6 +232,14 @@ function expandHome(p: string | null): string | null { } /** Read the live context from each tool. Every read fails soft to null. */ +/** Clerk publishable keys are `pk_live_…` / `pk_test_…`; the env segment is the + * "dev pointed at prod" signal. Returns "live" | "test" | null. */ +export function clerkEnvFromKey(pk: string | null): string | null { + if (!pk) return null; + const m = /^pk_(live|test)_/.exec(pk.trim()); + return m ? m[1] : null; +} + export async function gatherLive(cwd: string = process.cwd()): Promise { const live: LiveContext = {}; @@ -272,6 +287,18 @@ export async function gatherLive(cwd: string = process.cwd()): Promise ({ stdout: "", stderr: "", exitCode: 0, ok: true }), + httpGet: async () => over.http ?? { ok: true, status: 200, body: lints }, + }; +} +const ctx: HealthCtx = { cwd: "/tmp/repo", config: {} }; + +describe("parseSupabaseLints / errorLints", () => { + it("parses {lints:[]} and a bare array; [] on garbage", () => { + assert.equal(parseSupabaseLints(lints).length, 2); + assert.equal(parseSupabaseLints(JSON.stringify([{ level: "ERROR" }])).length, 1); + assert.deepEqual(parseSupabaseLints("nope"), []); + }); + it("keeps only ERROR-level lints", () => { + const errs = errorLints(parseSupabaseLints(lints)); + assert.equal(errs.length, 1); + assert.equal(errs[0].name, "rls_disabled"); + }); +}); + +describe("supabaseAdvisorSensor.probe", () => { + afterEach(() => { + delete process.env.SUPABASE_ACCESS_TOKEN; + delete process.env.SUPABASE_PROJECT_REF; + }); + function setEnv() { + process.env.SUPABASE_ACCESS_TOKEN = "sbp_x"; + process.env.SUPABASE_PROJECT_REF = "abcdefghijklmnopqrst"; + } + + it("emits red (code class) on ERROR-level advisors", async () => { + setEnv(); + const out = await supabaseAdvisorSensor.probe(ctx, deps()); + assert.equal(out[0].status, "red"); + assert.equal(out[0].suggestedClass, "code"); + assert.match(out[0].source, /supabase\/abcdef/); + assert.match(out[0].title, /1 ERROR-level/); + }); + + 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 } })); + assert.equal(out[0].status, "green"); + }); + + it("is unknown (not green) when token/ref not both set", async () => { + const out = await supabaseAdvisorSensor.probe(ctx, deps()); + assert.equal(out[0].status, "unknown"); + }); + + it("is unknown on a non-OK API response", async () => { + setEnv(); + 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 new file mode 100644 index 00000000..9dbb9ace --- /dev/null +++ b/src/health-sensors/supabase-advisor.ts @@ -0,0 +1,69 @@ +import type { HealthFinding, HealthSensor } from "../health.js"; + +export interface SupabaseLint { + name?: string; + level?: string; // "ERROR" | "WARN" | "INFO" + title?: string; + description?: string; + categories?: string[]; +} + +/** Parses the Supabase advisors response (`{ lints: [...] }` or a bare array). */ +export function parseSupabaseLints(body: string): SupabaseLint[] { + try { + const obj = JSON.parse(body) as { lints?: SupabaseLint[] } | SupabaseLint[]; + if (Array.isArray(obj)) return obj; + return Array.isArray(obj.lints) ? obj.lints : []; + } catch { + return []; + } +} + +/** Lints at ERROR level — the ones worth going red on (RLS gaps, exposure). */ +export function errorLints(lints: SupabaseLint[]): SupabaseLint[] { + return lints.filter((l) => (l.level ?? "").toUpperCase() === "ERROR"); +} + +export const supabaseAdvisorSensor: HealthSensor = { + id: "supabase-advisor", + async probe(_ctx, deps): Promise { + const token = process.env.SUPABASE_ACCESS_TOKEN; + 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", + }]; + } + // 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", + }]; + } + const errs = errorLints(parseSupabaseLints(res.body)); + if (errs.length === 0) { + 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", + }]; + }, +}; diff --git a/src/health-sensors/tls-cert.test.ts b/src/health-sensors/tls-cert.test.ts new file mode 100644 index 00000000..e00a5e6a --- /dev/null +++ b/src/health-sensors/tls-cert.test.ts @@ -0,0 +1,49 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { daysUntilExpiry, evaluateCert, tlsCertSensor } from "./tls-cert.js"; +import type { HealthCtx, HealthDeps } from "../health.js"; + +const NOW = Date.parse("2026-06-01T00:00:00Z"); + +describe("daysUntilExpiry", () => { + it("computes whole days; negative when past; null on garbage", () => { + assert.equal(daysUntilExpiry("2026-06-11T00:00:00Z", NOW), 10); + assert.equal(daysUntilExpiry("2026-05-22T00:00:00Z", NOW), -10); + assert.equal(daysUntilExpiry("not-a-date", NOW), null); + }); +}); + +describe("evaluateCert", () => { + it("green when comfortably ahead", () => { + assert.equal(evaluateCert("a.com", 90, 21).status, "green"); + }); + it("red (high) when within the warn window", () => { + const f = evaluateCert("a.com", 10, 21); + assert.equal(f.status, "red"); + assert.equal(f.severity, "high"); + assert.equal(f.suggestedClass, "human"); + }); + it("red (critical) when already expired", () => { + const f = evaluateCert("a.com", -3, 21); + assert.equal(f.status, "red"); + assert.equal(f.severity, "critical"); + assert.match(f.title, /EXPIRED 3 day/); + }); + it("unknown when expiry unreadable", () => { + assert.equal(evaluateCert("a.com", null, 21).status, "unknown"); + }); +}); + +describe("tlsCertSensor.probe", () => { + const ctx: HealthCtx = { cwd: "/tmp/repo", config: {} }; + const deps: HealthDeps = { + runCli: async () => ({ stdout: "", stderr: "", exitCode: 0, ok: true }), + httpGet: async () => ({ ok: true, status: 200, body: "" }), + }; + it("is unknown (not green) when KIT_TLS_HOST is unset", async () => { + delete process.env.KIT_TLS_HOST; + const out = await tlsCertSensor.probe(ctx, deps); + assert.equal(out[0].status, "unknown"); + assert.match(out[0].title, /KIT_TLS_HOST not set/); + }); +}); diff --git a/src/health-sensors/tls-cert.ts b/src/health-sensors/tls-cert.ts new file mode 100644 index 00000000..f1851bf9 --- /dev/null +++ b/src/health-sensors/tls-cert.ts @@ -0,0 +1,73 @@ +import { connect } from "node:tls"; +import type { HealthFinding, HealthSensor } from "../health.js"; + +export interface CertInfo { + validTo?: string; +} + +/** Whole days until `validTo` relative to `now` (negative = already expired); null on unparseable. */ +export function daysUntilExpiry(validTo: string, now: number): number | null { + const t = Date.parse(validTo); + if (Number.isNaN(t)) return null; + return Math.floor((t - now) / 86_400_000); +} + +/** Pure decision: days-left + warn threshold → the finding (no I/O, fully testable). */ +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` }; + } + if (daysLeft < 0) { + return { + 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", + }; + } + if (daysLeft <= warnDays) { + return { + 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", + }; + } + 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. */ +function fetchCert(host: string, timeoutMs: number): Promise { + return new Promise((resolve) => { + const socket = connect({ host, port: 443, servername: host, timeout: timeoutMs }, () => { + const cert = socket.getPeerCertificate(); + socket.end(); + resolve(cert && cert.valid_to ? { validTo: cert.valid_to } : null); + }); + socket.on("error", () => resolve(null)); + socket.on("timeout", () => { socket.destroy(); resolve(null); }); + }); +} + +export const tlsCertSensor: HealthSensor = { + id: "tls-cert", + async probe(_ctx, _deps): Promise { + 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", + }]; + } + const warnDays = Number(process.env.KIT_TLS_WARN_DAYS ?? "21") || 21; + const out: HealthFinding[] = []; + for (const host of hosts) { + const cert = await fetchCert(host, 10_000); + const daysLeft = cert?.validTo ? daysUntilExpiry(cert.validTo, Date.now()) : null; + out.push(evaluateCert(host, daysLeft, warnDays)); + } + return out; + }, +}; diff --git a/src/health.ts b/src/health.ts index addb9077..98666cc7 100644 --- a/src/health.ts +++ b/src/health.ts @@ -6,6 +6,8 @@ import { bitbucketSensor } from "./health-sensors/bitbucket-pipelines.js"; import { vercelSensor } from "./health-sensors/vercel.js"; import { sentrySensor } from "./health-sensors/sentry.js"; import { resendSensor } from "./health-sensors/resend.js"; +import { supabaseAdvisorSensor } from "./health-sensors/supabase-advisor.js"; +import { tlsCertSensor } from "./health-sensors/tls-cert.js"; export type HealthStatus = "green" | "red" | "unknown"; export type HealthClass = "code" | "human" | "noise"; @@ -86,6 +88,8 @@ export const HEALTH_SENSORS: HealthSensor[] = [ vercelSensor, sentrySensor, resendSensor, + supabaseAdvisorSensor, + tlsCertSensor, ]; /** Returns the sensors whose underlying CI platform the project actually uses. */ @@ -104,6 +108,11 @@ export function selectSensors(ctx: HealthCtx): HealthSensor[] { return ctx.services?.includes("sentry") === true; case "resend": return ctx.services?.includes("resend") === true; + case "supabase-advisor": + return ctx.services?.includes("supabase") === true; + case "tls-cert": + // Opt-in: only when the user names host(s) to check. + return Boolean(process.env.KIT_TLS_HOST); default: return false; } diff --git a/src/utils/redacted.test.ts b/src/utils/redacted.test.ts new file mode 100644 index 00000000..3d1f5017 --- /dev/null +++ b/src/utils/redacted.test.ts @@ -0,0 +1,44 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { inspect } from "node:util"; +import { Redacted, redacted, isRedacted } from "./redacted.js"; + +describe("Redacted", () => { + const secret = redacted("sk_live_supersecret"); + + it("exposes the real value only via .expose()", () => { + assert.equal(secret.expose(), "sk_live_supersecret"); + }); + + it("masks on String() / template / toString", () => { + assert.equal(String(secret), ""); + assert.equal(`${secret}`, ""); + }); + + it("masks in JSON.stringify, including when nested in an object", () => { + assert.equal(JSON.stringify(secret), '""'); + assert.equal(JSON.stringify({ apiKey: secret }), '{"apiKey":""}'); + }); + + it("masks under util.inspect / console.log", () => { + assert.match(inspect(secret), //); + assert.doesNotMatch(inspect(secret), /supersecret/); + }); + + it("does not expose the value via own keys / Object spread", () => { + assert.deepEqual(Object.keys(secret), []); + assert.doesNotMatch(JSON.stringify({ ...secret }), /supersecret/); + }); + + it("isRedacted narrows correctly", () => { + assert.equal(isRedacted(secret), true); + assert.equal(isRedacted("plain"), false); + assert.equal(isRedacted(new Redacted(123)), true); + }); + + it("works for non-string payloads", () => { + const r = redacted({ token: "abc", n: 1 }); + assert.deepEqual(r.expose(), { token: "abc", n: 1 }); + assert.equal(String(r), ""); + }); +}); diff --git a/src/utils/redacted.ts b/src/utils/redacted.ts new file mode 100644 index 00000000..d1590b48 --- /dev/null +++ b/src/utils/redacted.ts @@ -0,0 +1,45 @@ +/** + * `Redacted` — a secret wrapper whose value never leaks through string + * coercion, `JSON.stringify`, `console.log`/`util.inspect`, or object-key + * enumeration. The only way to read the real value is the explicit `.expose()`. + * + * Borrowed from Effect's `Redacted` pattern — the *pattern*, not the framework + * (see issue: borrow the wrapper, don't adopt Effect). The value is held in a + * module-private WeakMap, so it is not an instance property and cannot be + * reached by reflection/serialization. + */ +const store = new WeakMap, unknown>(); + +const MASK = ""; + +export class Redacted { + constructor(value: T) { + store.set(this, value); + } + + /** The only path to the underlying value. Call sites become grep-able. */ + expose(): T { + return store.get(this) as T; + } + + toString(): string { + return MASK; + } + + toJSON(): string { + return MASK; + } + + // console.log / util.inspect + [Symbol.for("nodejs.util.inspect.custom")](): string { + return MASK; + } +} + +export function redacted(value: T): Redacted { + return new Redacted(value); +} + +export function isRedacted(x: unknown): x is Redacted { + return x instanceof Redacted; +}