Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(ai-gateway): stop denying locked or stale-clerk-id accounts as not in good standing (#5918)

Ansh Grovere8732d64bb54
diff --git a/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts b/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts
index 9aece3cce..483bcd39a 100644
--- a/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts
+++ b/apps/screenpipe-app-tauri/lib/chat/__tests__/provider-errors.test.ts
@@ -39,6 +39,20 @@ describe("provider error copy", () => {
expect(presentation?.message).not.toContain("finish_reason");
});
+ it("maps an account-standing denial to friendly, non-retryable copy", () => {
+ const raw = 'Error: 403 "{\\"error\\":\\"account_not_in_good_standing\\",\\"message\\":\\"This screenpipe account is not in good standing.\\",\\"reason\\":\\"banned\\"}"';
+ const presentation = buildProviderErrorPresentation(raw, {
+ provider: "screenpipe-cloud",
+ model: "auto",
+ });
+
+ expect(presentation).toMatchObject({ kind: "provider", retryable: false });
+ expect(presentation?.message).toContain("not in good standing");
+ expect(presentation?.message).toContain("contact screenpipe support");
+ expect(presentation?.message).not.toContain("403");
+ expect(presentation?.message).not.toContain("account_not_in_good_standing");
+ });
+
it("does not classify an ordinary provider error as a safety refusal", () => {
expect(SafetyRefusalError.from("Connection error.")).toBeNull();
expect(
diff --git a/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts b/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts
index 1ca73fe94..0166a8941 100644
--- a/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts
+++ b/apps/screenpipe-app-tauri/lib/chat/provider-errors.ts
@@ -160,6 +160,17 @@ export function buildContextOverflowMessage(errorStr = ""): string {
return "This chat is too long for the selected model. Match Settings → AI → Advanced → model context tokens to the provider's context window. Start a new chat or remove large attachments/screenshots, then retry.";
}
+export function buildAccountStandingMessage(errorStr: string): string | null {
+ const normalized = errorStr.toLowerCase();
+ if (
+ !normalized.includes("account_not_in_good_standing") &&
+ !normalized.includes("not in good standing")
+ ) {
+ return null;
+ }
+ return "screenpipe cloud AI is blocked for this account — it's flagged as not in good standing. Signing out and back in can refresh your account status. If you believe this is a mistake, contact screenpipe support. Local models and your own provider keys keep working in Settings → AI.";
+}
+
export function buildChatGptAccountIdMessage(): string {
return "Your ChatGPT sign-in doesn't include chat access: the login token has no ChatGPT account id. This usually means an Enterprise/Business workspace where the admin hasn't enabled Codex local app access. Reconnect ChatGPT in Settings → AI with a personal account, or ask your workspace admin to enable access.";
}
@@ -257,6 +268,13 @@ export function buildProviderErrorPresentation(
};
}
+ // Retrying an account-standing denial resends the same doomed request, so
+ // don't offer the retry affordance the generic provider path gets.
+ const standingMessage = buildAccountStandingMessage(errorStr);
+ if (standingMessage) {
+ return { kind: "provider", message: standingMessage, retryable: false };
+ }
+
const message = buildGenericProviderErrorMessage(errorStr, preset);
return message ? { kind: "provider", message, retryable: true } : null;
}
diff --git a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
index 1d2d502e5..827b24edd 100644
--- a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
+++ b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
@@ -175,6 +175,13 @@ fn replace_with_merged_audio(
/// Returns both the number of chunks processed and whether the candidate query
/// hit its cap, which tells the scheduler to keep draining without a 120s nap.
#[allow(clippy::too_many_arguments)]
+/// The gateway rejected the account itself (banned/deleted), not this batch.
+/// Every retry with the same credentials is guaranteed to fail identically.
+fn is_account_standing_error(error: &anyhow::Error) -> bool {
+ let message = error.to_string();
+ message.contains("account_not_in_good_standing") || message.contains("not in good standing")
+}
+
pub async fn reconcile_untranscribed(
db: &DatabaseManager,
transcription_engine: &TranscriptionEngine,
@@ -399,6 +406,18 @@ pub async fn reconcile_untranscribed(
if let Some(metrics) = &metrics {
metrics.record_transcription_error();
}
+ // An account-standing denial fails every batch in this sweep the
+ // same way; continuing would hammer the API once per batch (seen
+ // in the wild: a 403-denied account produced a request every
+ // ~350ms). Stop the sweep and leave the chunks pending — they
+ // are the user's audio, not bad data — so the next sweep probes
+ // once and everything transcribes when the account recovers.
+ if is_account_standing_error(&e) {
+ warn!(
+ "reconciliation: transcription API rejected this account; pausing sweep until the next cycle"
+ );
+ break;
+ }
// Bump attempts on every chunk in the batch. Once a chunk has
// failed MAX_TRANSCRIPTION_ATTEMPTS times in a row the outcome
// helper flips it to status='failed' and it stops being picked.
@@ -1741,6 +1760,20 @@ mod tests {
p.to_string_lossy().to_string()
}
+ #[test]
+ fn account_standing_errors_are_recognized_and_transient_errors_are_not() {
+ let denied = anyhow::anyhow!(
+ "Deepgram API error (HTTP 403 Forbidden): {{\"error\":\"{{\\\"error\\\":\\\"account_not_in_good_standing\\\",\\\"message\\\":\\\"This screenpipe account is not in good standing.\\\"}}\"}}"
+ );
+ assert!(is_account_standing_error(&denied));
+ assert!(!is_account_standing_error(&anyhow::anyhow!(
+ "Deepgram API error (HTTP 429 Too Many Requests): slow down"
+ )));
+ assert!(!is_account_standing_error(&anyhow::anyhow!(
+ "connection reset by peer"
+ )));
+ }
+
#[test]
fn pending_chunk_filename_is_stable_and_unique() {
let a = "/data/Display 3 (output)_2026-02-27_23-15-38.mp4";
diff --git a/packages/ai-gateway/src/test/clerk-standing.unit.test.ts b/packages/ai-gateway/src/test/clerk-standing.unit.test.ts
index e6c5bc803..5b3eda3be 100644
--- a/packages/ai-gateway/src/test/clerk-standing.unit.test.ts
+++ b/packages/ai-gateway/src/test/clerk-standing.unit.test.ts
@@ -77,9 +77,8 @@ describe('lookupClerkStanding', () => {
it.each([
['banned', { banned: true, locked: false }],
- ['locked', { banned: false, locked: true }],
['banned and locked', { banned: true, locked: true }],
- ] as const)('returns a bounded DENIED decision for a %s user', async (
+ ] as const)('returns a bounded DENIED decision with a banned reason for a %s user', async (
_label,
overrides,
) => {
@@ -92,6 +91,23 @@ describe('lookupClerkStanding', () => {
version: CLERK_STANDING_RECORD_VERSION,
userId: USER_ID,
standing: 'denied',
+ reason: 'banned',
+ checkedAt: CHECKED_AT,
+ revalidateAfter: standingRevalidateAfter(USER_ID, CHECKED_AT),
+ });
+ });
+
+ it('keeps a locked (sign-in throttled) user in GOOD standing', async () => {
+ const record = await lookupClerkStanding(env(), USER_ID, {
+ fetchImpl: mock(async () =>
+ Response.json(clerkUser({ banned: false, locked: true }))) as typeof fetch,
+ now: CHECKED_AT,
+ });
+
+ expect(record).toEqual({
+ version: CLERK_STANDING_RECORD_VERSION,
+ userId: USER_ID,
+ standing: 'good',
checkedAt: CHECKED_AT,
revalidateAfter: standingRevalidateAfter(USER_ID, CHECKED_AT),
});
@@ -107,6 +123,7 @@ describe('lookupClerkStanding', () => {
version: CLERK_STANDING_RECORD_VERSION,
userId: USER_ID,
standing: 'denied',
+ reason: 'deleted',
checkedAt: CHECKED_AT,
revalidateAfter: standingRevalidateAfter(USER_ID, CHECKED_AT),
});
@@ -211,11 +228,17 @@ describe('isClerkStandingRecord', () => {
revalidateAfter: CHECKED_AT + STANDING_MIN_TTL_MS,
};
- it('accepts only complete v3 records bound to the expected Clerk subject', () => {
+ it('accepts only complete v4 records bound to the expected Clerk subject', () => {
expect(isClerkStandingRecord(goodRecord, USER_ID)).toBe(true);
expect(isClerkStandingRecord({
...goodRecord,
standing: 'denied',
+ reason: 'banned',
+ }, USER_ID)).toBe(true);
+ expect(isClerkStandingRecord({
+ ...goodRecord,
+ standing: 'denied',
+ reason: 'deleted',
}, USER_ID)).toBe(true);
expect(isClerkStandingRecord(goodRecord, 'user_different')).toBe(false);
expect(isClerkStandingRecord({ ...goodRecord, revalidateAfter: CHECKED_AT }, USER_ID)).toBe(false);
@@ -226,14 +249,32 @@ describe('isClerkStandingRecord', () => {
expect(isClerkStandingRecord({
...goodRecord,
standing: 'denied',
+ reason: 'banned',
revalidateAfter: null,
}, USER_ID)).toBe(false);
});
+ it('rejects denials without a valid reason and good records carrying one', () => {
+ expect(isClerkStandingRecord({
+ ...goodRecord,
+ standing: 'denied',
+ }, USER_ID)).toBe(false);
+ expect(isClerkStandingRecord({
+ ...goodRecord,
+ standing: 'denied',
+ reason: 'locked',
+ }, USER_ID)).toBe(false);
+ expect(isClerkStandingRecord({
+ ...goodRecord,
+ reason: 'banned',
+ }, USER_ID)).toBe(false);
+ });
+
it.each([
['legacy boolean', false],
['unversioned allowed record', { userId: USER_ID, standing: 'good' }],
['v2 record', { ...goodRecord, version: 2 }],
+ ['v3 record (pre reason, locked-denies era)', { ...goodRecord, version: 3 }],
] as const)('rejects %s so it must be authoritatively rechecked', (_label, value) => {
expect(isClerkStandingRecord(value, USER_ID)).toBe(false);
});
diff --git a/packages/ai-gateway/src/test/free-chat-route.unit.test.ts b/packages/ai-gateway/src/test/free-chat-route.unit.test.ts
index f47e00e36..37195d447 100644
--- a/packages/ai-gateway/src/test/free-chat-route.unit.test.ts
+++ b/packages/ai-gateway/src/test/free-chat-route.unit.test.ts
@@ -112,6 +112,7 @@ describe('/v1/chat/completions free-plan route policy', () => {
rateLimiterFetch.mockImplementation(async () => Response.json({
allowed: false,
standing: 'denied',
+ standing_reason: 'banned',
}));
return authFetch;
}
diff --git a/packages/ai-gateway/src/test/rate-limiter.unit.test.ts b/packages/ai-gateway/src/test/rate-limiter.unit.test.ts
index 34f2e0ee3..766f37cdd 100644
--- a/packages/ai-gateway/src/test/rate-limiter.unit.test.ts
+++ b/packages/ai-gateway/src/test/rate-limiter.unit.test.ts
@@ -128,6 +128,17 @@ function clerkAuth(userId: string): AuthResult {
...auth('subscribed', 'caller-device'),
userId,
clerkUserId: userId,
+ clerkUserIdVerified: true,
+ };
+}
+
+/** Caller whose clerk id came from the website user row, not a verified Clerk JWT. */
+function dbSourcedClerkAuth(userId: string): AuthResult {
+ return {
+ ...auth('subscribed', 'caller-device'),
+ userId,
+ clerkUserId: userId,
+ clerkUserIdVerified: false,
};
}
@@ -152,6 +163,7 @@ function standingRecord(
version: CLERK_STANDING_RECORD_VERSION,
userId,
standing,
+ ...(standing === 'denied' ? { reason: 'banned' as const } : {}),
checkedAt: clockNow,
revalidateAfter: standingRevalidateAfter(userId, clockNow),
...overrides,
@@ -346,11 +358,11 @@ describe('checkRateLimit — freeRpm clamped to never be below paid rpm', () =>
describe('Clerk GOOD-STANDING admission', () => {
it.each([
- ['historically banned', (userId: string) => Response.json(clerkUser(userId, { banned: true }))],
- ['historically locked', (userId: string) => Response.json(clerkUser(userId, { locked: true }))],
- ['historically deleted', (_userId: string) => new Response('not found', { status: 404 })],
- ] as const)('denies a %s user on the first request and persists the decision', async (
+ ['historically banned', 'banned', (userId: string) => Response.json(clerkUser(userId, { banned: true }))],
+ ['historically deleted', 'deleted', (_userId: string) => new Response('not found', { status: 404 })],
+ ] as const)('denies a %s verified user on the first request and persists the decision', async (
label,
+ reason,
clerkResponse,
) => {
const userId = `user_${label.replace(/\W/g, '_')}`;
@@ -369,10 +381,65 @@ describe('Clerk GOOD-STANDING admission', () => {
version: CLERK_STANDING_RECORD_VERSION,
userId,
standing: 'denied',
+ reason,
revalidateAfter: standingRevalidateAfter(userId, clockNow),
});
});
+ it('admits a locked user — a sign-in lockout is not an account revocation', async () => {
+ const userId = 'user_locked_but_valid';
+ const fetchMock = mock(async () =>
+ Response.json(clerkUser(userId, { locked: true }))) as typeof fetch;
+ globalThis.fetch = fetchMock;
+ const harness = makeHarness();
+
+ const result = await checkRateLimit(chatReq(), harness.env, clerkAuth(userId));
+
+ expect(result.allowed).toBe(true);
+ expect(harness.readStorage<ClerkStandingRecord>(userId, CLERK_STANDING_STORAGE_KEY))
+ .toMatchObject({ standing: 'good' });
+ });
+
+ it('surfaces the denial reason in the 403 body for supportability', async () => {
+ const userId = 'user_banned_reason_body';
+ globalThis.fetch = mock(async () =>
+ Response.json(clerkUser(userId, { banned: true }))) as typeof fetch;
+ const harness = makeHarness();
+
+ const result = await checkRateLimit(chatReq(), harness.env, clerkAuth(userId));
+
+ const outer = await result.response!.json() as { error: string };
+ expect(JSON.parse(outer.error)).toMatchObject({
+ error: 'account_not_in_good_standing',
+ reason: 'banned',
+ });
+ });
+
+ it('answers retryable-unavailable, not a ban, when a DB-sourced clerk id 404s', async () => {
+ const userId = 'user_stale_db_clerk_id';
+ const fetchMock = mock(async () => new Response('not found', { status: 404 })) as typeof fetch;
+ globalThis.fetch = fetchMock;
+ const harness = makeHarness();
+
+ const result = await checkRateLimit(chatReq(), harness.env, dbSourcedClerkAuth(userId));
+
+ expect(result.allowed).toBe(false);
+ expect(result.response?.status).toBe(503);
+ expect(await responseErrorCode(result.response!)).toBe('account_status_unavailable');
+ });
+
+ it('still denies a banned user whose clerk id came from the website user row', async () => {
+ const userId = 'user_banned_db_sourced';
+ globalThis.fetch = mock(async () =>
+ Response.json(clerkUser(userId, { banned: true }))) as typeof fetch;
+ const harness = makeHarness();
+
+ const result = await checkRateLimit(chatReq(), harness.env, dbSourcedClerkAuth(userId));
+
+ expect(result.response?.status).toBe(403);
+ expect(await responseErrorCode(result.response!)).toBe('account_not_in_good_standing');
+ });
+
it('caches a positive decision and reloads it after Durable Object eviction', async () => {
const userId = 'user_good_cached';
const fetchMock = mock(async () => Response.json(clerkUser(userId))) as typeof fetch;
@@ -423,7 +490,7 @@ describe('Clerk GOOD-STANDING admission', () => {
legacyRecord,
) => {
const userId = 'user_schema_migration';
- const fetchMock = mock(async () => Response.json(clerkUser(userId, { locked: true }))) as typeof fetch;
+ const fetchMock = mock(async () => Response.json(clerkUser(userId, { banned: true }))) as typeof fetch;
globalThis.fetch = fetchMock;
const harness = makeHarness();
harness.seedStorage(userId, CLERK_STANDING_STORAGE_KEY, legacyRecord);
@@ -443,7 +510,7 @@ describe('Clerk GOOD-STANDING admission', () => {
lookup++;
return lookup === 1
? Response.json(clerkUser(userId))
- : Response.json(clerkUser(userId, { locked: true }));
+ : Response.json(clerkUser(userId, { banned: true }));
}) as typeof fetch;
globalThis.fetch = fetchMock;
const harness = makeHarness({ LIMIT_SUBSCRIBED_RPM: '1' });
diff --git a/packages/ai-gateway/src/types.ts b/packages/ai-gateway/src/types.ts
index 9abd61357..2afeffae8 100644
--- a/packages/ai-gateway/src/types.ts
+++ b/packages/ai-gateway/src/types.ts
@@ -304,6 +304,12 @@ export interface AuthResult {
userId?: string;
/** Clerk subject proven by Clerk JWT verification or an authenticated /api/user response. */
clerkUserId?: string;
+ /**
+ * True when `clerkUserId` was proven by verifying a Clerk JWT in this
+ * request; false/absent when it was read from the website's user row, where
+ * a stale value must not be treated as proof the Clerk account is gone.
+ */
+ clerkUserIdVerified?: boolean;
/** True only for the dedicated backend service bearer. */
service?: boolean;
error?: string;
diff --git a/packages/ai-gateway/src/utils/auth.test.ts b/packages/ai-gateway/src/utils/auth.test.ts
index 953d62261..68553eeda 100644
--- a/packages/ai-gateway/src/utils/auth.test.ts
+++ b/packages/ai-gateway/src/utils/auth.test.ts
@@ -217,6 +217,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_verified',
userId: 'user_verified',
clerkUserId: 'user_verified',
+ clerkUserIdVerified: true,
} as const;
expect(await validateAuth(requestFor('eyJ.verified.clerk.1'), env)).toEqual(expected);
@@ -251,6 +252,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_refunded',
userId: 'user_refunded',
clerkUserId: 'user_refunded',
+ clerkUserIdVerified: true,
});
});
@@ -287,6 +289,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_basic',
userId: 'user_basic',
clerkUserId: 'user_basic',
+ clerkUserIdVerified: true,
} as const;
expect(await validateAuth(requestFor('eyJ.basic.clerk.1'), env)).toEqual(expected);
@@ -322,6 +325,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_lifetime',
userId: 'user_lifetime',
clerkUserId: 'user_lifetime',
+ clerkUserIdVerified: true,
});
expect(fetchMock).toHaveBeenCalledTimes(1);
});
@@ -353,6 +357,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_unknown',
userId: 'user_unknown',
clerkUserId: 'user_unknown',
+ clerkUserIdVerified: true,
} as const;
expect(await validateAuth(requestFor('eyJ.unknown.clerk.1'), env)).toEqual(expected);
@@ -371,6 +376,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_retry',
userId: 'user_retry',
clerkUserId: 'user_retry',
+ clerkUserIdVerified: true,
} as const;
expect(await validateAuth(requestFor('eyJ.retry.clerk.1'), env)).toEqual(expected);
@@ -411,6 +417,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_concurrent',
userId: 'user_concurrent',
clerkUserId: 'user_concurrent',
+ clerkUserIdVerified: true,
},
{
isValid: true,
@@ -419,6 +426,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_concurrent',
userId: 'user_concurrent',
clerkUserId: 'user_concurrent',
+ clerkUserIdVerified: true,
},
]);
expect(verifyTokenMock).toHaveBeenCalledTimes(2);
@@ -457,6 +465,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_subscribed',
userId: 'user_subscribed',
clerkUserId: 'user_subscribed',
+ clerkUserIdVerified: true,
});
});
@@ -482,6 +491,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_trial',
userId: 'user_trial',
clerkUserId: 'user_trial',
+ clerkUserIdVerified: true,
});
});
@@ -513,6 +523,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: clerkId,
userId: clerkId,
clerkUserId: clerkId,
+ clerkUserIdVerified: true,
});
}
});
@@ -544,6 +555,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: clerkId,
userId: clerkId,
clerkUserId: clerkId,
+ clerkUserIdVerified: true,
});
}
});
@@ -578,6 +590,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: clerkId,
userId: clerkId,
clerkUserId: clerkId,
+ clerkUserIdVerified: true,
} as const;
expect(await validateAuth(requestFor(`eyJ.bad-billing.${suffix}.1`), env)).toEqual(expected);
expect(await validateAuth(requestFor(`eyJ.bad-billing.${suffix}.2`), env)).toEqual(expected);
@@ -610,6 +623,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_verified_caller',
userId: 'user_verified_caller',
clerkUserId: 'user_verified_caller',
+ clerkUserIdVerified: true,
} as const;
expect(await validateAuth(requestFor('eyJ.verified.mismatch.1'), env)).toEqual(expected);
@@ -640,6 +654,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_verified_caller',
userId: 'user_verified_caller',
clerkUserId: 'user_verified_caller',
+ clerkUserIdVerified: true,
});
});
@@ -665,6 +680,7 @@ describe('validateAuth — verified identities only', () => {
deviceId: 'user_legacy',
userId: 'user_legacy',
clerkUserId: 'user_legacy',
+ clerkUserIdVerified: false,
});
});
diff --git a/packages/ai-gateway/src/utils/auth.ts b/packages/ai-gateway/src/utils/auth.ts
index 4b91e1ff6..d8fa979da 100644
--- a/packages/ai-gateway/src/utils/auth.ts
+++ b/packages/ai-gateway/src/utils/auth.ts
@@ -120,6 +120,7 @@ export async function validateAuth(request: Request, env: Env): Promise<AuthResu
deviceId: resolvedUserId,
userId: resolvedUserId,
clerkUserId: resolvedUserId,
+ clerkUserIdVerified: true,
};
}
@@ -137,8 +138,10 @@ export async function validateAuth(request: Request, env: Env): Promise<AuthResu
...usageTierField(screenpipeUser.accountPlan ?? 'unknown', 'subscribed'),
deviceId: resolvedUserId,
userId: screenpipeUser.userId,
+ // clerk_id here comes from the website's user row, not a verified Clerk
+ // JWT, so a Clerk 404 on it may just mean the row is stale.
...(screenpipeUser.clerkUserId
- ? { clerkUserId: screenpipeUser.clerkUserId }
+ ? { clerkUserId: screenpipeUser.clerkUserId, clerkUserIdVerified: false }
: {}),
};
}
@@ -151,7 +154,7 @@ export async function validateAuth(request: Request, env: Env): Promise<AuthResu
deviceId: resolvedUserId,
userId: screenpipeUser.userId,
...(screenpipeUser.clerkUserId
- ? { clerkUserId: screenpipeUser.clerkUserId }
+ ? { clerkUserId: screenpipeUser.clerkUserId, clerkUserIdVerified: false }
: {}),
};
}
diff --git a/packages/ai-gateway/src/utils/clerk-standing.ts b/packages/ai-gateway/src/utils/clerk-standing.ts
index 564286996..224c33362 100644
--- a/packages/ai-gateway/src/utils/clerk-standing.ts
+++ b/packages/ai-gateway/src/utils/clerk-standing.ts
@@ -4,7 +4,11 @@
import type { Env } from '../types';
-export const CLERK_STANDING_RECORD_VERSION = 3 as const;
+// v4: `locked` no longer denies (it is Clerk's temporary sign-in throttle, not a
+// revocation) and denied records carry a `reason`. Bumping the version discards
+// every cached v3 denial, so users wrongly denied for a lockout recover on the
+// next request instead of after the cache TTL.
+export const CLERK_STANDING_RECORD_VERSION = 4 as const;
export const CLERK_STANDING_STORAGE_KEY = 'clerk-user-standing';
export const CLERK_STANDING_LOOKUP_TIMEOUT_MS = 3_000;
@@ -15,10 +19,16 @@ const CLERK_USER_ID = /^user_[A-Za-z0-9_-]+$/;
export type ClerkStanding = 'good' | 'denied';
+// 'banned' is an explicit operator decision and is enforced unconditionally.
+// 'deleted' (Clerk 404) is only authoritative when the checked user id came
+// from a verified Clerk JWT; a DB-sourced id may simply be stale.
+export type ClerkStandingDenialReason = 'banned' | 'deleted';
+
export interface ClerkStandingRecord {
version: typeof CLERK_STANDING_RECORD_VERSION;
userId: string;
standing: ClerkStanding;
+ reason?: ClerkStandingDenialReason;
checkedAt: number;
revalidateAfter: number;
}
@@ -66,6 +76,11 @@ export function isClerkStandingRecord(
) {
return false;
}
+ if (record.standing === 'denied') {
+ if (record.reason !== 'banned' && record.reason !== 'deleted') return false;
+ } else if (record.reason !== undefined) {
+ return false;
+ }
return Number.isSafeInteger(record.revalidateAfter) &&
(record.revalidateAfter ?? -1) > (record.checkedAt ?? Number.MAX_SAFE_INTEGER) &&
(record.revalidateAfter ?? Number.MAX_SAFE_INTEGER) <=
@@ -136,6 +151,7 @@ export async function lookupClerkStanding(
version: CLERK_STANDING_RECORD_VERSION,
userId,
standing: 'denied',
+ reason: 'deleted',
checkedAt,
revalidateAfter: standingRevalidateAfter(userId, checkedAt),
};
@@ -182,11 +198,15 @@ export async function lookupClerkStanding(
throw new ClerkStandingLookupError('Clerk standing lookup returned an invalid user');
}
- const standing: ClerkStanding = !user.banned && !user.locked ? 'good' : 'denied';
+ // `locked` is Clerk's automatic throttle after failed sign-in attempts and
+ // clears on its own; a locked user still holds a valid token and keeps
+ // hosted access. Only an explicit ban revokes standing.
+ const standing: ClerkStanding = user.banned ? 'denied' : 'good';
return {
version: CLERK_STANDING_RECORD_VERSION,
userId,
standing,
+ ...(standing === 'denied' ? { reason: 'banned' as const } : {}),
checkedAt,
revalidateAfter: standingRevalidateAfter(userId, checkedAt),
};
diff --git a/packages/ai-gateway/src/utils/rate-limiter.ts b/packages/ai-gateway/src/utils/rate-limiter.ts
index 88977123d..960860fb2 100644
--- a/packages/ai-gateway/src/utils/rate-limiter.ts
+++ b/packages/ai-gateway/src/utils/rate-limiter.ts
@@ -191,6 +191,7 @@ export class RateLimiter {
return Response.json({
allowed: false,
standing: 'denied',
+ standing_reason: record.reason,
});
}
} catch (error) {
@@ -349,6 +350,7 @@ export async function checkRateLimit(
let rateLimitData: {
allowed?: unknown;
standing?: unknown;
+ standing_reason?: unknown;
remaining: number;
reset_in: number;
tier: string;
@@ -362,11 +364,24 @@ export async function checkRateLimit(
}
if (standingRequired && rateLimitData.standing === 'denied') {
+ const reason = rateLimitData.standing_reason;
+ if (reason !== 'banned' && reason !== 'deleted') {
+ console.error('rate limiter returned a denial without a valid reason');
+ return accountStatusUnavailable();
+ }
+ // A Clerk 404 proves deletion only for a subject verified from a Clerk JWT
+ // in this request. When the id came from the website's user row it may be
+ // stale, so answer retryable-unavailable instead of a permanent ban.
+ if (reason === 'deleted' && authResult?.clerkUserIdVerified !== true) {
+ console.error('clerk standing 404 for db-sourced clerk id', clerkUserId);
+ return accountStatusUnavailable();
+ }
return {
allowed: false,
response: createErrorResponse(403, JSON.stringify({
error: 'account_not_in_good_standing',
message: 'This screenpipe account is not in good standing.',
+ reason,
})),
};
}