create-disposabl-app 0.17.5 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +4 -0
  2. package/dist/disposabl.js +43 -10
  3. package/dist/index.js +64 -18
  4. package/dist/templates/default/apps/mobile/README.md +40 -0
  5. package/dist/templates/default/apps/mobile/app.config.js +46 -2
  6. package/dist/templates/default/apps/mobile/package.json +7 -1
  7. package/dist/templates/default/apps/mobile/plugins/with-android-signing.js +23 -1
  8. package/dist/templates/default/apps/mobile/scripts/fresh-android.mjs +24 -0
  9. package/dist/templates/default/apps/mobile/scripts/play-aab.mjs +176 -0
  10. package/dist/templates/default/apps/mobile/scripts/verify-play-aab.mjs +77 -0
  11. package/dist/templates/default/bun.lock +12 -3
  12. package/dist/templates/default/bunfig.toml +1 -0
  13. package/dist/templates/default/package.json +6 -2
  14. package/dist/templates/default/packages/backend/convex/files/guard.ts +2 -0
  15. package/dist/templates/default/packages/backend/convex/http.ts +11 -1
  16. package/dist/templates/default/packages/backend/convex/schema.ts +10 -0
  17. package/dist/templates/default/packages/backend/convex/telemetry.ts +12 -16
  18. package/dist/templates/default/packages/cli/build.ts +4 -0
  19. package/dist/templates/default/packages/cli/package.json +2 -1
  20. package/dist/templates/default/packages/cli/telemetry.ts +40 -3
  21. package/dist/templates/default/packages/disposabl-kit/PAYMENTS.md +2 -0
  22. package/dist/templates/default/packages/disposabl-kit/client/components/account-deletion.tsx +111 -0
  23. package/dist/templates/default/packages/disposabl-kit/client/components/consent-identity.tsx +50 -0
  24. package/dist/templates/default/packages/disposabl-kit/client/components/legal-page.tsx +12 -1
  25. package/dist/templates/default/packages/disposabl-kit/client/lib/telemetry-lease.ts +200 -0
  26. package/dist/templates/default/packages/disposabl-kit/client/lib/telemetry.ts +8 -1
  27. package/dist/templates/default/packages/disposabl-kit/client/routes/consent.tsx +23 -1
  28. package/dist/templates/default/packages/disposabl-kit/client/routes/legal/delete-account.tsx +6 -1
  29. package/dist/templates/default/packages/disposabl-kit/client/routes/legal/support.tsx +33 -0
  30. package/dist/templates/default/packages/disposabl-kit/client/routes/pricing.tsx +13 -0
  31. package/dist/templates/default/packages/disposabl-kit/client/routes/route.tsx +19 -2
  32. package/dist/templates/default/packages/disposabl-kit/client/vite.config.ts +1 -0
  33. package/dist/templates/default/packages/disposabl-kit/legal/README.md +1 -1
  34. package/dist/templates/default/packages/disposabl-kit/legal/config.ts +32 -4
  35. package/dist/templates/default/packages/disposabl-kit/legal/index.ts +2 -2
  36. package/dist/templates/default/packages/disposabl-kit/legal/publisher.ts +6 -0
  37. package/dist/templates/default/packages/disposabl-kit/mobile/billing/account-billing.tsx +13 -9
  38. package/dist/templates/default/packages/disposabl-kit/mobile/billing/paywall.ts +28 -4
  39. package/dist/templates/default/packages/disposabl-kit/mobile/billing/policy.ts +31 -14
  40. package/dist/templates/default/packages/disposabl-kit/mobile/billing/web-checkout.ts +45 -34
  41. package/dist/templates/default/packages/disposabl-kit/mobile/components/settings-links.tsx +14 -0
  42. package/dist/templates/default/packages/disposabl-kit/mobile/expo-plugin.cjs +3 -0
  43. package/dist/templates/default/packages/disposabl-kit/mobile/index.ts +4 -0
  44. package/dist/templates/default/packages/disposabl-kit/mobile/layout.tsx +55 -8
  45. package/dist/templates/default/packages/disposabl-kit/server/billing-functions.ts +147 -124
  46. package/dist/templates/default/packages/disposabl-kit/server/billing-handoff.ts +113 -95
  47. package/dist/templates/default/packages/disposabl-kit/server/files-functions.ts +70 -54
  48. package/dist/templates/default/packages/disposabl-kit/server/http.ts +49 -21
  49. package/dist/templates/default/packages/disposabl-kit/server/lib/platform-spec.ts +25 -1
  50. package/dist/templates/default/packages/disposabl-kit/server/lib/telemetry.ts +375 -69
  51. package/dist/templates/default/packages/disposabl-kit/server/release/clients.mjs +28 -1
  52. package/dist/templates/default/packages/disposabl-kit/server/release/verify-metadata.mjs +64 -0
  53. package/dist/templates/default/packages/sdk/README.md +2 -0
  54. package/dist/templates/default/packages/sdk/build.ts +8 -0
  55. package/dist/templates/default/packages/sdk/package.json +3 -2
  56. package/dist/templates/default/packages/sdk/src/analytics.ts +7 -2
  57. package/dist/templates/default/packages/skill/SKILL.md +4 -2
  58. package/dist/templates/default/packages/skill/references/store-submissions.md +25 -0
  59. package/dist/templates/default/packages/tests/README.md +28 -1
  60. package/dist/templates/default/packages/tests/account-deletion-ui.test.ts +21 -0
  61. package/dist/templates/default/packages/tests/auth-email-setup.test.ts +45 -0
  62. package/dist/templates/default/packages/tests/components/account-deletion.test.mjs +82 -0
  63. package/dist/templates/default/packages/tests/components/consent-identity.test.mjs +175 -0
  64. package/dist/templates/default/packages/tests/components/mobile-deletion-link.test.mjs +40 -0
  65. package/dist/templates/default/packages/tests/components/mobile-theme.test.mjs +56 -3
  66. package/dist/templates/default/packages/tests/components/pricing-identity.test.mjs +113 -0
  67. package/dist/templates/default/packages/tests/components/support-page.test.mjs +36 -0
  68. package/dist/templates/default/packages/tests/consent-identity.test.ts +13 -0
  69. package/dist/templates/default/packages/tests/desktop-macos-release.test.ts +153 -145
  70. package/dist/templates/default/packages/tests/flows/legal.e2e.ts +40 -3
  71. package/dist/templates/default/packages/tests/helpers/auth-email-setup/probe.test.mjs +44 -0
  72. package/dist/templates/default/packages/tests/helpers/mobile-simulator/preflight.py +80 -0
  73. package/dist/templates/default/packages/tests/helpers/mobile-simulator/test_preflight.py +57 -0
  74. package/dist/templates/default/packages/tests/mobile-android-e2e-network.test.ts +81 -1
  75. package/dist/templates/default/packages/tests/mobile-android-signing.test.ts +52 -0
  76. package/dist/templates/default/packages/tests/mobile-deletion-link.test.ts +21 -0
  77. package/dist/templates/default/packages/tests/mobile-ios-reachability-pin.test.ts +84 -0
  78. package/dist/templates/default/packages/tests/mobile-simulator-preflight.test.ts +16 -0
  79. package/dist/templates/default/packages/tests/native-billing.test.ts +288 -0
  80. package/dist/templates/default/packages/tests/pricing-identity.test.ts +13 -0
  81. package/dist/templates/default/packages/tests/sdk-analytics.test.ts +28 -2
  82. package/dist/templates/default/packages/tests/support-page.test.ts +13 -0
  83. package/dist/templates/default/packages/tests/telemetry.test.ts +389 -18
  84. package/dist/templates/default/packages/tests/ui-telemetry-lease.test.ts +346 -0
  85. package/dist/templates/default/patches/convex-mcp-account-erasure-alpha7.patch +466 -0
  86. package/dist/templates/default/vendor/README.md +61 -1
  87. package/dist/templates/default/vendor/convex-auth-040d8e36-disposabl.1.patch +890 -0
  88. package/dist/templates/default/vendor/convex-auth-040d8e36-disposabl.1.tgz +0 -0
  89. package/dist/templates/default/vendor/convex-auth-040d8e36-disposabl.2.patch +1060 -0
  90. package/dist/templates/default/vendor/convex-auth-040d8e36-disposabl.2.tgz +0 -0
  91. package/dist/templates/default/vendor/convex-auth-437831bd-disposabl.4.tgz +0 -0
  92. package/dist/templates/default/vendor/convex-auth-437831bd-disposabl.5.tgz +0 -0
  93. package/dist/templates/default/vendor/convex-auth-437831bd-disposabl.6.tgz +0 -0
  94. package/dist/templates/default/vendor/convex-auth-437831bd-disposabl.7.tgz +0 -0
  95. package/dist/templates/default/vendor/convex-auth-437831bd-disposabl.8.tgz +0 -0
  96. package/dist/templates/default/vendor/convex-auth-core-erasure-disposabl.6.patch +115 -0
  97. package/dist/templates/default/vendor/convex-auth-identity-cutoff-disposabl.7.patch +442 -0
  98. package/dist/templates/default/vendor/convex-auth-identity-erasure-disposabl.8.md +11 -0
  99. package/dist/templates/default/vendor/convex-auth-identity-erasure-disposabl.8.patch +78 -0
  100. package/dist/templates/default/vendor/convex-auth-marker-disposabl.4.patch +169 -0
  101. package/dist/templates/default/vendor/convex-auth-marker-password-disposabl.5.patch +126 -0
  102. package/dist/verify-metadata.mjs +64 -0
  103. package/package.json +3 -2
