better-auth-lead 0.5.0 → 0.6.1
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/README.md +60 -10
- package/dist/client.d.mts +1 -1
- package/dist/{index-DOhc8vla.d.mts → index-CypeYbkn.d.mts} +92 -2
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +83 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -146,9 +146,14 @@ const { data, error } = await authClient.lead.update({
|
|
|
146
146
|
|
|
147
147
|
If no session is present the endpoint responds with `401 Unauthorized`.
|
|
148
148
|
|
|
149
|
-
###
|
|
149
|
+
### Admin
|
|
150
150
|
|
|
151
|
-
|
|
151
|
+
The lead plugin ships with a set of admin-only endpoints to manage leads: `listLead`, `getLead`, and `removeLead`. They are only available when:
|
|
152
|
+
|
|
153
|
+
1. The better-auth [`admin`](https://www.better-auth.com/docs/plugins/admin) plugin is registered.
|
|
154
|
+
2. The `admin.enabled` lead option is set to `true`.
|
|
155
|
+
|
|
156
|
+
Enable them in your auth config:
|
|
152
157
|
|
|
153
158
|
```ts
|
|
154
159
|
// server/auth.ts
|
|
@@ -162,8 +167,9 @@ export const auth = betterAuth({
|
|
|
162
167
|
lead({
|
|
163
168
|
admin: {
|
|
164
169
|
enabled: true,
|
|
165
|
-
// Optional. Roles allowed to call
|
|
166
|
-
//
|
|
170
|
+
// Optional. Roles allowed to call the admin endpoints.
|
|
171
|
+
// Default: ['admin'].
|
|
172
|
+
// Checked against session.user.role (the admin plugin supports
|
|
167
173
|
// comma-separated roles).
|
|
168
174
|
roles: ['admin', 'editor'],
|
|
169
175
|
},
|
|
@@ -172,11 +178,23 @@ export const auth = betterAuth({
|
|
|
172
178
|
});
|
|
173
179
|
```
|
|
174
180
|
|
|
181
|
+
#### List leads
|
|
182
|
+
|
|
183
|
+
List a page of leads with optional search, filter, sort, and pagination. Requires a session with a role in `admin.roles`.
|
|
184
|
+
|
|
175
185
|
```ts
|
|
176
|
-
// GET /lead/list
|
|
177
|
-
const { data, error } = await authClient.lead.
|
|
186
|
+
// GET /lead/list-leads
|
|
187
|
+
const { data, error } = await authClient.lead.listLeads({
|
|
178
188
|
query: {
|
|
179
|
-
|
|
189
|
+
searchValue: 'user@example.com', // optional
|
|
190
|
+
searchField: 'email', // optional, default 'email'
|
|
191
|
+
searchOperator: 'contains', // optional: 'contains' | 'starts_with' | 'ends_with'
|
|
192
|
+
filterField: 'confirmed', // optional
|
|
193
|
+
filterValue: true, // optional
|
|
194
|
+
filterOperator: 'eq', // optional: any better-auth where operator
|
|
195
|
+
sortBy: 'createdAt', // optional
|
|
196
|
+
sortDirection: 'desc', // optional: 'asc' | 'desc'
|
|
197
|
+
limit: 100, // optional, default 100
|
|
180
198
|
offset: 0, // optional, default 0
|
|
181
199
|
},
|
|
182
200
|
});
|
|
@@ -184,9 +202,41 @@ const { data, error } = await authClient.lead.list({
|
|
|
184
202
|
|
|
185
203
|
The response includes the page of `leads`, the `total` number of leads in the database, and the resolved `limit` and `offset` for client-side pagination.
|
|
186
204
|
|
|
187
|
-
|
|
205
|
+
#### Get a lead
|
|
206
|
+
|
|
207
|
+
Fetch a single lead by `id`. Requires a session with a role in `admin.roles`.
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
// POST /lead/get-lead
|
|
211
|
+
const { data, error } = await authClient.lead.getLead({
|
|
212
|
+
query: {
|
|
213
|
+
id: 'lead-id',
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Returns the lead object, or `404 Not Found` (`LEAD_NOT_FOUND`) if no lead matches the id.
|
|
188
219
|
|
|
189
|
-
|
|
220
|
+
#### Remove a lead
|
|
221
|
+
|
|
222
|
+
Delete a single lead by `id`. Requires a session with a role in `admin.roles`.
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
// POST /lead/remove-lead
|
|
226
|
+
const { data, error } = await authClient.lead.removeLead({
|
|
227
|
+
body: {
|
|
228
|
+
leadId: 'lead-id',
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Returns `{ success: true }` on success, or `404 Not Found` (`LEAD_NOT_FOUND`) if no lead matches the id.
|
|
234
|
+
|
|
235
|
+
#### Responses
|
|
236
|
+
|
|
237
|
+
All admin endpoints share the following responses:
|
|
238
|
+
|
|
239
|
+
- `404 Not Found` (`ADMIN_PLUGIN_REQUIRED`) if the admin plugin is not registered or `admin.enabled` is not set.
|
|
190
240
|
- `403 Forbidden` (`FORBIDDEN`) if the session user's role is not in `admin.roles`.
|
|
191
241
|
- `401 Unauthorized` if no session is present.
|
|
192
242
|
|
|
@@ -332,10 +382,10 @@ model Lead {
|
|
|
332
382
|
updatedAt DateTime @updatedAt
|
|
333
383
|
email String?
|
|
334
384
|
userId String?
|
|
385
|
+
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
335
386
|
confirmed Boolean @default(false)
|
|
336
387
|
confirmationSentAt DateTime?
|
|
337
388
|
metadata String?
|
|
338
|
-
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
339
389
|
|
|
340
390
|
@@unique([email])
|
|
341
391
|
@@unique([userId])
|
package/dist/client.d.mts
CHANGED
|
@@ -207,11 +207,40 @@ declare const lead: <O extends LeadOptions>(options?: O) => {
|
|
|
207
207
|
};
|
|
208
208
|
};
|
|
209
209
|
endpoints: {
|
|
210
|
-
|
|
210
|
+
listLeads?: import("better-auth").StrictEndpoint<"/lead/list-leads", {
|
|
211
211
|
method: "GET";
|
|
212
212
|
query: import("zod").ZodObject<{
|
|
213
|
+
searchValue: import("zod").ZodOptional<import("zod").ZodString>;
|
|
214
|
+
searchField: import("zod").ZodOptional<import("zod").ZodEnum<{
|
|
215
|
+
email: "email";
|
|
216
|
+
}>>;
|
|
217
|
+
searchOperator: import("zod").ZodOptional<import("zod").ZodEnum<{
|
|
218
|
+
contains: "contains";
|
|
219
|
+
starts_with: "starts_with";
|
|
220
|
+
ends_with: "ends_with";
|
|
221
|
+
}>>;
|
|
213
222
|
limit: import("zod").ZodOptional<import("zod").ZodCoercedNumber<unknown>>;
|
|
214
223
|
offset: import("zod").ZodOptional<import("zod").ZodCoercedNumber<unknown>>;
|
|
224
|
+
sortBy: import("zod").ZodOptional<import("zod").ZodString>;
|
|
225
|
+
sortDirection: import("zod").ZodOptional<import("zod").ZodEnum<{
|
|
226
|
+
asc: "asc";
|
|
227
|
+
desc: "desc";
|
|
228
|
+
}>>;
|
|
229
|
+
filterField: import("zod").ZodOptional<import("zod").ZodString>;
|
|
230
|
+
filterValue: import("zod").ZodOptional<import("zod").ZodUnion<[import("zod").ZodUnion<[import("zod").ZodUnion<[import("zod").ZodUnion<[import("zod").ZodString, import("zod").ZodNumber]>, import("zod").ZodBoolean]>, import("zod").ZodArray<import("zod").ZodString>]>, import("zod").ZodArray<import("zod").ZodNumber>]>>;
|
|
231
|
+
filterOperator: import("zod").ZodOptional<import("zod").ZodEnum<{
|
|
232
|
+
in: "in";
|
|
233
|
+
contains: "contains";
|
|
234
|
+
starts_with: "starts_with";
|
|
235
|
+
ends_with: "ends_with";
|
|
236
|
+
eq: "eq";
|
|
237
|
+
ne: "ne";
|
|
238
|
+
lt: "lt";
|
|
239
|
+
lte: "lte";
|
|
240
|
+
gt: "gt";
|
|
241
|
+
gte: "gte";
|
|
242
|
+
not_in: "not_in";
|
|
243
|
+
}>>;
|
|
215
244
|
}, import("better-auth").$strip>;
|
|
216
245
|
use: ((inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
|
|
217
246
|
session: {
|
|
@@ -242,6 +271,66 @@ declare const lead: <O extends LeadOptions>(options?: O) => {
|
|
|
242
271
|
limit: number;
|
|
243
272
|
offset: number;
|
|
244
273
|
}> | undefined;
|
|
274
|
+
getLead?: import("better-auth").StrictEndpoint<"/lead/get-lead", {
|
|
275
|
+
method: "GET";
|
|
276
|
+
query: import("zod").ZodObject<{
|
|
277
|
+
id: import("zod").ZodString;
|
|
278
|
+
}, import("better-auth").$strip>;
|
|
279
|
+
use: ((inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
|
|
280
|
+
session: {
|
|
281
|
+
session: Record<string, any> & {
|
|
282
|
+
id: string;
|
|
283
|
+
createdAt: Date;
|
|
284
|
+
updatedAt: Date;
|
|
285
|
+
userId: string;
|
|
286
|
+
expiresAt: Date;
|
|
287
|
+
token: string;
|
|
288
|
+
ipAddress?: string | null | undefined;
|
|
289
|
+
userAgent?: string | null | undefined;
|
|
290
|
+
};
|
|
291
|
+
user: Record<string, any> & {
|
|
292
|
+
id: string;
|
|
293
|
+
createdAt: Date;
|
|
294
|
+
updatedAt: Date;
|
|
295
|
+
email: string;
|
|
296
|
+
emailVerified: boolean;
|
|
297
|
+
name: string;
|
|
298
|
+
image?: string | null | undefined;
|
|
299
|
+
};
|
|
300
|
+
};
|
|
301
|
+
}>)[];
|
|
302
|
+
}, Lead> | undefined;
|
|
303
|
+
removeLead?: import("better-auth").StrictEndpoint<"/lead/remove-lead", {
|
|
304
|
+
method: "POST";
|
|
305
|
+
body: import("zod").ZodObject<{
|
|
306
|
+
leadId: import("zod").ZodCoercedString<unknown>;
|
|
307
|
+
}, import("better-auth").$strip>;
|
|
308
|
+
use: ((inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
|
|
309
|
+
session: {
|
|
310
|
+
session: Record<string, any> & {
|
|
311
|
+
id: string;
|
|
312
|
+
createdAt: Date;
|
|
313
|
+
updatedAt: Date;
|
|
314
|
+
userId: string;
|
|
315
|
+
expiresAt: Date;
|
|
316
|
+
token: string;
|
|
317
|
+
ipAddress?: string | null | undefined;
|
|
318
|
+
userAgent?: string | null | undefined;
|
|
319
|
+
};
|
|
320
|
+
user: Record<string, any> & {
|
|
321
|
+
id: string;
|
|
322
|
+
createdAt: Date;
|
|
323
|
+
updatedAt: Date;
|
|
324
|
+
email: string;
|
|
325
|
+
emailVerified: boolean;
|
|
326
|
+
name: string;
|
|
327
|
+
image?: string | null | undefined;
|
|
328
|
+
};
|
|
329
|
+
};
|
|
330
|
+
}>)[];
|
|
331
|
+
}, {
|
|
332
|
+
success: boolean;
|
|
333
|
+
}> | undefined;
|
|
245
334
|
subscribe: import("better-auth").StrictEndpoint<"/lead/subscribe", {
|
|
246
335
|
method: "POST";
|
|
247
336
|
body: import("zod").ZodObject<{
|
|
@@ -375,8 +464,9 @@ declare const lead: <O extends LeadOptions>(options?: O) => {
|
|
|
375
464
|
INVALID_METADATA: import("better-auth").RawError<"INVALID_METADATA">;
|
|
376
465
|
EMAIL_OR_SESSION_REQUIRED: import("better-auth").RawError<"EMAIL_OR_SESSION_REQUIRED">;
|
|
377
466
|
ADMIN_PLUGIN_REQUIRED: import("better-auth").RawError<"ADMIN_PLUGIN_REQUIRED">;
|
|
467
|
+
LEAD_NOT_FOUND: import("better-auth").RawError<"LEAD_NOT_FOUND">;
|
|
378
468
|
};
|
|
379
469
|
};
|
|
380
470
|
//#endregion
|
|
381
471
|
export { LeadPayload as i, Lead as n, LeadOptions as r, lead as t };
|
|
382
|
-
//# sourceMappingURL=index-
|
|
472
|
+
//# sourceMappingURL=index-CypeYbkn.d.mts.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { i as LeadPayload, n as Lead, r as LeadOptions, t as lead } from "./index-
|
|
1
|
+
import { i as LeadPayload, n as Lead, r as LeadOptions, t as lead } from "./index-CypeYbkn.mjs";
|
|
2
2
|
export { type Lead, type LeadOptions, type LeadPayload, lead };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BASE_ERROR_CODES, defineErrorCodes } from "better-auth";
|
|
2
|
+
import { whereOperators } from "better-auth/adapters";
|
|
2
3
|
import { APIError, createAuthEndpoint, getSessionFromCtx, sessionMiddleware } from "better-auth/api";
|
|
3
4
|
import { SignJWT, jwtVerify } from "jose";
|
|
4
5
|
import { JWTExpired } from "jose/errors";
|
|
@@ -12,7 +13,8 @@ const LEAD_ERROR_CODES = defineErrorCodes({
|
|
|
12
13
|
INVALID_METADATA: "Invalid metadata",
|
|
13
14
|
EMAIL_OR_SESSION_REQUIRED: "Email or session is required",
|
|
14
15
|
ADMIN_PLUGIN_REQUIRED: "Admin plugin is required",
|
|
15
|
-
FORBIDDEN: "Forbidden"
|
|
16
|
+
FORBIDDEN: "Forbidden",
|
|
17
|
+
LEAD_NOT_FOUND: "Lead not found"
|
|
16
18
|
});
|
|
17
19
|
//#endregion
|
|
18
20
|
//#region src/routes.ts
|
|
@@ -271,10 +273,22 @@ const update = (options) => createAuthEndpoint("/lead/update", {
|
|
|
271
273
|
return ctx.json({ status: true });
|
|
272
274
|
});
|
|
273
275
|
const listQuerySchema = z.object({
|
|
276
|
+
searchValue: z.string().optional().meta({ description: "The value to search for. Eg: \"some name\"" }),
|
|
277
|
+
searchField: z.enum(["email"]).meta({ description: "The field to search in, defaults to email." }).optional(),
|
|
278
|
+
searchOperator: z.enum([
|
|
279
|
+
"contains",
|
|
280
|
+
"starts_with",
|
|
281
|
+
"ends_with"
|
|
282
|
+
]).meta({ description: "The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: \"contains\"" }).optional(),
|
|
274
283
|
limit: z.coerce.number().meta({ description: "The number of lead to return" }).optional(),
|
|
275
|
-
offset: z.coerce.number().meta({ description: "The offset to start from" }).optional()
|
|
284
|
+
offset: z.coerce.number().meta({ description: "The offset to start from" }).optional(),
|
|
285
|
+
sortBy: z.string().meta({ description: "The field to sort by" }).optional(),
|
|
286
|
+
sortDirection: z.enum(["asc", "desc"]).meta({ description: "The direction to sort by" }).optional(),
|
|
287
|
+
filterField: z.string().meta({ description: "The field to filter by" }).optional(),
|
|
288
|
+
filterValue: z.string().meta({ description: "The value to filter by" }).or(z.number()).or(z.boolean()).or(z.array(z.string())).or(z.array(z.number())).optional(),
|
|
289
|
+
filterOperator: z.enum(whereOperators).meta({ description: "The operator to use for the filter" }).optional()
|
|
276
290
|
});
|
|
277
|
-
const
|
|
291
|
+
const listLeads = (options) => createAuthEndpoint("/lead/list-leads", {
|
|
278
292
|
method: "GET",
|
|
279
293
|
query: listQuerySchema,
|
|
280
294
|
use: [sessionMiddleware]
|
|
@@ -282,12 +296,28 @@ const list = (options) => createAuthEndpoint("/lead/list", {
|
|
|
282
296
|
if (!ctx.context.hasPlugin("admin")) throw APIError.from("NOT_FOUND", LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);
|
|
283
297
|
const allowedRoles = options.admin?.roles ?? ["admin"];
|
|
284
298
|
if (!(ctx.context.session.user.role ?? "").split(",").map((r) => r.trim()).filter(Boolean).some((r) => allowedRoles.includes(r))) throw APIError.from("FORBIDDEN", LEAD_ERROR_CODES.FORBIDDEN);
|
|
299
|
+
const where = [];
|
|
300
|
+
if (ctx.query?.searchValue) where.push({
|
|
301
|
+
field: ctx.query.searchField || "email",
|
|
302
|
+
operator: ctx.query.searchOperator || "contains",
|
|
303
|
+
value: ctx.query.searchValue
|
|
304
|
+
});
|
|
305
|
+
if (ctx.query?.filterValue !== void 0) where.push({
|
|
306
|
+
field: ctx.query.filterField || "email",
|
|
307
|
+
operator: ctx.query.filterOperator || "eq",
|
|
308
|
+
value: ctx.query.filterValue
|
|
309
|
+
});
|
|
285
310
|
const limit = ctx.query.limit ?? 100;
|
|
286
311
|
const offset = ctx.query.offset ?? 0;
|
|
287
312
|
const [leads, total] = await Promise.all([ctx.context.adapter.findMany({
|
|
288
313
|
model: "lead",
|
|
289
314
|
limit,
|
|
290
|
-
offset
|
|
315
|
+
offset,
|
|
316
|
+
...ctx.query.sortBy && { sortBy: {
|
|
317
|
+
field: ctx.query.sortBy,
|
|
318
|
+
direction: ctx.query.sortDirection || "asc"
|
|
319
|
+
} },
|
|
320
|
+
where: where.length ? where : void 0
|
|
291
321
|
}), ctx.context.adapter.count({ model: "lead" })]);
|
|
292
322
|
return ctx.json({
|
|
293
323
|
leads,
|
|
@@ -296,6 +326,50 @@ const list = (options) => createAuthEndpoint("/lead/list", {
|
|
|
296
326
|
offset
|
|
297
327
|
});
|
|
298
328
|
});
|
|
329
|
+
const getLeadQuerySchema = z.object({ id: z.string().meta({ description: "The id of the Lead" }) });
|
|
330
|
+
const getLead = (options) => createAuthEndpoint("/lead/get-lead", {
|
|
331
|
+
method: "GET",
|
|
332
|
+
query: getLeadQuerySchema,
|
|
333
|
+
use: [sessionMiddleware]
|
|
334
|
+
}, async (ctx) => {
|
|
335
|
+
if (!ctx.context.hasPlugin("admin")) throw APIError.from("NOT_FOUND", LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);
|
|
336
|
+
const allowedRoles = options.admin?.roles ?? ["admin"];
|
|
337
|
+
if (!(ctx.context.session.user.role ?? "").split(",").map((r) => r.trim()).filter(Boolean).some((r) => allowedRoles.includes(r))) throw APIError.from("FORBIDDEN", LEAD_ERROR_CODES.FORBIDDEN);
|
|
338
|
+
const lead = await ctx.context.adapter.findOne({
|
|
339
|
+
model: "lead",
|
|
340
|
+
where: [{
|
|
341
|
+
field: "id",
|
|
342
|
+
value: ctx.body.leadId
|
|
343
|
+
}]
|
|
344
|
+
});
|
|
345
|
+
if (!lead) throw APIError.from("NOT_FOUND", LEAD_ERROR_CODES.LEAD_NOT_FOUND);
|
|
346
|
+
return lead;
|
|
347
|
+
});
|
|
348
|
+
const removeLeadBodySchema = z.object({ leadId: z.coerce.string().meta({ description: "The lead id" }) });
|
|
349
|
+
const removeLead = (options) => createAuthEndpoint("/lead/remove-lead", {
|
|
350
|
+
method: "POST",
|
|
351
|
+
body: removeLeadBodySchema,
|
|
352
|
+
use: [sessionMiddleware]
|
|
353
|
+
}, async (ctx) => {
|
|
354
|
+
if (!ctx.context.hasPlugin("admin")) throw APIError.from("NOT_FOUND", LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);
|
|
355
|
+
const allowedRoles = options.admin?.roles ?? ["admin"];
|
|
356
|
+
if (!(ctx.context.session.user.role ?? "").split(",").map((r) => r.trim()).filter(Boolean).some((r) => allowedRoles.includes(r))) throw APIError.from("FORBIDDEN", LEAD_ERROR_CODES.FORBIDDEN);
|
|
357
|
+
if (!await ctx.context.adapter.findOne({
|
|
358
|
+
model: "lead",
|
|
359
|
+
where: [{
|
|
360
|
+
field: "id",
|
|
361
|
+
value: ctx.body.leadId
|
|
362
|
+
}]
|
|
363
|
+
})) throw APIError.from("NOT_FOUND", LEAD_ERROR_CODES.LEAD_NOT_FOUND);
|
|
364
|
+
await ctx.context.adapter.delete({
|
|
365
|
+
model: "lead",
|
|
366
|
+
where: [{
|
|
367
|
+
field: "id",
|
|
368
|
+
value: ctx.body.leadId
|
|
369
|
+
}]
|
|
370
|
+
});
|
|
371
|
+
return ctx.json({ success: true });
|
|
372
|
+
});
|
|
299
373
|
async function createConfirmationToken(secret, payload, expiresIn) {
|
|
300
374
|
return new SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret));
|
|
301
375
|
}
|
|
@@ -373,7 +447,11 @@ const lead = (options = {}) => {
|
|
|
373
447
|
unsubscribeSession: unsubscribeSession(options),
|
|
374
448
|
resend: resend(options),
|
|
375
449
|
update: update(options),
|
|
376
|
-
...options.admin?.enabled ? {
|
|
450
|
+
...options.admin?.enabled ? {
|
|
451
|
+
listLeads: listLeads(options),
|
|
452
|
+
getLead: getLead(options),
|
|
453
|
+
removeLead: removeLead(options)
|
|
454
|
+
} : {}
|
|
377
455
|
};
|
|
378
456
|
return {
|
|
379
457
|
id: "lead",
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["lead"],"sources":["../src/error-codes.ts","../src/routes.ts","../src/schema.ts","../src/index.ts"],"sourcesContent":["import { defineErrorCodes } from 'better-auth';\n\nexport const LEAD_ERROR_CODES = defineErrorCodes({\n INVALID_EMAIL: 'Invalid email',\n INVALID_TOKEN: 'Invalid token',\n TOKEN_EXPIRED: 'Token expired',\n INVALID_METADATA: 'Invalid metadata',\n EMAIL_OR_SESSION_REQUIRED: 'Email or session is required',\n ADMIN_PLUGIN_REQUIRED: 'Admin plugin is required',\n FORBIDDEN: 'Forbidden',\n});\n","import { BASE_ERROR_CODES, type InternalLogger, type StandardSchemaV1 } from 'better-auth';\nimport {\n APIError,\n createAuthEndpoint,\n getSessionFromCtx,\n sessionMiddleware,\n} from 'better-auth/api';\nimport { SignJWT, jwtVerify } from 'jose';\nimport type { JWTPayload, JWTVerifyResult } from 'jose';\nimport { JWTExpired } from 'jose/errors';\nimport * as z from 'zod';\n\nimport { LEAD_ERROR_CODES } from './error-codes';\nimport type { Lead, LeadOptions, LeadPayload } from './type';\n\ntype InferMetadata<O extends LeadOptions> = O extends {\n metadata: { validationSchema: StandardSchemaV1<unknown, infer Out> };\n}\n ? Out\n : Record<string, any>;\n\ntype IdentifierType = 'email' | 'user';\n\nconst subscribeSchema = z.object({\n email: z.string().optional().meta({\n description: 'Email address of the lead',\n }),\n metadata: z.record(z.string(), z.any()).optional().meta({\n description: 'Additional metadata to store with the lead',\n }),\n});\n\nexport const subscribe = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/subscribe',\n {\n method: 'POST',\n body: subscribeSchema,\n metadata: {\n $Infer: {\n body: {} as {\n email?: string;\n metadata?: InferMetadata<O>;\n },\n },\n },\n },\n async (ctx) => {\n const email = ctx.body.email;\n\n const metadata = validateMetadata(\n options,\n ctx.body.metadata as Record<string, any> | undefined,\n ctx.context.logger,\n );\n\n let identifierType: IdentifierType;\n let leadIdentifier: string;\n let leadEmail: string;\n let createData: LeadPayload;\n\n if (email) {\n const isValidEmail = z.email().safeParse(email);\n if (!isValidEmail.success) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.INVALID_EMAIL);\n }\n\n leadIdentifier = email.toLowerCase();\n identifierType = 'email';\n leadEmail = leadIdentifier;\n createData = {\n email: leadIdentifier,\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n };\n } else {\n const session = await getSessionFromCtx(ctx);\n\n if (!session) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.EMAIL_OR_SESSION_REQUIRED);\n }\n\n leadIdentifier = session.user.id;\n identifierType = 'user';\n leadEmail = session.user.email;\n createData = {\n userId: leadIdentifier,\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n };\n }\n\n const whereField = identifierType === 'email' ? 'email' : 'userId';\n\n let lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n });\n\n if (!lead) {\n try {\n lead = await ctx.context.adapter.create<LeadPayload, Lead>({\n model: 'lead',\n data: createData,\n });\n } catch (e) {\n ctx.context.logger.info('Error creating lead');\n lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n });\n }\n }\n\n if (options.sendConfirmationEmail && lead && !lead.confirmed) {\n const token = await createConfirmationToken(\n ctx.context.secret,\n { identifier: leadIdentifier, type: identifierType },\n options.expiresIn ?? 3600,\n );\n const url = `${ctx.context.baseURL}/lead/verify?token=${token}`;\n const unsubscribeToken = await createUnsubscribeToken(\n ctx.context.secret,\n lead.id,\n options.unsubscribeExpiresIn,\n );\n const unsubscribeUrl = `${ctx.context.baseURL}/lead/unsubscribe?token=${unsubscribeToken}`;\n\n const sent = await options.sendConfirmationEmail(\n {\n lead,\n email: leadEmail,\n url,\n token,\n unsubscribeUrl,\n },\n ctx.request,\n );\n\n if (sent) {\n await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n update: { confirmationSentAt: new Date() },\n });\n }\n }\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst verifySchema = z.object({\n token: z.string().meta({\n description: 'The token to verify the email',\n }),\n});\n\nexport const verify = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/verify',\n {\n method: 'GET',\n query: verifySchema,\n },\n async (ctx) => {\n const { token } = ctx.query;\n\n let jwt: JWTVerifyResult<JWTPayload>;\n try {\n jwt = await jwtVerify(token, new TextEncoder().encode(ctx.context.secret), {\n algorithms: ['HS256'],\n });\n } catch (e) {\n if (e instanceof JWTExpired) {\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.TOKEN_EXPIRED);\n }\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.INVALID_TOKEN);\n }\n\n const confirmationPayloadSchema = z.object({\n identifier: z.string(),\n type: z.enum(['email', 'user']),\n });\n const parsed = confirmationPayloadSchema.parse(jwt.payload);\n\n const whereField = parsed.type === 'user' ? 'userId' : 'email';\n\n let lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: parsed.identifier }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n if (lead.confirmed) {\n return ctx.json({\n status: true,\n });\n }\n\n lead = await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: parsed.identifier }],\n update: {\n confirmed: true,\n },\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n if (options.onConfirmed) {\n await ctx.context.runInBackgroundOrAwait(options.onConfirmed({ lead }, ctx.request));\n }\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst unsubscribeQuerySchema = z.object({\n token: z.string().meta({\n description: 'Signed unsubscribe token',\n }),\n});\n\nexport const unsubscribe = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/unsubscribe',\n {\n method: 'POST',\n query: unsubscribeQuerySchema,\n metadata: {\n // Empty array overrides the router-level JSON-only restriction,\n // allowing POST with no body (required for RFC 8058 one-click unsubscribe).\n allowedMediaTypes: [],\n },\n },\n async (ctx) => {\n let payload: JWTPayload;\n try {\n const result = await jwtVerify(\n ctx.query.token,\n new TextEncoder().encode(ctx.context.secret),\n { algorithms: ['HS256'] },\n );\n payload = result.payload;\n } catch (e) {\n if (e instanceof JWTExpired) {\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.TOKEN_EXPIRED);\n }\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.INVALID_TOKEN);\n }\n\n const id = payload['id'] as string;\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [\n {\n field: 'id',\n value: id,\n },\n ],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n await ctx.context.adapter.delete({\n model: 'lead',\n where: [\n {\n field: 'id',\n value: id,\n },\n ],\n });\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nexport const unsubscribeSession = <O extends LeadOptions>(_options: O) =>\n createAuthEndpoint(\n '/lead/unsubscribe-session',\n {\n method: 'POST',\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const userId = ctx.context.session.user.id;\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n await ctx.context.adapter.delete({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n });\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst resendSchema = z.object({\n email: z.string().optional().meta({\n description: 'Email address to resend the verification email to',\n }),\n});\n\nexport const resend = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/resend',\n {\n method: 'POST',\n body: resendSchema,\n },\n async (ctx) => {\n const email = ctx.body.email;\n\n let identifierType: IdentifierType;\n let leadIdentifier: string;\n let leadEmail: string;\n\n if (email) {\n const isValidEmail = z.email().safeParse(email);\n if (!isValidEmail.success) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.INVALID_EMAIL);\n }\n\n leadIdentifier = email.toLowerCase();\n identifierType = 'email';\n leadEmail = leadIdentifier;\n } else {\n const session = await getSessionFromCtx(ctx);\n\n if (!session) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.EMAIL_OR_SESSION_REQUIRED);\n }\n leadIdentifier = session.user.id;\n identifierType = 'user';\n leadEmail = session.user.email;\n }\n\n const whereField = identifierType === 'email' ? 'email' : 'userId';\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n if (options.sendConfirmationEmail && !lead.confirmed) {\n const token = await createConfirmationToken(\n ctx.context.secret,\n { identifier: leadIdentifier, type: identifierType },\n options.expiresIn ?? 3600,\n );\n const url = `${ctx.context.baseURL}/lead/verify?token=${token}`;\n const unsubscribeToken = await createUnsubscribeToken(\n ctx.context.secret,\n lead.id,\n options.unsubscribeExpiresIn,\n );\n const unsubscribeUrl = `${ctx.context.baseURL}/lead/unsubscribe?token=${unsubscribeToken}`;\n\n const sent = await options.sendConfirmationEmail(\n {\n lead,\n email: leadEmail,\n url,\n token,\n unsubscribeUrl,\n },\n ctx.request,\n );\n\n if (sent) {\n await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n update: { confirmationSentAt: new Date() },\n });\n }\n }\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst updateSchema = z.object({\n metadata: z.record(z.string(), z.any()).optional().meta({\n description: 'Additional metadata to store with the lead',\n }),\n});\n\nexport const update = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/update',\n {\n method: 'POST',\n body: updateSchema,\n use: [sessionMiddleware],\n metadata: {\n $Infer: {\n body: {} as {\n metadata?: InferMetadata<O>;\n },\n },\n },\n },\n async (ctx) => {\n const userId = ctx.context.session.user.id;\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n const metadata = validateMetadata(\n options,\n ctx.body.metadata as Record<string, any> | undefined,\n ctx.context.logger,\n );\n\n await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n update: {\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n },\n });\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst listQuerySchema = z.object({\n limit: z.coerce\n .number()\n .meta({\n description: 'The number of lead to return',\n })\n .optional(),\n offset: z.coerce\n .number()\n .meta({\n description: 'The offset to start from',\n })\n .optional(),\n});\n\nexport const list = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/list',\n {\n method: 'GET',\n query: listQuerySchema,\n use: [sessionMiddleware],\n },\n async (ctx) => {\n if (!ctx.context.hasPlugin('admin')) {\n throw APIError.from('NOT_FOUND', LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);\n }\n\n const allowedRoles = options.admin?.roles ?? ['admin'];\n const userRole = (ctx.context.session.user as { role?: string }).role ?? '';\n const userRoles = userRole\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n const hasRole = userRoles.some((r) => allowedRoles.includes(r));\n\n if (!hasRole) {\n throw APIError.from('FORBIDDEN', LEAD_ERROR_CODES.FORBIDDEN);\n }\n\n const limit = ctx.query.limit ?? 100;\n const offset = ctx.query.offset ?? 0;\n\n const [leads, total] = await Promise.all([\n ctx.context.adapter.findMany<Lead>({\n model: 'lead',\n limit,\n offset,\n }),\n ctx.context.adapter.count({ model: 'lead' }),\n ]);\n\n return ctx.json({ leads, total, limit, offset });\n },\n );\n\nasync function createConfirmationToken(\n secret: string,\n payload: { identifier: string; type: IdentifierType },\n expiresIn: number,\n) {\n return new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + expiresIn)\n .sign(new TextEncoder().encode(secret));\n}\n\nasync function createUnsubscribeToken(secret: string, leadId: string, expiresIn?: number) {\n const jwt = new SignJWT({ id: leadId }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt();\n if (expiresIn !== undefined) {\n jwt.setExpirationTime(Math.floor(Date.now() / 1000) + expiresIn);\n }\n return jwt.sign(new TextEncoder().encode(secret));\n}\n\nfunction validateMetadata(\n options: LeadOptions,\n metadata: Record<string, any> | undefined,\n logger: InternalLogger,\n) {\n if (!metadata || !options.metadata?.validationSchema) {\n return metadata;\n }\n const validationResult = options.metadata.validationSchema['~standard'].validate(metadata);\n\n if (validationResult instanceof Promise) {\n throw APIError.from('INTERNAL_SERVER_ERROR', BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);\n }\n\n if (validationResult.issues) {\n logger.error('Invalid metadata', validationResult.issues);\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.INVALID_METADATA);\n }\n\n return validationResult.value as Record<string, any>;\n}\n","import { type BetterAuthPluginDBSchema } from 'better-auth';\nimport { mergeSchema } from 'better-auth/db';\n\nimport type { LeadOptions } from './type';\n\nexport const lead = {\n lead: {\n fields: {\n createdAt: {\n type: 'date',\n defaultValue: () => new Date(),\n required: true,\n input: false,\n },\n updatedAt: {\n type: 'date',\n defaultValue: () => new Date(),\n onUpdate: () => new Date(),\n required: true,\n input: false,\n },\n email: {\n type: 'string',\n required: false,\n unique: true,\n },\n userId: {\n type: 'string',\n required: false,\n unique: true,\n references: {\n model: 'user',\n field: 'id',\n },\n },\n confirmed: {\n type: 'boolean',\n defaultValue: false,\n required: true,\n input: false,\n },\n confirmationSentAt: {\n type: 'date',\n required: false,\n input: false,\n },\n metadata: {\n type: 'string',\n required: false,\n },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n\nexport const getSchema = <O extends LeadOptions>(options: O) => {\n return mergeSchema(lead, options.schema);\n};\n","import type { BetterAuthPlugin } from 'better-auth';\n\nimport { LEAD_ERROR_CODES } from './error-codes';\nimport { list, resend, subscribe, unsubscribe, unsubscribeSession, update, verify } from './routes';\nimport { getSchema } from './schema';\nimport type { LeadOptions } from './type';\n\nexport const lead = <O extends LeadOptions>(options: O = {} as O) => {\n const endpoints = {\n subscribe: subscribe(options),\n verify: verify(options),\n unsubscribe: unsubscribe(options),\n unsubscribeSession: unsubscribeSession(options),\n resend: resend(options),\n update: update(options),\n ...(options.admin?.enabled ? { list: list(options) } : {}),\n };\n\n return {\n id: 'lead',\n schema: getSchema(options),\n endpoints,\n options: options as NoInfer<O>,\n rateLimit: [\n {\n pathMatcher: (path) => ['/lead/subscribe', '/lead/resend'].includes(path),\n window: options.rateLimit?.window ?? 10,\n max: options.rateLimit?.max ?? 3,\n },\n ],\n $ERROR_CODES: LEAD_ERROR_CODES,\n } satisfies BetterAuthPlugin;\n};\n\nexport type * from './type';\n"],"mappings":";;;;;;;AAEA,MAAa,mBAAmB,iBAAiB;CAC/C,eAAe;CACf,eAAe;CACf,eAAe;CACf,kBAAkB;CAClB,2BAA2B;CAC3B,uBAAuB;CACvB,WAAW;AACb,CAAC;;;ACaD,MAAM,kBAAkB,EAAE,OAAO;CAC/B,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAChC,aAAa,4BACf,CAAC;CACD,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EACtD,aAAa,6CACf,CAAC;AACH,CAAC;AAED,MAAa,aAAoC,YAC/C,mBACE,mBACA;CACE,QAAQ;CACR,MAAM;CACN,UAAU,EACR,QAAQ,EACN,MAAM,CAAC,EAIT,EACF;AACF,GACA,OAAO,QAAQ;CACb,MAAM,QAAQ,IAAI,KAAK;CAEvB,MAAM,WAAW,iBACf,SACA,IAAI,KAAK,UACT,IAAI,QAAQ,MACd;CAEA,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO;EAET,IAAI,CADiB,EAAE,MAAM,EAAE,UAAU,KACzB,EAAE,SAChB,MAAM,SAAS,KAAK,eAAe,iBAAiB,aAAa;EAGnE,iBAAiB,MAAM,YAAY;EACnC,iBAAiB;EACjB,YAAY;EACZ,aAAa;GAC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ACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,QAAQ;EACR,YAAY;GACV,OAAO;GACP,OAAO;EACT;CACF;CACA,WAAW;EACT,MAAM;EACN,cAAc;EACd,UAAU;EACV,OAAO;CACT;CACA,oBAAoB;EAClB,MAAM;EACN,UAAU;EACV,OAAO;CACT;CACA,UAAU;EACR,MAAM;EACN,UAAU;CACZ;AACF,EACF,EACF;AAEA,MAAa,aAAoC,YAAe;CAC9D,OAAO,YAAYA,QAAM,QAAQ,MAAM;AACzC;;;ACjDA,MAAa,QAA+B,UAAa,CAAC,MAAW;CACnE,MAAM,YAAY;EAChB,WAAW,UAAU,OAAO;EAC5B,QAAQ,OAAO,OAAO;EACtB,aAAa,YAAY,OAAO;EAChC,oBAAoB,mBAAmB,OAAO;EAC9C,QAAQ,OAAO,OAAO;EACtB,QAAQ,OAAO,OAAO;EACtB,GAAI,QAAQ,OAAO,UAAU,EAAE,MAAM,KAAK,OAAO,EAAE,IAAI,CAAC;CAC1D;CAEA,OAAO;EACL,IAAI;EACJ,QAAQ,UAAU,OAAO;EACzB;EACS;EACT,WAAW,CACT;GACE,cAAc,SAAS,CAAC,mBAAmB,cAAc,EAAE,SAAS,IAAI;GACxE,QAAQ,QAAQ,WAAW,UAAU;GACrC,KAAK,QAAQ,WAAW,OAAO;EACjC,CACF;EACA,cAAc;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["lead"],"sources":["../src/error-codes.ts","../src/routes.ts","../src/schema.ts","../src/index.ts"],"sourcesContent":["import { defineErrorCodes } from 'better-auth';\n\nexport const LEAD_ERROR_CODES = defineErrorCodes({\n INVALID_EMAIL: 'Invalid email',\n INVALID_TOKEN: 'Invalid token',\n TOKEN_EXPIRED: 'Token expired',\n INVALID_METADATA: 'Invalid metadata',\n EMAIL_OR_SESSION_REQUIRED: 'Email or session is required',\n ADMIN_PLUGIN_REQUIRED: 'Admin plugin is required',\n FORBIDDEN: 'Forbidden',\n LEAD_NOT_FOUND: 'Lead not found',\n});\n","import {\n BASE_ERROR_CODES,\n type InternalLogger,\n type StandardSchemaV1,\n type Where,\n} from 'better-auth';\nimport { whereOperators } from 'better-auth/adapters';\nimport {\n APIError,\n createAuthEndpoint,\n getSessionFromCtx,\n sessionMiddleware,\n} from 'better-auth/api';\nimport { SignJWT, jwtVerify } from 'jose';\nimport type { JWTPayload, JWTVerifyResult } from 'jose';\nimport { JWTExpired } from 'jose/errors';\nimport * as z from 'zod';\n\nimport { LEAD_ERROR_CODES } from './error-codes';\nimport type { Lead, LeadOptions, LeadPayload } from './type';\n\ntype InferMetadata<O extends LeadOptions> = O extends {\n metadata: { validationSchema: StandardSchemaV1<unknown, infer Out> };\n}\n ? Out\n : Record<string, any>;\n\ntype IdentifierType = 'email' | 'user';\n\nconst subscribeSchema = z.object({\n email: z.string().optional().meta({\n description: 'Email address of the lead',\n }),\n metadata: z.record(z.string(), z.any()).optional().meta({\n description: 'Additional metadata to store with the lead',\n }),\n});\n\nexport const subscribe = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/subscribe',\n {\n method: 'POST',\n body: subscribeSchema,\n metadata: {\n $Infer: {\n body: {} as {\n email?: string;\n metadata?: InferMetadata<O>;\n },\n },\n },\n },\n async (ctx) => {\n const email = ctx.body.email;\n\n const metadata = validateMetadata(\n options,\n ctx.body.metadata as Record<string, any> | undefined,\n ctx.context.logger,\n );\n\n let identifierType: IdentifierType;\n let leadIdentifier: string;\n let leadEmail: string;\n let createData: LeadPayload;\n\n if (email) {\n const isValidEmail = z.email().safeParse(email);\n if (!isValidEmail.success) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.INVALID_EMAIL);\n }\n\n leadIdentifier = email.toLowerCase();\n identifierType = 'email';\n leadEmail = leadIdentifier;\n createData = {\n email: leadIdentifier,\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n };\n } else {\n const session = await getSessionFromCtx(ctx);\n\n if (!session) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.EMAIL_OR_SESSION_REQUIRED);\n }\n\n leadIdentifier = session.user.id;\n identifierType = 'user';\n leadEmail = session.user.email;\n createData = {\n userId: leadIdentifier,\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n };\n }\n\n const whereField = identifierType === 'email' ? 'email' : 'userId';\n\n let lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n });\n\n if (!lead) {\n try {\n lead = await ctx.context.adapter.create<LeadPayload, Lead>({\n model: 'lead',\n data: createData,\n });\n } catch (e) {\n ctx.context.logger.info('Error creating lead');\n lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n });\n }\n }\n\n if (options.sendConfirmationEmail && lead && !lead.confirmed) {\n const token = await createConfirmationToken(\n ctx.context.secret,\n { identifier: leadIdentifier, type: identifierType },\n options.expiresIn ?? 3600,\n );\n const url = `${ctx.context.baseURL}/lead/verify?token=${token}`;\n const unsubscribeToken = await createUnsubscribeToken(\n ctx.context.secret,\n lead.id,\n options.unsubscribeExpiresIn,\n );\n const unsubscribeUrl = `${ctx.context.baseURL}/lead/unsubscribe?token=${unsubscribeToken}`;\n\n const sent = await options.sendConfirmationEmail(\n {\n lead,\n email: leadEmail,\n url,\n token,\n unsubscribeUrl,\n },\n ctx.request,\n );\n\n if (sent) {\n await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n update: { confirmationSentAt: new Date() },\n });\n }\n }\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst verifySchema = z.object({\n token: z.string().meta({\n description: 'The token to verify the email',\n }),\n});\n\nexport const verify = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/verify',\n {\n method: 'GET',\n query: verifySchema,\n },\n async (ctx) => {\n const { token } = ctx.query;\n\n let jwt: JWTVerifyResult<JWTPayload>;\n try {\n jwt = await jwtVerify(token, new TextEncoder().encode(ctx.context.secret), {\n algorithms: ['HS256'],\n });\n } catch (e) {\n if (e instanceof JWTExpired) {\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.TOKEN_EXPIRED);\n }\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.INVALID_TOKEN);\n }\n\n const confirmationPayloadSchema = z.object({\n identifier: z.string(),\n type: z.enum(['email', 'user']),\n });\n const parsed = confirmationPayloadSchema.parse(jwt.payload);\n\n const whereField = parsed.type === 'user' ? 'userId' : 'email';\n\n let lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: parsed.identifier }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n if (lead.confirmed) {\n return ctx.json({\n status: true,\n });\n }\n\n lead = await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: parsed.identifier }],\n update: {\n confirmed: true,\n },\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n if (options.onConfirmed) {\n await ctx.context.runInBackgroundOrAwait(options.onConfirmed({ lead }, ctx.request));\n }\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst unsubscribeQuerySchema = z.object({\n token: z.string().meta({\n description: 'Signed unsubscribe token',\n }),\n});\n\nexport const unsubscribe = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/unsubscribe',\n {\n method: 'POST',\n query: unsubscribeQuerySchema,\n metadata: {\n // Empty array overrides the router-level JSON-only restriction,\n // allowing POST with no body (required for RFC 8058 one-click unsubscribe).\n allowedMediaTypes: [],\n },\n },\n async (ctx) => {\n let payload: JWTPayload;\n try {\n const result = await jwtVerify(\n ctx.query.token,\n new TextEncoder().encode(ctx.context.secret),\n { algorithms: ['HS256'] },\n );\n payload = result.payload;\n } catch (e) {\n if (e instanceof JWTExpired) {\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.TOKEN_EXPIRED);\n }\n throw APIError.from('UNAUTHORIZED', LEAD_ERROR_CODES.INVALID_TOKEN);\n }\n\n const id = payload['id'] as string;\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [\n {\n field: 'id',\n value: id,\n },\n ],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n await ctx.context.adapter.delete({\n model: 'lead',\n where: [\n {\n field: 'id',\n value: id,\n },\n ],\n });\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nexport const unsubscribeSession = <O extends LeadOptions>(_options: O) =>\n createAuthEndpoint(\n '/lead/unsubscribe-session',\n {\n method: 'POST',\n use: [sessionMiddleware],\n },\n async (ctx) => {\n const userId = ctx.context.session.user.id;\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n await ctx.context.adapter.delete({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n });\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst resendSchema = z.object({\n email: z.string().optional().meta({\n description: 'Email address to resend the verification email to',\n }),\n});\n\nexport const resend = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/resend',\n {\n method: 'POST',\n body: resendSchema,\n },\n async (ctx) => {\n const email = ctx.body.email;\n\n let identifierType: IdentifierType;\n let leadIdentifier: string;\n let leadEmail: string;\n\n if (email) {\n const isValidEmail = z.email().safeParse(email);\n if (!isValidEmail.success) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.INVALID_EMAIL);\n }\n\n leadIdentifier = email.toLowerCase();\n identifierType = 'email';\n leadEmail = leadIdentifier;\n } else {\n const session = await getSessionFromCtx(ctx);\n\n if (!session) {\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.EMAIL_OR_SESSION_REQUIRED);\n }\n leadIdentifier = session.user.id;\n identifierType = 'user';\n leadEmail = session.user.email;\n }\n\n const whereField = identifierType === 'email' ? 'email' : 'userId';\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n if (options.sendConfirmationEmail && !lead.confirmed) {\n const token = await createConfirmationToken(\n ctx.context.secret,\n { identifier: leadIdentifier, type: identifierType },\n options.expiresIn ?? 3600,\n );\n const url = `${ctx.context.baseURL}/lead/verify?token=${token}`;\n const unsubscribeToken = await createUnsubscribeToken(\n ctx.context.secret,\n lead.id,\n options.unsubscribeExpiresIn,\n );\n const unsubscribeUrl = `${ctx.context.baseURL}/lead/unsubscribe?token=${unsubscribeToken}`;\n\n const sent = await options.sendConfirmationEmail(\n {\n lead,\n email: leadEmail,\n url,\n token,\n unsubscribeUrl,\n },\n ctx.request,\n );\n\n if (sent) {\n await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: whereField, value: leadIdentifier }],\n update: { confirmationSentAt: new Date() },\n });\n }\n }\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst updateSchema = z.object({\n metadata: z.record(z.string(), z.any()).optional().meta({\n description: 'Additional metadata to store with the lead',\n }),\n});\n\nexport const update = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/update',\n {\n method: 'POST',\n body: updateSchema,\n use: [sessionMiddleware],\n metadata: {\n $Infer: {\n body: {} as {\n metadata?: InferMetadata<O>;\n },\n },\n },\n },\n async (ctx) => {\n const userId = ctx.context.session.user.id;\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n });\n\n if (!lead) {\n return ctx.json({\n status: true,\n });\n }\n\n const metadata = validateMetadata(\n options,\n ctx.body.metadata as Record<string, any> | undefined,\n ctx.context.logger,\n );\n\n await ctx.context.adapter.update<Lead>({\n model: 'lead',\n where: [{ field: 'userId', value: userId }],\n update: {\n metadata: metadata ? JSON.stringify(metadata) : undefined,\n },\n });\n\n return ctx.json({\n status: true,\n });\n },\n );\n\nconst listQuerySchema = z.object({\n searchValue: z.string().optional().meta({\n description: 'The value to search for. Eg: \"some name\"',\n }),\n searchField: z\n .enum(['email'])\n .meta({\n description: 'The field to search in, defaults to email.',\n })\n .optional(),\n searchOperator: z\n .enum(['contains', 'starts_with', 'ends_with'])\n .meta({\n description:\n 'The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: \"contains\"',\n })\n .optional(),\n limit: z.coerce\n .number()\n .meta({\n description: 'The number of lead to return',\n })\n .optional(),\n offset: z.coerce\n .number()\n .meta({\n description: 'The offset to start from',\n })\n .optional(),\n sortBy: z\n .string()\n .meta({\n description: 'The field to sort by',\n })\n .optional(),\n sortDirection: z\n .enum(['asc', 'desc'])\n .meta({\n description: 'The direction to sort by',\n })\n .optional(),\n filterField: z\n .string()\n .meta({\n description: 'The field to filter by',\n })\n .optional(),\n filterValue: z\n .string()\n .meta({\n description: 'The value to filter by',\n })\n .or(z.number())\n .or(z.boolean())\n .or(z.array(z.string()))\n .or(z.array(z.number()))\n .optional(),\n filterOperator: z\n .enum(whereOperators)\n .meta({\n description: 'The operator to use for the filter',\n })\n .optional(),\n});\n\nexport const listLeads = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/list-leads',\n {\n method: 'GET',\n query: listQuerySchema,\n use: [sessionMiddleware],\n },\n async (ctx) => {\n if (!ctx.context.hasPlugin('admin')) {\n throw APIError.from('NOT_FOUND', LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);\n }\n\n const allowedRoles = options.admin?.roles ?? ['admin'];\n const userRole = (ctx.context.session.user as { role?: string }).role ?? '';\n const userRoles = userRole\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n const hasRole = userRoles.some((r) => allowedRoles.includes(r));\n\n if (!hasRole) {\n throw APIError.from('FORBIDDEN', LEAD_ERROR_CODES.FORBIDDEN);\n }\n\n const where: Where[] = [];\n\n if (ctx.query?.searchValue) {\n where.push({\n field: ctx.query.searchField || 'email',\n operator: ctx.query.searchOperator || 'contains',\n value: ctx.query.searchValue,\n });\n }\n\n if (ctx.query?.filterValue !== undefined) {\n where.push({\n field: ctx.query.filterField || 'email',\n operator: ctx.query.filterOperator || 'eq',\n value: ctx.query.filterValue,\n });\n }\n\n const limit = ctx.query.limit ?? 100;\n const offset = ctx.query.offset ?? 0;\n\n const [leads, total] = await Promise.all([\n ctx.context.adapter.findMany<Lead>({\n model: 'lead',\n limit,\n offset,\n ...(ctx.query.sortBy && {\n sortBy: {\n field: ctx.query.sortBy,\n direction: ctx.query.sortDirection || 'asc',\n },\n }),\n where: where.length ? where : undefined,\n }),\n ctx.context.adapter.count({ model: 'lead' }),\n ]);\n\n return ctx.json({ leads, total, limit, offset });\n },\n );\n\nconst getLeadQuerySchema = z.object({\n id: z.string().meta({\n description: 'The id of the Lead',\n }),\n});\n\nexport const getLead = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/get-lead',\n {\n method: 'GET',\n query: getLeadQuerySchema,\n use: [sessionMiddleware],\n },\n async (ctx) => {\n if (!ctx.context.hasPlugin('admin')) {\n throw APIError.from('NOT_FOUND', LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);\n }\n\n const allowedRoles = options.admin?.roles ?? ['admin'];\n const userRole = (ctx.context.session.user as { role?: string }).role ?? '';\n const userRoles = userRole\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n const hasRole = userRoles.some((r) => allowedRoles.includes(r));\n\n if (!hasRole) {\n throw APIError.from('FORBIDDEN', LEAD_ERROR_CODES.FORBIDDEN);\n }\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: 'id', value: ctx.body.leadId }],\n });\n\n if (!lead) {\n throw APIError.from('NOT_FOUND', LEAD_ERROR_CODES.LEAD_NOT_FOUND);\n }\n\n return lead;\n },\n );\n\nconst removeLeadBodySchema = z.object({\n leadId: z.coerce.string().meta({\n description: 'The lead id',\n }),\n});\n\nexport const removeLead = <O extends LeadOptions>(options: O) =>\n createAuthEndpoint(\n '/lead/remove-lead',\n {\n method: 'POST',\n body: removeLeadBodySchema,\n use: [sessionMiddleware],\n },\n async (ctx) => {\n if (!ctx.context.hasPlugin('admin')) {\n throw APIError.from('NOT_FOUND', LEAD_ERROR_CODES.ADMIN_PLUGIN_REQUIRED);\n }\n\n const allowedRoles = options.admin?.roles ?? ['admin'];\n const userRole = (ctx.context.session.user as { role?: string }).role ?? '';\n const userRoles = userRole\n .split(',')\n .map((r) => r.trim())\n .filter(Boolean);\n const hasRole = userRoles.some((r) => allowedRoles.includes(r));\n\n if (!hasRole) {\n throw APIError.from('FORBIDDEN', LEAD_ERROR_CODES.FORBIDDEN);\n }\n\n const lead = await ctx.context.adapter.findOne<Lead>({\n model: 'lead',\n where: [{ field: 'id', value: ctx.body.leadId }],\n });\n\n if (!lead) {\n throw APIError.from('NOT_FOUND', LEAD_ERROR_CODES.LEAD_NOT_FOUND);\n }\n\n await ctx.context.adapter.delete({\n model: 'lead',\n where: [{ field: 'id', value: ctx.body.leadId }],\n });\n\n return ctx.json({ success: true });\n },\n );\n\nasync function createConfirmationToken(\n secret: string,\n payload: { identifier: string; type: IdentifierType },\n expiresIn: number,\n) {\n return new SignJWT(payload)\n .setProtectedHeader({ alg: 'HS256' })\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + expiresIn)\n .sign(new TextEncoder().encode(secret));\n}\n\nasync function createUnsubscribeToken(secret: string, leadId: string, expiresIn?: number) {\n const jwt = new SignJWT({ id: leadId }).setProtectedHeader({ alg: 'HS256' }).setIssuedAt();\n if (expiresIn !== undefined) {\n jwt.setExpirationTime(Math.floor(Date.now() / 1000) + expiresIn);\n }\n return jwt.sign(new TextEncoder().encode(secret));\n}\n\nfunction validateMetadata(\n options: LeadOptions,\n metadata: Record<string, any> | undefined,\n logger: InternalLogger,\n) {\n if (!metadata || !options.metadata?.validationSchema) {\n return metadata;\n }\n const validationResult = options.metadata.validationSchema['~standard'].validate(metadata);\n\n if (validationResult instanceof Promise) {\n throw APIError.from('INTERNAL_SERVER_ERROR', BASE_ERROR_CODES.ASYNC_VALIDATION_NOT_SUPPORTED);\n }\n\n if (validationResult.issues) {\n logger.error('Invalid metadata', validationResult.issues);\n throw APIError.from('BAD_REQUEST', LEAD_ERROR_CODES.INVALID_METADATA);\n }\n\n return validationResult.value as Record<string, any>;\n}\n","import { type BetterAuthPluginDBSchema } from 'better-auth';\nimport { mergeSchema } from 'better-auth/db';\n\nimport type { LeadOptions } from './type';\n\nexport const lead = {\n lead: {\n fields: {\n createdAt: {\n type: 'date',\n defaultValue: () => new Date(),\n required: true,\n input: false,\n },\n updatedAt: {\n type: 'date',\n defaultValue: () => new Date(),\n onUpdate: () => new Date(),\n required: true,\n input: false,\n },\n email: {\n type: 'string',\n required: false,\n unique: true,\n },\n userId: {\n type: 'string',\n required: false,\n unique: true,\n references: {\n model: 'user',\n field: 'id',\n },\n },\n confirmed: {\n type: 'boolean',\n defaultValue: false,\n required: true,\n input: false,\n },\n confirmationSentAt: {\n type: 'date',\n required: false,\n input: false,\n },\n metadata: {\n type: 'string',\n required: false,\n },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n\nexport const getSchema = <O extends LeadOptions>(options: O) => {\n return mergeSchema(lead, options.schema);\n};\n","import type { BetterAuthPlugin } from 'better-auth';\n\nimport { LEAD_ERROR_CODES } from './error-codes';\nimport {\n getLead,\n listLeads,\n removeLead,\n resend,\n subscribe,\n unsubscribe,\n unsubscribeSession,\n update,\n verify,\n} from './routes';\nimport { getSchema } from './schema';\nimport type { LeadOptions } from './type';\n\nexport const lead = <O extends LeadOptions>(options: O = {} as O) => {\n const endpoints = {\n subscribe: subscribe(options),\n verify: verify(options),\n unsubscribe: unsubscribe(options),\n unsubscribeSession: unsubscribeSession(options),\n resend: resend(options),\n update: update(options),\n ...(options.admin?.enabled\n ? {\n listLeads: listLeads(options),\n getLead: getLead(options),\n removeLead: removeLead(options),\n }\n : {}),\n };\n\n return {\n id: 'lead',\n schema: getSchema(options),\n endpoints,\n options: options as NoInfer<O>,\n rateLimit: [\n {\n pathMatcher: (path) => ['/lead/subscribe', '/lead/resend'].includes(path),\n window: options.rateLimit?.window ?? 10,\n max: options.rateLimit?.max ?? 3,\n },\n ],\n $ERROR_CODES: LEAD_ERROR_CODES,\n } satisfies BetterAuthPlugin;\n};\n\nexport type * from './type';\n"],"mappings":";;;;;;;;AAEA,MAAa,mBAAmB,iBAAiB;CAC/C,eAAe;CACf,eAAe;CACf,eAAe;CACf,kBAAkB;CAClB,2BAA2B;CAC3B,uBAAuB;CACvB,WAAW;CACX,gBAAgB;AAClB,CAAC;;;ACkBD,MAAM,kBAAkB,EAAE,OAAO;CAC/B,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAChC,aAAa,4BACf,CAAC;CACD,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,KAAK,EACtD,aAAa,6CACf,CAAC;AACH,CAAC;AAED,MAAa,aAAoC,YAC/C,mBACE,mBACA;CACE,QAAQ;CACR,MAAM;CACN,UAAU,EACR,QAAQ,EACN,MAAM,CAAC,EAIT,EACF;AACF,GACA,OAAO,QAAQ;CACb,MAAM,QAAQ,IAAI,KAAK;CAEvB,MAAM,WAAW,iBACf,SACA,IAAI,KAAK,UACT,IAAI,QAAQ,MACd;CAEA,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO;EAET,IAAI,CADiB,EAAE,MAAM,EAAE,UAAU,KACzB,EAAE,SAChB,MAAM,SAAS,KAAK,eAAe,iBAAiB,aAAa;EAGnE,iBAAiB,MAAM,YAAY;EACnC,iBAAiB;EACjB,YAAY;EACZ,aAAa;GACX,OAAO;GACP,UAAU,WAAW,KAAK,UAAU,QAAQ,IAAI,KAAA;EAClD;CACF,OAAO;EACL,MAAM,UAAU,MAAM,kBAAkB,GAAG;EAE3C,IAAI,CAAC,SACH,MAAM,SAAS,KAAK,eAAe,iBA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A,cAAc;CAChB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "better-auth-lead",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Better Auth Lead plugin",
|
|
5
5
|
"homepage": "https://github.com/marcjulian/better-auth-plugins#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
"zod": "^4.4.3"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@types/node": "^25.
|
|
33
|
-
"bumpp": "^
|
|
32
|
+
"@types/node": "^25.6.2",
|
|
33
|
+
"bumpp": "^11.1.0",
|
|
34
34
|
"tsdown": "^0.22.0",
|
|
35
|
-
"typescript": "^
|
|
35
|
+
"typescript": "^6.0.3",
|
|
36
36
|
"vitest": "^4.1.7"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|