better-auth-streampay 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1947,6 +1947,54 @@ function requireWebhookInbox(registry) {
1947
1947
  }
1948
1948
  return inbox;
1949
1949
  }
1950
+ var LinkSubscriptionBody = z.object({
1951
+ referenceType: z.enum(["user", "organization", "custom"]),
1952
+ referenceId: z.string().min(1),
1953
+ plan: z.string().min(1).optional()
1954
+ }).strict();
1955
+ function buildSubscriptionLinkEndpoints(adminOptions, registry) {
1956
+ return {
1957
+ adminLinkSubscription: createAuthEndpoint(
1958
+ "/admin/streampay/subscriptions/:id/link",
1959
+ {
1960
+ method: "POST",
1961
+ body: LinkSubscriptionBody,
1962
+ use: [sessionMiddleware]
1963
+ },
1964
+ async (ctx) => {
1965
+ const actor = await requireAdmin(ctx, adminOptions);
1966
+ if (!registry?.linkSubscription) {
1967
+ throw new APIError("BAD_REQUEST", {
1968
+ message: "Linking requires the subscriptions plugin."
1969
+ });
1970
+ }
1971
+ const subscriptionId = ctx.params.id;
1972
+ try {
1973
+ const { row, reused } = await registry.linkSubscription(ctx, {
1974
+ streampaySubscriptionId: subscriptionId,
1975
+ referenceType: ctx.body.referenceType,
1976
+ referenceId: ctx.body.referenceId,
1977
+ ...ctx.body.plan ? { plan: ctx.body.plan } : {}
1978
+ });
1979
+ getLogger(ctx).warn(
1980
+ `admin user=${actor.id} linked StreamPay sub=${subscriptionId} to ${ctx.body.referenceType}:${ctx.body.referenceId} (row=${row.id}, reused=${reused}).`
1981
+ );
1982
+ return ctx.json({ linked: true, reused, subscription: row });
1983
+ } catch (err) {
1984
+ if (err instanceof APIError) throw err;
1985
+ toAPIError(
1986
+ {
1987
+ logPrefix: `StreamPay adminLinkSubscription failed for subscription=${subscriptionId}:`,
1988
+ userMessage: "Linking the StreamPay subscription failed."
1989
+ },
1990
+ err,
1991
+ getLogger(ctx)
1992
+ );
1993
+ }
1994
+ }
1995
+ )
1996
+ };
1997
+ }
1950
1998
  function buildWebhookEventsEndpoints(adminOptions, registry) {
1951
1999
  return {
1952
2000
  adminListWebhookEvents: createAuthEndpoint(
@@ -2056,7 +2104,8 @@ var admin = (adminOptions = {}) => (options, registry) => {
2056
2104
  ...buildProductsEndpoints(client, adminOptions),
2057
2105
  ...buildCouponsEndpoints(client, adminOptions),
2058
2106
  ...buildPaymentLinksEndpoints(client, adminOptions),
2059
- ...buildWebhookEventsEndpoints(adminOptions, registry)
2107
+ ...buildWebhookEventsEndpoints(adminOptions, registry),
2108
+ ...buildSubscriptionLinkEndpoints(adminOptions, registry)
2060
2109
  }
2061
2110
  };
2062
2111
  };
@@ -2637,10 +2686,12 @@ function subscriptionSlotKey(referenceType, referenceId, group) {
2637
2686
  return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
2638
2687
  }
2639
2688
  var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
2689
+ var PLUGIN_METADATA_PREFIX = "streampay_plugin_";
2640
2690
  var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
2641
2691
  var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
2642
2692
  var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
2643
2693
  var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
2694
+ var APP_ID_METADATA_KEY = "streampay_plugin_app_id";
2644
2695
 
2645
2696
  // src/plugins/subscriptions/checkout-reservation.ts
2646
2697
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -2915,7 +2966,7 @@ async function yieldReservationToPaidSubscription(args) {
2915
2966
  `StreamPay sub=${streampaySubscriptionId} was linked to row=${holder.id} concurrently. Retry delivery.`
2916
2967
  );
2917
2968
  }
