@pithy-sh/payments 0.4.0 → 0.6.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 (180) hide show
  1. package/README.md +10 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +2 -1
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +77 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/data/webhookEvent.d.ts +1 -1
  49. package/dist/entitlement/allowance.d.ts +100 -0
  50. package/dist/entitlement/allowance.d.ts.map +1 -0
  51. package/dist/entitlement/allowance.js +171 -0
  52. package/dist/entitlement/manual.d.ts +5 -5
  53. package/dist/entitlement/manual.js +3 -3
  54. package/dist/entitlement/meter.d.ts +98 -0
  55. package/dist/entitlement/meter.d.ts.map +1 -0
  56. package/dist/entitlement/meter.js +177 -0
  57. package/dist/entitlement/override.d.ts +119 -0
  58. package/dist/entitlement/override.d.ts.map +1 -0
  59. package/dist/entitlement/override.js +256 -0
  60. package/dist/entitlement/resolver.d.ts +2 -1
  61. package/dist/entitlement/resolver.d.ts.map +1 -1
  62. package/dist/entitlement/resolver.js +32 -1
  63. package/dist/error/errors.d.ts +23 -3
  64. package/dist/error/errors.d.ts.map +1 -1
  65. package/dist/error/errors.js +35 -2
  66. package/dist/http/responses.d.ts +367 -0
  67. package/dist/http/responses.d.ts.map +1 -1
  68. package/dist/http/responses.js +146 -7
  69. package/dist/http/routes.d.ts.map +1 -1
  70. package/dist/http/routes.js +270 -16
  71. package/dist/http/schemas.d.ts +54 -0
  72. package/dist/http/schemas.d.ts.map +1 -1
  73. package/dist/http/schemas.js +61 -2
  74. package/dist/http/scopes.d.ts +25 -0
  75. package/dist/http/scopes.d.ts.map +1 -1
  76. package/dist/http/scopes.js +60 -1
  77. package/dist/http/view.d.ts +22 -4
  78. package/dist/http/view.d.ts.map +1 -1
  79. package/dist/http/view.js +88 -7
  80. package/dist/index.d.ts +2 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3 -2
  83. package/dist/migrations/0002_allowances.d.ts +26 -0
  84. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  85. package/dist/migrations/0002_allowances.js +62 -0
  86. package/dist/peer.d.ts +2 -1
  87. package/dist/peer.d.ts.map +1 -1
  88. package/dist/projection/event.d.ts +1 -0
  89. package/dist/projection/event.d.ts.map +1 -1
  90. package/dist/projection/event.js +1 -0
  91. package/dist/projection/writer.d.ts.map +1 -1
  92. package/dist/projection/writer.js +3 -1
  93. package/dist/rails/contract.d.ts +6 -0
  94. package/dist/rails/contract.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.d.ts.map +1 -1
  96. package/dist/rails/google/playApi.js +2 -0
  97. package/dist/rails/paddle/objects.d.ts +2 -0
  98. package/dist/rails/paddle/objects.d.ts.map +1 -1
  99. package/dist/rails/paddle/objects.js +7 -2
  100. package/dist/rails/paddle/usage.d.ts +11 -0
  101. package/dist/rails/paddle/usage.d.ts.map +1 -0
  102. package/dist/rails/paddle/usage.js +49 -0
  103. package/dist/rails/quantity.d.ts +12 -0
  104. package/dist/rails/quantity.d.ts.map +1 -0
  105. package/dist/rails/quantity.js +16 -0
  106. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  107. package/dist/rails/stripe/checkout.js +1 -1
  108. package/dist/rails/stripe/objects.d.ts.map +1 -1
  109. package/dist/rails/stripe/objects.js +3 -0
  110. package/dist/rails/stripe/usage.d.ts +10 -0
  111. package/dist/rails/stripe/usage.d.ts.map +1 -0
  112. package/dist/rails/stripe/usage.js +49 -0
  113. package/dist/usage/pass.d.ts +120 -0
  114. package/dist/usage/pass.d.ts.map +1 -0
  115. package/dist/usage/pass.js +363 -0
  116. package/dist/usage/reporter.d.ts +36 -0
  117. package/dist/usage/reporter.d.ts.map +1 -0
  118. package/dist/usage/reporter.js +2 -0
  119. package/dist/version.generated.d.ts +1 -1
  120. package/dist/version.generated.js +1 -1
  121. package/dist/workflows/report.d.ts.map +1 -1
  122. package/dist/workflows/specs.d.ts +28 -0
  123. package/dist/workflows/specs.d.ts.map +1 -1
  124. package/dist/workflows/specs.js +26 -1
  125. package/dist/workflows/usage.d.ts +38 -0
  126. package/dist/workflows/usage.d.ts.map +1 -0
  127. package/dist/workflows/usage.js +77 -0
  128. package/dist/workflows/worker.js +2 -2
  129. package/docs/entitlements.md +249 -0
  130. package/docs/lemon-squeezy.md +1 -0
  131. package/docs/paddle.md +1 -0
  132. package/package.json +5 -5
  133. package/pithy.manifest.json +3 -8
  134. package/src/admin/coverage.ts +28 -0
  135. package/src/admin/read.ts +173 -1
  136. package/src/audit/actions.ts +13 -0
  137. package/src/capability.ts +87 -9
  138. package/src/client/api.ts +44 -0
  139. package/src/client/hooks.ts +44 -0
  140. package/src/client/projection.ts +31 -0
  141. package/src/config/allowances.ts +211 -0
  142. package/src/config/config.ts +283 -15
  143. package/src/data/meterCounter.ts +38 -0
  144. package/src/data/override.ts +74 -0
  145. package/src/data/period.ts +53 -0
  146. package/src/data/purchase.ts +9 -0
  147. package/src/data/tables.ts +25 -1
  148. package/src/data/usageReport.ts +64 -0
  149. package/src/data/usageRun.ts +66 -0
  150. package/src/entitlement/allowance.ts +213 -0
  151. package/src/entitlement/manual.ts +6 -6
  152. package/src/entitlement/meter.ts +252 -0
  153. package/src/entitlement/override.ts +381 -0
  154. package/src/entitlement/resolver.ts +43 -2
  155. package/src/error/errors.ts +48 -4
  156. package/src/http/responses.ts +305 -4
  157. package/src/http/routes.ts +365 -11
  158. package/src/http/schemas.ts +139 -1
  159. package/src/http/scopes.ts +68 -0
  160. package/src/http/view.ts +112 -7
  161. package/src/index.ts +18 -0
  162. package/src/migrations/0002_allowances.ts +149 -0
  163. package/src/projection/event.ts +9 -0
  164. package/src/projection/writer.ts +4 -0
  165. package/src/rails/contract.ts +6 -0
  166. package/src/rails/google/playApi.ts +2 -0
  167. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  168. package/src/rails/paddle/objects.ts +6 -0
  169. package/src/rails/paddle/usage.ts +66 -0
  170. package/src/rails/quantity.ts +14 -0
  171. package/src/rails/stripe/checkout.ts +3 -1
  172. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  173. package/src/rails/stripe/objects.ts +4 -0
  174. package/src/rails/stripe/usage.ts +61 -0
  175. package/src/usage/pass.ts +539 -0
  176. package/src/usage/reporter.ts +38 -0
  177. package/src/version.generated.ts +1 -1
  178. package/src/workflows/report.ts +4 -2
  179. package/src/workflows/specs.ts +34 -0
  180. package/src/workflows/usage.ts +97 -0
