refactor(auth): migrate to new Supabase JWT Signing keys (#303)
* refactor(auth): replace Supabase `User` type with new `JWTUserData` type across the codebase - Replaced usage of Supabase's `User` type with the newly defined `JWTUserData` type for better type mapping and alignment with JWT claims. - Refactored session-related components and hooks (`useUser`, `requireUser`) to use the updated user structure. - Updated Supabase client keys to use `publicKey` instead of `anonKey`. - Adjusted multi-factor authentication logic and components to use `aal` and additional properties. - Applied consistent naming for Supabase secret key functions. - Incremented version to 2.12.0. - Introduced a new `deprecated` property in the `EnvVariableModel` type to handle deprecated environment variables. - Updated the `EnvList` component to display a warning badge for deprecated variables, including reason and alternative suggestions. - Enhanced filtering logic to allow users to toggle the visibility of deprecated variables. - Added new deprecated variables for Supabase keys with appropriate reasons and alternatives. - Added support for filtering deprecated environment variables in the `FilterSwitcher` component. - Updated the `Summary` component to display a badge for the count of deprecated variables. - Introduced a button to filter and display only deprecated variables. - Adjusted filtering logic to include deprecated variables in the overall state management. add BILLING_MODE configuration to environment variables - Introduced a new environment variable `BILLING_MODE` to configure billing options for the application. - The variable supports two values: `subscription` and `one-time`. - Marked as deprecated with a reason indicating that this configuration is no longer required, as billing mode is now automatically determined. - Added validation logic for the new variable to ensure correct value parsing.
This commit is contained in:
committed by
GitHub
parent
da8a3a903d
commit
9104ce9a2c
@@ -18,7 +18,8 @@
|
||||
"./require-user": "./src/require-user.ts",
|
||||
"./hooks/*": "./src/hooks/*.ts",
|
||||
"./database": "./src/database.types.ts",
|
||||
"./auth": "./src/auth.ts"
|
||||
"./auth": "./src/auth.ts",
|
||||
"./types": "./src/types.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@kit/eslint-config": "workspace:*",
|
||||
|
||||
@@ -10,5 +10,5 @@ import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
||||
export function getSupabaseBrowserClient<GenericSchema = Database>() {
|
||||
const keys = getSupabaseClientKeys();
|
||||
|
||||
return createBrowserClient<GenericSchema>(keys.url, keys.anonKey);
|
||||
return createBrowserClient<GenericSchema>(keys.url, keys.publicKey);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export function createMiddlewareClient<GenericSchema = Database>(
|
||||
) {
|
||||
const keys = getSupabaseClientKeys();
|
||||
|
||||
return createServerClient<GenericSchema>(keys.url, keys.anonKey, {
|
||||
return createServerClient<GenericSchema>(keys.url, keys.publicKey, {
|
||||
cookies: {
|
||||
getAll() {
|
||||
return request.cookies.getAll();
|
||||
|
||||
@@ -4,9 +4,9 @@ import { createClient } from '@supabase/supabase-js';
|
||||
|
||||
import { Database } from '../database.types';
|
||||
import {
|
||||
getServiceRoleKey,
|
||||
getSupabaseSecretKey,
|
||||
warnServiceRoleKeyUsage,
|
||||
} from '../get-service-role-key';
|
||||
} from '../get-secret-key';
|
||||
import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
||||
|
||||
/**
|
||||
@@ -17,8 +17,9 @@ export function getSupabaseServerAdminClient<GenericSchema = Database>() {
|
||||
warnServiceRoleKeyUsage();
|
||||
|
||||
const url = getSupabaseClientKeys().url;
|
||||
const secretKey = getSupabaseSecretKey();
|
||||
|
||||
return createClient<GenericSchema>(url, getServiceRoleKey(), {
|
||||
return createClient<GenericSchema>(url, secretKey, {
|
||||
auth: {
|
||||
persistSession: false,
|
||||
detectSessionInUrl: false,
|
||||
|
||||
@@ -14,7 +14,7 @@ import { getSupabaseClientKeys } from '../get-supabase-client-keys';
|
||||
export function getSupabaseServerClient<GenericSchema = Database>() {
|
||||
const keys = getSupabaseClientKeys();
|
||||
|
||||
return createServerClient<GenericSchema>(keys.url, keys.anonKey, {
|
||||
return createServerClient<GenericSchema>(keys.url, keys.publicKey, {
|
||||
cookies: {
|
||||
async getAll() {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
@@ -3,14 +3,14 @@ import 'server-only';
|
||||
import { z } from 'zod';
|
||||
|
||||
const message =
|
||||
'Invalid Supabase Service Role Key. Please add the environment variable SUPABASE_SERVICE_ROLE_KEY.';
|
||||
'Invalid Supabase Secret Key. Please add the environment variable SUPABASE_SECRET_KEY or SUPABASE_SERVICE_ROLE_KEY.';
|
||||
|
||||
/**
|
||||
* @name getServiceRoleKey
|
||||
* @name getSupabaseSecretKey
|
||||
* @description Get the Supabase Service Role Key.
|
||||
* ONLY USE IN SERVER-SIDE CODE. DO NOT EXPOSE THIS TO CLIENT-SIDE CODE.
|
||||
*/
|
||||
export function getServiceRoleKey() {
|
||||
export function getSupabaseSecretKey() {
|
||||
return z
|
||||
.string({
|
||||
required_error: message,
|
||||
@@ -18,7 +18,9 @@ export function getServiceRoleKey() {
|
||||
.min(1, {
|
||||
message: message,
|
||||
})
|
||||
.parse(process.env.SUPABASE_SERVICE_ROLE_KEY);
|
||||
.parse(
|
||||
process.env.SUPABASE_SECRET_KEY || process.env.SUPABASE_SERVICE_ROLE_KEY,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -27,7 +29,7 @@ export function getServiceRoleKey() {
|
||||
export function warnServiceRoleKeyUsage() {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.warn(
|
||||
`[Dev Only] This is a simple warning to let you know you are using the Supabase Service Role. Make sure it's the right call.`,
|
||||
`[Dev Only] This is a simple warning to let you know you are using the Supabase Secret Key. This key bypasses RLS and should only be used in server-side code. Please make sure it's the intended usage.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,15 +10,15 @@ export function getSupabaseClientKeys() {
|
||||
description: `This is the URL of your hosted Supabase instance. Please provide the variable NEXT_PUBLIC_SUPABASE_URL.`,
|
||||
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_URL`,
|
||||
}),
|
||||
anonKey: z
|
||||
.string({
|
||||
description: `This is the anon key provided by Supabase. It is a public key used client-side. Please provide the variable NEXT_PUBLIC_SUPABASE_ANON_KEY.`,
|
||||
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_ANON_KEY`,
|
||||
})
|
||||
.min(1),
|
||||
publicKey: z.string({
|
||||
description: `This is the public key provided by Supabase. It is a public key used client-side. Please provide the variable NEXT_PUBLIC_SUPABASE_PUBLIC_KEY.`,
|
||||
required_error: `Please provide the variable NEXT_PUBLIC_SUPABASE_PUBLIC_KEY`,
|
||||
}),
|
||||
})
|
||||
.parse({
|
||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL,
|
||||
anonKey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||
publicKey:
|
||||
process.env.NEXT_PUBLIC_SUPABASE_PUBLIC_KEY ||
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,27 +1,22 @@
|
||||
import type { User } from '@supabase/supabase-js';
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { requireUser } from '../require-user';
|
||||
import { JWTUserData } from '../types';
|
||||
import { useSupabase } from './use-supabase';
|
||||
|
||||
const queryKey = ['supabase:user'];
|
||||
|
||||
export function useUser(initialData?: User | null) {
|
||||
export function useUser(initialData?: JWTUserData | null) {
|
||||
const client = useSupabase();
|
||||
|
||||
const queryFn = async () => {
|
||||
const response = await client.auth.getUser();
|
||||
const response = await requireUser(client);
|
||||
|
||||
// this is most likely a session error or the user is not logged in
|
||||
if (response.error) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (response.data?.user) {
|
||||
return response.data.user;
|
||||
}
|
||||
|
||||
return Promise.reject(new Error('Unexpected result format'));
|
||||
return response.data;
|
||||
};
|
||||
|
||||
return useQuery({
|
||||
|
||||
@@ -1,19 +1,45 @@
|
||||
import type { SupabaseClient, User } from '@supabase/supabase-js';
|
||||
import type { SupabaseClient } from '@supabase/supabase-js';
|
||||
|
||||
import { checkRequiresMultiFactorAuthentication } from './check-requires-mfa';
|
||||
import { JWTUserData } from './types';
|
||||
|
||||
const MULTI_FACTOR_AUTH_VERIFY_PATH = '/auth/verify';
|
||||
const SIGN_IN_PATH = '/auth/sign-in';
|
||||
|
||||
/**
|
||||
* @name UserClaims
|
||||
* @description The user claims returned from the Supabase auth API.
|
||||
*/
|
||||
type UserClaims = {
|
||||
aud: string;
|
||||
exp: number;
|
||||
iat: number;
|
||||
iss: string;
|
||||
sub: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
app_metadata: Record<string, unknown>;
|
||||
user_metadata: Record<string, unknown>;
|
||||
role: string;
|
||||
aal: `aal1` | `aal2`;
|
||||
session_id: string;
|
||||
is_anonymous: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* @name requireUser
|
||||
* @description Require a session to be present in the request
|
||||
* @param client
|
||||
*/
|
||||
export async function requireUser(client: SupabaseClient): Promise<
|
||||
export async function requireUser(
|
||||
client: SupabaseClient,
|
||||
options?: {
|
||||
verifyMfa?: boolean;
|
||||
},
|
||||
): Promise<
|
||||
| {
|
||||
error: null;
|
||||
data: User;
|
||||
data: JWTUserData;
|
||||
}
|
||||
| (
|
||||
| {
|
||||
@@ -28,9 +54,9 @@ export async function requireUser(client: SupabaseClient): Promise<
|
||||
}
|
||||
)
|
||||
> {
|
||||
const { data, error } = await client.auth.getUser();
|
||||
const { data, error } = await client.auth.getClaims();
|
||||
|
||||
if (!data.user || error) {
|
||||
if (!data?.claims || error) {
|
||||
return {
|
||||
data: null,
|
||||
error: new AuthenticationError(),
|
||||
@@ -38,21 +64,36 @@ export async function requireUser(client: SupabaseClient): Promise<
|
||||
};
|
||||
}
|
||||
|
||||
const requiresMfa = await checkRequiresMultiFactorAuthentication(client);
|
||||
const { verifyMfa = true } = options ?? {};
|
||||
|
||||
// If the user requires multi-factor authentication,
|
||||
// redirect them to the page where they can verify their identity.
|
||||
if (requiresMfa) {
|
||||
return {
|
||||
data: null,
|
||||
error: new MultiFactorAuthError(),
|
||||
redirectTo: MULTI_FACTOR_AUTH_VERIFY_PATH,
|
||||
};
|
||||
if (verifyMfa) {
|
||||
const requiresMfa = await checkRequiresMultiFactorAuthentication(client);
|
||||
|
||||
// If the user requires multi-factor authentication,
|
||||
// redirect them to the page where they can verify their identity.
|
||||
if (requiresMfa) {
|
||||
return {
|
||||
data: null,
|
||||
error: new MultiFactorAuthError(),
|
||||
redirectTo: MULTI_FACTOR_AUTH_VERIFY_PATH,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// the client doesn't type the claims, so we need to cast it to the User type
|
||||
const user = data.claims as UserClaims;
|
||||
|
||||
return {
|
||||
error: null,
|
||||
data: data.user,
|
||||
data: {
|
||||
is_anonymous: user.is_anonymous,
|
||||
aal: user.aal,
|
||||
email: user.email,
|
||||
phone: user.phone,
|
||||
app_metadata: user.app_metadata,
|
||||
user_metadata: user.user_metadata,
|
||||
id: user.sub,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
13
packages/supabase/src/types.ts
Normal file
13
packages/supabase/src/types.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* @name JWTUserData
|
||||
* @description The user data mapped from the JWT claims.
|
||||
*/
|
||||
export type JWTUserData = {
|
||||
is_anonymous: boolean;
|
||||
aal: `aal1` | `aal2`;
|
||||
email: string;
|
||||
phone: string;
|
||||
app_metadata: Record<string, unknown>;
|
||||
user_metadata: Record<string, unknown>;
|
||||
id: string;
|
||||
};
|
||||
Reference in New Issue
Block a user