@robelest/convex-auth 0.0.4-preview.13 → 0.0.4-preview.16
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 +140 -9
- package/dist/bin.cjs +5957 -5478
- package/dist/client/index.d.ts +3 -7
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +27 -26
- package/dist/client/index.js.map +1 -1
- package/dist/component/_generated/api.d.ts +14 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +1672 -24
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/convex.config.d.ts +2 -2
- package/dist/component/convex.config.d.ts.map +1 -1
- package/dist/component/index.d.ts +1 -1
- package/dist/component/index.js +2 -2
- package/dist/component/model.d.ts +153 -0
- package/dist/component/model.d.ts.map +1 -0
- package/dist/component/model.js +343 -0
- package/dist/component/model.js.map +1 -0
- package/dist/component/providers/sso.d.ts +1 -1
- package/dist/component/public/enterprise.d.ts +54 -0
- package/dist/component/public/enterprise.d.ts.map +1 -0
- package/dist/component/public/enterprise.js +515 -0
- package/dist/component/public/enterprise.js.map +1 -0
- package/dist/component/public/factors.d.ts +52 -0
- package/dist/component/public/factors.d.ts.map +1 -0
- package/dist/component/public/factors.js +285 -0
- package/dist/component/public/factors.js.map +1 -0
- package/dist/component/public/groups.d.ts +116 -0
- package/dist/component/public/groups.d.ts.map +1 -0
- package/dist/component/public/groups.js +596 -0
- package/dist/component/public/groups.js.map +1 -0
- package/dist/component/public/identity.d.ts +93 -0
- package/dist/component/public/identity.d.ts.map +1 -0
- package/dist/component/public/identity.js +426 -0
- package/dist/component/public/identity.js.map +1 -0
- package/dist/component/public/keys.d.ts +41 -0
- package/dist/component/public/keys.d.ts.map +1 -0
- package/dist/component/public/keys.js +157 -0
- package/dist/component/public/keys.js.map +1 -0
- package/dist/component/public/shared.d.ts +26 -0
- package/dist/component/public/shared.d.ts.map +1 -0
- package/dist/component/public/shared.js +32 -0
- package/dist/component/public/shared.js.map +1 -0
- package/dist/component/public.d.ts +9 -321
- package/dist/component/public.d.ts.map +1 -1
- package/dist/component/public.js +6 -2145
- package/dist/component/schema.d.ts +406 -260
- package/dist/component/schema.js +37 -32
- package/dist/component/schema.js.map +1 -1
- package/dist/component/server/auth.d.ts +161 -15
- package/dist/component/server/auth.d.ts.map +1 -1
- package/dist/component/server/auth.js +100 -7
- package/dist/component/server/auth.js.map +1 -1
- package/dist/component/server/cookies.js +3 -0
- package/dist/component/server/cookies.js.map +1 -1
- package/dist/component/server/db.js +1 -0
- package/dist/component/server/db.js.map +1 -1
- package/dist/component/server/device.js +3 -1
- package/dist/component/server/device.js.map +1 -1
- package/dist/component/server/domains/core.js +629 -0
- package/dist/component/server/domains/core.js.map +1 -0
- package/dist/component/server/domains/sso.js +884 -0
- package/dist/component/server/domains/sso.js.map +1 -0
- package/dist/component/server/factory.d.ts +136 -0
- package/dist/component/server/factory.d.ts.map +1 -0
- package/dist/component/server/factory.js +1134 -0
- package/dist/component/server/factory.js.map +1 -0
- package/dist/component/server/fx.js +2 -1
- package/dist/component/server/fx.js.map +1 -1
- package/dist/component/server/http.js +287 -0
- package/dist/component/server/http.js.map +1 -0
- package/dist/component/server/identity.js +13 -0
- package/dist/component/server/identity.js.map +1 -0
- package/dist/component/server/keys.js +4 -0
- package/dist/component/server/keys.js.map +1 -1
- package/dist/component/server/mutations/account.js +1 -1
- package/dist/component/server/mutations/index.js +2 -2
- package/dist/component/server/mutations/index.js.map +1 -1
- package/dist/component/server/mutations/invalidate.js +1 -1
- package/dist/component/server/mutations/oauth.js +10 -7
- package/dist/component/server/mutations/oauth.js.map +1 -1
- package/dist/component/server/mutations/refresh.js +1 -1
- package/dist/component/server/mutations/register.js +1 -1
- package/dist/component/server/mutations/retrieve.js +1 -1
- package/dist/component/server/mutations/signature.js +1 -1
- package/dist/component/server/mutations/store.js +6 -3
- package/dist/component/server/mutations/store.js.map +1 -1
- package/dist/component/server/mutations/verify.js +1 -1
- package/dist/component/server/oauth.js +3 -0
- package/dist/component/server/oauth.js.map +1 -1
- package/dist/component/server/passkey.js +3 -2
- package/dist/component/server/passkey.js.map +1 -1
- package/dist/component/server/provider.js +2 -0
- package/dist/component/server/provider.js.map +1 -1
- package/dist/component/server/providers.js +10 -0
- package/dist/component/server/providers.js.map +1 -1
- package/dist/component/server/ratelimit.js +3 -0
- package/dist/component/server/ratelimit.js.map +1 -1
- package/dist/component/server/redirects.js +2 -0
- package/dist/component/server/redirects.js.map +1 -1
- package/dist/component/server/refresh.js +5 -0
- package/dist/component/server/refresh.js.map +1 -1
- package/dist/component/server/sessions.js +5 -0
- package/dist/component/server/sessions.js.map +1 -1
- package/dist/component/server/signin.js +2 -1
- package/dist/component/server/signin.js.map +1 -1
- package/dist/component/server/sso.js +166 -19
- package/dist/component/server/sso.js.map +1 -1
- package/dist/component/server/tokens.js +1 -0
- package/dist/component/server/tokens.js.map +1 -1
- package/dist/component/server/totp.js +4 -2
- package/dist/component/server/totp.js.map +1 -1
- package/dist/component/server/types.d.ts +106 -38
- package/dist/component/server/types.d.ts.map +1 -1
- package/dist/component/server/types.js.map +1 -1
- package/dist/component/server/users.js +1 -0
- package/dist/component/server/users.js.map +1 -1
- package/dist/component/server/utils.js +44 -2
- package/dist/component/server/utils.js.map +1 -1
- package/dist/providers/anonymous.d.ts +1 -1
- package/dist/providers/credentials.d.ts +1 -1
- package/dist/providers/password.d.ts +1 -1
- package/dist/providers/sso.d.ts +1 -1
- package/dist/providers/sso.js.map +1 -1
- package/dist/server/auth.d.ts +163 -17
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +100 -7
- package/dist/server/auth.js.map +1 -1
- package/dist/server/cookies.d.ts +1 -38
- package/dist/server/cookies.js +3 -0
- package/dist/server/cookies.js.map +1 -1
- package/dist/server/db.d.ts +1 -125
- package/dist/server/db.js +1 -0
- package/dist/server/db.js.map +1 -1
- package/dist/server/device.d.ts +1 -24
- package/dist/server/device.js +3 -1
- package/dist/server/device.js.map +1 -1
- package/dist/server/domains/core.d.ts +434 -0
- package/dist/server/domains/core.d.ts.map +1 -0
- package/dist/server/domains/core.js +629 -0
- package/dist/server/domains/core.js.map +1 -0
- package/dist/server/domains/sso.d.ts +409 -0
- package/dist/server/domains/sso.d.ts.map +1 -0
- package/dist/server/domains/sso.js +884 -0
- package/dist/server/domains/sso.js.map +1 -0
- package/dist/server/enterpriseValidators.d.ts +1 -0
- package/dist/server/enterpriseValidators.js +60 -0
- package/dist/server/enterpriseValidators.js.map +1 -0
- package/dist/server/factory.d.ts +136 -0
- package/dist/server/factory.d.ts.map +1 -0
- package/dist/server/factory.js +1134 -0
- package/dist/server/factory.js.map +1 -0
- package/dist/server/fx.d.ts +1 -16
- package/dist/server/fx.d.ts.map +1 -1
- package/dist/server/fx.js +1 -0
- package/dist/server/fx.js.map +1 -1
- package/dist/server/http.d.ts +59 -0
- package/dist/server/http.d.ts.map +1 -0
- package/dist/server/http.js +287 -0
- package/dist/server/http.js.map +1 -0
- package/dist/server/identity.d.ts +1 -0
- package/dist/server/identity.js +13 -0
- package/dist/server/identity.js.map +1 -0
- package/dist/server/index.d.ts +468 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +530 -36
- package/dist/server/index.js.map +1 -1
- package/dist/server/keys.d.ts +1 -57
- package/dist/server/keys.js +4 -0
- package/dist/server/keys.js.map +1 -1
- package/dist/server/mutations/account.d.ts +7 -7
- package/dist/server/mutations/account.d.ts.map +1 -1
- package/dist/server/mutations/code.d.ts +13 -13
- package/dist/server/mutations/code.d.ts.map +1 -1
- package/dist/server/mutations/index.d.ts +107 -107
- package/dist/server/mutations/index.d.ts.map +1 -1
- package/dist/server/mutations/index.js +1 -1
- package/dist/server/mutations/index.js.map +1 -1
- package/dist/server/mutations/invalidate.d.ts +5 -5
- package/dist/server/mutations/invalidate.d.ts.map +1 -1
- package/dist/server/mutations/oauth.d.ts +10 -10
- package/dist/server/mutations/oauth.d.ts.map +1 -1
- package/dist/server/mutations/oauth.js +9 -6
- package/dist/server/mutations/oauth.js.map +1 -1
- package/dist/server/mutations/refresh.d.ts +4 -4
- package/dist/server/mutations/register.d.ts +12 -12
- package/dist/server/mutations/register.d.ts.map +1 -1
- package/dist/server/mutations/retrieve.d.ts +7 -7
- package/dist/server/mutations/signature.d.ts +5 -5
- package/dist/server/mutations/signin.d.ts +6 -6
- package/dist/server/mutations/signin.d.ts.map +1 -1
- package/dist/server/mutations/signout.d.ts +1 -1
- package/dist/server/mutations/store.d.ts +3 -2
- package/dist/server/mutations/store.d.ts.map +1 -1
- package/dist/server/mutations/store.js +6 -3
- package/dist/server/mutations/store.js.map +1 -1
- package/dist/server/mutations/verifier.d.ts +1 -1
- package/dist/server/mutations/verify.d.ts +11 -11
- package/dist/server/mutations/verify.d.ts.map +1 -1
- package/dist/server/oauth.d.ts +1 -59
- package/dist/server/oauth.js +3 -0
- package/dist/server/oauth.js.map +1 -1
- package/dist/server/passkey.d.ts.map +1 -1
- package/dist/server/passkey.js +3 -2
- package/dist/server/passkey.js.map +1 -1
- package/dist/server/provider.d.ts +1 -14
- package/dist/server/provider.d.ts.map +1 -1
- package/dist/server/provider.js +2 -0
- package/dist/server/provider.js.map +1 -1
- package/dist/server/providers.js +10 -0
- package/dist/server/providers.js.map +1 -1
- package/dist/server/ratelimit.d.ts +1 -22
- package/dist/server/ratelimit.js +3 -0
- package/dist/server/ratelimit.js.map +1 -1
- package/dist/server/redirects.d.ts +1 -10
- package/dist/server/redirects.js +2 -0
- package/dist/server/redirects.js.map +1 -1
- package/dist/server/refresh.d.ts +1 -37
- package/dist/server/refresh.js +5 -0
- package/dist/server/refresh.js.map +1 -1
- package/dist/server/sessions.d.ts +1 -28
- package/dist/server/sessions.js +5 -0
- package/dist/server/sessions.js.map +1 -1
- package/dist/server/signin.d.ts +1 -55
- package/dist/server/signin.js +2 -1
- package/dist/server/signin.js.map +1 -1
- package/dist/server/sso.d.ts +1 -348
- package/dist/server/sso.js +165 -18
- package/dist/server/sso.js.map +1 -1
- package/dist/server/templates.d.ts +1 -21
- package/dist/server/templates.js +1 -0
- package/dist/server/templates.js.map +1 -1
- package/dist/server/tokens.d.ts +1 -11
- package/dist/server/tokens.js +1 -0
- package/dist/server/tokens.js.map +1 -1
- package/dist/server/totp.d.ts +1 -23
- package/dist/server/totp.js +4 -2
- package/dist/server/totp.js.map +1 -1
- package/dist/server/types.d.ts +114 -77
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/types.js.map +1 -1
- package/dist/server/users.d.ts +1 -31
- package/dist/server/users.js +1 -0
- package/dist/server/users.js.map +1 -1
- package/dist/server/utils.d.ts +1 -27
- package/dist/server/utils.js +44 -2
- package/dist/server/utils.js.map +1 -1
- package/dist/server/version.d.ts +1 -1
- package/dist/server/version.js +1 -1
- package/dist/server/version.js.map +1 -1
- package/package.json +4 -5
- package/src/cli/bin.ts +5 -0
- package/src/cli/index.ts +22 -9
- package/src/cli/keys.ts +3 -0
- package/src/client/index.ts +36 -37
- package/src/component/_generated/api.ts +14 -0
- package/src/component/_generated/component.ts +2106 -9
- package/src/component/index.ts +3 -1
- package/src/component/model.ts +441 -0
- package/src/component/public/enterprise.ts +753 -0
- package/src/component/public/factors.ts +332 -0
- package/src/component/public/groups.ts +932 -0
- package/src/component/public/identity.ts +566 -0
- package/src/component/public/keys.ts +209 -0
- package/src/component/public/shared.ts +119 -0
- package/src/component/public.ts +5 -2965
- package/src/component/schema.ts +68 -63
- package/src/providers/sso.ts +1 -1
- package/src/server/auth.ts +413 -18
- package/src/server/cookies.ts +3 -0
- package/src/server/db.ts +3 -0
- package/src/server/device.ts +3 -1
- package/src/server/domains/core.ts +1071 -0
- package/src/server/domains/sso.ts +1749 -0
- package/src/server/enterpriseValidators.ts +93 -0
- package/src/server/factory.ts +2181 -0
- package/src/server/fx.ts +1 -0
- package/src/server/http.ts +529 -0
- package/src/server/identity.ts +18 -0
- package/src/server/index.ts +806 -40
- package/src/server/keys.ts +4 -0
- package/src/server/mutations/index.ts +1 -1
- package/src/server/mutations/oauth.ts +36 -8
- package/src/server/mutations/store.ts +6 -3
- package/src/server/oauth.ts +6 -0
- package/src/server/passkey.ts +3 -2
- package/src/server/provider.ts +2 -0
- package/src/server/providers.ts +20 -0
- package/src/server/ratelimit.ts +3 -0
- package/src/server/redirects.ts +2 -0
- package/src/server/refresh.ts +5 -0
- package/src/server/sessions.ts +5 -0
- package/src/server/signin.ts +1 -0
- package/src/server/sso.ts +259 -17
- package/src/server/templates.ts +1 -0
- package/src/server/tokens.ts +1 -0
- package/src/server/totp.ts +4 -2
- package/src/server/types.ts +178 -83
- package/src/server/users.ts +1 -0
- package/src/server/utils.ts +71 -1
- package/src/server/version.ts +1 -1
- package/dist/component/public.js.map +0 -1
- package/dist/component/server/implementation.d.ts +0 -1264
- package/dist/component/server/implementation.d.ts.map +0 -1
- package/dist/component/server/implementation.js +0 -2365
- package/dist/component/server/implementation.js.map +0 -1
- package/dist/server/cookies.d.ts.map +0 -1
- package/dist/server/db.d.ts.map +0 -1
- package/dist/server/device.d.ts.map +0 -1
- package/dist/server/implementation.d.ts +0 -1264
- package/dist/server/implementation.d.ts.map +0 -1
- package/dist/server/implementation.js +0 -2365
- package/dist/server/implementation.js.map +0 -1
- package/dist/server/keys.d.ts.map +0 -1
- package/dist/server/oauth.d.ts.map +0 -1
- package/dist/server/ratelimit.d.ts.map +0 -1
- package/dist/server/redirects.d.ts.map +0 -1
- package/dist/server/refresh.d.ts.map +0 -1
- package/dist/server/sessions.d.ts.map +0 -1
- package/dist/server/signin.d.ts.map +0 -1
- package/dist/server/sso.d.ts.map +0 -1
- package/dist/server/templates.d.ts.map +0 -1
- package/dist/server/tokens.d.ts.map +0 -1
- package/dist/server/totp.d.ts.map +0 -1
- package/dist/server/users.d.ts.map +0 -1
- package/dist/server/utils.d.ts.map +0 -1
- package/src/server/implementation.ts +0 -5336
package/src/component/public.ts
CHANGED
|
@@ -1,2965 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
// ============================================================================
|
|
7
|
-
// Tag normalization helpers
|
|
8
|
-
// ============================================================================
|
|
9
|
-
|
|
10
|
-
/** Validator for a single `{ key, value }` tag pair. */
|
|
11
|
-
const vTag = v.object({ key: v.string(), value: v.string() });
|
|
12
|
-
|
|
13
|
-
const TABLES = {
|
|
14
|
-
User: "User",
|
|
15
|
-
Session: "Session",
|
|
16
|
-
Account: "Account",
|
|
17
|
-
AuthVerifier: "AuthVerifier",
|
|
18
|
-
VerificationCode: "VerificationCode",
|
|
19
|
-
RefreshToken: "RefreshToken",
|
|
20
|
-
Passkey: "Passkey",
|
|
21
|
-
TotpFactor: "TotpFactor",
|
|
22
|
-
RateLimit: "RateLimit",
|
|
23
|
-
Group: "Group",
|
|
24
|
-
GroupTag: "GroupTag",
|
|
25
|
-
GroupMember: "GroupMember",
|
|
26
|
-
GroupInvite: "GroupInvite",
|
|
27
|
-
Enterprise: "Enterprise",
|
|
28
|
-
EnterpriseDomain: "EnterpriseDomain",
|
|
29
|
-
EnterpriseScimConfig: "EnterpriseScimConfig",
|
|
30
|
-
EnterpriseScimIdentity: "EnterpriseScimIdentity",
|
|
31
|
-
EnterpriseAuditEvent: "EnterpriseAuditEvent",
|
|
32
|
-
EnterpriseWebhookEndpoint: "EnterpriseWebhookEndpoint",
|
|
33
|
-
EnterpriseWebhookDelivery: "EnterpriseWebhookDelivery",
|
|
34
|
-
ApiKey: "ApiKey",
|
|
35
|
-
DeviceCode: "DeviceCode",
|
|
36
|
-
} as const;
|
|
37
|
-
|
|
38
|
-
const vInviteStatus = v.union(
|
|
39
|
-
v.literal("pending"),
|
|
40
|
-
v.literal("accepted"),
|
|
41
|
-
v.literal("revoked"),
|
|
42
|
-
v.literal("expired"),
|
|
43
|
-
);
|
|
44
|
-
|
|
45
|
-
const vDeviceStatus = v.union(
|
|
46
|
-
v.literal("pending"),
|
|
47
|
-
v.literal("authorized"),
|
|
48
|
-
v.literal("denied"),
|
|
49
|
-
);
|
|
50
|
-
|
|
51
|
-
const vEnterpriseStatus = v.union(
|
|
52
|
-
v.literal("draft"),
|
|
53
|
-
v.literal("active"),
|
|
54
|
-
v.literal("disabled"),
|
|
55
|
-
);
|
|
56
|
-
|
|
57
|
-
const vScimStatus = v.union(
|
|
58
|
-
v.literal("draft"),
|
|
59
|
-
v.literal("active"),
|
|
60
|
-
v.literal("disabled"),
|
|
61
|
-
);
|
|
62
|
-
|
|
63
|
-
const vScimResourceType = v.union(v.literal("user"), v.literal("group"));
|
|
64
|
-
|
|
65
|
-
const vAuditActorType = v.union(
|
|
66
|
-
v.literal("user"),
|
|
67
|
-
v.literal("system"),
|
|
68
|
-
v.literal("scim"),
|
|
69
|
-
v.literal("api_key"),
|
|
70
|
-
v.literal("webhook"),
|
|
71
|
-
);
|
|
72
|
-
|
|
73
|
-
const vAuditStatus = v.union(v.literal("success"), v.literal("failure"));
|
|
74
|
-
|
|
75
|
-
const vWebhookEndpointStatus = v.union(
|
|
76
|
-
v.literal("active"),
|
|
77
|
-
v.literal("disabled"),
|
|
78
|
-
);
|
|
79
|
-
|
|
80
|
-
const vWebhookDeliveryStatus = v.union(
|
|
81
|
-
v.literal("pending"),
|
|
82
|
-
v.literal("processing"),
|
|
83
|
-
v.literal("delivered"),
|
|
84
|
-
v.literal("failed"),
|
|
85
|
-
);
|
|
86
|
-
|
|
87
|
-
const vInviteTokenAcceptStatus = v.union(
|
|
88
|
-
v.literal("accepted"),
|
|
89
|
-
v.literal("already_accepted"),
|
|
90
|
-
);
|
|
91
|
-
|
|
92
|
-
const vMembershipStatus = v.union(
|
|
93
|
-
v.literal("joined"),
|
|
94
|
-
v.literal("already_joined"),
|
|
95
|
-
v.literal("not_applicable"),
|
|
96
|
-
);
|
|
97
|
-
|
|
98
|
-
const vApiKeyScope = v.object({
|
|
99
|
-
resource: v.string(),
|
|
100
|
-
actions: v.array(v.string()),
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
const vApiKeyRateLimit = v.object({
|
|
104
|
-
maxRequests: v.number(),
|
|
105
|
-
windowMs: v.number(),
|
|
106
|
-
});
|
|
107
|
-
|
|
108
|
-
const vApiKeyRateLimitState = v.object({
|
|
109
|
-
attemptsLeft: v.number(),
|
|
110
|
-
lastAttemptTime: v.number(),
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
function vDocMeta<T extends (typeof TABLES)[keyof typeof TABLES]>(
|
|
114
|
-
tableName: T,
|
|
115
|
-
) {
|
|
116
|
-
return {
|
|
117
|
-
_id: v.id(tableName),
|
|
118
|
-
_creationTime: v.number(),
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const vUserDoc = v.object({
|
|
123
|
-
...vDocMeta(TABLES.User),
|
|
124
|
-
name: v.optional(v.string()),
|
|
125
|
-
image: v.optional(v.string()),
|
|
126
|
-
email: v.optional(v.string()),
|
|
127
|
-
emailVerificationTime: v.optional(v.number()),
|
|
128
|
-
phone: v.optional(v.string()),
|
|
129
|
-
phoneVerificationTime: v.optional(v.number()),
|
|
130
|
-
isAnonymous: v.optional(v.boolean()),
|
|
131
|
-
extend: v.optional(v.any()),
|
|
132
|
-
});
|
|
133
|
-
|
|
134
|
-
const vSessionDoc = v.object({
|
|
135
|
-
...vDocMeta(TABLES.Session),
|
|
136
|
-
userId: v.id(TABLES.User),
|
|
137
|
-
expirationTime: v.number(),
|
|
138
|
-
});
|
|
139
|
-
|
|
140
|
-
const vAccountDoc = v.object({
|
|
141
|
-
...vDocMeta(TABLES.Account),
|
|
142
|
-
userId: v.id(TABLES.User),
|
|
143
|
-
provider: v.string(),
|
|
144
|
-
providerAccountId: v.string(),
|
|
145
|
-
secret: v.optional(v.string()),
|
|
146
|
-
emailVerified: v.optional(v.string()),
|
|
147
|
-
phoneVerified: v.optional(v.string()),
|
|
148
|
-
extend: v.optional(v.any()),
|
|
149
|
-
});
|
|
150
|
-
|
|
151
|
-
const vAuthVerifierDoc = v.object({
|
|
152
|
-
...vDocMeta(TABLES.AuthVerifier),
|
|
153
|
-
sessionId: v.optional(v.id(TABLES.Session)),
|
|
154
|
-
signature: v.optional(v.string()),
|
|
155
|
-
});
|
|
156
|
-
|
|
157
|
-
const vVerificationCodeDoc = v.object({
|
|
158
|
-
...vDocMeta(TABLES.VerificationCode),
|
|
159
|
-
accountId: v.id(TABLES.Account),
|
|
160
|
-
provider: v.string(),
|
|
161
|
-
code: v.string(),
|
|
162
|
-
expirationTime: v.number(),
|
|
163
|
-
verifier: v.optional(v.string()),
|
|
164
|
-
emailVerified: v.optional(v.string()),
|
|
165
|
-
phoneVerified: v.optional(v.string()),
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
const vRefreshTokenDoc = v.object({
|
|
169
|
-
...vDocMeta(TABLES.RefreshToken),
|
|
170
|
-
sessionId: v.id(TABLES.Session),
|
|
171
|
-
expirationTime: v.number(),
|
|
172
|
-
firstUsedTime: v.optional(v.number()),
|
|
173
|
-
parentRefreshTokenId: v.optional(v.id(TABLES.RefreshToken)),
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
const vPasskeyDoc = v.object({
|
|
177
|
-
...vDocMeta(TABLES.Passkey),
|
|
178
|
-
userId: v.id(TABLES.User),
|
|
179
|
-
credentialId: v.string(),
|
|
180
|
-
publicKey: v.bytes(),
|
|
181
|
-
algorithm: v.number(),
|
|
182
|
-
counter: v.number(),
|
|
183
|
-
transports: v.optional(v.array(v.string())),
|
|
184
|
-
deviceType: v.string(),
|
|
185
|
-
backedUp: v.boolean(),
|
|
186
|
-
name: v.optional(v.string()),
|
|
187
|
-
createdAt: v.number(),
|
|
188
|
-
lastUsedAt: v.optional(v.number()),
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
const vTotpFactorDoc = v.object({
|
|
192
|
-
...vDocMeta(TABLES.TotpFactor),
|
|
193
|
-
userId: v.id(TABLES.User),
|
|
194
|
-
secret: v.bytes(),
|
|
195
|
-
digits: v.number(),
|
|
196
|
-
period: v.number(),
|
|
197
|
-
verified: v.boolean(),
|
|
198
|
-
name: v.optional(v.string()),
|
|
199
|
-
createdAt: v.number(),
|
|
200
|
-
lastUsedAt: v.optional(v.number()),
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
const _vRateLimitDoc = v.object({
|
|
204
|
-
...vDocMeta(TABLES.RateLimit),
|
|
205
|
-
identifier: v.string(),
|
|
206
|
-
last_attempt_time: v.number(),
|
|
207
|
-
attempts_left: v.number(),
|
|
208
|
-
});
|
|
209
|
-
|
|
210
|
-
const vGroupDoc = v.object({
|
|
211
|
-
...vDocMeta(TABLES.Group),
|
|
212
|
-
name: v.string(),
|
|
213
|
-
slug: v.optional(v.string()),
|
|
214
|
-
type: v.optional(v.string()),
|
|
215
|
-
parentGroupId: v.optional(v.id(TABLES.Group)),
|
|
216
|
-
tags: v.optional(v.array(vTag)),
|
|
217
|
-
extend: v.optional(v.any()),
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
const vGroupMemberDoc = v.object({
|
|
221
|
-
...vDocMeta(TABLES.GroupMember),
|
|
222
|
-
groupId: v.id(TABLES.Group),
|
|
223
|
-
userId: v.id(TABLES.User),
|
|
224
|
-
role: v.optional(v.string()),
|
|
225
|
-
status: v.optional(v.string()),
|
|
226
|
-
extend: v.optional(v.any()),
|
|
227
|
-
});
|
|
228
|
-
|
|
229
|
-
const vGroupInviteDoc = v.object({
|
|
230
|
-
...vDocMeta(TABLES.GroupInvite),
|
|
231
|
-
groupId: v.optional(v.id(TABLES.Group)),
|
|
232
|
-
invitedByUserId: v.optional(v.id(TABLES.User)),
|
|
233
|
-
email: v.optional(v.string()),
|
|
234
|
-
tokenHash: v.string(),
|
|
235
|
-
role: v.optional(v.string()),
|
|
236
|
-
status: vInviteStatus,
|
|
237
|
-
expiresTime: v.optional(v.number()),
|
|
238
|
-
acceptedByUserId: v.optional(v.id(TABLES.User)),
|
|
239
|
-
acceptedTime: v.optional(v.number()),
|
|
240
|
-
extend: v.optional(v.any()),
|
|
241
|
-
});
|
|
242
|
-
|
|
243
|
-
const vApiKeyDoc = v.object({
|
|
244
|
-
...vDocMeta(TABLES.ApiKey),
|
|
245
|
-
userId: v.id(TABLES.User),
|
|
246
|
-
prefix: v.string(),
|
|
247
|
-
hashedKey: v.string(),
|
|
248
|
-
name: v.string(),
|
|
249
|
-
scopes: v.array(vApiKeyScope),
|
|
250
|
-
rateLimit: v.optional(vApiKeyRateLimit),
|
|
251
|
-
rateLimitState: v.optional(vApiKeyRateLimitState),
|
|
252
|
-
expiresAt: v.optional(v.number()),
|
|
253
|
-
lastUsedAt: v.optional(v.number()),
|
|
254
|
-
createdAt: v.number(),
|
|
255
|
-
revoked: v.boolean(),
|
|
256
|
-
});
|
|
257
|
-
|
|
258
|
-
const vDeviceCodeDoc = v.object({
|
|
259
|
-
...vDocMeta(TABLES.DeviceCode),
|
|
260
|
-
deviceCodeHash: v.string(),
|
|
261
|
-
userCode: v.string(),
|
|
262
|
-
expiresAt: v.number(),
|
|
263
|
-
interval: v.number(),
|
|
264
|
-
status: vDeviceStatus,
|
|
265
|
-
userId: v.optional(v.id(TABLES.User)),
|
|
266
|
-
sessionId: v.optional(v.id(TABLES.Session)),
|
|
267
|
-
lastPolledAt: v.optional(v.number()),
|
|
268
|
-
});
|
|
269
|
-
|
|
270
|
-
const vEnterpriseDoc = v.object({
|
|
271
|
-
...vDocMeta(TABLES.Enterprise),
|
|
272
|
-
groupId: v.id(TABLES.Group),
|
|
273
|
-
slug: v.optional(v.string()),
|
|
274
|
-
name: v.optional(v.string()),
|
|
275
|
-
status: vEnterpriseStatus,
|
|
276
|
-
config: v.optional(v.any()),
|
|
277
|
-
extend: v.optional(v.any()),
|
|
278
|
-
});
|
|
279
|
-
|
|
280
|
-
const vEnterpriseDomainDoc = v.object({
|
|
281
|
-
...vDocMeta(TABLES.EnterpriseDomain),
|
|
282
|
-
enterpriseId: v.id(TABLES.Enterprise),
|
|
283
|
-
groupId: v.id(TABLES.Group),
|
|
284
|
-
domain: v.string(),
|
|
285
|
-
isPrimary: v.boolean(),
|
|
286
|
-
verifiedAt: v.optional(v.number()),
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
const vEnterpriseScimConfigDoc = v.object({
|
|
290
|
-
...vDocMeta(TABLES.EnterpriseScimConfig),
|
|
291
|
-
enterpriseId: v.id(TABLES.Enterprise),
|
|
292
|
-
groupId: v.id(TABLES.Group),
|
|
293
|
-
status: vScimStatus,
|
|
294
|
-
basePath: v.string(),
|
|
295
|
-
tokenHash: v.string(),
|
|
296
|
-
lastRotatedAt: v.optional(v.number()),
|
|
297
|
-
deprovisionMode: v.optional(v.union(v.literal("soft"), v.literal("hard"))),
|
|
298
|
-
extend: v.optional(v.any()),
|
|
299
|
-
});
|
|
300
|
-
|
|
301
|
-
const vEnterpriseScimIdentityDoc = v.object({
|
|
302
|
-
...vDocMeta(TABLES.EnterpriseScimIdentity),
|
|
303
|
-
enterpriseId: v.id(TABLES.Enterprise),
|
|
304
|
-
groupId: v.id(TABLES.Group),
|
|
305
|
-
resourceType: vScimResourceType,
|
|
306
|
-
externalId: v.string(),
|
|
307
|
-
userId: v.optional(v.id(TABLES.User)),
|
|
308
|
-
mappedGroupId: v.optional(v.id(TABLES.Group)),
|
|
309
|
-
lastProvisionedAt: v.optional(v.number()),
|
|
310
|
-
active: v.optional(v.boolean()),
|
|
311
|
-
raw: v.optional(v.any()),
|
|
312
|
-
});
|
|
313
|
-
|
|
314
|
-
const vEnterpriseAuditEventDoc = v.object({
|
|
315
|
-
...vDocMeta(TABLES.EnterpriseAuditEvent),
|
|
316
|
-
enterpriseId: v.id(TABLES.Enterprise),
|
|
317
|
-
groupId: v.id(TABLES.Group),
|
|
318
|
-
eventType: v.string(),
|
|
319
|
-
actorType: vAuditActorType,
|
|
320
|
-
actorId: v.optional(v.string()),
|
|
321
|
-
subjectType: v.string(),
|
|
322
|
-
subjectId: v.optional(v.string()),
|
|
323
|
-
status: vAuditStatus,
|
|
324
|
-
occurredAt: v.number(),
|
|
325
|
-
requestId: v.optional(v.string()),
|
|
326
|
-
ip: v.optional(v.string()),
|
|
327
|
-
metadata: v.optional(v.any()),
|
|
328
|
-
});
|
|
329
|
-
|
|
330
|
-
const vEnterpriseWebhookEndpointDoc = v.object({
|
|
331
|
-
...vDocMeta(TABLES.EnterpriseWebhookEndpoint),
|
|
332
|
-
enterpriseId: v.id(TABLES.Enterprise),
|
|
333
|
-
groupId: v.id(TABLES.Group),
|
|
334
|
-
url: v.string(),
|
|
335
|
-
status: vWebhookEndpointStatus,
|
|
336
|
-
secretHash: v.string(),
|
|
337
|
-
subscriptions: v.array(v.string()),
|
|
338
|
-
createdByUserId: v.optional(v.id(TABLES.User)),
|
|
339
|
-
lastSuccessAt: v.optional(v.number()),
|
|
340
|
-
lastFailureAt: v.optional(v.number()),
|
|
341
|
-
failureCount: v.number(),
|
|
342
|
-
extend: v.optional(v.any()),
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
const vEnterpriseWebhookDeliveryDoc = v.object({
|
|
346
|
-
...vDocMeta(TABLES.EnterpriseWebhookDelivery),
|
|
347
|
-
enterpriseId: v.id(TABLES.Enterprise),
|
|
348
|
-
endpointId: v.id(TABLES.EnterpriseWebhookEndpoint),
|
|
349
|
-
auditEventId: v.optional(v.id(TABLES.EnterpriseAuditEvent)),
|
|
350
|
-
eventType: v.string(),
|
|
351
|
-
status: vWebhookDeliveryStatus,
|
|
352
|
-
attemptCount: v.number(),
|
|
353
|
-
nextAttemptAt: v.number(),
|
|
354
|
-
lastAttemptAt: v.optional(v.number()),
|
|
355
|
-
lastResponseStatus: v.optional(v.number()),
|
|
356
|
-
lastError: v.optional(v.string()),
|
|
357
|
-
payload: v.any(),
|
|
358
|
-
});
|
|
359
|
-
|
|
360
|
-
const vRateLimitResult = v.object({
|
|
361
|
-
...vDocMeta(TABLES.RateLimit),
|
|
362
|
-
identifier: v.string(),
|
|
363
|
-
last_attempt_time: v.number(),
|
|
364
|
-
attempts_left: v.number(),
|
|
365
|
-
attemptsLeft: v.number(),
|
|
366
|
-
lastAttemptTime: v.number(),
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
const vInviteAcceptByTokenResult = v.object({
|
|
370
|
-
inviteId: v.id(TABLES.GroupInvite),
|
|
371
|
-
groupId: v.union(v.id(TABLES.Group), v.null()),
|
|
372
|
-
memberId: v.optional(v.id(TABLES.GroupMember)),
|
|
373
|
-
inviteStatus: vInviteTokenAcceptStatus,
|
|
374
|
-
membershipStatus: vMembershipStatus,
|
|
375
|
-
});
|
|
376
|
-
|
|
377
|
-
const vPaginated = (item: any) =>
|
|
378
|
-
v.object({
|
|
379
|
-
items: v.array(item),
|
|
380
|
-
nextCursor: v.union(v.string(), v.null()),
|
|
381
|
-
});
|
|
382
|
-
|
|
383
|
-
type TagPair = { key: string; value: string };
|
|
384
|
-
|
|
385
|
-
/** Normalize a single tag: trim + lowercase key and value. */
|
|
386
|
-
function normalizeTag(tag: TagPair): TagPair {
|
|
387
|
-
return {
|
|
388
|
-
key: tag.key.trim().toLowerCase(),
|
|
389
|
-
value: tag.value.trim().toLowerCase(),
|
|
390
|
-
};
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
/**
|
|
394
|
-
* Normalize and deduplicate an array of tags.
|
|
395
|
-
* Deduplication is based on the normalized `key\0value` composite.
|
|
396
|
-
*/
|
|
397
|
-
function normalizeTags(tags: TagPair[]): TagPair[] {
|
|
398
|
-
const seen = new Set<string>();
|
|
399
|
-
const result: TagPair[] = [];
|
|
400
|
-
for (const raw of tags) {
|
|
401
|
-
const t = normalizeTag(raw);
|
|
402
|
-
const composite = `${t.key}\0${t.value}`;
|
|
403
|
-
if (!seen.has(composite)) {
|
|
404
|
-
seen.add(composite);
|
|
405
|
-
result.push(t);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
return result;
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
// ============================================================================
|
|
412
|
-
// Users
|
|
413
|
-
// ============================================================================
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* List users with optional filtering, sorting, and pagination.
|
|
417
|
-
*
|
|
418
|
-
* Returns `{ items, nextCursor }` — pass `nextCursor` back as `cursor`
|
|
419
|
-
* for the next page, or `null` when exhausted.
|
|
420
|
-
*/
|
|
421
|
-
export const userList = query({
|
|
422
|
-
args: {
|
|
423
|
-
where: v.optional(
|
|
424
|
-
v.object({
|
|
425
|
-
email: v.optional(v.string()),
|
|
426
|
-
phone: v.optional(v.string()),
|
|
427
|
-
isAnonymous: v.optional(v.boolean()),
|
|
428
|
-
name: v.optional(v.string()),
|
|
429
|
-
}),
|
|
430
|
-
),
|
|
431
|
-
limit: v.optional(v.number()),
|
|
432
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
433
|
-
orderBy: v.optional(
|
|
434
|
-
v.union(
|
|
435
|
-
v.literal("_creationTime"),
|
|
436
|
-
v.literal("name"),
|
|
437
|
-
v.literal("email"),
|
|
438
|
-
v.literal("phone"),
|
|
439
|
-
),
|
|
440
|
-
),
|
|
441
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
442
|
-
},
|
|
443
|
-
returns: vPaginated(vUserDoc),
|
|
444
|
-
handler: async (ctx, args) => {
|
|
445
|
-
const where = args.where ?? {};
|
|
446
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
447
|
-
const order = args.order ?? "desc";
|
|
448
|
-
|
|
449
|
-
// Pick index based on where fields
|
|
450
|
-
let q;
|
|
451
|
-
if (where.email !== undefined) {
|
|
452
|
-
q = ctx.db
|
|
453
|
-
.query("User")
|
|
454
|
-
.withIndex("email", (idx) => idx.eq("email", where.email!));
|
|
455
|
-
} else if (where.phone !== undefined) {
|
|
456
|
-
q = ctx.db
|
|
457
|
-
.query("User")
|
|
458
|
-
.withIndex("phone", (idx) => idx.eq("phone", where.phone!));
|
|
459
|
-
} else {
|
|
460
|
-
q = ctx.db.query("User");
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
// Apply remaining filters
|
|
464
|
-
if (where.isAnonymous !== undefined) {
|
|
465
|
-
q = q.filter((f) => f.eq(f.field("isAnonymous"), where.isAnonymous!));
|
|
466
|
-
}
|
|
467
|
-
if (where.name !== undefined) {
|
|
468
|
-
q = q.filter((f) => f.eq(f.field("name"), where.name!));
|
|
469
|
-
}
|
|
470
|
-
// email/phone filters when not used as index
|
|
471
|
-
if (where.email !== undefined && where.phone !== undefined) {
|
|
472
|
-
q = q.filter((f) => f.eq(f.field("phone"), where.phone!));
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
q = q.order(order);
|
|
476
|
-
|
|
477
|
-
// Cursor-based pagination: skip past the cursor ID
|
|
478
|
-
const all = await q.collect();
|
|
479
|
-
let startIdx = 0;
|
|
480
|
-
if (args.cursor) {
|
|
481
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
482
|
-
if (cursorIdx !== -1) {
|
|
483
|
-
startIdx = cursorIdx + 1;
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
487
|
-
const hasMore = page.length > limit;
|
|
488
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
489
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
490
|
-
return { items, nextCursor };
|
|
491
|
-
},
|
|
492
|
-
});
|
|
493
|
-
|
|
494
|
-
/** Retrieve a user by their document ID. */
|
|
495
|
-
export const userGetById = query({
|
|
496
|
-
args: { userId: v.id("User") },
|
|
497
|
-
returns: v.union(vUserDoc, v.null()),
|
|
498
|
-
handler: async (ctx, { userId }) => {
|
|
499
|
-
return await ctx.db.get("User", userId);
|
|
500
|
-
},
|
|
501
|
-
});
|
|
502
|
-
|
|
503
|
-
/**
|
|
504
|
-
* Find a user by their verified email address. Returns `null` if no user
|
|
505
|
-
* has this email verified, or if multiple users share the same verified email
|
|
506
|
-
* (ambiguous — should not happen in normal operation).
|
|
507
|
-
*/
|
|
508
|
-
export const userFindByVerifiedEmail = query({
|
|
509
|
-
args: { email: v.string() },
|
|
510
|
-
returns: v.union(vUserDoc, v.null()),
|
|
511
|
-
handler: async (ctx, { email }) => {
|
|
512
|
-
const users = await ctx.db
|
|
513
|
-
.query("User")
|
|
514
|
-
.withIndex("email", (q) => q.eq("email", email))
|
|
515
|
-
.filter((q) => q.neq(q.field("emailVerificationTime"), undefined))
|
|
516
|
-
.take(2);
|
|
517
|
-
return users.length === 1 ? users[0] : null;
|
|
518
|
-
},
|
|
519
|
-
});
|
|
520
|
-
|
|
521
|
-
/**
|
|
522
|
-
* Find a user by their verified phone number. Returns `null` if no user
|
|
523
|
-
* has this phone verified, or if multiple users share the same verified phone
|
|
524
|
-
* (ambiguous — should not happen in normal operation).
|
|
525
|
-
*/
|
|
526
|
-
export const userFindByVerifiedPhone = query({
|
|
527
|
-
args: { phone: v.string() },
|
|
528
|
-
returns: v.union(vUserDoc, v.null()),
|
|
529
|
-
handler: async (ctx, { phone }) => {
|
|
530
|
-
const users = await ctx.db
|
|
531
|
-
.query("User")
|
|
532
|
-
.withIndex("phone", (q) => q.eq("phone", phone))
|
|
533
|
-
.filter((q) => q.neq(q.field("phoneVerificationTime"), undefined))
|
|
534
|
-
.take(2);
|
|
535
|
-
return users.length === 1 ? users[0] : null;
|
|
536
|
-
},
|
|
537
|
-
});
|
|
538
|
-
|
|
539
|
-
/** Insert a new user document. */
|
|
540
|
-
export const userInsert = mutation({
|
|
541
|
-
args: { data: v.any() },
|
|
542
|
-
returns: v.id("User"),
|
|
543
|
-
handler: async (ctx, { data }) => {
|
|
544
|
-
return await ctx.db.insert("User", data);
|
|
545
|
-
},
|
|
546
|
-
});
|
|
547
|
-
|
|
548
|
-
/** Insert a new user or update an existing one. */
|
|
549
|
-
export const userUpsert = mutation({
|
|
550
|
-
args: { userId: v.optional(v.id("User")), data: v.any() },
|
|
551
|
-
returns: v.id("User"),
|
|
552
|
-
handler: async (ctx, { userId, data }) => {
|
|
553
|
-
if (userId !== undefined) {
|
|
554
|
-
await ctx.db.patch("User", userId, data);
|
|
555
|
-
return userId;
|
|
556
|
-
}
|
|
557
|
-
return await ctx.db.insert("User", data);
|
|
558
|
-
},
|
|
559
|
-
});
|
|
560
|
-
|
|
561
|
-
/** Patch an existing user document with partial data. */
|
|
562
|
-
export const userPatch = mutation({
|
|
563
|
-
args: { userId: v.id("User"), data: v.any() },
|
|
564
|
-
returns: v.null(),
|
|
565
|
-
handler: async (ctx, { userId, data }) => {
|
|
566
|
-
await ctx.db.patch("User", userId, data);
|
|
567
|
-
return null;
|
|
568
|
-
},
|
|
569
|
-
});
|
|
570
|
-
|
|
571
|
-
/** Delete a user document by ID. No-op if the user does not exist. */
|
|
572
|
-
export const userDelete = mutation({
|
|
573
|
-
args: { userId: v.id("User") },
|
|
574
|
-
returns: v.null(),
|
|
575
|
-
handler: async (ctx, { userId }) => {
|
|
576
|
-
if ((await ctx.db.get("User", userId)) !== null) {
|
|
577
|
-
await ctx.db.delete("User", userId);
|
|
578
|
-
}
|
|
579
|
-
return null;
|
|
580
|
-
},
|
|
581
|
-
});
|
|
582
|
-
|
|
583
|
-
// ============================================================================
|
|
584
|
-
// Accounts
|
|
585
|
-
// ============================================================================
|
|
586
|
-
|
|
587
|
-
/** List all accounts for a user. */
|
|
588
|
-
export const accountListByUser = query({
|
|
589
|
-
args: { userId: v.id("User") },
|
|
590
|
-
returns: v.array(vAccountDoc),
|
|
591
|
-
handler: async (ctx, { userId }) => {
|
|
592
|
-
return await ctx.db
|
|
593
|
-
.query("Account")
|
|
594
|
-
.withIndex("user_id_provider", (q) => q.eq("userId", userId as any))
|
|
595
|
-
.collect();
|
|
596
|
-
},
|
|
597
|
-
});
|
|
598
|
-
|
|
599
|
-
/** Look up an account by provider and provider-specific account ID. */
|
|
600
|
-
export const accountGet = query({
|
|
601
|
-
args: { provider: v.string(), providerAccountId: v.string() },
|
|
602
|
-
returns: v.union(vAccountDoc, v.null()),
|
|
603
|
-
handler: async (ctx, { provider, providerAccountId }) => {
|
|
604
|
-
return await ctx.db
|
|
605
|
-
.query("Account")
|
|
606
|
-
.withIndex("provider_account_id", (q) =>
|
|
607
|
-
q.eq("provider", provider).eq("providerAccountId", providerAccountId),
|
|
608
|
-
)
|
|
609
|
-
.unique();
|
|
610
|
-
},
|
|
611
|
-
});
|
|
612
|
-
|
|
613
|
-
/** Retrieve an account by its document ID. */
|
|
614
|
-
export const accountGetById = query({
|
|
615
|
-
args: { accountId: v.id("Account") },
|
|
616
|
-
returns: v.union(vAccountDoc, v.null()),
|
|
617
|
-
handler: async (ctx, { accountId }) => {
|
|
618
|
-
return await ctx.db.get("Account", accountId);
|
|
619
|
-
},
|
|
620
|
-
});
|
|
621
|
-
|
|
622
|
-
/** Create a new account linking a user to an auth provider. */
|
|
623
|
-
export const accountInsert = mutation({
|
|
624
|
-
args: {
|
|
625
|
-
userId: v.id("User"),
|
|
626
|
-
provider: v.string(),
|
|
627
|
-
providerAccountId: v.string(),
|
|
628
|
-
secret: v.optional(v.string()),
|
|
629
|
-
extend: v.optional(v.any()),
|
|
630
|
-
},
|
|
631
|
-
returns: v.id("Account"),
|
|
632
|
-
handler: async (ctx, args) => {
|
|
633
|
-
return await ctx.db.insert("Account", args as any);
|
|
634
|
-
},
|
|
635
|
-
});
|
|
636
|
-
|
|
637
|
-
/** Patch an existing account document with partial data. */
|
|
638
|
-
export const accountPatch = mutation({
|
|
639
|
-
args: { accountId: v.id("Account"), data: v.any() },
|
|
640
|
-
returns: v.null(),
|
|
641
|
-
handler: async (ctx, { accountId, data }) => {
|
|
642
|
-
await ctx.db.patch("Account", accountId, data);
|
|
643
|
-
return null;
|
|
644
|
-
},
|
|
645
|
-
});
|
|
646
|
-
|
|
647
|
-
/** Delete an account document. */
|
|
648
|
-
export const accountDelete = mutation({
|
|
649
|
-
args: { accountId: v.id("Account") },
|
|
650
|
-
returns: v.null(),
|
|
651
|
-
handler: async (ctx, { accountId }) => {
|
|
652
|
-
await ctx.db.delete("Account", accountId);
|
|
653
|
-
return null;
|
|
654
|
-
},
|
|
655
|
-
});
|
|
656
|
-
|
|
657
|
-
// ============================================================================
|
|
658
|
-
// Sessions
|
|
659
|
-
// ============================================================================
|
|
660
|
-
|
|
661
|
-
/**
|
|
662
|
-
* List sessions with optional filtering and pagination.
|
|
663
|
-
*
|
|
664
|
-
* Returns `{ items, nextCursor }`.
|
|
665
|
-
*/
|
|
666
|
-
export const sessionList = query({
|
|
667
|
-
args: {
|
|
668
|
-
where: v.optional(
|
|
669
|
-
v.object({
|
|
670
|
-
userId: v.optional(v.id("User")),
|
|
671
|
-
}),
|
|
672
|
-
),
|
|
673
|
-
limit: v.optional(v.number()),
|
|
674
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
675
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
676
|
-
},
|
|
677
|
-
returns: vPaginated(vSessionDoc),
|
|
678
|
-
handler: async (ctx, args) => {
|
|
679
|
-
const where = args.where ?? {};
|
|
680
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
681
|
-
const order = args.order ?? "desc";
|
|
682
|
-
|
|
683
|
-
let q;
|
|
684
|
-
if (where.userId !== undefined) {
|
|
685
|
-
q = ctx.db
|
|
686
|
-
.query("Session")
|
|
687
|
-
.withIndex("user_id", (idx) => idx.eq("userId", where.userId!));
|
|
688
|
-
} else {
|
|
689
|
-
q = ctx.db.query("Session");
|
|
690
|
-
}
|
|
691
|
-
|
|
692
|
-
q = q.order(order);
|
|
693
|
-
|
|
694
|
-
const all = await q.collect();
|
|
695
|
-
let startIdx = 0;
|
|
696
|
-
if (args.cursor) {
|
|
697
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
698
|
-
if (cursorIdx !== -1) {
|
|
699
|
-
startIdx = cursorIdx + 1;
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
703
|
-
const hasMore = page.length > limit;
|
|
704
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
705
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
706
|
-
return { items, nextCursor };
|
|
707
|
-
},
|
|
708
|
-
});
|
|
709
|
-
|
|
710
|
-
/** Create a new session for a user with an expiration time. */
|
|
711
|
-
export const sessionCreate = mutation({
|
|
712
|
-
args: { userId: v.id("User"), expirationTime: v.number() },
|
|
713
|
-
returns: v.id("Session"),
|
|
714
|
-
handler: async (ctx, { userId, expirationTime }) => {
|
|
715
|
-
return await ctx.db.insert("Session", {
|
|
716
|
-
userId: userId as any,
|
|
717
|
-
expirationTime,
|
|
718
|
-
});
|
|
719
|
-
},
|
|
720
|
-
});
|
|
721
|
-
|
|
722
|
-
/** Retrieve a session by its document ID. */
|
|
723
|
-
export const sessionGetById = query({
|
|
724
|
-
args: { sessionId: v.id("Session") },
|
|
725
|
-
returns: v.union(vSessionDoc, v.null()),
|
|
726
|
-
handler: async (ctx, { sessionId }) => {
|
|
727
|
-
return await ctx.db.get("Session", sessionId);
|
|
728
|
-
},
|
|
729
|
-
});
|
|
730
|
-
|
|
731
|
-
/** Delete a session. No-op if the session does not exist. */
|
|
732
|
-
export const sessionDelete = mutation({
|
|
733
|
-
args: { sessionId: v.id("Session") },
|
|
734
|
-
returns: v.null(),
|
|
735
|
-
handler: async (ctx, { sessionId }) => {
|
|
736
|
-
if ((await ctx.db.get("Session", sessionId)) !== null) {
|
|
737
|
-
await ctx.db.delete("Session", sessionId);
|
|
738
|
-
}
|
|
739
|
-
return null;
|
|
740
|
-
},
|
|
741
|
-
});
|
|
742
|
-
|
|
743
|
-
/** List all sessions for a user. */
|
|
744
|
-
export const sessionListByUser = query({
|
|
745
|
-
args: { userId: v.id("User") },
|
|
746
|
-
returns: v.array(vSessionDoc),
|
|
747
|
-
handler: async (ctx, { userId }) => {
|
|
748
|
-
return await ctx.db
|
|
749
|
-
.query("Session")
|
|
750
|
-
.withIndex("user_id", (q) => q.eq("userId", userId as any))
|
|
751
|
-
.collect();
|
|
752
|
-
},
|
|
753
|
-
});
|
|
754
|
-
|
|
755
|
-
// ============================================================================
|
|
756
|
-
// Verifiers
|
|
757
|
-
// ============================================================================
|
|
758
|
-
|
|
759
|
-
/** Create a new PKCE verifier, optionally linked to a session. */
|
|
760
|
-
export const verifierCreate = mutation({
|
|
761
|
-
args: { sessionId: v.optional(v.id("Session")) },
|
|
762
|
-
returns: v.id("AuthVerifier"),
|
|
763
|
-
handler: async (ctx, { sessionId }) => {
|
|
764
|
-
return await ctx.db.insert("AuthVerifier", { sessionId: sessionId as any });
|
|
765
|
-
},
|
|
766
|
-
});
|
|
767
|
-
|
|
768
|
-
/** Retrieve a verifier by its document ID. */
|
|
769
|
-
export const verifierGetById = query({
|
|
770
|
-
args: { verifierId: v.id("AuthVerifier") },
|
|
771
|
-
returns: v.union(vAuthVerifierDoc, v.null()),
|
|
772
|
-
handler: async (ctx, { verifierId }) => {
|
|
773
|
-
return await ctx.db.get("AuthVerifier", verifierId);
|
|
774
|
-
},
|
|
775
|
-
});
|
|
776
|
-
|
|
777
|
-
/** Look up a verifier by its cryptographic signature. */
|
|
778
|
-
export const verifierGetBySignature = query({
|
|
779
|
-
args: { signature: v.string() },
|
|
780
|
-
returns: v.union(vAuthVerifierDoc, v.null()),
|
|
781
|
-
handler: async (ctx, { signature }) => {
|
|
782
|
-
return await ctx.db
|
|
783
|
-
.query("AuthVerifier")
|
|
784
|
-
.withIndex("signature", (q) => q.eq("signature", signature))
|
|
785
|
-
.unique();
|
|
786
|
-
},
|
|
787
|
-
});
|
|
788
|
-
|
|
789
|
-
/** Patch a verifier document with partial data. */
|
|
790
|
-
export const verifierPatch = mutation({
|
|
791
|
-
args: { verifierId: v.id("AuthVerifier"), data: v.any() },
|
|
792
|
-
returns: v.null(),
|
|
793
|
-
handler: async (ctx, { verifierId, data }) => {
|
|
794
|
-
await ctx.db.patch("AuthVerifier", verifierId, data);
|
|
795
|
-
return null;
|
|
796
|
-
},
|
|
797
|
-
});
|
|
798
|
-
|
|
799
|
-
/** Delete a verifier document. */
|
|
800
|
-
export const verifierDelete = mutation({
|
|
801
|
-
args: { verifierId: v.id("AuthVerifier") },
|
|
802
|
-
returns: v.null(),
|
|
803
|
-
handler: async (ctx, { verifierId }) => {
|
|
804
|
-
await ctx.db.delete("AuthVerifier", verifierId);
|
|
805
|
-
return null;
|
|
806
|
-
},
|
|
807
|
-
});
|
|
808
|
-
|
|
809
|
-
// ============================================================================
|
|
810
|
-
// Verification Codes
|
|
811
|
-
// ============================================================================
|
|
812
|
-
|
|
813
|
-
/** Find a verification code by its associated account ID. */
|
|
814
|
-
export const verificationCodeGetByAccountId = query({
|
|
815
|
-
args: { accountId: v.id("Account") },
|
|
816
|
-
returns: v.union(vVerificationCodeDoc, v.null()),
|
|
817
|
-
handler: async (ctx, { accountId }) => {
|
|
818
|
-
return await ctx.db
|
|
819
|
-
.query("VerificationCode")
|
|
820
|
-
.withIndex("account_id", (q) => q.eq("accountId", accountId as any))
|
|
821
|
-
.unique();
|
|
822
|
-
},
|
|
823
|
-
});
|
|
824
|
-
|
|
825
|
-
/** Find a verification code by its code string. */
|
|
826
|
-
export const verificationCodeGetByCode = query({
|
|
827
|
-
args: { code: v.string() },
|
|
828
|
-
returns: v.union(vVerificationCodeDoc, v.null()),
|
|
829
|
-
handler: async (ctx, { code }) => {
|
|
830
|
-
return await ctx.db
|
|
831
|
-
.query("VerificationCode")
|
|
832
|
-
.withIndex("code", (q) => q.eq("code", code))
|
|
833
|
-
.unique();
|
|
834
|
-
},
|
|
835
|
-
});
|
|
836
|
-
|
|
837
|
-
/** Create a new verification code for OTP, magic link, or OAuth flows. */
|
|
838
|
-
export const verificationCodeCreate = mutation({
|
|
839
|
-
args: {
|
|
840
|
-
accountId: v.id("Account"),
|
|
841
|
-
provider: v.string(),
|
|
842
|
-
code: v.string(),
|
|
843
|
-
expirationTime: v.number(),
|
|
844
|
-
verifier: v.optional(v.string()),
|
|
845
|
-
emailVerified: v.optional(v.string()),
|
|
846
|
-
phoneVerified: v.optional(v.string()),
|
|
847
|
-
},
|
|
848
|
-
returns: v.id("VerificationCode"),
|
|
849
|
-
handler: async (ctx, args) => {
|
|
850
|
-
return await ctx.db.insert("VerificationCode", args as any);
|
|
851
|
-
},
|
|
852
|
-
});
|
|
853
|
-
|
|
854
|
-
/** Delete a verification code document. */
|
|
855
|
-
export const verificationCodeDelete = mutation({
|
|
856
|
-
args: { verificationCodeId: v.id("VerificationCode") },
|
|
857
|
-
returns: v.null(),
|
|
858
|
-
handler: async (ctx, { verificationCodeId }) => {
|
|
859
|
-
await ctx.db.delete("VerificationCode", verificationCodeId);
|
|
860
|
-
return null;
|
|
861
|
-
},
|
|
862
|
-
});
|
|
863
|
-
|
|
864
|
-
// ============================================================================
|
|
865
|
-
// Refresh Tokens
|
|
866
|
-
// ============================================================================
|
|
867
|
-
|
|
868
|
-
/** Create a new refresh token for a session. */
|
|
869
|
-
export const refreshTokenCreate = mutation({
|
|
870
|
-
args: {
|
|
871
|
-
sessionId: v.id("Session"),
|
|
872
|
-
expirationTime: v.number(),
|
|
873
|
-
parentRefreshTokenId: v.optional(v.id("RefreshToken")),
|
|
874
|
-
},
|
|
875
|
-
returns: v.id("RefreshToken"),
|
|
876
|
-
handler: async (ctx, args) => {
|
|
877
|
-
return await ctx.db.insert("RefreshToken", args as any);
|
|
878
|
-
},
|
|
879
|
-
});
|
|
880
|
-
|
|
881
|
-
/** Retrieve a refresh token by its document ID. */
|
|
882
|
-
export const refreshTokenGetById = query({
|
|
883
|
-
args: { refreshTokenId: v.id("RefreshToken") },
|
|
884
|
-
returns: v.union(vRefreshTokenDoc, v.null()),
|
|
885
|
-
handler: async (ctx, { refreshTokenId }) => {
|
|
886
|
-
return await ctx.db.get("RefreshToken", refreshTokenId);
|
|
887
|
-
},
|
|
888
|
-
});
|
|
889
|
-
|
|
890
|
-
/** Patch a refresh token document with partial data. */
|
|
891
|
-
export const refreshTokenPatch = mutation({
|
|
892
|
-
args: { refreshTokenId: v.id("RefreshToken"), data: v.any() },
|
|
893
|
-
returns: v.null(),
|
|
894
|
-
handler: async (ctx, { refreshTokenId, data }) => {
|
|
895
|
-
await ctx.db.patch("RefreshToken", refreshTokenId, data);
|
|
896
|
-
return null;
|
|
897
|
-
},
|
|
898
|
-
});
|
|
899
|
-
|
|
900
|
-
/** Get child tokens that were created by exchanging a specific parent token. */
|
|
901
|
-
export const refreshTokenGetChildren = query({
|
|
902
|
-
args: {
|
|
903
|
-
sessionId: v.id("Session"),
|
|
904
|
-
parentRefreshTokenId: v.id("RefreshToken"),
|
|
905
|
-
},
|
|
906
|
-
returns: v.array(vRefreshTokenDoc),
|
|
907
|
-
handler: async (ctx, { sessionId, parentRefreshTokenId }) => {
|
|
908
|
-
return await ctx.db
|
|
909
|
-
.query("RefreshToken")
|
|
910
|
-
.withIndex("session_id_parent_refresh_token_id", (q) =>
|
|
911
|
-
q
|
|
912
|
-
.eq("sessionId", sessionId as any)
|
|
913
|
-
.eq("parentRefreshTokenId", parentRefreshTokenId as any),
|
|
914
|
-
)
|
|
915
|
-
.collect();
|
|
916
|
-
},
|
|
917
|
-
});
|
|
918
|
-
|
|
919
|
-
/** List all refresh tokens for a session. */
|
|
920
|
-
export const refreshTokenListBySession = query({
|
|
921
|
-
args: { sessionId: v.id("Session") },
|
|
922
|
-
returns: v.array(vRefreshTokenDoc),
|
|
923
|
-
handler: async (ctx, { sessionId }) => {
|
|
924
|
-
return await ctx.db
|
|
925
|
-
.query("RefreshToken")
|
|
926
|
-
.withIndex("session_id_parent_refresh_token_id", (q) =>
|
|
927
|
-
q.eq("sessionId", sessionId as any),
|
|
928
|
-
)
|
|
929
|
-
.collect();
|
|
930
|
-
},
|
|
931
|
-
});
|
|
932
|
-
|
|
933
|
-
/** Delete all refresh tokens for a session. */
|
|
934
|
-
export const refreshTokenDeleteAll = mutation({
|
|
935
|
-
args: { sessionId: v.id("Session") },
|
|
936
|
-
returns: v.null(),
|
|
937
|
-
handler: async (ctx, { sessionId }) => {
|
|
938
|
-
const tokens = await ctx.db
|
|
939
|
-
.query("RefreshToken")
|
|
940
|
-
.withIndex("session_id_parent_refresh_token_id", (q) =>
|
|
941
|
-
q.eq("sessionId", sessionId as any),
|
|
942
|
-
)
|
|
943
|
-
.collect();
|
|
944
|
-
await Promise.all(
|
|
945
|
-
tokens.map((token) => ctx.db.delete("RefreshToken", token._id)),
|
|
946
|
-
);
|
|
947
|
-
return null;
|
|
948
|
-
},
|
|
949
|
-
});
|
|
950
|
-
|
|
951
|
-
/** Get the active (unused) refresh token for a session. */
|
|
952
|
-
export const refreshTokenGetActive = query({
|
|
953
|
-
args: { sessionId: v.id("Session") },
|
|
954
|
-
returns: v.union(vRefreshTokenDoc, v.null()),
|
|
955
|
-
handler: async (ctx, { sessionId }) => {
|
|
956
|
-
return await ctx.db
|
|
957
|
-
.query("RefreshToken")
|
|
958
|
-
.withIndex("session_id", (q) => q.eq("sessionId", sessionId as any))
|
|
959
|
-
.filter((q) => q.eq(q.field("firstUsedTime"), undefined))
|
|
960
|
-
.order("desc")
|
|
961
|
-
.first();
|
|
962
|
-
},
|
|
963
|
-
});
|
|
964
|
-
|
|
965
|
-
// ============================================================================
|
|
966
|
-
// Passkeys
|
|
967
|
-
// ============================================================================
|
|
968
|
-
|
|
969
|
-
/** Store a new passkey credential for a user. */
|
|
970
|
-
export const passkeyInsert = mutation({
|
|
971
|
-
args: {
|
|
972
|
-
userId: v.id("User"),
|
|
973
|
-
credentialId: v.string(),
|
|
974
|
-
publicKey: v.bytes(),
|
|
975
|
-
algorithm: v.number(),
|
|
976
|
-
counter: v.number(),
|
|
977
|
-
transports: v.optional(v.array(v.string())),
|
|
978
|
-
deviceType: v.string(),
|
|
979
|
-
backedUp: v.boolean(),
|
|
980
|
-
name: v.optional(v.string()),
|
|
981
|
-
createdAt: v.number(),
|
|
982
|
-
},
|
|
983
|
-
returns: v.id("Passkey"),
|
|
984
|
-
handler: async (ctx, args) => {
|
|
985
|
-
return await ctx.db.insert("Passkey", args);
|
|
986
|
-
},
|
|
987
|
-
});
|
|
988
|
-
|
|
989
|
-
/** Look up a passkey by its credential ID. */
|
|
990
|
-
export const passkeyGetByCredentialId = query({
|
|
991
|
-
args: { credentialId: v.string() },
|
|
992
|
-
returns: v.union(vPasskeyDoc, v.null()),
|
|
993
|
-
handler: async (ctx, { credentialId }) => {
|
|
994
|
-
return await ctx.db
|
|
995
|
-
.query("Passkey")
|
|
996
|
-
.withIndex("credential_id", (q) => q.eq("credentialId", credentialId))
|
|
997
|
-
.unique();
|
|
998
|
-
},
|
|
999
|
-
});
|
|
1000
|
-
|
|
1001
|
-
/** List all passkeys for a user. */
|
|
1002
|
-
export const passkeyListByUserId = query({
|
|
1003
|
-
args: { userId: v.id("User") },
|
|
1004
|
-
returns: v.array(vPasskeyDoc),
|
|
1005
|
-
handler: async (ctx, { userId }) => {
|
|
1006
|
-
return await ctx.db
|
|
1007
|
-
.query("Passkey")
|
|
1008
|
-
.withIndex("user_id", (q) => q.eq("userId", userId))
|
|
1009
|
-
.collect();
|
|
1010
|
-
},
|
|
1011
|
-
});
|
|
1012
|
-
|
|
1013
|
-
/** Update a passkey's counter and last used timestamp after authentication. */
|
|
1014
|
-
export const passkeyUpdateCounter = mutation({
|
|
1015
|
-
args: {
|
|
1016
|
-
passkeyId: v.id("Passkey"),
|
|
1017
|
-
counter: v.number(),
|
|
1018
|
-
lastUsedAt: v.number(),
|
|
1019
|
-
},
|
|
1020
|
-
returns: v.null(),
|
|
1021
|
-
handler: async (ctx, { passkeyId, counter, lastUsedAt }) => {
|
|
1022
|
-
await ctx.db.patch("Passkey", passkeyId, { counter, lastUsedAt });
|
|
1023
|
-
return null;
|
|
1024
|
-
},
|
|
1025
|
-
});
|
|
1026
|
-
|
|
1027
|
-
/** Update a passkey's metadata (name). */
|
|
1028
|
-
export const passkeyUpdateMeta = mutation({
|
|
1029
|
-
args: { passkeyId: v.id("Passkey"), data: v.any() },
|
|
1030
|
-
returns: v.null(),
|
|
1031
|
-
handler: async (ctx, { passkeyId, data }) => {
|
|
1032
|
-
await ctx.db.patch("Passkey", passkeyId, data);
|
|
1033
|
-
return null;
|
|
1034
|
-
},
|
|
1035
|
-
});
|
|
1036
|
-
|
|
1037
|
-
/** Delete a passkey credential. */
|
|
1038
|
-
export const passkeyDelete = mutation({
|
|
1039
|
-
args: { passkeyId: v.id("Passkey") },
|
|
1040
|
-
returns: v.null(),
|
|
1041
|
-
handler: async (ctx, { passkeyId }) => {
|
|
1042
|
-
await ctx.db.delete("Passkey", passkeyId);
|
|
1043
|
-
return null;
|
|
1044
|
-
},
|
|
1045
|
-
});
|
|
1046
|
-
|
|
1047
|
-
// ============================================================================
|
|
1048
|
-
// TOTP Two-Factor Authentication
|
|
1049
|
-
// ============================================================================
|
|
1050
|
-
|
|
1051
|
-
/** Store a new TOTP enrollment for a user. */
|
|
1052
|
-
export const totpInsert = mutation({
|
|
1053
|
-
args: {
|
|
1054
|
-
userId: v.id("User"),
|
|
1055
|
-
secret: v.bytes(),
|
|
1056
|
-
digits: v.number(),
|
|
1057
|
-
period: v.number(),
|
|
1058
|
-
verified: v.boolean(),
|
|
1059
|
-
name: v.optional(v.string()),
|
|
1060
|
-
createdAt: v.number(),
|
|
1061
|
-
},
|
|
1062
|
-
returns: v.id("TotpFactor"),
|
|
1063
|
-
handler: async (ctx, args) => {
|
|
1064
|
-
return await ctx.db.insert("TotpFactor", args);
|
|
1065
|
-
},
|
|
1066
|
-
});
|
|
1067
|
-
|
|
1068
|
-
/** Get a verified TOTP enrollment for a user (returns first match). */
|
|
1069
|
-
export const totpGetVerifiedByUserId = query({
|
|
1070
|
-
args: { userId: v.id("User") },
|
|
1071
|
-
returns: v.union(vTotpFactorDoc, v.null()),
|
|
1072
|
-
handler: async (ctx, { userId }) => {
|
|
1073
|
-
return await ctx.db
|
|
1074
|
-
.query("TotpFactor")
|
|
1075
|
-
.withIndex("user_id", (q) => q.eq("userId", userId))
|
|
1076
|
-
.filter((q) => q.eq(q.field("verified"), true))
|
|
1077
|
-
.first();
|
|
1078
|
-
},
|
|
1079
|
-
});
|
|
1080
|
-
|
|
1081
|
-
/** List all TOTP enrollments for a user. */
|
|
1082
|
-
export const totpListByUserId = query({
|
|
1083
|
-
args: { userId: v.id("User") },
|
|
1084
|
-
returns: v.array(vTotpFactorDoc),
|
|
1085
|
-
handler: async (ctx, { userId }) => {
|
|
1086
|
-
return await ctx.db
|
|
1087
|
-
.query("TotpFactor")
|
|
1088
|
-
.withIndex("user_id", (q) => q.eq("userId", userId))
|
|
1089
|
-
.collect();
|
|
1090
|
-
},
|
|
1091
|
-
});
|
|
1092
|
-
|
|
1093
|
-
/** Get a TOTP enrollment by its ID. */
|
|
1094
|
-
export const totpGetById = query({
|
|
1095
|
-
args: { totpId: v.id("TotpFactor") },
|
|
1096
|
-
returns: v.union(vTotpFactorDoc, v.null()),
|
|
1097
|
-
handler: async (ctx, { totpId }) => {
|
|
1098
|
-
return await ctx.db.get("TotpFactor", totpId);
|
|
1099
|
-
},
|
|
1100
|
-
});
|
|
1101
|
-
|
|
1102
|
-
/** Mark a TOTP enrollment as verified (setup complete). */
|
|
1103
|
-
export const totpMarkVerified = mutation({
|
|
1104
|
-
args: { totpId: v.id("TotpFactor"), lastUsedAt: v.number() },
|
|
1105
|
-
returns: v.null(),
|
|
1106
|
-
handler: async (ctx, { totpId, lastUsedAt }) => {
|
|
1107
|
-
await ctx.db.patch("TotpFactor", totpId, { verified: true, lastUsedAt });
|
|
1108
|
-
return null;
|
|
1109
|
-
},
|
|
1110
|
-
});
|
|
1111
|
-
|
|
1112
|
-
/** Update a TOTP enrollment's last used timestamp. */
|
|
1113
|
-
export const totpUpdateLastUsed = mutation({
|
|
1114
|
-
args: { totpId: v.id("TotpFactor"), lastUsedAt: v.number() },
|
|
1115
|
-
returns: v.null(),
|
|
1116
|
-
handler: async (ctx, { totpId, lastUsedAt }) => {
|
|
1117
|
-
await ctx.db.patch("TotpFactor", totpId, { lastUsedAt });
|
|
1118
|
-
return null;
|
|
1119
|
-
},
|
|
1120
|
-
});
|
|
1121
|
-
|
|
1122
|
-
/** Delete a TOTP enrollment. */
|
|
1123
|
-
export const totpDelete = mutation({
|
|
1124
|
-
args: { totpId: v.id("TotpFactor") },
|
|
1125
|
-
returns: v.null(),
|
|
1126
|
-
handler: async (ctx, { totpId }) => {
|
|
1127
|
-
await ctx.db.delete("TotpFactor", totpId);
|
|
1128
|
-
return null;
|
|
1129
|
-
},
|
|
1130
|
-
});
|
|
1131
|
-
|
|
1132
|
-
// ============================================================================
|
|
1133
|
-
// Rate Limits
|
|
1134
|
-
// ============================================================================
|
|
1135
|
-
|
|
1136
|
-
/** Look up a rate limit entry by its identifier. */
|
|
1137
|
-
export const rateLimitGet = query({
|
|
1138
|
-
args: { identifier: v.string() },
|
|
1139
|
-
returns: v.union(vRateLimitResult, v.null()),
|
|
1140
|
-
handler: async (ctx, { identifier }) => {
|
|
1141
|
-
const row = await ctx.db
|
|
1142
|
-
.query("RateLimit")
|
|
1143
|
-
.withIndex("by_identifier", (q) => q.eq("identifier", identifier))
|
|
1144
|
-
.unique();
|
|
1145
|
-
if (row === null) {
|
|
1146
|
-
return null;
|
|
1147
|
-
}
|
|
1148
|
-
return {
|
|
1149
|
-
...row,
|
|
1150
|
-
attemptsLeft: row.attempts_left,
|
|
1151
|
-
lastAttemptTime: row.last_attempt_time,
|
|
1152
|
-
};
|
|
1153
|
-
},
|
|
1154
|
-
});
|
|
1155
|
-
|
|
1156
|
-
/** Create a new rate limit entry. */
|
|
1157
|
-
export const rateLimitCreate = mutation({
|
|
1158
|
-
args: {
|
|
1159
|
-
identifier: v.string(),
|
|
1160
|
-
attemptsLeft: v.number(),
|
|
1161
|
-
lastAttemptTime: v.number(),
|
|
1162
|
-
},
|
|
1163
|
-
returns: v.id("RateLimit"),
|
|
1164
|
-
handler: async (ctx, { identifier, attemptsLeft, lastAttemptTime }) => {
|
|
1165
|
-
return await ctx.db.insert("RateLimit", {
|
|
1166
|
-
identifier,
|
|
1167
|
-
attempts_left: attemptsLeft,
|
|
1168
|
-
last_attempt_time: lastAttemptTime,
|
|
1169
|
-
});
|
|
1170
|
-
},
|
|
1171
|
-
});
|
|
1172
|
-
|
|
1173
|
-
/** Patch a rate limit entry with partial data. */
|
|
1174
|
-
export const rateLimitPatch = mutation({
|
|
1175
|
-
args: { rateLimitId: v.id("RateLimit"), data: v.any() },
|
|
1176
|
-
returns: v.null(),
|
|
1177
|
-
handler: async (ctx, { rateLimitId, data }) => {
|
|
1178
|
-
const nextData: Record<string, unknown> = { ...data };
|
|
1179
|
-
if (nextData.attemptsLeft !== undefined) {
|
|
1180
|
-
nextData.attempts_left = nextData.attemptsLeft;
|
|
1181
|
-
delete nextData.attemptsLeft;
|
|
1182
|
-
}
|
|
1183
|
-
if (nextData.lastAttemptTime !== undefined) {
|
|
1184
|
-
nextData.last_attempt_time = nextData.lastAttemptTime;
|
|
1185
|
-
delete nextData.lastAttemptTime;
|
|
1186
|
-
}
|
|
1187
|
-
await ctx.db.patch("RateLimit", rateLimitId, nextData);
|
|
1188
|
-
return null;
|
|
1189
|
-
},
|
|
1190
|
-
});
|
|
1191
|
-
|
|
1192
|
-
/** Delete a rate limit entry. */
|
|
1193
|
-
export const rateLimitDelete = mutation({
|
|
1194
|
-
args: { rateLimitId: v.id("RateLimit") },
|
|
1195
|
-
returns: v.null(),
|
|
1196
|
-
handler: async (ctx, { rateLimitId }) => {
|
|
1197
|
-
await ctx.db.delete("RateLimit", rateLimitId);
|
|
1198
|
-
return null;
|
|
1199
|
-
},
|
|
1200
|
-
});
|
|
1201
|
-
|
|
1202
|
-
// ============================================================================
|
|
1203
|
-
// Groups
|
|
1204
|
-
// ============================================================================
|
|
1205
|
-
|
|
1206
|
-
/**
|
|
1207
|
-
* Create a new group. Groups are hierarchical — set `parentGroupId` to nest
|
|
1208
|
-
* under an existing group, or omit it to create a root-level group.
|
|
1209
|
-
*
|
|
1210
|
-
* @returns The ID of the newly created group.
|
|
1211
|
-
*/
|
|
1212
|
-
export const groupCreate = mutation({
|
|
1213
|
-
args: {
|
|
1214
|
-
name: v.string(),
|
|
1215
|
-
slug: v.optional(v.string()),
|
|
1216
|
-
type: v.optional(v.string()),
|
|
1217
|
-
parentGroupId: v.optional(v.id("Group")),
|
|
1218
|
-
tags: v.optional(v.array(vTag)),
|
|
1219
|
-
extend: v.optional(v.any()),
|
|
1220
|
-
},
|
|
1221
|
-
returns: v.id("Group"),
|
|
1222
|
-
handler: async (ctx, args) => {
|
|
1223
|
-
const { tags: rawTags, ...rest } = args;
|
|
1224
|
-
const normalizedTags = rawTags ? normalizeTags(rawTags) : undefined;
|
|
1225
|
-
const groupId = await ctx.db.insert("Group", {
|
|
1226
|
-
...rest,
|
|
1227
|
-
tags: normalizedTags,
|
|
1228
|
-
});
|
|
1229
|
-
// Sync companion group_tag rows
|
|
1230
|
-
if (normalizedTags) {
|
|
1231
|
-
for (const tag of normalizedTags) {
|
|
1232
|
-
await ctx.db.insert("GroupTag", {
|
|
1233
|
-
group_id: groupId,
|
|
1234
|
-
key: tag.key,
|
|
1235
|
-
value: tag.value,
|
|
1236
|
-
});
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
return groupId;
|
|
1240
|
-
},
|
|
1241
|
-
});
|
|
1242
|
-
|
|
1243
|
-
/** Retrieve a group by its document ID. Returns `null` if not found. */
|
|
1244
|
-
export const groupGet = query({
|
|
1245
|
-
args: { groupId: v.id("Group") },
|
|
1246
|
-
returns: v.union(vGroupDoc, v.null()),
|
|
1247
|
-
handler: async (ctx, { groupId }) => {
|
|
1248
|
-
return await ctx.db.get("Group", groupId);
|
|
1249
|
-
},
|
|
1250
|
-
});
|
|
1251
|
-
|
|
1252
|
-
/**
|
|
1253
|
-
* List groups with optional filtering, sorting, and pagination.
|
|
1254
|
-
*
|
|
1255
|
-
* Returns `{ items, nextCursor }`. Empty `where` returns **all** groups.
|
|
1256
|
-
*/
|
|
1257
|
-
export const groupList = query({
|
|
1258
|
-
args: {
|
|
1259
|
-
where: v.optional(
|
|
1260
|
-
v.object({
|
|
1261
|
-
slug: v.optional(v.string()),
|
|
1262
|
-
type: v.optional(v.string()),
|
|
1263
|
-
parentGroupId: v.optional(v.id("Group")),
|
|
1264
|
-
name: v.optional(v.string()),
|
|
1265
|
-
isRoot: v.optional(v.boolean()),
|
|
1266
|
-
tagsAll: v.optional(v.array(vTag)),
|
|
1267
|
-
tagsAny: v.optional(v.array(vTag)),
|
|
1268
|
-
}),
|
|
1269
|
-
),
|
|
1270
|
-
limit: v.optional(v.number()),
|
|
1271
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
1272
|
-
orderBy: v.optional(
|
|
1273
|
-
v.union(
|
|
1274
|
-
v.literal("_creationTime"),
|
|
1275
|
-
v.literal("name"),
|
|
1276
|
-
v.literal("slug"),
|
|
1277
|
-
v.literal("type"),
|
|
1278
|
-
),
|
|
1279
|
-
),
|
|
1280
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
1281
|
-
},
|
|
1282
|
-
returns: vPaginated(vGroupDoc),
|
|
1283
|
-
handler: async (ctx, args) => {
|
|
1284
|
-
const where = args.where ?? {};
|
|
1285
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
1286
|
-
const order = args.order ?? "desc";
|
|
1287
|
-
|
|
1288
|
-
// ---- Resolve tag filters into a Set<Id<"Group">> ----
|
|
1289
|
-
let tagFilteredIds: Set<string> | null = null;
|
|
1290
|
-
|
|
1291
|
-
if (where.tagsAll && where.tagsAll.length > 0) {
|
|
1292
|
-
// Intersect: group must have ALL specified tags
|
|
1293
|
-
let allSet: Set<string> | null = null;
|
|
1294
|
-
for (const rawTag of where.tagsAll) {
|
|
1295
|
-
const t = normalizeTag(rawTag);
|
|
1296
|
-
const rows = await ctx.db
|
|
1297
|
-
.query("GroupTag")
|
|
1298
|
-
.withIndex("by_key_value", (idx) =>
|
|
1299
|
-
idx.eq("key", t.key).eq("value", t.value),
|
|
1300
|
-
)
|
|
1301
|
-
.collect();
|
|
1302
|
-
const ids = new Set(rows.map((r) => r.group_id as string));
|
|
1303
|
-
if (allSet === null) {
|
|
1304
|
-
allSet = ids;
|
|
1305
|
-
} else {
|
|
1306
|
-
// Intersect
|
|
1307
|
-
for (const id of allSet) {
|
|
1308
|
-
if (!ids.has(id)) allSet.delete(id);
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
// Short-circuit: empty intersection
|
|
1312
|
-
if (allSet.size === 0) break;
|
|
1313
|
-
}
|
|
1314
|
-
tagFilteredIds = allSet ?? new Set();
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
|
-
if (where.tagsAny && where.tagsAny.length > 0) {
|
|
1318
|
-
// Union: group must have at least one of the specified tags
|
|
1319
|
-
const anySet = new Set<string>();
|
|
1320
|
-
for (const rawTag of where.tagsAny) {
|
|
1321
|
-
const t = normalizeTag(rawTag);
|
|
1322
|
-
const rows = await ctx.db
|
|
1323
|
-
.query("GroupTag")
|
|
1324
|
-
.withIndex("by_key_value", (idx) =>
|
|
1325
|
-
idx.eq("key", t.key).eq("value", t.value),
|
|
1326
|
-
)
|
|
1327
|
-
.collect();
|
|
1328
|
-
for (const r of rows) {
|
|
1329
|
-
anySet.add(r.group_id as string);
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1332
|
-
if (tagFilteredIds !== null) {
|
|
1333
|
-
// AND with tagsAll result
|
|
1334
|
-
for (const id of tagFilteredIds) {
|
|
1335
|
-
if (!anySet.has(id)) tagFilteredIds.delete(id);
|
|
1336
|
-
}
|
|
1337
|
-
} else {
|
|
1338
|
-
tagFilteredIds = anySet;
|
|
1339
|
-
}
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
// ---- Pick best index based on non-tag where fields ----
|
|
1343
|
-
let q;
|
|
1344
|
-
if (where.type !== undefined && where.parentGroupId !== undefined) {
|
|
1345
|
-
q = ctx.db
|
|
1346
|
-
.query("Group")
|
|
1347
|
-
.withIndex("type_parent_group_id", (idx) =>
|
|
1348
|
-
idx.eq("type", where.type!).eq("parentGroupId", where.parentGroupId!),
|
|
1349
|
-
);
|
|
1350
|
-
} else if (where.slug !== undefined) {
|
|
1351
|
-
q = ctx.db
|
|
1352
|
-
.query("Group")
|
|
1353
|
-
.withIndex("slug", (idx) => idx.eq("slug", where.slug!));
|
|
1354
|
-
} else if (where.type !== undefined) {
|
|
1355
|
-
q = ctx.db
|
|
1356
|
-
.query("Group")
|
|
1357
|
-
.withIndex("type", (idx) => idx.eq("type", where.type!));
|
|
1358
|
-
} else if (where.parentGroupId !== undefined) {
|
|
1359
|
-
q = ctx.db
|
|
1360
|
-
.query("Group")
|
|
1361
|
-
.withIndex("parent_group_id", (idx) =>
|
|
1362
|
-
idx.eq("parentGroupId", where.parentGroupId!),
|
|
1363
|
-
);
|
|
1364
|
-
} else {
|
|
1365
|
-
q = ctx.db.query("Group");
|
|
1366
|
-
}
|
|
1367
|
-
|
|
1368
|
-
// Apply remaining non-tag filters not covered by index
|
|
1369
|
-
if (where.name !== undefined) {
|
|
1370
|
-
q = q.filter((f) => f.eq(f.field("name"), where.name!));
|
|
1371
|
-
}
|
|
1372
|
-
if (where.isRoot === true) {
|
|
1373
|
-
q = q.filter((f) => f.eq(f.field("parentGroupId"), undefined));
|
|
1374
|
-
} else if (where.isRoot === false) {
|
|
1375
|
-
q = q.filter((f) => f.neq(f.field("parentGroupId"), undefined));
|
|
1376
|
-
}
|
|
1377
|
-
// slug filter when not used as index
|
|
1378
|
-
if (where.slug !== undefined && where.type !== undefined) {
|
|
1379
|
-
q = q.filter((f) => f.eq(f.field("slug"), where.slug!));
|
|
1380
|
-
}
|
|
1381
|
-
|
|
1382
|
-
q = q.order(order);
|
|
1383
|
-
|
|
1384
|
-
let all = await q.collect();
|
|
1385
|
-
|
|
1386
|
-
// Apply tag filter (intersect with resolved groupIds)
|
|
1387
|
-
if (tagFilteredIds !== null) {
|
|
1388
|
-
all = all.filter((doc) => tagFilteredIds!.has(doc._id as string));
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
// Cursor-based pagination
|
|
1392
|
-
let startIdx = 0;
|
|
1393
|
-
if (args.cursor) {
|
|
1394
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
1395
|
-
if (cursorIdx !== -1) {
|
|
1396
|
-
startIdx = cursorIdx + 1;
|
|
1397
|
-
}
|
|
1398
|
-
}
|
|
1399
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
1400
|
-
const hasMore = page.length > limit;
|
|
1401
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
1402
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
1403
|
-
return { items, nextCursor };
|
|
1404
|
-
},
|
|
1405
|
-
});
|
|
1406
|
-
|
|
1407
|
-
/** Update a group's fields (name, slug, tags, extend, parentGroupId). */
|
|
1408
|
-
export const groupUpdate = mutation({
|
|
1409
|
-
args: { groupId: v.id("Group"), data: v.any() },
|
|
1410
|
-
returns: v.null(),
|
|
1411
|
-
handler: async (ctx, { groupId, data }) => {
|
|
1412
|
-
// If tags are being updated, normalize and replace the full tag set
|
|
1413
|
-
if (data.tags !== undefined) {
|
|
1414
|
-
const normalizedTags: TagPair[] = Array.isArray(data.tags)
|
|
1415
|
-
? normalizeTags(data.tags as TagPair[])
|
|
1416
|
-
: [];
|
|
1417
|
-
// Delete existing group_tag rows for this group
|
|
1418
|
-
const existingTags = await ctx.db
|
|
1419
|
-
.query("GroupTag")
|
|
1420
|
-
.withIndex("by_group", (idx) => idx.eq("group_id", groupId))
|
|
1421
|
-
.collect();
|
|
1422
|
-
for (const existing of existingTags) {
|
|
1423
|
-
await ctx.db.delete("GroupTag", existing._id);
|
|
1424
|
-
}
|
|
1425
|
-
// Insert new normalized group_tag rows
|
|
1426
|
-
for (const tag of normalizedTags) {
|
|
1427
|
-
await ctx.db.insert("GroupTag", {
|
|
1428
|
-
group_id: groupId,
|
|
1429
|
-
key: tag.key,
|
|
1430
|
-
value: tag.value,
|
|
1431
|
-
});
|
|
1432
|
-
}
|
|
1433
|
-
// Patch group with normalized tags (empty array = clear all)
|
|
1434
|
-
await ctx.db.patch("Group", groupId, {
|
|
1435
|
-
...data,
|
|
1436
|
-
tags: normalizedTags.length > 0 ? normalizedTags : undefined,
|
|
1437
|
-
});
|
|
1438
|
-
} else {
|
|
1439
|
-
await ctx.db.patch("Group", groupId, data);
|
|
1440
|
-
}
|
|
1441
|
-
return null;
|
|
1442
|
-
},
|
|
1443
|
-
});
|
|
1444
|
-
|
|
1445
|
-
/**
|
|
1446
|
-
* Delete a group and all of its descendants. This cascades to:
|
|
1447
|
-
* - All child groups (recursively)
|
|
1448
|
-
* - All members of this group and its descendants
|
|
1449
|
-
* - All invites for this group and its descendants
|
|
1450
|
-
*/
|
|
1451
|
-
export const groupDelete = mutation({
|
|
1452
|
-
args: { groupId: v.id("Group") },
|
|
1453
|
-
returns: v.null(),
|
|
1454
|
-
handler: async (ctx, { groupId }) => {
|
|
1455
|
-
const deleteGroup = async (id: typeof groupId) => {
|
|
1456
|
-
const children = await ctx.db
|
|
1457
|
-
.query("Group")
|
|
1458
|
-
.withIndex("parent_group_id", (q) => q.eq("parentGroupId", id))
|
|
1459
|
-
.collect();
|
|
1460
|
-
for (const child of children) {
|
|
1461
|
-
await deleteGroup(child._id);
|
|
1462
|
-
}
|
|
1463
|
-
|
|
1464
|
-
const members = await ctx.db
|
|
1465
|
-
.query("GroupMember")
|
|
1466
|
-
.withIndex("group_id", (q) => q.eq("groupId", id))
|
|
1467
|
-
.collect();
|
|
1468
|
-
for (const member of members) {
|
|
1469
|
-
await ctx.db.delete("GroupMember", member._id);
|
|
1470
|
-
}
|
|
1471
|
-
|
|
1472
|
-
const invites = await ctx.db
|
|
1473
|
-
.query("GroupInvite")
|
|
1474
|
-
.withIndex("group_id", (q) => q.eq("groupId", id))
|
|
1475
|
-
.collect();
|
|
1476
|
-
for (const invite of invites) {
|
|
1477
|
-
await ctx.db.delete("GroupInvite", invite._id);
|
|
1478
|
-
}
|
|
1479
|
-
|
|
1480
|
-
// Delete companion group_tag rows
|
|
1481
|
-
const tags = await ctx.db
|
|
1482
|
-
.query("GroupTag")
|
|
1483
|
-
.withIndex("by_group", (q) => q.eq("group_id", id))
|
|
1484
|
-
.collect();
|
|
1485
|
-
for (const tag of tags) {
|
|
1486
|
-
await ctx.db.delete("GroupTag", tag._id);
|
|
1487
|
-
}
|
|
1488
|
-
|
|
1489
|
-
await ctx.db.delete("Group", id);
|
|
1490
|
-
};
|
|
1491
|
-
|
|
1492
|
-
await deleteGroup(groupId);
|
|
1493
|
-
return null;
|
|
1494
|
-
},
|
|
1495
|
-
});
|
|
1496
|
-
|
|
1497
|
-
// ============================================================================
|
|
1498
|
-
// Members
|
|
1499
|
-
// ============================================================================
|
|
1500
|
-
|
|
1501
|
-
/**
|
|
1502
|
-
* Add a user as a member of a group.
|
|
1503
|
-
*
|
|
1504
|
-
* The `role` field is an application-defined string (e.g. "owner", "admin",
|
|
1505
|
-
* "member", "viewer"). The auth component stores it but does not enforce
|
|
1506
|
-
* access control — your application defines what each role means.
|
|
1507
|
-
*
|
|
1508
|
-
* Throws `ConvexError` with code `DUPLICATE_MEMBERSHIP` when the user is
|
|
1509
|
-
* already a member of the target group.
|
|
1510
|
-
*
|
|
1511
|
-
* @returns The ID of the new member record.
|
|
1512
|
-
*/
|
|
1513
|
-
export const memberAdd = mutation({
|
|
1514
|
-
args: {
|
|
1515
|
-
groupId: v.id("Group"),
|
|
1516
|
-
userId: v.id("User"),
|
|
1517
|
-
role: v.optional(v.string()),
|
|
1518
|
-
status: v.optional(v.string()),
|
|
1519
|
-
extend: v.optional(v.any()),
|
|
1520
|
-
},
|
|
1521
|
-
returns: v.id("GroupMember"),
|
|
1522
|
-
handler: async (ctx, args) => {
|
|
1523
|
-
const existingMembership = await ctx.db
|
|
1524
|
-
.query("GroupMember")
|
|
1525
|
-
.withIndex("group_id_user_id", (q) =>
|
|
1526
|
-
q.eq("groupId", args.groupId).eq("userId", args.userId),
|
|
1527
|
-
)
|
|
1528
|
-
.unique();
|
|
1529
|
-
if (existingMembership !== null) {
|
|
1530
|
-
throw new ConvexError({
|
|
1531
|
-
code: "DUPLICATE_MEMBERSHIP",
|
|
1532
|
-
message: "User is already a member of this group",
|
|
1533
|
-
groupId: args.groupId,
|
|
1534
|
-
userId: args.userId,
|
|
1535
|
-
existingMemberId: existingMembership._id,
|
|
1536
|
-
});
|
|
1537
|
-
}
|
|
1538
|
-
return await ctx.db.insert("GroupMember", args);
|
|
1539
|
-
},
|
|
1540
|
-
});
|
|
1541
|
-
|
|
1542
|
-
/** Retrieve a member record by its document ID. Returns `null` if not found. */
|
|
1543
|
-
export const memberGet = query({
|
|
1544
|
-
args: { memberId: v.id("GroupMember") },
|
|
1545
|
-
returns: v.union(vGroupMemberDoc, v.null()),
|
|
1546
|
-
handler: async (ctx, { memberId }) => {
|
|
1547
|
-
return await ctx.db.get("GroupMember", memberId);
|
|
1548
|
-
},
|
|
1549
|
-
});
|
|
1550
|
-
|
|
1551
|
-
/**
|
|
1552
|
-
* List members with optional filtering, sorting, and pagination.
|
|
1553
|
-
*
|
|
1554
|
-
* Returns `{ items, nextCursor }`. Supports filtering by `groupId`,
|
|
1555
|
-
* `userId`, `role`, and `status`.
|
|
1556
|
-
*/
|
|
1557
|
-
export const memberList = query({
|
|
1558
|
-
args: {
|
|
1559
|
-
where: v.optional(
|
|
1560
|
-
v.object({
|
|
1561
|
-
groupId: v.optional(v.id("Group")),
|
|
1562
|
-
userId: v.optional(v.id("User")),
|
|
1563
|
-
role: v.optional(v.string()),
|
|
1564
|
-
status: v.optional(v.string()),
|
|
1565
|
-
}),
|
|
1566
|
-
),
|
|
1567
|
-
limit: v.optional(v.number()),
|
|
1568
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
1569
|
-
orderBy: v.optional(
|
|
1570
|
-
v.union(
|
|
1571
|
-
v.literal("_creationTime"),
|
|
1572
|
-
v.literal("role"),
|
|
1573
|
-
v.literal("status"),
|
|
1574
|
-
),
|
|
1575
|
-
),
|
|
1576
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
1577
|
-
},
|
|
1578
|
-
returns: vPaginated(vGroupMemberDoc),
|
|
1579
|
-
handler: async (ctx, args) => {
|
|
1580
|
-
const where = args.where ?? {};
|
|
1581
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
1582
|
-
const order = args.order ?? "desc";
|
|
1583
|
-
|
|
1584
|
-
let q;
|
|
1585
|
-
if (where.groupId !== undefined && where.userId !== undefined) {
|
|
1586
|
-
q = ctx.db
|
|
1587
|
-
.query("GroupMember")
|
|
1588
|
-
.withIndex("group_id_user_id", (idx) =>
|
|
1589
|
-
idx.eq("groupId", where.groupId!).eq("userId", where.userId!),
|
|
1590
|
-
);
|
|
1591
|
-
} else if (where.groupId !== undefined) {
|
|
1592
|
-
q = ctx.db
|
|
1593
|
-
.query("GroupMember")
|
|
1594
|
-
.withIndex("group_id", (idx) => idx.eq("groupId", where.groupId!));
|
|
1595
|
-
} else if (where.userId !== undefined) {
|
|
1596
|
-
q = ctx.db
|
|
1597
|
-
.query("GroupMember")
|
|
1598
|
-
.withIndex("user_id", (idx) => idx.eq("userId", where.userId!));
|
|
1599
|
-
} else {
|
|
1600
|
-
q = ctx.db.query("GroupMember");
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
if (where.role !== undefined) {
|
|
1604
|
-
q = q.filter((f) => f.eq(f.field("role"), where.role!));
|
|
1605
|
-
}
|
|
1606
|
-
if (where.status !== undefined) {
|
|
1607
|
-
q = q.filter((f) => f.eq(f.field("status"), where.status!));
|
|
1608
|
-
}
|
|
1609
|
-
|
|
1610
|
-
q = q.order(order);
|
|
1611
|
-
|
|
1612
|
-
const all = await q.collect();
|
|
1613
|
-
let startIdx = 0;
|
|
1614
|
-
if (args.cursor) {
|
|
1615
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
1616
|
-
if (cursorIdx !== -1) {
|
|
1617
|
-
startIdx = cursorIdx + 1;
|
|
1618
|
-
}
|
|
1619
|
-
}
|
|
1620
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
1621
|
-
const hasMore = page.length > limit;
|
|
1622
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
1623
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
1624
|
-
return { items, nextCursor };
|
|
1625
|
-
},
|
|
1626
|
-
});
|
|
1627
|
-
|
|
1628
|
-
/**
|
|
1629
|
-
* @deprecated Use `memberList` with `where: { userId }` instead.
|
|
1630
|
-
* Kept for backward compatibility with generated component types.
|
|
1631
|
-
*/
|
|
1632
|
-
export const memberListByUser = query({
|
|
1633
|
-
args: { userId: v.id("User") },
|
|
1634
|
-
returns: v.array(vGroupMemberDoc),
|
|
1635
|
-
handler: async (ctx, { userId }) => {
|
|
1636
|
-
return await ctx.db
|
|
1637
|
-
.query("GroupMember")
|
|
1638
|
-
.withIndex("user_id", (q) => q.eq("userId", userId))
|
|
1639
|
-
.collect();
|
|
1640
|
-
},
|
|
1641
|
-
});
|
|
1642
|
-
|
|
1643
|
-
/**
|
|
1644
|
-
* Look up a specific user's membership in a specific group.
|
|
1645
|
-
* Returns `null` if the user is not a member of the group.
|
|
1646
|
-
*/
|
|
1647
|
-
export const memberGetByGroupAndUser = query({
|
|
1648
|
-
args: { groupId: v.id("Group"), userId: v.id("User") },
|
|
1649
|
-
returns: v.union(vGroupMemberDoc, v.null()),
|
|
1650
|
-
handler: async (ctx, { groupId, userId }) => {
|
|
1651
|
-
return await ctx.db
|
|
1652
|
-
.query("GroupMember")
|
|
1653
|
-
.withIndex("group_id_user_id", (q) =>
|
|
1654
|
-
q.eq("groupId", groupId).eq("userId", userId),
|
|
1655
|
-
)
|
|
1656
|
-
.unique();
|
|
1657
|
-
},
|
|
1658
|
-
});
|
|
1659
|
-
|
|
1660
|
-
/** Remove a member from a group by deleting the member record. */
|
|
1661
|
-
export const memberRemove = mutation({
|
|
1662
|
-
args: { memberId: v.id("GroupMember") },
|
|
1663
|
-
returns: v.null(),
|
|
1664
|
-
handler: async (ctx, { memberId }) => {
|
|
1665
|
-
await ctx.db.delete("GroupMember", memberId);
|
|
1666
|
-
return null;
|
|
1667
|
-
},
|
|
1668
|
-
});
|
|
1669
|
-
|
|
1670
|
-
/**
|
|
1671
|
-
* Update a member record's fields (role, status, extend).
|
|
1672
|
-
*
|
|
1673
|
-
* Common usage: `memberUpdate({ memberId, data: { role: "admin" } })`
|
|
1674
|
-
*/
|
|
1675
|
-
export const memberUpdate = mutation({
|
|
1676
|
-
args: { memberId: v.id("GroupMember"), data: v.any() },
|
|
1677
|
-
returns: v.null(),
|
|
1678
|
-
handler: async (ctx, { memberId, data }) => {
|
|
1679
|
-
await ctx.db.patch("GroupMember", memberId, data);
|
|
1680
|
-
return null;
|
|
1681
|
-
},
|
|
1682
|
-
});
|
|
1683
|
-
|
|
1684
|
-
// ============================================================================
|
|
1685
|
-
// Invites
|
|
1686
|
-
// ============================================================================
|
|
1687
|
-
|
|
1688
|
-
/**
|
|
1689
|
-
* Create a new platform-level invitation. Optionally set `groupId` to tie
|
|
1690
|
-
* the invite to a specific group. The invitation is sent to an email address
|
|
1691
|
-
* and includes a hashed token for secure acceptance.
|
|
1692
|
-
*
|
|
1693
|
-
* Throws `ConvexError` with code `DUPLICATE_INVITE` when a pending invite
|
|
1694
|
-
* already exists for the same email and scope:
|
|
1695
|
-
* - group invite: same `email` + same `groupId`
|
|
1696
|
-
* - platform invite: same `email` with no `groupId`
|
|
1697
|
-
*
|
|
1698
|
-
* @returns The ID of the new invite record.
|
|
1699
|
-
*/
|
|
1700
|
-
export const inviteCreate = mutation({
|
|
1701
|
-
args: {
|
|
1702
|
-
groupId: v.optional(v.id("Group")),
|
|
1703
|
-
invitedByUserId: v.optional(v.id("User")),
|
|
1704
|
-
email: v.optional(v.string()),
|
|
1705
|
-
tokenHash: v.string(),
|
|
1706
|
-
role: v.optional(v.string()),
|
|
1707
|
-
status: vInviteStatus,
|
|
1708
|
-
expiresTime: v.optional(v.number()),
|
|
1709
|
-
extend: v.optional(v.any()),
|
|
1710
|
-
},
|
|
1711
|
-
returns: v.id("GroupInvite"),
|
|
1712
|
-
handler: async (ctx, args) => {
|
|
1713
|
-
const now = Date.now();
|
|
1714
|
-
|
|
1715
|
-
// Only check for duplicates when an email is provided.
|
|
1716
|
-
// CLI-generated invites (no email) are always allowed.
|
|
1717
|
-
if (args.email !== undefined) {
|
|
1718
|
-
if (args.groupId !== undefined) {
|
|
1719
|
-
const existingGroupInvites = await ctx.db
|
|
1720
|
-
.query("GroupInvite")
|
|
1721
|
-
.withIndex("group_id_status", (q) =>
|
|
1722
|
-
q.eq("groupId", args.groupId).eq("status", "pending"),
|
|
1723
|
-
)
|
|
1724
|
-
.filter((q) => q.eq(q.field("email"), args.email))
|
|
1725
|
-
.collect();
|
|
1726
|
-
|
|
1727
|
-
for (const existingGroupInvite of existingGroupInvites) {
|
|
1728
|
-
const isExpired =
|
|
1729
|
-
existingGroupInvite.expiresTime !== undefined &&
|
|
1730
|
-
existingGroupInvite.expiresTime <= now;
|
|
1731
|
-
if (isExpired) {
|
|
1732
|
-
await ctx.db.patch("GroupInvite", existingGroupInvite._id, {
|
|
1733
|
-
status: "expired",
|
|
1734
|
-
});
|
|
1735
|
-
continue;
|
|
1736
|
-
}
|
|
1737
|
-
throw new ConvexError({
|
|
1738
|
-
code: "DUPLICATE_INVITE",
|
|
1739
|
-
message:
|
|
1740
|
-
"A pending invite already exists for this email in this group",
|
|
1741
|
-
email: args.email,
|
|
1742
|
-
groupId: args.groupId,
|
|
1743
|
-
existingInviteId: existingGroupInvite._id,
|
|
1744
|
-
});
|
|
1745
|
-
}
|
|
1746
|
-
} else {
|
|
1747
|
-
const existingPlatformInvites = await ctx.db
|
|
1748
|
-
.query("GroupInvite")
|
|
1749
|
-
.withIndex("email_status", (q) =>
|
|
1750
|
-
q.eq("email", args.email).eq("status", "pending"),
|
|
1751
|
-
)
|
|
1752
|
-
.filter((q) => q.eq(q.field("groupId"), undefined))
|
|
1753
|
-
.collect();
|
|
1754
|
-
|
|
1755
|
-
for (const existingPlatformInvite of existingPlatformInvites) {
|
|
1756
|
-
const isExpired =
|
|
1757
|
-
existingPlatformInvite.expiresTime !== undefined &&
|
|
1758
|
-
existingPlatformInvite.expiresTime <= now;
|
|
1759
|
-
if (isExpired) {
|
|
1760
|
-
await ctx.db.patch("GroupInvite", existingPlatformInvite._id, {
|
|
1761
|
-
status: "expired",
|
|
1762
|
-
});
|
|
1763
|
-
continue;
|
|
1764
|
-
}
|
|
1765
|
-
throw new ConvexError({
|
|
1766
|
-
code: "DUPLICATE_INVITE",
|
|
1767
|
-
message: "A pending platform invite already exists for this email",
|
|
1768
|
-
email: args.email,
|
|
1769
|
-
existingInviteId: existingPlatformInvite._id,
|
|
1770
|
-
});
|
|
1771
|
-
}
|
|
1772
|
-
}
|
|
1773
|
-
}
|
|
1774
|
-
return await ctx.db.insert("GroupInvite", args);
|
|
1775
|
-
},
|
|
1776
|
-
});
|
|
1777
|
-
|
|
1778
|
-
/** Retrieve an invite by its document ID. Returns `null` if not found. */
|
|
1779
|
-
export const inviteGet = query({
|
|
1780
|
-
args: { inviteId: v.id("GroupInvite") },
|
|
1781
|
-
returns: v.union(vGroupInviteDoc, v.null()),
|
|
1782
|
-
handler: async (ctx, { inviteId }) => {
|
|
1783
|
-
return await ctx.db.get("GroupInvite", inviteId);
|
|
1784
|
-
},
|
|
1785
|
-
});
|
|
1786
|
-
|
|
1787
|
-
/** Retrieve an invite by hashed token. Returns `null` if not found. */
|
|
1788
|
-
export const inviteGetByTokenHash = query({
|
|
1789
|
-
args: { tokenHash: v.string() },
|
|
1790
|
-
returns: v.union(vGroupInviteDoc, v.null()),
|
|
1791
|
-
handler: async (ctx, { tokenHash }) => {
|
|
1792
|
-
return await ctx.db
|
|
1793
|
-
.query("GroupInvite")
|
|
1794
|
-
.withIndex("token_hash", (q) => q.eq("tokenHash", tokenHash))
|
|
1795
|
-
.first();
|
|
1796
|
-
},
|
|
1797
|
-
});
|
|
1798
|
-
|
|
1799
|
-
/**
|
|
1800
|
-
* List invites with optional filtering, sorting, and pagination.
|
|
1801
|
-
*
|
|
1802
|
-
* Returns `{ items, nextCursor }`. Supports filtering by `groupId`,
|
|
1803
|
-
* `status`, `email`, `invitedByUserId`, `role`, `acceptedByUserId`, and `tokenHash`.
|
|
1804
|
-
*/
|
|
1805
|
-
export const inviteList = query({
|
|
1806
|
-
args: {
|
|
1807
|
-
where: v.optional(
|
|
1808
|
-
v.object({
|
|
1809
|
-
tokenHash: v.optional(v.string()),
|
|
1810
|
-
groupId: v.optional(v.id("Group")),
|
|
1811
|
-
status: v.optional(vInviteStatus),
|
|
1812
|
-
email: v.optional(v.string()),
|
|
1813
|
-
invitedByUserId: v.optional(v.id("User")),
|
|
1814
|
-
role: v.optional(v.string()),
|
|
1815
|
-
acceptedByUserId: v.optional(v.id("User")),
|
|
1816
|
-
}),
|
|
1817
|
-
),
|
|
1818
|
-
limit: v.optional(v.number()),
|
|
1819
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
1820
|
-
orderBy: v.optional(
|
|
1821
|
-
v.union(
|
|
1822
|
-
v.literal("_creationTime"),
|
|
1823
|
-
v.literal("status"),
|
|
1824
|
-
v.literal("email"),
|
|
1825
|
-
v.literal("expiresTime"),
|
|
1826
|
-
v.literal("acceptedTime"),
|
|
1827
|
-
),
|
|
1828
|
-
),
|
|
1829
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
1830
|
-
},
|
|
1831
|
-
returns: vPaginated(vGroupInviteDoc),
|
|
1832
|
-
handler: async (ctx, args) => {
|
|
1833
|
-
const where = args.where ?? {};
|
|
1834
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
1835
|
-
const order = args.order ?? "desc";
|
|
1836
|
-
|
|
1837
|
-
// Pick best index
|
|
1838
|
-
let q;
|
|
1839
|
-
if (where.tokenHash !== undefined) {
|
|
1840
|
-
q = ctx.db
|
|
1841
|
-
.query("GroupInvite")
|
|
1842
|
-
.withIndex("token_hash", (idx) =>
|
|
1843
|
-
idx.eq("tokenHash", where.tokenHash!),
|
|
1844
|
-
);
|
|
1845
|
-
} else if (
|
|
1846
|
-
where.role !== undefined &&
|
|
1847
|
-
where.status !== undefined &&
|
|
1848
|
-
where.acceptedByUserId !== undefined
|
|
1849
|
-
) {
|
|
1850
|
-
q = ctx.db
|
|
1851
|
-
.query("GroupInvite")
|
|
1852
|
-
.withIndex("role_status_accepted_by_user_id", (idx) =>
|
|
1853
|
-
idx
|
|
1854
|
-
.eq("role", where.role!)
|
|
1855
|
-
.eq("status", where.status!)
|
|
1856
|
-
.eq("acceptedByUserId", where.acceptedByUserId!),
|
|
1857
|
-
);
|
|
1858
|
-
} else if (where.groupId !== undefined && where.status !== undefined) {
|
|
1859
|
-
q = ctx.db
|
|
1860
|
-
.query("GroupInvite")
|
|
1861
|
-
.withIndex("group_id_status", (idx) =>
|
|
1862
|
-
idx.eq("groupId", where.groupId!).eq("status", where.status!),
|
|
1863
|
-
);
|
|
1864
|
-
} else if (where.email !== undefined && where.status !== undefined) {
|
|
1865
|
-
q = ctx.db
|
|
1866
|
-
.query("GroupInvite")
|
|
1867
|
-
.withIndex("email_status", (idx) =>
|
|
1868
|
-
idx.eq("email", where.email!).eq("status", where.status!),
|
|
1869
|
-
);
|
|
1870
|
-
} else if (
|
|
1871
|
-
where.invitedByUserId !== undefined &&
|
|
1872
|
-
where.status !== undefined
|
|
1873
|
-
) {
|
|
1874
|
-
q = ctx.db
|
|
1875
|
-
.query("GroupInvite")
|
|
1876
|
-
.withIndex("invited_by_user_id_status", (idx) =>
|
|
1877
|
-
idx
|
|
1878
|
-
.eq("invitedByUserId", where.invitedByUserId!)
|
|
1879
|
-
.eq("status", where.status!),
|
|
1880
|
-
);
|
|
1881
|
-
} else if (where.groupId !== undefined) {
|
|
1882
|
-
q = ctx.db
|
|
1883
|
-
.query("GroupInvite")
|
|
1884
|
-
.withIndex("group_id", (idx) => idx.eq("groupId", where.groupId!));
|
|
1885
|
-
} else if (where.status !== undefined) {
|
|
1886
|
-
q = ctx.db
|
|
1887
|
-
.query("GroupInvite")
|
|
1888
|
-
.withIndex("status", (idx) => idx.eq("status", where.status!));
|
|
1889
|
-
} else {
|
|
1890
|
-
q = ctx.db.query("GroupInvite");
|
|
1891
|
-
}
|
|
1892
|
-
|
|
1893
|
-
// Apply remaining filters
|
|
1894
|
-
if (where.groupId !== undefined) {
|
|
1895
|
-
q = q.filter((f) => f.eq(f.field("groupId"), where.groupId!));
|
|
1896
|
-
}
|
|
1897
|
-
if (where.status !== undefined) {
|
|
1898
|
-
q = q.filter((f) => f.eq(f.field("status"), where.status!));
|
|
1899
|
-
}
|
|
1900
|
-
if (where.email !== undefined) {
|
|
1901
|
-
q = q.filter((f) => f.eq(f.field("email"), where.email!));
|
|
1902
|
-
}
|
|
1903
|
-
if (where.invitedByUserId !== undefined) {
|
|
1904
|
-
q = q.filter((f) =>
|
|
1905
|
-
f.eq(f.field("invitedByUserId"), where.invitedByUserId!),
|
|
1906
|
-
);
|
|
1907
|
-
}
|
|
1908
|
-
if (where.role !== undefined) {
|
|
1909
|
-
q = q.filter((f) => f.eq(f.field("role"), where.role!));
|
|
1910
|
-
}
|
|
1911
|
-
if (where.acceptedByUserId !== undefined) {
|
|
1912
|
-
q = q.filter((f) =>
|
|
1913
|
-
f.eq(f.field("acceptedByUserId"), where.acceptedByUserId!),
|
|
1914
|
-
);
|
|
1915
|
-
}
|
|
1916
|
-
if (where.tokenHash !== undefined) {
|
|
1917
|
-
q = q.filter((f) => f.eq(f.field("tokenHash"), where.tokenHash!));
|
|
1918
|
-
}
|
|
1919
|
-
|
|
1920
|
-
q = q.order(order);
|
|
1921
|
-
|
|
1922
|
-
const all = await q.collect();
|
|
1923
|
-
let startIdx = 0;
|
|
1924
|
-
if (args.cursor) {
|
|
1925
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
1926
|
-
if (cursorIdx !== -1) {
|
|
1927
|
-
startIdx = cursorIdx + 1;
|
|
1928
|
-
}
|
|
1929
|
-
}
|
|
1930
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
1931
|
-
const hasMore = page.length > limit;
|
|
1932
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
1933
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
1934
|
-
return { items, nextCursor };
|
|
1935
|
-
},
|
|
1936
|
-
});
|
|
1937
|
-
|
|
1938
|
-
/**
|
|
1939
|
-
* Accept a pending invitation.
|
|
1940
|
-
*
|
|
1941
|
-
* Marks the invite as "accepted" and records the acceptance timestamp.
|
|
1942
|
-
* Throws a structured `ConvexError` when the invite doesn't exist or is not
|
|
1943
|
-
* currently pending.
|
|
1944
|
-
*
|
|
1945
|
-
* The caller is responsible for creating the corresponding member record.
|
|
1946
|
-
*/
|
|
1947
|
-
export const inviteAccept = mutation({
|
|
1948
|
-
args: {
|
|
1949
|
-
inviteId: v.id("GroupInvite"),
|
|
1950
|
-
acceptedByUserId: v.optional(v.id("User")),
|
|
1951
|
-
},
|
|
1952
|
-
returns: v.null(),
|
|
1953
|
-
handler: async (ctx, { inviteId, acceptedByUserId }) => {
|
|
1954
|
-
const invite = await ctx.db.get("GroupInvite", inviteId);
|
|
1955
|
-
if (invite === null) {
|
|
1956
|
-
throw new ConvexError({
|
|
1957
|
-
code: "INVITE_NOT_FOUND",
|
|
1958
|
-
message: "Invite not found",
|
|
1959
|
-
inviteId,
|
|
1960
|
-
});
|
|
1961
|
-
}
|
|
1962
|
-
if (invite.status !== "pending") {
|
|
1963
|
-
throw new ConvexError({
|
|
1964
|
-
code: "INVITE_NOT_PENDING",
|
|
1965
|
-
message: `Cannot accept invite with status "${invite.status}"`,
|
|
1966
|
-
inviteId,
|
|
1967
|
-
currentStatus: invite.status,
|
|
1968
|
-
});
|
|
1969
|
-
}
|
|
1970
|
-
if (invite.expiresTime !== undefined && invite.expiresTime <= Date.now()) {
|
|
1971
|
-
await ctx.db.patch("GroupInvite", inviteId, {
|
|
1972
|
-
status: "expired",
|
|
1973
|
-
});
|
|
1974
|
-
throw new ConvexError({
|
|
1975
|
-
code: "INVITE_EXPIRED",
|
|
1976
|
-
message: "Invite has expired",
|
|
1977
|
-
inviteId,
|
|
1978
|
-
});
|
|
1979
|
-
}
|
|
1980
|
-
await ctx.db.patch("GroupInvite", inviteId, {
|
|
1981
|
-
status: "accepted",
|
|
1982
|
-
acceptedTime: Date.now(),
|
|
1983
|
-
...(acceptedByUserId ? { acceptedByUserId } : {}),
|
|
1984
|
-
});
|
|
1985
|
-
return null;
|
|
1986
|
-
},
|
|
1987
|
-
});
|
|
1988
|
-
|
|
1989
|
-
/**
|
|
1990
|
-
* Accept an invitation by raw token hash and atomically join group membership.
|
|
1991
|
-
*
|
|
1992
|
-
* Returns idempotent success when the invite was already accepted by the same
|
|
1993
|
-
* user. If the invite targets a group, this mutation also ensures membership.
|
|
1994
|
-
*/
|
|
1995
|
-
export const inviteAcceptByToken = mutation({
|
|
1996
|
-
args: {
|
|
1997
|
-
tokenHash: v.string(),
|
|
1998
|
-
acceptedByUserId: v.id("User"),
|
|
1999
|
-
},
|
|
2000
|
-
returns: vInviteAcceptByTokenResult,
|
|
2001
|
-
handler: async (ctx, { tokenHash, acceptedByUserId }) => {
|
|
2002
|
-
const invite = await ctx.db
|
|
2003
|
-
.query("GroupInvite")
|
|
2004
|
-
.withIndex("token_hash", (q) => q.eq("tokenHash", tokenHash))
|
|
2005
|
-
.first();
|
|
2006
|
-
|
|
2007
|
-
if (invite === null) {
|
|
2008
|
-
throw new ConvexError({
|
|
2009
|
-
code: "INVITE_NOT_FOUND",
|
|
2010
|
-
message: "Invite not found",
|
|
2011
|
-
});
|
|
2012
|
-
}
|
|
2013
|
-
|
|
2014
|
-
const now = Date.now();
|
|
2015
|
-
if (invite.status === "pending") {
|
|
2016
|
-
if (invite.expiresTime !== undefined && invite.expiresTime <= now) {
|
|
2017
|
-
await ctx.db.patch("GroupInvite", invite._id, { status: "expired" });
|
|
2018
|
-
throw new ConvexError({
|
|
2019
|
-
code: "INVITE_EXPIRED",
|
|
2020
|
-
message: "Invite has expired",
|
|
2021
|
-
inviteId: invite._id,
|
|
2022
|
-
});
|
|
2023
|
-
}
|
|
2024
|
-
} else if (invite.status === "accepted") {
|
|
2025
|
-
if (invite.acceptedByUserId !== acceptedByUserId) {
|
|
2026
|
-
throw new ConvexError({
|
|
2027
|
-
code: "INVITE_ALREADY_ACCEPTED",
|
|
2028
|
-
message: "Invite already accepted by another user",
|
|
2029
|
-
inviteId: invite._id,
|
|
2030
|
-
});
|
|
2031
|
-
}
|
|
2032
|
-
} else {
|
|
2033
|
-
throw new ConvexError({
|
|
2034
|
-
code: "INVITE_NOT_PENDING",
|
|
2035
|
-
message: `Cannot accept invite with status "${invite.status}"`,
|
|
2036
|
-
inviteId: invite._id,
|
|
2037
|
-
currentStatus: invite.status,
|
|
2038
|
-
});
|
|
2039
|
-
}
|
|
2040
|
-
|
|
2041
|
-
if (invite.email !== undefined) {
|
|
2042
|
-
const user = await ctx.db.get("User", acceptedByUserId);
|
|
2043
|
-
const normalizedInviteEmail = invite.email.trim().toLowerCase();
|
|
2044
|
-
const normalizedUserEmail = user?.email?.trim().toLowerCase();
|
|
2045
|
-
|
|
2046
|
-
if (
|
|
2047
|
-
normalizedUserEmail === undefined ||
|
|
2048
|
-
normalizedUserEmail !== normalizedInviteEmail
|
|
2049
|
-
) {
|
|
2050
|
-
throw new ConvexError({
|
|
2051
|
-
code: "INVITE_EMAIL_MISMATCH",
|
|
2052
|
-
message: "Invite email does not match accepting user's email",
|
|
2053
|
-
inviteId: invite._id,
|
|
2054
|
-
});
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
|
|
2058
|
-
let membershipStatus: "joined" | "already_joined" | "not_applicable" =
|
|
2059
|
-
"not_applicable";
|
|
2060
|
-
let memberId: Id<"GroupMember"> | undefined;
|
|
2061
|
-
|
|
2062
|
-
if (invite.groupId !== undefined) {
|
|
2063
|
-
const existingMembership = await ctx.db
|
|
2064
|
-
.query("GroupMember")
|
|
2065
|
-
.withIndex("group_id_user_id", (q) =>
|
|
2066
|
-
q.eq("groupId", invite.groupId!).eq("userId", acceptedByUserId),
|
|
2067
|
-
)
|
|
2068
|
-
.unique();
|
|
2069
|
-
|
|
2070
|
-
if (existingMembership !== null) {
|
|
2071
|
-
membershipStatus = "already_joined";
|
|
2072
|
-
memberId = existingMembership._id;
|
|
2073
|
-
} else {
|
|
2074
|
-
memberId = await ctx.db.insert("GroupMember", {
|
|
2075
|
-
groupId: invite.groupId,
|
|
2076
|
-
userId: acceptedByUserId,
|
|
2077
|
-
role: invite.role,
|
|
2078
|
-
status: "active",
|
|
2079
|
-
});
|
|
2080
|
-
membershipStatus = "joined";
|
|
2081
|
-
}
|
|
2082
|
-
}
|
|
2083
|
-
|
|
2084
|
-
if (invite.status === "pending") {
|
|
2085
|
-
await ctx.db.patch("GroupInvite", invite._id, {
|
|
2086
|
-
status: "accepted",
|
|
2087
|
-
acceptedByUserId,
|
|
2088
|
-
acceptedTime: now,
|
|
2089
|
-
});
|
|
2090
|
-
}
|
|
2091
|
-
|
|
2092
|
-
const inviteStatus: "accepted" | "already_accepted" =
|
|
2093
|
-
invite.status === "accepted" ? "already_accepted" : "accepted";
|
|
2094
|
-
|
|
2095
|
-
return {
|
|
2096
|
-
inviteId: invite._id,
|
|
2097
|
-
groupId: invite.groupId ?? null,
|
|
2098
|
-
memberId,
|
|
2099
|
-
inviteStatus,
|
|
2100
|
-
membershipStatus,
|
|
2101
|
-
};
|
|
2102
|
-
},
|
|
2103
|
-
});
|
|
2104
|
-
|
|
2105
|
-
/**
|
|
2106
|
-
* Revoke a pending invitation.
|
|
2107
|
-
*
|
|
2108
|
-
* Marks the invite as "revoked". Throws a structured `ConvexError` when the
|
|
2109
|
-
* invite doesn't exist or is not currently pending.
|
|
2110
|
-
*/
|
|
2111
|
-
export const inviteRevoke = mutation({
|
|
2112
|
-
args: { inviteId: v.id("GroupInvite") },
|
|
2113
|
-
returns: v.null(),
|
|
2114
|
-
handler: async (ctx, { inviteId }) => {
|
|
2115
|
-
const invite = await ctx.db.get("GroupInvite", inviteId);
|
|
2116
|
-
if (invite === null) {
|
|
2117
|
-
throw new ConvexError({
|
|
2118
|
-
code: "INVITE_NOT_FOUND",
|
|
2119
|
-
message: "Invite not found",
|
|
2120
|
-
inviteId,
|
|
2121
|
-
});
|
|
2122
|
-
}
|
|
2123
|
-
if (invite.status !== "pending") {
|
|
2124
|
-
throw new ConvexError({
|
|
2125
|
-
code: "INVITE_NOT_PENDING",
|
|
2126
|
-
message: `Cannot revoke invite with status "${invite.status}"`,
|
|
2127
|
-
inviteId,
|
|
2128
|
-
currentStatus: invite.status,
|
|
2129
|
-
});
|
|
2130
|
-
}
|
|
2131
|
-
await ctx.db.patch("GroupInvite", inviteId, { status: "revoked" });
|
|
2132
|
-
return null;
|
|
2133
|
-
},
|
|
2134
|
-
});
|
|
2135
|
-
|
|
2136
|
-
// ============================================================================
|
|
2137
|
-
// Enterprise
|
|
2138
|
-
// ============================================================================
|
|
2139
|
-
|
|
2140
|
-
/** Create an enterprise record attached to a root group. */
|
|
2141
|
-
export const enterpriseCreate = mutation({
|
|
2142
|
-
args: {
|
|
2143
|
-
groupId: v.id("Group"),
|
|
2144
|
-
slug: v.optional(v.string()),
|
|
2145
|
-
name: v.optional(v.string()),
|
|
2146
|
-
status: v.optional(vEnterpriseStatus),
|
|
2147
|
-
config: v.optional(v.any()),
|
|
2148
|
-
extend: v.optional(v.any()),
|
|
2149
|
-
},
|
|
2150
|
-
returns: v.id("Enterprise"),
|
|
2151
|
-
handler: async (ctx, args) => {
|
|
2152
|
-
const existing = await ctx.db
|
|
2153
|
-
.query("Enterprise")
|
|
2154
|
-
.withIndex("group_id", (idx) => idx.eq("groupId", args.groupId))
|
|
2155
|
-
.first();
|
|
2156
|
-
if (existing) {
|
|
2157
|
-
throw new ConvexError({
|
|
2158
|
-
code: "ENTERPRISE_ALREADY_EXISTS",
|
|
2159
|
-
message: "An enterprise record already exists for this group.",
|
|
2160
|
-
});
|
|
2161
|
-
}
|
|
2162
|
-
return await ctx.db.insert("Enterprise", {
|
|
2163
|
-
...args,
|
|
2164
|
-
status: args.status ?? "draft",
|
|
2165
|
-
});
|
|
2166
|
-
},
|
|
2167
|
-
});
|
|
2168
|
-
|
|
2169
|
-
/** Retrieve an enterprise record by ID. */
|
|
2170
|
-
export const enterpriseGet = query({
|
|
2171
|
-
args: { enterpriseId: v.id("Enterprise") },
|
|
2172
|
-
returns: v.union(vEnterpriseDoc, v.null()),
|
|
2173
|
-
handler: async (ctx, { enterpriseId }) => {
|
|
2174
|
-
return await ctx.db.get("Enterprise", enterpriseId);
|
|
2175
|
-
},
|
|
2176
|
-
});
|
|
2177
|
-
|
|
2178
|
-
/** Retrieve an enterprise record by group ID. */
|
|
2179
|
-
export const enterpriseGetByGroup = query({
|
|
2180
|
-
args: { groupId: v.id("Group") },
|
|
2181
|
-
returns: v.union(vEnterpriseDoc, v.null()),
|
|
2182
|
-
handler: async (ctx, { groupId }) => {
|
|
2183
|
-
return await ctx.db
|
|
2184
|
-
.query("Enterprise")
|
|
2185
|
-
.withIndex("group_id", (idx) => idx.eq("groupId", groupId))
|
|
2186
|
-
.first();
|
|
2187
|
-
},
|
|
2188
|
-
});
|
|
2189
|
-
|
|
2190
|
-
/** Retrieve an enterprise record by a linked domain. */
|
|
2191
|
-
export const enterpriseGetByDomain = query({
|
|
2192
|
-
args: { domain: v.string() },
|
|
2193
|
-
returns: v.union(
|
|
2194
|
-
v.object({
|
|
2195
|
-
enterprise: vEnterpriseDoc,
|
|
2196
|
-
domain: vEnterpriseDomainDoc,
|
|
2197
|
-
}),
|
|
2198
|
-
v.null(),
|
|
2199
|
-
),
|
|
2200
|
-
handler: async (ctx, { domain }) => {
|
|
2201
|
-
const domainRow = await ctx.db
|
|
2202
|
-
.query("EnterpriseDomain")
|
|
2203
|
-
.withIndex("domain", (idx) => idx.eq("domain", domain))
|
|
2204
|
-
.first();
|
|
2205
|
-
if (!domainRow) {
|
|
2206
|
-
return null;
|
|
2207
|
-
}
|
|
2208
|
-
const enterprise = await ctx.db.get("Enterprise", domainRow.enterpriseId);
|
|
2209
|
-
if (!enterprise) {
|
|
2210
|
-
return null;
|
|
2211
|
-
}
|
|
2212
|
-
return { enterprise, domain: domainRow };
|
|
2213
|
-
},
|
|
2214
|
-
});
|
|
2215
|
-
|
|
2216
|
-
/** List enterprises with lightweight filtering and cursor pagination. */
|
|
2217
|
-
export const enterpriseList = query({
|
|
2218
|
-
args: {
|
|
2219
|
-
where: v.optional(
|
|
2220
|
-
v.object({
|
|
2221
|
-
groupId: v.optional(v.id("Group")),
|
|
2222
|
-
slug: v.optional(v.string()),
|
|
2223
|
-
status: v.optional(vEnterpriseStatus),
|
|
2224
|
-
}),
|
|
2225
|
-
),
|
|
2226
|
-
limit: v.optional(v.number()),
|
|
2227
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
2228
|
-
orderBy: v.optional(
|
|
2229
|
-
v.union(
|
|
2230
|
-
v.literal("_creationTime"),
|
|
2231
|
-
v.literal("name"),
|
|
2232
|
-
v.literal("slug"),
|
|
2233
|
-
v.literal("status"),
|
|
2234
|
-
),
|
|
2235
|
-
),
|
|
2236
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
2237
|
-
},
|
|
2238
|
-
returns: vPaginated(vEnterpriseDoc),
|
|
2239
|
-
handler: async (ctx, args) => {
|
|
2240
|
-
const where = args.where ?? {};
|
|
2241
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
2242
|
-
const order = args.order ?? "desc";
|
|
2243
|
-
|
|
2244
|
-
let q;
|
|
2245
|
-
if (where.groupId !== undefined) {
|
|
2246
|
-
q = ctx.db
|
|
2247
|
-
.query("Enterprise")
|
|
2248
|
-
.withIndex("group_id", (idx) => idx.eq("groupId", where.groupId!));
|
|
2249
|
-
} else if (where.slug !== undefined) {
|
|
2250
|
-
q = ctx.db
|
|
2251
|
-
.query("Enterprise")
|
|
2252
|
-
.withIndex("slug", (idx) => idx.eq("slug", where.slug!));
|
|
2253
|
-
} else if (where.status !== undefined) {
|
|
2254
|
-
q = ctx.db
|
|
2255
|
-
.query("Enterprise")
|
|
2256
|
-
.withIndex("status", (idx) => idx.eq("status", where.status!));
|
|
2257
|
-
} else {
|
|
2258
|
-
q = ctx.db.query("Enterprise");
|
|
2259
|
-
}
|
|
2260
|
-
|
|
2261
|
-
if (where.groupId !== undefined && where.slug !== undefined) {
|
|
2262
|
-
q = q.filter((f) => f.eq(f.field("slug"), where.slug!));
|
|
2263
|
-
}
|
|
2264
|
-
if (where.status !== undefined && where.groupId === undefined) {
|
|
2265
|
-
// already handled by index in the dedicated branch
|
|
2266
|
-
} else if (where.status !== undefined) {
|
|
2267
|
-
q = q.filter((f) => f.eq(f.field("status"), where.status!));
|
|
2268
|
-
}
|
|
2269
|
-
|
|
2270
|
-
q = q.order(order);
|
|
2271
|
-
const all = await q.collect();
|
|
2272
|
-
let startIdx = 0;
|
|
2273
|
-
if (args.cursor) {
|
|
2274
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
2275
|
-
if (cursorIdx !== -1) {
|
|
2276
|
-
startIdx = cursorIdx + 1;
|
|
2277
|
-
}
|
|
2278
|
-
}
|
|
2279
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
2280
|
-
const hasMore = page.length > limit;
|
|
2281
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
2282
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
2283
|
-
return { items, nextCursor };
|
|
2284
|
-
},
|
|
2285
|
-
});
|
|
2286
|
-
|
|
2287
|
-
/** Patch an enterprise record. */
|
|
2288
|
-
export const enterpriseUpdate = mutation({
|
|
2289
|
-
args: { enterpriseId: v.id("Enterprise"), data: v.any() },
|
|
2290
|
-
returns: v.null(),
|
|
2291
|
-
handler: async (ctx, { enterpriseId, data }) => {
|
|
2292
|
-
await ctx.db.patch(enterpriseId, data);
|
|
2293
|
-
return null;
|
|
2294
|
-
},
|
|
2295
|
-
});
|
|
2296
|
-
|
|
2297
|
-
/** Delete an enterprise record. */
|
|
2298
|
-
export const enterpriseDelete = mutation({
|
|
2299
|
-
args: { enterpriseId: v.id("Enterprise") },
|
|
2300
|
-
returns: v.null(),
|
|
2301
|
-
handler: async (ctx, { enterpriseId }) => {
|
|
2302
|
-
const domains = await ctx.db
|
|
2303
|
-
.query("EnterpriseDomain")
|
|
2304
|
-
.withIndex("enterprise_id", (idx) => idx.eq("enterpriseId", enterpriseId))
|
|
2305
|
-
.collect();
|
|
2306
|
-
for (const domain of domains) {
|
|
2307
|
-
await ctx.db.delete(domain._id);
|
|
2308
|
-
}
|
|
2309
|
-
await ctx.db.delete(enterpriseId);
|
|
2310
|
-
return null;
|
|
2311
|
-
},
|
|
2312
|
-
});
|
|
2313
|
-
|
|
2314
|
-
/** Link a domain to an enterprise record. */
|
|
2315
|
-
export const enterpriseDomainAdd = mutation({
|
|
2316
|
-
args: {
|
|
2317
|
-
enterpriseId: v.id("Enterprise"),
|
|
2318
|
-
groupId: v.id("Group"),
|
|
2319
|
-
domain: v.string(),
|
|
2320
|
-
isPrimary: v.optional(v.boolean()),
|
|
2321
|
-
verifiedAt: v.optional(v.number()),
|
|
2322
|
-
},
|
|
2323
|
-
returns: v.id("EnterpriseDomain"),
|
|
2324
|
-
handler: async (ctx, args) => {
|
|
2325
|
-
const existingByDomain = await ctx.db
|
|
2326
|
-
.query("EnterpriseDomain")
|
|
2327
|
-
.withIndex("domain", (idx) => idx.eq("domain", args.domain))
|
|
2328
|
-
.first();
|
|
2329
|
-
if (
|
|
2330
|
-
existingByDomain &&
|
|
2331
|
-
existingByDomain.enterpriseId !== args.enterpriseId
|
|
2332
|
-
) {
|
|
2333
|
-
throw new ConvexError({
|
|
2334
|
-
code: "ENTERPRISE_DOMAIN_TAKEN",
|
|
2335
|
-
message: "That domain is already attached to another enterprise.",
|
|
2336
|
-
});
|
|
2337
|
-
}
|
|
2338
|
-
|
|
2339
|
-
const existingForEnterprise = await ctx.db
|
|
2340
|
-
.query("EnterpriseDomain")
|
|
2341
|
-
.withIndex("enterprise_id", (idx) =>
|
|
2342
|
-
idx.eq("enterpriseId", args.enterpriseId),
|
|
2343
|
-
)
|
|
2344
|
-
.collect();
|
|
2345
|
-
|
|
2346
|
-
for (const row of existingForEnterprise) {
|
|
2347
|
-
if (row.domain === args.domain) {
|
|
2348
|
-
await ctx.db.patch(row._id, {
|
|
2349
|
-
isPrimary: args.isPrimary ?? row.isPrimary,
|
|
2350
|
-
verifiedAt: args.verifiedAt ?? row.verifiedAt,
|
|
2351
|
-
});
|
|
2352
|
-
return row._id;
|
|
2353
|
-
}
|
|
2354
|
-
}
|
|
2355
|
-
|
|
2356
|
-
if (args.isPrimary === true) {
|
|
2357
|
-
for (const row of existingForEnterprise) {
|
|
2358
|
-
if (row.isPrimary) {
|
|
2359
|
-
await ctx.db.patch(row._id, { isPrimary: false });
|
|
2360
|
-
}
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
|
|
2364
|
-
return await ctx.db.insert("EnterpriseDomain", {
|
|
2365
|
-
...args,
|
|
2366
|
-
isPrimary: args.isPrimary ?? existingForEnterprise.length === 0,
|
|
2367
|
-
});
|
|
2368
|
-
},
|
|
2369
|
-
});
|
|
2370
|
-
|
|
2371
|
-
/** List domains linked to an enterprise. */
|
|
2372
|
-
export const enterpriseDomainList = query({
|
|
2373
|
-
args: { enterpriseId: v.id("Enterprise") },
|
|
2374
|
-
returns: v.array(vEnterpriseDomainDoc),
|
|
2375
|
-
handler: async (ctx, { enterpriseId }) => {
|
|
2376
|
-
return await ctx.db
|
|
2377
|
-
.query("EnterpriseDomain")
|
|
2378
|
-
.withIndex("enterprise_id", (idx) => idx.eq("enterpriseId", enterpriseId))
|
|
2379
|
-
.collect();
|
|
2380
|
-
},
|
|
2381
|
-
});
|
|
2382
|
-
|
|
2383
|
-
/** Remove a linked enterprise domain. */
|
|
2384
|
-
export const enterpriseDomainDelete = mutation({
|
|
2385
|
-
args: { domainId: v.id("EnterpriseDomain") },
|
|
2386
|
-
returns: v.null(),
|
|
2387
|
-
handler: async (ctx, { domainId }) => {
|
|
2388
|
-
await ctx.db.delete(domainId);
|
|
2389
|
-
return null;
|
|
2390
|
-
},
|
|
2391
|
-
});
|
|
2392
|
-
|
|
2393
|
-
/** Create or rotate SCIM configuration for an enterprise. */
|
|
2394
|
-
export const enterpriseScimConfigUpsert = mutation({
|
|
2395
|
-
args: {
|
|
2396
|
-
enterpriseId: v.id("Enterprise"),
|
|
2397
|
-
groupId: v.id("Group"),
|
|
2398
|
-
status: vScimStatus,
|
|
2399
|
-
basePath: v.string(),
|
|
2400
|
-
tokenHash: v.string(),
|
|
2401
|
-
lastRotatedAt: v.optional(v.number()),
|
|
2402
|
-
deprovisionMode: v.optional(v.union(v.literal("soft"), v.literal("hard"))),
|
|
2403
|
-
extend: v.optional(v.any()),
|
|
2404
|
-
},
|
|
2405
|
-
returns: v.id("EnterpriseScimConfig"),
|
|
2406
|
-
handler: async (ctx, args) => {
|
|
2407
|
-
const existing = await ctx.db
|
|
2408
|
-
.query("EnterpriseScimConfig")
|
|
2409
|
-
.withIndex("enterprise_id", (idx) =>
|
|
2410
|
-
idx.eq("enterpriseId", args.enterpriseId),
|
|
2411
|
-
)
|
|
2412
|
-
.first();
|
|
2413
|
-
if (existing) {
|
|
2414
|
-
await ctx.db.patch(existing._id, args);
|
|
2415
|
-
return existing._id;
|
|
2416
|
-
}
|
|
2417
|
-
return await ctx.db.insert("EnterpriseScimConfig", args);
|
|
2418
|
-
},
|
|
2419
|
-
});
|
|
2420
|
-
|
|
2421
|
-
export const enterpriseScimConfigGetByEnterprise = query({
|
|
2422
|
-
args: { enterpriseId: v.id("Enterprise") },
|
|
2423
|
-
returns: v.union(vEnterpriseScimConfigDoc, v.null()),
|
|
2424
|
-
handler: async (ctx, { enterpriseId }) => {
|
|
2425
|
-
return await ctx.db
|
|
2426
|
-
.query("EnterpriseScimConfig")
|
|
2427
|
-
.withIndex("enterprise_id", (idx) => idx.eq("enterpriseId", enterpriseId))
|
|
2428
|
-
.first();
|
|
2429
|
-
},
|
|
2430
|
-
});
|
|
2431
|
-
|
|
2432
|
-
export const enterpriseScimConfigGetByTokenHash = query({
|
|
2433
|
-
args: { tokenHash: v.string() },
|
|
2434
|
-
returns: v.union(vEnterpriseScimConfigDoc, v.null()),
|
|
2435
|
-
handler: async (ctx, { tokenHash }) => {
|
|
2436
|
-
return await ctx.db
|
|
2437
|
-
.query("EnterpriseScimConfig")
|
|
2438
|
-
.withIndex("token_hash", (idx) => idx.eq("tokenHash", tokenHash))
|
|
2439
|
-
.first();
|
|
2440
|
-
},
|
|
2441
|
-
});
|
|
2442
|
-
|
|
2443
|
-
export const enterpriseScimIdentityGet = query({
|
|
2444
|
-
args: {
|
|
2445
|
-
enterpriseId: v.id("Enterprise"),
|
|
2446
|
-
resourceType: vScimResourceType,
|
|
2447
|
-
externalId: v.string(),
|
|
2448
|
-
},
|
|
2449
|
-
returns: v.union(vEnterpriseScimIdentityDoc, v.null()),
|
|
2450
|
-
handler: async (ctx, args) => {
|
|
2451
|
-
return await ctx.db
|
|
2452
|
-
.query("EnterpriseScimIdentity")
|
|
2453
|
-
.withIndex("enterprise_id_resource_type_external_id", (idx) =>
|
|
2454
|
-
idx
|
|
2455
|
-
.eq("enterpriseId", args.enterpriseId)
|
|
2456
|
-
.eq("resourceType", args.resourceType)
|
|
2457
|
-
.eq("externalId", args.externalId),
|
|
2458
|
-
)
|
|
2459
|
-
.first();
|
|
2460
|
-
},
|
|
2461
|
-
});
|
|
2462
|
-
|
|
2463
|
-
export const enterpriseScimIdentityGetByUser = query({
|
|
2464
|
-
args: { userId: v.id("User") },
|
|
2465
|
-
returns: v.union(vEnterpriseScimIdentityDoc, v.null()),
|
|
2466
|
-
handler: async (ctx, { userId }) => {
|
|
2467
|
-
return await ctx.db
|
|
2468
|
-
.query("EnterpriseScimIdentity")
|
|
2469
|
-
.withIndex("user_id", (idx) => idx.eq("userId", userId))
|
|
2470
|
-
.first();
|
|
2471
|
-
},
|
|
2472
|
-
});
|
|
2473
|
-
|
|
2474
|
-
export const enterpriseScimIdentityGetByMappedGroup = query({
|
|
2475
|
-
args: { mappedGroupId: v.id("Group") },
|
|
2476
|
-
returns: v.union(vEnterpriseScimIdentityDoc, v.null()),
|
|
2477
|
-
handler: async (ctx, { mappedGroupId }) => {
|
|
2478
|
-
return await ctx.db
|
|
2479
|
-
.query("EnterpriseScimIdentity")
|
|
2480
|
-
.withIndex("mapped_group_id", (idx) =>
|
|
2481
|
-
idx.eq("mappedGroupId", mappedGroupId),
|
|
2482
|
-
)
|
|
2483
|
-
.first();
|
|
2484
|
-
},
|
|
2485
|
-
});
|
|
2486
|
-
|
|
2487
|
-
export const enterpriseScimIdentityListByEnterprise = query({
|
|
2488
|
-
args: { enterpriseId: v.id("Enterprise") },
|
|
2489
|
-
returns: v.array(vEnterpriseScimIdentityDoc),
|
|
2490
|
-
handler: async (ctx, { enterpriseId }) => {
|
|
2491
|
-
return await ctx.db
|
|
2492
|
-
.query("EnterpriseScimIdentity")
|
|
2493
|
-
.withIndex("enterprise_id", (idx) => idx.eq("enterpriseId", enterpriseId))
|
|
2494
|
-
.collect();
|
|
2495
|
-
},
|
|
2496
|
-
});
|
|
2497
|
-
|
|
2498
|
-
export const enterpriseScimIdentityUpsert = mutation({
|
|
2499
|
-
args: {
|
|
2500
|
-
enterpriseId: v.id("Enterprise"),
|
|
2501
|
-
groupId: v.id("Group"),
|
|
2502
|
-
resourceType: vScimResourceType,
|
|
2503
|
-
externalId: v.string(),
|
|
2504
|
-
userId: v.optional(v.id("User")),
|
|
2505
|
-
mappedGroupId: v.optional(v.id("Group")),
|
|
2506
|
-
lastProvisionedAt: v.optional(v.number()),
|
|
2507
|
-
active: v.optional(v.boolean()),
|
|
2508
|
-
raw: v.optional(v.any()),
|
|
2509
|
-
},
|
|
2510
|
-
returns: v.id("EnterpriseScimIdentity"),
|
|
2511
|
-
handler: async (ctx, args) => {
|
|
2512
|
-
const existing = await ctx.db
|
|
2513
|
-
.query("EnterpriseScimIdentity")
|
|
2514
|
-
.withIndex("enterprise_id_resource_type_external_id", (idx) =>
|
|
2515
|
-
idx
|
|
2516
|
-
.eq("enterpriseId", args.enterpriseId)
|
|
2517
|
-
.eq("resourceType", args.resourceType)
|
|
2518
|
-
.eq("externalId", args.externalId),
|
|
2519
|
-
)
|
|
2520
|
-
.first();
|
|
2521
|
-
if (existing) {
|
|
2522
|
-
await ctx.db.patch(existing._id, args);
|
|
2523
|
-
return existing._id;
|
|
2524
|
-
}
|
|
2525
|
-
return await ctx.db.insert("EnterpriseScimIdentity", args);
|
|
2526
|
-
},
|
|
2527
|
-
});
|
|
2528
|
-
|
|
2529
|
-
export const enterpriseScimIdentityDelete = mutation({
|
|
2530
|
-
args: { identityId: v.id("EnterpriseScimIdentity") },
|
|
2531
|
-
returns: v.null(),
|
|
2532
|
-
handler: async (ctx, { identityId }) => {
|
|
2533
|
-
await ctx.db.delete(identityId);
|
|
2534
|
-
return null;
|
|
2535
|
-
},
|
|
2536
|
-
});
|
|
2537
|
-
|
|
2538
|
-
export const enterpriseAuditEventCreate = mutation({
|
|
2539
|
-
args: {
|
|
2540
|
-
enterpriseId: v.id("Enterprise"),
|
|
2541
|
-
groupId: v.id("Group"),
|
|
2542
|
-
eventType: v.string(),
|
|
2543
|
-
actorType: vAuditActorType,
|
|
2544
|
-
actorId: v.optional(v.string()),
|
|
2545
|
-
subjectType: v.string(),
|
|
2546
|
-
subjectId: v.optional(v.string()),
|
|
2547
|
-
status: vAuditStatus,
|
|
2548
|
-
occurredAt: v.number(),
|
|
2549
|
-
requestId: v.optional(v.string()),
|
|
2550
|
-
ip: v.optional(v.string()),
|
|
2551
|
-
metadata: v.optional(v.any()),
|
|
2552
|
-
},
|
|
2553
|
-
returns: v.id("EnterpriseAuditEvent"),
|
|
2554
|
-
handler: async (ctx, args) => {
|
|
2555
|
-
return await ctx.db.insert("EnterpriseAuditEvent", args);
|
|
2556
|
-
},
|
|
2557
|
-
});
|
|
2558
|
-
|
|
2559
|
-
export const enterpriseAuditEventList = query({
|
|
2560
|
-
args: {
|
|
2561
|
-
enterpriseId: v.optional(v.id("Enterprise")),
|
|
2562
|
-
groupId: v.optional(v.id("Group")),
|
|
2563
|
-
limit: v.optional(v.number()),
|
|
2564
|
-
},
|
|
2565
|
-
returns: v.array(vEnterpriseAuditEventDoc),
|
|
2566
|
-
handler: async (ctx, args) => {
|
|
2567
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
2568
|
-
if (args.enterpriseId !== undefined) {
|
|
2569
|
-
return await ctx.db
|
|
2570
|
-
.query("EnterpriseAuditEvent")
|
|
2571
|
-
.withIndex("enterprise_id_occurred_at", (idx) =>
|
|
2572
|
-
idx.eq("enterpriseId", args.enterpriseId!),
|
|
2573
|
-
)
|
|
2574
|
-
.order("desc")
|
|
2575
|
-
.take(limit);
|
|
2576
|
-
}
|
|
2577
|
-
if (args.groupId !== undefined) {
|
|
2578
|
-
return await ctx.db
|
|
2579
|
-
.query("EnterpriseAuditEvent")
|
|
2580
|
-
.withIndex("group_id_occurred_at", (idx) =>
|
|
2581
|
-
idx.eq("groupId", args.groupId!),
|
|
2582
|
-
)
|
|
2583
|
-
.order("desc")
|
|
2584
|
-
.take(limit);
|
|
2585
|
-
}
|
|
2586
|
-
return await ctx.db.query("EnterpriseAuditEvent").order("desc").take(limit);
|
|
2587
|
-
},
|
|
2588
|
-
});
|
|
2589
|
-
|
|
2590
|
-
export const enterpriseWebhookEndpointCreate = mutation({
|
|
2591
|
-
args: {
|
|
2592
|
-
enterpriseId: v.id("Enterprise"),
|
|
2593
|
-
groupId: v.id("Group"),
|
|
2594
|
-
url: v.string(),
|
|
2595
|
-
status: v.optional(vWebhookEndpointStatus),
|
|
2596
|
-
secretHash: v.string(),
|
|
2597
|
-
subscriptions: v.array(v.string()),
|
|
2598
|
-
createdByUserId: v.optional(v.id("User")),
|
|
2599
|
-
extend: v.optional(v.any()),
|
|
2600
|
-
},
|
|
2601
|
-
returns: v.id("EnterpriseWebhookEndpoint"),
|
|
2602
|
-
handler: async (ctx, args) => {
|
|
2603
|
-
return await ctx.db.insert("EnterpriseWebhookEndpoint", {
|
|
2604
|
-
...args,
|
|
2605
|
-
status: args.status ?? "active",
|
|
2606
|
-
failureCount: 0,
|
|
2607
|
-
});
|
|
2608
|
-
},
|
|
2609
|
-
});
|
|
2610
|
-
|
|
2611
|
-
export const enterpriseWebhookEndpointList = query({
|
|
2612
|
-
args: { enterpriseId: v.id("Enterprise") },
|
|
2613
|
-
returns: v.array(vEnterpriseWebhookEndpointDoc),
|
|
2614
|
-
handler: async (ctx, { enterpriseId }) => {
|
|
2615
|
-
return await ctx.db
|
|
2616
|
-
.query("EnterpriseWebhookEndpoint")
|
|
2617
|
-
.withIndex("enterprise_id", (idx) => idx.eq("enterpriseId", enterpriseId))
|
|
2618
|
-
.collect();
|
|
2619
|
-
},
|
|
2620
|
-
});
|
|
2621
|
-
|
|
2622
|
-
export const enterpriseWebhookEndpointUpdate = mutation({
|
|
2623
|
-
args: { endpointId: v.id("EnterpriseWebhookEndpoint"), data: v.any() },
|
|
2624
|
-
returns: v.null(),
|
|
2625
|
-
handler: async (ctx, { endpointId, data }) => {
|
|
2626
|
-
await ctx.db.patch(endpointId, data);
|
|
2627
|
-
return null;
|
|
2628
|
-
},
|
|
2629
|
-
});
|
|
2630
|
-
|
|
2631
|
-
export const enterpriseWebhookDeliveryEnqueue = mutation({
|
|
2632
|
-
args: {
|
|
2633
|
-
enterpriseId: v.id("Enterprise"),
|
|
2634
|
-
endpointId: v.id("EnterpriseWebhookEndpoint"),
|
|
2635
|
-
auditEventId: v.optional(v.id("EnterpriseAuditEvent")),
|
|
2636
|
-
eventType: v.string(),
|
|
2637
|
-
payload: v.any(),
|
|
2638
|
-
nextAttemptAt: v.number(),
|
|
2639
|
-
},
|
|
2640
|
-
returns: v.id("EnterpriseWebhookDelivery"),
|
|
2641
|
-
handler: async (ctx, args) => {
|
|
2642
|
-
return await ctx.db.insert("EnterpriseWebhookDelivery", {
|
|
2643
|
-
...args,
|
|
2644
|
-
status: "pending",
|
|
2645
|
-
attemptCount: 0,
|
|
2646
|
-
});
|
|
2647
|
-
},
|
|
2648
|
-
});
|
|
2649
|
-
|
|
2650
|
-
export const enterpriseWebhookDeliveryListReady = query({
|
|
2651
|
-
args: { now: v.number(), limit: v.optional(v.number()) },
|
|
2652
|
-
returns: v.array(vEnterpriseWebhookDeliveryDoc),
|
|
2653
|
-
handler: async (ctx, { now, limit }) => {
|
|
2654
|
-
return await ctx.db
|
|
2655
|
-
.query("EnterpriseWebhookDelivery")
|
|
2656
|
-
.withIndex("status_next_attempt_at", (idx) =>
|
|
2657
|
-
idx.eq("status", "pending").lte("nextAttemptAt", now),
|
|
2658
|
-
)
|
|
2659
|
-
.take(Math.min(Math.max(limit ?? 50, 1), 100));
|
|
2660
|
-
},
|
|
2661
|
-
});
|
|
2662
|
-
|
|
2663
|
-
export const enterpriseWebhookDeliveryList = query({
|
|
2664
|
-
args: { enterpriseId: v.id("Enterprise"), limit: v.optional(v.number()) },
|
|
2665
|
-
returns: v.array(vEnterpriseWebhookDeliveryDoc),
|
|
2666
|
-
handler: async (ctx, { enterpriseId, limit }) => {
|
|
2667
|
-
return await ctx.db
|
|
2668
|
-
.query("EnterpriseWebhookDelivery")
|
|
2669
|
-
.withIndex("enterprise_id", (idx) => idx.eq("enterpriseId", enterpriseId))
|
|
2670
|
-
.order("desc")
|
|
2671
|
-
.take(Math.min(Math.max(limit ?? 50, 1), 100));
|
|
2672
|
-
},
|
|
2673
|
-
});
|
|
2674
|
-
|
|
2675
|
-
export const enterpriseWebhookDeliveryPatch = mutation({
|
|
2676
|
-
args: { deliveryId: v.id("EnterpriseWebhookDelivery"), data: v.any() },
|
|
2677
|
-
returns: v.null(),
|
|
2678
|
-
handler: async (ctx, { deliveryId, data }) => {
|
|
2679
|
-
await ctx.db.patch(deliveryId, data);
|
|
2680
|
-
return null;
|
|
2681
|
-
},
|
|
2682
|
-
});
|
|
2683
|
-
|
|
2684
|
-
// ============================================================================
|
|
2685
|
-
// API Keys
|
|
2686
|
-
// ============================================================================
|
|
2687
|
-
|
|
2688
|
-
/**
|
|
2689
|
-
* Insert a new API key record.
|
|
2690
|
-
*
|
|
2691
|
-
* The caller is responsible for hashing the raw key before passing it here —
|
|
2692
|
-
* this function only stores the hash and metadata.
|
|
2693
|
-
*/
|
|
2694
|
-
export const keyInsert = mutation({
|
|
2695
|
-
args: {
|
|
2696
|
-
userId: v.id("User"),
|
|
2697
|
-
prefix: v.string(),
|
|
2698
|
-
hashedKey: v.string(),
|
|
2699
|
-
name: v.string(),
|
|
2700
|
-
scopes: v.array(
|
|
2701
|
-
v.object({
|
|
2702
|
-
resource: v.string(),
|
|
2703
|
-
actions: v.array(v.string()),
|
|
2704
|
-
}),
|
|
2705
|
-
),
|
|
2706
|
-
rateLimit: v.optional(vApiKeyRateLimit),
|
|
2707
|
-
expiresAt: v.optional(v.number()),
|
|
2708
|
-
metadata: v.optional(v.any()),
|
|
2709
|
-
},
|
|
2710
|
-
returns: v.id("ApiKey"),
|
|
2711
|
-
handler: async (ctx, args) => {
|
|
2712
|
-
return await ctx.db.insert("ApiKey", {
|
|
2713
|
-
...args,
|
|
2714
|
-
createdAt: Date.now(),
|
|
2715
|
-
revoked: false,
|
|
2716
|
-
});
|
|
2717
|
-
},
|
|
2718
|
-
});
|
|
2719
|
-
|
|
2720
|
-
/**
|
|
2721
|
-
* Look up an API key by its SHA-256 hash.
|
|
2722
|
-
*
|
|
2723
|
-
* Used during Bearer token verification. Returns the full key record
|
|
2724
|
-
* (including rate limit state) or `null` if not found.
|
|
2725
|
-
*/
|
|
2726
|
-
export const keyGetByHashedKey = query({
|
|
2727
|
-
args: { hashedKey: v.string() },
|
|
2728
|
-
returns: v.union(vApiKeyDoc, v.null()),
|
|
2729
|
-
handler: async (ctx, { hashedKey }) => {
|
|
2730
|
-
return await ctx.db
|
|
2731
|
-
.query("ApiKey")
|
|
2732
|
-
.withIndex("hashed_key", (q) => q.eq("hashedKey", hashedKey))
|
|
2733
|
-
.first();
|
|
2734
|
-
},
|
|
2735
|
-
});
|
|
2736
|
-
|
|
2737
|
-
/**
|
|
2738
|
-
* @deprecated Use `keyList` with `where: { userId }` instead.
|
|
2739
|
-
* Kept for backward compatibility with generated component types.
|
|
2740
|
-
*/
|
|
2741
|
-
export const keyListByUserId = query({
|
|
2742
|
-
args: { userId: v.id("User") },
|
|
2743
|
-
returns: v.array(vApiKeyDoc),
|
|
2744
|
-
handler: async (ctx, { userId }) => {
|
|
2745
|
-
return await ctx.db
|
|
2746
|
-
.query("ApiKey")
|
|
2747
|
-
.withIndex("user_id", (q) => q.eq("userId", userId))
|
|
2748
|
-
.collect();
|
|
2749
|
-
},
|
|
2750
|
-
});
|
|
2751
|
-
|
|
2752
|
-
/**
|
|
2753
|
-
* List API keys with optional filtering, sorting, and pagination.
|
|
2754
|
-
*
|
|
2755
|
-
* Returns `{ items, nextCursor }`. Supports filtering by `userId`,
|
|
2756
|
-
* `revoked`, `name`, and `prefix`.
|
|
2757
|
-
*/
|
|
2758
|
-
export const keyList = query({
|
|
2759
|
-
args: {
|
|
2760
|
-
where: v.optional(
|
|
2761
|
-
v.object({
|
|
2762
|
-
userId: v.optional(v.id("User")),
|
|
2763
|
-
revoked: v.optional(v.boolean()),
|
|
2764
|
-
name: v.optional(v.string()),
|
|
2765
|
-
prefix: v.optional(v.string()),
|
|
2766
|
-
}),
|
|
2767
|
-
),
|
|
2768
|
-
limit: v.optional(v.number()),
|
|
2769
|
-
cursor: v.optional(v.union(v.string(), v.null())),
|
|
2770
|
-
orderBy: v.optional(
|
|
2771
|
-
v.union(
|
|
2772
|
-
v.literal("_creationTime"),
|
|
2773
|
-
v.literal("name"),
|
|
2774
|
-
v.literal("lastUsedAt"),
|
|
2775
|
-
v.literal("expiresAt"),
|
|
2776
|
-
v.literal("revoked"),
|
|
2777
|
-
),
|
|
2778
|
-
),
|
|
2779
|
-
order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
|
|
2780
|
-
},
|
|
2781
|
-
returns: vPaginated(vApiKeyDoc),
|
|
2782
|
-
handler: async (ctx, args) => {
|
|
2783
|
-
const where = args.where ?? {};
|
|
2784
|
-
const limit = Math.min(Math.max(args.limit ?? 50, 1), 100);
|
|
2785
|
-
const order = args.order ?? "desc";
|
|
2786
|
-
|
|
2787
|
-
let q;
|
|
2788
|
-
if (where.userId !== undefined) {
|
|
2789
|
-
q = ctx.db
|
|
2790
|
-
.query("ApiKey")
|
|
2791
|
-
.withIndex("user_id", (idx) => idx.eq("userId", where.userId!));
|
|
2792
|
-
} else {
|
|
2793
|
-
q = ctx.db.query("ApiKey");
|
|
2794
|
-
}
|
|
2795
|
-
|
|
2796
|
-
if (where.revoked !== undefined) {
|
|
2797
|
-
q = q.filter((f) => f.eq(f.field("revoked"), where.revoked!));
|
|
2798
|
-
}
|
|
2799
|
-
if (where.name !== undefined) {
|
|
2800
|
-
q = q.filter((f) => f.eq(f.field("name"), where.name!));
|
|
2801
|
-
}
|
|
2802
|
-
if (where.prefix !== undefined) {
|
|
2803
|
-
q = q.filter((f) => f.eq(f.field("prefix"), where.prefix!));
|
|
2804
|
-
}
|
|
2805
|
-
|
|
2806
|
-
q = q.order(order);
|
|
2807
|
-
|
|
2808
|
-
const all = await q.collect();
|
|
2809
|
-
let startIdx = 0;
|
|
2810
|
-
if (args.cursor) {
|
|
2811
|
-
const cursorIdx = all.findIndex((doc) => doc._id === args.cursor);
|
|
2812
|
-
if (cursorIdx !== -1) {
|
|
2813
|
-
startIdx = cursorIdx + 1;
|
|
2814
|
-
}
|
|
2815
|
-
}
|
|
2816
|
-
const page = all.slice(startIdx, startIdx + limit + 1);
|
|
2817
|
-
const hasMore = page.length > limit;
|
|
2818
|
-
const items = hasMore ? page.slice(0, limit) : page;
|
|
2819
|
-
const nextCursor = hasMore ? items[items.length - 1]._id : null;
|
|
2820
|
-
return { items, nextCursor };
|
|
2821
|
-
},
|
|
2822
|
-
});
|
|
2823
|
-
|
|
2824
|
-
/** Get a single API key by document ID. */
|
|
2825
|
-
export const keyGetById = query({
|
|
2826
|
-
args: { keyId: v.id("ApiKey") },
|
|
2827
|
-
returns: v.union(vApiKeyDoc, v.null()),
|
|
2828
|
-
handler: async (ctx, { keyId }) => {
|
|
2829
|
-
return await ctx.db.get("ApiKey", keyId);
|
|
2830
|
-
},
|
|
2831
|
-
});
|
|
2832
|
-
|
|
2833
|
-
/**
|
|
2834
|
-
* Patch an API key record. Used for updating name, scopes, rate limit config,
|
|
2835
|
-
* revocation, and lastUsedAt / rate limit state tracking.
|
|
2836
|
-
*/
|
|
2837
|
-
export const keyPatch = mutation({
|
|
2838
|
-
args: {
|
|
2839
|
-
keyId: v.id("ApiKey"),
|
|
2840
|
-
data: v.object({
|
|
2841
|
-
name: v.optional(v.string()),
|
|
2842
|
-
scopes: v.optional(v.array(vApiKeyScope)),
|
|
2843
|
-
rateLimit: v.optional(vApiKeyRateLimit),
|
|
2844
|
-
rateLimitState: v.optional(vApiKeyRateLimitState),
|
|
2845
|
-
revoked: v.optional(v.boolean()),
|
|
2846
|
-
lastUsedAt: v.optional(v.number()),
|
|
2847
|
-
}),
|
|
2848
|
-
},
|
|
2849
|
-
returns: v.null(),
|
|
2850
|
-
handler: async (ctx, { keyId, data }) => {
|
|
2851
|
-
const key = await ctx.db.get("ApiKey", keyId);
|
|
2852
|
-
if (key === null) {
|
|
2853
|
-
throw new ConvexError({
|
|
2854
|
-
code: "KEY_NOT_FOUND",
|
|
2855
|
-
message: "API key not found",
|
|
2856
|
-
keyId,
|
|
2857
|
-
});
|
|
2858
|
-
}
|
|
2859
|
-
await ctx.db.patch("ApiKey", keyId, data);
|
|
2860
|
-
return null;
|
|
2861
|
-
},
|
|
2862
|
-
});
|
|
2863
|
-
|
|
2864
|
-
/** Hard delete an API key record. */
|
|
2865
|
-
export const keyDelete = mutation({
|
|
2866
|
-
args: { keyId: v.id("ApiKey") },
|
|
2867
|
-
returns: v.null(),
|
|
2868
|
-
handler: async (ctx, { keyId }) => {
|
|
2869
|
-
const key = await ctx.db.get("ApiKey", keyId);
|
|
2870
|
-
if (key === null) {
|
|
2871
|
-
throw new ConvexError({
|
|
2872
|
-
code: "KEY_NOT_FOUND",
|
|
2873
|
-
message: "API key not found",
|
|
2874
|
-
keyId,
|
|
2875
|
-
});
|
|
2876
|
-
}
|
|
2877
|
-
await ctx.db.delete("ApiKey", keyId);
|
|
2878
|
-
return null;
|
|
2879
|
-
},
|
|
2880
|
-
});
|
|
2881
|
-
|
|
2882
|
-
// ============================================================================
|
|
2883
|
-
// Device Authorization (RFC 8628)
|
|
2884
|
-
// ============================================================================
|
|
2885
|
-
|
|
2886
|
-
/** Insert a new device authorization record. */
|
|
2887
|
-
export const deviceInsert = mutation({
|
|
2888
|
-
args: {
|
|
2889
|
-
deviceCodeHash: v.string(),
|
|
2890
|
-
userCode: v.string(),
|
|
2891
|
-
expiresAt: v.number(),
|
|
2892
|
-
interval: v.number(),
|
|
2893
|
-
status: vDeviceStatus,
|
|
2894
|
-
},
|
|
2895
|
-
returns: v.id("DeviceCode"),
|
|
2896
|
-
handler: async (ctx, args) => {
|
|
2897
|
-
return await ctx.db.insert("DeviceCode", args);
|
|
2898
|
-
},
|
|
2899
|
-
});
|
|
2900
|
-
|
|
2901
|
-
/** Look up a device authorization by its hashed device code. */
|
|
2902
|
-
export const deviceGetByCodeHash = query({
|
|
2903
|
-
args: { deviceCodeHash: v.string() },
|
|
2904
|
-
returns: v.union(vDeviceCodeDoc, v.null()),
|
|
2905
|
-
handler: async (ctx, { deviceCodeHash }) => {
|
|
2906
|
-
return await ctx.db
|
|
2907
|
-
.query("DeviceCode")
|
|
2908
|
-
.withIndex("device_code_hash", (q) =>
|
|
2909
|
-
q.eq("deviceCodeHash", deviceCodeHash),
|
|
2910
|
-
)
|
|
2911
|
-
.first();
|
|
2912
|
-
},
|
|
2913
|
-
});
|
|
2914
|
-
|
|
2915
|
-
/** Look up a pending device authorization by its user code. */
|
|
2916
|
-
export const deviceGetByUserCode = query({
|
|
2917
|
-
args: { userCode: v.string() },
|
|
2918
|
-
returns: v.union(vDeviceCodeDoc, v.null()),
|
|
2919
|
-
handler: async (ctx, { userCode }) => {
|
|
2920
|
-
return await ctx.db
|
|
2921
|
-
.query("DeviceCode")
|
|
2922
|
-
.withIndex("user_code_status", (q) =>
|
|
2923
|
-
q.eq("userCode", userCode).eq("status", "pending"),
|
|
2924
|
-
)
|
|
2925
|
-
.first();
|
|
2926
|
-
},
|
|
2927
|
-
});
|
|
2928
|
-
|
|
2929
|
-
/** Authorize a device code — link it to a user and session. */
|
|
2930
|
-
export const deviceAuthorize = mutation({
|
|
2931
|
-
args: {
|
|
2932
|
-
deviceId: v.id("DeviceCode"),
|
|
2933
|
-
userId: v.id("User"),
|
|
2934
|
-
sessionId: v.id("Session"),
|
|
2935
|
-
},
|
|
2936
|
-
returns: v.null(),
|
|
2937
|
-
handler: async (ctx, { deviceId, userId, sessionId }) => {
|
|
2938
|
-
await ctx.db.patch("DeviceCode", deviceId, {
|
|
2939
|
-
status: "authorized",
|
|
2940
|
-
userId,
|
|
2941
|
-
sessionId,
|
|
2942
|
-
});
|
|
2943
|
-
return null;
|
|
2944
|
-
},
|
|
2945
|
-
});
|
|
2946
|
-
|
|
2947
|
-
/** Update the last-polled timestamp on a device authorization record. */
|
|
2948
|
-
export const deviceUpdateLastPolled = mutation({
|
|
2949
|
-
args: { deviceId: v.id("DeviceCode"), lastPolledAt: v.number() },
|
|
2950
|
-
returns: v.null(),
|
|
2951
|
-
handler: async (ctx, { deviceId, lastPolledAt }) => {
|
|
2952
|
-
await ctx.db.patch("DeviceCode", deviceId, { lastPolledAt });
|
|
2953
|
-
return null;
|
|
2954
|
-
},
|
|
2955
|
-
});
|
|
2956
|
-
|
|
2957
|
-
/** Delete a device authorization record (cleanup after use or expiry). */
|
|
2958
|
-
export const deviceDelete = mutation({
|
|
2959
|
-
args: { deviceId: v.id("DeviceCode") },
|
|
2960
|
-
returns: v.null(),
|
|
2961
|
-
handler: async (ctx, { deviceId }) => {
|
|
2962
|
-
await ctx.db.delete("DeviceCode", deviceId);
|
|
2963
|
-
return null;
|
|
2964
|
-
},
|
|
2965
|
-
});
|
|
1
|
+
export * from "./public/identity";
|
|
2
|
+
export * from "./public/factors";
|
|
3
|
+
export * from "./public/groups";
|
|
4
|
+
export * from "./public/enterprise";
|
|
5
|
+
export * from "./public/keys";
|