@@ -6,10 +6,13 @@ import { providerProductId, railEnabled, resolveProduct } from "../config/config
6
6
  import { PaymentsPurchase } from "../data/purchase.js";
7
7
  import { WEBHOOK_EVENT_ORPHANED } from "../data/webhookEvent.js";
8
8
  import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables.js";
9
- import { resolveEntitlements } from "../projection/resolve.js";
10
9
  import { PaymentsEntitlementNotInCatalogError, PaymentsProductNotFoundError, PaymentsRailNotConfiguredError, PaymentsReceiptAlreadyOwnedError, PaymentsReconcileNotProvisionedError, PaymentsSubscriptionChangeRefusedError } from "../error/errors.js";
10
+ import { resolveEntitlements } from "../projection/resolve.js";
11
+ import { resolveAllowances } from "../entitlement/allowance.js";
12
+ import { allowanceOverride, clearOverride, overrideCeiling, overrideVersion, readOverride, setOverride, setUnrestricted } from "../entitlement/override.js";
13
+ import { allowanceInputFor } from "../entitlement/meter.js";
11
14
  import { requirePaymentsSubject, resolvePaymentsSubject } from "../entitlement/subjectSeam.js";
12
- import { listEntitlements, listPurchases, listReconcileRuns, listSubscriptions, readEntitlements } from "../admin/read.js";
15
+ import { lastReports, listEntitlements, listOverrides, listPurchases, listReconcileRuns, listSubscriptions, listUsageRuns, readEntitlements, unrestrictedSubjects } from "../admin/read.js";
13
16
  import { PaymentsAuditActions } from "../audit/actions.js";
14
17
  import { nextSubscriptionEvent } from "../data/subscription.js";
15
18
  import { grantEntitlement, revokeEntitlement } from "../entitlement/manual.js";
@@ -22,12 +25,13 @@ import { PAYMENTS_PROVIDER_SECRET, paymentsSecretsRegistry } from "../secret/reg
22
25
  import { resolveRailProvider } from "../rails/providers.js";
23
26
  import { PAYMENTS_CAPABILITY, paymentsWorkflows } from "../workflows/specs.js";
24
27
  import { requireAuth } from "./guards.js";
25
- import { PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementsResponse, PaymentsAdminPurchasesResponse, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsCheckoutHandoffResponse, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementsResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPurchaseResponse, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionStandingResponse, PaymentsWebhookAck } from "./responses.js";
26
- import { AdminDiscountsQuery, AdminEntitlementsQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest } from "./schemas.js";
27
- import { PAYMENTS_CATALOG_READ_SCOPE, PAYMENTS_DISCOUNT_CREATE_SCOPE, PAYMENTS_DISCOUNT_READ_SCOPE, PAYMENTS_ENTITLEMENTS_READ_SCOPE, PAYMENTS_ENTITLEMENT_GRANT_SCOPE, PAYMENTS_ENTITLEMENT_REVOKE_SCOPE, PAYMENTS_PURCHASES_READ_SCOPE, PAYMENTS_RECONCILE_READ_SCOPE, PAYMENTS_RECONCILE_RUN_SCOPE, PAYMENTS_SUBSCRIPTIONS_READ_SCOPE } from "./scopes.js";
28
- import { adminCatalogView, adminEntitlementView, adminPurchaseView, adminReconcileRunView, entitlementView, purchaseView } from "./view.js";
28
+ import { PaymentsAdminCatalogResponse, PaymentsAdminDiscountsResponse, PaymentsAdminEntitlementsResponse, PaymentsAdminOverridesResponse, PaymentsAdminPurchasesResponse, PaymentsAdminReconcileRunStarted, PaymentsAdminReconcileRunsResponse, PaymentsAdminSubjectEntitlementsResponse, PaymentsAdminSubscriptionsResponse, PaymentsAdminUsageRunsResponse, PaymentsCheckoutHandoffResponse, PaymentsDiscountResponse, PaymentsEntitlementResponse, PaymentsEntitlementsResponse, PaymentsOverrideResponse, PaymentsPortalHandoffResponse, PaymentsPricingEnvelope, PaymentsPurchaseResponse, PaymentsRefundResponse, PaymentsRestoreResponse, PaymentsSubscriptionQuoteResponse, PaymentsSubscriptionResponse, PaymentsSubscriptionStandingResponse, PaymentsWebhookAck } from "./responses.js";
29
+ import { AdminDiscountsQuery, AdminEntitlementsQuery, AdminOverridesQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AdminUsageRunsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, OverrideClearRequest, OverrideSetRequest, OverrideUnrestrictedRequest, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest } from "./schemas.js";
30
+ import { PAYMENTS_CATALOG_READ_SCOPE, PAYMENTS_DISCOUNT_CREATE_SCOPE, PAYMENTS_DISCOUNT_READ_SCOPE, PAYMENTS_ENTITLEMENTS_READ_SCOPE, PAYMENTS_ENTITLEMENT_GRANT_SCOPE, PAYMENTS_ENTITLEMENT_REVOKE_SCOPE, PAYMENTS_OVERRIDE_CLEAR_SCOPE, PAYMENTS_OVERRIDE_SET_SCOPE, PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE, PAYMENTS_PURCHASES_READ_SCOPE, PAYMENTS_RECONCILE_READ_SCOPE, PAYMENTS_RECONCILE_RUN_SCOPE, PAYMENTS_SUBSCRIPTIONS_READ_SCOPE, PAYMENTS_USAGE_READ_SCOPE } from "./scopes.js";
31
+ import { adminAllowancesView, adminCatalogView, adminEntitlementView, adminOverrideView, adminPurchaseView, adminReconcileRunView, adminUsageRunView, entitlementView, overrideView, purchaseView } from "./view.js";
29
32
  import { completeWebhook, requireSignedWebhook, verifiedWebhook } from "./webhookGuard.js";
