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
15 changes: 15 additions & 0 deletions .changeset/hono-middleware-env-vars.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@clerk/hono': minor
---

`clerkMiddleware()` now reads these environment variables from `process.env` or from Cloudflare Workers bindings:

- `CLERK_JWT_KEY`
- `CLERK_DOMAIN`
- `CLERK_PROXY_URL`
- `CLERK_IS_SATELLITE`
- `CLERK_SIGN_IN_URL`
- `CLERK_TELEMETRY_DISABLED`
- `CLERK_TELEMETRY_DEBUG`

An option passed to `clerkMiddleware()` overrides the matching variable. With `CLERK_JWT_KEY` set, the middleware verifies session tokens without fetching the JWKS when the key type matches the token's algorithm.
123 changes: 122 additions & 1 deletion packages/hono/src/__tests__/clerkMiddleware.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Hono } from 'hono';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';

import { clerkMiddleware, getAuth } from '../index';

Expand All @@ -18,6 +18,7 @@ const createMockSessionAuth = () => ({
});

const authenticateRequestMock = vi.fn();
const createClerkClientMock = vi.fn();

const { mockClerkFrontendApiProxy } = vi.hoisted(() => ({
mockClerkFrontendApiProxy: vi.fn(),
Expand All @@ -37,6 +38,7 @@ vi.mock(import('@clerk/backend'), async importOriginal => {
return {
...original,
createClerkClient(options: Parameters<typeof original.createClerkClient>[0]) {
createClerkClientMock(options);
const client = original.createClerkClient(options);
vi.spyOn(client, 'authenticateRequest').mockImplementation(authenticateRequestMock);
return client;
Expand Down Expand Up @@ -174,6 +176,125 @@ describe('clerkMiddleware()', () => {

expect(response.status).toEqual(500);
});

describe('environment variables', () => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const satelliteEnv = {
CLERK_JWT_KEY: 'jwt-key',
CLERK_DOMAIN: 'satellite.dev',
CLERK_PROXY_URL: 'https://example.com/__clerk',
CLERK_IS_SATELLITE: 'true',
CLERK_SIGN_IN_URL: 'https://primary.dev/sign-in',
};

const expectedOptions = {
jwtKey: 'jwt-key',
domain: 'satellite.dev',
proxyUrl: 'https://example.com/__clerk',
isSatellite: true,
signInUrl: 'https://primary.dev/sign-in',
};

const createApp = (options?: Parameters<typeof clerkMiddleware>[0]) => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: createMockSessionAuth,
});
const app = new Hono();
app.use('*', clerkMiddleware(options));
app.get('/', c => c.json({ ok: true }));
return app;
};

afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});

test('reads satellite and JWT key settings from process.env', async () => {
Object.entries(satelliteEnv).forEach(([key, value]) => vi.stubEnv(key, value));

const response = await createApp().request(new Request('http://localhost/'));

expect(response.status).toEqual(200);
expect(authenticateRequestMock).toHaveBeenCalledWith(
expect.any(Request),
expect.objectContaining(expectedOptions),
);
});

test('reads satellite and JWT key settings from Cloudflare Workers bindings', async () => {
vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' });

const response = await createApp().request(new Request('http://localhost/'), undefined, {
...EnvVariables,
...satelliteEnv,
});

expect(response.status).toEqual(200);
expect(authenticateRequestMock).toHaveBeenCalledWith(
expect.any(Request),
expect.objectContaining(expectedOptions),
);
});

test('prefers options passed to clerkMiddleware() over environment variables', async () => {
Object.entries(satelliteEnv).forEach(([key, value]) => vi.stubEnv(key, value));

const response = await createApp({ domain: 'other.dev', isSatellite: false }).request(
new Request('http://localhost/'),
);

expect(response.status).toEqual(200);
expect(authenticateRequestMock).toHaveBeenCalledWith(
expect.any(Request),
expect.objectContaining({ domain: 'other.dev', isSatellite: false }),
);
});

test("configures the client from c.get('clerk') with the same settings", async () => {
Object.entries(satelliteEnv).forEach(([key, value]) => vi.stubEnv(key, value));

const response = await createApp().request(new Request('http://localhost/'));

expect(response.status).toEqual(200);
expect(createClerkClientMock).toHaveBeenCalledWith(
Comment thread
wobsoriano marked this conversation as resolved.
Resolved
expect.objectContaining({
jwtKey: 'jwt-key',
domain: 'satellite.dev',
proxyUrl: 'https://example.com/__clerk',
isSatellite: true,
}),
);
});

test.each([
{ flags: {}, isEnabled: true, isDebug: false },
{ flags: { CLERK_TELEMETRY_DISABLED: '1', CLERK_TELEMETRY_DEBUG: '1' }, isEnabled: false, isDebug: true },
{ flags: { CLERK_TELEMETRY_DISABLED: 'false', CLERK_TELEMETRY_DEBUG: 'false' }, isEnabled: true, isDebug: false },
Comment thread
wobsoriano marked this conversation as resolved.
Resolved
])('reads telemetry flags $flags from Cloudflare Workers bindings', async ({ flags, isEnabled, isDebug }) => {
vi.stubEnv('CLERK_TELEMETRY_DISABLED', '');
vi.stubEnv('CLERK_TELEMETRY_DEBUG', '');
vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' });
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: createMockSessionAuth,
});
const app = new Hono();
app.use('*', clerkMiddleware());
app.get('/', c => {
const { telemetry } = c.get('clerk');
return c.json({ isEnabled: telemetry.isEnabled, isDebug: telemetry.isDebug });
});

const response = await app.request(new Request('http://localhost/'), undefined, {
CLERK_SECRET_KEY: 'sk_test_secret',
CLERK_PUBLISHABLE_KEY: `pk_test_${btoa('example.clerk.accounts.dev$')}`,
...flags,
});

expect(await response.json()).toEqual({ isEnabled, isDebug });
});
});
});

