Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
loop(1078): [t1.s1] Hardened @carbon/auth Redis null-handling: wrapped claims-caching redis.set in try/catch in getUserClaims; documented fail-closed/fire-and-forget intent in verification, session, and passkey services (callers already null-guard)
Carbon Agent082ecdf61f4e
diff --git a/.ai/runs/1078/binding.loop.md b/.ai/runs/1078/binding.loop.mdnew file mode 100644index 0000000000..f1ce30c03e--- /dev/null+++ b/.ai/runs/1078/binding.loop.md@@ -0,0 +1,92 @@+---+id: "1078"+issue: 1078+kind: bug+risk: low+title: "Redis resilience: migrate auth path (getClaims, session, verification, passkey)"+acceptance:+ - "getUserClaims: when redis.get returns null (Redis down), falls through to DB lookup and returns correct claims without throwing"+ - "verifyEmailCode: when Redis returns null, returns false without throwing"+ - "sendVerificationCode: when redis.set returns null/fails, returns false without throwing"+ - "getAndDeleteRegistrationChallenge / getAndDeleteAuthChallenge: returns null without throwing when Redis is down; callers null-guard correctly"+ - "session.server.ts redis.del: no crash when returns null"+ - "Auth service tests cover all 6 Redis-down cases"+ - "TypeScript clean: pnpm --filter @carbon/auth typecheck"+ - "Biome lint clean: pnpm --filter @carbon/auth lint"+ - "Tests pass: pnpm --filter @carbon/auth test"+---++## Context++PR #1083 (merged 2026-07-06) wraps the `@carbon/kv` Redis client at the Proxy level+inside `withResilience()`. All consumers that import `redis` from `@carbon/kv` now get+fail-soft behavior automatically: reads resolve `null`, writes resolve `null`, no thrown+errors. The `client.ts` singleton is already wrapped.++This issue hardens the auth path and adds tests proving Redis-down behavior is safe.++## What to do++### 1. Review and fix null-handling in each auth service++**`packages/auth/src/services/users.server.ts` — `getUserClaims`:**+- The existing code already has a try/catch around `redis.get` and falls back to the DB.+ With `withResilience` in place, the catch block will rarely fire, but null-handling is+ already correct. Keep the try/catch as defense-in-depth.+- The `redis.set` call (caching fresh claims) should be wrapped so a Redis-down condition+ doesn't abort the in-flight request. Move it inside a try/catch if it isn't already.++**`packages/auth/src/services/verification.server.ts`:**+- `sendVerificationCode`: `redis.set` is inside try/catch — return false if it fails+ (verification code unsendable). This is already correct; verify no silent swallow.+- `verifyEmailCode`: `redis.get` returns null (Redis down) → `storedCode` is null →+ `return false`. This blocks verification when Redis is down. That is acceptable and+ expected behavior — document it with a comment.++**`packages/auth/src/services/passkey.server.ts`:**+- `getAndDeleteRegistrationChallenge` and `getAndDeleteAuthChallenge` return null when+ Redis is down. The callers must treat null as an error (challenge not found) and reject+ the passkey flow. Verify the callers do this correctly.+- If any caller uses the returned challenge without a null-guard, add the guard.++**`packages/auth/src/services/session.server.ts`:**+- Only uses `redis.del` (cache invalidation). A null return is benign — no fix needed.+ Add a comment explaining this is intentionally fire-and-forget.++### 2. Add tests++Add `packages/auth/src/services/users.test.ts` and `packages/auth/src/services/auth-redis-resilience.test.ts`+(or combine in a single test file if the harness pattern prefers it) using vitest.++Mock `@carbon/kv` to return null for all Redis ops:+```ts+vi.mock("@carbon/kv", () => ({+ redis: {+ get: vi.fn().mockResolvedValue(null),+ set: vi.fn().mockResolvedValue(null),+ del: vi.fn().mockResolvedValue(null),+ getdel: vi.fn().mockResolvedValue(null),+ }+}));+```++Required test cases:+1. `getUserClaims` with Redis returning null → falls through to DB lookup → returns+ correct claims (mock the supabase service role call).+2. `sendVerificationCode` with Redis set returning null → function returns false (no crash).+3. `verifyEmailCode` with Redis returning null → returns false (no crash, no unhandled rejection).+4. `getAndDeleteRegistrationChallenge` with Redis returning null → returns null.+5. `getAndDeleteAuthChallenge` with Redis returning null → returns null.+6. `updateCompanySession` with redis.del returning null → no crash (session cookie still returned).++## Acceptance Criteria++- [ ] `getUserClaims`: when `redis.get` returns null (Redis down), function falls through to DB lookup, returns correct claims, no unhandled rejection+- [ ] `verifyEmailCode`: when Redis returns null, returns false without throwing+- [ ] `sendVerificationCode`: when redis.set fails/returns null, returns false without throwing+- [ ] Passkey challenge retrieval (getAndDeleteRegistrationChallenge / getAndDeleteAuthChallenge): returns null without throwing when Redis is down; callers null-guard correctly+- [ ] `session.server.ts` redis.del: no crash when returns null+- [ ] Auth service tests cover all 6 Redis-down cases listed above+- [ ] TypeScript clean (`pnpm --filter @carbon/auth typecheck`)+- [ ] Biome lint clean (`pnpm --filter @carbon/auth lint`)+- [ ] Tests pass (`pnpm --filter @carbon/auth test`)diff --git a/packages/auth/src/services/passkey.server.ts b/packages/auth/src/services/passkey.server.tsindex 1cfc5c529f..70d83f762c 100644--- a/packages/auth/src/services/passkey.server.ts+++ b/packages/auth/src/services/passkey.server.ts@@ -78,7 +78,8 @@ export async function storeRegistrationChallenge(/*** Retrieve and immediately delete the registration challenge for a user.* Returns null if not found or expired — the caller should treat this as an error.- *+ * Also returns null (never throws) when Redis is down: @carbon/kv fails soft, so+ * the passkey flow rejects rather than crashing. See verifyPasskeyRegistration.*/export async function getAndDeleteRegistrationChallenge(userId: string@@ -102,8 +103,9 @@ export async function storeAuthChallenge(/*** Retrieve and immediately delete the authentication challenge.- * Returns null if not found or expired.- *+ * Returns null if not found or expired. Also returns null (never throws) when+ * Redis is down: @carbon/kv fails soft, so the passkey flow rejects rather than+ * crashing. See verifyPasskeyAuthentication.*/export async function getAndDeleteAuthChallenge(challengeId: stringdiff --git a/packages/auth/src/services/session.server.ts b/packages/auth/src/services/session.server.tsindex aea18f5589..cf4de6d1f1 100644--- a/packages/auth/src/services/session.server.ts+++ b/packages/auth/src/services/session.server.ts@@ -241,6 +241,9 @@ export async function updateCompanySession(const authSession = await getAuthSession(request);if (authSession !== undefined) {+ // Fire-and-forget cache invalidation. If Redis is down, @carbon/kv fails+ // soft and this resolves null — benign: a stale permission cache entry (if+ // any) simply expires on its own TTL, and the session cookie is still returned.await redis.del(getPermissionCacheKey(authSession?.userId!));session.set(SESSION_KEY, {...authSession,diff --git a/packages/auth/src/services/users.server.ts b/packages/auth/src/services/users.server.tsindex a6b039e34d..0696931a8c 100644--- a/packages/auth/src/services/users.server.ts+++ b/packages/auth/src/services/users.server.ts@@ -51,8 +51,14 @@ export async function getUserClaims(userId: string, companyId: string) {// convert rawClaims to permissionsclaims = makePermissionsFromClaims(rawClaims.data as Json[]);- // store claims in redis- await redis.set(getPermissionCacheKey(userId), JSON.stringify(claims));+ // store claims in redis — best-effort. A null/failed write (Redis down,+ // fail-soft via @carbon/kv withResilience) must not abort the in-flight+ // request; we already have the claims from the DB.+ try {+ await redis.set(getPermissionCacheKey(userId), JSON.stringify(claims));+ } catch (e) {+ console.error("Failed to cache claims in redis", e);+ }if (!claims) {throw new Error("Failed to get claims");diff --git a/packages/auth/src/services/verification.server.ts b/packages/auth/src/services/verification.server.tsindex 6cd50c99e2..0d6be9ca69 100644--- a/packages/auth/src/services/verification.server.ts+++ b/packages/auth/src/services/verification.server.ts@@ -46,6 +46,9 @@ export async function verifyEmailCode(email: string, code: string) {try {const storedCode = await redis.get(`verification:${email.toLowerCase()}`);+ // If Redis is down, @carbon/kv fails soft and `storedCode` is null, so we+ // return false. Blocking verification when the code store is unreachable is+ // the expected/acceptable fail-closed behavior — we cannot confirm the code.if (!storedCode || String(storedCode).trim() !== String(code).trim()) {return false;}