30
33
  import { InternalError, NotFoundError, PithyError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
34
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
31
35
  import { safeEmit } from "@pithy-sh/core/src/controlPlane/audit/actions";
32
36
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
33
37
  import { memoryJwksCache } from "@pithy-sh/core/src/http/oidcWebhook";
@@ -827,7 +831,7 @@ function registerPaymentsRoutes(options) {
827
831
  }
828
832
  });
829
833
  return c.json({
830
- purchases: page.items.map(adminPurchaseView),
834
+ purchases: page.items.map((row) => adminPurchaseView(row)),
831
835
  nextCursor: page.nextCursor
832
836
  }, 200);
833
837
  });
@@ -852,6 +856,10 @@ function registerPaymentsRoutes(options) {
852
856
  ...query,
853
857
  subject
854
858
  });
859
+ const reported = await lastReports(database(c), page.items.flatMap((row) => row.originalTransactionId === null ? [] : [{
860
+ rail: row.rail,
861
+ providerSubscriptionId: row.originalTransactionId
862
+ }]));
855
863
  await recordRead(c, PaymentsAuditActions.subscriptionsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
856
864
  returned: page.items.length,
857
865
  resumed: query.cursor !== void 0,
@@ -862,7 +870,7 @@ function registerPaymentsRoutes(options) {
862
870
  }
863
871
  });
864
872
  return c.json({
865
- subscriptions: page.items.map(adminPurchaseView),
873
+ subscriptions: page.items.map((row) => adminPurchaseView(row, reported.get(`${row.rail}:${row.originalTransactionId}`) ?? null)),
866
874
  nextCursor: page.nextCursor
867
875
  }, 200);
868
876
  });
@@ -886,6 +894,7 @@ function registerPaymentsRoutes(options) {
886
894
  ...query,
887
895
  subject
888
896
  });
897
+ const unrestricted = await unrestrictedSubjects(database(c), page.items);
889
898
  await recordRead(c, PaymentsAuditActions.entitlementsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
890
899
  returned: page.items.length,
891
900
  resumed: query.cursor !== void 0,
@@ -896,7 +905,48 @@ function registerPaymentsRoutes(options) {
896
905
  }
897
906
  });
898
907
  return c.json({
899
- entitlements: page.items.map((row) => adminEntitlementView(row, now)),
908
+ entitlements: page.items.map((row) => adminEntitlementView(row, now, unrestricted.has(encodeSubjectReference(row)))),
909
+ nextCursor: page.nextCursor
910
+ }, 200);
911
+ });
912
+ /**
913
+ * CONTROL PLANE. Every subject's override, most recently changed first.
914
+ *
915
+ * The read the override writes are paired with, on the entitlement read's scope: what a subject may have
916
+ * is one question with its entitlements, and an operator who can see one can see the other. Filterable to
917
+ * `unrestricted=true`, because "who holds the whole product" must be a question anyone holding this scope
918
+ * can answer in one request.
919
+ */
920
+ app.get(`${base}/admin/overrides`, describeRoute({
921
+ summary: "Read every subject's override, page by page.",
922
+ verification: "control-plane",
923
+ scopes: [PAYMENTS_ENTITLEMENTS_READ_SCOPE],
924
+ responses: { 200: PaymentsAdminOverridesResponse }
925
+ }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("query", AdminOverridesQuery), async (c) => {
926
+ const query = c.req.valid("query");
927
+ const subject = subjectFilter(query);
928
+ const unrestricted = query.unrestricted === void 0 ? void 0 : query.unrestricted === "true";
929
+ const page = await listOverrides(database(c), {
930
+ ...subject ? { subject } : {},
931
+ ...unrestricted === void 0 ? {} : { unrestricted },
932
+ ...query.cursor ? { cursor: query.cursor } : {},
933
+ ...query.limit ? { limit: query.limit } : {}
934
+ });
935
+ await recordRead(c, PaymentsAuditActions.entitlementsRead, subject === void 0 ? null : encodeSubjectReference(subject), {
936
+ returned: page.items.length,
937
+ resumed: query.cursor !== void 0,
938
+ filters: {
939
+ subjectType: subject?.subjectType ?? null,
940
+ subjectId: subject?.subjectId ?? null,
941
+ unrestricted: unrestricted ?? null
942
+ }
943
+ });
944
+ return c.json({
945
+ overrides: page.items.map((row) => ({
946
+ subjectType: row.subjectType,
947
+ subjectId: row.subjectId,
948
+ override: overrideView(row)
949
+ })),
900
950
  nextCursor: page.nextCursor
901
951
  }, 200);
902
952
  });
@@ -923,15 +973,34 @@ function registerPaymentsRoutes(options) {
923
973
  }), requireControlPlane(PAYMENTS_ENTITLEMENTS_READ_SCOPE), validate("param", AdminSubjectParam), async (c) => {
924
974
  const subject = c.req.valid("param");
925
975
  const now = clock();
926
- const rows = await readEntitlements(database(c), subject);
976
+ const d1 = database(c);
977
+ const rows = await readEntitlements(d1, subject);
978
+ const override = await readOverride(paymentsDatabase(d1), subject);
979
+ const held = grantedEntitlementKeys(rows.map((row) => ({
980
+ key: row.entitlement,
981
+ active: row.active,
982
+ expiresAt: row.expiresAt,
983
+ source: null
984
+ })), now);
985
+ const resolved = resolveAllowances({
986
+ declarations: config,
987
+ held,
988
+ override: allowanceOverride(override)
989
+ });
990
+ const unrestricted = override?.unrestricted === true;
927
991
  await recordRead(c, PaymentsAuditActions.entitlementsRead, encodeSubjectReference(subject), {
928
992
  subjectType: subject.subjectType,
929
993
  subjectId: subject.subjectId,
930
- returned: rows.length
994
+ returned: rows.length,
995
+ unrestricted
931
996
  });
932
997
  return c.json({
933
998
  ...subject,
934
- entitlements: rows.map((row) => adminEntitlementView(row, now))
999
+ entitlements: rows.map((row) => adminEntitlementView(row, now, unrestricted)),
1000
+ unrestricted,
1001
+ overrideVersion: overrideVersion(override),
1002
+ override: adminOverrideView(override),
1003
+ allowances: adminAllowancesView(resolved, (name) => overrideCeiling(config, held, name))
935
1004
  }, 200);
936
1005
  });
