1import { assertCliScope } from "../cli/scope";2import { mutation } from "../_generated/server";3import { ConvexError, v } from "convex/values";4import { internal } from "../_generated/api";5 6import { resolveProjectByApiKeyFromDb } from "../projects/helpers";7import {8 bindOneTimePurchaseToUser,9 rebindOneTimePurchaseToUser,10} from "../purchases/binding";11import { recordBindIssue } from "../purchaseIssues/internal";12import {13 bindSubscriptionToUserOutcome,14 findSubscriptionByToken,15 rebindSubscriptionToUserHandler,16 type BindOutcome,17} from "./internal";18import { isValidSubscriptionUserId } from "./limits";19import { hmacSha256Hex, sha256Hex } from "../utils/sha256";20import { randomHex } from "../utils/helpers";21import { bindReasonValidator } from "../utils/validation";22 23const bindArgs = {24 apiKey: v.string(),25 purchaseToken: v.string(),26 userId: v.string(),27 // Labels a secret-key bind issue; never read otherwise.28 correlationId: v.optional(v.string()),29};30 31function isBound(outcome: BindOutcome): boolean {32 return outcome.reason === "bound" || outcome.reason === "already_bound";33}34 35// An authenticated app backend chooses the owner; store evidence alone cannot.36export const bindUser = mutation({37 args: bindArgs,38 returns: v.object({39 ok: v.boolean(),40 bound: v.boolean(),41 reason: v.optional(bindReasonValidator),42 }),43 handler: async (ctx, args) => {44 await assertCliScope(ctx, "write");45 const resolved = await resolveProjectByApiKeyFromDb(46 ctx,47 args.apiKey,48 "admin",49 );50 if (!resolved) return { ok: false, bound: false };51 const { project } = resolved;52 if (!isValidSubscriptionUserId(args.userId)) {53 throw new ConvexError(54 "userId must be nonblank and at most 256 characters",55 );56 }57 58 const sub = await findSubscriptionByToken(59 ctx,60 project._id,61 args.purchaseToken,62 );63 // Amazon store identity is linked by the authenticated developer backend.64 let outcome: BindOutcome =65 sub?.store === "amazon"66 ? { reason: "not_bindable" }67 : await bindSubscriptionToUserOutcome(ctx, {68 projectId: project._id,69 purchaseToken: args.purchaseToken,70 userId: args.userId,71 });72 if (outcome.reason === "not_found") {73 outcome = await bindOneTimePurchaseToUser(74 ctx,75 project,76 args.purchaseToken,77 args.userId,78 );79 }80 await recordBindIssue(ctx, project._id, outcome, {81 evidence: args.purchaseToken,82 userId: args.userId,83 correlationId: args.correlationId,84 });85 return { ok: true, bound: isBound(outcome), reason: outcome.reason };86 },87});88 89// Commerce Protocol bindPurchase: same idempotent, never-move binding as90// bindUser, but server-role only. The protocol says a shipped app must not91// reach an account mutation, and the edge prefix check alone cannot classify92// a legacy no-prefix key, so the admin access is asserted here in Convex where93// the stored key type is authoritative. Apple and Google stay subscription-only94// here: a bound one-time purchase would have to appear in Commerce95// entitlements, which IAPKit cannot recheck with those stores (SPEC §4.3).96export const bindUserAsServer = mutation({97 args: bindArgs,98 returns: v.object({ ok: v.boolean(), bound: v.boolean() }),99 handler: async (ctx, args) => {100 await assertCliScope(ctx, "write");101 // resolveProjectByApiKeyFromDb throws INSUFFICIENT_SCOPE for a valid but102 // under-scoped (publishable/legacy) key, and returns null for an unknown103 // or inactive one. The two must map to different protocol codes: an104 // unknown key is UNAUTHORIZED (INVALID_API_KEY), only a real-but-wrong-role105 // key is FORBIDDEN.106 const resolved = await resolveProjectByApiKeyFromDb(107 ctx,108 args.apiKey,109 "admin",110 );111 if (!resolved) {112 throw new ConvexError({113 code: "INVALID_API_KEY",114 message: "API key is invalid or inactive",115 });116 }117 118 const outcome = await bindSubscriptionToUserOutcome(ctx, {119 projectId: resolved.project._id,120 purchaseToken: args.purchaseToken,121 userId: args.userId,122 });123 await recordBindIssue(ctx, resolved.project._id, outcome, {124 evidence: args.purchaseToken,125 userId: args.userId,126 correlationId: args.correlationId,127 });128 129 return { ok: true, bound: isBound(outcome) };130 },131});132 133// Recovery for a purchase bound to the wrong user. `bindUser` deliberately134// refuses to move an existing binding — token possession is not proof of135// ownership — so without this an operator has no way to correct one.136// Secret key only: this reassigns who owns a purchase.137export const rebindUser = mutation({138 args: {139 apiKey: v.string(),140 purchaseToken: v.string(),141 userId: v.string(),142 },143 returns: v.object({144 ok: v.boolean(),145 rebound: v.boolean(),146 // False when the binding moved but no entitlement events could be147 // attributed, so the caller knows the developer backend still believes the148 // previous user owns the purchase.149 notified: v.boolean(),150 }),151 handler: async (ctx, args) => {152 await assertCliScope(ctx, "write");153 const resolved = await resolveProjectByApiKeyFromDb(154 ctx,155 args.apiKey,156 "admin",157 );158 const project = resolved?.project ?? null;159 if (!project) return { ok: false, rebound: false, notified: false };160 161 const result = await rebindSubscriptionToUserHandler(ctx, {162 projectId: project._id,163 purchaseToken: args.purchaseToken,164 userId: args.userId,165 });166 if (result) {167 return { ok: true, rebound: true, notified: result.notified };168 }169 170 // One-time purchases emit no commerce events, so a move is never notified.171 const oneTime = await rebindOneTimePurchaseToUser(172 ctx,173 project,174 args.purchaseToken,175 args.userId,176 );177 return {178 ok: true,179 rebound: oneTime !== null,180 notified: oneTime?.moved !== true,181 };182 },183});184 185export const requestUserErasure = mutation({186 args: { apiKey: v.string(), userId: v.string() },187 returns: v.object({188 ok: v.boolean(),189 jobId: v.id("subscriptionUserErasureJobs"),190 status: v.union(191 v.literal("queued"),192 v.literal("running"),193 v.literal("completed"),194 ),195 }),196 handler: async (ctx, args) => {197 await assertCliScope(ctx, "write");198 const resolved = await resolveProjectByApiKeyFromDb(199 ctx,200 args.apiKey,201 "admin",202 );203 if (!resolved) {204 throw new ConvexError({205 code: "INVALID_API_KEY",206 message: "API key is invalid or inactive",207 });208 }209 if (!isValidSubscriptionUserId(args.userId)) {210 throw new ConvexError({211 code: "INVALID_INPUT",212 message: "userId is invalid",213 });214 }215 216 const hashKey = resolved.project.userErasureHashKey ?? randomHex();217 if (resolved.project.userErasureHashKey === undefined) {218 await ctx.db.patch(resolved.project._id, { userErasureHashKey: hashKey });219 }220 const userIdHash = await hmacSha256Hex(hashKey, args.userId);221 let existing = await ctx.db222 .query("subscriptionUserErasureJobs")223 .withIndex("by_project_and_user_hash", (q) =>224 q.eq("projectId", resolved.project._id).eq("userIdHash", userIdHash),225 )226 .unique();227 if (!existing) {228 const legacyHash = await sha256Hex(args.userId);229 existing = await ctx.db230 .query("subscriptionUserErasureJobs")231 .withIndex("by_project_and_user_hash", (q) =>232 q.eq("projectId", resolved.project._id).eq("userIdHash", legacyHash),233 )234 .unique();235 if (existing) {236 await ctx.db.patch(existing._id, { userIdHash });237 }238 }239 if (existing) {240 return { ok: true, jobId: existing._id, status: existing.status };241 }242 243 const now = Date.now();244 const jobId = await ctx.db.insert("subscriptionUserErasureJobs", {245 projectId: resolved.project._id,246 userId: args.userId,247 userIdHash,248 status: "queued",249 subscriptionsErased: 0,250 commerceEventsErased: 0,251 createdAt: now,252 updatedAt: now,253 });254 await ctx.scheduler.runAfter(255 0,256 internal.subscriptions.internal.drainSubscriptionUserErasureJob,257 { jobId },258 );259 return { ok: true, jobId, status: "queued" as const };260 },261});262