@@ -5,6 +5,9 @@ import {
5
5
  action,
6
6
  internalMutation,
7
7
  internalQuery,
8
+ type ActionCtx,
9
+ type MutationCtx,
10
+ type QueryCtx,
8
11
  } from "../../backend/convex/_generated/server";
9
12
  import { paymentsEnabled } from "../features";
10
13
  import { setupBilling } from "./billing-setup";
@@ -35,6 +38,11 @@ async function context(ctx: { auth: Auth }) {
35
38
  );
36
39
  }
37
40
 
41
+ export type BillingEligibility = (
42
+ ctx: ActionCtx | MutationCtx | QueryCtx,
43
+ userId: string,
44
+ ) => Promise<void>;
45
+
38
46
  const purchaseValidator = v.union(v.literal("monthly"), v.literal("topup"));
39
47
  const attemptArgs = {
40
48
  userId: v.string(),
@@ -62,46 +70,50 @@ const pendingRef = makeFunctionReference<"query", { userId: string }, boolean>(
62
70
 
63
71
  // Persist before the provider call. A crash or lost response requires operator
64
72
  // reconciliation; an automatic retry could charge the same customer twice.
65
- export const beginAttempt = internalMutation({
66
- args: attemptArgs,
67
- returns: v.union(
68
- v.string(),
69
- v.null(),
70
- v.object({ retryAllowed: v.literal(true) }),
71
- ),
72
- handler: async (ctx, args) => {
73
- const same = await ctx.db
74
- .query("billingAttempts")
75
- .withIndex("by_userId_requestId", (q) =>
76
- q.eq("userId", args.userId).eq("requestId", args.requestId),
77
- )
78
- .unique();
79
- if (same) {
80
- if (same.purchase !== args.purchase)
73
+ export const createBeginAttempt = (eligibility?: BillingEligibility) =>
74
+ internalMutation({
75
+ args: attemptArgs,
76
+ returns: v.union(
77
+ v.string(),
78
+ v.null(),
79
+ v.object({ retryAllowed: v.literal(true) }),
80
+ ),
81
+ handler: async (ctx, args) => {
82
+ await eligibility?.(ctx, args.userId);
83
+ const same = await ctx.db
84
+ .query("billingAttempts")
85
+ .withIndex("by_userId_requestId", (q) =>
86
+ q.eq("userId", args.userId).eq("requestId", args.requestId),
87
+ )
88
+ .unique();
89
+ if (same) {
90
+ if (same.purchase !== args.purchase)
91
+ throw new Error("A previous checkout needs review.");
92
+ if (same.resolvedAt !== undefined)
93
+ return { retryAllowed: true as const };
94
+ if (!same.url) throw new Error("A previous checkout needs review.");
95
+ return same.url;
96
+ }
97
+ const prior = await ctx.db
98
+ .query("billingAttempts")
99
+ .withIndex("by_userId_purchase_resolvedAt_url", (q) => {
100
+ const open = q
101
+ .eq("userId", args.userId)
102
+ .eq("purchase", args.purchase)
103
+ .eq("resolvedAt", undefined);
104
+ // A returned monthly link remains payable until the provider closes it.
105
+ return args.purchase === "monthly" ? open : open.eq("url", undefined);
106
+ })
107
+ .first();
108
+ if (prior) {
109
+ if (args.purchase === "monthly" && prior.url) return prior.url;
81
110
  throw new Error("A previous checkout needs review.");
82
- if (same.resolvedAt !== undefined) return { retryAllowed: true as const };
83
- if (!same.url) throw new Error("A previous checkout needs review.");
84
- return same.url;
85
- }
86
- const prior = await ctx.db
87
- .query("billingAttempts")
88
- .withIndex("by_userId_purchase_resolvedAt_url", (q) => {
89
- const open = q
90
- .eq("userId", args.userId)
91
- .eq("purchase", args.purchase)
92
- .eq("resolvedAt", undefined);
93
- // A returned monthly link remains payable until the provider closes it.
94
- return args.purchase === "monthly" ? open : open.eq("url", undefined);
95
- })
96
- .first();
97
- if (prior) {
98
- if (args.purchase === "monthly" && prior.url) return prior.url;
99
- throw new Error("A previous checkout needs review.");
100
- }
101
- await ctx.db.insert("billingAttempts", args);
102
- return null;
103
- },
104
- });
111
+ }
112
+ await ctx.db.insert("billingAttempts", args);
113
+ return null;
114
+ },
115
+ });
116
+ export const beginAttempt = createBeginAttempt();
105
117
  export const finishAttempt = internalMutation({
106
118
  args: { ...attemptArgs, url: v.string() },
107
119
  returns: v.null(),
@@ -204,96 +216,107 @@ const monthlyPendingRef = makeFunctionReference<
204
216
  boolean
205
217
  >("billing:hasPendingMonthlyAttempt");
206
218
 
207
- export const snapshot = action({
208
- args: {},
209
- returns: v.object({
210
- balance: v.union(v.number(), v.null()),
211
- hasMonthlyPlan: v.union(v.boolean(), v.null()),
212
- nativeSubscriptionsEnabled: v.boolean(),
213
- nativeTopupRoutes: v.array(
214
- v.object({ app: v.string(), store: v.string(), product: v.string() }),
215
- ),
216
- mobileWebCheckoutEnabled: v.boolean(),
217
- checkoutNeedsReview: v.boolean(),
218
- monthlyCheckoutPending: v.boolean(),
219
- customerId: v.string(),
220
- }),
221
- handler: async (ctx) => {
222
- const { key, userId } = await context(ctx);
223
- try {
224
- const customer = await billingRequest(key, "customers.get_or_create", {
225
- customer_id: userId,
226
- });
227
- return {
228
- balance: balanceFromCustomer(customer),
229
- hasMonthlyPlan: monthlyPlanFromCustomer(customer),
230
- nativeSubscriptionsEnabled:
231
- process.env.REVENUECAT_SYNC_ENABLED === "true",
232
- nativeTopupRoutes: nativeTopupRoutes(paymentsEnabled, process.env),
233
- mobileWebCheckoutEnabled: mobileWebCheckoutConfigured(
234
- paymentsEnabled,
235
- process.env,
236
- ),
237
- checkoutNeedsReview: await ctx.runQuery(pendingRef, { userId }),
238
- monthlyCheckoutPending: await ctx.runQuery(monthlyPendingRef, {
239
- userId,
240
- }),
241
- customerId: userId,
242
- };
243
- } catch {
244
- throw new Error("Billing is temporarily unavailable.");
245
- }
246
- },
247
- });
219
+ export const createSnapshot = (eligibility?: BillingEligibility) =>
220
+ action({
221
+ args: {},
222
+ returns: v.object({
223
+ balance: v.union(v.number(), v.null()),
224
+ hasMonthlyPlan: v.union(v.boolean(), v.null()),
225
+ nativeSubscriptionsEnabled: v.boolean(),
226
+ nativeTopupRoutes: v.array(
227
+ v.object({ app: v.string(), store: v.string(), product: v.string() }),
228
+ ),
229
+ mobileWebCheckoutEnabled: v.boolean(),
230
+ checkoutNeedsReview: v.boolean(),
231
+ monthlyCheckoutPending: v.boolean(),
232
+ customerId: v.string(),
233
+ }),
234
+ handler: async (ctx) => {
235
+ const { key, userId } = await context(ctx);
236
+ await eligibility?.(ctx, userId);
237
+ try {
238
+ const customer = await billingRequest(key, "customers.get_or_create", {
239
+ customer_id: userId,
240
+ });
241
+ return {
242
+ balance: balanceFromCustomer(customer),
243
+ hasMonthlyPlan: monthlyPlanFromCustomer(customer),
244
+ nativeSubscriptionsEnabled:
245
+ process.env.REVENUECAT_SYNC_ENABLED === "true",
246
+ nativeTopupRoutes: nativeTopupRoutes(paymentsEnabled, process.env),
247
+ mobileWebCheckoutEnabled: mobileWebCheckoutConfigured(
248
+ paymentsEnabled,
249
+ process.env,
250
+ ),
251
+ checkoutNeedsReview: await ctx.runQuery(pendingRef, { userId }),
252
+ monthlyCheckoutPending: await ctx.runQuery(monthlyPendingRef, {
253
+ userId,
254
+ }),
255
+ customerId: userId,
256
+ };
257
+ } catch {
258
+ throw new Error("Billing is temporarily unavailable.");
259
+ }
260
+ },
261
+ });
248
262
 
249
- export const checkout = action({
250
- args: { purchase: purchaseValidator, requestId: v.string() },
251
- returns: v.object({
252
- url: v.union(v.string(), v.null()),
253
- retryAllowed: v.optional(v.literal(true)),
254
- }),
255
- handler: async (ctx, { purchase, requestId }) => {
256
- if (!/^[0-9a-f-]{36}$/.test(requestId))
257
- throw new Error("Invalid checkout request.");
258
- const { key, userId, returnUrl } = await context(ctx);
259
- if (purchase === "monthly") {
260
- const customer = await billingRequest(key, "customers.get_or_create", {
261
- customer_id: userId,
263
+ export const snapshot = createSnapshot();
264
+ export const createCheckout = (eligibility?: BillingEligibility) =>
265
+ action({
266
+ args: { purchase: purchaseValidator, requestId: v.string() },
267
+ returns: v.object({
268
+ url: v.union(v.string(), v.null()),
269
+ retryAllowed: v.optional(v.literal(true)),
270
+ }),
271
+ handler: async (ctx, { purchase, requestId }) => {
272
+ if (!/^[0-9a-f-]{36}$/.test(requestId))
273
+ throw new Error("Invalid checkout request.");
274
+ const { key, userId, returnUrl } = await context(ctx);
275
+ await eligibility?.(ctx, userId);
276
+ if (purchase === "monthly") {
277
+ const customer = await billingRequest(key, "customers.get_or_create", {
278
+ customer_id: userId,
279
+ });
280
+ const active = monthlyPlanFromCustomer(customer);
281
+ if (active !== false)
282
+ throw new Error(
283
+ active
284
+ ? "You already have a monthly plan. Manage it where you purchased it."
285
+ : "Could not check your current plan. Please refresh and try again.",
286
+ );
287
+ }
288
+ const existing = await ctx.runMutation(beginRef, {
289
+ userId,
290
+ purchase,
291
+ requestId,
262
292
  });
263
- const active = monthlyPlanFromCustomer(customer);
264
- if (active !== false)
293
+ if (typeof existing === "string") {
294
+ await eligibility?.(ctx, userId);
295
+ return { url: existing };
296
+ }
297
+ if (existing?.retryAllowed)
298
+ return { url: null, retryAllowed: true as const };
299
+ await eligibility?.(ctx, userId);
300
+ try {
301
+ const result = await billingRequest(
302
+ key,
303
+ "billing.attach",
304
+ purchaseRequest(userId, purchase, returnUrl),
305
+ );
306
+ const url = checkoutUrl(result);
307
+ if (!url) throw new Error("Checkout response is unknown.");
308
+ await ctx.runMutation(finishRef, { userId, purchase, requestId, url });
309
+ await eligibility?.(ctx, userId);
310
+ return { url };
311
+ } catch {
265
312
  throw new Error(
266
- active
267
- ? "You already have a monthly plan. Manage it where you purchased it."
268
- : "Could not check your current plan. Please refresh and try again.",
313
+ "Checkout status is unknown. Contact support before retrying.",
269
314
  );
270
- }
271
- const existing = await ctx.runMutation(beginRef, {
272
- userId,
273
- purchase,
274
- requestId,
275
- });
276
- if (typeof existing === "string") return { url: existing };
277
- if (existing?.retryAllowed)
278
- return { url: null, retryAllowed: true as const };
279
- try {
280
- const result = await billingRequest(
281
- key,
282
- "billing.attach",
283
- purchaseRequest(userId, purchase, returnUrl),
284
- );
285
- const url = checkoutUrl(result);
286
- if (!url) throw new Error("Checkout response is unknown.");
287
- await ctx.runMutation(finishRef, { userId, purchase, requestId, url });
288
- return { url };
289
- } catch {
290
- throw new Error(
291
- "Checkout status is unknown. Contact support before retrying.",
292
- );
293
- }
294
- },
295
- });
315
+ }
316
+ },
317
+ });
296
318
 
319
+ export const checkout = createCheckout();
297
320
  export const portal = action({
298
321
  args: {},
299
322
  returns: v.object({ url: v.string() }),
@@ -16,6 +16,8 @@ import {
16
16
  exchangeBrowserSession,
17
17
  } from "./browser-session";
18
18
 
19
+ import type { BillingEligibility } from "./billing-functions";
20
+
19
21
  const ttl = 120_000;
20
22
  const returnTtl = 30 * 60_000;
21
23
  const allowedChannel = (channel: string | undefined) =>
@@ -57,105 +59,121 @@ async function lookup(ctx: QueryCtx, code: string) {
57
59
  throw invalid();
58
60
  return row;
59
61
  }
60
- export const create = mutation({
61
- args: {
62
- purchase: v.union(v.literal("monthly"), v.literal("topup")),
63
- returnChannel: v.optional(v.string()),
64
- },
65
- returns: v.object({ url: v.string(), userId: v.string() }),
66
- handler: async (ctx, { purchase, returnChannel }) => {
67
- const config = billingConfig(paymentsEnabled, process.env);
68
- if (!config || !mobileWebCheckoutConfigured(paymentsEnabled, process.env))
69
- throw new ConvexError("Website checkout is unavailable.");
70
- const userId = await getAuthUserId(ctx);
71
- const identity = await ctx.auth.getUserIdentity();
72
- if (!userId || !identity) throw invalid();
73
- const code = btoa(
74
- String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))),
75
- )
76
- .replaceAll("+", "-")
77
- .replaceAll("/", "_")
78
- .replaceAll("=", "");
79
- const hash = await digest(code);
80
- const channel = allowedChannel(returnChannel) ? returnChannel : undefined;
81
- const now = Date.now();
82
- await ctx.db.insert("billingHandoffs", {
83
- hash,
84
- userId,
85
- sessionId: identity.subject,
86
- purchase,
87
- ...(channel
88
- ? { returnChannel: channel, returnExpiresAt: now + returnTtl }
89
- : {}),
90
- expiresAt: now + ttl,
91
- });
92
- await ctx.scheduler.runAfter(channel ? returnTtl : ttl, cleanupRef, {
93
- hash,
94
- });
95
- const url = new URL("/billing-login", config.returnUrl);
96
- url.hash = code;
97
- return { url: url.href, userId };
98
- },
99
- });
100
- export const inspect = query({
101
- args: { code: v.string() },
102
- returns: v.union(v.null(), v.object({ name: v.union(v.string(), v.null()) })),
103
- handler: async (ctx, { code }) => {
104
- try {
105
- const row = await lookup(ctx, code);
106
- const session = await ctx.runQuery(components.auth.public.getSession, {
107
- sessionId: row.sessionId,
62
+ export const createHandoff = (eligibility?: BillingEligibility) =>
63
+ mutation({
64
+ args: {
65
+ purchase: v.union(v.literal("monthly"), v.literal("topup")),
66
+ returnChannel: v.optional(v.string()),
67
+ },
68
+ returns: v.object({ url: v.string(), userId: v.string() }),
69
+ handler: async (ctx, { purchase, returnChannel }) => {
70
+ const config = billingConfig(paymentsEnabled, process.env);
71
+ if (!config || !mobileWebCheckoutConfigured(paymentsEnabled, process.env))
72
+ throw new ConvexError("Website checkout is unavailable.");
73
+ const userId = await getAuthUserId(ctx);
74
+ const identity = await ctx.auth.getUserIdentity();
75
+ if (!userId || !identity) throw invalid();
76
+ await eligibility?.(ctx, userId);
77
+ const code = btoa(
78
+ String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))),
79
+ )
80
+ .replaceAll("+", "-")
81
+ .replaceAll("/", "_")
82
+ .replaceAll("=", "");
83
+ const hash = await digest(code);
84
+ const channel = allowedChannel(returnChannel) ? returnChannel : undefined;
85
+ const now = Date.now();
86
+ await ctx.db.insert("billingHandoffs", {
87
+ hash,
88
+ userId,
89
+ sessionId: identity.subject,
90
+ purchase,
91
+ ...(channel
92
+ ? { returnChannel: channel, returnExpiresAt: now + returnTtl }
93
+ : {}),
94
+ expiresAt: now + ttl,
108
95
  });
109
- if (session?.userId !== row.userId) return null;
110
- const email = await ctx.runQuery(
111
- components.authEmail.verifiedEmails.getPrimaryEmail,
112
- { userId: row.userId },
113
- );
114
- const username = await ctx.runQuery(
115
- components.authUsername.public.getUsername,
116
- { userId: row.userId },
96
+ await ctx.scheduler.runAfter(channel ? returnTtl : ttl, cleanupRef, {
97
+ hash,
98
+ });
99
+ const url = new URL("/billing-login", config.returnUrl);
100
+ url.hash = code;
101
+ return { url: url.href, userId };
102
+ },
103
+ });
104
+ export const create = createHandoff();
105
+ export const inspectHandoff = (eligibility?: BillingEligibility) =>
106
+ query({
107
+ args: { code: v.string() },
108
+ returns: v.union(
109
+ v.null(),
110
+ v.object({ name: v.union(v.string(), v.null()) }),
111
+ ),
112
+ handler: async (ctx, { code }) => {
113
+ try {
114
+ const row = await lookup(ctx, code);
115
+ await eligibility?.(ctx, row.userId);
116
+ const session = await ctx.runQuery(components.auth.public.getSession, {
117
+ sessionId: row.sessionId,
118
+ });
119
+ if (session?.userId !== row.userId) return null;
120
+ const email = await ctx.runQuery(
121
+ components.authEmail.verifiedEmails.getPrimaryEmail,
122
+ { userId: row.userId },
123
+ );
124
+ const username = await ctx.runQuery(
125
+ components.authUsername.public.getUsername,
126
+ { userId: row.userId },
127
+ );
128
+ const id = ctx.db.normalizeId("users", row.userId);
129
+ const user = id ? await ctx.db.get("users", id) : null;
130
+ return {
131
+ name:
132
+ email ?? user?.profile?.email ?? (username ? `@${username}` : null),
133
+ };
134
+ } catch {
135
+ return null;
136
+ }
137
+ },
138
+ });
139
+ export const inspect = inspectHandoff();
140
+ export const redeemHandoff = (eligibility?: BillingEligibility) =>
141
+ mutation({
142
+ args: { code: v.string() },
143
+ returns: v.object({
144
+ accessToken: v.string(),
145
+ refreshToken: v.string(),
146
+ refreshTokenExpiresAt: v.number(),
147
+ userId: v.string(),
148
+ purchase: v.union(v.literal("monthly"), v.literal("topup")),
149
+ expiresAt: v.number(),
150
+ returnClaim: v.union(v.string(), v.null()),
151
+ }),
152
+ handler: async (ctx, { code }) => {
153
+ const row = await lookup(ctx, code);
154
+ await eligibility?.(ctx, row.userId);
155
+ const tokens = await exchangeBrowserSession(
156
+ ctx,
157
+ row.sessionId,
158
+ row.userId,
117
159
  );
118
- const id = ctx.db.normalizeId("users", row.userId);
119
- const user = id ? await ctx.db.get("users", id) : null;
160
+ const browserSessionId = accessSessionId(tokens.accessToken);
161
+ const hasReturn =
162
+ !!row.returnChannel &&
163
+ allowedChannel(row.returnChannel) &&
164
+ !!browserSessionId;
165
+ if (hasReturn)
166
+ await ctx.db.patch("billingHandoffs", row._id, { browserSessionId });
167
+ else await ctx.db.delete("billingHandoffs", row._id);
120
168
  return {
121
- name:
122
- email ?? user?.profile?.email ?? (username ? `@${username}` : null),
169
+ ...tokens,
170
+ purchase: row.purchase ?? "monthly",
171
+ expiresAt: row.expiresAt,
172
+ returnClaim: hasReturn ? code : null,
123
173
  };
124
- } catch {
125
- return null;
126
- }
127
- },
128
- });
129
- export const redeem = mutation({
130
- args: { code: v.string() },
131
- returns: v.object({
132
- accessToken: v.string(),
133
- refreshToken: v.string(),
134
- refreshTokenExpiresAt: v.number(),
135
- userId: v.string(),
136
- purchase: v.union(v.literal("monthly"), v.literal("topup")),
137
- expiresAt: v.number(),
138
- returnClaim: v.union(v.string(), v.null()),
139
- }),
140
- handler: async (ctx, { code }) => {
141
- const row = await lookup(ctx, code);
142
- const tokens = await exchangeBrowserSession(ctx, row.sessionId, row.userId);
143
- const browserSessionId = accessSessionId(tokens.accessToken);
144
- const hasReturn =
145
- !!row.returnChannel &&
146
- allowedChannel(row.returnChannel) &&
147
- !!browserSessionId;
148
- if (hasReturn)
149
- await ctx.db.patch("billingHandoffs", row._id, { browserSessionId });
150
- else await ctx.db.delete("billingHandoffs", row._id);
151
- return {
152
- ...tokens,
153
- purchase: row.purchase ?? "monthly",
154
- expiresAt: row.expiresAt,
155
- returnClaim: hasReturn ? code : null,
156
- };
157
- },
158
- });
174
+ },
175
+ });
176
+ export const redeem = redeemHandoff();
159
177
  export const returnTarget = query({
160
178
  args: { code: v.string() },
161
179
  returns: v.union(