937
1006
  /**
@@ -966,6 +1035,30 @@ function registerPaymentsRoutes(options) {
966
1035
  }, 200);
967
1036
  });
968
1037
  /**
1038
+ * CONTROL PLANE. What usage reporting has done — the passes this Worker has run, newest first.
1039
+ *
1040
+ * Its own scope, separate from the reconciliation log's: a run's findings name the subjects it did not
1041
+ * report and why, which is what an operator answering "why was this customer not billed" needs and what a
1042
+ * health monitor does not.
1043
+ */
1044
+ app.get(`${base}/admin/usage-runs`, describeRoute({
1045
+ summary: "Read the usage-reporting passes this deployment has run.",
1046
+ verification: "control-plane",
1047
+ scopes: [PAYMENTS_USAGE_READ_SCOPE],
1048
+ responses: { 200: PaymentsAdminUsageRunsResponse }
1049
+ }), requireControlPlane(PAYMENTS_USAGE_READ_SCOPE), validate("query", AdminUsageRunsQuery), async (c) => {
1050
+ const query = c.req.valid("query");
1051
+ const page = await listUsageRuns(database(c), query);
1052
+ await recordRead(c, PaymentsAuditActions.usageRunsRead, null, {
1053
+ returned: page.items.length,
1054
+ resumed: query.cursor !== void 0
1055
+ });
1056
+ return c.json({
1057
+ runs: page.items.map(adminUsageRunView),
1058
+ nextCursor: page.nextCursor
1059
+ }, 200);
1060
+ });
1061
+ /**
969
1062
  * CONTROL PLANE WRITE. Start a reconciliation pass now.
970
1063
  *
971
1064
  * **The counterpart to the read above, and a different power.** Reading the log says whether the nightly
@@ -1090,9 +1183,23 @@ function registerPaymentsRoutes(options) {
1090
1183
  responses: { 200: PaymentsEntitlementsResponse }
1091
1184
  }), requireAuth(), async (c) => {
1092
1185
  const subject = await resolvePaymentsSubject(c, seam);
1093
- if (subject === void 0) return c.json({ entitlements: [] }, 200);
1094
- const entitlements = await resolveEntitlements(paymentsDatabase(database(c)), subject, clock());
1095
- return c.json({ entitlements: entitlements.map(entitlementView) }, 200);
1186
+ const now = clock();
1187
+ const db = subject === void 0 ? void 0 : paymentsDatabase(database(c));
1188
+ const input = await allowanceInputFor(db, config, subject, now);
1189
+ const resolved = resolveAllowances(input);
1190
+ const allowances = {
1191
+ quotas: Object.fromEntries(resolved.quotas.map((entry) => [entry.name, entry.effective.value])),
1192
+ features: Object.fromEntries(resolved.features.map((entry) => [entry.name, entry.effective.value]))
1193
+ };
1194
+ if (subject === void 0 || db === void 0) return c.json({
1195
+ entitlements: [],
1196
+ ...allowances
1197
+ }, 200);
1198
+ const entitlements = await resolveEntitlements(db, subject, now);
1199
+ return c.json({
1200
+ entitlements: entitlements.map(entitlementView),
1201
+ ...allowances
1202
+ }, 200);
1096
1203
  });
1097
1204
  /**
1098
1205
  * AUTHED WRITE. Restore Purchases, client-driven because only the device can enumerate what its store
@@ -1250,6 +1357,7 @@ function registerPaymentsRoutes(options) {
1250
1357
  const handoff = await (await checkoutRail(c, rail)).createCheckoutSession({
1251
1358
  providerProductId: sku,
1252
1359
  subscription: entry.product.type === "subscription",
1360
+ reported: entry.product.billing?.kind === "reported",
1253
1361
  subject,
1254
1362
  providerAccountId: await accountFor(c, rail, subject),
1255
1363
  successUrl: settings.successUrl,
@@ -1500,7 +1608,16 @@ function registerPaymentsRoutes(options) {
1500
1608
  deployment: deploymentName(c)
1501
1609
  });
1502
1610
  if (standing === void 0) return c.json({ subscription: null }, 200);
1503
- return c.json({ subscription: subscriptionView(target.purchase.productId, standing) }, 200);
1611
+ const subscriptionId = target.purchase.originalTransactionId;
1612
+ const last = subscriptionId === null ? void 0 : (await lastReports(database(c), [{
1613
+ rail: target.purchase.rail,
1614
+ providerSubscriptionId: subscriptionId
1615
+ }])).get(`${target.purchase.rail}:${subscriptionId}`);
1616
+ return c.json({ subscription: {
1617
+ ...subscriptionView(target.purchase.productId, standing),
1618
+ reportedQuantity: last?.quantity ?? null,
1619
+ reportedAt: last?.reportedAt.toISOString() ?? null
1620
+ } }, 200);
1504
1621
  });
1505
1622
  /**
1506
1623
  * AUTHED READ — what moving to one catalog product would cost, as the store previews it.
@@ -1974,6 +2091,143 @@ function registerPaymentsRoutes(options) {
1974
2091
  expiresAt: revoked.expiresAt
1975
2092
  }) }, 200);
1976
2093
  });
2094
+ /**
2095
+ * The billing-kind check every override write shares, refused exactly as a grant refuses it. An override
2096
+ * keyed on a kind no read path resolves would shade nobody's numbers and answer 200.
2097
+ */
2098
+ function requireBilledKind(subjectType) {
2099
+ if (subjectType === config.billingSubject) return;
2100
+ throw new ValidationError({
2101
+ message: `This project bills ${config.billingSubject}s, not ${subjectType}s.`,
2102
+ action: "Send `subjectType` as the kind this project bills, or change `billingSubject` in pithy.config.ts.",
2103
+ detail: `An override for a ${subjectType} here writes a row keyed on a kind no read path resolves, so it would shade nobody's allowances and the table would say otherwise.`
2104
+ });
2105
+ }
2106
+ /** What every override write answers. */
2107
+ function overrideResponse(subject, change) {
2108
+ return {
2109
+ ...subject,
2110
+ override: adminOverrideView(change.after),
2111
+ version: overrideVersion(change.after)
2112
+ };
2113
+ }
2114
+ /**
2115
+ * The audit event every override write emits — the subject, the mode, the before and the after, and the
2116
+ * reason verbatim. Severity `warning`, as a comp is: nothing else here changes what a customer may have
2117
+ * with no money moving.
2118
+ */
2119
+ async function emitOverride(c, action, subject, mode, reason, change) {
2120
+ const caller = controlPlaneCaller(c);
2121
+ await c.var.emit({
2122
+ action,
2123
+ outcome: "success",
2124
+ severity: "warning",
2125
+ actorType: "control-plane",
2126
+ actorId: caller.subject,
2127
+ resourceType: "entitlement_override",
2128
+ resourceId: encodeSubjectReference(subject),
2129
+ metadata: {
2130
+ connectionId: caller.connectionId,
2131
+ subjectType: subject.subjectType,
2132
+ subjectId: subject.subjectId,
2133
+ mode,
2134
+ reason,
2135
+ before: adminOverrideView(change.before),
2136
+ after: adminOverrideView(change.after)
2137
+ }
2138
+ });
2139
+ }
2140
+ /**
2141
+ * CONTROL PLANE. Pin a negotiated number or switch for one subject.
2142
+ *
2143
+ * **A merge by name, never a replace.** Only the names sent change; every other pin stands and every name
2144
+ * never pinned keeps tracking the plan, so an upgrade still reaches a customer whose email allowance was
2145
+ * negotiated. **Version-checked**: the body names the version it read, and a set behind the row is
2146
+ * `payments/override_stale` with nothing written. **Bounded**: a number past a declared `overrideMax` is a
2147
+ * 400 naming the limit. **Explained**: `reason` is required and the audit event carries it.
2148
+ *
2149
+ * It does not set `unrestricted`, and a body that tries is a 400 rather than a field quietly dropped:
2150
+ * that is the other route, behind its own scope.
2151
+ */
2152
+ app.post(`${base}/entitlements/overrides`, describeRoute({
2153
+ summary: "Pin quotas and features for one subject.",
2154
+ verification: "control-plane",
2155
+ scopes: [PAYMENTS_OVERRIDE_SET_SCOPE],
2156
+ responses: { 200: PaymentsOverrideResponse }
2157
+ }), requireControlPlane(PAYMENTS_OVERRIDE_SET_SCOPE), validate("json", OverrideSetRequest), async (c) => {
2158
+ const input = c.req.valid("json");
2159
+ requireBilledKind(input.subjectType);
2160
+ const subject = {
2161
+ subjectType: input.subjectType,
2162
+ subjectId: input.subjectId
2163
+ };
2164
+ const change = await setOverride(database(c), config, {
2165
+ subject,
2166
+ version: input.version,
2167
+ reason: input.reason,
2168
+ ...input.quotas ? { quotas: input.quotas } : {},
2169
+ ...input.features ? { features: input.features } : {}
2170
+ }, { now: clock() });
2171
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "patch", input.reason, change);
2172
+ return c.json(overrideResponse(subject, change), 200);
2173
+ });
2174
+ /**
2175
+ * CONTROL PLANE. Grant one subject the whole product, or take it back.
2176
+ *
2177
+ * **Its own route and its own scope**, because it is the largest grant the kit has and the only one whose
2178
+ * reach grows by itself as names are declared: a credential that may raise one email cap must not be able
2179
+ * to do this. Never bounded by `overrideMax` — being unbounded is the point. It grants no entitlement key:
2180
+ * a subject holding nothing is still refused at every gate.
2181
+ */
2182
+ app.post(`${base}/entitlements/overrides/unrestricted`, describeRoute({
2183
+ summary: "Turn unrestricted on or off for one subject.",
2184
+ verification: "control-plane",
2185
+ scopes: [PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE],
2186
+ responses: { 200: PaymentsOverrideResponse }
2187
+ }), requireControlPlane(PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE), validate("json", OverrideUnrestrictedRequest), async (c) => {
2188
+ const input = c.req.valid("json");
2189
+ requireBilledKind(input.subjectType);
2190
+ const subject = {
2191
+ subjectType: input.subjectType,
2192
+ subjectId: input.subjectId
2193
+ };
2194
+ const change = await setUnrestricted(database(c), {
2195
+ subject,
2196
+ version: input.version,
2197
+ reason: input.reason,
2198
+ unrestricted: input.unrestricted
2199
+ }, { now: clock() });
2200
+ await emitOverride(c, PaymentsAuditActions.overrideSet, subject, "unrestricted", input.reason, change);
2201
+ return c.json(overrideResponse(subject, change), 200);
2202
+ });
2203
+ /**
2204
+ * CONTROL PLANE. Unpin names for one subject, or clear its override.
2205
+ *
2206
+ * **Idempotent**: a subject with no override answers 200 with nothing changed — the state the caller asked
2207
+ * for — and writes no audit row, because nothing moved. A name unpinned resolves from the plan again.
2208
+ */
2209
+ app.post(`${base}/entitlements/overrides/clear`, describeRoute({
2210
+ summary: "Unpin allowances for one subject, or clear its override.",
2211
+ verification: "control-plane",
2212
+ scopes: [PAYMENTS_OVERRIDE_CLEAR_SCOPE],
2213
+ responses: { 200: PaymentsOverrideResponse }
2214
+ }), requireControlPlane(PAYMENTS_OVERRIDE_CLEAR_SCOPE), validate("json", OverrideClearRequest), async (c) => {
2215
+ const input = c.req.valid("json");
2216
+ requireBilledKind(input.subjectType);
2217
+ const subject = {
2218
+ subjectType: input.subjectType,
2219
+ subjectId: input.subjectId
2220
+ };
2221
+ const change = await clearOverride(database(c), {
2222
+ subject,
2223
+ ...input.version !== void 0 ? { version: input.version } : {},
2224
+ ...input.quotas ? { quotas: input.quotas } : {},
2225
+ ...input.features ? { features: input.features } : {},
2226
+ ...input.reason ? { reason: input.reason } : {}
2227
+ }, { now: clock() });
2228
+ if (change.before !== void 0) await emitOverride(c, PaymentsAuditActions.overrideCleared, subject, "clear", input.reason ?? null, change);
2229
+ return c.json(overrideResponse(subject, change), 200);
2230
+ });
1977
2231
  };
