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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` secret wrapper (`src/utils/redacted.ts`).** A value held in a module-private WeakMap that masks as `<redacted>` 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
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
11 changes: 11 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down
42 changes: 42 additions & 0 deletions src/context-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
parseGcloudProject,
suggestContextToml,
hasLockableContext,
clerkEnvFromKey,
type LiveContext,
} from "./context-lock.js";

Expand Down Expand Up @@ -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);
});
});
27 changes: 27 additions & 0 deletions src/context-lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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 },
];

/**
Expand Down Expand Up @@ -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<LiveContext> {
const live: LiveContext = {};

Expand Down Expand Up @@ -272,6 +287,18 @@ export async function gatherLive(cwd: string = process.cwd()): Promise<LiveConte
live.vercel = { orgId: null, projectId: null };
}

// App-service auth identity from the app's env — the "live" realm/tenant the app
// would actually authenticate against. Only set when the env names it (so an
// undeclared service stays unchecked rather than reporting a spurious unknown).
const kcRealm = process.env.KEYCLOAK_REALM ?? null;
if (kcRealm) live.keycloak = { realm: kcRealm };
const auth0Tenant = process.env.AUTH0_DOMAIN ?? process.env.AUTH0_TENANT ?? null;
if (auth0Tenant) live.auth0 = { tenant: auth0Tenant };
const clerkEnv = clerkEnvFromKey(
process.env.CLERK_PUBLISHABLE_KEY ?? process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
);
if (clerkEnv) live.clerk = { env: clerkEnv };

return live;
}

Expand Down
71 changes: 71 additions & 0 deletions src/health-sensors/supabase-advisor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { describe, it, afterEach } from "node:test";
import assert from "node:assert/strict";
import { parseSupabaseLints, errorLints, supabaseAdvisorSensor } from "./supabase-advisor.js";
import type { HealthCtx, HealthDeps, HttpResponse } from "../health.js";

const lints = JSON.stringify({
lints: [
{ name: "rls_disabled", level: "ERROR", title: "RLS disabled on public.users" },
{ name: "auth_otp_long", level: "WARN", title: "OTP expiry too long" },
],
});

function deps(over: { http?: HttpResponse } = {}): HealthDeps {
return {
runCli: async () => ({ 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/);
});
});
69 changes: 69 additions & 0 deletions src/health-sensors/supabase-advisor.ts
Original file line number Diff line number Diff line change
@@ -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<HealthFinding[]> {
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",
}];
},
};
49 changes: 49 additions & 0 deletions src/health-sensors/tls-cert.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
});
Loading
Loading