create-disposabl-app 0.20.16 → 0.20.18
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/dist/disposabl.js +1 -1
- package/dist/index.js +3 -1
- package/dist/templates/default/.github/scripts/apple.sh +9 -0
- package/dist/templates/default/.github/scripts/release.sh +11 -1
- package/dist/templates/default/.github/workflows/pipeline.yml +1 -1
- package/dist/templates/default/apps/docs/content/mobile.mdx +2 -0
- package/dist/templates/default/apps/docs/content/publishing/apple.mdx +12 -0
- package/dist/templates/default/apps/docs/content/publishing/google-play.mdx +12 -0
- package/dist/templates/default/apps/docs/content/publishing/index.mdx +23 -0
- package/dist/templates/default/apps/mobile/eas.json +2 -0
- package/dist/templates/default/apps/mobile/package.json +15 -14
- package/dist/templates/default/apps/mobile/scripts/android-release-verify.mjs +62 -7
- package/dist/templates/default/apps/mobile/scripts/play-aab.mjs +4 -0
- package/dist/templates/default/apps/mobile/scripts/verify-play-aab.mjs +48 -0
- package/dist/templates/default/bun.lock +111 -169
- package/dist/templates/default/disposabl.json +1 -1
- package/dist/templates/default/package.json +6 -6
- package/dist/templates/default/packages/backend/convex/authEmail.ts +1 -1
- package/dist/templates/default/packages/backend/convex/convex.config.ts +1 -0
- package/dist/templates/default/packages/backend/convex/users/internal.ts +13 -16
- package/dist/templates/default/packages/disposabl-kit/PAYMENTS.md +8 -0
- package/dist/templates/default/packages/disposabl-kit/client/components/cookie-consent.tsx +117 -0
- package/dist/templates/default/packages/disposabl-kit/client/components/google-sign-in.tsx +0 -2
- package/dist/templates/default/packages/disposabl-kit/client/components/legal-page.tsx +19 -1
- package/dist/templates/default/packages/disposabl-kit/client/routes/_auth-pages/verify-email.tsx +4 -2
- package/dist/templates/default/packages/disposabl-kit/client/routes/pricing.tsx +18 -4
- package/dist/templates/default/packages/disposabl-kit/client/styles/cookie-consent.css +54 -0
- package/dist/templates/default/packages/disposabl-kit/legal/config.ts +10 -7
- package/dist/templates/default/packages/disposabl-kit/legal/documents/privacy.ts +3 -1
- package/dist/templates/default/packages/disposabl-kit/legal/index.ts +2 -1
- package/dist/templates/default/packages/disposabl-kit/legal/publisher.ts +5 -1
- package/dist/templates/default/packages/disposabl-kit/legal/types.ts +18 -0
- package/dist/templates/default/packages/disposabl-kit/lib/auth-errors.ts +2 -0
- package/dist/templates/default/packages/disposabl-kit/mobile/billing/account-billing.tsx +168 -99
- package/dist/templates/default/packages/disposabl-kit/mobile/components/auth-ui.tsx +9 -21
- package/dist/templates/default/packages/disposabl-kit/mobile/components/email-verification.tsx +4 -2
- package/dist/templates/default/packages/disposabl-kit/mobile/components/settings-page.tsx +52 -20
- package/dist/templates/default/packages/disposabl-kit/mobile/layout.tsx +13 -4
- package/dist/templates/default/packages/disposabl-kit/mobile/lib/auth-errors.ts +2 -0
- package/dist/templates/default/packages/disposabl-kit/package.json +14 -9
- package/dist/templates/default/packages/disposabl-kit/payments/catalog.ts +6 -0
- package/dist/templates/default/packages/disposabl-kit/payments/config.ts +5 -3
- package/dist/templates/default/packages/disposabl-kit/server/billing-functions.ts +15 -3
- package/dist/templates/default/packages/disposabl-kit/server/billing-native-capability.ts +33 -6
- package/dist/templates/default/packages/disposabl-kit/server/billing.ts +11 -3
- package/dist/templates/default/packages/disposabl-kit/server/revenuecat-contract.ts +87 -8
- package/dist/templates/default/packages/disposabl-kit/server/revenuecat-functions.ts +34 -8
- package/dist/templates/default/packages/disposabl-kit/server/revenuecat-validator.ts +3 -0
- package/dist/templates/default/packages/tests/billing-setup.test.ts +14 -14
- package/dist/templates/default/packages/tests/billing.test.ts +22 -0
- package/dist/templates/default/packages/tests/components/mobile-account-billing.test.mjs +149 -0
- package/dist/templates/default/packages/tests/flows/email-delivery.e2e.ts +1 -1
- package/dist/templates/default/packages/tests/flows/legal.e2e.ts +7 -5
- package/dist/templates/default/packages/tests/flows/password-backend.e2e.ts +1 -1
- package/dist/templates/default/packages/tests/helpers/auth-email-setup/probe.test.mjs +1 -1
- package/dist/templates/default/packages/tests/ios-ota.test.ts +32 -10
- package/dist/templates/default/packages/tests/mobile-account-billing.test.ts +19 -0
- package/dist/templates/default/packages/tests/native-billing.test.ts +71 -0
- package/dist/templates/default/packages/tests/package-release.test.ts +16 -0
- package/dist/templates/default/packages/tests/revenuecat-inbox.test.ts +91 -3
- package/dist/templates/default/patches/expo-modules-core@58.1.0.patch +23 -0
- package/dist/templates/default/vendor/README.md +4 -10
- package/dist/templates/default/vendor/convex-auth-2.0.0-disposabl.2.patch +2096 -0
- package/dist/templates/default/vendor/convex-auth-2.0.0-disposabl.2.tgz +0 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2096 @@
|
|
|
1
|
+
--- a/package.json
|
|
2
|
+
+++ b/package.json
|
|
3
|
+
@@ -1,6 +1,6 @@
|
|
4
|
+
{
|
|
5
|
+
"name": "@convex-dev/auth",
|
|
6
|
+
- "version": "2.0.0",
|
|
7
|
+
+ "version": "2.0.0-disposabl.2",
|
|
8
|
+
"description": "Authentication for Convex",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"auth",
|
|
11
|
+
--- a/src/browser/sessionManager.test.ts
|
|
12
|
+
+++ b/src/browser/sessionManager.test.ts
|
|
13
|
+
@@ -808,3 +808,44 @@
|
|
14
|
+
expect(storage.entries.size).toBe(0);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
+
|
|
18
|
+
+test("a delayed refresh cannot overwrite a session adopted in another client", async () => {
|
|
19
|
+
+ const storage = new InMemoryStorage();
|
|
20
|
+
+ let started!: () => void;
|
|
21
|
+
+ let release!: () => void;
|
|
22
|
+
+ const waiting = new Promise<void>((resolve) => {
|
|
23
|
+
+ started = resolve;
|
|
24
|
+
+ });
|
|
25
|
+
+ const gate = new Promise<void>((resolve) => {
|
|
26
|
+
+ release = resolve;
|
|
27
|
+
+ });
|
|
28
|
+
+ const config = {
|
|
29
|
+
+ mode: "spa" as const,
|
|
30
|
+
+ storage,
|
|
31
|
+
+ storageNamespace: "handoff-race",
|
|
32
|
+
+ authApi: {
|
|
33
|
+
+ signOut: async () => {},
|
|
34
|
+
+ refreshSession: async () => {
|
|
35
|
+
+ started();
|
|
36
|
+
+ await gate;
|
|
37
|
+
+ return rotated(2);
|
|
38
|
+
+ },
|
|
39
|
+
+ },
|
|
40
|
+
+ };
|
|
41
|
+
+ const oldTab = new AuthClient(config);
|
|
42
|
+
+ await oldTab.init();
|
|
43
|
+
+ await oldTab.setSession(bundle(1));
|
|
44
|
+
+ const newTab = new AuthClient(config);
|
|
45
|
+
+ await newTab.init();
|
|
46
|
+
+ const refresh = oldTab.fetchAccessToken({ forceRefreshToken: true });
|
|
47
|
+
+ await waiting;
|
|
48
|
+
+ const adopt = newTab.setSession(bundle(3));
|
|
49
|
+
+ release();
|
|
50
|
+
+ await Promise.all([refresh, adopt]);
|
|
51
|
+
+ const restarted = new AuthClient(config);
|
|
52
|
+
+ await restarted.init();
|
|
53
|
+
+ expect(restarted.getAccessToken()).toBe("access-3");
|
|
54
|
+
+ oldTab.dispose();
|
|
55
|
+
+ newTab.dispose();
|
|
56
|
+
+ restarted.dispose();
|
|
57
|
+
+});
|
|
58
|
+
--- a/src/browser/sessionManager.ts
|
|
59
|
+
+++ b/src/browser/sessionManager.ts
|
|
60
|
+
@@ -410,7 +410,9 @@
|
|
61
|
+
setSession = async (
|
|
62
|
+
session: TokenBundle | SlimTokenBundle,
|
|
63
|
+
): Promise<void> => {
|
|
64
|
+
- await this.#storeFullTokenResult(session);
|
|
65
|
+
+ await runWithMutex(this.#lockKey, () =>
|
|
66
|
+
+ this.#storeFullTokenResult(session),
|
|
67
|
+
+ );
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
--- a/src/component/_generated/api.ts
|
|
72
|
+
+++ b/src/component/_generated/api.ts
|
|
73
|
+
@@ -9,7 +9,9 @@
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
import type * as crypto from "../crypto.js";
|
|
77
|
+
+import type * as erasure from "../erasure.js";
|
|
78
|
+
import type * as expiry from "../expiry.js";
|
|
79
|
+
+import type * as migration from "../migration.js";
|
|
80
|
+
import type * as public_ from "../public.js";
|
|
81
|
+
import type * as sessions from "../sessions.js";
|
|
82
|
+
|
|
83
|
+
@@ -22,7 +24,9 @@
|
|
84
|
+
|
|
85
|
+
const fullApi: ApiFromModules<{
|
|
86
|
+
crypto: typeof crypto;
|
|
87
|
+
+ erasure: typeof erasure;
|
|
88
|
+
expiry: typeof expiry;
|
|
89
|
+
+ migration: typeof migration;
|
|
90
|
+
public: typeof public_;
|
|
91
|
+
sessions: typeof sessions;
|
|
92
|
+
}> = anyApi as any;
|
|
93
|
+
--- a/src/component/_generated/component.ts
|
|
94
|
+
+++ b/src/component/_generated/component.ts
|
|
95
|
+
@@ -23,6 +23,99 @@
|
|
96
|
+
*/
|
|
97
|
+
export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
98
|
+
{
|
|
99
|
+
+ erasure: {
|
|
100
|
+
+ beginUserErasure: FunctionReference<
|
|
101
|
+
+ "mutation",
|
|
102
|
+
+ "internal",
|
|
103
|
+
+ { userId: string },
|
|
104
|
+
+ null,
|
|
105
|
+
+ Name
|
|
106
|
+
+ >;
|
|
107
|
+
+ purgeUserLinkedAuth: FunctionReference<
|
|
108
|
+
+ "mutation",
|
|
109
|
+
+ "internal",
|
|
110
|
+
+ { userId: string },
|
|
111
|
+
+ {
|
|
112
|
+
+ deletedAccounts: number;
|
|
113
|
+
+ deletedRefreshTokens: number;
|
|
114
|
+
+ deletedSessions: number;
|
|
115
|
+
+ legacyOrphansUnverified: true;
|
|
116
|
+
+ linkedRowsCleared: boolean;
|
|
117
|
+
+ },
|
|
118
|
+
+ Name
|
|
119
|
+
+ >;
|
|
120
|
+
+ };
|
|
121
|
+
+ migration: {
|
|
122
|
+
+ _internal_dangerous_advance: FunctionReference<
|
|
123
|
+
+ "mutation",
|
|
124
|
+
+ "internal",
|
|
125
|
+
+ {},
|
|
126
|
+
+ {
|
|
127
|
+
+ phase: "cutoffs" | "users" | "accounts" | "sessions" | "complete";
|
|
128
|
+
+ rows: Array<
|
|
129
|
+
+ | { cutoff: number; digest: string }
|
|
130
|
+
+ | { requestedAt: number; userId: string }
|
|
131
|
+
+ | { provider: string; providerAccountId: string; userId: string }
|
|
132
|
+
+ >;
|
|
133
|
+
+ },
|
|
134
|
+
+ Name
|
|
135
|
+
+ >;
|
|
136
|
+
+ erasedUsers: FunctionReference<
|
|
137
|
+
+ "query",
|
|
138
|
+
+ "internal",
|
|
139
|
+
+ {
|
|
140
|
+
+ paginationOpts: {
|
|
141
|
+
+ cursor: string | null;
|
|
142
|
+
+ endCursor?: string | null;
|
|
143
|
+
+ id?: number;
|
|
144
|
+
+ maximumBytesRead?: number;
|
|
145
|
+
+ maximumRowsRead?: number;
|
|
146
|
+
+ numItems: number;
|
|
147
|
+
+ };
|
|
148
|
+
+ },
|
|
149
|
+
+ any,
|
|
150
|
+
+ Name
|
|
151
|
+
+ >;
|
|
152
|
+
+ googleAccounts: FunctionReference<
|
|
153
|
+
+ "query",
|
|
154
|
+
+ "internal",
|
|
155
|
+
+ {
|
|
156
|
+
+ paginationOpts: {
|
|
157
|
+
+ cursor: string | null;
|
|
158
|
+
+ endCursor?: string | null;
|
|
159
|
+
+ id?: number;
|
|
160
|
+
+ maximumBytesRead?: number;
|
|
161
|
+
+ maximumRowsRead?: number;
|
|
162
|
+
+ numItems: number;
|
|
163
|
+
+ };
|
|
164
|
+
+ },
|
|
165
|
+
+ any,
|
|
166
|
+
+ Name
|
|
167
|
+
+ >;
|
|
168
|
+
+ identityCutoffs: FunctionReference<
|
|
169
|
+
+ "query",
|
|
170
|
+
+ "internal",
|
|
171
|
+
+ {
|
|
172
|
+
+ paginationOpts: {
|
|
173
|
+
+ cursor: string | null;
|
|
174
|
+
+ endCursor?: string | null;
|
|
175
|
+
+ id?: number;
|
|
176
|
+
+ maximumBytesRead?: number;
|
|
177
|
+
+ maximumRowsRead?: number;
|
|
178
|
+
+ numItems: number;
|
|
179
|
+
+ };
|
|
180
|
+
+ },
|
|
181
|
+
+ any,
|
|
182
|
+
+ Name
|
|
183
|
+
+ >;
|
|
184
|
+
+ retireLegacySession: FunctionReference<
|
|
185
|
+
+ "mutation",
|
|
186
|
+
+ "internal",
|
|
187
|
+
+ {},
|
|
188
|
+
+ { deletedSession: boolean; deletedTokens: number; done: boolean },
|
|
189
|
+
+ Name
|
|
190
|
+
+ >;
|
|
191
|
+
+ };
|
|
192
|
+
public: {
|
|
193
|
+
_internal_dangerous_signIn: FunctionReference<
|
|
194
|
+
"mutation",
|
|
195
|
+
@@ -69,6 +162,31 @@
|
|
196
|
+
"internal",
|
|
197
|
+
{ claims: { method: string; profile: any }; createUserHandle: string },
|
|
198
|
+
{ userId: string },
|
|
199
|
+
+ Name
|
|
200
|
+
+ >;
|
|
201
|
+
+ beginUserErasure: FunctionReference<
|
|
202
|
+
+ "mutation",
|
|
203
|
+
+ "internal",
|
|
204
|
+
+ { userId: string },
|
|
205
|
+
+ null,
|
|
206
|
+
+ Name
|
|
207
|
+
+ >;
|
|
208
|
+
+ exchangeSession: FunctionReference<
|
|
209
|
+
+ "mutation",
|
|
210
|
+
+ "internal",
|
|
211
|
+
+ {
|
|
212
|
+
+ accessTokenTtlSeconds: number;
|
|
213
|
+
+ refreshInactivityTimeoutSeconds: number;
|
|
214
|
+
+ sessionId: string;
|
|
215
|
+
+ sessionMaxLifetimeSeconds: number;
|
|
216
|
+
+ userId: string;
|
|
217
|
+
+ },
|
|
218
|
+
+ {
|
|
219
|
+
+ accessToken: string;
|
|
220
|
+
+ refreshToken: string;
|
|
221
|
+
+ refreshTokenExpiresAt: number;
|
|
222
|
+
+ userId: string;
|
|
223
|
+
+ },
|
|
224
|
+
Name
|
|
225
|
+
>;
|
|
226
|
+
getSession: FunctionReference<
|
|
227
|
+
@@ -94,6 +212,19 @@
|
|
228
|
+
"internal",
|
|
229
|
+
{ userId: string },
|
|
230
|
+
null,
|
|
231
|
+
+ Name
|
|
232
|
+
+ >;
|
|
233
|
+
+ purgeUserLinkedAuth: FunctionReference<
|
|
234
|
+
+ "mutation",
|
|
235
|
+
+ "internal",
|
|
236
|
+
+ { userId: string },
|
|
237
|
+
+ {
|
|
238
|
+
+ deletedAccounts: number;
|
|
239
|
+
+ deletedRefreshTokens: number;
|
|
240
|
+
+ deletedSessions: number;
|
|
241
|
+
+ legacyOrphansUnverified: true;
|
|
242
|
+
+ linkedRowsCleared: boolean;
|
|
243
|
+
+ },
|
|
244
|
+
Name
|
|
245
|
+
>;
|
|
246
|
+
refresh: FunctionReference<
|
|
247
|
+
--- a/src/component/core.test.ts
|
|
248
|
+
+++ b/src/component/core.test.ts
|
|
249
|
+
@@ -1591,3 +1591,130 @@
|
|
250
|
+
).toBeNull();
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
+
|
|
254
|
+
+describe("local erasure and session exchange", () => {
|
|
255
|
+
+ test("fencing blocks refresh, session lookup, exchange, and later sign-in while another user remains active", async () => {
|
|
256
|
+
+ const t = setup();
|
|
257
|
+
+ const alice = await signUp(t, claims());
|
|
258
|
+
+ const bob = await signUp(t, claims());
|
|
259
|
+
+ const sessionId = decodeJwt(alice.accessToken).sub!;
|
|
260
|
+
+ const exchange = await t.mutation(api.public.exchangeSession, {
|
|
261
|
+
+ sessionId,
|
|
262
|
+
+ userId: alice.userId,
|
|
263
|
+
+ ...DEFAULT_TTL,
|
|
264
|
+
+ });
|
|
265
|
+
+ expect(exchange.userId).toBe(alice.userId);
|
|
266
|
+
+ await expect(
|
|
267
|
+
+ t.mutation(api.public.exchangeSession, {
|
|
268
|
+
+ sessionId,
|
|
269
|
+
+ userId: bob.userId,
|
|
270
|
+
+ ...DEFAULT_TTL,
|
|
271
|
+
+ }),
|
|
272
|
+
+ ).rejects.toThrow();
|
|
273
|
+
+ await t.mutation(api.public.beginUserErasure, { userId: alice.userId });
|
|
274
|
+
+ expect(await t.query(api.public.getSession, { sessionId })).toBeNull();
|
|
275
|
+
+ expect((await refresh(t, alice.refreshToken)).kind).toBe("noSession");
|
|
276
|
+
+ await expect(
|
|
277
|
+
+ t.mutation(api.public.exchangeSession, {
|
|
278
|
+
+ sessionId,
|
|
279
|
+
+ userId: alice.userId,
|
|
280
|
+
+ ...DEFAULT_TTL,
|
|
281
|
+
+ }),
|
|
282
|
+
+ ).rejects.toThrow();
|
|
283
|
+
+ await expect(signIn(t, claims(), alice.userId)).rejects.toThrow();
|
|
284
|
+
+ expect((await refresh(t, bob.refreshToken)).kind).toBe("rotated");
|
|
285
|
+
+ let done = false;
|
|
286
|
+
+ for (let i = 0; i < 10 && !done; i++)
|
|
287
|
+
+ done = (
|
|
288
|
+
+ await t.mutation(api.public.purgeUserLinkedAuth, {
|
|
289
|
+
+ userId: alice.userId,
|
|
290
|
+
+ })
|
|
291
|
+
+ ).linkedRowsCleared;
|
|
292
|
+
+ expect(done).toBe(true);
|
|
293
|
+
+ expect(
|
|
294
|
+
+ await t.run(async (ctx) =>
|
|
295
|
+
+ (await ctx.db.query("sessions").collect()).some(
|
|
296
|
+
+ (row) => row.userId === alice.userId,
|
|
297
|
+
+ ),
|
|
298
|
+
+ ),
|
|
299
|
+
+ ).toBe(false);
|
|
300
|
+
+ await expect(signIn(t, claims(), alice.userId)).rejects.toThrow();
|
|
301
|
+
+ });
|
|
302
|
+
+});
|
|
303
|
+
+
|
|
304
|
+
+test("a signed-out session remains attributable to erasure until tokens are purged", async () => {
|
|
305
|
+
+ const t = setup();
|
|
306
|
+
+ const user = await signUp(t, claims());
|
|
307
|
+
+ await t.mutation(api.public.signOut, { refreshToken: user.refreshToken });
|
|
308
|
+
+ expect(
|
|
309
|
+
+ await t.run(
|
|
310
|
+
+ async (ctx) =>
|
|
311
|
+
+ (await ctx.db.query("sessionCleanupReceipts").collect()).length,
|
|
312
|
+
+ ),
|
|
313
|
+
+ ).toBe(1);
|
|
314
|
+
+ await t.mutation(api.public.beginUserErasure, { userId: user.userId });
|
|
315
|
+
+ const first = await t.mutation(api.public.purgeUserLinkedAuth, {
|
|
316
|
+
+ userId: user.userId,
|
|
317
|
+
+ });
|
|
318
|
+
+ expect(first.deletedRefreshTokens).toBeGreaterThan(0);
|
|
319
|
+
+ expect(
|
|
320
|
+
+ await t.run(
|
|
321
|
+
+ async (ctx) =>
|
|
322
|
+
+ (await ctx.db.query("sessionCleanupReceipts").collect()).length,
|
|
323
|
+
+ ),
|
|
324
|
+
+ ).toBe(0);
|
|
325
|
+
+ expect(
|
|
326
|
+
+ (await t.mutation(api.public.purgeUserLinkedAuth, { userId: user.userId }))
|
|
327
|
+
+ .linkedRowsCleared,
|
|
328
|
+
+ ).toBe(true);
|
|
329
|
+
+});
|
|
330
|
+
+
|
|
331
|
+
+test("legacy rows are accepted but old sessions and new sign-ins stay closed", async () => {
|
|
332
|
+
+ const t = setup();
|
|
333
|
+
+ const data = await t.run(async (ctx) => {
|
|
334
|
+
+ const accountId = await ctx.db.insert("accounts", {
|
|
335
|
+
+ provider: "google",
|
|
336
|
+
+ providerAccountId: "legacy-google",
|
|
337
|
+
+ userId: "legacy-user",
|
|
338
|
+
+ });
|
|
339
|
+
+ const sessionId = await ctx.db.insert("sessions", {
|
|
340
|
+
+ userId: "legacy-user",
|
|
341
|
+
+ accountId,
|
|
342
|
+
+ });
|
|
343
|
+
+ await ctx.db.insert("refreshTokens", {
|
|
344
|
+
+ hash: await sha256Hex("legacy-token"),
|
|
345
|
+
+ sessionId,
|
|
346
|
+
+ state: "issued",
|
|
347
|
+
+ });
|
|
348
|
+
+ await ctx.db.insert("identityErasure", {
|
|
349
|
+
+ digest: "a".repeat(64),
|
|
350
|
+
+ cutoff: 1,
|
|
351
|
+
+ });
|
|
352
|
+
+ return { sessionId };
|
|
353
|
+
+ });
|
|
354
|
+
+ expect(
|
|
355
|
+
+ await t.query(api.public.getSession, { sessionId: data.sessionId }),
|
|
356
|
+
+ ).toBeNull();
|
|
357
|
+
+ expect((await refresh(t, "legacy-token")).kind).toBe("noSession");
|
|
358
|
+
+ await expect(signIn(t, claims(), "legacy-user")).rejects.toThrow(
|
|
359
|
+
+ "Legacy auth migration is not complete",
|
|
360
|
+
+ );
|
|
361
|
+
+ const oldRows = await t.query(api.migration.googleAccounts, {
|
|
362
|
+
+ paginationOpts: { cursor: null, numItems: 10 },
|
|
363
|
+
+ });
|
|
364
|
+
+ expect(oldRows.page.map((row) => row.userId)).toEqual(["legacy-user"]);
|
|
365
|
+
+ expect(await t.mutation(api.migration.retireLegacySession, {})).toMatchObject(
|
|
366
|
+
+ { done: false, deletedSession: true, deletedTokens: 1 },
|
|
367
|
+
+ );
|
|
368
|
+
+ expect(await t.mutation(api.migration.retireLegacySession, {})).toMatchObject(
|
|
369
|
+
+ { done: true },
|
|
370
|
+
+ );
|
|
371
|
+
+ expect(
|
|
372
|
+
+ await t.run(
|
|
373
|
+
+ async (ctx) => (await ctx.db.query("accounts").collect()).length,
|
|
374
|
+
+ ),
|
|
375
|
+
+ ).toBe(1);
|
|
376
|
+
+ await expect(signIn(t, claims(), "legacy-user")).rejects.toThrow(
|
|
377
|
+
+ "Legacy auth migration is not complete",
|
|
378
|
+
+ );
|
|
379
|
+
+});
|
|
380
|
+
--- /dev/null
|
|
381
|
+
+++ b/src/component/erasure.ts
|
|
382
|
+
@@ -0,0 +1,102 @@
|
|
383
|
+
+import { v } from "convex/values";
|
|
384
|
+
+import { mutation, type QueryCtx } from "./_generated/server.ts";
|
|
385
|
+
+
|
|
386
|
+
+export function erasedUser(ctx: QueryCtx, userId: string) {
|
|
387
|
+
+ return ctx.db
|
|
388
|
+
+ .query("erasedUsers")
|
|
389
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
390
|
+
+ .unique();
|
|
391
|
+
+}
|
|
392
|
+
+export async function requireMigrationComplete(ctx: QueryCtx) {
|
|
393
|
+
+ const control = await ctx.db
|
|
394
|
+
+ .query("migrationControl")
|
|
395
|
+
+ .withIndex("by_key", (q) => q.eq("key", "auth-v2"))
|
|
396
|
+
+ .unique();
|
|
397
|
+
+ if (control?.complete) return;
|
|
398
|
+
+ if (control) throw new Error("Legacy auth migration is not complete.");
|
|
399
|
+
+ if (
|
|
400
|
+
+ (await ctx.db.query("accounts").first()) ||
|
|
401
|
+
+ (await ctx.db.query("identityErasure").first()) ||
|
|
402
|
+
+ (await ctx.db
|
|
403
|
+
+ .query("sessions")
|
|
404
|
+
+ .withIndex("by_component", (q) => q.eq("component", undefined))
|
|
405
|
+
+ .first())
|
|
406
|
+
+ )
|
|
407
|
+
+ throw new Error("Legacy auth migration is not complete.");
|
|
408
|
+
+}
|
|
409
|
+
+export async function requireActiveUser(ctx: QueryCtx, userId: string) {
|
|
410
|
+
+ await requireMigrationComplete(ctx);
|
|
411
|
+
+ if (await erasedUser(ctx, userId))
|
|
412
|
+
+ throw new Error("Auth account is unavailable.");
|
|
413
|
+
+}
|
|
414
|
+
+
|
|
415
|
+
+/** App-server-only fence; establish provider fences in the same app mutation. */
|
|
416
|
+
+export const beginUserErasure = mutation({
|
|
417
|
+
+ args: { userId: v.string() },
|
|
418
|
+
+ returns: v.null(),
|
|
419
|
+
+ handler: async (ctx, { userId }) => {
|
|
420
|
+
+ await requireMigrationComplete(ctx);
|
|
421
|
+
+ if (!userId) throw new Error("Missing user ID.");
|
|
422
|
+
+ if (!(await erasedUser(ctx, userId)))
|
|
423
|
+
+ await ctx.db.insert("erasedUsers", { userId, requestedAt: Date.now() });
|
|
424
|
+
+ return null;
|
|
425
|
+
+ },
|
|
426
|
+
+});
|
|
427
|
+
+
|
|
428
|
+
+/** Only core-owned sessions and tokens. Stable v2 provider accounts are separate. */
|
|
429
|
+
+export const purgeUserLinkedAuth = mutation({
|
|
430
|
+
+ args: { userId: v.string() },
|
|
431
|
+
+ returns: v.object({
|
|
432
|
+
+ linkedRowsCleared: v.boolean(),
|
|
433
|
+
+ deletedAccounts: v.number(),
|
|
434
|
+
+ deletedSessions: v.number(),
|
|
435
|
+
+ deletedRefreshTokens: v.number(),
|
|
436
|
+
+ legacyOrphansUnverified: v.literal(true),
|
|
437
|
+
+ }),
|
|
438
|
+
+ handler: async (ctx, { userId }) => {
|
|
439
|
+
+ if (!(await erasedUser(ctx, userId)))
|
|
440
|
+
+ throw new Error("Begin auth erasure first.");
|
|
441
|
+
+ const result = {
|
|
442
|
+
+ linkedRowsCleared: false,
|
|
443
|
+
+ deletedAccounts: 0,
|
|
444
|
+
+ deletedSessions: 0,
|
|
445
|
+
+ deletedRefreshTokens: 0,
|
|
446
|
+
+ legacyOrphansUnverified: true as const,
|
|
447
|
+
+ };
|
|
448
|
+
+ const receipt = await ctx.db
|
|
449
|
+
+ .query("sessionCleanupReceipts")
|
|
450
|
+
+ .withIndex("by_user", (q) => q.eq("userId", userId))
|
|
451
|
+
+ .first();
|
|
452
|
+
+ const session = receipt
|
|
453
|
+
+ ? null
|
|
454
|
+
+ : await ctx.db
|
|
455
|
+
+ .query("sessions")
|
|
456
|
+
+ .withIndex("by_user", (q) => q.eq("userId", userId))
|
|
457
|
+
+ .first();
|
|
458
|
+
+ const sessionId = receipt?.sessionId ?? session?._id;
|
|
459
|
+
+ if (sessionId) {
|
|
460
|
+
+ const tokens = await ctx.db
|
|
461
|
+
+ .query("refreshTokens")
|
|
462
|
+
+ .withIndex("by_session_state", (q) => q.eq("sessionId", sessionId))
|
|
463
|
+
+ .take(101);
|
|
464
|
+
+ for (const token of tokens.slice(0, 100))
|
|
465
|
+
+ await ctx.db.delete("refreshTokens", token._id);
|
|
466
|
+
+ result.deletedRefreshTokens = Math.min(tokens.length, 100);
|
|
467
|
+
+ if (tokens.length <= 100) {
|
|
468
|
+
+ if (receipt) await ctx.db.delete("sessionCleanupReceipts", receipt._id);
|
|
469
|
+
+ else if (session) {
|
|
470
|
+
+ await ctx.db.delete("sessions", session._id);
|
|
471
|
+
+ result.deletedSessions = 1;
|
|
472
|
+
+ }
|
|
473
|
+
+ }
|
|
474
|
+
+ return result;
|
|
475
|
+
+ }
|
|
476
|
+
+ const created = await ctx.db
|
|
477
|
+
+ .query("createdUserIds")
|
|
478
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
479
|
+
+ .take(101);
|
|
480
|
+
+ for (const row of created.slice(0, 100))
|
|
481
|
+
+ await ctx.db.delete("createdUserIds", row._id);
|
|
482
|
+
+ return { ...result, linkedRowsCleared: created.length <= 100 };
|
|
483
|
+
+ },
|
|
484
|
+
+});
|
|
485
|
+
--- /dev/null
|
|
486
|
+
+++ b/src/component/migration.ts
|
|
487
|
+
@@ -0,0 +1,164 @@
|
|
488
|
+
+/** Read-only legacy component exports. App-internal orchestration must copy each
|
|
489
|
+
+ * page atomically with progress and keep auth gated until verification. */
|
|
490
|
+
+import { paginationOptsValidator } from "convex/server";
|
|
491
|
+
+import { query, mutation } from "./_generated/server.ts";
|
|
492
|
+
+import { v } from "convex/values";
|
|
493
|
+
+
|
|
494
|
+
+export const googleAccounts = query({
|
|
495
|
+
+ args: { paginationOpts: paginationOptsValidator },
|
|
496
|
+
+ handler: async (ctx, { paginationOpts }) => {
|
|
497
|
+
+ if (paginationOpts.numItems < 1 || paginationOpts.numItems > 100)
|
|
498
|
+
+ throw new Error("Invalid batch size");
|
|
499
|
+
+ return await ctx.db
|
|
500
|
+
+ .query("accounts")
|
|
501
|
+
+ .withIndex("by_provider_account", (q) => q.eq("provider", "google"))
|
|
502
|
+
+ .paginate(paginationOpts);
|
|
503
|
+
+ },
|
|
504
|
+
+});
|
|
505
|
+
+export const identityCutoffs = query({
|
|
506
|
+
+ args: { paginationOpts: paginationOptsValidator },
|
|
507
|
+
+ handler: async (ctx, { paginationOpts }) => {
|
|
508
|
+
+ if (paginationOpts.numItems < 1 || paginationOpts.numItems > 100)
|
|
509
|
+
+ throw new Error("Invalid batch size");
|
|
510
|
+
+ return await ctx.db.query("identityErasure").paginate(paginationOpts);
|
|
511
|
+
+ },
|
|
512
|
+
+});
|
|
513
|
+
+export const erasedUsers = query({
|
|
514
|
+
+ args: { paginationOpts: paginationOptsValidator },
|
|
515
|
+
+ handler: async (ctx, { paginationOpts }) => {
|
|
516
|
+
+ if (paginationOpts.numItems < 1 || paginationOpts.numItems > 100)
|
|
517
|
+
+ throw new Error("Invalid batch size");
|
|
518
|
+
+ return await ctx.db.query("erasedUsers").paginate(paginationOpts);
|
|
519
|
+
+ },
|
|
520
|
+
+});
|
|
521
|
+
+/** Delete one old session's tokens in bounded batches, then the session.
|
|
522
|
+
+ * Stable sessions remain untouched; historical unattributed orphan tokens remain. */
|
|
523
|
+
+export const retireLegacySession = mutation({
|
|
524
|
+
+ args: {},
|
|
525
|
+
+ returns: v.object({
|
|
526
|
+
+ done: v.boolean(),
|
|
527
|
+
+ deletedTokens: v.number(),
|
|
528
|
+
+ deletedSession: v.boolean(),
|
|
529
|
+
+ }),
|
|
530
|
+
+ handler: async (ctx) => {
|
|
531
|
+
+ const session = await ctx.db
|
|
532
|
+
+ .query("sessions")
|
|
533
|
+
+ .withIndex("by_component", (q) => q.eq("component", undefined))
|
|
534
|
+
+ .first();
|
|
535
|
+
+ if (!session)
|
|
536
|
+
+ return { done: true, deletedTokens: 0, deletedSession: false };
|
|
537
|
+
+ const tokens = await ctx.db
|
|
538
|
+
+ .query("refreshTokens")
|
|
539
|
+
+ .withIndex("by_session_state", (q) => q.eq("sessionId", session._id))
|
|
540
|
+
+ .take(101);
|
|
541
|
+
+ for (const token of tokens.slice(0, 100))
|
|
542
|
+
+ await ctx.db.delete("refreshTokens", token._id);
|
|
543
|
+
+ if (tokens.length <= 100) await ctx.db.delete("sessions", session._id);
|
|
544
|
+
+ return {
|
|
545
|
+
+ done: false,
|
|
546
|
+
+ deletedTokens: Math.min(tokens.length, 100),
|
|
547
|
+
+ deletedSession: tokens.length <= 100,
|
|
548
|
+
+ };
|
|
549
|
+
+ },
|
|
550
|
+
+});
|
|
551
|
+
+
|
|
552
|
+
+/**
|
|
553
|
+
+ * DANGER: only invoke from an app-internal transaction which imports the
|
|
554
|
+
+ * returned rows into the Google component before returning. A failed import
|
|
555
|
+
+ * must roll back this progress. Never expose this component function publicly.
|
|
556
|
+
+ */
|
|
557
|
+
+export const _internal_dangerous_advance = mutation({
|
|
558
|
+
+ args: {},
|
|
559
|
+
+ returns: v.object({
|
|
560
|
+
+ phase: v.union(
|
|
561
|
+
+ v.literal("cutoffs"),
|
|
562
|
+
+ v.literal("users"),
|
|
563
|
+
+ v.literal("accounts"),
|
|
564
|
+
+ v.literal("sessions"),
|
|
565
|
+
+ v.literal("complete"),
|
|
566
|
+
+ ),
|
|
567
|
+
+ rows: v.array(
|
|
568
|
+
+ v.union(
|
|
569
|
+
+ v.object({ digest: v.string(), cutoff: v.number() }),
|
|
570
|
+
+ v.object({ userId: v.string(), requestedAt: v.number() }),
|
|
571
|
+
+ v.object({
|
|
572
|
+
+ provider: v.string(),
|
|
573
|
+
+ providerAccountId: v.string(),
|
|
574
|
+
+ userId: v.string(),
|
|
575
|
+
+ }),
|
|
576
|
+
+ ),
|
|
577
|
+
+ ),
|
|
578
|
+
+ }),
|
|
579
|
+
+ handler: async (ctx) => {
|
|
580
|
+
+ let state = await ctx.db
|
|
581
|
+
+ .query("migrationControl")
|
|
582
|
+
+ .withIndex("by_key", (q) => q.eq("key", "auth-v2"))
|
|
583
|
+
+ .unique();
|
|
584
|
+
+ if (!state) {
|
|
585
|
+
+ const id = await ctx.db.insert("migrationControl", {
|
|
586
|
+
+ key: "auth-v2",
|
|
587
|
+
+ complete: false,
|
|
588
|
+
+ phase: "cutoffs",
|
|
589
|
+
+ });
|
|
590
|
+
+ state = await ctx.db.get("migrationControl", id);
|
|
591
|
+
+ }
|
|
592
|
+
+ if (!state) throw new Error("Migration state missing");
|
|
593
|
+
+ if (state.complete) return { phase: "complete" as const, rows: [] };
|
|
594
|
+
+ const phase = state.phase;
|
|
595
|
+
+ if (!phase) throw new Error("Invalid migration phase");
|
|
596
|
+
+ const paginationOpts = { cursor: state.cursor ?? null, numItems: 100 };
|
|
597
|
+
+ if (phase === "sessions") {
|
|
598
|
+
+ const session = await ctx.db
|
|
599
|
+
+ .query("sessions")
|
|
600
|
+
+ .withIndex("by_component", (q) => q.eq("component", undefined))
|
|
601
|
+
+ .first();
|
|
602
|
+
+ if (session) {
|
|
603
|
+
+ const tokens = await ctx.db
|
|
604
|
+
+ .query("refreshTokens")
|
|
605
|
+
+ .withIndex("by_session_state", (q) => q.eq("sessionId", session._id))
|
|
606
|
+
+ .take(101);
|
|
607
|
+
+ for (const token of tokens.slice(0, 100))
|
|
608
|
+
+ await ctx.db.delete("refreshTokens", token._id);
|
|
609
|
+
+ if (tokens.length <= 100) await ctx.db.delete("sessions", session._id);
|
|
610
|
+
+ return { phase, rows: [] };
|
|
611
|
+
+ }
|
|
612
|
+
+ await ctx.db.patch("migrationControl", state._id, {
|
|
613
|
+
+ complete: true,
|
|
614
|
+
+ phase: undefined,
|
|
615
|
+
+ cursor: undefined,
|
|
616
|
+
+ });
|
|
617
|
+
+ return { phase: "complete" as const, rows: [] };
|
|
618
|
+
+ }
|
|
619
|
+
+ const result =
|
|
620
|
+
+ phase === "cutoffs"
|
|
621
|
+
+ ? await ctx.db.query("identityErasure").paginate(paginationOpts)
|
|
622
|
+
+ : phase === "users"
|
|
623
|
+
+ ? await ctx.db.query("erasedUsers").paginate(paginationOpts)
|
|
624
|
+
+ : phase === "accounts"
|
|
625
|
+
+ ? await ctx.db
|
|
626
|
+
+ .query("accounts")
|
|
627
|
+
+ .withIndex("by_provider_account", (q) =>
|
|
628
|
+
+ q.eq("provider", "google"),
|
|
629
|
+
+ )
|
|
630
|
+
+ .paginate(paginationOpts)
|
|
631
|
+
+ : null;
|
|
632
|
+
+ if (!result) throw new Error("Invalid migration phase");
|
|
633
|
+
+ const next =
|
|
634
|
+
+ phase === "cutoffs"
|
|
635
|
+
+ ? "users"
|
|
636
|
+
+ : phase === "users"
|
|
637
|
+
+ ? "accounts"
|
|
638
|
+
+ : "sessions";
|
|
639
|
+
+ await ctx.db.patch(
|
|
640
|
+
+ "migrationControl",
|
|
641
|
+
+ state._id,
|
|
642
|
+
+ result.isDone
|
|
643
|
+
+ ? { phase: next, cursor: undefined }
|
|
644
|
+
+ : { cursor: result.continueCursor },
|
|
645
|
+
+ );
|
|
646
|
+
+ return {
|
|
647
|
+
+ phase,
|
|
648
|
+
+ rows: result.page.map(({ _id, _creationTime, ...row }) => row),
|
|
649
|
+
+ };
|
|
650
|
+
+ },
|
|
651
|
+
+});
|
|
652
|
+
--- a/src/component/public.ts
|
|
653
|
+
+++ b/src/component/public.ts
|
|
654
|
+
@@ -17,6 +17,8 @@
|
|
655
|
+
type OnSignInFn,
|
|
656
|
+
} from "../lib/types.ts";
|
|
657
|
+
import { sha256Hex } from "../lib/crypto.ts";
|
|
658
|
+
+import { erasedUser, requireActiveUser } from "./erasure.ts";
|
|
659
|
+
+export { beginUserErasure, purgeUserLinkedAuth } from "./erasure.ts";
|
|
660
|
+
import { assertMountedAsCore } from "../lib/coreComponent.ts";
|
|
661
|
+
import {
|
|
662
|
+
refreshTokenInactivityExpiresAt,
|
|
663
|
+
@@ -78,6 +80,7 @@
|
|
664
|
+
component: string,
|
|
665
|
+
ttl: TtlConfig,
|
|
666
|
+
): Promise<TokenBundle> {
|
|
667
|
+
+ await requireActiveUser(ctx, userId);
|
|
668
|
+
const now = Date.now();
|
|
669
|
+
await evictLeastRecentlyRefreshedSessions(ctx, userId);
|
|
670
|
+
const sessionId = await ctx.db.insert("sessions", {
|
|
671
|
+
@@ -156,6 +159,7 @@
|
|
672
|
+
ctx: MutationCtx,
|
|
673
|
+
userId: string,
|
|
674
|
+
): Promise<void> {
|
|
675
|
+
+ await requireActiveUser(ctx, userId);
|
|
676
|
+
const existing = await ctx.db
|
|
677
|
+
.query("createdUserIds")
|
|
678
|
+
.withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
679
|
+
@@ -360,7 +364,11 @@
|
|
680
|
+
const id = ctx.db.normalizeId("sessions", sessionId);
|
|
681
|
+
if (id === null) return null;
|
|
682
|
+
const session = await ctx.db.get("sessions", id);
|
|
683
|
+
- return session === null ? null : { userId: session.userId };
|
|
684
|
+
+ return session === null ||
|
|
685
|
+
+ !session.component ||
|
|
686
|
+
+ (await erasedUser(ctx, session.userId))
|
|
687
|
+
+ ? null
|
|
688
|
+
+ : { userId: session.userId };
|
|
689
|
+
},
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
@@ -418,7 +426,12 @@
|
|
693
|
+
// `deleteSession`), so a token can outlive its session for a moment. The
|
|
694
|
+
// session ended already, thus there is nothing to refresh or revoke.
|
|
695
|
+
const session = await ctx.db.get("sessions", token.sessionId);
|
|
696
|
+
- if (session === null) return { kind: "noSession" };
|
|
697
|
+
+ if (
|
|
698
|
+
+ session === null ||
|
|
699
|
+
+ !session.component ||
|
|
700
|
+
+ (await erasedUser(ctx, session.userId))
|
|
701
|
+
+ )
|
|
702
|
+
+ return { kind: "noSession" };
|
|
703
|
+
|
|
704
|
+
switch (token.state) {
|
|
705
|
+
case "spent":
|
|
706
|
+
@@ -616,3 +629,29 @@
|
|
707
|
+
return revoked;
|
|
708
|
+
},
|
|
709
|
+
});
|
|
710
|
+
+
|
|
711
|
+
+/** App-server only: caller authenticates the source or consumes a one-use handoff. */
|
|
712
|
+
+export const exchangeSession = mutation({
|
|
713
|
+
+ args: { sessionId: v.string(), userId: v.string(), ...vTtlConfigFields },
|
|
714
|
+
+ returns: vTokenBundle,
|
|
715
|
+
+ handler: async (ctx, args): Promise<TokenBundle> => {
|
|
716
|
+
+ const ttl = validateTtlConfig(args);
|
|
717
|
+
+ await requireActiveUser(ctx, args.userId);
|
|
718
|
+
+ const id = ctx.db.normalizeId("sessions", args.sessionId);
|
|
719
|
+
+ const session = id ? await ctx.db.get("sessions", id) : null;
|
|
720
|
+
+ if (!session || !session.component || session.userId !== args.userId)
|
|
721
|
+
+ throw new Error("Source session is no longer active.");
|
|
722
|
+
+ const latest = await newestIssuedToken(ctx, session._id);
|
|
723
|
+
+ const now = Date.now();
|
|
724
|
+
+ if (
|
|
725
|
+
+ !latest ||
|
|
726
|
+
+ refreshTokenInactivityExpiresAt(
|
|
727
|
+
+ latest,
|
|
728
|
+
+ ttl.refreshInactivityTimeoutSeconds,
|
|
729
|
+
+ ) <= now ||
|
|
730
|
+
+ sessionMaxLifetimeExpiresAt(session, ttl.sessionMaxLifetimeSeconds) <= now
|
|
731
|
+
+ )
|
|
732
|
+
+ throw new Error("Source session has expired.");
|
|
733
|
+
+ return issueSession(ctx, session.userId, session.component, ttl);
|
|
734
|
+
+ },
|
|
735
|
+
+});
|
|
736
|
+
--- a/src/component/schema.ts
|
|
737
|
+
+++ b/src/component/schema.ts
|
|
738
|
+
@@ -2,6 +2,41 @@
|
|
739
|
+
import { v } from "convex/values";
|
|
740
|
+
|
|
741
|
+
export default defineSchema({
|
|
742
|
+
+ migrationControl: defineTable({
|
|
743
|
+
+ key: v.literal("auth-v2"),
|
|
744
|
+
+ complete: v.boolean(),
|
|
745
|
+
+ phase: v.optional(
|
|
746
|
+
+ v.union(
|
|
747
|
+
+ v.literal("cutoffs"),
|
|
748
|
+
+ v.literal("users"),
|
|
749
|
+
+ v.literal("accounts"),
|
|
750
|
+
+ v.literal("sessions"),
|
|
751
|
+
+ ),
|
|
752
|
+
+ ),
|
|
753
|
+
+ cursor: v.optional(v.string()),
|
|
754
|
+
+ }).index("by_key", ["key"]),
|
|
755
|
+
+ // Retain all legacy mappings and fences until the migration is verified.
|
|
756
|
+
+ accounts: defineTable({
|
|
757
|
+
+ provider: v.string(),
|
|
758
|
+
+ providerAccountId: v.string(),
|
|
759
|
+
+ userId: v.string(),
|
|
760
|
+
+ })
|
|
761
|
+
+ .index("by_provider_account", ["provider", "providerAccountId"])
|
|
762
|
+
+ .index("by_user", ["userId"]),
|
|
763
|
+
+ identityErasure: defineTable({
|
|
764
|
+
+ digest: v.string(),
|
|
765
|
+
+ cutoff: v.number(),
|
|
766
|
+
+ }).index("by_digest", ["digest"]),
|
|
767
|
+
+ erasedUsers: defineTable({
|
|
768
|
+
+ userId: v.string(),
|
|
769
|
+
+ requestedAt: v.number(),
|
|
770
|
+
+ }).index("by_userId", ["userId"]),
|
|
771
|
+
+ sessionCleanupReceipts: defineTable({
|
|
772
|
+
+ userId: v.string(),
|
|
773
|
+
+ sessionId: v.id("sessions"),
|
|
774
|
+
+ })
|
|
775
|
+
+ .index("by_user", ["userId"])
|
|
776
|
+
+ .index("by_session", ["sessionId"]),
|
|
777
|
+
// The IDs of the app users that the core created or signed in, or that the
|
|
778
|
+
// app marked as created (`markUserIdCreated`).
|
|
779
|
+
createdUserIds: defineTable({
|
|
780
|
+
@@ -19,8 +54,11 @@
|
|
781
|
+
userId: v.string(),
|
|
782
|
+
// The path of the component that authenticated the user when the session
|
|
783
|
+
// was created, for example `"authPassword"`.
|
|
784
|
+
- component: v.string(),
|
|
785
|
+
- }).index("by_user", ["userId"]),
|
|
786
|
+
+ component: v.optional(v.string()),
|
|
787
|
+
+ accountId: v.optional(v.id("accounts")),
|
|
788
|
+
+ })
|
|
789
|
+
+ .index("by_user", ["userId"])
|
|
790
|
+
+ .index("by_component", ["component"]),
|
|
791
|
+
|
|
792
|
+
// Every refresh token a session has handed out and still remembers, by its
|
|
793
|
+
// SHA-256 hash. The raw refresh token is never stored.
|
|
794
|
+
--- a/src/component/sessions.ts
|
|
795
|
+
+++ b/src/component/sessions.ts
|
|
796
|
+
@@ -146,9 +146,17 @@
|
|
797
|
+
): Promise<void> {
|
|
798
|
+
// `delete` throws on an id that is already gone, and the session may have
|
|
799
|
+
// been deleted by whoever we raced, which also scheduled its tokens.
|
|
800
|
+
- if ((await ctx.db.get("sessions", sessionId)) === null) {
|
|
801
|
+
- return;
|
|
802
|
+
- }
|
|
803
|
+
+ const session = await ctx.db.get("sessions", sessionId);
|
|
804
|
+
+ if (session === null) return;
|
|
805
|
+
+ const receipt = await ctx.db
|
|
806
|
+
+ .query("sessionCleanupReceipts")
|
|
807
|
+
+ .withIndex("by_session", (q) => q.eq("sessionId", sessionId))
|
|
808
|
+
+ .unique();
|
|
809
|
+
+ if (!receipt)
|
|
810
|
+
+ await ctx.db.insert("sessionCleanupReceipts", {
|
|
811
|
+
+ userId: session.userId,
|
|
812
|
+
+ sessionId,
|
|
813
|
+
+ });
|
|
814
|
+
await ctx.db.delete("sessions", sessionId);
|
|
815
|
+
await ctx.scheduler.runAfter(0, internal.sessions.deleteSessionTokens, {
|
|
816
|
+
sessionId,
|
|
817
|
+
@@ -175,6 +183,13 @@
|
|
818
|
+
.take(TOKEN_DELETION_BATCH_SIZE);
|
|
819
|
+
for (const row of tokens) {
|
|
820
|
+
await ctx.db.delete("refreshTokens", row._id);
|
|
821
|
+
+ }
|
|
822
|
+
+ if (tokens.length < TOKEN_DELETION_BATCH_SIZE) {
|
|
823
|
+
+ const receipt = await ctx.db
|
|
824
|
+
+ .query("sessionCleanupReceipts")
|
|
825
|
+
+ .withIndex("by_session", (q) => q.eq("sessionId", sessionId))
|
|
826
|
+
+ .unique();
|
|
827
|
+
+ if (receipt) await ctx.db.delete("sessionCleanupReceipts", receipt._id);
|
|
828
|
+
}
|
|
829
|
+
if (tokens.length === TOKEN_DELETION_BATCH_SIZE) {
|
|
830
|
+
await ctx.scheduler.runAfter(0, internal.sessions.deleteSessionTokens, {
|
|
831
|
+
--- a/src/components/email/_generated/component.ts
|
|
832
|
+
+++ b/src/components/email/_generated/component.ts
|
|
833
|
+
@@ -274,6 +274,13 @@
|
|
834
|
+
null,
|
|
835
|
+
Name
|
|
836
|
+
>;
|
|
837
|
+
+ eraseUserBatch: FunctionReference<
|
|
838
|
+
+ "mutation",
|
|
839
|
+
+ "internal",
|
|
840
|
+
+ { userId: string },
|
|
841
|
+
+ { challengesDeleted: number; complete: boolean; emailsDeleted: number },
|
|
842
|
+
+ Name
|
|
843
|
+
+ >;
|
|
844
|
+
getEmails: FunctionReference<
|
|
845
|
+
"query",
|
|
846
|
+
"internal",
|
|
847
|
+
--- a/src/components/email/challenge/common.ts
|
|
848
|
+
+++ b/src/components/email/challenge/common.ts
|
|
849
|
+
@@ -392,6 +392,15 @@
|
|
850
|
+
copy: ChallengeEmailCopy;
|
|
851
|
+
},
|
|
852
|
+
): Promise<{ browserSecret: string; challengeId: Id<"challenges"> }> {
|
|
853
|
+
+ const challengeUserId = args.purpose.userId;
|
|
854
|
+
+ if (
|
|
855
|
+
+ challengeUserId !== undefined &&
|
|
856
|
+
+ (await ctx.db
|
|
857
|
+
+ .query("erasedUsers")
|
|
858
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", challengeUserId))
|
|
859
|
+
+ .unique())
|
|
860
|
+
+ )
|
|
861
|
+
+ throw new Error("User identity has been erased");
|
|
862
|
+
const emailCode = generateRandomToken();
|
|
863
|
+
const browserSecret = generateRandomToken();
|
|
864
|
+
const challengeId = await ctx.db.insert("challenges", {
|
|
865
|
+
@@ -496,6 +505,15 @@
|
|
866
|
+
);
|
|
867
|
+
return claimFailure("INVALID_CHALLENGE");
|
|
868
|
+
}
|
|
869
|
+
+ const challengeUserId = row.purpose.userId;
|
|
870
|
+
+ if (
|
|
871
|
+
+ challengeUserId !== undefined &&
|
|
872
|
+
+ (await ctx.db
|
|
873
|
+
+ .query("erasedUsers")
|
|
874
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", challengeUserId))
|
|
875
|
+
+ .unique())
|
|
876
|
+
+ )
|
|
877
|
+
+ return claimFailure("INVALID_CHALLENGE");
|
|
878
|
+
// At exactly `expiresAt` the link is expired, like in the cleanup loop.
|
|
879
|
+
if (row.expiresAt <= Date.now()) {
|
|
880
|
+
console.warn(
|
|
881
|
+
--- /dev/null
|
|
882
|
+
+++ b/src/components/email/erasure.test.ts
|
|
883
|
+
@@ -0,0 +1,42 @@
|
|
884
|
+
+import { convexTest } from "convex-test";
|
|
885
|
+
+import { expect, test } from "vitest";
|
|
886
|
+
+import { api } from "./_generated/api.ts";
|
|
887
|
+
+import schema from "./schema.ts";
|
|
888
|
+
+const modules = import.meta.glob("./**/*.ts");
|
|
889
|
+
+test("bounded email erasure removes attributed rows and preserves another user", async () => {
|
|
890
|
+
+ const t = convexTest({ schema, modules });
|
|
891
|
+
+ await t.run(async (ctx) => {
|
|
892
|
+
+ for (let i = 0; i < 101; i++)
|
|
893
|
+
+ await ctx.db.insert("verifiedEmails", {
|
|
894
|
+
+ email: `${i}@example.com`,
|
|
895
|
+
+ normalizedEmail: `${i}@example.com`,
|
|
896
|
+
+ userId: "old",
|
|
897
|
+
+ isPrimary: i === 0,
|
|
898
|
+
+ });
|
|
899
|
+
+ await ctx.db.insert("verifiedEmails", {
|
|
900
|
+
+ email: "other@example.com",
|
|
901
|
+
+ normalizedEmail: "other@example.com",
|
|
902
|
+
+ userId: "other",
|
|
903
|
+
+ isPrimary: true,
|
|
904
|
+
+ });
|
|
905
|
+
+ await ctx.db.insert("challenges", {
|
|
906
|
+
+ email: "a@example.com",
|
|
907
|
+
+ purpose: { kind: "changeEmail", userId: "old" },
|
|
908
|
+
+ emailCodeHash: "a",
|
|
909
|
+
+ browserSecretHash: "b",
|
|
910
|
+
+ expiresAt: Date.now() + 10000,
|
|
911
|
+
+ });
|
|
912
|
+
+ });
|
|
913
|
+
+ expect(
|
|
914
|
+
+ await t.mutation(api.verifiedEmails.eraseUserBatch, { userId: "old" }),
|
|
915
|
+
+ ).toEqual({ emailsDeleted: 100, challengesDeleted: 1, complete: false });
|
|
916
|
+
+ expect(
|
|
917
|
+
+ await t.mutation(api.verifiedEmails.eraseUserBatch, { userId: "old" }),
|
|
918
|
+
+ ).toEqual({ emailsDeleted: 1, challengesDeleted: 0, complete: true });
|
|
919
|
+
+ expect(
|
|
920
|
+
+ await t.query(api.verifiedEmails.getPrimaryEmail, { userId: "other" }),
|
|
921
|
+
+ ).toBe("other@example.com");
|
|
922
|
+
+ expect(
|
|
923
|
+
+ await t.query(api.verifiedEmails.getPrimaryEmail, { userId: "old" }),
|
|
924
|
+
+ ).toBeNull();
|
|
925
|
+
+});
|
|
926
|
+
--- a/src/components/email/schema.ts
|
|
927
|
+
+++ b/src/components/email/schema.ts
|
|
928
|
+
@@ -2,6 +2,10 @@
|
|
929
|
+
import { v } from "convex/values";
|
|
930
|
+
|
|
931
|
+
export default defineSchema({
|
|
932
|
+
+ erasedUsers: defineTable({ userId: v.string(), erasedAt: v.number() }).index(
|
|
933
|
+
+ "by_userId",
|
|
934
|
+
+ ["userId"],
|
|
935
|
+
+ ),
|
|
936
|
+
// One row for each verified email address.
|
|
937
|
+
//
|
|
938
|
+
// Invariants the component keeps true:
|
|
939
|
+
--- a/src/components/email/verifiedEmails.ts
|
|
940
|
+
+++ b/src/components/email/verifiedEmails.ts
|
|
941
|
+
@@ -114,3 +114,36 @@
|
|
942
|
+
return null;
|
|
943
|
+
},
|
|
944
|
+
});
|
|
945
|
+
+
|
|
946
|
+
+/** App-server only. Establish a permanent fence and delete bounded attributed rows. */
|
|
947
|
+
+export const eraseUserBatch = mutation({
|
|
948
|
+
+ args: { userId: v.string() },
|
|
949
|
+
+ returns: v.object({
|
|
950
|
+
+ emailsDeleted: v.number(),
|
|
951
|
+
+ challengesDeleted: v.number(),
|
|
952
|
+
+ complete: v.boolean(),
|
|
953
|
+
+ }),
|
|
954
|
+
+ handler: async (ctx, { userId }) => {
|
|
955
|
+
+ const tombstone = await ctx.db
|
|
956
|
+
+ .query("erasedUsers")
|
|
957
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
958
|
+
+ .unique();
|
|
959
|
+
+ if (!tombstone)
|
|
960
|
+
+ await ctx.db.insert("erasedUsers", { userId, erasedAt: Date.now() });
|
|
961
|
+
+ const emails = await ctx.db
|
|
962
|
+
+ .query("verifiedEmails")
|
|
963
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
964
|
+
+ .take(100);
|
|
965
|
+
+ const challenges = await ctx.db
|
|
966
|
+
+ .query("challenges")
|
|
967
|
+
+ .withIndex("by_purpose_userId", (q) => q.eq("purpose.userId", userId))
|
|
968
|
+
+ .take(100);
|
|
969
|
+
+ for (const row of emails) await ctx.db.delete("verifiedEmails", row._id);
|
|
970
|
+
+ for (const row of challenges) await ctx.db.delete("challenges", row._id);
|
|
971
|
+
+ return {
|
|
972
|
+
+ emailsDeleted: emails.length,
|
|
973
|
+
+ challengesDeleted: challenges.length,
|
|
974
|
+
+ complete: emails.length < 100 && challenges.length < 100,
|
|
975
|
+
+ };
|
|
976
|
+
+ },
|
|
977
|
+
+});
|
|
978
|
+
--- a/src/components/google/_generated/api.ts
|
|
979
|
+
+++ b/src/components/google/_generated/api.ts
|
|
980
|
+
@@ -9,7 +9,9 @@
|
|
981
|
+
*/
|
|
982
|
+
|
|
983
|
+
import type * as constants from "../constants.js";
|
|
984
|
+
+import type * as erasure from "../erasure.js";
|
|
985
|
+
import type * as http from "../http.js";
|
|
986
|
+
+import type * as migration from "../migration.js";
|
|
987
|
+
import type * as provider from "../provider.js";
|
|
988
|
+
|
|
989
|
+
import type {
|
|
990
|
+
@@ -21,7 +23,9 @@
|
|
991
|
+
|
|
992
|
+
const fullApi: ApiFromModules<{
|
|
993
|
+
constants: typeof constants;
|
|
994
|
+
+ erasure: typeof erasure;
|
|
995
|
+
http: typeof http;
|
|
996
|
+
+ migration: typeof migration;
|
|
997
|
+
provider: typeof provider;
|
|
998
|
+
}> = anyApi as any;
|
|
999
|
+
|
|
1000
|
+
--- a/src/components/google/_generated/component.ts
|
|
1001
|
+
+++ b/src/components/google/_generated/component.ts
|
|
1002
|
+
@@ -23,6 +23,59 @@
|
|
1003
|
+
*/
|
|
1004
|
+
export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
1005
|
+
{
|
|
1006
|
+
+ erasure: {
|
|
1007
|
+
+ beginUserErasure: FunctionReference<
|
|
1008
|
+
+ "mutation",
|
|
1009
|
+
+ "internal",
|
|
1010
|
+
+ { userId: string },
|
|
1011
|
+
+ null,
|
|
1012
|
+
+ Name
|
|
1013
|
+
+ >;
|
|
1014
|
+
+ purgeUserLinkedAuth: FunctionReference<
|
|
1015
|
+
+ "mutation",
|
|
1016
|
+
+ "internal",
|
|
1017
|
+
+ { userId: string },
|
|
1018
|
+
+ { complete: boolean; deletedAccounts: number },
|
|
1019
|
+
+ Name
|
|
1020
|
+
+ >;
|
|
1021
|
+
+ };
|
|
1022
|
+
+ migration: {
|
|
1023
|
+
+ _internal_dangerous_lock: FunctionReference<
|
|
1024
|
+
+ "mutation",
|
|
1025
|
+
+ "internal",
|
|
1026
|
+
+ {},
|
|
1027
|
+
+ null,
|
|
1028
|
+
+ Name
|
|
1029
|
+
+ >;
|
|
1030
|
+
+ _internal_dangerous_unlock: FunctionReference<
|
|
1031
|
+
+ "mutation",
|
|
1032
|
+
+ "internal",
|
|
1033
|
+
+ {},
|
|
1034
|
+
+ null,
|
|
1035
|
+
+ Name
|
|
1036
|
+
+ >;
|
|
1037
|
+
+ importAccounts: FunctionReference<
|
|
1038
|
+
+ "mutation",
|
|
1039
|
+
+ "internal",
|
|
1040
|
+
+ { rows: Array<{ providerAccountId: string; userId: string }> },
|
|
1041
|
+
+ null,
|
|
1042
|
+
+ Name
|
|
1043
|
+
+ >;
|
|
1044
|
+
+ importCutoffs: FunctionReference<
|
|
1045
|
+
+ "mutation",
|
|
1046
|
+
+ "internal",
|
|
1047
|
+
+ { rows: Array<{ cutoff: number; digest: string }> },
|
|
1048
|
+
+ null,
|
|
1049
|
+
+ Name
|
|
1050
|
+
+ >;
|
|
1051
|
+
+ importErasedUsers: FunctionReference<
|
|
1052
|
+
+ "mutation",
|
|
1053
|
+
+ "internal",
|
|
1054
|
+
+ { rows: Array<{ requestedAt: number; userId: string }> },
|
|
1055
|
+
+ null,
|
|
1056
|
+
+ Name
|
|
1057
|
+
+ >;
|
|
1058
|
+
+ };
|
|
1059
|
+
provider: {
|
|
1060
|
+
_internal_dangerous_createAccount: FunctionReference<
|
|
1061
|
+
"mutation",
|
|
1062
|
+
@@ -36,6 +89,13 @@
|
|
1063
|
+
"internal",
|
|
1064
|
+
{ codeVerifier: string; redirectTo: string; stateHash: string },
|
|
1065
|
+
{ callbackUrl: string; clientId: string },
|
|
1066
|
+
+ Name
|
|
1067
|
+
+ >;
|
|
1068
|
+
+ beginUserErasure: FunctionReference<
|
|
1069
|
+
+ "mutation",
|
|
1070
|
+
+ "internal",
|
|
1071
|
+
+ { userId: string },
|
|
1072
|
+
+ null,
|
|
1073
|
+
Name
|
|
1074
|
+
>;
|
|
1075
|
+
claimTicket: FunctionReference<
|
|
1076
|
+
@@ -52,5 +112,12 @@
|
|
1077
|
+
string | null,
|
|
1078
|
+
Name
|
|
1079
|
+
>;
|
|
1080
|
+
+ purgeUserLinkedAuth: FunctionReference<
|
|
1081
|
+
+ "mutation",
|
|
1082
|
+
+ "internal",
|
|
1083
|
+
+ { userId: string },
|
|
1084
|
+
+ { complete: boolean; deletedAccounts: number },
|
|
1085
|
+
+ Name
|
|
1086
|
+
+ >;
|
|
1087
|
+
};
|
|
1088
|
+
};
|
|
1089
|
+
--- a/src/components/google/_generated/server.ts
|
|
1090
|
+
+++ b/src/components/google/_generated/server.ts
|
|
1091
|
+
@@ -39,8 +39,9 @@
|
|
1092
|
+
type Env = {
|
|
1093
|
+
readonly CONVEX_CLOUD_URL: string;
|
|
1094
|
+
readonly CONVEX_SITE_URL: string;
|
|
1095
|
+
- readonly CLIENT_ID: string;
|
|
1096
|
+
- readonly CLIENT_SECRET: string;
|
|
1097
|
+
+ readonly CALLBACK_URL: string | undefined;
|
|
1098
|
+
+ readonly CLIENT_ID: string | undefined;
|
|
1099
|
+
+ readonly CLIENT_SECRET: string | undefined;
|
|
1100
|
+
};
|
|
1101
|
+
|
|
1102
|
+
/**
|
|
1103
|
+
--- a/src/components/google/convex.config.ts
|
|
1104
|
+
+++ b/src/components/google/convex.config.ts
|
|
1105
|
+
@@ -17,8 +17,9 @@
|
|
1106
|
+
*/
|
|
1107
|
+
const component = defineComponent("authGoogle", {
|
|
1108
|
+
env: {
|
|
1109
|
+
- CLIENT_ID: v.string(),
|
|
1110
|
+
- CLIENT_SECRET: v.string(),
|
|
1111
|
+
+ CLIENT_ID: v.optional(v.string()),
|
|
1112
|
+
+ CLIENT_SECRET: v.optional(v.string()),
|
|
1113
|
+
+ CALLBACK_URL: v.optional(v.string()),
|
|
1114
|
+
},
|
|
1115
|
+
});
|
|
1116
|
+
|
|
1117
|
+
--- /dev/null
|
|
1118
|
+
+++ b/src/components/google/erasure.test.ts
|
|
1119
|
+
@@ -0,0 +1,105 @@
|
|
1120
|
+
+import { convexTest } from "convex-test";
|
|
1121
|
+
+import { expect, test } from "vitest";
|
|
1122
|
+
+import { api } from "./_generated/api.ts";
|
|
1123
|
+
+import schema from "./schema.ts";
|
|
1124
|
+
+
|
|
1125
|
+
+const modules = import.meta.glob("./**/*.ts");
|
|
1126
|
+
+test("a mapped identity is fenced before purge and remains fenced after its mapping is removed", async () => {
|
|
1127
|
+
+ const t = convexTest({ schema, modules });
|
|
1128
|
+
+ await t.mutation(api.provider._internal_dangerous_createAccount, {
|
|
1129
|
+
+ providerAccountId: "identity-a",
|
|
1130
|
+
+ userId: "user-a",
|
|
1131
|
+
+ });
|
|
1132
|
+
+ await t.mutation(api.provider._internal_dangerous_createAccount, {
|
|
1133
|
+
+ providerAccountId: "identity-b",
|
|
1134
|
+
+ userId: "user-b",
|
|
1135
|
+
+ });
|
|
1136
|
+
+ const staleUserId = await t.query(api.provider.getUserIdByAccount, {
|
|
1137
|
+
+ providerAccountId: "identity-a",
|
|
1138
|
+
+ });
|
|
1139
|
+
+ expect(staleUserId).toBe("user-a");
|
|
1140
|
+
+ await t.mutation(api.provider.beginUserErasure, { userId: "user-a" });
|
|
1141
|
+
+ await expect(
|
|
1142
|
+
+ t.mutation(api.provider._internal_dangerous_createAccount, {
|
|
1143
|
+
+ providerAccountId: "identity-a",
|
|
1144
|
+
+ userId: staleUserId!,
|
|
1145
|
+
+ }),
|
|
1146
|
+
+ ).rejects.toThrow();
|
|
1147
|
+
+ await expect(
|
|
1148
|
+
+ t.query(api.provider.getUserIdByAccount, {
|
|
1149
|
+
+ providerAccountId: "identity-a",
|
|
1150
|
+
+ }),
|
|
1151
|
+
+ ).rejects.toThrow();
|
|
1152
|
+
+ expect(
|
|
1153
|
+
+ await t.mutation(api.provider.purgeUserLinkedAuth, { userId: "user-a" }),
|
|
1154
|
+
+ ).toEqual({ complete: true, deletedAccounts: 1 });
|
|
1155
|
+
+ await expect(
|
|
1156
|
+
+ t.query(api.provider.getUserIdByAccount, {
|
|
1157
|
+
+ providerAccountId: "identity-a",
|
|
1158
|
+
+ }),
|
|
1159
|
+
+ ).rejects.toThrow();
|
|
1160
|
+
+ await expect(
|
|
1161
|
+
+ t.mutation(api.provider._internal_dangerous_createAccount, {
|
|
1162
|
+
+ providerAccountId: "identity-a",
|
|
1163
|
+
+ userId: "fresh-user",
|
|
1164
|
+
+ }),
|
|
1165
|
+
+ ).rejects.toThrow();
|
|
1166
|
+
+ expect(
|
|
1167
|
+
+ await t.query(api.provider.getUserIdByAccount, {
|
|
1168
|
+
+ providerAccountId: "identity-b",
|
|
1169
|
+
+ }),
|
|
1170
|
+
+ ).toBe("user-b");
|
|
1171
|
+
+});
|
|
1172
|
+
+
|
|
1173
|
+
+test("concurrent account creation and fence prevent reuse of the erased user ID", async () => {
|
|
1174
|
+
+ const t = convexTest({ schema, modules });
|
|
1175
|
+
+ await Promise.allSettled([
|
|
1176
|
+
+ t.mutation(api.provider._internal_dangerous_createAccount, {
|
|
1177
|
+
+ providerAccountId: "raced",
|
|
1178
|
+
+ userId: "owner",
|
|
1179
|
+
+ }),
|
|
1180
|
+
+ t.mutation(api.provider.beginUserErasure, { userId: "owner" }),
|
|
1181
|
+
+ ]);
|
|
1182
|
+
+ // If creation lost, it is rejected by the user fence. If it won, purge records
|
|
1183
|
+
+ // the identity fence before deleting the mapping.
|
|
1184
|
+
+ await t.mutation(api.provider.beginUserErasure, { userId: "owner" });
|
|
1185
|
+
+ await t.mutation(api.provider.purgeUserLinkedAuth, { userId: "owner" });
|
|
1186
|
+
+ await expect(
|
|
1187
|
+
+ t.mutation(api.provider._internal_dangerous_createAccount, {
|
|
1188
|
+
+ providerAccountId: "raced",
|
|
1189
|
+
+ userId: "owner",
|
|
1190
|
+
+ }),
|
|
1191
|
+
+ ).rejects.toThrow();
|
|
1192
|
+
+});
|
|
1193
|
+
+
|
|
1194
|
+
+test("migration imports are idempotent, bounded, and reject conflicting owners", async () => {
|
|
1195
|
+
+ const t = convexTest({ schema, modules });
|
|
1196
|
+
+ const cutoffs = [{ digest: "a".repeat(64), cutoff: 100 }];
|
|
1197
|
+
+ const erasedUsers = [{ userId: "old", requestedAt: 101 }];
|
|
1198
|
+
+ const accounts = [{ providerAccountId: "old-identity", userId: "old" }];
|
|
1199
|
+
+ for (let i = 0; i < 2; i++) {
|
|
1200
|
+
+ await t.mutation(api.migration.importCutoffs, { rows: cutoffs });
|
|
1201
|
+
+ await t.mutation(api.migration.importErasedUsers, { rows: erasedUsers });
|
|
1202
|
+
+ await t.mutation(api.migration.importAccounts, { rows: accounts });
|
|
1203
|
+
+ }
|
|
1204
|
+
+ await expect(
|
|
1205
|
+
+ t.mutation(api.migration.importAccounts, {
|
|
1206
|
+
+ rows: [{ ...accounts[0], userId: "other" }],
|
|
1207
|
+
+ }),
|
|
1208
|
+
+ ).rejects.toThrow("Mapping conflict");
|
|
1209
|
+
+ await expect(
|
|
1210
|
+
+ t.query(api.provider.getUserIdByAccount, {
|
|
1211
|
+
+ providerAccountId: "old-identity",
|
|
1212
|
+
+ }),
|
|
1213
|
+
+ ).rejects.toThrow();
|
|
1214
|
+
+ expect(
|
|
1215
|
+
+ await t.run(
|
|
1216
|
+
+ async (ctx) => (await ctx.db.query("accounts").collect()).length,
|
|
1217
|
+
+ ),
|
|
1218
|
+
+ ).toBe(1);
|
|
1219
|
+
+ await expect(
|
|
1220
|
+
+ t.mutation(api.migration.importAccounts, {
|
|
1221
|
+
+ rows: Array.from({ length: 101 }, () => accounts[0]),
|
|
1222
|
+
+ }),
|
|
1223
|
+
+ ).rejects.toThrow();
|
|
1224
|
+
+});
|
|
1225
|
+
--- /dev/null
|
|
1226
|
+
+++ b/src/components/google/erasure.ts
|
|
1227
|
+
@@ -0,0 +1,86 @@
|
|
1228
|
+
+import { v } from "convex/values";
|
|
1229
|
+
+import { mutation, type QueryCtx } from "./_generated/server.ts";
|
|
1230
|
+
+import { sha256Hex } from "../../lib/crypto.ts";
|
|
1231
|
+
+
|
|
1232
|
+
+function erasedUser(ctx: QueryCtx, userId: string) {
|
|
1233
|
+
+ return ctx.db
|
|
1234
|
+
+ .query("erasedUsers")
|
|
1235
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1236
|
+
+ .unique();
|
|
1237
|
+
+}
|
|
1238
|
+
+function identityDigest(account: string) {
|
|
1239
|
+
+ // Same digest as the pre-stable core, so retained fences can be migrated.
|
|
1240
|
+
+ return sha256Hex(JSON.stringify(["google", account]));
|
|
1241
|
+
+}
|
|
1242
|
+
+export async function requireMigrationUnlocked(ctx: QueryCtx) {
|
|
1243
|
+
+ if (
|
|
1244
|
+
+ await ctx.db
|
|
1245
|
+
+ .query("migrationLock")
|
|
1246
|
+
+ .withIndex("by_key", (q) => q.eq("key", "auth-v2"))
|
|
1247
|
+
+ .unique()
|
|
1248
|
+
+ )
|
|
1249
|
+
+ throw new Error("Legacy auth migration is in progress.");
|
|
1250
|
+
+}
|
|
1251
|
+
+export async function assertIdentityActive(
|
|
1252
|
+
+ ctx: QueryCtx,
|
|
1253
|
+
+ account: string,
|
|
1254
|
+
+ userId: string | null,
|
|
1255
|
+
+) {
|
|
1256
|
+
+ await requireMigrationUnlocked(ctx);
|
|
1257
|
+
+ const digest = await identityDigest(account);
|
|
1258
|
+
+ const cutoff = await ctx.db
|
|
1259
|
+
+ .query("identityErasure")
|
|
1260
|
+
+ .withIndex("by_digest", (q) => q.eq("digest", digest))
|
|
1261
|
+
+ .unique();
|
|
1262
|
+
+ if (cutoff || (userId && (await erasedUser(ctx, userId))))
|
|
1263
|
+
+ throw new Error("Identity registration is unavailable.");
|
|
1264
|
+
+}
|
|
1265
|
+
+
|
|
1266
|
+
+/** App-server only. Coordinate with the core/password/username/email fences atomically. */
|
|
1267
|
+
+export const beginUserErasure = mutation({
|
|
1268
|
+
+ args: { userId: v.string() },
|
|
1269
|
+
+ returns: v.null(),
|
|
1270
|
+
+ handler: async (ctx, { userId }) => {
|
|
1271
|
+
+ await requireMigrationUnlocked(ctx);
|
|
1272
|
+
+ if (!userId) throw new Error("Missing user ID.");
|
|
1273
|
+
+ if (!(await erasedUser(ctx, userId)))
|
|
1274
|
+
+ await ctx.db.insert("erasedUsers", { userId, requestedAt: Date.now() });
|
|
1275
|
+
+ return null;
|
|
1276
|
+
+ },
|
|
1277
|
+
+});
|
|
1278
|
+
+
|
|
1279
|
+
+/** Bounded mapping removal with a permanent digest fence; re-registration is not supported. */
|
|
1280
|
+
+export const purgeUserLinkedAuth = mutation({
|
|
1281
|
+
+ args: { userId: v.string() },
|
|
1282
|
+
+ returns: v.object({ complete: v.boolean(), deletedAccounts: v.number() }),
|
|
1283
|
+
+ handler: async (ctx, { userId }) => {
|
|
1284
|
+
+ await requireMigrationUnlocked(ctx);
|
|
1285
|
+
+ const fence = await erasedUser(ctx, userId);
|
|
1286
|
+
+ if (!fence) throw new Error("Begin Google auth erasure first.");
|
|
1287
|
+
+ const rows = await ctx.db
|
|
1288
|
+
+ .query("accounts")
|
|
1289
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1290
|
+
+ .take(101);
|
|
1291
|
+
+ for (const row of rows.slice(0, 100)) {
|
|
1292
|
+
+ const digest = await identityDigest(row.providerAccountId);
|
|
1293
|
+
+ const previous = await ctx.db
|
|
1294
|
+
+ .query("identityErasure")
|
|
1295
|
+
+ .withIndex("by_digest", (q) => q.eq("digest", digest))
|
|
1296
|
+
+ .unique();
|
|
1297
|
+
+ if (!previous)
|
|
1298
|
+
+ await ctx.db.insert("identityErasure", {
|
|
1299
|
+
+ digest,
|
|
1300
|
+
+ cutoff: fence.requestedAt,
|
|
1301
|
+
+ });
|
|
1302
|
+
+ else if (previous.cutoff < fence.requestedAt)
|
|
1303
|
+
+ await ctx.db.patch("identityErasure", previous._id, {
|
|
1304
|
+
+ cutoff: fence.requestedAt,
|
|
1305
|
+
+ });
|
|
1306
|
+
+ await ctx.db.delete("accounts", row._id);
|
|
1307
|
+
+ }
|
|
1308
|
+
+ return {
|
|
1309
|
+
+ complete: rows.length <= 100,
|
|
1310
|
+
+ deletedAccounts: Math.min(rows.length, 100),
|
|
1311
|
+
+ };
|
|
1312
|
+
+ },
|
|
1313
|
+
+});
|
|
1314
|
+
--- a/src/components/google/http.ts
|
|
1315
|
+
+++ b/src/components/google/http.ts
|
|
1316
|
+
@@ -18,13 +18,21 @@
|
|
1317
|
+
stateHash: request.stateHash,
|
|
1318
|
+
...ticket,
|
|
1319
|
+
}),
|
|
1320
|
+
- exchangeConfig: () => ({
|
|
1321
|
+
- providerName: PROVIDER_NAME,
|
|
1322
|
+
- tokenEndpoint: TOKEN_ENDPOINT,
|
|
1323
|
+
- clientId: env.CLIENT_ID,
|
|
1324
|
+
- clientSecret: () => env.CLIENT_SECRET,
|
|
1325
|
+
- issuers: ISSUERS,
|
|
1326
|
+
- }),
|
|
1327
|
+
+ exchangeConfig: () => {
|
|
1328
|
+
+ if (!env.CLIENT_ID || !env.CLIENT_SECRET)
|
|
1329
|
+
+ throw new Error("Google credentials are not configured.");
|
|
1330
|
+
+ return {
|
|
1331
|
+
+ providerName: PROVIDER_NAME,
|
|
1332
|
+
+ tokenEndpoint: TOKEN_ENDPOINT,
|
|
1333
|
+
+ clientId: env.CLIENT_ID,
|
|
1334
|
+
+ clientSecret: () => {
|
|
1335
|
+
+ if (!env.CLIENT_SECRET)
|
|
1336
|
+
+ throw new Error("Google credentials are not configured.");
|
|
1337
|
+
+ return env.CLIENT_SECRET;
|
|
1338
|
+
+ },
|
|
1339
|
+
+ issuers: ISSUERS,
|
|
1340
|
+
+ };
|
|
1341
|
+
+ },
|
|
1342
|
+
});
|
|
1343
|
+
|
|
1344
|
+
export default http;
|
|
1345
|
+
--- /dev/null
|
|
1346
|
+
+++ b/src/components/google/migration.ts
|
|
1347
|
+
@@ -0,0 +1,99 @@
|
|
1348
|
+
+/** Component-only import primitives. They do not open auth or establish that a
|
|
1349
|
+
+ * source snapshot is complete; the app's atomic coordinator must do both. */
|
|
1350
|
+
+import { v } from "convex/values";
|
|
1351
|
+
+import { mutation } from "./_generated/server.ts";
|
|
1352
|
+
+
|
|
1353
|
+
+const itemLimit = <T>(items: T[]) => {
|
|
1354
|
+
+ if (items.length > 100) throw new Error("Migration batch exceeds 100 rows");
|
|
1355
|
+
+};
|
|
1356
|
+
+export const importCutoffs = mutation({
|
|
1357
|
+
+ args: { rows: v.array(v.object({ digest: v.string(), cutoff: v.number() })) },
|
|
1358
|
+
+ returns: v.null(),
|
|
1359
|
+
+ handler: async (ctx, { rows }) => {
|
|
1360
|
+
+ itemLimit(rows);
|
|
1361
|
+
+ for (const row of rows) {
|
|
1362
|
+
+ if (!/^[a-f0-9]{64}$/.test(row.digest) || !Number.isFinite(row.cutoff))
|
|
1363
|
+
+ throw new Error("Invalid cutoff");
|
|
1364
|
+
+ const existing = await ctx.db
|
|
1365
|
+
+ .query("identityErasure")
|
|
1366
|
+
+ .withIndex("by_digest", (q) => q.eq("digest", row.digest))
|
|
1367
|
+
+ .unique();
|
|
1368
|
+
+ if (existing && existing.cutoff !== row.cutoff)
|
|
1369
|
+
+ throw new Error("Cutoff conflict");
|
|
1370
|
+
+ if (!existing) await ctx.db.insert("identityErasure", row);
|
|
1371
|
+
+ }
|
|
1372
|
+
+ return null;
|
|
1373
|
+
+ },
|
|
1374
|
+
+});
|
|
1375
|
+
+export const importErasedUsers = mutation({
|
|
1376
|
+
+ args: {
|
|
1377
|
+
+ rows: v.array(v.object({ userId: v.string(), requestedAt: v.number() })),
|
|
1378
|
+
+ },
|
|
1379
|
+
+ returns: v.null(),
|
|
1380
|
+
+ handler: async (ctx, { rows }) => {
|
|
1381
|
+
+ itemLimit(rows);
|
|
1382
|
+
+ for (const row of rows) {
|
|
1383
|
+
+ if (!row.userId || !Number.isFinite(row.requestedAt))
|
|
1384
|
+
+ throw new Error("Invalid user fence");
|
|
1385
|
+
+ const existing = await ctx.db
|
|
1386
|
+
+ .query("erasedUsers")
|
|
1387
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", row.userId))
|
|
1388
|
+
+ .unique();
|
|
1389
|
+
+ if (existing && existing.requestedAt !== row.requestedAt)
|
|
1390
|
+
+ throw new Error("User fence conflict");
|
|
1391
|
+
+ if (!existing) await ctx.db.insert("erasedUsers", row);
|
|
1392
|
+
+ }
|
|
1393
|
+
+ return null;
|
|
1394
|
+
+ },
|
|
1395
|
+
+});
|
|
1396
|
+
+export const importAccounts = mutation({
|
|
1397
|
+
+ args: {
|
|
1398
|
+
+ rows: v.array(
|
|
1399
|
+
+ v.object({ providerAccountId: v.string(), userId: v.string() }),
|
|
1400
|
+
+ ),
|
|
1401
|
+
+ },
|
|
1402
|
+
+ returns: v.null(),
|
|
1403
|
+
+ handler: async (ctx, { rows }) => {
|
|
1404
|
+
+ itemLimit(rows);
|
|
1405
|
+
+ for (const row of rows) {
|
|
1406
|
+
+ if (!row.providerAccountId || !row.userId)
|
|
1407
|
+
+ throw new Error("Invalid mapping");
|
|
1408
|
+
+ const existing = await ctx.db
|
|
1409
|
+
+ .query("accounts")
|
|
1410
|
+
+ .withIndex("providerAccountId", (q) =>
|
|
1411
|
+
+ q.eq("providerAccountId", row.providerAccountId),
|
|
1412
|
+
+ )
|
|
1413
|
+
+ .unique();
|
|
1414
|
+
+ if (existing && existing.userId !== row.userId)
|
|
1415
|
+
+ throw new Error("Mapping conflict");
|
|
1416
|
+
+ if (!existing) await ctx.db.insert("accounts", row);
|
|
1417
|
+
+ }
|
|
1418
|
+
+ return null;
|
|
1419
|
+
+ },
|
|
1420
|
+
+});
|
|
1421
|
+
+
|
|
1422
|
+
+/** Only the app's internal coordinator may hold or release this lock. */
|
|
1423
|
+
+export const _internal_dangerous_lock = mutation({
|
|
1424
|
+
+ args: {},
|
|
1425
|
+
+ returns: v.null(),
|
|
1426
|
+
+ handler: async (ctx) => {
|
|
1427
|
+
+ const row = await ctx.db
|
|
1428
|
+
+ .query("migrationLock")
|
|
1429
|
+
+ .withIndex("by_key", (q) => q.eq("key", "auth-v2"))
|
|
1430
|
+
+ .unique();
|
|
1431
|
+
+ if (!row) await ctx.db.insert("migrationLock", { key: "auth-v2" });
|
|
1432
|
+
+ return null;
|
|
1433
|
+
+ },
|
|
1434
|
+
+});
|
|
1435
|
+
+export const _internal_dangerous_unlock = mutation({
|
|
1436
|
+
+ args: {},
|
|
1437
|
+
+ returns: v.null(),
|
|
1438
|
+
+ handler: async (ctx) => {
|
|
1439
|
+
+ const row = await ctx.db
|
|
1440
|
+
+ .query("migrationLock")
|
|
1441
|
+
+ .withIndex("by_key", (q) => q.eq("key", "auth-v2"))
|
|
1442
|
+
+ .unique();
|
|
1443
|
+
+ if (row) await ctx.db.delete("migrationLock", row._id);
|
|
1444
|
+
+ return null;
|
|
1445
|
+
+ },
|
|
1446
|
+
+});
|
|
1447
|
+
--- a/src/components/google/provider.ts
|
|
1448
|
+
+++ b/src/components/google/provider.ts
|
|
1449
|
+
@@ -1,14 +1,17 @@
|
|
1450
|
+
import type { Doc } from "./_generated/dataModel.ts";
|
|
1451
|
+
import { env, internalMutation, mutation, query } from "./_generated/server.ts";
|
|
1452
|
+
import { buildProviderFunctions } from "../../lib/oauth/providerFunctions.ts";
|
|
1453
|
+
+import { v } from "convex/values";
|
|
1454
|
+
+import * as dbHelpers from "../../lib/oauth/dbHelpers.ts";
|
|
1455
|
+
+import { accountFields } from "../../lib/oauth/schema.ts";
|
|
1456
|
+
+import { assertIdentityActive } from "./erasure.ts";
|
|
1457
|
+
+export { beginUserErasure, purgeUserLinkedAuth } from "./erasure.ts";
|
|
1458
|
+
|
|
1459
|
+
export const {
|
|
1460
|
+
_internal_dangerous_createAuthorizationRequest,
|
|
1461
|
+
claimAuthorizationRequest,
|
|
1462
|
+
createTicket,
|
|
1463
|
+
claimTicket,
|
|
1464
|
+
- getUserIdByAccount,
|
|
1465
|
+
- _internal_dangerous_createAccount,
|
|
1466
|
+
} = buildProviderFunctions<
|
|
1467
|
+
Doc<"authorizationRequests">,
|
|
1468
|
+
Doc<"tickets">,
|
|
1469
|
+
@@ -17,5 +20,29 @@
|
|
1470
|
+
query,
|
|
1471
|
+
mutation,
|
|
1472
|
+
internalMutation,
|
|
1473
|
+
- clientId: () => env.CLIENT_ID,
|
|
1474
|
+
+ clientId: () => {
|
|
1475
|
+
+ if (!env.CLIENT_ID) throw new Error("Google CLIENT_ID is not configured.");
|
|
1476
|
+
+ return env.CLIENT_ID;
|
|
1477
|
+
+ },
|
|
1478
|
+
});
|
|
1479
|
+
+
|
|
1480
|
+
+export const getUserIdByAccount = query({
|
|
1481
|
+
+ args: { providerAccountId: v.string() },
|
|
1482
|
+
+ returns: v.union(v.string(), v.null()),
|
|
1483
|
+
+ handler: async (ctx, args) => {
|
|
1484
|
+
+ const userId = await dbHelpers.findAccountUserId<Doc<"accounts">>(
|
|
1485
|
+
+ ctx,
|
|
1486
|
+
+ args,
|
|
1487
|
+
+ );
|
|
1488
|
+
+ await assertIdentityActive(ctx, args.providerAccountId, userId);
|
|
1489
|
+
+ return userId;
|
|
1490
|
+
+ },
|
|
1491
|
+
+});
|
|
1492
|
+
+export const _internal_dangerous_createAccount = mutation({
|
|
1493
|
+
+ args: accountFields,
|
|
1494
|
+
+ returns: v.null(),
|
|
1495
|
+
+ handler: async (ctx, args) => {
|
|
1496
|
+
+ await assertIdentityActive(ctx, args.providerAccountId, args.userId);
|
|
1497
|
+
+ return dbHelpers.insertAccount<Doc<"accounts">>(ctx, args);
|
|
1498
|
+
+ },
|
|
1499
|
+
+});
|
|
1500
|
+
--- a/src/components/google/schema.ts
|
|
1501
|
+
+++ b/src/components/google/schema.ts
|
|
1502
|
+
@@ -1,12 +1,26 @@
|
|
1503
|
+
-import { defineSchema } from "convex/server";
|
|
1504
|
+
+import { defineSchema, defineTable } from "convex/server";
|
|
1505
|
+
+import { v } from "convex/values";
|
|
1506
|
+
import {
|
|
1507
|
+
- accountsTable,
|
|
1508
|
+
+ accountFields,
|
|
1509
|
+
authorizationRequestsTable,
|
|
1510
|
+
ticketsTable,
|
|
1511
|
+
} from "../../lib/oauth/schema.ts";
|
|
1512
|
+
|
|
1513
|
+
export default defineSchema({
|
|
1514
|
+
+ migrationLock: defineTable({ key: v.literal("auth-v2") }).index("by_key", [
|
|
1515
|
+
+ "key",
|
|
1516
|
+
+ ]),
|
|
1517
|
+
authorizationRequests: authorizationRequestsTable,
|
|
1518
|
+
tickets: ticketsTable,
|
|
1519
|
+
- accounts: accountsTable,
|
|
1520
|
+
+ accounts: defineTable(accountFields)
|
|
1521
|
+
+ .index("providerAccountId", ["providerAccountId"])
|
|
1522
|
+
+ .index("by_userId", ["userId"]),
|
|
1523
|
+
+ erasedUsers: defineTable({
|
|
1524
|
+
+ userId: v.string(),
|
|
1525
|
+
+ requestedAt: v.number(),
|
|
1526
|
+
+ }).index("by_userId", ["userId"]),
|
|
1527
|
+
+ identityErasure: defineTable({
|
|
1528
|
+
+ digest: v.string(),
|
|
1529
|
+
+ cutoff: v.number(),
|
|
1530
|
+
+ }).index("by_digest", ["digest"]),
|
|
1531
|
+
});
|
|
1532
|
+
--- a/src/components/password/_generated/component.ts
|
|
1533
|
+
+++ b/src/components/password/_generated/component.ts
|
|
1534
|
+
@@ -39,6 +39,13 @@
|
|
1535
|
+
},
|
|
1536
|
+
Name
|
|
1537
|
+
>;
|
|
1538
|
+
+ eraseUserPasswords: FunctionReference<
|
|
1539
|
+
+ "mutation",
|
|
1540
|
+
+ "internal",
|
|
1541
|
+
+ { userId: string },
|
|
1542
|
+
+ { complete: boolean; deleted: number },
|
|
1543
|
+
+ Name
|
|
1544
|
+
+ >;
|
|
1545
|
+
verifyPassword: FunctionReference<
|
|
1546
|
+
"mutation",
|
|
1547
|
+
"internal",
|
|
1548
|
+
--- /dev/null
|
|
1549
|
+
+++ b/src/components/password/erasure.test.ts
|
|
1550
|
+
@@ -0,0 +1,46 @@
|
|
1551
|
+
+import { convexTest } from "convex-test";
|
|
1552
|
+
+import { expect, test } from "vitest";
|
|
1553
|
+
+import { api } from "./_generated/api.ts";
|
|
1554
|
+
+import schema from "./schema.ts";
|
|
1555
|
+
+const modules = import.meta.glob("./**/*.ts");
|
|
1556
|
+
+test("bounded password erasure fences old-user verification and writes", async () => {
|
|
1557
|
+
+ const t = convexTest({ schema, modules });
|
|
1558
|
+
+ await t.run(async (ctx) => {
|
|
1559
|
+
+ for (let i = 0; i < 201; i++)
|
|
1560
|
+
+ await ctx.db.insert("passwords", {
|
|
1561
|
+
+ userId: "old",
|
|
1562
|
+
+ passwordHashPHC: "unused",
|
|
1563
|
+
+ });
|
|
1564
|
+
+ await ctx.db.insert("passwords", {
|
|
1565
|
+
+ userId: "other",
|
|
1566
|
+
+ passwordHashPHC: "unused",
|
|
1567
|
+
+ });
|
|
1568
|
+
+ });
|
|
1569
|
+
+ expect(
|
|
1570
|
+
+ await t.mutation(api.public.eraseUserPasswords, { userId: "old" }),
|
|
1571
|
+
+ ).toEqual({ complete: false, deleted: 100 });
|
|
1572
|
+
+ expect(
|
|
1573
|
+
+ await t.mutation(api.public.eraseUserPasswords, { userId: "old" }),
|
|
1574
|
+
+ ).toEqual({ complete: false, deleted: 100 });
|
|
1575
|
+
+ expect(
|
|
1576
|
+
+ await t.mutation(api.public.eraseUserPasswords, { userId: "old" }),
|
|
1577
|
+
+ ).toEqual({ complete: true, deleted: 1 });
|
|
1578
|
+
+ expect(
|
|
1579
|
+
+ await t.mutation(api.public.verifyPassword, {
|
|
1580
|
+
+ userId: "old",
|
|
1581
|
+
+ password: "valid password phrase",
|
|
1582
|
+
+ }),
|
|
1583
|
+
+ ).toMatchObject({ success: false });
|
|
1584
|
+
+ await expect(
|
|
1585
|
+
+ t.mutation(api.public._internal_dangerous_setPassword, {
|
|
1586
|
+
+ userId: "old",
|
|
1587
|
+
+ password: "valid password phrase",
|
|
1588
|
+
+ minimumLength: 10,
|
|
1589
|
+
+ }),
|
|
1590
|
+
+ ).rejects.toThrow();
|
|
1591
|
+
+ expect(
|
|
1592
|
+
+ await t.run(async (ctx) =>
|
|
1593
|
+
+ (await ctx.db.query("passwords").collect()).map((row) => row.userId),
|
|
1594
|
+
+ ),
|
|
1595
|
+
+ ).toEqual(["other"]);
|
|
1596
|
+
+});
|
|
1597
|
+
--- a/src/components/password/public.ts
|
|
1598
|
+
+++ b/src/components/password/public.ts
|
|
1599
|
+
@@ -72,6 +72,8 @@
|
|
1600
|
+
ctx,
|
|
1601
|
+
{ userId, password, minimumLength },
|
|
1602
|
+
): Promise<SetPasswordResult> => {
|
|
1603
|
+
+ if (await erasedUser(ctx, userId))
|
|
1604
|
+
+ throw new Error("Password account is unavailable.");
|
|
1605
|
+
const userError = validateNewPassword(password, minimumLength);
|
|
1606
|
+
if (userError !== null) {
|
|
1607
|
+
return { success: false, userError };
|
|
1608
|
+
@@ -107,6 +109,8 @@
|
|
1609
|
+
args: { userId: v.string(), password: v.string() },
|
|
1610
|
+
returns: verifyPasswordResult,
|
|
1611
|
+
handler: async (ctx, { userId, password }): Promise<VerifyPasswordResult> => {
|
|
1612
|
+
+ if (await erasedUser(ctx, userId))
|
|
1613
|
+
+ return { success: false, userError: { error: "INVALID_CREDENTIALS" } };
|
|
1614
|
+
const status = await rateLimiter.limit(ctx, "verifyPassword", {
|
|
1615
|
+
key: userId,
|
|
1616
|
+
});
|
|
1617
|
+
@@ -162,3 +166,30 @@
|
|
1618
|
+
.withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1619
|
+
.unique();
|
|
1620
|
+
}
|
|
1621
|
+
+
|
|
1622
|
+
+/** App-server-only bounded erasure; tombstone prevents old-user recreation. */
|
|
1623
|
+
+export const eraseUserPasswords = mutation({
|
|
1624
|
+
+ args: { userId: v.string() },
|
|
1625
|
+
+ returns: v.object({ complete: v.boolean(), deleted: v.number() }),
|
|
1626
|
+
+ handler: async (ctx, { userId }) => {
|
|
1627
|
+
+ if (!userId) throw new Error("Missing user ID.");
|
|
1628
|
+
+ if (!(await erasedUser(ctx, userId)))
|
|
1629
|
+
+ await ctx.db.insert("erasedUsers", { userId, erasedAt: Date.now() });
|
|
1630
|
+
+ const rows = await ctx.db
|
|
1631
|
+
+ .query("passwords")
|
|
1632
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1633
|
+
+ .take(101);
|
|
1634
|
+
+ for (const row of rows.slice(0, 100))
|
|
1635
|
+
+ await ctx.db.delete("passwords", row._id);
|
|
1636
|
+
+ return {
|
|
1637
|
+
+ complete: rows.length <= 100,
|
|
1638
|
+
+ deleted: Math.min(rows.length, 100),
|
|
1639
|
+
+ };
|
|
1640
|
+
+ },
|
|
1641
|
+
+});
|
|
1642
|
+
+async function erasedUser(ctx: QueryCtx, userId: string) {
|
|
1643
|
+
+ return await ctx.db
|
|
1644
|
+
+ .query("erasedUsers")
|
|
1645
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1646
|
+
+ .unique();
|
|
1647
|
+
+}
|
|
1648
|
+
--- a/src/components/password/schema.ts
|
|
1649
|
+
+++ b/src/components/password/schema.ts
|
|
1650
|
+
@@ -2,6 +2,10 @@
|
|
1651
|
+
import { v } from "convex/values";
|
|
1652
|
+
|
|
1653
|
+
export default defineSchema({
|
|
1654
|
+
+ erasedUsers: defineTable({ userId: v.string(), erasedAt: v.number() }).index(
|
|
1655
|
+
+ "by_userId",
|
|
1656
|
+
+ ["userId"],
|
|
1657
|
+
+ ),
|
|
1658
|
+
passwords: defineTable({
|
|
1659
|
+
userId: v.string(),
|
|
1660
|
+
passwordHashPHC: v.string(), // format: https://github.com/C2SP/C2SP/blob/main/phc-strings.md
|
|
1661
|
+
--- a/src/components/username/_generated/component.ts
|
|
1662
|
+
+++ b/src/components/username/_generated/component.ts
|
|
1663
|
+
@@ -25,6 +25,13 @@
|
|
1664
|
+
{
|
|
1665
|
+
public: {
|
|
1666
|
+
deleteUsername: FunctionReference<
|
|
1667
|
+
+ "mutation",
|
|
1668
|
+
+ "internal",
|
|
1669
|
+
+ { userId: string },
|
|
1670
|
+
+ { deleted: boolean },
|
|
1671
|
+
+ Name
|
|
1672
|
+
+ >;
|
|
1673
|
+
+ eraseUser: FunctionReference<
|
|
1674
|
+
"mutation",
|
|
1675
|
+
"internal",
|
|
1676
|
+
{ userId: string },
|
|
1677
|
+
--- /dev/null
|
|
1678
|
+
+++ b/src/components/username/erasure.test.ts
|
|
1679
|
+
@@ -0,0 +1,29 @@
|
|
1680
|
+
+import { convexTest } from "convex-test";
|
|
1681
|
+
+import { expect, test } from "vitest";
|
|
1682
|
+
+import { api } from "./_generated/api.ts";
|
|
1683
|
+
+import schema from "./schema.ts";
|
|
1684
|
+
+const modules = import.meta.glob("./**/*.ts");
|
|
1685
|
+
+test("erased users cannot restore their username", async () => {
|
|
1686
|
+
+ const t = convexTest({ schema, modules });
|
|
1687
|
+
+ await t.mutation(api.public.setUsername, {
|
|
1688
|
+
+ userId: "old",
|
|
1689
|
+
+ username: "alice",
|
|
1690
|
+
+ });
|
|
1691
|
+
+ expect(await t.mutation(api.public.eraseUser, { userId: "old" })).toEqual({
|
|
1692
|
+
+ deleted: true,
|
|
1693
|
+
+ });
|
|
1694
|
+
+ expect(
|
|
1695
|
+
+ await t.query(api.public.getUserIdByUsername, { username: "alice" }),
|
|
1696
|
+
+ ).toBeNull();
|
|
1697
|
+
+ await expect(
|
|
1698
|
+
+ t.mutation(api.public.setUsername, { userId: "old", username: "alice" }),
|
|
1699
|
+
+ ).rejects.toThrow();
|
|
1700
|
+
+ expect(
|
|
1701
|
+
+ (
|
|
1702
|
+
+ await t.mutation(api.public.setUsername, {
|
|
1703
|
+
+ userId: "other",
|
|
1704
|
+
+ username: "bob",
|
|
1705
|
+
+ })
|
|
1706
|
+
+ ).success,
|
|
1707
|
+
+ ).toBe(true);
|
|
1708
|
+
+});
|
|
1709
|
+
--- a/src/components/username/public.ts
|
|
1710
|
+
+++ b/src/components/username/public.ts
|
|
1711
|
+
@@ -37,6 +37,13 @@
|
|
1712
|
+
args: { userId: v.string(), username: v.string() },
|
|
1713
|
+
returns: setUsernameResult,
|
|
1714
|
+
handler: async (ctx, { userId, username }): Promise<SetUsernameResult> => {
|
|
1715
|
+
+ if (
|
|
1716
|
+
+ await ctx.db
|
|
1717
|
+
+ .query("erasedUsers")
|
|
1718
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1719
|
+
+ .unique()
|
|
1720
|
+
+ )
|
|
1721
|
+
+ throw new Error("User identity has been erased");
|
|
1722
|
+
const userError = validateUsernameFormat(username);
|
|
1723
|
+
if (userError !== null) {
|
|
1724
|
+
return { success: false, userError };
|
|
1725
|
+
@@ -122,6 +129,24 @@
|
|
1726
|
+
},
|
|
1727
|
+
});
|
|
1728
|
+
|
|
1729
|
+
+/** Permanently fence the old user ID and remove its username. App-server only. */
|
|
1730
|
+
+export const eraseUser = mutation({
|
|
1731
|
+
+ args: { userId: v.string() },
|
|
1732
|
+
+ returns: v.object({ deleted: v.boolean() }),
|
|
1733
|
+
+ handler: async (ctx, { userId }) => {
|
|
1734
|
+
+ const tombstone = await ctx.db
|
|
1735
|
+
+ .query("erasedUsers")
|
|
1736
|
+
+ .withIndex("by_userId", (q) => q.eq("userId", userId))
|
|
1737
|
+
+ .unique();
|
|
1738
|
+
+ if (!tombstone)
|
|
1739
|
+
+ await ctx.db.insert("erasedUsers", { userId, erasedAt: Date.now() });
|
|
1740
|
+
+ const row = await rowByUserId(ctx, userId);
|
|
1741
|
+
+ if (!row) return { deleted: false };
|
|
1742
|
+
+ await ctx.db.delete("usernames", row._id);
|
|
1743
|
+
+ return { deleted: true };
|
|
1744
|
+
+ },
|
|
1745
|
+
+});
|
|
1746
|
+
+
|
|
1747
|
+
function rowByUserId(
|
|
1748
|
+
ctx: QueryCtx,
|
|
1749
|
+
userId: string,
|
|
1750
|
+
--- a/src/components/username/schema.ts
|
|
1751
|
+
+++ b/src/components/username/schema.ts
|
|
1752
|
+
@@ -2,6 +2,10 @@
|
|
1753
|
+
import { v } from "convex/values";
|
|
1754
|
+
|
|
1755
|
+
export default defineSchema({
|
|
1756
|
+
+ erasedUsers: defineTable({ userId: v.string(), erasedAt: v.number() }).index(
|
|
1757
|
+
+ "by_userId",
|
|
1758
|
+
+ ["userId"],
|
|
1759
|
+
+ ),
|
|
1760
|
+
// One row for each user that has a username. The component only sees an
|
|
1761
|
+
// opaque app `userId` string.
|
|
1762
|
+
usernames: defineTable({
|
|
1763
|
+
--- a/src/lib/oauth/authorize.ts
|
|
1764
|
+
+++ b/src/lib/oauth/authorize.ts
|
|
1765
|
+
@@ -59,6 +59,8 @@
|
|
1766
|
+
allowedOrigins: string[];
|
|
1767
|
+
/** The provider's authorization endpoint (a full URL). */
|
|
1768
|
+
authorizationEndpoint: string;
|
|
1769
|
+
+ /** Wrap state for a trusted shared callback relay; the client keeps the original. */
|
|
1770
|
+
+ authorizationState?: (state: string) => Promise<string>;
|
|
1771
|
+
/** Scopes to request. Left off the URL entirely when empty. */
|
|
1772
|
+
scopes: readonly string[];
|
|
1773
|
+
/**
|
|
1774
|
+
@@ -120,7 +122,9 @@
|
|
1775
|
+
response_type: "code",
|
|
1776
|
+
client_id: clientId,
|
|
1777
|
+
redirect_uri: callbackUrl,
|
|
1778
|
+
- state,
|
|
1779
|
+
+ state: options.authorizationState
|
|
1780
|
+
+ ? await options.authorizationState(state)
|
|
1781
|
+
+ : state,
|
|
1782
|
+
// Every provider gets a challenge. One that does not implement PKCE
|
|
1783
|
+
// ignores the parameters, which RFC 6749 requires of it.
|
|
1784
|
+
code_challenge: await sha256Base64Url(codeVerifier),
|
|
1785
|
+
--- a/src/lib/oauth/dbHelpers.ts
|
|
1786
|
+
+++ b/src/lib/oauth/dbHelpers.ts
|
|
1787
|
+
@@ -87,7 +87,7 @@
|
|
1788
|
+
"functions.",
|
|
1789
|
+
);
|
|
1790
|
+
}
|
|
1791
|
+
- const callbackUrl = `${siteUrl}${CALLBACK_PATH}`;
|
|
1792
|
+
+ const callbackUrl = process.env.CALLBACK_URL || `${siteUrl}${CALLBACK_PATH}`;
|
|
1793
|
+
await ctx.db.insert("authorizationRequests", {
|
|
1794
|
+
...fields,
|
|
1795
|
+
callbackUrl,
|
|
1796
|
+
--- a/src/lib/oauth/providerFunctions.ts
|
|
1797
|
+
+++ b/src/lib/oauth/providerFunctions.ts
|
|
1798
|
+
@@ -57,7 +57,7 @@
|
|
1799
|
+
*/
|
|
1800
|
+
const createRequestArgs = v
|
|
1801
|
+
.object(authorizationRequestFields)
|
|
1802
|
+
- .omit("callbackUrl", "expiresAt");
|
|
1803
|
+
+ .omit("callbackUrl", "expiresAt", "authorizationStartedAt");
|
|
1804
|
+
|
|
1805
|
+
/** The fields of a claimed request that is still live. */
|
|
1806
|
+
const claimedRequestFields = v
|
|
1807
|
+
--- /dev/null
|
|
1808
|
+
+++ b/src/lib/oauth/relay.test.ts
|
|
1809
|
+
@@ -0,0 +1,52 @@
|
|
1810
|
+
+import { convexTest } from "convex-test";
|
|
1811
|
+
+import { makeFunctionReference } from "convex/server";
|
|
1812
|
+
+import { expect, test } from "vitest";
|
|
1813
|
+
+import { sha256Hex } from "../crypto.ts";
|
|
1814
|
+
+import { buildStartSignIn } from "./authorize.ts";
|
|
1815
|
+
+import schema from "../../components/google/schema.ts";
|
|
1816
|
+
+
|
|
1817
|
+
+const start = buildStartSignIn({
|
|
1818
|
+
+ providerName: "google",
|
|
1819
|
+
+ allowedOrigins: ["https://app.example"],
|
|
1820
|
+
+ authorizationEndpoint: "https://provider.example/auth",
|
|
1821
|
+
+ scopes: ["openid"],
|
|
1822
|
+
+ authorizationState: async (state) => `relay.${state}`,
|
|
1823
|
+
+ createAuthorizationRequest: async (ctx, args) => {
|
|
1824
|
+
+ await ctx.db.insert("authorizationRequests", {
|
|
1825
|
+
+ ...args,
|
|
1826
|
+
+ callbackUrl: "https://relay.example/oauth/google/callback",
|
|
1827
|
+
+ expiresAt: Date.now() + 60_000,
|
|
1828
|
+
+ });
|
|
1829
|
+
+ return {
|
|
1830
|
+
+ clientId: "client",
|
|
1831
|
+
+ callbackUrl: "https://relay.example/oauth/google/callback",
|
|
1832
|
+
+ };
|
|
1833
|
+
+ },
|
|
1834
|
+
+});
|
|
1835
|
+
+const reference = makeFunctionReference<
|
|
1836
|
+
+ "mutation",
|
|
1837
|
+
+ { redirectTo: string },
|
|
1838
|
+
+ { redirect: string; state: string }
|
|
1839
|
+
+>("testApp:start");
|
|
1840
|
+
+test("relay state wraps only the provider URL while stored and returned state remain original", async () => {
|
|
1841
|
+
+ const t = convexTest({
|
|
1842
|
+
+ schema,
|
|
1843
|
+
+ modules: {
|
|
1844
|
+
+ ...import.meta.glob("../../components/google/**/*.ts"),
|
|
1845
|
+
+ "../../components/google/testApp.ts": async () => ({ start }),
|
|
1846
|
+
+ },
|
|
1847
|
+
+ });
|
|
1848
|
+
+ const result = await t.mutation(reference, {
|
|
1849
|
+
+ redirectTo: "https://app.example/login",
|
|
1850
|
+
+ });
|
|
1851
|
+
+ expect(new URL(result.redirect).searchParams.get("state")).toBe(
|
|
1852
|
+
+ `relay.${result.state}`,
|
|
1853
|
+
+ );
|
|
1854
|
+
+ const request = await t.run((ctx) =>
|
|
1855
|
+
+ ctx.db.query("authorizationRequests").unique(),
|
|
1856
|
+
+ );
|
|
1857
|
+
+ expect(request?.stateHash).toBe(await sha256Hex(result.state));
|
|
1858
|
+
+ expect(request?.callbackUrl).toBe(
|
|
1859
|
+
+ "https://relay.example/oauth/google/callback",
|
|
1860
|
+
+ );
|
|
1861
|
+
+});
|
|
1862
|
+
--- a/src/lib/oauth/schema.ts
|
|
1863
|
+
+++ b/src/lib/oauth/schema.ts
|
|
1864
|
+
@@ -24,6 +24,8 @@
|
|
1865
|
+
* ignores the parameters.
|
|
1866
|
+
*/
|
|
1867
|
+
codeVerifier: v.string(),
|
|
1868
|
+
+ // Retain pending requests written by the previous package.
|
|
1869
|
+
+ authorizationStartedAt: v.optional(v.number()),
|
|
1870
|
+
/** The callback rejects requests older than this. */
|
|
1871
|
+
expiresAt: v.number(),
|
|
1872
|
+
};
|
|
1873
|
+
@@ -41,6 +43,8 @@
|
|
1874
|
+
* or server that initiated the flow.
|
|
1875
|
+
*/
|
|
1876
|
+
stateHash: v.string(),
|
|
1877
|
+
+ // Retain pending tickets written by the previous package.
|
|
1878
|
+
+ authorizationStartedAt: v.optional(v.number()),
|
|
1879
|
+
/**
|
|
1880
|
+
* sha256 of the server-minted ticket code. The raw value appears only
|
|
1881
|
+
* in the callback redirect URL and is never stored.
|
|
1882
|
+
--- a/src/methods/google/server.ts
|
|
1883
|
+
+++ b/src/methods/google/server.ts
|
|
1884
|
+
@@ -73,6 +73,8 @@
|
|
1885
|
+
* for open-redirect prevention.
|
|
1886
|
+
*/
|
|
1887
|
+
allowedRedirectOrigins: string[];
|
|
1888
|
+
+ /** Wrap OAuth state for an application-controlled shared callback relay. */
|
|
1889
|
+
+ authorizationState?: (state: string) => Promise<string>;
|
|
1890
|
+
};
|
|
1891
|
+
|
|
1892
|
+
/**
|
|
1893
|
+
@@ -125,6 +127,7 @@
|
|
1894
|
+
const startSignIn = buildStartSignIn({
|
|
1895
|
+
providerName: PROVIDER_NAME,
|
|
1896
|
+
allowedOrigins,
|
|
1897
|
+
+ authorizationState: options.authorizationState,
|
|
1898
|
+
authorizationEndpoint: AUTHORIZATION_ENDPOINT,
|
|
1899
|
+
scopes: SCOPES,
|
|
1900
|
+
createAuthorizationRequest:
|
|
1901
|
+
--- a/src/server/index.ts
|
|
1902
|
+
+++ b/src/server/index.ts
|
|
1903
|
+
@@ -13,3 +13,5 @@
|
|
1904
|
+
export { convexAuthProvider } from "./authProvider.ts";
|
|
1905
|
+
export { setupConvexAuth, type AuthCore } from "./setup.ts";
|
|
1906
|
+
export { getAuthUserId } from "./userId.ts";
|
|
1907
|
+
+
|
|
1908
|
+
+export { setupLegacyGoogleMigration } from "./legacyMigration.ts";
|
|
1909
|
+
--- /dev/null
|
|
1910
|
+
+++ b/src/server/legacyMigration.test.ts
|
|
1911
|
+
@@ -0,0 +1,122 @@
|
|
1912
|
+
+import { convexTest } from "convex-test";
|
|
1913
|
+
+import {
|
|
1914
|
+
+ componentsGeneric,
|
|
1915
|
+
+ internalMutationGeneric,
|
|
1916
|
+
+ makeFunctionReference,
|
|
1917
|
+
+} from "convex/server";
|
|
1918
|
+
+import { v } from "convex/values";
|
|
1919
|
+
+import { expect, test } from "vitest";
|
|
1920
|
+
+import type { ComponentApi as Core } from "../component/_generated/component.ts";
|
|
1921
|
+
+import type { ComponentApi as Google } from "../components/google/_generated/component.ts";
|
|
1922
|
+
+import coreSchema from "../component/schema.ts";
|
|
1923
|
+
+import googleSchema from "../components/google/schema.ts";
|
|
1924
|
+
+import { mutation } from "../component/_generated/server.ts";
|
|
1925
|
+
+import { setupLegacyGoogleMigration } from "./legacyMigration.ts";
|
|
1926
|
+
+
|
|
1927
|
+
+const components = componentsGeneric() as unknown as {
|
|
1928
|
+
+ auth: Core<"auth">;
|
|
1929
|
+
+ authGoogle: Google<"authGoogle">;
|
|
1930
|
+
+};
|
|
1931
|
+
+const seed = mutation({
|
|
1932
|
+
+ args: {},
|
|
1933
|
+
+ returns: v.null(),
|
|
1934
|
+
+ handler: async (ctx) => {
|
|
1935
|
+
+ for (let i = 0; i < 205; i++)
|
|
1936
|
+
+ await ctx.db.insert("accounts", {
|
|
1937
|
+
+ provider: "google",
|
|
1938
|
+
+ providerAccountId: `g${i}`,
|
|
1939
|
+
+ userId: `u${i}`,
|
|
1940
|
+
+ });
|
|
1941
|
+
+ await ctx.db.insert("identityErasure", {
|
|
1942
|
+
+ digest: "a".repeat(64),
|
|
1943
|
+
+ cutoff: 42,
|
|
1944
|
+
+ });
|
|
1945
|
+
+ await ctx.db.insert("erasedUsers", { userId: "u1", requestedAt: 55 });
|
|
1946
|
+
+ return null;
|
|
1947
|
+
+ },
|
|
1948
|
+
+});
|
|
1949
|
+
+const seedRef = (
|
|
1950
|
+
+ componentsGeneric() as unknown as { auth: { seed: { seed: any } } }
|
|
1951
|
+
+).auth.seed.seed;
|
|
1952
|
+
+const app = {
|
|
1953
|
+
+ seed: internalMutationGeneric({
|
|
1954
|
+
+ args: {},
|
|
1955
|
+
+ handler: async (ctx) => ctx.runMutation(seedRef, {}),
|
|
1956
|
+
+ }),
|
|
1957
|
+
+ step: setupLegacyGoogleMigration(components.auth, components.authGoogle),
|
|
1958
|
+
+ lookup: internalMutationGeneric({
|
|
1959
|
+
+ args: { id: v.string() },
|
|
1960
|
+
+ handler: async (ctx, { id }) =>
|
|
1961
|
+
+ ctx.runQuery(components.authGoogle.provider.getUserIdByAccount, {
|
|
1962
|
+
+ providerAccountId: id,
|
|
1963
|
+
+ }),
|
|
1964
|
+
+ }),
|
|
1965
|
+
+ conflict: internalMutationGeneric({
|
|
1966
|
+
+ args: {},
|
|
1967
|
+
+ handler: async (ctx) =>
|
|
1968
|
+
+ ctx.runMutation(components.authGoogle.migration.importAccounts, {
|
|
1969
|
+
+ rows: [{ providerAccountId: "g0", userId: "wrong" }],
|
|
1970
|
+
+ }),
|
|
1971
|
+
+ }),
|
|
1972
|
+
+};
|
|
1973
|
+
+const rootModules = {
|
|
1974
|
+
+ "./_generated/api.ts": async () => ({}),
|
|
1975
|
+
+ "./app.ts": async () => app,
|
|
1976
|
+
+};
|
|
1977
|
+
+const seedFn = makeFunctionReference<"mutation", {}, null>("app:seed");
|
|
1978
|
+
+const stepFn = makeFunctionReference<
|
|
1979
|
+
+ "mutation",
|
|
1980
|
+
+ {},
|
|
1981
|
+
+ { phase: string; count: number; complete: boolean }
|
|
1982
|
+
+>("app:step");
|
|
1983
|
+
+const lookupFn = makeFunctionReference<
|
|
1984
|
+
+ "mutation",
|
|
1985
|
+
+ { id: string },
|
|
1986
|
+
+ string | null
|
|
1987
|
+
+>("app:lookup");
|
|
1988
|
+
+const conflictFn = makeFunctionReference<"mutation", {}, null>("app:conflict");
|
|
1989
|
+
+function setup() {
|
|
1990
|
+
+ const t = convexTest(undefined, rootModules);
|
|
1991
|
+
+ t.registerComponent("auth", coreSchema, {
|
|
1992
|
+
+ ...import.meta.glob("../component/**/*.ts"),
|
|
1993
|
+
+ "../component/seed.ts": async () => ({ seed }),
|
|
1994
|
+
+ });
|
|
1995
|
+
+ t.registerComponent(
|
|
1996
|
+
+ "authGoogle",
|
|
1997
|
+
+ googleSchema,
|
|
1998
|
+
+ import.meta.glob("../components/google/**/*.ts"),
|
|
1999
|
+
+ );
|
|
2000
|
+
+ return t;
|
|
2001
|
+
+}
|
|
2002
|
+
+
|
|
2003
|
+
+test("resumes batches, copies user IDs and fences before opening", async () => {
|
|
2004
|
+
+ const t = setup();
|
|
2005
|
+
+ await t.mutation(seedFn, {});
|
|
2006
|
+
+ const phases: string[] = [];
|
|
2007
|
+
+ for (let i = 0; i < 12; i++) {
|
|
2008
|
+
+ const step = await t.mutation(stepFn, {});
|
|
2009
|
+
+ phases.push(step.phase);
|
|
2010
|
+
+ if (step.complete) break;
|
|
2011
|
+
+ }
|
|
2012
|
+
+ expect(phases).toEqual([
|
|
2013
|
+
+ "cutoffs",
|
|
2014
|
+
+ "users",
|
|
2015
|
+
+ "accounts",
|
|
2016
|
+
+ "accounts",
|
|
2017
|
+
+ "accounts",
|
|
2018
|
+
+ "complete",
|
|
2019
|
+
+ ]);
|
|
2020
|
+
+ expect(await t.mutation(lookupFn, { id: "g0" })).toBe("u0");
|
|
2021
|
+
+ expect(await t.mutation(lookupFn, { id: "g204" })).toBe("u204");
|
|
2022
|
+
+ await expect(t.mutation(lookupFn, { id: "g1" })).rejects.toThrow();
|
|
2023
|
+
+});
|
|
2024
|
+
+
|
|
2025
|
+
+test("target conflict rolls back cursor and cannot open migration", async () => {
|
|
2026
|
+
+ const t = setup();
|
|
2027
|
+
+ await t.mutation(seedFn, {});
|
|
2028
|
+
+ await t.mutation(conflictFn, {});
|
|
2029
|
+
+ expect((await t.mutation(stepFn, {})).phase).toBe("cutoffs");
|
|
2030
|
+
+ expect((await t.mutation(stepFn, {})).phase).toBe("users");
|
|
2031
|
+
+ await expect(t.mutation(stepFn, {})).rejects.toThrow("Mapping conflict");
|
|
2032
|
+
+ await expect(t.mutation(stepFn, {})).rejects.toThrow("Mapping conflict");
|
|
2033
|
+
+});
|
|
2034
|
+
--- /dev/null
|
|
2035
|
+
+++ b/src/server/legacyMigration.ts
|
|
2036
|
+
@@ -0,0 +1,60 @@
|
|
2037
|
+
+import { internalMutationGeneric } from "convex/server";
|
|
2038
|
+
+import { v } from "convex/values";
|
|
2039
|
+
+import type { ComponentApi as Core } from "../component/_generated/component.ts";
|
|
2040
|
+
+import type { ComponentApi as Google } from "../components/google/_generated/component.ts";
|
|
2041
|
+
+
|
|
2042
|
+
+/**
|
|
2043
|
+
+ * Export the returned function as an app-internal mutation. Run repeatedly until
|
|
2044
|
+
+ * `complete` is true. All component calls share one transaction: a conflict or
|
|
2045
|
+
+ * failed target import rolls back the core cursor, including its final gate.
|
|
2046
|
+
+ * Never call `_internal_dangerous_advance` independently.
|
|
2047
|
+
+ */
|
|
2048
|
+
+export function setupLegacyGoogleMigration(core: Core, google: Google) {
|
|
2049
|
+
+ return internalMutationGeneric({
|
|
2050
|
+
+ args: {},
|
|
2051
|
+
+ returns: v.object({
|
|
2052
|
+
+ phase: v.string(),
|
|
2053
|
+
+ count: v.number(),
|
|
2054
|
+
+ complete: v.boolean(),
|
|
2055
|
+
+ }),
|
|
2056
|
+
+ handler: async (ctx) => {
|
|
2057
|
+
+ await ctx.runMutation(google.migration._internal_dangerous_lock, {});
|
|
2058
|
+
+ const batch = await ctx.runMutation(
|
|
2059
|
+
+ core.migration._internal_dangerous_advance,
|
|
2060
|
+
+ {},
|
|
2061
|
+
+ );
|
|
2062
|
+
+ if (batch.phase === "cutoffs") {
|
|
2063
|
+
+ const rows = batch.rows.map((row) => {
|
|
2064
|
+
+ if (!("digest" in row)) throw new Error("Invalid cutoff batch");
|
|
2065
|
+
+ return row;
|
|
2066
|
+
+ });
|
|
2067
|
+
+ await ctx.runMutation(google.migration.importCutoffs, { rows });
|
|
2068
|
+
+ } else if (batch.phase === "users") {
|
|
2069
|
+
+ const rows = batch.rows.map((row) => {
|
|
2070
|
+
+ if (!("requestedAt" in row))
|
|
2071
|
+
+ throw new Error("Invalid user fence batch");
|
|
2072
|
+
+ return row;
|
|
2073
|
+
+ });
|
|
2074
|
+
+ await ctx.runMutation(google.migration.importErasedUsers, { rows });
|
|
2075
|
+
+ } else if (batch.phase === "accounts") {
|
|
2076
|
+
+ const rows = batch.rows.map((row) => {
|
|
2077
|
+
+ if (!("providerAccountId" in row) || row.provider !== "google")
|
|
2078
|
+
+ throw new Error("Invalid Google account batch");
|
|
2079
|
+
+ return {
|
|
2080
|
+
+ providerAccountId: row.providerAccountId,
|
|
2081
|
+
+ userId: row.userId,
|
|
2082
|
+
+ };
|
|
2083
|
+
+ });
|
|
2084
|
+
+ await ctx.runMutation(google.migration.importAccounts, { rows });
|
|
2085
|
+
+ } else if (batch.rows.length)
|
|
2086
|
+
+ throw new Error("Unexpected migration rows");
|
|
2087
|
+
+ if (batch.phase === "complete")
|
|
2088
|
+
+ await ctx.runMutation(google.migration._internal_dangerous_unlock, {});
|
|
2089
|
+
+ return {
|
|
2090
|
+
+ phase: batch.phase,
|
|
2091
|
+
+ count: batch.rows.length,
|
|
2092
|
+
+ complete: batch.phase === "complete",
|
|
2093
|
+
+ };
|
|
2094
|
+
+ },
|
|
2095
|
+
+ });
|
|
2096
|
+
+}
|