@supa-media/convex 1.4.0 → 1.5.0
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 +21 -0
- package/package.json +1 -1
- package/src/auth/admission.ts +90 -0
- package/src/auth/index.ts +2 -0
- package/src/auth/setup.ts +14 -84
- package/src/auth/users.ts +113 -0
package/README.md
CHANGED
|
@@ -193,6 +193,7 @@ function createSupaAuth(config?: {
|
|
|
193
193
|
appName?: string;
|
|
194
194
|
methods?: Array<"email" | "phone">; // default ["email", "phone"]
|
|
195
195
|
magicLink?: SupaAuthMagicLinkConfig; // off unless present
|
|
196
|
+
admission?: SupaAuthAdmission; // invite-only; open sign-up unless present
|
|
196
197
|
resend?: { fromAddress: string; emailSubject?: (code) => string;
|
|
197
198
|
renderHtml?: (p: { code, email }) => string };
|
|
198
199
|
twilio?: { tokenBridgePath?: string }; // default "/api/internal/phone-token"
|
|
@@ -244,6 +245,26 @@ production login code.
|
|
|
244
245
|
> `PHONE_TOKEN_BRIDGE_SECRET` is unset, the provider logs the raw token to the
|
|
245
246
|
> console and returns, so local dev degrades rather than breaks.
|
|
246
247
|
|
|
248
|
+
|
|
249
|
+
### Invite-only sign-in (`admission`)
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
createSupaAuth({
|
|
253
|
+
admission: {
|
|
254
|
+
canReceiveEmailCode: (ctx, email) => ctx.runQuery(internal.waitlist.isAdmitted, { email }),
|
|
255
|
+
canCreateUser: (ctx, { email }) => isAdmitted(ctx.db, email),
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
`canReceiveEmailCode` runs before a sign-in code is mailed; refusing means no
|
|
261
|
+
mail goes out and `signIn` throws. `canCreateUser` runs before a user row is
|
|
262
|
+
created for somebody with no account, whichever provider they came through, and
|
|
263
|
+
is never asked for an account that already exists. Both fail closed: a hook
|
|
264
|
+
that throws refuses. Ask your own "is this address let in?" before calling
|
|
265
|
+
`signIn` and draw the answer yourself; the error message is redacted in
|
|
266
|
+
production.
|
|
267
|
+
|
|
247
268
|
### Magic link (opt-in)
|
|
248
269
|
|
|
249
270
|
Set `magicLink: {}` and a **second** email provider is registered under
|
package/package.json
CHANGED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may sign in at all: the hooks an invite-only or waitlisted app uses.
|
|
3
|
+
*
|
|
4
|
+
* Without `admission`, anybody who can read their inbox can make an account —
|
|
5
|
+
* the default, and unchanged. With it, an app answers two questions:
|
|
6
|
+
*
|
|
7
|
+
* - **May this address be mailed a code?** Asked before the email OTP
|
|
8
|
+
* provider sends anything. Refusing means no mail goes out and `signIn`
|
|
9
|
+
* throws, so a person who has not been let in never holds a code.
|
|
10
|
+
* - **May this person get a brand-new account?** Asked in
|
|
11
|
+
* `createOrUpdateUser`, only when no user exists yet. This is the backstop,
|
|
12
|
+
* and it is the one that covers every provider — the magic link, the
|
|
13
|
+
* fixed-code test accounts, a phone number — not only the email OTP.
|
|
14
|
+
* Returning users never reach it, so turning an app invite-only can never
|
|
15
|
+
* lock out an account that already exists.
|
|
16
|
+
*
|
|
17
|
+
* Both hooks fail closed: one that throws, or a send that arrives with no ctx
|
|
18
|
+
* to ask with, refuses.
|
|
19
|
+
*
|
|
20
|
+
* The refusal is one fixed message, `NOT_ADMITTED_MESSAGE`. A client should
|
|
21
|
+
* not rely on reading it — Convex redacts action errors in production — and
|
|
22
|
+
* should instead ask the app whether an address is let in *before* calling
|
|
23
|
+
* `signIn`, drawing its own "you're on the list" for the answer. These hooks
|
|
24
|
+
* are what makes that answer binding rather than advisory.
|
|
25
|
+
*/
|
|
26
|
+
import type {
|
|
27
|
+
AnyDataModel,
|
|
28
|
+
GenericActionCtx,
|
|
29
|
+
GenericMutationCtx,
|
|
30
|
+
} from "convex/server";
|
|
31
|
+
|
|
32
|
+
export interface SupaAuthAdmission {
|
|
33
|
+
/**
|
|
34
|
+
* Before a sign-in code is mailed. `email` is the address as the provider
|
|
35
|
+
* received it; normalize it the same way the app stores addresses.
|
|
36
|
+
*/
|
|
37
|
+
canReceiveEmailCode?: (
|
|
38
|
+
ctx: GenericActionCtx<AnyDataModel>,
|
|
39
|
+
email: string,
|
|
40
|
+
) => Promise<boolean>;
|
|
41
|
+
/**
|
|
42
|
+
* Before a user row is created for somebody with no account. `provider` is
|
|
43
|
+
* the auth provider's id (`"email"`, `"magic-link"`, `"test-email"`, …).
|
|
44
|
+
*/
|
|
45
|
+
canCreateUser?: (
|
|
46
|
+
ctx: GenericMutationCtx<AnyDataModel>,
|
|
47
|
+
who: { provider: string; email?: string; phone?: string },
|
|
48
|
+
) => Promise<boolean>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const NOT_ADMITTED_MESSAGE = "This address has not been let in yet.";
|
|
52
|
+
|
|
53
|
+
async function allowed(check: () => Promise<boolean>): Promise<boolean> {
|
|
54
|
+
try {
|
|
55
|
+
return (await check()) === true;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
console.error("[supa-auth] admission check failed, refusing:", error);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Throws unless `admission` lets `email` be mailed a code. */
|
|
63
|
+
export async function assertMayReceiveEmailCode(
|
|
64
|
+
admission: SupaAuthAdmission | undefined,
|
|
65
|
+
ctx: unknown,
|
|
66
|
+
email: string,
|
|
67
|
+
): Promise<void> {
|
|
68
|
+
const check = admission?.canReceiveEmailCode;
|
|
69
|
+
if (check === undefined) return;
|
|
70
|
+
const ok =
|
|
71
|
+
ctx !== undefined &&
|
|
72
|
+
ctx !== null &&
|
|
73
|
+
(await allowed(() =>
|
|
74
|
+
check(ctx as GenericActionCtx<AnyDataModel>, email),
|
|
75
|
+
));
|
|
76
|
+
if (!ok) throw new Error(NOT_ADMITTED_MESSAGE);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Throws unless `admission` lets this person have a new account. */
|
|
80
|
+
export async function assertMayCreateUser(
|
|
81
|
+
admission: SupaAuthAdmission | undefined,
|
|
82
|
+
ctx: GenericMutationCtx<AnyDataModel>,
|
|
83
|
+
who: { provider: string; email?: string; phone?: string },
|
|
84
|
+
): Promise<void> {
|
|
85
|
+
const check = admission?.canCreateUser;
|
|
86
|
+
if (check === undefined) return;
|
|
87
|
+
if (!(await allowed(() => check(ctx, who)))) {
|
|
88
|
+
throw new Error(NOT_ADMITTED_MESSAGE);
|
|
89
|
+
}
|
|
90
|
+
}
|
package/src/auth/index.ts
CHANGED
package/src/auth/setup.ts
CHANGED
|
@@ -25,9 +25,11 @@
|
|
|
25
25
|
import { convexAuth } from "@convex-dev/auth/server";
|
|
26
26
|
import { Email } from "@convex-dev/auth/providers/Email";
|
|
27
27
|
import { Phone } from "@convex-dev/auth/providers/Phone";
|
|
28
|
-
import type
|
|
29
|
-
|
|
28
|
+
import { assertMayReceiveEmailCode, type SupaAuthAdmission } from "./admission";
|
|
30
29
|
import { createTestEmailOtps, type SupaAuthTestEmailConfig } from "./testEmail";
|
|
30
|
+
import { userCallback } from "./users";
|
|
31
|
+
|
|
32
|
+
export { NOT_ADMITTED_MESSAGE, type SupaAuthAdmission } from "./admission";
|
|
31
33
|
|
|
32
34
|
export {
|
|
33
35
|
createTestEmailOtp,
|
|
@@ -117,6 +119,11 @@ export interface SupaAuthConfig {
|
|
|
117
119
|
* other email address is refused by a distinct provider.
|
|
118
120
|
*/
|
|
119
121
|
testEmail?: SupaAuthTestEmailConfig | SupaAuthTestEmailConfig[];
|
|
122
|
+
/**
|
|
123
|
+
* Make the app invite-only: who may be mailed a sign-in code, and who may
|
|
124
|
+
* get a brand-new account. Omitted, anybody may sign up. See `admission.ts`.
|
|
125
|
+
*/
|
|
126
|
+
admission?: SupaAuthAdmission;
|
|
120
127
|
/** Resend email OTP configuration. */
|
|
121
128
|
resend?: SupaAuthResendConfig;
|
|
122
129
|
/** Twilio phone OTP configuration. */
|
|
@@ -165,7 +172,10 @@ function createEmailOtp(config: SupaAuthConfig) {
|
|
|
165
172
|
return Email({
|
|
166
173
|
maxAge: 10 * 60, // 10 minutes
|
|
167
174
|
generateVerificationToken: createOtpGenerator(config.productionIdentifier),
|
|
168
|
-
|
|
175
|
+
// `@convex-dev/auth` passes its action ctx as a second argument that the
|
|
176
|
+
// Auth.js type does not declare; the admission check needs it to ask.
|
|
177
|
+
sendVerificationRequest: async ({ identifier: email, token }, ctx?: unknown) => {
|
|
178
|
+
await assertMayReceiveEmailCode(config.admission, ctx, email);
|
|
169
179
|
// Dynamic import of resend — only loaded when RESEND_API_KEY is set
|
|
170
180
|
const apiKey = process.env.RESEND_API_KEY;
|
|
171
181
|
|
|
@@ -430,86 +440,6 @@ export function createSupaAuth(config: SupaAuthConfig = {}) {
|
|
|
430
440
|
|
|
431
441
|
return convexAuth({
|
|
432
442
|
providers,
|
|
433
|
-
callbacks: {
|
|
434
|
-
async createOrUpdateUser(ctx, { existingUserId, type, profile }) {
|
|
435
|
-
// Returning user — auth account already exists
|
|
436
|
-
if (existingUserId !== null) {
|
|
437
|
-
const existingUser = await ctx.db.get(existingUserId);
|
|
438
|
-
if (existingUser) {
|
|
439
|
-
const updateData: Record<string, unknown> = {};
|
|
440
|
-
if (type === "phone" || type === "verification") {
|
|
441
|
-
updateData.phoneVerificationTime = Date.now();
|
|
442
|
-
}
|
|
443
|
-
if (type === "email" || type === "verification") {
|
|
444
|
-
updateData.emailVerificationTime = Date.now();
|
|
445
|
-
}
|
|
446
|
-
if (profile.phone) updateData.phone = profile.phone;
|
|
447
|
-
if (profile.email) updateData.email = profile.email;
|
|
448
|
-
if (profile.name) updateData.name = profile.name;
|
|
449
|
-
|
|
450
|
-
if (Object.keys(updateData).length > 0) {
|
|
451
|
-
await ctx.db.patch(existingUserId, updateData);
|
|
452
|
-
}
|
|
453
|
-
return existingUserId;
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
// New auth account — try to link to existing user by phone
|
|
458
|
-
if (type === "phone" && typeof profile.phone === "string") {
|
|
459
|
-
const phone = profile.phone;
|
|
460
|
-
const existingUser = await ctx.db
|
|
461
|
-
.query("users")
|
|
462
|
-
.filter((q) => q.eq(q.field("phone"), phone))
|
|
463
|
-
.first();
|
|
464
|
-
|
|
465
|
-
if (existingUser) {
|
|
466
|
-
await ctx.db.patch(existingUser._id, {
|
|
467
|
-
phoneVerificationTime: Date.now(),
|
|
468
|
-
});
|
|
469
|
-
return existingUser._id;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// New auth account — try to link to existing user by email
|
|
474
|
-
if (type === "email" && typeof profile.email === "string") {
|
|
475
|
-
const email = profile.email;
|
|
476
|
-
const existingUser = await ctx.db
|
|
477
|
-
.query("users")
|
|
478
|
-
.filter((q) => q.eq(q.field("email"), email))
|
|
479
|
-
.first();
|
|
480
|
-
|
|
481
|
-
if (existingUser) {
|
|
482
|
-
await ctx.db.patch(existingUser._id, {
|
|
483
|
-
emailVerificationTime: Date.now(),
|
|
484
|
-
});
|
|
485
|
-
return existingUser._id;
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
// No existing user — create a new one
|
|
490
|
-
const userData: Record<string, unknown> = {};
|
|
491
|
-
if (profile.email) userData.email = profile.email;
|
|
492
|
-
if (profile.phone) userData.phone = profile.phone;
|
|
493
|
-
if (profile.name) userData.name = profile.name;
|
|
494
|
-
if (profile.image) userData.image = profile.image;
|
|
495
|
-
if (profile.emailVerified || type === "email") {
|
|
496
|
-
userData.emailVerificationTime = Date.now();
|
|
497
|
-
}
|
|
498
|
-
if (profile.phoneVerified || type === "phone") {
|
|
499
|
-
userData.phoneVerificationTime = Date.now();
|
|
500
|
-
}
|
|
501
|
-
userData.isActive = true;
|
|
502
|
-
userData.createdAt = Date.now();
|
|
503
|
-
|
|
504
|
-
const userId = await ctx.db.insert(
|
|
505
|
-
"users",
|
|
506
|
-
userData as Record<string, unknown> & {
|
|
507
|
-
email?: string;
|
|
508
|
-
phone?: string;
|
|
509
|
-
},
|
|
510
|
-
);
|
|
511
|
-
return userId as GenericId<"users">;
|
|
512
|
-
},
|
|
513
|
-
},
|
|
443
|
+
callbacks: { createOrUpdateUser: userCallback(config.admission) },
|
|
514
444
|
});
|
|
515
445
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `createOrUpdateUser` callback `createSupaAuth` hands `convexAuth`.
|
|
3
|
+
*
|
|
4
|
+
* A returning account keeps its user. A new account is linked to an existing
|
|
5
|
+
* user with the same phone or email before anything is created, so one person
|
|
6
|
+
* who signs in two ways is one user. Only when nobody matches is a user row
|
|
7
|
+
* created — and that is the one place `admission.canCreateUser` is asked, so
|
|
8
|
+
* an invite-only app can refuse a stranger without ever locking out somebody
|
|
9
|
+
* who already has an account.
|
|
10
|
+
*/
|
|
11
|
+
import type { GenericId } from "convex/values";
|
|
12
|
+
import type { convexAuth } from "@convex-dev/auth/server";
|
|
13
|
+
|
|
14
|
+
import { assertMayCreateUser, type SupaAuthAdmission } from "./admission";
|
|
15
|
+
|
|
16
|
+
type Handler = NonNullable<
|
|
17
|
+
NonNullable<Parameters<typeof convexAuth>[0]["callbacks"]>["createOrUpdateUser"]
|
|
18
|
+
>;
|
|
19
|
+
|
|
20
|
+
export function userCallback(admission: SupaAuthAdmission | undefined): Handler {
|
|
21
|
+
async function createOrUpdateUser(
|
|
22
|
+
ctx: Parameters<Handler>[0],
|
|
23
|
+
{ existingUserId, type, provider, profile }: Parameters<Handler>[1],
|
|
24
|
+
): Promise<GenericId<"users">> {
|
|
25
|
+
// Returning user — auth account already exists
|
|
26
|
+
if (existingUserId !== null) {
|
|
27
|
+
const existingUser = await ctx.db.get(existingUserId);
|
|
28
|
+
if (existingUser) {
|
|
29
|
+
const updateData: Record<string, unknown> = {};
|
|
30
|
+
if (type === "phone" || type === "verification") {
|
|
31
|
+
updateData.phoneVerificationTime = Date.now();
|
|
32
|
+
}
|
|
33
|
+
if (type === "email" || type === "verification") {
|
|
34
|
+
updateData.emailVerificationTime = Date.now();
|
|
35
|
+
}
|
|
36
|
+
if (profile.phone) updateData.phone = profile.phone;
|
|
37
|
+
if (profile.email) updateData.email = profile.email;
|
|
38
|
+
if (profile.name) updateData.name = profile.name;
|
|
39
|
+
|
|
40
|
+
if (Object.keys(updateData).length > 0) {
|
|
41
|
+
await ctx.db.patch(existingUserId, updateData);
|
|
42
|
+
}
|
|
43
|
+
return existingUserId;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// New auth account — try to link to existing user by phone
|
|
48
|
+
if (type === "phone" && typeof profile.phone === "string") {
|
|
49
|
+
const phone = profile.phone;
|
|
50
|
+
const existingUser = await ctx.db
|
|
51
|
+
.query("users")
|
|
52
|
+
.filter((q) => q.eq(q.field("phone"), phone))
|
|
53
|
+
.first();
|
|
54
|
+
|
|
55
|
+
if (existingUser) {
|
|
56
|
+
await ctx.db.patch(existingUser._id, {
|
|
57
|
+
phoneVerificationTime: Date.now(),
|
|
58
|
+
});
|
|
59
|
+
return existingUser._id;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// New auth account — try to link to existing user by email
|
|
64
|
+
if (type === "email" && typeof profile.email === "string") {
|
|
65
|
+
const email = profile.email;
|
|
66
|
+
const existingUser = await ctx.db
|
|
67
|
+
.query("users")
|
|
68
|
+
.filter((q) => q.eq(q.field("email"), email))
|
|
69
|
+
.first();
|
|
70
|
+
|
|
71
|
+
if (existingUser) {
|
|
72
|
+
await ctx.db.patch(existingUser._id, {
|
|
73
|
+
emailVerificationTime: Date.now(),
|
|
74
|
+
});
|
|
75
|
+
return existingUser._id;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// No existing user. Ask the app first: this is the backstop that holds
|
|
80
|
+
// for every provider, not only the email OTP. See `admission.ts`.
|
|
81
|
+
await assertMayCreateUser(admission, ctx, {
|
|
82
|
+
provider: provider.id,
|
|
83
|
+
...(typeof profile.email === "string" ? { email: profile.email } : {}),
|
|
84
|
+
...(typeof profile.phone === "string" ? { phone: profile.phone } : {}),
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// No existing user — create a new one
|
|
88
|
+
const userData: Record<string, unknown> = {};
|
|
89
|
+
if (profile.email) userData.email = profile.email;
|
|
90
|
+
if (profile.phone) userData.phone = profile.phone;
|
|
91
|
+
if (profile.name) userData.name = profile.name;
|
|
92
|
+
if (profile.image) userData.image = profile.image;
|
|
93
|
+
if (profile.emailVerified || type === "email") {
|
|
94
|
+
userData.emailVerificationTime = Date.now();
|
|
95
|
+
}
|
|
96
|
+
if (profile.phoneVerified || type === "phone") {
|
|
97
|
+
userData.phoneVerificationTime = Date.now();
|
|
98
|
+
}
|
|
99
|
+
userData.isActive = true;
|
|
100
|
+
userData.createdAt = Date.now();
|
|
101
|
+
|
|
102
|
+
const userId = await ctx.db.insert(
|
|
103
|
+
"users",
|
|
104
|
+
userData as Record<string, unknown> & {
|
|
105
|
+
email?: string;
|
|
106
|
+
phone?: string;
|
|
107
|
+
},
|
|
108
|
+
);
|
|
109
|
+
return userId as GenericId<"users">;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return createOrUpdateUser;
|
|
113
|
+
}
|