1978
2232
  /**
1979
2233
  * The webhook handler, once, for every rail.
@@ -303,6 +303,41 @@ export declare const EntitlementRevokeRequest: z.ZodObject<{
303
303
  entitlement: z.ZodString;
304
304
  }, z.core.$strip>;
305
305
  export type EntitlementRevokeRequest = z.output<typeof EntitlementRevokeRequest>;
306
+ export declare const OverrideSetRequest: z.ZodObject<{
307
+ subjectType: z.ZodEnum<{
308
+ organization: "organization";
309
+ user: "user";
310
+ }>;
311
+ subjectId: z.ZodString;
312
+ version: z.ZodNumber;
313
+ reason: z.ZodString;
314
+ quotas: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodNumber>>>;
315
+ features: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
316
+ }, z.core.$strict>;
317
+ export type OverrideSetRequest = z.output<typeof OverrideSetRequest>;
318
+ export declare const OverrideUnrestrictedRequest: z.ZodObject<{
319
+ subjectType: z.ZodEnum<{
320
+ organization: "organization";
321
+ user: "user";
322
+ }>;
323
+ subjectId: z.ZodString;
324
+ version: z.ZodNumber;
325
+ reason: z.ZodString;
326
+ unrestricted: z.ZodBoolean;
327
+ }, z.core.$strict>;
328
+ export type OverrideUnrestrictedRequest = z.output<typeof OverrideUnrestrictedRequest>;
329
+ export declare const OverrideClearRequest: z.ZodObject<{
330
+ subjectType: z.ZodEnum<{
331
+ organization: "organization";
332
+ user: "user";
333
+ }>;
334
+ subjectId: z.ZodString;
335
+ version: z.ZodOptional<z.ZodNumber>;
336
+ reason: z.ZodOptional<z.ZodString>;
337
+ quotas: z.ZodOptional<z.ZodArray<z.ZodString>>;
338
+ features: z.ZodOptional<z.ZodArray<z.ZodString>>;
339
+ }, z.core.$strict>;
340
+ export type OverrideClearRequest = z.output<typeof OverrideClearRequest>;
306
341
  export declare const AdminPurchasesQuery: z.ZodObject<{
307
342
  subjectType: z.ZodOptional<z.ZodEnum<{
308
343
  organization: "organization";
@@ -367,6 +402,20 @@ export declare const AdminEntitlementsQuery: z.ZodObject<{
367
402
  limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
368
403
  }, z.core.$strip>;
369
404
  export type AdminEntitlementsQuery = z.output<typeof AdminEntitlementsQuery>;
405
+ export declare const AdminOverridesQuery: z.ZodObject<{
406
+ subjectType: z.ZodOptional<z.ZodEnum<{
407
+ organization: "organization";
408
+ user: "user";
409
+ }>>;
410
+ subjectId: z.ZodOptional<z.ZodString>;
411
+ unrestricted: z.ZodOptional<z.ZodEnum<{
412
+ false: "false";
413
+ true: "true";
414
+ }>>;
415
+ cursor: z.ZodOptional<z.ZodString>;
416
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
417
+ }, z.core.$strip>;
418
+ export type AdminOverridesQuery = z.output<typeof AdminOverridesQuery>;
370
419
  export declare const AdminReconcileRunsQuery: z.ZodObject<{
371
420
  rail: z.ZodOptional<z.ZodEnum<{
372
421
  apple: "apple";
@@ -383,6 +432,11 @@ export declare const AdminReconcileRunsQuery: z.ZodObject<{
383
432
  limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
384
433
  }, z.core.$strip>;
385
434
  export type AdminReconcileRunsQuery = z.output<typeof AdminReconcileRunsQuery>;
435
+ export declare const AdminUsageRunsQuery: z.ZodObject<{
436
+ cursor: z.ZodOptional<z.ZodString>;
437
+ limit: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
438
+ }, z.core.$strip>;
439
+ export type AdminUsageRunsQuery = z.output<typeof AdminUsageRunsQuery>;
386
440
  /**
387
441
  * The two path segments on the per-subject management read: `…/entitlements/:subjectType/:subjectId`.
388
442
  *
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA6DxB,eAAO,MAAM,kBAAkB;;;;;;;;;iBAa5B,CAAC;AACJ,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEpE,eAAO,MAAM,cAAc;;;;;;;;;iBAaqF,CAAC;AACjH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cA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B;;;;;;;;;;;;iBAW+D,CAAC;AAChG,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEvE,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;iBAWmD,CAAC;AACxF,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAE/E,eAAO,MAAM,mBAAmB;;;iBAEkC,CAAC;AACnE,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEvE;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB;;;;;;iBASgE,CAAC;AAC/F,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEnE;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,iBAAiB;;iBAW8D,CAAC;AAC7F,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { PaymentsHostedRail, PaymentsRail } from "../data/rail.js";
4
4
  import { PaymentsSubject } from "../data/subject.js";
5
+ import { AllowanceName, QuotaValue } from "../config/allowances.js";
5
6
  import { PurchaseStatus } from "../data/status.js";
6
7
  import { PurchaseEnvironment } from "../data/purchase.js";
7
8
  import { SubscriptionCancelTiming } from "../data/subscription.js";
@@ -260,7 +261,7 @@ const PaddleWebhookNotification = z.object({
260
261
  const EntitlementGrantRequest = z.object({
261
262
  subjectType: PaymentsSubject.shape.subjectType.describe("Which kind of holder to grant — the half that makes the id an address. Named, never assumed from the project's `billingSubject`, so what an audit row records is what a management client asked for."),
262
263
  subjectId: PaymentsSubject.shape.subjectId.describe("The subject to grant. Support acts on somebody else's holding, so this is one of the two routes where the subject is a request field rather than the server's own answer."),
263
- entitlement: EntitlementKey.describe("The entitlement key to grant, as gating code names it. Not a store SKU. It must be one this project defines — a key some product grants, or one the adopter declared in `manualEntitlements` — and anything else is a 400 naming the key. Comping a key nothing sells is still the durable case; declaring it is how a project says so."),
264
+ entitlement: EntitlementKey.describe("The entitlement key to grant, as gating code names it. Not a store SKU. It must be one the `entitlements` map declares, and anything else is a 400 naming the key. Comping a key nothing sells is still the durable case; declaring it with no product behind it is how a project says so."),
264
265
  expiresAt: JsonDate.optional().describe("When the grant lapses, as an ISO 8601 timestamp. Omit for a comp that never ends. A past timestamp writes a row that grants nothing, which is a slower way of revoking.")
265
266
  }).describe("A control-plane request to grant one entitlement to one subject, with no purchase behind it.");
266
267
  /**
@@ -276,6 +277,54 @@ const EntitlementRevokeRequest = z.object({
276
277
  entitlement: EntitlementKey.describe("The entitlement key to revoke, as gating code names it.")
277
278
  }).describe("A control-plane request to revoke one entitlement from one subject, effective immediately.");
278
279
  /**
280
+ * ## The override writes
281
+ *
282
+ * Three routes, three scopes, and the split is the security core of them. **Set** pins numbers and switches;
283
+ * **unrestricted** hands a subject the whole product; **clear** removes pins. A credential that may raise one
284
+ * customer's email cap must not, by that fact, be able to hand anybody everything — so `unrestricted` is not a
285
+ * field on the set, and every one of these is a `strictObject`: a set body carrying `unrestricted: true` is a
286
+ * 400, never a field quietly dropped while the caller believes it took.
287
+ *
288
+ * **Both halves of the subject, a version, and on a set a reason.** The version is the one the caller read;
289
+ * a write behind the row is refused as stale. The reason is required because an override is a sentence about a
290
+ * commercial decision, and the audit event records it verbatim.
291
+ *
292
+ * Whether a name is declared, and whether a number is under its ceiling, are config-backed questions and stay
293
+ * in the handler: a schema constrains a value, it never replaces a lookup. What the schema does refuse is the
294
+ * shape — a float, a negative, a string where a quota belongs — as `validation/invalid_input`.
295
+ */
296
+ /** The longest reason a write may carry. A sentence, a ticket number, a contract reference — not a document. */
297
+ const MAX_OVERRIDE_REASON_LENGTH = 500;
298
+ /** The most names one write may carry. Far past any real catalog; bounded because a verified client can still loop. */
299
+ const MAX_OVERRIDE_NAMES = 100;
300
+ const OverrideSubjectType = PaymentsSubject.shape.subjectType.describe("Which kind of holder the override is for. Named, never assumed — and refused when it is not the kind this project bills.");
301
+ const OverrideSubjectId = PaymentsSubject.shape.subjectId.describe("The subject whose allowances this shades.");
302
+ const OverrideVersion = z.number().int().min(0).describe("The override version the caller read — `0` when the subject had none. A write naming a version behind the row is refused with `payments/override_stale` and changes nothing.");
303
+ const OverrideReason = z.string().trim().min(1).max(MAX_OVERRIDE_REASON_LENGTH).describe("Why — a contract, a goodwill credit, a migration. Required, and recorded verbatim on the audit event.");
304
+ const OverrideSetRequest = z.strictObject({
305
+ subjectType: OverrideSubjectType,
306
+ subjectId: OverrideSubjectId,
307
+ version: OverrideVersion,
308
+ reason: OverrideReason,
309
+ quotas: z.record(AllowanceName, QuotaValue).optional().describe("Quotas to pin, by name — a whole number from 0, or null for unlimited. Merged: a name absent here keeps whatever it had."),
310
+ features: z.record(AllowanceName, z.boolean().describe("Whether the switch is on.")).optional().describe("Features to pin, by name. Merged: a name absent here keeps whatever it had.")
311
+ }).refine((body) => Object.keys(body.quotas ?? {}).length + Object.keys(body.features ?? {}).length > 0, { message: "Name at least one quota or feature to pin." }).refine((body) => Object.keys(body.quotas ?? {}).length + Object.keys(body.features ?? {}).length <= MAX_OVERRIDE_NAMES, { message: `Pin at most ${MAX_OVERRIDE_NAMES} names in one write.` }).describe("A control-plane request to pin quotas and features for one subject. A merge by name, version-checked, with a reason.");
312
+ const OverrideUnrestrictedRequest = z.strictObject({
313
+ subjectType: OverrideSubjectType,
314
+ subjectId: OverrideSubjectId,
315
+ version: OverrideVersion,
316
+ reason: OverrideReason,
317
+ unrestricted: z.boolean().describe("True grants every quota unlimited and every feature on, for every name declared now and later, except the names the override pins. False takes it back and leaves the pins.")
318
+ }).describe("A control-plane request to turn `unrestricted` on or off for one subject. Its own route, behind its own scope.");
319
+ const OverrideClearRequest = z.strictObject({
320
+ subjectType: OverrideSubjectType,
321
+ subjectId: OverrideSubjectId,
322
+ version: OverrideVersion.optional().describe("The override version the caller read. Optional: sent, a clear behind the row is refused as stale; omitted, the clear is not checked, which is safe because a clear can only move a subject back toward its plan — unpinning a name on an unrestricted subject is refused."),
323
+ reason: OverrideReason.optional().describe("Why, when the caller says. Recorded on the audit event."),
324
+ quotas: z.array(AllowanceName).max(MAX_OVERRIDE_NAMES).optional().describe("Quota pins to remove. Each resolves from the plan again. Refused on an unrestricted subject, where it would resolve to unlimited."),
325
+ features: z.array(AllowanceName).max(MAX_OVERRIDE_NAMES).optional().describe("Feature pins to remove. Each resolves from the plan again. Refused on an unrestricted subject, where it would resolve to on.")
326
+ }).describe("A control-plane request to unpin names, or — naming neither list — to clear the subject's override entirely, `unrestricted` included. Idempotent: clearing nothing answers 200. A clear never resets the version.");
327
+ /**
279
328
  * ## The management read queries
280
329
  *
281
330
  * The `Admin*` shapes below belong to the **control-plane reads**, which take no bodies at all: there is
@@ -336,12 +385,22 @@ const AdminEntitlementsQuery = z.object({
336
385
  cursor: Cursor,
337
386
  limit: Limit
338
387
  }).refine(subjectFilterIsWhole, SUBJECT_FILTER_RULE).describe("The entitlement query: what to narrow it to, and where to resume.");
388
+ const AdminOverridesQuery = z.object({
389
+ ...SUBJECT_FILTER,
390
+ unrestricted: z.enum(["true", "false"]).optional().describe("`true` lists only the subjects that are `unrestricted` — the largest grant the kit has."),
391
+ cursor: Cursor,
392
+ limit: Limit
393
+ }).refine(subjectFilterIsWhole, SUBJECT_FILTER_RULE).describe("The override listing query: a holder, whether unrestricted, and where to resume.");
339
394
  const AdminReconcileRunsQuery = z.object({
340
395
  rail: PaymentsRail.optional().describe("Restrict to the passes narrowed to one store. A scheduled pass runs against every rail and carries no rail, so this never matches one."),
341
396
  environment: PurchaseEnvironment.optional().describe("Restrict to one store environment — the sandbox host and the production host each keep their own passes."),
342
397
  cursor: Cursor,
343
398
  limit: Limit
344
399
  }).describe("The reconciliation-run query: what to narrow it to, and where to resume.");
400
+ const AdminUsageRunsQuery = z.object({
401
+ cursor: Cursor,
402
+ limit: Limit
403
+ }).describe("The usage-run query: where to resume, and how many.");
345
404
  /**
346
405
  * The two path segments on the per-subject management read: `…/entitlements/:subjectType/:subjectId`.
347
406
  *
@@ -376,4 +435,4 @@ const AdminSubjectParam = z.object({
376
435
  */