describe('Frontend API proxy handling', () => {
Expand Down
29 changes: 28 additions & 1 deletion packages/hono/src/clerkMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createClerkClient } from '@clerk/backend';
import type { AuthenticateRequestOptions, AuthOptions, GetAuthFnNoRequest } from '@clerk/backend/internal';
import { getAuthObjectForAcceptedToken } from '@clerk/backend/internal';
import { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, matchProxyPath, stripTrailingSlashes } from '@clerk/backend/proxy';
import { isTruthy } from '@clerk/shared/underscore';
import type { MiddlewareHandler } from 'hono';
import { env } from 'hono/adapter';

Expand All @@ -14,6 +15,14 @@ type ClerkEnv = {
CLERK_MACHINE_SECRET_KEY?: string;
CLERK_API_URL?: string;
CLERK_API_VERSION?: string;
CLERK_JWT_KEY?: string;
CLERK_DOMAIN?: string;
CLERK_PROXY_URL?: string;
CLERK_IS_SATELLITE?: string;
CLERK_SIGN_IN_URL?: string;
CLERK_TELEMETRY_DISABLED?: string;
CLERK_TELEMETRY_DEBUG?: string;
NODE_ENV?: string;
};

export type ClerkMiddlewareOptions = Omit<AuthenticateRequestOptions, 'acceptsToken'> & {
Expand Down Expand Up @@ -47,6 +56,11 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan
machineSecretKey = clerkEnv.CLERK_MACHINE_SECRET_KEY || '',
apiUrl = clerkEnv.CLERK_API_URL,
apiVersion = clerkEnv.CLERK_API_VERSION,
jwtKey = clerkEnv.CLERK_JWT_KEY,
domain = clerkEnv.CLERK_DOMAIN,
proxyUrl = clerkEnv.CLERK_PROXY_URL,
isSatellite = isTruthy(clerkEnv.CLERK_IS_SATELLITE),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
signInUrl = clerkEnv.CLERK_SIGN_IN_URL,
frontendApiProxy,
...rest
} = options || {};
Expand All @@ -64,7 +78,7 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan
}

// Handle Frontend API proxy requests and auto-derive proxyUrl
let derivedProxyUrl = rest.proxyUrl;
let derivedProxyUrl = proxyUrl;
if (frontendApiProxy) {
const proxyPath = stripTrailingSlashes(frontendApiProxy.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;
const requestUrl = new URL(c.req.url);
Expand Down Expand Up @@ -95,15 +109,28 @@ export const clerkMiddleware = (options?: ClerkMiddlewareOptions): MiddlewareHan
secretKey,
publishableKey,
machineSecretKey,
jwtKey,
domain,
proxyUrl: derivedProxyUrl,
isSatellite,
userAgent: `${PACKAGE_NAME}@${PACKAGE_VERSION}`,
sdkMetadata: { name: PACKAGE_NAME, version: PACKAGE_VERSION, environment: clerkEnv.NODE_ENV },
telemetry: {
disabled: isTruthy(clerkEnv.CLERK_TELEMETRY_DISABLED),
debug: isTruthy(clerkEnv.CLERK_TELEMETRY_DEBUG),
},
});

const requestState = await clerkClient.authenticateRequest(c.req.raw, {
...rest,
secretKey,
publishableKey,
machineSecretKey,
jwtKey,
domain,
proxyUrl: derivedProxyUrl,
isSatellite,
signInUrl,
acceptsToken: 'any',
});

Expand Down
Loading