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