377
436
  const PaddleResumeQuery = z.object({ transaction: z.string().refine(isPaddleTransactionId, { message: "Not a Paddle transaction id. Expected the `txn_…` Paddle put in `_ptxn`." }).describe("The Paddle transaction to resume — the `_ptxn` value, `txn_…`. Publishable: Paddle itself put it in a URL it mailed to the buyer.") }).describe("The resume read's query: which transaction a Paddle payment link arrived for.");
378
437
  //#endregion
379
- export { AdminDiscountsQuery, AdminEntitlementsQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest };
438
+ export { AdminDiscountsQuery, AdminEntitlementsQuery, AdminOverridesQuery, AdminPurchasesQuery, AdminReconcileRunsQuery, AdminSubjectParam, AdminSubscriptionsQuery, AdminUsageRunsQuery, AppleWebhookNotification, CheckoutRequest, DiscountCreateRequest, EntitlementGrantRequest, EntitlementRevokeRequest, GoogleWebhookNotification, LemonSqueezyWebhookNotification, OverrideClearRequest, OverrideSetRequest, OverrideUnrestrictedRequest, PaddleResumeQuery, PaddleWebhookNotification, PurchaseSubmission, RestoreRequest, StripeWebhookNotification, SubscriptionCancelRequest, SubscriptionChangeRequest, SubscriptionPreviewRequest };
@@ -130,6 +130,31 @@ export declare const PAYMENTS_RECONCILE_READ_SCOPE: ControlPlaneScope;
130
130
  * a reconciled catalog already matching and writes nothing.
