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 .changeset/brave-cats-recover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"kitcn": patch
---

## Features

- Add provider-owned Convex authentication recovery after transient token failures.
421 changes: 421 additions & 0 deletions docs/plans/299-convex-auth-recovery.md

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions packages/kitcn/skills/kitcn/references/features/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ All from `kitcn/react`:
| `useMaybeAuth()` | `boolean` | Has token (optimistic, may not be verified) |
| `useIsAuth()` | `boolean` | Server-verified authentication |
| `useAuthGuard()` | `() => boolean` | Guard mutations, returns true if blocked |
| `useConvexAuthRecovery()` | `{ recover, status, error }` | Rebind Convex auth after a transient token failure |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Regenerate the local kitcn skill mirror

This updates the published kitcn skill source, but the generated mirror at .agents/skills/kitcn/references/features/auth.md still lacks the new useConvexAuthRecovery row and recovery section, so repo-local agents will read stale auth guidance until the mirror is regenerated and committed. Please run bun tooling/sync-kitcn-skill.ts or bun install and include the generated diff.

AGENTS.md reference: AGENTS.md:L6-L7

Useful? React with πŸ‘Β / πŸ‘Ž.


### useAuthGuard

Expand Down Expand Up @@ -409,6 +410,28 @@ import { ConvexProviderWithAuth } from 'kitcn/react';
<ConvexProviderWithAuth client={convex} useAuth={useAuthFromConvexDev}>
```

### Convex Auth Recovery

Use recovery only when the outer auth provider remains authenticated but
Convex entered an unauthenticated state after a transient token refresh
failure:

```tsx
import { useConvexAuthRecovery } from 'kitcn/react';

const { error, recover, status } = useConvexAuthRecovery();
await recover();
```

`recover()` replaces the provider-owned auth binding and resolves after Convex
confirms authentication. Concurrent calls share one promise. The default
timeout is 10 seconds; override it with `recover({ timeoutMs })`.

Failures are `ConvexAuthRecoveryError` values with code
`AUTH_PROVIDER_LOADING`, `AUTH_PROVIDER_UNAUTHENTICATED`,
`AUTH_RECOVERY_CANCELLED`, `AUTH_RECOVERY_FAILED`, or
`AUTH_RECOVERY_TIMEOUT`. Never recover an intentional sign-out.

---

## Auth Triggers
Expand Down
89 changes: 88 additions & 1 deletion packages/kitcn/src/auth-client/convex-auth-provider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { act, render, renderHook } from '@testing-library/react';
import { act, render, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import {
decodeJwtExp,
useAuth,
useAuthStore,
useConvexAuthRecovery,
useFetchAccessToken,
} from '../react/auth-store';
import { ConvexAuthProvider } from './convex-auth-provider';
Expand Down Expand Up @@ -31,6 +32,92 @@ describe('ConvexAuthProvider', () => {
}
});

test('recovers Better Auth after a transient token refresh failure', async () => {
const bindings: Array<{
fetchToken: (args: {
forceRefreshToken: boolean;
}) => Promise<string | null>;
onChange: (isAuthenticated: boolean) => void;
}> = [];
const client = {
clearAuth: mock(() => {}),
setAuth: mock(
(
fetchToken: (args: {
forceRefreshToken: boolean;
}) => Promise<string | null>,
onChange: (isAuthenticated: boolean) => void
) => {
bindings.push({ fetchToken, onChange });
}
),
};
const recoveredToken = makeJwt(7200);
const token = mock()
.mockResolvedValueOnce({ data: {} })
.mockResolvedValueOnce({ data: { token: recoveredToken } });
const authClient = {
useSession: () => ({
data: { session: { id: 'session-1' } },
isPending: false,
}),
convex: { token },
getSession: async () => null,
updateSession: () => {},
crossDomain: { oneTimeToken: { verify: async () => ({ data: {} }) } },
};
const wrapper = ({ children }: { children: ReactNode }) => (
<ConvexAuthProvider authClient={authClient as any} client={client as any}>
{children}
</ConvexAuthProvider>
);

let recovery: ReturnType<typeof useConvexAuthRecovery> | undefined;
expect(() => {
renderHook(
() => {
recovery = useConvexAuthRecovery();
},
{ wrapper }
);
}).not.toThrow();

await waitFor(() => {
expect(bindings).toHaveLength(1);
});
let failedToken: string | null = null;
await act(async () => {
failedToken = await bindings[0]!.fetchToken({
forceRefreshToken: true,
});
});
expect(failedToken).toBeNull();
act(() => {
bindings[0]!.onChange(false);
});

let recovered!: Promise<void>;
act(() => {
recovered = recovery!.recover({ timeoutMs: 1_000 });
});
await waitFor(() => {
expect(bindings).toHaveLength(2);
});
let freshToken: string | null = null;
await act(async () => {
freshToken = await bindings[1]!.fetchToken({
forceRefreshToken: false,
});
});
expect(freshToken).toBe(recoveredToken);
act(() => {
bindings[1]!.onChange(true);
});

await expect(recovered).resolves.toBeUndefined();
expect(token).toHaveBeenCalledTimes(2);
});

test('syncs ConvexQueryClient with the auth store before children render', () => {
const client = {
setAuth: () => {},
Expand Down
3 changes: 2 additions & 1 deletion packages/kitcn/src/auth-client/convex-auth-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import type { AuthTokenFetcher } from 'convex/browser';
import type { ConvexReactClient } from 'convex/react';
import { ConvexProviderWithAuth, useConvexAuth } from 'convex/react';
import { useConvexAuth } from 'convex/react';
import type { ReactNode } from 'react';
import { useCallback, useEffect, useMemo, useRef } from 'react';

Expand All @@ -21,6 +21,7 @@ import {
AUTH_SESSION_SYNC_GRACE_MS,
AuthProvider,
type AuthStore,
ConvexProviderWithAuth,
decodeJwtExp,
FetchAccessTokenContext,
isSessionSyncGraceActive,
Expand Down
Loading
Loading