@stripe/radar-better-auth 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Stripe, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @stripe/radar-better-auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Stripe [Account Evaluations](https://docs.stripe.com/radar/customer-account-evaluations) for Better Auth email/password signup and login.
4
+
5
+ ## Install
6
+
7
+ Requires Node.js 22.13+ and Better Auth 1.7.x (1.7.7 or later). Use a secret key and publishable key from the same Stripe account that has access to the Account Evaluations API.
8
+
9
+ ```sh
10
+ npm install @stripe/radar-better-auth
11
+ ```
12
+
13
+ ## Configure
14
+
15
+ Server:
16
+
17
+ ```ts
18
+ import { betterAuth } from "better-auth";
19
+ import { accountEvaluations } from "@stripe/radar-better-auth";
20
+
21
+ export const auth = betterAuth({
22
+ database, // Your Better Auth database adapter.
23
+ emailAndPassword: { enabled: true },
24
+ plugins: [
25
+ accountEvaluations({
26
+ stripe: { secretKey: process.env.STRIPE_SECRET_KEY! },
27
+ resolveCustomer: async (user) => yourCustomerResolutionFn(user),
28
+ }),
29
+ ],
30
+ });
31
+ ```
32
+
33
+ Client:
34
+
35
+ ```ts
36
+ import { createAuthClient } from "better-auth/react";
37
+ import { accountEvaluationsClient } from "@stripe/radar-better-auth/client";
38
+
39
+ export const authClient = createAuthClient({
40
+ plugins: [
41
+ accountEvaluationsClient({
42
+ publishableKey: process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
43
+ }),
44
+ ],
45
+ });
46
+
47
+ await authClient.signUp.email({ email, name, password });
48
+ await authClient.signIn.email({ email, password });
49
+ ```
50
+
51
+ Use your existing Better Auth handler.
52
+
53
+ ## Customer setup
54
+
55
+ To evaluate logins, your app must create and store a Stripe Customer ID for each user. Implement `yourCustomerResolutionFn` in the example above to return that user's Customer ID, or `undefined` if none exists. Signup can be evaluated using email alone.
56
+
57
+ ## Behavior
58
+
59
+ Signup checks for multiple-account abuse. Login checks for account sharing.
60
+
61
+ Attempts with risk scores of 75 or higher are blocked. Set `blockThreshold` to change that cutoff or `mode: "monitor"` to evaluate without blocking. If you're in monitor mode, you can check your Stripe Radar dashboard to analyze the results before moving to enforcement.
62
+
63
+ If a risk check cannot complete, normal authentication continues (`failureMode: "open"`, the default). Set `failureMode: "closed"` to reject those attempts.
64
+
65
+ ## License
66
+
67
+ Licensed under the [MIT License](LICENSE).
@@ -0,0 +1,8 @@
1
+ // src/shared.ts
2
+ var RADAR_SESSION_HEADER = "x-stripe-radar-session";
3
+ var protectedPaths = ["/sign-up/email", "/sign-in/email"];
4
+
5
+ export {
6
+ RADAR_SESSION_HEADER,
7
+ protectedPaths
8
+ };
@@ -0,0 +1,84 @@
1
+ import * as _better_fetch_fetch from '@better-fetch/fetch';
2
+ import { accountEvaluations } from './index.js';
3
+ export { RADAR_SESSION_HEADER } from './index.js';
4
+ import 'better-call';
5
+ import 'better-auth';
6
+ import 'stripe';
7
+
8
+ type AccountEvaluationsClientOptions = ({
9
+ /** Loads Stripe.js for Radar collection. */
10
+ publishableKey: string;
11
+ createRadarSession?: never;
12
+ } | {
13
+ /** Custom Radar collector. */
14
+ createRadarSession: () => Promise<string | undefined>;
15
+ publishableKey?: never;
16
+ }) & {
17
+ /** Preload one browser session. Default: true. */
18
+ preload?: boolean;
19
+ /** Collection timeout. Default: 10 seconds. */
20
+ timeoutMs?: number;
21
+ };
22
+ declare function accountEvaluationsClient(options: AccountEvaluationsClientOptions): {
23
+ id: "account-evaluations";
24
+ $InferServerPlugin: ReturnType<typeof accountEvaluations>;
25
+ fetchPlugins: {
26
+ id: string;
27
+ name: string;
28
+ hooks: {
29
+ onRequest<T extends Record<string, any>>(ctx: _better_fetch_fetch.RequestContext<T>): Promise<{
30
+ headers: Headers;
31
+ url: URL | string;
32
+ body: any;
33
+ method: string;
34
+ signal: AbortSignal;
35
+ redirect?: RequestRedirect | undefined;
36
+ window?: null | undefined;
37
+ cache?: RequestCache | undefined;
38
+ credentials?: RequestCredentials | undefined;
39
+ integrity?: string | undefined;
40
+ keepalive?: boolean | undefined;
41
+ mode?: RequestMode | undefined;
42
+ priority?: RequestPriority | undefined;
43
+ referrer?: string | undefined;
44
+ referrerPolicy?: ReferrerPolicy | undefined;
45
+ onRequest?: (<T extends Record<string, any>>(context: _better_fetch_fetch.RequestContext<T>) => Promise<_better_fetch_fetch.RequestContext | void> | _better_fetch_fetch.RequestContext | void) | undefined;
46
+ onResponse?: ((context: _better_fetch_fetch.ResponseContext) => Promise<Response | void | _better_fetch_fetch.ResponseContext> | Response | _better_fetch_fetch.ResponseContext | void) | undefined;
47
+ onSuccess?: ((context: _better_fetch_fetch.SuccessContext<T>) => Promise<void> | void) | undefined;
48
+ onError?: ((context: _better_fetch_fetch.ErrorContext) => Promise<void> | void) | undefined;
49
+ onRetry?: ((response: _better_fetch_fetch.ResponseContext) => Promise<void> | void) | undefined;
50
+ hookOptions?: {
51
+ cloneResponse?: boolean;
52
+ } | undefined;
53
+ timeout?: number | undefined;
54
+ customFetchImpl?: _better_fetch_fetch.FetchEsque | undefined;
55
+ plugins?: _better_fetch_fetch.BetterFetchPlugin[] | undefined;
56
+ baseURL?: string | undefined;
57
+ throw?: boolean | undefined;
58
+ auth?: ({
59
+ type: "Bearer";
60
+ token: string | Promise<string | undefined> | (() => string | Promise<string | undefined> | undefined) | undefined;
61
+ } | {
62
+ type: "Basic";
63
+ username: string | (() => string | undefined) | undefined;
64
+ password: string | (() => string | undefined) | undefined;
65
+ } | {
66
+ type: "Custom";
67
+ prefix: string | (() => string | undefined) | undefined;
68
+ value: string | (() => string | undefined) | undefined;
69
+ }) | undefined;
70
+ query?: any;
71
+ params?: any;
72
+ duplex?: "full" | "half" | undefined;
73
+ jsonParser?: ((text: string) => Promise<any> | any) | undefined;
74
+ retry?: _better_fetch_fetch.RetryOptions | undefined;
75
+ retryAttempt?: number | undefined;
76
+ output?: (_better_fetch_fetch.StandardSchemaV1 | typeof Blob | typeof File) | undefined;
77
+ errorSchema?: _better_fetch_fetch.StandardSchemaV1 | undefined;
78
+ disableValidation?: boolean | undefined;
79
+ } | undefined>;
80
+ };
81
+ }[];
82
+ };
83
+
84
+ export { type AccountEvaluationsClientOptions, accountEvaluationsClient };
package/dist/client.js ADDED
@@ -0,0 +1,89 @@
1
+ import {
2
+ RADAR_SESSION_HEADER,
3
+ protectedPaths
4
+ } from "./chunk-WJT4SCTS.js";
5
+
6
+ // src/client.ts
7
+ import { loadStripe } from "@stripe/stripe-js/pure";
8
+ function accountEvaluationsClient(options) {
9
+ const timeoutMs = options.timeoutMs ?? 1e4;
10
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0)
11
+ throw new Error("timeoutMs must be a positive integer.");
12
+ if (!options.createRadarSession && !options.publishableKey?.startsWith("pk_")) {
13
+ throw new Error("A Stripe publishableKey is required.");
14
+ }
15
+ let stripePromise;
16
+ const createRadarSession = options.createRadarSession ?? (async () => {
17
+ stripePromise ??= loadStripe(options.publishableKey).catch((error) => {
18
+ stripePromise = void 0;
19
+ throw error;
20
+ });
21
+ const stripe = await stripePromise;
22
+ if (!stripe) {
23
+ stripePromise = void 0;
24
+ throw new Error("Stripe.js could not load. Please try again.");
25
+ }
26
+ const result = await stripe.createRadarSession();
27
+ if (result.error)
28
+ throw new Error("Device verification failed. Please try again.");
29
+ return result.radarSession.id;
30
+ });
31
+ async function collectRadarSession() {
32
+ let timer;
33
+ try {
34
+ const session = await Promise.race([
35
+ createRadarSession(),
36
+ new Promise((_, reject) => {
37
+ timer = setTimeout(
38
+ () => reject(
39
+ new Error("Device verification timed out. Please try again.")
40
+ ),
41
+ timeoutMs
42
+ );
43
+ })
44
+ ]);
45
+ if (!session || !/^rse_[a-zA-Z0-9_]{1,250}$/.test(session))
46
+ throw new Error("Device verification failed. Please try again.");
47
+ return session;
48
+ } finally {
49
+ if (timer) clearTimeout(timer);
50
+ }
51
+ }
52
+ let preloadedSession;
53
+ if (options.preload !== false && typeof window !== "undefined") {
54
+ preloadedSession = collectRadarSession();
55
+ void preloadedSession.catch(() => {
56
+ preloadedSession = void 0;
57
+ });
58
+ }
59
+ return {
60
+ id: "account-evaluations",
61
+ $InferServerPlugin: {},
62
+ fetchPlugins: [
63
+ {
64
+ id: "account-evaluations-radar-session",
65
+ name: "Account Evaluations Radar Session",
66
+ hooks: {
67
+ async onRequest(ctx) {
68
+ const pathname = new URL(ctx.url, "http://localhost").pathname;
69
+ if (!protectedPaths.some((path) => pathname.endsWith(path)) || ctx.method.toUpperCase() !== "POST")
70
+ return;
71
+ const headers = new Headers(ctx.headers);
72
+ headers.delete(RADAR_SESSION_HEADER);
73
+ try {
74
+ const pending = preloadedSession ?? collectRadarSession();
75
+ preloadedSession = void 0;
76
+ headers.set(RADAR_SESSION_HEADER, await pending);
77
+ } catch {
78
+ }
79
+ return { ...ctx, headers };
80
+ }
81
+ }
82
+ }
83
+ ]
84
+ };
85
+ }
86
+ export {
87
+ RADAR_SESSION_HEADER,
88
+ accountEvaluationsClient
89
+ };
@@ -0,0 +1,138 @@
1
+ import * as better_call from 'better-call';
2
+ import * as better_auth from 'better-auth';
3
+ import { GenericEndpointContext } from 'better-auth';
4
+ import Stripe from 'stripe';
5
+
6
+ declare const STRIPE_API_VERSION: Stripe.LatestApiVersion;
7
+ type Activity = "registration" | "login";
8
+ type Signal = "user_multi_accounting" | "user_account_sharing";
9
+ type SdkEvaluatedSignals = NonNullable<Stripe.V2.Signals.AccountEvaluation["evaluated_signals"]>;
10
+ type SdkSharingSignal = NonNullable<SdkEvaluatedSignals["user_account_sharing"]>;
11
+ type SdkClientDetails = Stripe.V2.Signals.AccountEvaluationCreateParams.AccountActivityDetails.Data.RegistrationAttempt.ClientDetails;
12
+ type RiskLevel = SdkSharingSignal["risk_level"];
13
+ type Decision = "allowed" | "blocked";
14
+ type ClientDetails = {
15
+ radar_session: NonNullable<SdkClientDetails["radar_session"]>;
16
+ } | {
17
+ data: NonNullable<SdkClientDetails["data"]>;
18
+ };
19
+ interface Evaluation {
20
+ id: string;
21
+ signal: Signal;
22
+ score: number;
23
+ riskLevel: RiskLevel;
24
+ }
25
+ type AccountReference = {
26
+ customerId: string;
27
+ contactEmail?: never;
28
+ } | {
29
+ customerId?: never;
30
+ contactEmail: string;
31
+ };
32
+ type DecisionReport = AccountReference & {
33
+ evaluationId: string;
34
+ activity: Activity;
35
+ status: Decision;
36
+ };
37
+ interface AccountEvaluationsClient {
38
+ evaluate(input: AccountReference & {
39
+ activity: Activity;
40
+ clientDetails: ClientDetails;
41
+ }): Promise<Evaluation>;
42
+ reportDecision(report: DecisionReport): Promise<void>;
43
+ }
44
+ interface StripeClientOptions {
45
+ secretKey: string;
46
+ /** Per-request timeout. Defaults to 5 seconds. */
47
+ timeoutMs?: number;
48
+ /** Existing SDK instance. */
49
+ stripeClient?: Stripe;
50
+ }
51
+ declare function validateEvaluation(value: Evaluation, signal: Signal): Evaluation;
52
+ declare function createStripeAccountEvaluationsClient(options: StripeClientOptions): AccountEvaluationsClient;
53
+
54
+ declare const RADAR_SESSION_HEADER = "x-stripe-radar-session";
55
+
56
+ type EvaluationEvent = DecisionReport & {
57
+ evaluation: Evaluation;
58
+ reported: boolean;
59
+ };
60
+ interface PluginErrorEvent {
61
+ operation: "evaluation" | "report" | "callback";
62
+ error: unknown;
63
+ /** Failed report, available for retry. */
64
+ report?: DecisionReport;
65
+ }
66
+ type AccountEvaluationsOptions = {
67
+ /** Custom adapter or mock. */
68
+ client: AccountEvaluationsClient;
69
+ stripe?: never;
70
+ } | {
71
+ stripe: StripeClientOptions;
72
+ client?: never;
73
+ };
74
+ type AccountEvaluationsConfig = AccountEvaluationsOptions & {
75
+ /** Block scores >= this value. Default: 75. */
76
+ blockThreshold?: number;
77
+ /** Observe scores without blocking. Default: enforce. */
78
+ mode?: "enforce" | "monitor";
79
+ /** Whether auth continues when risk checks cannot complete. Default: open. */
80
+ failureMode?: "closed" | "open";
81
+ /** Resolve an application-owned Customer for each evaluation; signup may use email if undefined, but login requires a Customer. */
82
+ resolveCustomer?: (user: {
83
+ id?: string;
84
+ email: string;
85
+ name: string;
86
+ }) => Promise<string | undefined>;
87
+ onDecision?: (event: EvaluationEvent) => void | Promise<void>;
88
+ onError?: (event: PluginErrorEvent) => void | Promise<void>;
89
+ };
90
+ declare function accountEvaluations(options: AccountEvaluationsConfig): {
91
+ id: "account-evaluations";
92
+ version: string;
93
+ init(): {
94
+ options: {
95
+ databaseHooks: {
96
+ user: {
97
+ create: {
98
+ before(user: {
99
+ id: string;
100
+ createdAt: Date;
101
+ updatedAt: Date;
102
+ email: string;
103
+ emailVerified: boolean;
104
+ name: string;
105
+ image?: string | null | undefined;
106
+ } & Record<string, unknown>, ctx: GenericEndpointContext | null): Promise<void>;
107
+ };
108
+ };
109
+ session: {
110
+ create: {
111
+ before(session: {
112
+ id: string;
113
+ createdAt: Date;
114
+ updatedAt: Date;
115
+ userId: string;
116
+ expiresAt: Date;
117
+ token: string;
118
+ ipAddress?: string | null | undefined;
119
+ userAgent?: string | null | undefined;
120
+ } & Record<string, unknown>, ctx: GenericEndpointContext | null): Promise<void>;
121
+ };
122
+ };
123
+ };
124
+ };
125
+ };
126
+ hooks: {
127
+ before: {
128
+ matcher: (ctx: better_auth.HookEndpointContext) => boolean;
129
+ handler: better_call.Middleware<better_call.MiddlewareOptions, (inputContext: better_call.MiddlewareInputContext<better_call.MiddlewareOptions>) => Promise<void>>;
130
+ }[];
131
+ after: {
132
+ matcher: (ctx: better_auth.HookEndpointContext) => boolean;
133
+ handler: better_call.Middleware<better_call.MiddlewareOptions, (inputContext: better_call.MiddlewareInputContext<better_call.MiddlewareOptions>) => Promise<void>>;
134
+ }[];
135
+ };
136
+ };
137
+
138
+ export { type AccountEvaluationsClient, type AccountEvaluationsConfig, type AccountEvaluationsOptions, type AccountReference, type Activity, type ClientDetails, type Decision, type DecisionReport, type Evaluation, type EvaluationEvent, type PluginErrorEvent, RADAR_SESSION_HEADER, type RiskLevel, STRIPE_API_VERSION, type Signal, type StripeClientOptions, accountEvaluations, createStripeAccountEvaluationsClient, validateEvaluation };
package/dist/index.js ADDED
@@ -0,0 +1,293 @@
1
+ import {
2
+ RADAR_SESSION_HEADER,
3
+ protectedPaths
4
+ } from "./chunk-WJT4SCTS.js";
5
+
6
+ // src/index.ts
7
+ import { APIError, createAuthMiddleware, getIP } from "better-auth/api";
8
+
9
+ // src/stripe.ts
10
+ import { randomUUID } from "crypto";
11
+ import Stripe from "stripe";
12
+ var STRIPE_API_VERSION = "2026-10-14.preview";
13
+ function validateEvaluation(value, signal) {
14
+ if (!value.id?.startsWith("acctevl_") || value.signal !== signal || !Number.isFinite(value.score) || value.score < 0 || value.score > 100 || !["low", "normal", "elevated", "highest", "unknown"].includes(
15
+ value.riskLevel
16
+ )) {
17
+ throw new Error("Stripe did not return a usable risk signal.");
18
+ }
19
+ return value;
20
+ }
21
+ function scoreNumber(value) {
22
+ if (typeof value === "number") return value;
23
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
24
+ if (typeof value === "object" && value !== null && "toNumber" in value && typeof value.toNumber === "function") {
25
+ return value.toNumber();
26
+ }
27
+ return NaN;
28
+ }
29
+ function createStripeAccountEvaluationsClient(options) {
30
+ if (!options.secretKey.trim())
31
+ throw new Error("A Stripe secret key is required.");
32
+ const timeoutMs = options.timeoutMs ?? 5e3;
33
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
34
+ throw new Error("timeoutMs must be a positive integer.");
35
+ }
36
+ const stripe = options.stripeClient ?? new Stripe(options.secretKey, {
37
+ timeout: timeoutMs,
38
+ maxNetworkRetries: 0,
39
+ typescript: true,
40
+ appInfo: {
41
+ name: "@stripe/radar-better-auth",
42
+ version: "0.1.0"
43
+ }
44
+ });
45
+ function accountDetails(reference) {
46
+ if (reference.customerId) return { customer: reference.customerId };
47
+ return {
48
+ data: { contact_email: reference.contactEmail }
49
+ };
50
+ }
51
+ return {
52
+ async evaluate({ activity, clientDetails, ...reference }) {
53
+ const signal = activity === "registration" ? "user_multi_accounting" : "user_account_sharing";
54
+ const type = `${activity}_attempt`;
55
+ const activityData = activity === "registration" ? {
56
+ type,
57
+ registration_attempt: { client_details: clientDetails }
58
+ } : {
59
+ type,
60
+ login_attempt: { client_details: clientDetails }
61
+ };
62
+ const result = await stripe.v2.signals.accountEvaluations.create(
63
+ {
64
+ account_details: accountDetails(reference),
65
+ requested_signals: [signal],
66
+ account_activity_details: { data: activityData }
67
+ },
68
+ {
69
+ apiVersion: STRIPE_API_VERSION,
70
+ idempotencyKey: `ba-evaluation-${randomUUID()}`
71
+ }
72
+ );
73
+ const evaluated = signal === "user_multi_accounting" ? result.evaluated_signals?.user_multi_accounting : result.evaluated_signals?.user_account_sharing;
74
+ if (!evaluated)
75
+ throw new Error("Stripe did not return the requested signal.");
76
+ return validateEvaluation(
77
+ {
78
+ id: result.id,
79
+ signal,
80
+ score: scoreNumber(evaluated.score),
81
+ riskLevel: evaluated.risk_level
82
+ },
83
+ signal
84
+ );
85
+ },
86
+ async reportDecision({ evaluationId, activity, status, ...reference }) {
87
+ const type = `${activity}_decision`;
88
+ const decision = { status };
89
+ await stripe.v2.signals.accountActivities.create(
90
+ {
91
+ account_details: accountDetails(reference),
92
+ account_evaluation: evaluationId,
93
+ type,
94
+ ...activity === "registration" ? { registration_decision: decision } : { login_decision: decision }
95
+ },
96
+ {
97
+ apiVersion: STRIPE_API_VERSION,
98
+ idempotencyKey: `ba-decision-${evaluationId}-${status}`
99
+ }
100
+ );
101
+ }
102
+ };
103
+ }
104
+
105
+ // src/index.ts
106
+ var RequestState = class {
107
+ pending;
108
+ };
109
+ function accountEvaluations(options) {
110
+ const client = options.client ?? createStripeAccountEvaluationsClient(options.stripe);
111
+ const failureMode = options.failureMode ?? "open";
112
+ const threshold = options.blockThreshold ?? 75;
113
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 100) {
114
+ throw new Error("blockThreshold must be a number between 0 and 100.");
115
+ }
116
+ async function notifyError(event, ctx) {
117
+ ctx.context.logger.warn(`[account-evaluations] ${event.operation} failed`);
118
+ try {
119
+ await options.onError?.(event);
120
+ } catch {
121
+ ctx.context.logger.warn("[account-evaluations] onError callback failed");
122
+ }
123
+ }
124
+ async function report(pending, ctx) {
125
+ let reported = false;
126
+ try {
127
+ await client.reportDecision(pending.report);
128
+ reported = true;
129
+ } catch (error) {
130
+ await notifyError(
131
+ { operation: "report", error, report: pending.report },
132
+ ctx
133
+ );
134
+ }
135
+ try {
136
+ await options.onDecision?.({
137
+ ...pending.report,
138
+ evaluation: pending.evaluation,
139
+ reported
140
+ });
141
+ } catch (error) {
142
+ await notifyError({ operation: "callback", error }, ctx);
143
+ }
144
+ }
145
+ function deviceDetails(ctx) {
146
+ const headers = ctx.headers ?? ctx.request?.headers;
147
+ const token = headers?.get(RADAR_SESSION_HEADER);
148
+ if (token !== null && token !== void 0) {
149
+ if (!/^rse_[a-zA-Z0-9_]{1,250}$/.test(token)) {
150
+ throw new APIError("BAD_REQUEST", {
151
+ code: "INVALID_RADAR_SESSION",
152
+ message: "Invalid device verification. Please try again."
153
+ });
154
+ }
155
+ return { radar_session: token };
156
+ }
157
+ const ip = headers ? getIP(headers, ctx.context.options) : null;
158
+ if (ip) {
159
+ const userAgent = headers?.get("user-agent");
160
+ const referrer = headers?.get("referer");
161
+ return {
162
+ data: {
163
+ ip,
164
+ ...userAgent ? { user_agent: userAgent } : {},
165
+ ...referrer ? { referrer } : {}
166
+ }
167
+ };
168
+ }
169
+ throw new APIError("BAD_REQUEST", {
170
+ code: "RADAR_SESSION_REQUIRED",
171
+ message: "Device verification is required. Please try again."
172
+ });
173
+ }
174
+ async function evaluate(user, activity, ctx) {
175
+ let clientDetails;
176
+ try {
177
+ clientDetails = deviceDetails(ctx);
178
+ } catch (error) {
179
+ await notifyError({ operation: "evaluation", error }, ctx);
180
+ if (failureMode === "open") return;
181
+ throw error;
182
+ }
183
+ let account;
184
+ let evaluation;
185
+ try {
186
+ const customerId = await options.resolveCustomer?.(user);
187
+ if (activity === "login" && !customerId)
188
+ throw new Error("Login evaluation requires a Stripe Customer.");
189
+ if (customerId && !/^cus_[a-zA-Z0-9]+$/.test(customerId))
190
+ throw new Error("Invalid Stripe customer ID.");
191
+ account = customerId ? { customerId } : { contactEmail: user.email };
192
+ evaluation = validateEvaluation(
193
+ await client.evaluate({ ...account, activity, clientDetails }),
194
+ activity === "registration" ? "user_multi_accounting" : "user_account_sharing"
195
+ );
196
+ } catch (error) {
197
+ await notifyError({ operation: "evaluation", error }, ctx);
198
+ if (failureMode === "open") return;
199
+ throw new APIError("SERVICE_UNAVAILABLE", {
200
+ code: "ACCOUNT_EVALUATION_UNAVAILABLE",
201
+ message: "Unable to verify this attempt. Please try again shortly."
202
+ });
203
+ }
204
+ const blocked = options.mode !== "monitor" && evaluation.score >= threshold;
205
+ const pending = {
206
+ evaluation,
207
+ report: {
208
+ ...account,
209
+ evaluationId: evaluation.id,
210
+ activity,
211
+ status: blocked ? "blocked" : "allowed"
212
+ }
213
+ };
214
+ if (blocked) {
215
+ await report(pending, ctx);
216
+ throw new APIError("FORBIDDEN", {
217
+ code: "ACCOUNT_EVALUATION_BLOCKED",
218
+ message: "We couldn't complete this request. Please contact support if you need help."
219
+ });
220
+ }
221
+ const state = ctx.context.accountEvaluationsState;
222
+ if (!state)
223
+ throw new Error("Account evaluations request context is missing.");
224
+ state.pending = pending;
225
+ }
226
+ return {
227
+ id: "account-evaluations",
228
+ version: "0.1.0",
229
+ init() {
230
+ return {
231
+ options: {
232
+ databaseHooks: {
233
+ user: {
234
+ create: {
235
+ async before(user, ctx) {
236
+ if (ctx?.path !== "/sign-up/email") return;
237
+ await evaluate(user, "registration", ctx);
238
+ }
239
+ }
240
+ },
241
+ session: {
242
+ create: {
243
+ async before(session, ctx) {
244
+ if (ctx?.path !== "/sign-in/email") return;
245
+ const user = await ctx.context.internalAdapter.findUserById(
246
+ session.userId
247
+ );
248
+ if (!user)
249
+ throw new APIError("UNAUTHORIZED", {
250
+ message: "Invalid credentials."
251
+ });
252
+ await evaluate(user, "login", ctx);
253
+ }
254
+ }
255
+ }
256
+ }
257
+ }
258
+ };
259
+ },
260
+ hooks: {
261
+ before: [
262
+ {
263
+ matcher: (ctx) => protectedPaths.some((path) => path === ctx.path),
264
+ handler: createAuthMiddleware(async (ctx) => {
265
+ ctx.context.accountEvaluationsState = new RequestState();
266
+ })
267
+ }
268
+ ],
269
+ after: [
270
+ {
271
+ matcher: (ctx) => protectedPaths.some((path) => path === ctx.path),
272
+ handler: createAuthMiddleware(async (ctx) => {
273
+ const state = ctx.context.accountEvaluationsState;
274
+ const pending = state?.pending;
275
+ if (!pending) return;
276
+ state.pending = void 0;
277
+ const result = ctx.context.returned;
278
+ if (result && typeof result === "object" && "user" in result && !(result instanceof APIError)) {
279
+ await report(pending, ctx);
280
+ }
281
+ })
282
+ }
283
+ ]
284
+ }
285
+ };
286
+ }
287
+ export {
288
+ RADAR_SESSION_HEADER,
289
+ STRIPE_API_VERSION,
290
+ accountEvaluations,
291
+ createStripeAccountEvaluationsClient,
292
+ validateEvaluation
293
+ };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@stripe/radar-better-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Stripe v2 Account Evaluations for Better Auth email/password flows",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/stripe/radar-better-auth-plugin.git",
9
+ "directory": "packages/account-evaluations"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "main": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ },
27
+ "./client": {
28
+ "types": "./dist/client.d.ts",
29
+ "import": "./dist/client.js"
30
+ }
31
+ },
32
+ "sideEffects": false,
33
+ "engines": {
34
+ "node": ">=22.13.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsup src/index.ts src/client.ts --format esm --dts --clean",
38
+ "typecheck": "tsc --noEmit"
39
+ },
40
+ "peerDependencies": {
41
+ "better-auth": ">=1.7.7 <1.8.0"
42
+ },
43
+ "dependencies": {
44
+ "@better-fetch/fetch": "^1.3.1",
45
+ "@stripe/stripe-js": "9.15.0",
46
+ "better-call": "^1.4.0",
47
+ "stripe": "23.1.0-alpha.4"
48
+ },
49
+ "devDependencies": {
50
+ "better-auth": "1.7.7"
51
+ }
52
+ }