131
131
  */
132
132
  export declare const PAYMENTS_RECONCILE_RUN_SCOPE: ControlPlaneScope;
133
+ /**
134
+ * Pin a number or a switch for one subject — a negotiated email allowance, a goodwill seat. A merge by name,
135
+ * version-checked, with a reason on the record and bounded by any `overrideMax` the catalog declares.
136
+ *
137
+ * **It does not confer `unrestricted`.** A credential that may raise one customer's email cap must not, by
138
+ * that fact, be able to hand anybody the entire product.
139
+ */
140
+ export declare const PAYMENTS_OVERRIDE_SET_SCOPE: ControlPlaneScope;
141
+ /**
142
+ * Turn `unrestricted` on or off for one subject: every quota unlimited and every feature on, for every name
143
+ * declared now and every name declared later. **The largest grant the kit has**, and the only one whose reach
144
+ * grows by itself, which is why it is its own scope and its own route — never a field on the set.
145
+ */
146
+ export declare const PAYMENTS_OVERRIDE_UNRESTRICTED_SCOPE: ControlPlaneScope;
147
+ /**
148
+ * Remove pins from one subject's override, or the whole override. Separate from setting, the way revoke is
149
+ * separate from grant: a tool that tidies up after a contract ends needs to clear and has no business
150
+ * pinning.
151
+ */
152
+ export declare const PAYMENTS_OVERRIDE_CLEAR_SCOPE: ControlPlaneScope;
153
+ /**
154
+ * Read the usage-reporting run log — when each pass ran, what it reported, and which subjects it skipped and
155
+ * why. Its own scope, separate from the reconciliation log's: its findings name subjects.
156
+ */
157
+ export declare const PAYMENTS_USAGE_READ_SCOPE: ControlPlaneScope;
133
158
  /**
134
159
  * Every control-plane scope payments defines — what `pithy dashboard connect` offers for this capability, and
135
160
  * the list a manifest or a doc quotes rather than re-typing. Core's `SEAM_SCOPES` is the same idea for the
@@ -1 +1 @@
1
- {"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../../src/http/scopes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH;;;;;;GAMG;AACH,eAAO,MAAM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