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
12 changes: 11 additions & 1 deletion packages/backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { deprecatedObjectProperty } from '@clerk/shared/deprecated';
import type { TelemetryCollectorOptions } from '@clerk/shared/telemetry';
import { TelemetryCollector } from '@clerk/shared/telemetry';
import type { SDKMetadata } from '@clerk/types';

import type { CreateBackendApiOptions } from './api';
import { createBackendApiClient } from './api';
Expand All @@ -21,16 +24,23 @@ export type ClerkOptions = CreateBackendApiOptions &
CreateAuthenticateRequestOptions['options'],
'audience' | 'jwtKey' | 'proxyUrl' | 'secretKey' | 'publishableKey' | 'domain' | 'isSatellite'
>
>;
> & { sdkMetadata?: SDKMetadata; telemetry?: Pick<TelemetryCollectorOptions, 'disabled' | 'debug'> };

export function Clerk(options: ClerkOptions) {
const opts = { ...options };
const apiClient = createBackendApiClient(opts);
const requestState = createAuthenticateRequest({ options: opts, apiClient });
const telemetry = new TelemetryCollector({
...options.telemetry,
publishableKey: opts.publishableKey,
secretKey: opts.secretKey,
...(opts.sdkMetadata ? { sdk: opts.sdkMetadata.name, sdkVersion: opts.sdkMetadata.version } : {}),
});

const clerkInstance = {
...apiClient,
...requestState,
telemetry,
/**
* @deprecated This prop has been deprecated and will be removed in the next major release.
*/
Expand Down
3 changes: 2 additions & 1 deletion packages/fastify/src/clerkClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Clerk } from '@clerk/backend';

import { API_URL, API_VERSION, JWT_KEY, SECRET_KEY } from './constants';
import { API_URL, API_VERSION, JWT_KEY, SDK_METADATA, SECRET_KEY } from './constants';

export const createClerkClient = Clerk;

Expand All @@ -9,4 +9,5 @@ export const clerkClient = createClerkClient({
apiUrl: API_URL,
apiVersion: API_VERSION,
jwtKey: JWT_KEY,
sdkMetadata: SDK_METADATA,
});
4 changes: 4 additions & 0 deletions packages/fastify/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ export const SECRET_KEY = process.env.CLERK_SECRET_KEY || '';
export const PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || '';
export const API_URL = process.env.CLERK_API_URL || apiUrlFromPublishableKey(PUBLISHABLE_KEY);
export const JWT_KEY = process.env.CLERK_JWT_KEY || '';
export const SDK_METADATA = {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
};

export const { Cookies, Headers } = constants;
6 changes: 6 additions & 0 deletions packages/fastify/src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare global {
const PACKAGE_NAME: string;
const PACKAGE_VERSION: string;
}

export {};
2 changes: 1 addition & 1 deletion packages/fastify/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@
"resolveJsonModule": true,
"declarationDir": "dist/types"
},
"include": ["src/index.ts"],
"include": ["src/index.ts", "src/global.d.ts"],
"exclude": ["node_modules"]
}
7 changes: 1 addition & 6 deletions packages/gatsby-plugin-clerk/src/GatsbyClerkProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@ import {
import { navigate } from 'gatsby';
import React from 'react';

import { TELEMETRY_DEBUG, TELEMETRY_DISABLED } from './constants';

const SDK_METADATA = {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
};
import { SDK_METADATA, TELEMETRY_DEBUG, TELEMETRY_DISABLED } from './constants';

__internal__setErrorThrowerOptions({ packageName: 'gatsby-plugin-clerk' });

Expand Down
5 changes: 5 additions & 0 deletions packages/gatsby-plugin-clerk/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,8 @@ export const PROXY_URL = process.env.GATSBY_CLERK_PROXY_URL;

export const TELEMETRY_DISABLED = isTruthy(process.env.GATSBY_CLERK_TELEMETRY_DISABLED);
export const TELEMETRY_DEBUG = isTruthy(process.env.GATSBY_CLERK_TELEMETRY_DEBUG);

export const SDK_METADATA = {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
};
7 changes: 6 additions & 1 deletion packages/gatsby-plugin-clerk/src/ssr/clerkClient.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { Clerk } from '@clerk/backend';

import { API_URL, API_VERSION, SECRET_KEY } from '../constants';
import { API_URL, API_VERSION, SDK_METADATA, SECRET_KEY, TELEMETRY_DEBUG, TELEMETRY_DISABLED } from '../constants';

const clerkClient = Clerk({
secretKey: SECRET_KEY,
apiUrl: API_URL,
apiVersion: API_VERSION,
// TODO: Fetch version from package.json
userAgent: 'gatsby-plugin-clerk',
sdkMetadata: SDK_METADATA,
telemetry: {
disabled: TELEMETRY_DISABLED,
debug: TELEMETRY_DEBUG,
},
});

const createClerkClient = Clerk;
Expand Down
14 changes: 3 additions & 11 deletions packages/nextjs/src/server/authMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { AuthObject, RequestState } from '@clerk/backend';
import { buildRequestUrl, constants } from '@clerk/backend';
import { isDevelopmentFromApiKey } from '@clerk/shared/keys';
import { TelemetryCollector } from '@clerk/shared/telemetry';
import type { Autocomplete } from '@clerk/types';
import type Link from 'next/link';
import type { NextFetchEvent, NextMiddleware, NextRequest } from 'next/server';
Expand All @@ -10,7 +9,8 @@ import { NextResponse } from 'next/server';
import { isRedirect, mergeResponses, paths, setHeader, stringifyHeaders } from '../utils';
import { withLogger } from '../utils/debugLogger';
import { authenticateRequest, handleInterstitialState, handleUnknownState } from './authenticateRequest';
import { PUBLISHABLE_KEY, SECRET_KEY } from './constants';
import { clerkClient } from './clerkClient';
import { SECRET_KEY } from './constants';
import { DEV_BROWSER_JWT_MARKER, setDevBrowserJWTInURL } from './devBrowser';
import {
clockSkewDetected,
Expand All @@ -28,14 +28,6 @@ import {
setRequestHeadersOnNextResponse,
} from './utils';

const telemetry = new TelemetryCollector({
verbose: true,
samplingRate: 1,
publishableKey: PUBLISHABLE_KEY,
sdk: PACKAGE_NAME,
sdkVersion: PACKAGE_VERSION,
});

type WithPathPatternWildcard<T> = `${T & string}(.*)`;
type NextTypedRoute<T = Parameters<typeof Link>['0']['href']> = T extends string ? T : never;

Expand Down Expand Up @@ -154,7 +146,7 @@ const authMiddleware: AuthMiddleware = (...args: unknown[]) => {
const isApiRoute = createApiRoutes(apiRoutes);
const defaultAfterAuth = createDefaultAfterAuth(isPublicRoute, isApiRoute, params);

telemetry.record('METHOD_CALLED', {
clerkClient.telemetry.record('METHOD_CALLED', {
Comment thread
brkalow marked this conversation as resolved.
method: 'authMiddleware',
publicRoutes: Boolean(publicRoutes),
ignoredRoutes: Boolean(ignoredRoutes),
Expand Down
17 changes: 16 additions & 1 deletion packages/nextjs/src/server/clerkClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { Clerk } from '@clerk/backend';

import { API_URL, API_VERSION, DOMAIN, IS_SATELLITE, PROXY_URL, SECRET_KEY } from './constants';
import {
API_URL,
API_VERSION,
DOMAIN,
IS_SATELLITE,
PROXY_URL,
SDK_METADATA,
SECRET_KEY,
TELEMETRY_DEBUG,
TELEMETRY_DISABLED,
} from './constants';

const clerkClient = Clerk({
secretKey: SECRET_KEY,
Expand All @@ -11,6 +21,11 @@ const clerkClient = Clerk({
proxyUrl: PROXY_URL,
domain: DOMAIN,
isSatellite: IS_SATELLITE,
sdkMetadata: SDK_METADATA,
telemetry: {
disabled: TELEMETRY_DISABLED,
debug: TELEMETRY_DEBUG,
},
});

const createClerkClient = Clerk;
Expand Down
7 changes: 7 additions & 0 deletions packages/nextjs/src/server/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,10 @@ export const PROXY_URL = process.env.NEXT_PUBLIC_CLERK_PROXY_URL || '';
export const IS_SATELLITE = isTruthy(process.env.NEXT_PUBLIC_CLERK_IS_SATELLITE) || false;
export const SIGN_IN_URL = process.env.NEXT_PUBLIC_CLERK_SIGN_IN_URL || '';
export const SIGN_UP_URL = process.env.NEXT_PUBLIC_CLERK_SIGN_UP_URL || '';
export const SDK_METADATA = {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
};

export const TELEMETRY_DISABLED = isTruthy(process.env.NEXT_PUBLIC_CLERK_TELEMETRY_DISABLED);
export const TELEMETRY_DEBUG = isTruthy(process.env.NEXT_PUBLIC_CLERK_TELEMETRY_DEBUG);
6 changes: 2 additions & 4 deletions packages/nextjs/src/utils/mergeNextClerkPropsWithEnv.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isTruthy } from '@clerk/shared/underscore';

import { SDK_METADATA } from '../server/constants';
import type { NextClerkProviderProps } from '../types';

export const mergeNextClerkPropsWithEnv = (props: Omit<NextClerkProviderProps, 'children'>) => {
Expand All @@ -19,9 +20,6 @@ export const mergeNextClerkPropsWithEnv = (props: Omit<NextClerkProviderProps, '
disabled: isTruthy(process.env.NEXT_PUBLIC_CLERK_TELEMETRY_DISABLED),
debug: isTruthy(process.env.NEXT_PUBLIC_CLERK_TELEMETRY_DEBUG),
},
sdkMetadata: {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
},
sdkMetadata: SDK_METADATA,
};
};
6 changes: 6 additions & 0 deletions packages/sdk-node/src/globals.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export {};

declare global {
const PACKAGE_NAME: string;
const PACKAGE_VERSION: string;
}
4 changes: 4 additions & 0 deletions packages/sdk-node/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,9 @@ export const loadApiEnv = () => {
signInUrl: process.env.CLERK_SIGN_IN_URL || '',
isSatellite: isTruthy(process.env.CLERK_IS_SATELLITE),
jwtKey: process.env.CLERK_JWT_KEY || '',
sdkMetadata: {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
},
};
};
2 changes: 1 addition & 1 deletion packages/sdk-node/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
"types": ["jest"]
},
"exclude": ["node_modules"],
"include": ["src/index.ts", "src/instance.ts"]
"include": ["src/index.ts", "src/instance.ts", "src/globals.d.ts"]
}
36 changes: 22 additions & 14 deletions packages/shared/src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { InstanceType } from '@clerk/types';
import { parsePublishableKey } from './keys';
import { isTruthy } from './underscore';

type TelemetryCollectorOptions = {
export type TelemetryCollectorOptions = {
/**
* If true, telemetry will not be collected.
*/
Expand All @@ -21,13 +21,13 @@ type TelemetryCollectorOptions = {
*/
maxBufferSize?: number;
/**
* Determines whether or not events will be logged to the console.
* The publishableKey to associate with the collected events.
*/
verbose?: boolean;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

verbose is now unused with the debug option.

publishableKey?: string;
/**
* The publishableKey to associate with the collected events.
* The secretKey to associate with the collected events.
*/
publishableKey: string;
secretKey?: string;
/**
* The current clerk-js version.
*/
Expand All @@ -44,13 +44,13 @@ type TelemetryCollectorOptions = {

type TelemetryCollectorConfig = Pick<
TelemetryCollectorOptions,
'samplingRate' | 'verbose' | 'disabled' | 'debug' | 'maxBufferSize'
'samplingRate' | 'disabled' | 'debug' | 'maxBufferSize'
> & {
endpoint: string;
};

type TelemetryMetadata = Required<
Pick<TelemetryCollectorOptions, 'clerkVersion' | 'sdk' | 'sdkVersion' | 'publishableKey'>
Pick<TelemetryCollectorOptions, 'clerkVersion' | 'sdk' | 'sdkVersion' | 'publishableKey' | 'secretKey'>
> & {
/**
* The instance type, derived from the provided publishableKey.
Expand All @@ -64,6 +64,10 @@ type TelemetryEvent = {
* publishableKey
*/
pk?: string;
/**
* secretKey
*/
sk?: string;
/**
* instanceType
*/
Expand All @@ -85,8 +89,8 @@ type TelemetryEvent = {

const DEFAULT_CONFIG: Partial<Required<TelemetryCollectorConfig>> = {
samplingRate: 1,
verbose: false,
maxBufferSize: 5,
endpoint: 'https://staging.clerk-telemetry.com',
};

// TODO: determine some type of throttle/dedupe heuristic to avoid sending excessive events for e.g. a component render
Expand All @@ -100,7 +104,6 @@ export class TelemetryCollector {
this.#config = {
maxBufferSize: options.maxBufferSize ?? DEFAULT_CONFIG.maxBufferSize,
samplingRate: options.samplingRate ?? DEFAULT_CONFIG.samplingRate,
verbose: options.verbose ?? DEFAULT_CONFIG.verbose,
disabled: options.disabled ?? false,
debug: options.debug ?? false,
} as Required<TelemetryCollectorConfig>;
Expand All @@ -116,15 +119,19 @@ export class TelemetryCollector {
this.#metadata.sdk = options.sdk!;
this.#metadata.sdkVersion = options.sdkVersion!;

this.#metadata.publishableKey = options.publishableKey;
this.#metadata.publishableKey = options.publishableKey ?? '';

const parsedKey = parsePublishableKey(options.publishableKey);
if (parsedKey) {
this.#metadata.instanceType = parsedKey.instanceType;
}

// this.#config.endpoint = 'https://telemetry-service-staging.bryce-clerk.workers.dev';
this.#config.endpoint = 'http://localhost:8787';
if (options.secretKey) {
// Only send the first 16 characters of the secret key to to avoid sending the full key. We can still query against the partial key.
this.#metadata.secretKey = options.secretKey.substring(0, 16);
}

// this.#config.endpoint = 'http://localhost:8787';
}

get isEnabled(): boolean {
Expand Down Expand Up @@ -260,11 +267,12 @@ export class TelemetryCollector {

return {
event,
cv: this.#metadata.clerkVersion,
it: this.#metadata.instanceType,
cv: this.#metadata.clerkVersion ?? '',
it: this.#metadata.instanceType ?? '',
sdk: sdkMetadata.name,
sdkv: sdkMetadata.version,
...(this.#metadata.publishableKey ? { pk: this.#metadata.publishableKey } : {}),
...(this.#metadata.secretKey ? { sk: this.#metadata.secretKey } : {}),
payload,
};
}
Expand Down
4 changes: 3 additions & 1 deletion playground/app-router/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { authMiddleware } from '@clerk/nextjs';
import { NextMiddleware, NextResponse } from 'next/server';

const clerkMiddleware = authMiddleware()

const middleware: NextMiddleware = (request, event) => {
if (request.geo?.country?.toLocaleUpperCase() === 'IN') {
return new NextResponse(null, { status: 403 });
}
return authMiddleware()(request, event);
return clerkMiddleware(request, event);
};

export default middleware;
Expand Down