2918
- if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
2969
+ if (holder.status !== "incomplete" || holder.streampaySubscriptionId || args.displaceUnpaid === false) {
2919
2970
  throw new SubscriptionCorrelationError(
2920
2971
  `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
2921
2972
  );
@@ -3886,7 +3937,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3886
3937
  [PLAN_NAME_METADATA_KEY]: plan.name,
3887
3938
  [REFERENCE_ID_METADATA_KEY]: referenceId,
3888
3939
  [REFERENCE_TYPE_METADATA_KEY]: referenceType,
3889
- [SUBSCRIPTION_ROW_ID_METADATA_KEY]: row.id
3940
+ [SUBSCRIPTION_ROW_ID_METADATA_KEY]: row.id,
3941
+ ...subsOptions.appId ? { [APP_ID_METADATA_KEY]: subsOptions.appId } : {}
3890
3942
  }
3891
3943
  };
3892
3944
  if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
@@ -4881,8 +4933,6 @@ var subscriptionSchema = {
4881
4933
  ...subscriptionTable,
4882
4934
  ...webhookEventTable
4883
4935
  };
4884
-
4885
- // src/plugins/subscriptions/sync.ts
4886
4936
  var SUBSCRIPTION_MODEL6 = "subscription";
4887
4937
  var RENEWAL_CALLBACK_FAILURE_CODE = "SUBSCRIPTION_RENEWAL_CALLBACK_FAILED";
4888
4938
  var LEGACY_RENEWAL_CALLBACK_FAILURE_PREFIX = "Subscription callback onSubscriptionRenewed failed:";
@@ -4991,17 +5041,18 @@ function providerStateConfirmsEvent(eventType, stream) {
4991
5041
  return false;
4992
5042
  }
4993
5043
  }
4994
- async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
5044
+ async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId, displaceUnpaid = true) {
4995
5045
  await yieldReservationToPaidSubscription({
4996
5046
  client,
4997
5047
  adapter: ctx.context.adapter,
4998
5048
  slotKey,
4999
5049
  ownerRowId,
5000
5050
  streampaySubscriptionId,
5051
+ displaceUnpaid,
5001
5052
  log: logger(ctx)
5002
5053
  });
5003
5054
  }
5004
- async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
5055
+ async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId, displaceUnpaid = true) {
5005
5056
  const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
5006
5057
  row.referenceType ?? metadataReferenceType ?? "user",
5007
5058
  row.referenceId,
@@ -5016,16 +5067,137 @@ async function linkReservedRow(ctx, client, row, projected, metadataReferenceTyp
5016
5067
  billingStatus: row.billingStatus ?? "current",
5017
5068
  ...activeSlotKey === null ? {} : { activeSlotKey }
5018
5069
  },
5019
- streampaySubscriptionId
5070
+ streampaySubscriptionId,
5071
+ displaceUnpaid
5020
5072
  );
5021
5073
  }
5022
- function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
5074
+ function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId, displaceUnpaid = true) {
5023
5075
  return persistReconciledProjection(ctx.context.adapter, existing, projected, {
5024
5076
  streampaySubscriptionId,
5025
- takeSlot: (slotKey) => takeSlotFromReservation(ctx, client, slotKey, existing.id, streampaySubscriptionId)
5077
+ takeSlot: (slotKey) => takeSlotFromReservation(
5078
+ ctx,
5079
+ client,
5080
+ slotKey,
5081
+ existing.id,
5082
+ streampaySubscriptionId,
5083
+ displaceUnpaid
5084
+ )
5026
5085
  });
5027
5086
  }
5028
- async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5087
+ function linkPolicy(options, source) {
5088
+ return { ...options, source };
5089
+ }
5090
+ var CREATION_EVENT_TYPES = /* @__PURE__ */ new Set(["SUBSCRIPTION_CREATED", "SUBSCRIPTION_ACTIVATED"]);
5091
+ var LinkCallbackError = class extends Error {
5092
+ constructor(callbackName, cause) {
5093
+ super(`${callbackName} failed: ${cause instanceof Error ? cause.message : String(cause)}`);
5094
+ this.name = "LinkCallbackError";
5095
+ }
5096
+ };
5097
+ async function runLinkCallback(callbackName, run) {
5098
+ try {
5099
+ return await run();
5100
+ } catch (err) {
5101
+ throw new LinkCallbackError(callbackName, err);
5102
+ }
5103
+ }
5104
+ async function findUserRow(ctx, where) {
5105
+ return ctx.context.adapter.findOne({ model: "user", where });
5106
+ }
5107
+ async function resolveUnlinkedCorrelation(ctx, payload, stream, plans, policy) {
5108
+ const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
5109
+ const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
5110
+ if (referenceId && planName) {
5111
+ return {
5112
+ referenceId,
5113
+ referenceType: readReferenceType(payload.data),
5114
+ planName,
5115
+ localRowId: readMetadataString(payload.data, SUBSCRIPTION_ROW_ID_METADATA_KEY),
5116
+ appId: readMetadataString(payload.data, APP_ID_METADATA_KEY),
5117
+ resolved: false
5118
+ };
5119
+ }
5120
+ const metadata = payload.data?.metadata;
5121
+ const hasPluginMetadata = Object.keys(metadata ?? {}).some(
5122
+ (key) => key.startsWith(PLUGIN_METADATA_PREFIX)
5123
+ );
5124
+ const resolve = policy.resolveUnlinkedSubscription;
5125
+ if (!resolve || hasPluginMetadata) {
5126
+ logger(ctx).warn(
5127
+ `webhook ${payload.event_type}: cannot link sub=${stream.id} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
5128
+ );
5129
+ return null;
5130
+ }
5131
+ const inferredName = inferPlanFromItems(stream, plans);
5132
+ const consumerUser = stream.organization_consumer_id ? await findUserRow(ctx, [
5133
+ { field: "streampayConsumerId", value: stream.organization_consumer_id }
5134
+ ]) : null;
5135
+ const resolution = await runLinkCallback(
5136
+ "resolveUnlinkedSubscription",
5137
+ () => resolve({
5138
+ subscription: stream,
5139
+ consumerUser: asSessionUser(consumerUser),
5140
+ linkMetadata: metadata && Object.keys(metadata).length > 0 ? metadata : null,
5141
+ inferredPlan: inferredName ? plans.byName.get(inferredName) ?? null : null
5142
+ })
5143
+ );
5144
+ if (!resolution) {
5145
+ logger(ctx).info(
5146
+ `webhook ${payload.event_type}: resolveUnlinkedSubscription left sub=${stream.id} unlinked.`
5147
+ );
5148
+ return null;
5149
+ }
5150
+ const resolvedPlan = resolution.plan ?? inferredName;
5151
+ if (!inferredName || resolvedPlan !== inferredName) {
5152
+ throw new SubscriptionCorrelationError(
5153
+ `resolveUnlinkedSubscription chose plan "${resolution.plan}" for sub=${stream.id}, but StreamPay bills ${inferredName ? `plan "${inferredName}"` : "no configured plan"}.`
5154
+ );
5155
+ }
5156
+ return {
5157
+ referenceId: resolution.referenceId,
5158
+ referenceType: resolution.referenceType,
5159
+ planName: resolvedPlan,
5160
+ localRowId: null,
5161
+ appId: null,
5162
+ resolved: true
5163
+ };
5164
+ }
5165
+ async function verifyUnlinkedOwnership(ctx, stream, plans, policy, correlation) {
5166
+ const inferredName = inferPlanFromItems(stream, plans);
5167
+ const plan = inferredName ? plans.byName.get(inferredName) : void 0;
5168
+ if (!plan) return { refusal: "StreamPay bills no configured plan product" };
5169
+ const { referenceId } = correlation;
5170
+ if (correlation.referenceType === null || correlation.referenceType === "user") {
5171
+ const user = await findUserRow(ctx, [{ field: "id", value: referenceId }]);
5172
+ const consumerMatches = correlation.resolved || policy.source === "admin" || !user?.streampayConsumerId || !stream.organization_consumer_id || user.streampayConsumerId === stream.organization_consumer_id;
5173
+ if (user && consumerMatches) return { plan, referenceType: "user" };
5174
+ if (correlation.referenceType === "user") {
5175
+ return {
5176
+ refusal: user ? "user belongs to another StreamPay consumer" : "user does not exist"
5177
+ };
5178
+ }
5179
+ }
5180
+ const referenceType = correlation.referenceType ?? "custom";
5181
+ if (correlation.resolved || policy.source === "admin") {
5182
+ return { plan, referenceType };
5183
+ }
5184
+ if (policy.resolveSubscriptionReference) {
5185
+ const resolveReference2 = policy.resolveSubscriptionReference;
5186
+ const accepted = await runLinkCallback(
5187
+ "resolveSubscriptionReference",
5188
+ () => resolveReference2({ referenceType, referenceId, plan, subscription: stream })
5189
+ );
5190
+ return accepted ? { plan, referenceType } : { refusal: `resolveSubscriptionReference rejected ${referenceType} reference` };
5191
+ }
5192
+ if (policy.source === "recovery") {
5193
+ return { refusal: `${referenceType} references need resolveSubscriptionReference` };
5194
+ }
5195
+ logger(ctx).warn(
5196
+ `linking StreamPay sub=${stream.id} to unverified ${referenceType} reference=${referenceId}; configure resolveSubscriptionReference to verify it.`
5197
+ );
5198
+ return { plan, referenceType };
5199
+ }
5200
+ async function reconcileFromStreamPay(ctx, payload, client, plans, policy, prefetched) {
5029
5201
  const streampaySubscriptionId = payload.entity_id;
5030
5202
  if (!streampaySubscriptionId) {
5031
5203
  logger(ctx).warn(`webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`);
@@ -5081,7 +5253,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5081
5253
  client,
5082
5254
  existing,
5083
5255
  projected,
5084
- streampaySubscriptionId
5256
+ streampaySubscriptionId,
5257
+ policy.source !== "admin"
5085
5258
  );
5086
5259
  if (!eventApplies) {
5087
5260
  logger(ctx).info(
@@ -5091,17 +5264,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5091
5264
  }
5092
5265
  return { row: updated, stream };
5093
5266
  }
5094
- const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
5095
- const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
5096
- const metadataReferenceType = readReferenceType(payload.data);
5097
- if (!planName || !referenceId) {
5267
+ const correlation = await resolveUnlinkedCorrelation(ctx, payload, stream, plans, policy);
5268
+ if (!correlation) return { row: null, stream };
5269
+ const { referenceId, referenceType: metadataReferenceType, planName } = correlation;
5270
+ const refuse = (reason) => {
5098
5271
  logger(ctx).warn(
5099
- `webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
5272
+ `webhook ${payload.event_type}: did not link StreamPay sub=${streampaySubscriptionId}: ${reason}.`
5100
5273
  );
5101
5274
  return { row: null, stream };
5275
+ };
5276
+ if (correlation.appId && correlation.appId !== policy.appId) {
5277
+ return refuse(`checkout link belongs to app "${correlation.appId}"`);
5102
5278
  }
5279
+ const displaceUnpaid = policy.source !== "admin";
5103
5280
  const paymentLinkId = stream.latest_invoice?.payment_link_id ?? payload.data?.payment_link?.id ?? null;
5104
- const localRowId = readMetadataString(payload.data, SUBSCRIPTION_ROW_ID_METADATA_KEY);
5281
+ const rowMatches = (row2) => row2.referenceId === referenceId && (!metadataReferenceType || (row2.referenceType ?? "user") === metadataReferenceType) && row2.plan === planName && (!row2.streampayConsumerId || !stream.organization_consumer_id || row2.streampayConsumerId === stream.organization_consumer_id) && (!row2.streampaySubscriptionId || row2.streampaySubscriptionId === streampaySubscriptionId) && (!row2.streampayPaymentLinkId || !paymentLinkId || row2.streampayPaymentLinkId === paymentLinkId);
5282
+ const localRowId = correlation.localRowId;
5105
5283
  if (localRowId) {
5106
5284
  const metadataRow = await ctx.context.adapter.findOne({
5107
5285
  model: SUBSCRIPTION_MODEL6,
@@ -5111,18 +5289,18 @@ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5111
5289
  logger(ctx).warn(
5112
5290
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
5113
5291
  );
5114
- } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampayConsumerId || !stream.organization_consumer_id || metadataRow.streampayConsumerId === stream.organization_consumer_id) && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
5292
+ } else if (rowMatches(metadataRow)) {
5115
5293
  const updated = await linkReservedRow(
5116
5294
  ctx,
5117
5295
  client,
5118
5296
  metadataRow,
5119
5297
  projected,
5120
5298
  metadataReferenceType,
5121
- streampaySubscriptionId
5299
+ streampaySubscriptionId,
5300
+ displaceUnpaid
5122
5301
  );
5123
5302
  return { row: updated, stream };
5124
- }
5125
- if (metadataRow) {
5303
+ } else {
5126
5304
  logger(ctx).warn(
5127
5305
  `webhook ${payload.event_type}: ignored unsafe subscription row correlation for row=${localRowId}.`
5128
5306
  );
@@ -5131,14 +5309,35 @@ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5131
5309
  );
5132
5310
  }
5133
5311
  }
5134
- const incomplete = await findIncompleteRow(
5312
+ const linkOwner = paymentLinkId ? await ctx.context.adapter.findOne({
5313
+ model: SUBSCRIPTION_MODEL6,
5314
+ where: [{ field: "streampayPaymentLinkId", value: paymentLinkId }]
5315
+ }) : null;
5316
+ if (linkOwner) {
5317
+ if (!rowMatches(linkOwner)) {
5318
+ throw new SubscriptionCorrelationError(
5319
+ `StreamPay sub=${streampaySubscriptionId} was paid through payment link=${paymentLinkId} of row=${linkOwner.id}, which belongs to another reference or plan.`
5320
+ );
5321
+ }
5322
+ const updated = await linkReservedRow(
5323
+ ctx,
5324
+ client,
5325
+ linkOwner,
5326
+ projected,
5327
+ metadataReferenceType,
5328
+ streampaySubscriptionId,
5329
+ displaceUnpaid
5330
+ );
5331
+ return { row: updated, stream };
5332
+ }
5333
+ const incomplete = displaceUnpaid ? await findIncompleteRow(
5135
5334
  ctx,
5136
5335
  referenceId,
5137
5336
  metadataReferenceType,
5138
5337
  planName,
5139
5338
  paymentLinkId,
5140
5339
  stream.organization_consumer_id ?? null
5141
- );
5340
+ ) : null;
5142
5341
  if (incomplete) {
5143
5342
  const updated = await linkReservedRow(
5144
5343
  ctx,
@@ -5146,15 +5345,24 @@ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5146
5345
  incomplete,
5147
5346
  projected,
5148
5347
  metadataReferenceType,
5149
- streampaySubscriptionId
5348
+ streampaySubscriptionId,
5349
+ displaceUnpaid
5150
5350
  );
5151
5351
  return { row: updated, stream };
5152
5352
  }
5153
- const plan = plans.byName.get(planName);
5154
- const referenceType = metadataReferenceType ?? "custom";
5155
- const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
5353
+ const owner = await verifyUnlinkedOwnership(ctx, stream, plans, policy, correlation);
5354
+ if ("refusal" in owner) return refuse(owner.refusal);
5355
+ const { plan, referenceType } = owner;
5356
+ const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan.group);
5156
5357
  if (activeSlotKey) {
5157
- await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
5358
+ await takeSlotFromReservation(
5359
+ ctx,
5360
+ client,
5361
+ activeSlotKey,
5362
+ null,
5363
+ streampaySubscriptionId,
5364
+ displaceUnpaid
5365
+ );
5158
5366
  }
5159
5367
  const row = await ctx.context.adapter.create({
5160
5368
  model: SUBSCRIPTION_MODEL6,
@@ -5166,10 +5374,10 @@ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
5166
5374
  referenceType,
5167
5375
  activeSlotKey,
5168
5376
  streampayPaymentLinkId: paymentLinkId,
5169
- plan: planName,
5170
- planVersion: plan?.version ?? null,
5171
- productId: plan?.productId ?? subscriptionItemProductId(stream.items?.[0]),
5172
- group: plan?.group ?? null,
5377
+ plan: plan.name,
5378
+ planVersion: plan.version ?? null,
5379
+ productId: plan.productId,
5380
+ group: plan.group ?? null,
5173
5381
  billingStatus: "current",
5174
5382
  createdAt: /* @__PURE__ */ new Date()
5175
5383
  }
@@ -5196,7 +5404,13 @@ async function processSubscriptionEvent(ctx, payload, client, plans, callbacks,
5196
5404
  );
5197
5405
  return;
5198
5406
  }
5199
- const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
5407
+ const { row, stream } = await reconcileFromStreamPay(
5408
+ ctx,
5409
+ payload,
5410
+ client,
5411
+ plans,
5412
+ linkPolicy(callbacks, CREATION_EVENT_TYPES.has(payload.event_type) ? "creation" : "recovery")
5413
+ );
5200
5414
  if (!row) return;
5201
5415
  const user = await resolveRowUser(ctx, row);
5202
5416
  await dispatchSubscriptionCallback(
@@ -5290,37 +5504,47 @@ async function releaseLockOfCompletedRenewal(ctx, subscriptionRowId, lockEventId
5290
5504
  }
5291
5505
  return released !== null;
5292
5506
  }
5293
- async function linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, stream) {
5294
- const paymentLinkId = stream.latest_invoice?.payment_link_id;
5295
- if (!paymentLinkId || !stream.id) return null;
5296
- const reservation = await ctx.context.adapter.findOne({
5507
+ async function linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, policy, stream) {
5508
+ if (!stream.id) return null;
5509
+ const paymentLinkId = stream.latest_invoice?.payment_link_id ?? null;
5510
+ const reservation = paymentLinkId ? await ctx.context.adapter.findOne({
5297
5511
  model: SUBSCRIPTION_MODEL6,
5298
5512
  where: [{ field: "streampayPaymentLinkId", value: paymentLinkId }]
5299
- });
5300
- if (!reservation) return null;
5301
- const link = await client.getPaymentLink(paymentLinkId);
5513
+ }) : null;
5514
+ if (!reservation && !inferPlanFromItems(stream, plans)) return null;
5515
+ const metadata = paymentLinkId ? await readCheckoutLinkMetadata(client, paymentLinkId) : null;
5302
5516
  const { row } = await reconcileFromStreamPay(
5303
5517
  ctx,
5304
5518
  {
5305
5519
  ...payload,
5306
5520
  entity_id: stream.id,
5307
5521
  data: {
5308
- metadata: link.custom_metadata ?? {},
5309
- payment_link: { id: paymentLinkId, url: "" }
5522
+ metadata: metadata ?? {},
5523
+ ...paymentLinkId ? { payment_link: { id: paymentLinkId, url: "" } } : {}
5310
5524
  }
5311
5525
  },
5312
5526
  client,
5313
5527
  plans,
5528
+ policy,
5314
5529
  stream
5315
5530
  );
5316
5531
  if (row) {
5317
5532
  logger(ctx).warn(
5318
- `webhook ${payload.event_type}: linked checkout row=${row.id} to StreamPay sub=${stream.id} from renewal evidence.`
5533
+ `webhook ${payload.event_type}: linked row=${row.id} to StreamPay sub=${stream.id} from renewal evidence.`
5319
5534
  );
5320
5535
  return row;
5321
5536
  }
5322
5537
  return findSubscriptionByStreampayId(ctx, stream.id);
5323
5538
  }
5539
+ async function readCheckoutLinkMetadata(client, paymentLinkId) {
5540
+ try {
5541
+ const link = await client.getPaymentLink(paymentLinkId);
5542
+ return link?.custom_metadata ?? null;
5543
+ } catch (err) {
5544
+ if (readSdkErrorFields(err).status === 404) return null;
5545
+ throw err;
5546
+ }
5547
+ }
5324
5548
  async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback, inboxEnabled) {
5325
5549
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
5326
5550
  if (!invoiceId) return;
@@ -5347,7 +5571,14 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
5347
5571
  logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
5348
5572
  throw err;
5349
5573
  }
5350
- const existing = await findSubscriptionByStreampayId(ctx, subscriptionId) ?? await linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, stream);
5574
+ const existing = await findSubscriptionByStreampayId(ctx, subscriptionId) ?? await linkCheckoutFromRenewalEvidence(
5575
+ ctx,
5576
+ payload,
5577
+ client,
5578
+ plans,
5579
+ linkPolicy(callbacks, "recovery"),
5580
+ stream
5581
+ );
5351
5582
  if (!existing) return;
5352
5583
  const eventAt = parseDate(payload.timestamp);
5353
5584
  const eventIsStale = Boolean(
@@ -5468,6 +5699,106 @@ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retry
5468
5699
  if (!callbackName) return;
5469
5700
  await fireCallback(ctx, callbacks[callbackName], data, callbackName, retryOnCallbackError);
5470
5701
  }
5702
+ async function linkSubscriptionToReference(ctx, client, plans, options, request) {
5703
+ const { streampaySubscriptionId, referenceType, referenceId } = request;
5704
+ const stream = await client.getSubscription(streampaySubscriptionId);
5705
+ const sameReference = (row) => row.referenceId === referenceId && (row.referenceType ?? "user") === referenceType;
5706
+ const reuse = async (row) => {
5707
+ if (!sameReference(row)) {
5708
+ throw new APIError("CONFLICT", {
5709
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
5710
+ message: `StreamPay subscription ${streampaySubscriptionId} is already linked to another reference.`
5711
+ });
5712
+ }
5713
+ await applySubscriptionProjection(
5714
+ ctx.context.adapter,
5715
+ stream,
5716
+ plans,
5717
+ logger(ctx),
5718
+ "link subscription"
5719
+ );
5720
+ return {
5721
+ row: await findSubscriptionByStreampayId(ctx, streampaySubscriptionId) ?? row,
5722
+ reused: true
5723
+ };
5724
+ };
5725
+ const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
5726
+ if (existing) return reuse(existing);
5727
+ const inferredName = inferPlanFromItems(stream, plans);
5728
+ const planName = request.plan ?? inferredName;
5729
+ const plan = planName ? plans.byName.get(planName) : void 0;
5730
+ if (!plan || planName !== inferredName) {
5731
+ throw new APIError("BAD_REQUEST", {
5732
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
5733
+ message: inferredName ? `StreamPay bills plan "${inferredName}", not "${request.plan}".` : "StreamPay bills no configured plan product."
5734
+ });
5735
+ }
5736
+ if (referenceType === "user" && !await findUserRow(ctx, [{ field: "id", value: referenceId }])) {
5737
+ throw new APIError("BAD_REQUEST", {
5738
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
5739
+ message: `User ${referenceId} does not exist.`
5740
+ });
5741
+ }
5742
+ const paymentLinkId = stream.latest_invoice?.payment_link_id ?? null;
5743
+ if (!isTerminalSubscriptionStatus(toLocalStatus(stream.status))) {
5744
+ const holder = await ctx.context.adapter.findOne({
5745
+ model: SUBSCRIPTION_MODEL6,
5746
+ where: [
5747
+ {
5748
+ field: "activeSlotKey",
5749
+ value: subscriptionSlotKey(referenceType, referenceId, plan.group)
5750
+ }
5751
+ ]
5752
+ });
5753
+ if (holder && !(paymentLinkId && holder.streampayPaymentLinkId === paymentLinkId)) {
5754
+ throw new APIError("CONFLICT", {
5755
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
5756
+ message: `Row ${holder.id} (${holder.status}) holds this reference's billing slot. Resolve it first.`
5757
+ });
5758
+ }
5759
+ }
5760
+ try {
5761
+ const { row } = await reconcileFromStreamPay(
5762
+ ctx,
5763
+ {
5764
+ event_type: "SUBSCRIPTION_CREATED",
5765
+ entity_type: "SUBSCRIPTION",
5766
+ entity_id: streampaySubscriptionId,
5767
+ entity_url: "",
5768
+ status: stream.status ?? "",
5769
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5770
+ data: {
5771
+ metadata: {
5772
+ [PLAN_NAME_METADATA_KEY]: plan.name,
5773
+ [REFERENCE_ID_METADATA_KEY]: referenceId,
5774
+ [REFERENCE_TYPE_METADATA_KEY]: referenceType
5775
+ },
5776
+ ...paymentLinkId ? { payment_link: { id: paymentLinkId, url: "" } } : {}
5777
+ }
5778
+ },
5779
+ client,
5780
+ plans,
5781
+ linkPolicy(options, "admin"),
5782
+ stream
5783
+ );
5784
+ if (row && !sameReference(row)) return reuse(row);
5785
+ if (row) return { row, reused: false };
5786
+ } catch (err) {
5787
+ const winner = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
5788
+ if (winner) return reuse(winner);
5789
+ if (err instanceof SubscriptionCorrelationError || isUniqueConstraintError(err)) {
5790
+ throw new APIError("CONFLICT", {
5791
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
5792
+ message: err instanceof Error ? err.message : String(err)
5793
+ });
5794
+ }
5795
+ throw err;
5796
+ }
5797
+ throw new APIError("BAD_REQUEST", {
5798
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
5799
+ message: `StreamPay subscription ${streampaySubscriptionId} could not be linked. See server logs.`
5800
+ });
5801
+ }
5471
5802
  function classifyWebhookFailure(err) {
5472
5803
  if (err instanceof SubscriptionCorrelationError) return "PERMANENT";
5473
5804
  const { status } = readSdkErrorFields(err);
@@ -5563,6 +5894,13 @@ function subscriptions(subsOptions) {
5563
5894
  throw err;
5564
5895
  }
5565
5896
  };
