Skip to content

Add ConvexProviderWithAuthKit for WorkOS AuthKit integration #55

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
18 changes: 18 additions & 0 deletions api-extractor-configs/react-authkit-api-extractor.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": "./api-extractor-base.json",
"mainEntryPointFilePath": "<projectFolder>/dist/types/react-authkit/index.d.ts",
"dtsRollup": {
"untrimmedFilePath": "<projectFolder>/dist/types/react-authkit/react-authkit-internal.d.ts",
"publicTrimmedFilePath": "<projectFolder>/dist/types/react-authkit/react-authkit.d.ts"
},
/**
* Enable the apiReport but use the same reportFolder and tempFolder to make it a no-op.
* This way forgotten exports are a warning instead of an error.
*/
"apiReport": {
"enabled": true,
"reportFileName": "react-authkit-tmp.api.md",
"reportFolder": "temp",
"reportTempFolder": "temp"
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@
"@types/serve-handler": "~6.1.4",
"@types/ws": "^8.5.13",
"@vitest/eslint-plugin": "~1.3.0",
"@workos-inc/authkit-react": "^0.11.0",
"adm-zip": "^0.5.10",
"bufferutil": "^4.0.7",
"chalk": "5",
Expand Down
5 changes: 5 additions & 0 deletions react-authkit/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"main": "../dist/cjs/react-authkit/index.js",
"module": "../dist/esm/react-authkit/index.js",
"types": "../dist/cjs-types/react-authkit/index.d.ts"
}
18 changes: 18 additions & 0 deletions src/react-authkit/ConvexProviderWithAuthKit.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @vitest-environment custom-vitest-environment.ts
*/
import { test } from "vitest";
import React from "react";
import { ConvexProviderWithAuthKit } from "./ConvexProviderWithAuthKit.js";
import { ConvexReactClient } from "../react/index.js";
import { useAuth } from "@workos-inc/authkit-react";

test("Helpers are valid children", () => {
const convex = new ConvexReactClient("https://localhost:3001");

const _ = (
<ConvexProviderWithAuthKit client={convex} useAuth={useAuth}>
Hello world
</ConvexProviderWithAuthKit>
);
});
71 changes: 71 additions & 0 deletions src/react-authkit/ConvexProviderWithAuthKit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React from "react";

import { ReactNode, useCallback, useMemo } from "react";
import { AuthTokenFetcher } from "../browser/sync/client.js";
import { ConvexProviderWithAuth } from "../react/ConvexAuthState.js";

type IConvexReactClient = {
setAuth(fetchToken: AuthTokenFetcher): void;
clearAuth(): void;
};

// Modified to match WorkOS's auth hook structure
type UseAuth = () => {
isLoading: boolean;
user: any | null;
getAccessToken: () => Promise<string | null>;
};

/**
* A wrapper React component which provides a {@link react.ConvexReactClient}
* authenticated with WorkOS AuthKit.
*
* It must be wrapped by a configured `AuthKitProvider`, from
* `@workos-inc/authkit-react`.
*
* @public
*/
export function ConvexProviderWithAuthKit({
children,
client,
useAuth,
}: {
children: ReactNode;
client: IConvexReactClient;
useAuth: UseAuth;
}) {
const useAuthFromWorkOS = useUseAuthFromAuthKit(useAuth);
return (
<ConvexProviderWithAuth client={client} useAuth={useAuthFromWorkOS}>
{children}
</ConvexProviderWithAuth>
);
}

function useUseAuthFromAuthKit(useAuth: UseAuth) {
return useMemo(
() =>
function useAuthFromWorkOS() {
const { isLoading, user, getAccessToken } = useAuth();

const fetchAccessToken = useCallback(async () => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

@nicknisi since this fetchAccessToken can't actually force a refreshed token this is breaking the state machine, looking into whether we can relax this or we really want to expect a refreshed token

Copy link
Collaborator

Choose a reason for hiding this comment

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

I see that client.getAccessToken() has a forceRefresh, but agree that this is unnecessary if we can trust the AuthKit client to always have fresh-enough auth. Alternately we can build a new interface that allows WorkOS to tell us when a token has been refreshed.

The time the Convex client calls fetchToken with forceRefreshToken: true are

  1. the server says the previous token has expired, so before we throw an error on the client we're getting a new token
  2. the token has an expiration time that is two seconds (configurable, 2s is the default) away
  3. the client is just coming online and just sent in the cached token, now we want a fresh token so it will have the full expiration time on it (we could calculate instead of re-requesting if we trusted the client not to have clock skew)

In case (3), if the token returned is not different than the previous token, the Convex client gives up on automated refreshing. This is the only behavior that needs to be changed, but in order to make other changes to the JWT instantly reactive (the user changes orgs, changes their, name, etc.).

Also I want to look into whether we're properly reactive to changes in the JWT, which are intended to be communicated by the identity of fetchToken changing (a new fetchToken is interpreted to mean it should be called again)

Just making a note, will get back to this later.

try {
const token = await getAccessToken();
return token;
} catch {
return null;
}
}, [getAccessToken]);

return useMemo(
() => ({
isLoading,
isAuthenticated: !!user,
fetchAccessToken,
}),
[isLoading, user, fetchAccessToken],
);
},
[useAuth],
);
}
6 changes: 6 additions & 0 deletions src/react-authkit/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/**
* React login component for use with WorkOS AuthKit
*
* @module
*/
export { ConvexProviderWithAuthKit } from "./ConvexProviderWithAuthKit.js";