Skip to content
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

fix(clerk): add alternative decoder #8642

Merged
merged 18 commits into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
32 changes: 25 additions & 7 deletions packages/auth-providers/clerk/api/src/__tests__/clerk.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda'

import { authDecoder } from '../decoder'
import { authDecoder, jwtAuthDecoder } from '../decoder'

const req = {
event: {} as APIGatewayProxyEvent,
Expand All @@ -18,14 +18,32 @@ afterAll(() => {
console.error = consoleError
})

test('returns null for unsupported type', async () => {
const decoded = await authDecoder('token', 'netlify', req)
describe('deprecated authDecoder', () => {
test('returns null for unsupported type', async () => {
const decoded = await authDecoder('token', 'netlify', req)

expect(decoded).toBe(null)
expect(decoded).toBe(null)
})

test('rejects when the token is invalid', async () => {
process.env.CLERK_JWT_KEY = 'jwt-key'

await expect(authDecoder('invalid-token', 'clerk', req)).rejects.toThrow()
})
})

test('rejects when the token is invalid', async () => {
process.env.CLERK_JWT_KEY = 'jwt-key'
describe('jwtAuthDecoder', () => {
test('returns null for unsupported type', async () => {
const decoded = await jwtAuthDecoder('token', 'netlify', req)

expect(decoded).toBe(null)
})

test('rejects when the token is invalid', async () => {
process.env.CLERK_JWT_KEY = 'jwt-key'

await expect(authDecoder('invalid-token', 'clerk', req)).rejects.toThrow()
await expect(
jwtAuthDecoder('invalid-token', 'clerk', req)
).rejects.toThrow()
})
})
36 changes: 36 additions & 0 deletions packages/auth-providers/clerk/api/src/decoder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Decoder } from '@redwoodjs/api'

/**
* @deprecated This function will be removed; it uses a rate-limited API. Use `jwtAuthDecoder` instead.
*/
export const authDecoder: Decoder = async (token: string, type: string) => {
if (type !== 'clerk') {
return null
Expand Down Expand Up @@ -34,3 +37,36 @@ export const authDecoder: Decoder = async (token: string, type: string) => {
return Promise.reject(error)
}
}

export const jwtAuthDecoder: Decoder = async (token: string, type: string) => {
jtoar marked this conversation as resolved.
Show resolved Hide resolved
if (type !== 'clerk') {
return null
}

const { verifyToken } = await import('@clerk/clerk-sdk-node')

try {
const issuer = (iss: string) =>
iss.startsWith('https://clerk.') || iss.includes('.clerk.accounts')

const jwtPayload = await verifyToken(token, {
issuer,
apiUrl: process.env.CLERK_API_URL || 'https://api.clerk.dev',
jwtKey: process.env.CLERK_JWT_KEY,
apiKey: process.env.CLERK_API_KEY,
secretKey: process.env.CLERK_SECRET_KEY,
})

if (!jwtPayload.sub) {
return Promise.reject(new Error('Session invalid'))
}

return {
...jwtPayload,
jtoar marked this conversation as resolved.
Show resolved Hide resolved
id: jwtPayload.sub,
}
} catch (error) {
console.error(error)
return Promise.reject(error)
}
}
2 changes: 1 addition & 1 deletion packages/auth-providers/clerk/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { authDecoder } from './decoder'
export { authDecoder, jwtAuthDecoder } from './decoder'
7 changes: 2 additions & 5 deletions packages/auth-providers/clerk/setup/src/setupHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const handler = async ({ force: forceArg }: Args) => {
standardAuthHandler({
basedir: __dirname,
forceArg,
authDecoderImport: `import { authDecoder } from '@redwoodjs/auth-clerk-api'`,
authDecoderImport: `import { jwtAuthDecoder as authDecoder } from '@redwoodjs/auth-clerk-api'`,
provider: 'clerk',
webPackages: [
'@clerk/clerk-react@^4',
Expand All @@ -26,17 +26,14 @@ export const handler = async ({ force: forceArg }: Args) => {
'```title=".env"',
'CLERK_PUBLISHABLE_KEY="..."',
'CLERK_SECRET_KEY="..."',
'CLERK_JWT_KEY="-----BEGIN PUBLIC KEY-----',
'...',
'-----END PUBLIC KEY-----"',
jtoar marked this conversation as resolved.
Show resolved Hide resolved
'```',
'',
`You can find their values under "API Keys" on your Clerk app's dashboard.`,
'Be sure to include `CLERK_PUBLISHABLE_KEY` in the `includeEnvironmentVariables` array in redwood.toml.',
'',
'```toml title="redwood.toml"',
'includeEnvironmentVariables = [',
' "CLERK_PUBLISHABLE_KEY"',
' "CLERK_PUBLISHABLE_KEY,"',
']',
'```',
'',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,12 @@ export const getCurrentUser = async (
return null
}

const { roles } = parseJWT({ decoded })
const { roles, ...user } = parseJWT({ decoded })

// Remove privateMetadata property from CurrentUser as it should not be accessible on the web
const { privateMetadata, ...userWithoutPrivateMetadata } = decoded

if (roles) {
return { ...userWithoutPrivateMetadata, roles }
return {
...user,
...(roles && { roles }),
}

return { ...userWithoutPrivateMetadata }
}

/**
Expand Down