5897
+ registry.linkSubscription = async (ctx, request) => linkSubscriptionToReference(
5898
+ toSyncContext(ctx),
5899
+ options.client,
5900
+ await plansRef(),
5901
+ subsOptions,
5902
+ request
5903
+ );
5566
5904
  }
5567
5905
  const schema = {
5568
5906
  ...subscriptionTable,
@@ -6012,7 +6350,7 @@ var onUserDelete = (options) => async (user, context) => {
6012
6350
 
6013
6351
  // package.json
6014
6352
  var package_default = {
6015
- version: "3.4.0"};
6353
+ version: "3.5.0"};
6016
6354
 
6017
6355
  // src/version.ts
6018
6356
  var version = package_default.version;
@@ -6091,6 +6429,6 @@ var StreamPayAmount = {
6091
6429
  }
6092
6430
  };
6093
6431
 
6094
- export { $ERROR_CODES, CheckoutBody, DEFAULT_ACCESS_STATUSES, PLAN_NAME_METADATA_KEY, REFERENCE_ID_METADATA_KEY, REFERENCE_TYPE_METADATA_KEY, STREAMPAY_EVENT_TYPES, STREAMPAY_INVOICE_EVENT_TYPES, STREAMPAY_PAYMENT_EVENT_TYPES, STREAMPAY_PAYMENT_LINK_EVENT_TYPES, STREAMPAY_SUBSCRIPTION_EVENT_TYPES, SUBSCRIPTION_ROW_ID_METADATA_KEY, StreamPayAmount, StreamPayWebhookError, admin, checkLimit, checkout, classifyWebhookFailure, dispatchWebhook, findConsumerByExternalId, findConsumerByIdentifiers, formatStreamPayError, hasFeature, hasSubscriptionAccess, isKnownStreamPayWebhookPayload, isStreamPayWebhookEnvelope, mapToErrorCode, parseStreamPayError, portal, streampay, subscriptionSchema, subscriptionSlotKey, subscriptions, syncWebhookPayload, verifyWebhook, verifyWebhookOrThrow, webhooks };
6432
+ export { $ERROR_CODES, APP_ID_METADATA_KEY, CheckoutBody, DEFAULT_ACCESS_STATUSES, PLAN_NAME_METADATA_KEY, REFERENCE_ID_METADATA_KEY, REFERENCE_TYPE_METADATA_KEY, STREAMPAY_EVENT_TYPES, STREAMPAY_INVOICE_EVENT_TYPES, STREAMPAY_PAYMENT_EVENT_TYPES, STREAMPAY_PAYMENT_LINK_EVENT_TYPES, STREAMPAY_SUBSCRIPTION_EVENT_TYPES, SUBSCRIPTION_ROW_ID_METADATA_KEY, StreamPayAmount, StreamPayWebhookError, admin, checkLimit, checkout, classifyWebhookFailure, dispatchWebhook, findConsumerByExternalId, findConsumerByIdentifiers, formatStreamPayError, hasFeature, hasSubscriptionAccess, isKnownStreamPayWebhookPayload, isStreamPayWebhookEnvelope, mapToErrorCode, parseStreamPayError, portal, streampay, subscriptionSchema, subscriptionSlotKey, subscriptions, syncWebhookPayload, verifyWebhook, verifyWebhookOrThrow, webhooks };
6095
6433
  //# sourceMappingURL=index.js.map
6096
6434
  //# sourceMappingURL=index.js.map