fluentcart-developer 2.3.4 → 3.0.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 (655) hide show
  1. package/dist/cards/fluentcart/tools.d.ts.map +1 -1
  2. package/dist/cards/fluentcart/tools.js +2368 -2323
  3. package/dist/cards/fluentcart/tools.js.map +1 -1
  4. package/dist/paths.d.ts +1 -1
  5. package/dist/paths.d.ts.map +1 -1
  6. package/dist/paths.js +1 -1
  7. package/dist/paths.js.map +1 -1
  8. package/dist/reference-reader.d.ts +32 -1
  9. package/dist/reference-reader.d.ts.map +1 -1
  10. package/dist/reference-reader.js +111 -22
  11. package/dist/reference-reader.js.map +1 -1
  12. package/dist/server.d.ts.map +1 -1
  13. package/dist/server.js +8 -1
  14. package/dist/server.js.map +1 -1
  15. package/dist/skills/fluentcart-developer/SKILL.md +66 -538
  16. package/dist/skills/fluentcart-developer/references/api/authentication.md +452 -0
  17. package/dist/skills/fluentcart-developer/references/api/coupons.md +786 -0
  18. package/dist/skills/fluentcart-developer/references/api/customers.md +889 -0
  19. package/dist/skills/fluentcart-developer/references/api/files.md +609 -0
  20. package/dist/skills/fluentcart-developer/references/api/index.md +432 -0
  21. package/dist/skills/fluentcart-developer/references/api/licensing.md +633 -0
  22. package/dist/skills/fluentcart-developer/references/api/order-bump.md +384 -0
  23. package/dist/skills/fluentcart-developer/references/api/orders.md +814 -0
  24. package/dist/skills/fluentcart-developer/references/api/products.md +866 -0
  25. package/dist/skills/fluentcart-developer/references/api/roles-permissions.md +536 -0
  26. package/dist/skills/fluentcart-developer/references/api/subscriptions.md +827 -0
  27. package/dist/skills/fluentcart-developer/references/database/index.md +44 -0
  28. package/dist/skills/fluentcart-developer/references/database/models/activity.md +178 -0
  29. package/dist/skills/fluentcart-developer/references/database/models/applied-coupon.md +291 -0
  30. package/dist/skills/fluentcart-developer/references/database/models/attribute-group.md +239 -0
  31. package/dist/skills/fluentcart-developer/references/database/models/attribute-relation.md +181 -0
  32. package/dist/skills/fluentcart-developer/references/database/models/attribute-term.md +219 -0
  33. package/dist/skills/fluentcart-developer/references/database/models/cart.md +645 -0
  34. package/dist/skills/fluentcart-developer/references/database/models/coupon.md +427 -0
  35. package/dist/skills/fluentcart-developer/references/database/models/customer-addresses.md +348 -0
  36. package/dist/skills/fluentcart-developer/references/database/models/customer-meta.md +156 -0
  37. package/dist/skills/fluentcart-developer/references/database/models/customer.md +584 -0
  38. package/dist/skills/fluentcart-developer/references/database/models/dynamic-model.md +163 -0
  39. package/dist/skills/fluentcart-developer/references/database/models/label-relationship.md +155 -0
  40. package/dist/skills/fluentcart-developer/references/database/models/label.md +153 -0
  41. package/dist/skills/fluentcart-developer/references/database/models/license-activation.md +182 -0
  42. package/dist/skills/fluentcart-developer/references/database/models/license-meta.md +163 -0
  43. package/dist/skills/fluentcart-developer/references/database/models/license-site.md +208 -0
  44. package/dist/skills/fluentcart-developer/references/database/models/license.md +640 -0
  45. package/dist/skills/fluentcart-developer/references/database/models/meta.md +233 -0
  46. package/dist/skills/fluentcart-developer/references/database/models/order-address.md +391 -0
  47. package/dist/skills/fluentcart-developer/references/database/models/order-download-permission.md +144 -0
  48. package/dist/skills/fluentcart-developer/references/database/models/order-item.md +383 -0
  49. package/dist/skills/fluentcart-developer/references/database/models/order-meta.md +303 -0
  50. package/dist/skills/fluentcart-developer/references/database/models/order-operation.md +158 -0
  51. package/dist/skills/fluentcart-developer/references/database/models/order-promotion-stat.md +175 -0
  52. package/dist/skills/fluentcart-developer/references/database/models/order-promotion.md +250 -0
  53. package/dist/skills/fluentcart-developer/references/database/models/order-tax-rate.md +172 -0
  54. package/dist/skills/fluentcart-developer/references/database/models/order-transaction.md +440 -0
  55. package/dist/skills/fluentcart-developer/references/database/models/order.md +727 -0
  56. package/dist/skills/fluentcart-developer/references/database/models/product-detail.md +397 -0
  57. package/dist/skills/fluentcart-developer/references/database/models/product-download.md +258 -0
  58. package/dist/skills/fluentcart-developer/references/database/models/product-meta.md +153 -0
  59. package/dist/skills/fluentcart-developer/references/database/models/product-variation.md +556 -0
  60. package/dist/skills/fluentcart-developer/references/database/models/product.md +580 -0
  61. package/dist/skills/fluentcart-developer/references/database/models/relationships.md +427 -0
  62. package/dist/skills/fluentcart-developer/references/database/models/scheduled-action.md +175 -0
  63. package/dist/skills/fluentcart-developer/references/database/models/shipping-class.md +148 -0
  64. package/dist/skills/fluentcart-developer/references/database/models/shipping-method.md +280 -0
  65. package/dist/skills/fluentcart-developer/references/database/models/shipping-zone.md +205 -0
  66. package/dist/skills/fluentcart-developer/references/database/models/subscription-meta.md +173 -0
  67. package/dist/skills/fluentcart-developer/references/database/models/subscription.md +528 -0
  68. package/dist/skills/fluentcart-developer/references/database/models/tax-class.md +195 -0
  69. package/dist/skills/fluentcart-developer/references/database/models/tax-rate.md +225 -0
  70. package/dist/skills/fluentcart-developer/references/database/models/user-meta.md +166 -0
  71. package/dist/skills/fluentcart-developer/references/database/models/user.md +220 -0
  72. package/dist/skills/fluentcart-developer/references/database/models.md +404 -0
  73. package/dist/skills/fluentcart-developer/references/database/query-builder.md +860 -0
  74. package/dist/skills/fluentcart-developer/references/database/readme.md +276 -0
  75. package/dist/skills/fluentcart-developer/references/database/schema.md +1002 -0
  76. package/dist/skills/fluentcart-developer/references/engineering/adding-custom-pages-to-the-customer-dashboard.md +395 -0
  77. package/dist/skills/fluentcart-developer/references/engineering/index.md +4 -0
  78. package/dist/skills/fluentcart-developer/references/engineering.md +4 -0
  79. package/dist/skills/fluentcart-developer/references/getting-started.md +249 -0
  80. package/dist/skills/fluentcart-developer/references/guides/frontend.md +519 -0
  81. package/dist/skills/fluentcart-developer/references/guides/index.md +107 -0
  82. package/dist/skills/fluentcart-developer/references/guides/integrations.md +600 -0
  83. package/dist/skills/fluentcart-developer/references/guides/shipping-carrier/index.md +237 -0
  84. package/dist/skills/fluentcart-developer/references/guides/shipping-carrier/labels-and-tracking.md +481 -0
  85. package/dist/skills/fluentcart-developer/references/guides/shipping-carrier/live-rates.md +269 -0
  86. package/dist/skills/fluentcart-developer/references/guides/shipping-carrier/reference.md +223 -0
  87. package/dist/skills/fluentcart-developer/references/guides/shipping-carrier/settings.md +370 -0
  88. package/dist/skills/fluentcart-developer/references/guides/shipping-carrier.md +237 -0
  89. package/dist/skills/fluentcart-developer/references/{subscription-customization.md → guides/subscriptions.md} +57 -37
  90. package/dist/skills/fluentcart-developer/references/hooks/actions/admin-and-templates.md +1079 -0
  91. package/dist/skills/fluentcart-developer/references/hooks/actions/cart-and-checkout.md +1795 -0
  92. package/dist/skills/fluentcart-developer/references/hooks/actions/customers-and-users.md +327 -0
  93. package/dist/skills/fluentcart-developer/references/hooks/actions/licenses.md +829 -0
  94. package/dist/skills/fluentcart-developer/references/hooks/actions/modules.md +81 -0
  95. package/dist/skills/fluentcart-developer/references/hooks/actions/orders.md +757 -0
  96. package/dist/skills/fluentcart-developer/references/hooks/actions/payments-and-integrations.md +1163 -0
  97. package/dist/skills/fluentcart-developer/references/hooks/actions/pro-modules.md +219 -0
  98. package/dist/skills/fluentcart-developer/references/hooks/actions/products-and-coupons.md +1019 -0
  99. package/dist/skills/fluentcart-developer/references/hooks/actions/subscriptions.md +1290 -0
  100. package/dist/skills/fluentcart-developer/references/hooks/actions.md +16 -0
  101. package/dist/skills/fluentcart-developer/references/hooks/deprecated.md +60 -0
  102. package/dist/skills/fluentcart-developer/references/hooks/filters/cart-and-checkout.md +2032 -0
  103. package/dist/skills/fluentcart-developer/references/hooks/filters/customers-and-subscriptions.md +1746 -0
  104. package/dist/skills/fluentcart-developer/references/hooks/filters/integrations-and-advanced.md +2439 -0
  105. package/dist/skills/fluentcart-developer/references/hooks/filters/modules.md +464 -0
  106. package/dist/skills/fluentcart-developer/references/hooks/filters/orders-and-payments.md +2658 -0
  107. package/dist/skills/fluentcart-developer/references/hooks/filters/pro-modules.md +502 -0
  108. package/dist/skills/fluentcart-developer/references/hooks/filters/products-and-pricing.md +1785 -0
  109. package/dist/skills/fluentcart-developer/references/hooks/filters/settings-and-configuration.md +2966 -0
  110. package/dist/skills/fluentcart-developer/references/hooks/filters.md +14 -0
  111. package/dist/skills/fluentcart-developer/references/hooks/index.md +35 -0
  112. package/dist/skills/fluentcart-developer/references/index.md +625 -0
  113. package/dist/skills/fluentcart-developer/references/{fee-system-guide.md → modules/fee-system.md} +38 -60
  114. package/dist/skills/fluentcart-developer/references/{ghost-product-selling.md → modules/ghost-product-selling.md} +71 -89
  115. package/dist/skills/fluentcart-developer/references/modules/index.md +484 -0
  116. package/dist/skills/fluentcart-developer/references/modules/licensing.md +342 -0
  117. package/dist/skills/fluentcart-developer/references/modules/order-bump.md +433 -0
  118. package/dist/skills/fluentcart-developer/references/modules/payment-methods.md +129 -0
  119. package/dist/skills/fluentcart-developer/references/modules/refunds.md +170 -0
  120. package/dist/skills/fluentcart-developer/references/modules/shipping.md +846 -0
  121. package/dist/skills/fluentcart-developer/references/modules/storage.md +986 -0
  122. package/dist/skills/fluentcart-developer/references/modules/subscription-vendor-ids.md +186 -0
  123. package/dist/skills/fluentcart-developer/references/modules/subscriptions.md +678 -0
  124. package/dist/skills/fluentcart-developer/references/payment-methods-integration/index.md +164 -0
  125. package/dist/skills/fluentcart-developer/references/payment-methods-integration/paddle-example.md +1648 -0
  126. package/dist/skills/fluentcart-developer/references/payment-methods-integration/payment/setting/fields.md +353 -0
  127. package/dist/skills/fluentcart-developer/references/payment-methods-integration/quick-implementation.md +1079 -0
  128. package/dist/skills/fluentcart-developer/references/payment-methods-integration.md +164 -0
  129. package/dist/skills/fluentcart-developer/references/restapi/checkout.md +573 -0
  130. package/dist/skills/fluentcart-developer/references/restapi/coupons.md +958 -0
  131. package/dist/skills/fluentcart-developer/references/restapi/customer-profile.md +1423 -0
  132. package/dist/skills/fluentcart-developer/references/{rest-api-customers.md → restapi/customers.md} +406 -424
  133. package/dist/skills/fluentcart-developer/references/restapi/dashboard.md +1083 -0
  134. package/dist/skills/fluentcart-developer/references/restapi/data-export.md +132 -0
  135. package/dist/skills/fluentcart-developer/references/restapi/email-notifications.md +846 -0
  136. package/dist/skills/fluentcart-developer/references/restapi/files.md +313 -0
  137. package/dist/skills/fluentcart-developer/references/restapi/index.md +127 -0
  138. package/dist/skills/fluentcart-developer/references/restapi/integrations.md +1000 -0
  139. package/dist/skills/fluentcart-developer/references/restapi/inventory.md +192 -0
  140. package/dist/skills/fluentcart-developer/references/restapi/labels-and-attributes.md +797 -0
  141. package/dist/skills/fluentcart-developer/references/restapi/licensing.md +1733 -0
  142. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/get-available-shipping-methods.md +30 -0
  143. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/get-checkout-summary.md +28 -0
  144. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/get-country-info.md +29 -0
  145. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/get-order-info.md +28 -0
  146. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/get-shipping-methods-list-view.md +30 -0
  147. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/login.md +66 -0
  148. package/dist/skills/fluentcart-developer/references/restapi/operations/checkout/place-order.md +179 -0
  149. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/apply-coupon.md +83 -0
  150. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/cancel-coupon.md +87 -0
  151. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/check-product-eligibility.md +59 -0
  152. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/create-coupon.md +230 -0
  153. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/delete-coupon.md +29 -0
  154. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/get-coupon-settings.md +20 -0
  155. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/get-coupon.md +27 -0
  156. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/list-coupon-codes.md +20 -0
  157. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/list-coupons.md +37 -0
  158. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/re-apply-coupons.md +75 -0
  159. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/store-coupon-settings.md +40 -0
  160. package/dist/skills/fluentcart-developer/references/restapi/operations/coupons/update-coupon.md +133 -0
  161. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/create-address-checkout.md +138 -0
  162. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/create-profile-address.md +119 -0
  163. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/dashboard-overview.md +22 -0
  164. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/delete-profile-address.md +46 -0
  165. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/get-order-details.md +30 -0
  166. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/get-portal-sections.md +29 -0
  167. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/get-profile-details.md +22 -0
  168. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/get-transaction-billing-address.md +30 -0
  169. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/get-upgrade-paths.md +31 -0
  170. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/list-downloads.md +29 -0
  171. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/list-orders.md +28 -0
  172. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/make-profile-address-primary.md +55 -0
  173. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/pause-subscription.md +29 -0
  174. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/resume-subscription.md +29 -0
  175. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/save-transaction-billing-address.md +92 -0
  176. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/select-address-for-checkout.md +32 -0
  177. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/update-profile-address.md +115 -0
  178. package/dist/skills/fluentcart-developer/references/restapi/operations/customer-profile/update-profile-details.md +69 -0
  179. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/attach-user.md +50 -0
  180. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/bulk-actions.md +65 -0
  181. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/create-address.md +135 -0
  182. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/create-customer.md +108 -0
  183. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/delete-address.md +62 -0
  184. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/detach-user.md +28 -0
  185. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/find-customer-order.md +27 -0
  186. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/get-attachable-users.md +20 -0
  187. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/get-customer-addresses.md +28 -0
  188. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/get-customer-orders.md +37 -0
  189. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/get-customer-stats.md +27 -0
  190. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/get-customer.md +32 -0
  191. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/list-customers.md +37 -0
  192. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/recalculate-ltv.md +28 -0
  193. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/set-primary-address.md +72 -0
  194. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/update-additional-info.md +55 -0
  195. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/update-address.md +144 -0
  196. package/dist/skills/fluentcart-developer/references/restapi/operations/customers/update-customer.md +123 -0
  197. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/attach-note-to-order.md +49 -0
  198. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/create-all-pages.md +21 -0
  199. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/create-single-page.md +55 -0
  200. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/delete-activity.md +28 -0
  201. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-country-info.md +29 -0
  202. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-dashboard-stats.md +22 -0
  203. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-filter-options.md +31 -0
  204. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-onboarding-data.md +20 -0
  205. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-onboarding-settings.md +20 -0
  206. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-print-templates.md +20 -0
  207. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-search-options.md +27 -0
  208. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/get-widgets.md +28 -0
  209. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/initialize-app.md +20 -0
  210. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/list-activities.md +33 -0
  211. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/list-attachments.md +21 -0
  212. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/list-countries.md +20 -0
  213. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/mark-activity-read.md +53 -0
  214. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/run-data-backfills.md +21 -0
  215. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/save-onboarding-settings.md +54 -0
  216. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/save-onboarding-tax-settings.md +73 -0
  217. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/save-print-templates.md +64 -0
  218. package/dist/skills/fluentcart-developer/references/restapi/operations/dashboard/upload-attachment.md +42 -0
  219. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/export-customers-batch.md +129 -0
  220. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/export-licenses-batch.md +133 -0
  221. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/export-orders-batch.md +129 -0
  222. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/export-subscriptions-batch.md +129 -0
  223. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/get-customers-export-schema.md +21 -0
  224. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/get-licenses-export-schema.md +26 -0
  225. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/get-orders-export-schema.md +21 -0
  226. package/dist/skills/fluentcart-developer/references/restapi/operations/data-export/get-subscriptions-export-schema.md +21 -0
  227. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/enable-notification.md +57 -0
  228. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/get-digest-settings.md +22 -0
  229. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/get-notification.md +30 -0
  230. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/get-reminders.md +22 -0
  231. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/get-settings.md +22 -0
  232. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/get-shortcodes.md +22 -0
  233. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/list-notifications.md +20 -0
  234. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/preview-default-template.md +66 -0
  235. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/preview-notification.md +50 -0
  236. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/save-digest-settings.md +101 -0
  237. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/save-reminders.md +162 -0
  238. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/save-settings.md +99 -0
  239. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/send-digest-test.md +47 -0
  240. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/send-manual-reminder.md +51 -0
  241. package/dist/skills/fluentcart-developer/references/restapi/operations/email-notification/update-notification.md +93 -0
  242. package/dist/skills/fluentcart-developer/references/restapi/operations/files/delete-file.md +31 -0
  243. package/dist/skills/fluentcart-developer/references/restapi/operations/files/get-bucket-list.md +28 -0
  244. package/dist/skills/fluentcart-developer/references/restapi/operations/files/list-files.md +30 -0
  245. package/dist/skills/fluentcart-developer/references/restapi/operations/files/upload-editor-file.md +32 -0
  246. package/dist/skills/fluentcart-developer/references/restapi/operations/files/upload-file.md +34 -0
  247. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/chained-data-request.md +46 -0
  248. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/change-feed-status.md +51 -0
  249. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/delete-feed.md +27 -0
  250. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/get-dynamic-options.md +29 -0
  251. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/get-feed-lists.md +27 -0
  252. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/get-feed-settings.md +27 -0
  253. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/get-global-feeds.md +20 -0
  254. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/get-global-settings.md +26 -0
  255. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/install-addon-plugin.md +49 -0
  256. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/list-addons.md +20 -0
  257. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/save-feed-settings.md +52 -0
  258. package/dist/skills/fluentcart-developer/references/restapi/operations/integration/set-global-settings.md +50 -0
  259. package/dist/skills/fluentcart-developer/references/restapi/operations/inventory/bulk-update-stock.md +94 -0
  260. package/dist/skills/fluentcart-developer/references/restapi/operations/inventory/export-inventory.md +81 -0
  261. package/dist/skills/fluentcart-developer/references/restapi/operations/inventory/get-adjustment-history.md +26 -0
  262. package/dist/skills/fluentcart-developer/references/restapi/operations/inventory/get-inventory-stats.md +21 -0
  263. package/dist/skills/fluentcart-developer/references/restapi/operations/inventory/list-inventory.md +33 -0
  264. package/dist/skills/fluentcart-developer/references/restapi/operations/inventory/update-stock.md +75 -0
  265. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/create-attribute-group.md +31 -0
  266. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/create-label.md +31 -0
  267. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/create-terms.md +90 -0
  268. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/delete-attribute-group.md +28 -0
  269. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/delete-attribute-term.md +29 -0
  270. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/get-attribute-group.md +28 -0
  271. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/get-attribute-library.md +20 -0
  272. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/list-attribute-groups.md +32 -0
  273. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/list-attribute-terms.md +33 -0
  274. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/list-labels.md +20 -0
  275. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/reorder-groups.md +51 -0
  276. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/reorder-terms.md +56 -0
  277. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/update-attribute-group.md +37 -0
  278. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/update-attribute-term.md +39 -0
  279. package/dist/skills/fluentcart-developer/references/restapi/operations/labels-attributes/update-label-selections.md +32 -0
  280. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/activate-plugin-license.md +41 -0
  281. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/activate-site-admin.md +60 -0
  282. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/deactivate-plugin-license.md +18 -0
  283. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/deactivate-site-admin.md +67 -0
  284. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/deactivate-site-customer.md +47 -0
  285. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/delete-license.md +24 -0
  286. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/extend-license-validity.md +47 -0
  287. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-customer-license-details.md +25 -0
  288. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-customer-licenses-admin.md +26 -0
  289. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-license-activations.md +25 -0
  290. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-license-details.md +25 -0
  291. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-license-site.md +30 -0
  292. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-plugin-license-status.md +18 -0
  293. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/get-product-license-settings.md +24 -0
  294. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/list-customer-licenses.md +25 -0
  295. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/list-license-sites.md +33 -0
  296. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/list-licenses.md +38 -0
  297. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/public-activate-license.md +54 -0
  298. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/public-check-license.md +26 -0
  299. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/public-deactivate-license.md +46 -0
  300. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/public-download-license-package.md +23 -0
  301. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/public-get-license-version.md +26 -0
  302. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/regenerate-license-key.md +24 -0
  303. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/save-product-license-settings.md +193 -0
  304. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/update-license-activation-limit.md +53 -0
  305. package/dist/skills/fluentcart-developer/references/restapi/operations/licensing/update-license-status.md +52 -0
  306. package/dist/skills/fluentcart-developer/references/restapi/operations/order-bumps/create-order-bump.md +47 -0
  307. package/dist/skills/fluentcart-developer/references/restapi/operations/order-bumps/delete-order-bump.md +25 -0
  308. package/dist/skills/fluentcart-developer/references/restapi/operations/order-bumps/get-order-bump.md +25 -0
  309. package/dist/skills/fluentcart-developer/references/restapi/operations/order-bumps/list-order-bumps.md +29 -0
  310. package/dist/skills/fluentcart-developer/references/restapi/operations/order-bumps/update-order-bump.md +141 -0
  311. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/accept-dispute.md +47 -0
  312. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/bulk-actions.md +72 -0
  313. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/calculate-shipping.md +67 -0
  314. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/calculate-tax.md +98 -0
  315. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/change-customer.md +50 -0
  316. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/charge-now.md +29 -0
  317. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/create-and-change-customer.md +92 -0
  318. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/create-custom-order-item.md +68 -0
  319. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/create-order.md +351 -0
  320. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/create-renewal-now.md +29 -0
  321. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/delete-order.md +28 -0
  322. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/generate-missing-licenses.md +29 -0
  323. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/get-order-transactions.md +27 -0
  324. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/get-order.md +27 -0
  325. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/get-renewal.md +28 -0
  326. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/get-shipping-methods.md +28 -0
  327. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/get-single-transaction.md +28 -0
  328. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/list-order-currencies.md +22 -0
  329. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/list-orders.md +42 -0
  330. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/list-renewals.md +28 -0
  331. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/mark-as-paid.md +61 -0
  332. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/price-order.md +135 -0
  333. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/refund-order.md +72 -0
  334. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/resend-renewal-invoice.md +29 -0
  335. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/skip-renewal.md +48 -0
  336. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/sync-order-statuses.md +28 -0
  337. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/sync-pending-transaction.md +29 -0
  338. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/update-order-address-id.md +60 -0
  339. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/update-order-address.md +98 -0
  340. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/update-order.md +172 -0
  341. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/update-statuses.md +77 -0
  342. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/update-subscription-details.md +84 -0
  343. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/update-transaction-status.md +51 -0
  344. package/dist/skills/fluentcart-developer/references/restapi/operations/orders/void-renewal.md +30 -0
  345. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/create-pdf-template.md +42 -0
  346. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/delete-pdf-template.md +26 -0
  347. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/download-pdf-preview.md +44 -0
  348. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/get-factory-default-templates.md +19 -0
  349. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/get-pdf-status.md +21 -0
  350. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/get-pdf-template.md +26 -0
  351. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/get-saved-templates.md +21 -0
  352. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/get-seller-details.md +19 -0
  353. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/list-pdf-templates.md +19 -0
  354. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/save-pdf-template.md +53 -0
  355. package/dist/skills/fluentcart-developer/references/restapi/operations/pdf-templates/save-seller-details.md +97 -0
  356. package/dist/skills/fluentcart-developer/references/restapi/operations/products/add-product-terms.md +64 -0
  357. package/dist/skills/fluentcart-developer/references/restapi/operations/products/bulk-edit-fetch.md +30 -0
  358. package/dist/skills/fluentcart-developer/references/restapi/operations/products/bulk-insert-products.md +62 -0
  359. package/dist/skills/fluentcart-developer/references/restapi/operations/products/bulk-update-products.md +59 -0
  360. package/dist/skills/fluentcart-developer/references/restapi/operations/products/bulk-update-variants.md +83 -0
  361. package/dist/skills/fluentcart-developer/references/restapi/operations/products/change-integration-status.md +64 -0
  362. package/dist/skills/fluentcart-developer/references/restapi/operations/products/create-dummy-products.md +45 -0
  363. package/dist/skills/fluentcart-developer/references/restapi/operations/products/create-product.md +81 -0
  364. package/dist/skills/fluentcart-developer/references/restapi/operations/products/create-variation.md +181 -0
  365. package/dist/skills/fluentcart-developer/references/restapi/operations/products/delete-downloadable-file.md +27 -0
  366. package/dist/skills/fluentcart-developer/references/restapi/operations/products/delete-product-integration.md +30 -0
  367. package/dist/skills/fluentcart-developer/references/restapi/operations/products/delete-product.md +27 -0
  368. package/dist/skills/fluentcart-developer/references/restapi/operations/products/delete-taxonomy-term.md +55 -0
  369. package/dist/skills/fluentcart-developer/references/restapi/operations/products/delete-upgrade-path.md +27 -0
  370. package/dist/skills/fluentcart-developer/references/restapi/operations/products/delete-variation.md +27 -0
  371. package/dist/skills/fluentcart-developer/references/restapi/operations/products/do-bulk-action.md +56 -0
  372. package/dist/skills/fluentcart-developer/references/restapi/operations/products/duplicate-product.md +56 -0
  373. package/dist/skills/fluentcart-developer/references/restapi/operations/products/fetch-products-by-ids.md +26 -0
  374. package/dist/skills/fluentcart-developer/references/restapi/operations/products/fetch-taxonomy-terms.md +20 -0
  375. package/dist/skills/fluentcart-developer/references/restapi/operations/products/fetch-terms-by-parent.md +60 -0
  376. package/dist/skills/fluentcart-developer/references/restapi/operations/products/fetch-variations-by-ids.md +26 -0
  377. package/dist/skills/fluentcart-developer/references/restapi/operations/products/find-subscription-variants.md +26 -0
  378. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-bundle-info.md +27 -0
  379. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-downloadable-url.md +27 -0
  380. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-max-excerpt-word-count.md +20 -0
  381. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-pricing-widgets.md +27 -0
  382. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-product-integration-feeds.md +29 -0
  383. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-product-integration-settings.md +31 -0
  384. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-product-pricing.md +28 -0
  385. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-product.md +28 -0
  386. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-related-products.md +31 -0
  387. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-upgrade-settings.md +27 -0
  388. package/dist/skills/fluentcart-developer/references/restapi/operations/products/get-variation-upgrade-paths.md +28 -0
  389. package/dist/skills/fluentcart-developer/references/restapi/operations/products/group-bulk-update-variants.md +103 -0
  390. package/dist/skills/fluentcart-developer/references/restapi/operations/products/list-all-variants.md +26 -0
  391. package/dist/skills/fluentcart-developer/references/restapi/operations/products/list-product-variations.md +26 -0
  392. package/dist/skills/fluentcart-developer/references/restapi/operations/products/list-products.md +34 -0
  393. package/dist/skills/fluentcart-developer/references/restapi/operations/products/remove-shipping-class.md +27 -0
  394. package/dist/skills/fluentcart-developer/references/restapi/operations/products/remove-tax-class.md +27 -0
  395. package/dist/skills/fluentcart-developer/references/restapi/operations/products/save-bundle-info.md +56 -0
  396. package/dist/skills/fluentcart-developer/references/restapi/operations/products/save-product-integration.md +62 -0
  397. package/dist/skills/fluentcart-developer/references/restapi/operations/products/save-upgrade-path.md +78 -0
  398. package/dist/skills/fluentcart-developer/references/restapi/operations/products/search-product-variant-options.md +29 -0
  399. package/dist/skills/fluentcart-developer/references/restapi/operations/products/search-products-by-name.md +28 -0
  400. package/dist/skills/fluentcart-developer/references/restapi/operations/products/search-variants-by-name.md +28 -0
  401. package/dist/skills/fluentcart-developer/references/restapi/operations/products/set-variation-media.md +74 -0
  402. package/dist/skills/fluentcart-developer/references/restapi/operations/products/suggest-sku.md +28 -0
  403. package/dist/skills/fluentcart-developer/references/restapi/operations/products/sync-downloadable-files.md +134 -0
  404. package/dist/skills/fluentcart-developer/references/restapi/operations/products/sync-taxonomy-terms.md +61 -0
  405. package/dist/skills/fluentcart-developer/references/restapi/operations/products/toggle-product-tax-exemption.md +56 -0
  406. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-downloadable-file.md +98 -0
  407. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-inventory.md +56 -0
  408. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-long-desc-editor-mode.md +49 -0
  409. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-manage-stock.md +53 -0
  410. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-product-detail.md +58 -0
  411. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-product-pricing.md +225 -0
  412. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-shipping-class.md +49 -0
  413. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-tax-class.md +49 -0
  414. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-upgrade-path.md +78 -0
  415. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-variant-option.md +79 -0
  416. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-variant-tax-exemption.md +56 -0
  417. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-variation-pricing-table.md +49 -0
  418. package/dist/skills/fluentcart-developer/references/restapi/operations/products/update-variation.md +105 -0
  419. package/dist/skills/fluentcart-developer/references/restapi/operations/public-shop/get-product-views.md +34 -0
  420. package/dist/skills/fluentcart-developer/references/restapi/operations/public-shop/list-products.md +42 -0
  421. package/dist/skills/fluentcart-developer/references/restapi/operations/public-shop/search-products.md +30 -0
  422. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/channel-rules.md +24 -0
  423. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/country-heat-map.md +22 -0
  424. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/coupon-overview.md +37 -0
  425. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/coupons.md +36 -0
  426. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/customer-insights.md +31 -0
  427. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/customer-overview.md +36 -0
  428. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/customer-repeat.md +35 -0
  429. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/customer-segment-customers.md +36 -0
  430. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/customer-segments.md +30 -0
  431. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/customer-value.md +34 -0
  432. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/dashboard-stats.md +30 -0
  433. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/failed-orders.md +34 -0
  434. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/fetch-new-vs-returning-customer.md +34 -0
  435. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/fetch-report-by-day-and-hour.md +34 -0
  436. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/fetch-report-meta.md +29 -0
  437. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/fetch-top-sold-products.md +34 -0
  438. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/future-renewals.md +31 -0
  439. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/generate-retention-snapshots.md +24 -0
  440. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/get-overview.md +30 -0
  441. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/get-recent-activities.md +26 -0
  442. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/get-recent-orders.md +20 -0
  443. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/get-revenue.md +37 -0
  444. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/installments-at-risk.md +35 -0
  445. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/installments-variations.md +33 -0
  446. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/installments.md +33 -0
  447. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/item-count-distribution.md +34 -0
  448. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/license-chart.md +30 -0
  449. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/license-pie-chart.md +22 -0
  450. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/license-summary.md +22 -0
  451. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/locations.md +43 -0
  452. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/order-chart.md +37 -0
  453. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/order-completion-time.md +34 -0
  454. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/order-mix.md +34 -0
  455. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/order-value-distribution.md +34 -0
  456. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/payment-methods-disputes.md +38 -0
  457. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/payment-methods-methods.md +36 -0
  458. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/payment-methods.md +37 -0
  459. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/product-comparison-launch.md +33 -0
  460. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/product-comparison.md +40 -0
  461. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/product-detail.md +37 -0
  462. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/product-sales.md +37 -0
  463. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/refunds-overview.md +37 -0
  464. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/retention-snapshots-step.md +45 -0
  465. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/sales-growth-chart.md +35 -0
  466. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/save-channel-rules.md +73 -0
  467. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/source-channels.md +37 -0
  468. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/sources.md +49 -0
  469. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/subscription-cohorts.md +33 -0
  470. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/subscription-health.md +30 -0
  471. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/subscription-rebuys.md +37 -0
  472. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/subscription-retention.md +34 -0
  473. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/subscription-variations.md +22 -0
  474. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/subscriptions-overview.md +37 -0
  475. package/dist/skills/fluentcart-developer/references/restapi/operations/reports/weeks-between-refund.md +34 -0
  476. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/assign-role.md +48 -0
  477. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/delete-role-assignment.md +47 -0
  478. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/get-role.md +25 -0
  479. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/list-managers.md +18 -0
  480. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/list-roles.md +18 -0
  481. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/search-users.md +25 -0
  482. package/dist/skills/fluentcart-developer/references/restapi/operations/roles-permissions/update-role.md +43 -0
  483. package/dist/skills/fluentcart-developer/references/restapi/operations/saved-views/create-saved-view.md +106 -0
  484. package/dist/skills/fluentcart-developer/references/restapi/operations/saved-views/delete-saved-view.md +26 -0
  485. package/dist/skills/fluentcart-developer/references/restapi/operations/saved-views/list-saved-views.md +25 -0
  486. package/dist/skills/fluentcart-developer/references/restapi/operations/saved-views/update-saved-view.md +83 -0
  487. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/activate-payment-addon.md +44 -0
  488. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/activate-plugin-addon.md +44 -0
  489. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/change-storage-driver-status.md +56 -0
  490. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/check-paypal-webhook.md +26 -0
  491. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/create-storage-bucket.md +63 -0
  492. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/disconnect-payment-method.md +55 -0
  493. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/exchange-paypal-seller-auth-token.md +62 -0
  494. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-active-storage-drivers.md +20 -0
  495. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-checkout-fields.md +22 -0
  496. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-email-shortcodes.md +20 -0
  497. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-mcp-config-snippets.md +26 -0
  498. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-mcp-status.md +20 -0
  499. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-module-settings.md +20 -0
  500. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-payment-method-connection-info.md +26 -0
  501. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-payment-method-settings.md +26 -0
  502. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-permissions.md +22 -0
  503. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-plugin-addons.md +20 -0
  504. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-storage-driver-settings.md +27 -0
  505. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/get-store-settings.md +26 -0
  506. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/install-mcp-adapter.md +21 -0
  507. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/install-payment-addon.md +60 -0
  508. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/install-plugin-addon.md +64 -0
  509. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/list-all-payment-methods.md +20 -0
  510. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/list-all-storage-drivers.md +20 -0
  511. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/list-storage-buckets.md +67 -0
  512. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/reorder-payment-methods.md +55 -0
  513. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/reset-storage-driver-settings.md +45 -0
  514. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-checkout-fields.md +133 -0
  515. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-confirmation-settings.md +68 -0
  516. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-module-settings.md +68 -0
  517. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-payment-method-design.md +67 -0
  518. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-payment-method-settings.md +58 -0
  519. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-permissions.md +68 -0
  520. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-storage-driver-settings.md +62 -0
  521. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/save-store-settings.md +239 -0
  522. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/setup-paypal-webhook.md +48 -0
  523. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/toggle-mcp.md +40 -0
  524. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/verify-storage-driver-connection.md +62 -0
  525. package/dist/skills/fluentcart-developer/references/restapi/operations/settings/verify-turnstile-keys.md +55 -0
  526. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/create-shipping-class.md +73 -0
  527. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/create-shipping-method.md +110 -0
  528. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/create-shipping-zone.md +56 -0
  529. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/delete-shipping-class.md +29 -0
  530. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/delete-shipping-method.md +29 -0
  531. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/delete-shipping-zone.md +29 -0
  532. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/get-shipping-class-profile.md +30 -0
  533. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/get-shipping-class.md +29 -0
  534. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/get-shipping-packages.md +22 -0
  535. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/get-shipping-zone.md +27 -0
  536. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/get-zone-countries.md +22 -0
  537. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/get-zone-states.md +28 -0
  538. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/list-shipping-classes.md +31 -0
  539. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/list-shipping-zones.md +31 -0
  540. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/save-shipping-packages.md +112 -0
  541. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/update-shipping-class.md +79 -0
  542. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/update-shipping-method.md +113 -0
  543. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/update-shipping-zone.md +62 -0
  544. package/dist/skills/fluentcart-developer/references/restapi/operations/shipping/update-zone-order.md +52 -0
  545. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/cancel-auto-renew.md +30 -0
  546. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/cancel-subscription.md +52 -0
  547. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/confirm-subscription-switch.md +70 -0
  548. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/fetch-subscription-remote.md +28 -0
  549. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/generate-early-payment-link.md +29 -0
  550. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/get-customer-subscription.md +27 -0
  551. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/get-or-create-plan.md +69 -0
  552. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/get-setup-intent-attempts.md +30 -0
  553. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/get-subscription.md +28 -0
  554. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/initiate-early-payment.md +31 -0
  555. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/list-customer-subscriptions.md +27 -0
  556. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/list-subscriptions.md +39 -0
  557. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/pause-subscription.md +28 -0
  558. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/reactivate-subscription.md +28 -0
  559. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/resume-subscription.md +28 -0
  560. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/switch-payment-method.md +70 -0
  561. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/update-payment-method.md +69 -0
  562. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/update-vendor-ids.md +56 -0
  563. package/dist/skills/fluentcart-developer/references/restapi/operations/subscriptions/verify-vendor-ids.md +56 -0
  564. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/create-tax-class.md +51 -0
  565. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/create-tax-rate.md +117 -0
  566. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/delete-product-override.md +27 -0
  567. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/delete-shipping-tax-override.md +27 -0
  568. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/delete-tax-class.md +28 -0
  569. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/delete-tax-rate.md +27 -0
  570. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-country-tax-id.md +27 -0
  571. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-country-tax-rates.md +28 -0
  572. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-eu-vat-product-overrides.md +20 -0
  573. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-oss-country-rates.md +20 -0
  574. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-preconfigured-tax-rates.md +20 -0
  575. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-product-overrides.md +27 -0
  576. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/get-tax-settings.md +20 -0
  577. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/list-all-tax-rates.md +20 -0
  578. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/list-tax-classes.md +20 -0
  579. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/list-tax-records.md +37 -0
  580. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/mark-taxes-as-filed.md +58 -0
  581. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/reset-eu-vat-rates.md +21 -0
  582. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-configured-countries.md +57 -0
  583. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-country-tax-id.md +50 -0
  584. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-eu-vat-cross-border-settings.md +127 -0
  585. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-oss-country-rates.md +100 -0
  586. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-product-override.md +110 -0
  587. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-shipping-tax-override.md +52 -0
  588. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/save-tax-settings.md +166 -0
  589. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/update-country-status.md +54 -0
  590. package/dist/skills/fluentcart-developer/references/restapi/operations/tax/update-tax-rate.md +116 -0
  591. package/dist/skills/fluentcart-developer/references/restapi/order-bumps.md +433 -0
  592. package/dist/skills/fluentcart-developer/references/{rest-api-orders.md → restapi/orders.md} +146 -396
  593. package/dist/skills/fluentcart-developer/references/restapi/pdf-templates.md +212 -0
  594. package/dist/skills/fluentcart-developer/references/{rest-api-products.md → restapi/products.md} +354 -566
  595. package/dist/skills/fluentcart-developer/references/restapi/public-shop.md +191 -0
  596. package/dist/skills/fluentcart-developer/references/restapi/reports.md +3773 -0
  597. package/dist/skills/fluentcart-developer/references/restapi/roles.md +403 -0
  598. package/dist/skills/fluentcart-developer/references/restapi/saved-views.md +136 -0
  599. package/dist/skills/fluentcart-developer/references/restapi/settings.md +1423 -0
  600. package/dist/skills/fluentcart-developer/references/{rest-api-shipping.md → restapi/shipping.md} +243 -138
  601. package/dist/skills/fluentcart-developer/references/restapi/subscriptions.md +1169 -0
  602. package/dist/skills/fluentcart-developer/references/restapi/tax.md +1551 -0
  603. package/dist/skills/fluentcart-developer/references/restapi.md +127 -0
  604. package/dist/version.d.ts +1 -1
  605. package/dist/version.js +1 -1
  606. package/package.json +1 -1
  607. package/dist/skills/fluentcart-developer/.claude-plugin/plugin.json +0 -12
  608. package/dist/skills/fluentcart-developer/.mcp.json +0 -11
  609. package/dist/skills/fluentcart-developer/references/action-hooks-admin-templates.md +0 -787
  610. package/dist/skills/fluentcart-developer/references/action-hooks-cart-checkout.md +0 -1355
  611. package/dist/skills/fluentcart-developer/references/action-hooks-customers-users.md +0 -266
  612. package/dist/skills/fluentcart-developer/references/action-hooks-licenses.md +0 -855
  613. package/dist/skills/fluentcart-developer/references/action-hooks-orders.md +0 -631
  614. package/dist/skills/fluentcart-developer/references/action-hooks-payments-integrations.md +0 -963
  615. package/dist/skills/fluentcart-developer/references/action-hooks-products-coupons.md +0 -585
  616. package/dist/skills/fluentcart-developer/references/action-hooks-subscriptions.md +0 -661
  617. package/dist/skills/fluentcart-developer/references/customer-dashboard-endpoints.md +0 -169
  618. package/dist/skills/fluentcart-developer/references/database-models-query-builder.md +0 -194
  619. package/dist/skills/fluentcart-developer/references/database-models-reference.md +0 -604
  620. package/dist/skills/fluentcart-developer/references/database-schema-reference.md +0 -947
  621. package/dist/skills/fluentcart-developer/references/engineering-notes.md +0 -154
  622. package/dist/skills/fluentcart-developer/references/filter-hooks-cart-checkout.md +0 -1202
  623. package/dist/skills/fluentcart-developer/references/filter-hooks-customers-subscriptions.md +0 -902
  624. package/dist/skills/fluentcart-developer/references/filter-hooks-integrations-advanced.md +0 -1598
  625. package/dist/skills/fluentcart-developer/references/filter-hooks-orders-payments.md +0 -1319
  626. package/dist/skills/fluentcart-developer/references/filter-hooks-products-pricing.md +0 -628
  627. package/dist/skills/fluentcart-developer/references/filter-hooks-settings-configuration.md +0 -1177
  628. package/dist/skills/fluentcart-developer/references/fluentcart-developer-guide.md +0 -154
  629. package/dist/skills/fluentcart-developer/references/hooks-complete-index.md +0 -834
  630. package/dist/skills/fluentcart-developer/references/models-complete-index.md +0 -912
  631. package/dist/skills/fluentcart-developer/references/modules-and-extensions-reference.md +0 -224
  632. package/dist/skills/fluentcart-developer/references/order-bump-module.md +0 -163
  633. package/dist/skills/fluentcart-developer/references/paddle-gateway-case-study.md +0 -1931
  634. package/dist/skills/fluentcart-developer/references/payment-gateway-integration.md +0 -761
  635. package/dist/skills/fluentcart-developer/references/rest-api-checkout.md +0 -288
  636. package/dist/skills/fluentcart-developer/references/rest-api-coupons.md +0 -801
  637. package/dist/skills/fluentcart-developer/references/rest-api-customer-profile.md +0 -190
  638. package/dist/skills/fluentcart-developer/references/rest-api-dashboard-utilities.md +0 -219
  639. package/dist/skills/fluentcart-developer/references/rest-api-email-notifications.md +0 -619
  640. package/dist/skills/fluentcart-developer/references/rest-api-files.md +0 -290
  641. package/dist/skills/fluentcart-developer/references/rest-api-integrations.md +0 -324
  642. package/dist/skills/fluentcart-developer/references/rest-api-labels-attributes.md +0 -321
  643. package/dist/skills/fluentcart-developer/references/rest-api-licensing.md +0 -174
  644. package/dist/skills/fluentcart-developer/references/rest-api-order-bumps.md +0 -200
  645. package/dist/skills/fluentcart-developer/references/rest-api-overview.md +0 -131
  646. package/dist/skills/fluentcart-developer/references/rest-api-public-shop.md +0 -172
  647. package/dist/skills/fluentcart-developer/references/rest-api-reference.md +0 -552
  648. package/dist/skills/fluentcart-developer/references/rest-api-reports.md +0 -377
  649. package/dist/skills/fluentcart-developer/references/rest-api-roles-permissions.md +0 -147
  650. package/dist/skills/fluentcart-developer/references/rest-api-settings.md +0 -528
  651. package/dist/skills/fluentcart-developer/references/rest-api-subscriptions.md +0 -938
  652. package/dist/skills/fluentcart-developer/references/rest-api-tax.md +0 -356
  653. package/dist/skills/fluentcart-developer/references/shipping-module-guide.md +0 -126
  654. package/dist/skills/fluentcart-developer/references/software-licensing-sdk.md +0 -228
  655. package/dist/skills/fluentcart-developer/references/storage-drivers-module.md +0 -140
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { z } from 'zod';
4
4
  import { skillRefs } from '../../paths.js';
5
- import { listReferences, readReference } from '../../reference-reader.js';
5
+ import { listReferences, readReference, searchReferences } from '../../reference-reader.js';
6
6
  import { nativeClientTemplate } from './templates-native.js';
7
7
  export function registerFluentCartTools(server) {
8
8
  const FC_REFS_DIR = skillRefs('fluentcart-developer');
@@ -75,14 +75,14 @@ export function registerFluentCartTools(server) {
75
75
  try {
76
76
  // Two schema sources: FluentCart core (wp_fct_*) and the Fastr Devices
77
77
  // add-on's own wp_fastr_* tables, which live in no core file.
78
- const schemaFile = path.join(FC_REFS_DIR, 'database-schema-reference.md');
78
+ const schemaFile = path.join(FC_REFS_DIR, 'database', 'schema.md');
79
79
  const addonFile = path.join(FC_REFS_DIR, 'fastr-addon-schema.md');
80
80
  if (!fs.existsSync(schemaFile)) {
81
81
  return { content: [{ type: 'text', text: 'Database schema reference not found.' }], isError: true };
82
82
  }
83
83
  const wanted = table.toLowerCase();
84
84
  let match;
85
- let source = 'database-schema-reference.md';
85
+ let source = 'database/schema.md';
86
86
  for (const file of [schemaFile, addonFile]) {
87
87
  if (!fs.existsSync(file))
88
88
  continue;
@@ -100,7 +100,7 @@ export function registerFluentCartTools(server) {
100
100
  return {
101
101
  content: [{
102
102
  type: 'text',
103
- text: `Table "${table}" not found in database-schema-reference.md or fastr-addon-schema.md. ` +
103
+ text: `Table "${table}" not found in database/schema.md or fastr-addon-schema.md. ` +
104
104
  `The first documents every wp_fct_* table — try the name without the prefix, e.g. "orders", ` +
105
105
  `"order_items", "customer_addresses". The second documents the add-on's wp_fastr_* tables: ` +
106
106
  `fastr_releases, fastr_trial_registry, fastr_usage, fastr_webhooks, fastr_webhook_deliveries. ` +
@@ -169,6 +169,61 @@ export function registerFluentCartTools(server) {
169
169
  };
170
170
  }
171
171
  });
172
+ server.registerTool('fc_search_docs', {
173
+ description: 'Full-text search across all 588 FluentCart documentation pages — the 474 REST API ' +
174
+ 'operations, 49 database models, 22 hook files, modules, guides and payment integration. ' +
175
+ 'Use this when you know the keyword but not which page holds it, then read the hit with ' +
176
+ 'fc_get_reference. Every word in the query must appear on the matching line.',
177
+ inputSchema: {
178
+ query: z
179
+ .string()
180
+ .describe('Words to find, e.g. "void renewal", "tax rate", "order bump", "license activation"'),
181
+ prefix: z
182
+ .string()
183
+ .optional()
184
+ .describe('Restrict to a path prefix: "restapi/", "database/", "hooks/", "modules/"'),
185
+ limit: z
186
+ .number()
187
+ .int()
188
+ .min(1)
189
+ .max(100)
190
+ .default(20)
191
+ .describe('Maximum hits to return (default 20)')
192
+ },
193
+ annotations: { readOnlyHint: true }
194
+ }, async ({ query, prefix, limit }) => {
195
+ try {
196
+ if (!fs.existsSync(FC_REFS_DIR)) {
197
+ return { content: [{ type: 'text', text: 'FluentCart references directory not found.' }], isError: true };
198
+ }
199
+ const { hits, scanned } = searchReferences(FC_REFS_DIR, query, { prefix, limit });
200
+ if (hits.length === 0) {
201
+ return {
202
+ content: [
203
+ { type: 'text', text: `No match for "${query}" across ${scanned} pages${prefix ? ` under ${prefix}` : ''}.` }
204
+ ]
205
+ };
206
+ }
207
+ const body = hits
208
+ .map((h) => `- ${h.file}:${h.line} — ${h.heading}\n ${h.snippet}`)
209
+ .join('\n');
210
+ return {
211
+ content: [
212
+ {
213
+ type: 'text',
214
+ text: `${hits.length} hit(s) for "${query}" across ${scanned} pages.\n\n${body}\n\n` +
215
+ 'Read one with fc_get_reference — pass the path before the colon as "file".'
216
+ }
217
+ ]
218
+ };
219
+ }
220
+ catch (err) {
221
+ return {
222
+ content: [{ type: 'text', text: `Search failed: ${err.message}` }],
223
+ isError: true
224
+ };
225
+ }
226
+ });
172
227
  // ==========================================
173
228
  // Code generation — free like everything else in the suite
174
229
  // ==========================================
@@ -181,48 +236,48 @@ export function registerFluentCartTools(server) {
181
236
  }
182
237
  }, async ({ gatewaySlug, gatewayTitle, supportsSubscriptions }) => {
183
238
  const className = gatewaySlug.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('') + 'Gateway';
184
- const code = `<?php
185
- defined('ABSPATH') || exit;
186
-
187
- use FluentCart\\App\\Services\\Gateways\\AbstractPaymentGateway;
188
- use FluentCart\\App\\Services\\Gateways\\BaseGatewaySettings;
189
-
190
- class ${className} extends AbstractPaymentGateway
191
- {
192
- protected string $gateway = '${gatewaySlug}';
193
- protected string $title = '${gatewayTitle}';
194
-
195
- public function init(): void
196
- {
197
- $this->supports = [
198
- 'products',
199
- 'refunds'${supportsSubscriptions ? ",\n 'subscriptions'" : ''}
200
- ];
201
- }
202
-
203
- public function handlePayment(array $orderData): array
204
- {
205
- // 1. Extract order parameters (order_id, total in cents, customer_email)
206
- $orderId = $orderData['id'];
207
- $amountCents = $orderData['total'];
208
-
209
- // 2. Call external gateway API and obtain session / redirect URL
210
- $redirectUrl = 'https://checkout.example.com/' . $orderId;
211
-
212
- return [
213
- 'status' => 'pending',
214
- 'redirect_url' => $redirectUrl,
215
- 'message' => 'Redirecting to ${gatewayTitle}...'
216
- ];
217
- }
218
-
219
- public function handleWebhook(): void
220
- {
221
- // Verified webhook handler with nonce and payload integrity checks
222
- $payload = file_get_contents('php://input');
223
- // Update FluentCart order via fluent_cart_order_status_updated action
224
- }
225
- }
239
+ const code = `<?php
240
+ defined('ABSPATH') || exit;
241
+
242
+ use FluentCart\\App\\Services\\Gateways\\AbstractPaymentGateway;
243
+ use FluentCart\\App\\Services\\Gateways\\BaseGatewaySettings;
244
+
245
+ class ${className} extends AbstractPaymentGateway
246
+ {
247
+ protected string $gateway = '${gatewaySlug}';
248
+ protected string $title = '${gatewayTitle}';
249
+
250
+ public function init(): void
251
+ {
252
+ $this->supports = [
253
+ 'products',
254
+ 'refunds'${supportsSubscriptions ? ",\n 'subscriptions'" : ''}
255
+ ];
256
+ }
257
+
258
+ public function handlePayment(array $orderData): array
259
+ {
260
+ // 1. Extract order parameters (order_id, total in cents, customer_email)
261
+ $orderId = $orderData['id'];
262
+ $amountCents = $orderData['total'];
263
+
264
+ // 2. Call external gateway API and obtain session / redirect URL
265
+ $redirectUrl = 'https://checkout.example.com/' . $orderId;
266
+
267
+ return [
268
+ 'status' => 'pending',
269
+ 'redirect_url' => $redirectUrl,
270
+ 'message' => 'Redirecting to ${gatewayTitle}...'
271
+ ];
272
+ }
273
+
274
+ public function handleWebhook(): void
275
+ {
276
+ // Verified webhook handler with nonce and payload integrity checks
277
+ $payload = file_get_contents('php://input');
278
+ // Update FluentCart order via fluent_cart_order_status_updated action
279
+ }
280
+ }
226
281
  `;
227
282
  return {
228
283
  content: [{ type: 'text', text: code }]
@@ -242,80 +297,80 @@ class ${className} extends AbstractPaymentGateway
242
297
  const slug = pluginTitle.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
243
298
  const constPrefix = slug.toUpperCase().replace(/-/g, '_');
244
299
  const adminUiCode = includeAdminUi
245
- ? `
246
- // 3. Mount turnkey Admin License Management page
247
- if (is_admin() && class_exists('\\\\${cleanNamespace}\\\\LicenseSettings')) {
248
- $settings = new \\\\${cleanNamespace}\\\\LicenseSettings();
249
- $settings->register($licenseManager);
250
-
251
- $settings->setConfig([
252
- 'title' => __('${pluginTitle} License', '${slug}'),
253
- 'heading' => __('Activate License Key', '${slug}'),
254
- 'description' => __('Enter your FluentCart license key to receive automatic one-click updates and pro features.', '${slug}'),
255
- 'help_text' => __('Manage your active site licenses in your customer portal.', '${slug}')
256
- ]);
257
-
258
- $settings->addPage([
259
- 'type' => 'submenu',
260
- 'parent_slug' => 'tools.php',
261
- 'page_title' => __('${pluginTitle} License', '${slug}'),
262
- 'menu_title' => __('${pluginTitle} License', '${slug}'),
263
- 'capability' => 'manage_options',
264
- 'menu_slug' => '${slug}-license'
265
- ]);
300
+ ? `
301
+ // 3. Mount turnkey Admin License Management page
302
+ if (is_admin() && class_exists('\\\\${cleanNamespace}\\\\LicenseSettings')) {
303
+ $settings = new \\\\${cleanNamespace}\\\\LicenseSettings();
304
+ $settings->register($licenseManager);
305
+
306
+ $settings->setConfig([
307
+ 'title' => __('${pluginTitle} License', '${slug}'),
308
+ 'heading' => __('Activate License Key', '${slug}'),
309
+ 'description' => __('Enter your FluentCart license key to receive automatic one-click updates and pro features.', '${slug}'),
310
+ 'help_text' => __('Manage your active site licenses in your customer portal.', '${slug}')
311
+ ]);
312
+
313
+ $settings->addPage([
314
+ 'type' => 'submenu',
315
+ 'parent_slug' => 'tools.php',
316
+ 'page_title' => __('${pluginTitle} License', '${slug}'),
317
+ 'menu_title' => __('${pluginTitle} License', '${slug}'),
318
+ 'capability' => 'manage_options',
319
+ 'menu_slug' => '${slug}-license'
320
+ ]);
266
321
  }`
267
322
  : '';
268
- const code = `<?php
269
- defined('ABSPATH') || exit;
270
-
271
- /**
272
- * FluentCart Software Licensing SDK Integration Boilerplate
273
- * For: ${pluginTitle}
274
- * Powered by fluent-cart/software-licensing-sdk
275
- */
276
-
277
- define('${constPrefix}_VERSION', '1.0.0');
278
- define('${constPrefix}_DIR', plugin_dir_path(__FILE__));
279
-
280
- add_action('plugins_loaded', function () {
281
- // 1. Include the SDK licensing class
282
- if (!class_exists('\\\\${cleanNamespace}\\\\FluentLicensing')) {
283
- require_once ${constPrefix}_DIR . 'updater/FluentLicensing.php';
284
- }
285
-
286
- $licenseManager = new \\\\${cleanNamespace}\\\\FluentLicensing();
287
-
288
- // 2. Register licensing parameters
289
- $licenseManager->register([
290
- 'version' => ${constPrefix}_VERSION,
291
- 'item_id' => ${itemId},
292
- 'basename' => plugin_basename(__FILE__),
293
- 'api_url' => '${apiUrl}',
294
- 'plugin_title' => '${pluginTitle}',
295
- 'purchase_url' => '${apiUrl}checkout/?item_id=${itemId}',
296
- 'activate_url' => admin_url('tools.php?page=${slug}-license'),
297
- 'show_check_update' => true,
298
- 'settings_key' => '__${slug.replace(/-/g, '_')}_sl_info'
299
- ]);${adminUiCode}
300
- });
301
-
302
- /**
303
- * Helper to check whether the plugin license is currently active.
304
- */
305
- function ${slug.replace(/-/g, '_')}_is_license_active(): bool
306
- {
307
- if (!class_exists('\\\\${cleanNamespace}\\\\FluentLicensing')) {
308
- return false;
309
- }
310
-
311
- $manager = \\\\${cleanNamespace}\\\\FluentLicensing::getInstance();
312
- if (!$manager) {
313
- return false;
314
- }
315
-
316
- $status = $manager->getStatus();
317
- return !is_wp_error($status) && isset($status['status']) && $status['status'] === 'valid';
318
- }
323
+ const code = `<?php
324
+ defined('ABSPATH') || exit;
325
+
326
+ /**
327
+ * FluentCart Software Licensing SDK Integration Boilerplate
328
+ * For: ${pluginTitle}
329
+ * Powered by fluent-cart/software-licensing-sdk
330
+ */
331
+
332
+ define('${constPrefix}_VERSION', '1.0.0');
333
+ define('${constPrefix}_DIR', plugin_dir_path(__FILE__));
334
+
335
+ add_action('plugins_loaded', function () {
336
+ // 1. Include the SDK licensing class
337
+ if (!class_exists('\\\\${cleanNamespace}\\\\FluentLicensing')) {
338
+ require_once ${constPrefix}_DIR . 'updater/FluentLicensing.php';
339
+ }
340
+
341
+ $licenseManager = new \\\\${cleanNamespace}\\\\FluentLicensing();
342
+
343
+ // 2. Register licensing parameters
344
+ $licenseManager->register([
345
+ 'version' => ${constPrefix}_VERSION,
346
+ 'item_id' => ${itemId},
347
+ 'basename' => plugin_basename(__FILE__),
348
+ 'api_url' => '${apiUrl}',
349
+ 'plugin_title' => '${pluginTitle}',
350
+ 'purchase_url' => '${apiUrl}checkout/?item_id=${itemId}',
351
+ 'activate_url' => admin_url('tools.php?page=${slug}-license'),
352
+ 'show_check_update' => true,
353
+ 'settings_key' => '__${slug.replace(/-/g, '_')}_sl_info'
354
+ ]);${adminUiCode}
355
+ });
356
+
357
+ /**
358
+ * Helper to check whether the plugin license is currently active.
359
+ */
360
+ function ${slug.replace(/-/g, '_')}_is_license_active(): bool
361
+ {
362
+ if (!class_exists('\\\\${cleanNamespace}\\\\FluentLicensing')) {
363
+ return false;
364
+ }
365
+
366
+ $manager = \\\\${cleanNamespace}\\\\FluentLicensing::getInstance();
367
+ if (!$manager) {
368
+ return false;
369
+ }
370
+
371
+ $status = $manager->getStatus();
372
+ return !is_wp_error($status) && isset($status['status']) && $status['status'] === 'valid';
373
+ }
319
374
  `;
320
375
  return {
321
376
  content: [{ type: 'text', text: code }]
@@ -335,95 +390,95 @@ function ${slug.replace(/-/g, '_')}_is_license_active(): bool
335
390
  const defaultSvg = iconSvg ||
336
391
  `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M3 4a1 1 0 011-1h12a1 1 0 011 1v2a1 1 0 01-1 1H4a1 1 0 01-1-1V4zM3 10a1 1 0 011-1h12a1 1 0 011 1v6a1 1 0 01-1 1H4a1 1 0 01-1-1v-6z" fill="currentColor"/></svg>`;
337
392
  const subRouteCases = (subRoutes || ['history', 'settings'])
338
- .map((route) => ` case '${route}':
339
- echo '<div class="fct-custom-subpage">';
340
- echo '<h4>' . esc_html__('${route.charAt(0).toUpperCase() + route.slice(1)}', 'my-addon') . '</h4>';
341
- echo '<p>' . esc_html__('Custom content for ${route} sub-route.', 'my-addon') . '</p>';
342
- echo '</div>';
393
+ .map((route) => ` case '${route}':
394
+ echo '<div class="fct-custom-subpage">';
395
+ echo '<h4>' . esc_html__('${route.charAt(0).toUpperCase() + route.slice(1)}', 'my-addon') . '</h4>';
396
+ echo '<p>' . esc_html__('Custom content for ${route} sub-route.', 'my-addon') . '</p>';
397
+ echo '</div>';
343
398
  break;`)
344
399
  .join('\n');
345
- const code = `<?php
346
- defined('ABSPATH') || exit;
347
-
348
- use FluentCart\\Api\\Resource\\CustomerResource;
349
-
350
- /**
351
- * Register Custom Customer Dashboard Tab in FluentCart Vue 3 Portal
352
- * Endpoint: /account/${cleanSlug}
353
- */
354
- add_action('fluent_cart/init', function () {
355
- if (!function_exists('fluent_cart_api')) {
356
- return;
357
- }
358
-
359
- fluent_cart_api()->addCustomerDashboardEndpoint('${cleanSlug}', [
360
- 'title' => __('${tabTitle}', 'my-addon'),
361
- 'icon_svg' => '${defaultSvg.replace(/'/g, "\\'")}',
362
- 'render_callback' => '${funcPrefix}_render_customer_dashboard_tab'
363
- ]);
364
- });
365
-
366
- /**
367
- * Render Callback for Customer Dashboard Tab
368
- * Core wraps this output inside the portal layout shell (nav, header, avatar, logout).
369
- */
370
- function ${funcPrefix}_render_customer_dashboard_tab(): void
371
- {
372
- // 1. Resolve currently authenticated FluentCart customer (memoized, zero-overhead)
373
- $customer = CustomerResource::getCurrentCustomer();
374
- if (!$customer) {
375
- echo '<div class="fct-endpoint-notice">';
376
- echo '<p>' . esc_html__('Please log in to access this page.', 'my-addon') . '</p>';
377
- echo '</div>';
378
- return;
379
- }
380
-
381
- // 2. Parse multi-segment sub-routes from $wp->request
382
- global $wp;
383
- $requestPath = trim($wp->request ?? '', '/');
384
- $segments = explode('/', $requestPath);
385
- // Path structure: {account_slug}/{endpoint_slug}/{sub_action}
386
- $endpointIndex = array_search('${cleanSlug}', $segments, true);
387
- $subAction = ($endpointIndex !== false && isset($segments[$endpointIndex + 1])) ? sanitize_key($segments[$endpointIndex + 1]) : 'index';
388
-
389
- // 3. Render content matching the customer portal design system
390
- ?>
391
- <div class="fct-customer-dashboard-custom-page" style="
392
- color: var(--fct-customer-dashboard-text-color, #374151);
393
- border: 1px solid var(--fct-customer-dashboard-border-color, #e5e7eb);
394
- border-radius: 8px;
395
- padding: 24px;
396
- background: #ffffff;
397
- ">
398
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
399
- <h2 style="margin: 0; color: var(--fct-customer-dashboard-title-color, #111827); font-size: 1.5rem;">
400
- <?php echo esc_html__('${tabTitle}', 'my-addon'); ?>
401
- </h2>
402
- <div class="fct-sub-nav" style="display: flex; gap: 12px;">
403
- <a href="<?php echo esc_url(site_url('/account/${cleanSlug}')); ?>" style="text-decoration: none; font-weight: <?php echo $subAction === 'index' ? '600' : '400'; ?>;">
404
- <?php esc_html_e('Overview', 'my-addon'); ?>
405
- </a>
406
- <a href="<?php echo esc_url(site_url('/account/${cleanSlug}/history')); ?>" style="text-decoration: none; font-weight: <?php echo $subAction === 'history' ? '600' : '400'; ?>;">
407
- <?php esc_html_e('History', 'my-addon'); ?>
408
- </a>
409
- </div>
410
- </div>
411
-
412
- <?php
413
- switch ($subAction) {
414
- ${subRouteCases}
415
- case 'index':
416
- default:
417
- echo '<div class="fct-overview">';
418
- echo '<p>' . esc_html(sprintf(__('Welcome back, %s (%s)!', 'my-addon'), $customer->full_name, $customer->email)) . '</p>';
419
- echo '<!-- Render your customer dashboard widget or shortcode here -->';
420
- echo '</div>';
421
- break;
422
- }
423
- ?>
424
- </div>
425
- <?php
426
- }
400
+ const code = `<?php
401
+ defined('ABSPATH') || exit;
402
+
403
+ use FluentCart\\Api\\Resource\\CustomerResource;
404
+
405
+ /**
406
+ * Register Custom Customer Dashboard Tab in FluentCart Vue 3 Portal
407
+ * Endpoint: /account/${cleanSlug}
408
+ */
409
+ add_action('fluent_cart/init', function () {
410
+ if (!function_exists('fluent_cart_api')) {
411
+ return;
412
+ }
413
+
414
+ fluent_cart_api()->addCustomerDashboardEndpoint('${cleanSlug}', [
415
+ 'title' => __('${tabTitle}', 'my-addon'),
416
+ 'icon_svg' => '${defaultSvg.replace(/'/g, "\\'")}',
417
+ 'render_callback' => '${funcPrefix}_render_customer_dashboard_tab'
418
+ ]);
419
+ });
420
+
421
+ /**
422
+ * Render Callback for Customer Dashboard Tab
423
+ * Core wraps this output inside the portal layout shell (nav, header, avatar, logout).
424
+ */
425
+ function ${funcPrefix}_render_customer_dashboard_tab(): void
426
+ {
427
+ // 1. Resolve currently authenticated FluentCart customer (memoized, zero-overhead)
428
+ $customer = CustomerResource::getCurrentCustomer();
429
+ if (!$customer) {
430
+ echo '<div class="fct-endpoint-notice">';
431
+ echo '<p>' . esc_html__('Please log in to access this page.', 'my-addon') . '</p>';
432
+ echo '</div>';
433
+ return;
434
+ }
435
+
436
+ // 2. Parse multi-segment sub-routes from $wp->request
437
+ global $wp;
438
+ $requestPath = trim($wp->request ?? '', '/');
439
+ $segments = explode('/', $requestPath);
440
+ // Path structure: {account_slug}/{endpoint_slug}/{sub_action}
441
+ $endpointIndex = array_search('${cleanSlug}', $segments, true);
442
+ $subAction = ($endpointIndex !== false && isset($segments[$endpointIndex + 1])) ? sanitize_key($segments[$endpointIndex + 1]) : 'index';
443
+
444
+ // 3. Render content matching the customer portal design system
445
+ ?>
446
+ <div class="fct-customer-dashboard-custom-page" style="
447
+ color: var(--fct-customer-dashboard-text-color, #374151);
448
+ border: 1px solid var(--fct-customer-dashboard-border-color, #e5e7eb);
449
+ border-radius: 8px;
450
+ padding: 24px;
451
+ background: #ffffff;
452
+ ">
453
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
454
+ <h2 style="margin: 0; color: var(--fct-customer-dashboard-title-color, #111827); font-size: 1.5rem;">
455
+ <?php echo esc_html__('${tabTitle}', 'my-addon'); ?>
456
+ </h2>
457
+ <div class="fct-sub-nav" style="display: flex; gap: 12px;">
458
+ <a href="<?php echo esc_url(site_url('/account/${cleanSlug}')); ?>" style="text-decoration: none; font-weight: <?php echo $subAction === 'index' ? '600' : '400'; ?>;">
459
+ <?php esc_html_e('Overview', 'my-addon'); ?>
460
+ </a>
461
+ <a href="<?php echo esc_url(site_url('/account/${cleanSlug}/history')); ?>" style="text-decoration: none; font-weight: <?php echo $subAction === 'history' ? '600' : '400'; ?>;">
462
+ <?php esc_html_e('History', 'my-addon'); ?>
463
+ </a>
464
+ </div>
465
+ </div>
466
+
467
+ <?php
468
+ switch ($subAction) {
469
+ ${subRouteCases}
470
+ case 'index':
471
+ default:
472
+ echo '<div class="fct-overview">';
473
+ echo '<p>' . esc_html(sprintf(__('Welcome back, %s (%s)!', 'my-addon'), $customer->full_name, $customer->email)) . '</p>';
474
+ echo '<!-- Render your customer dashboard widget or shortcode here -->';
475
+ echo '</div>';
476
+ break;
477
+ }
478
+ ?>
479
+ </div>
480
+ <?php
481
+ }
427
482
  `;
428
483
  return {
429
484
  content: [{ type: 'text', text: code }]
@@ -459,809 +514,799 @@ ${subRouteCases}
459
514
  .join('\n')}\n`;
460
515
  let code = '';
461
516
  if (platform === 'tauri_rust') {
462
- code = `${header('Tauri / Rust', 'src/licensing.rs')}
463
- //
464
- // Cargo.toml
465
- // reqwest = { version = "0.12", features = ["blocking", "json"] }
466
- // serde = { version = "1", features = ["derive"] }
467
- // serde_json = "1"
468
- // uuid = { version = "1", features = ["v4"] }
469
- //
470
- // # keyring 3 enables no backend by default. A bare keyring = "3" compiles
471
- // # and even returns Ok from set_password(), but get_password() always
472
- // # answers NoEntry. The device id and the stored licence then never
473
- // # survive a restart: every launch registers a NEW device, which costs a
474
- // # seat, and deactivate() cannot find its own state to give the seat back.
475
- // # Declare the store for each platform you ship.
476
- // [target.'cfg(target_os = "windows")'.dependencies]
477
- // keyring = { version = "3", features = ["windows-native"] }
478
- //
479
- // [target.'cfg(target_os = "macos")'.dependencies]
480
- // keyring = { version = "3", features = ["apple-native"] }
481
- //
482
- // [target.'cfg(target_os = "linux")'.dependencies]
483
- // keyring = { version = "3", features = ["sync-secret-service"] }
484
- //
485
- // All functions are blocking: call them from tauri::async_runtime::spawn_blocking.
486
-
487
- use serde::{Deserialize, Serialize};
488
- use std::collections::HashMap;
489
- use std::time::{SystemTime, UNIX_EPOCH};
490
-
491
- const STORE_URL: &str = "${base}";
492
- const ITEM_ID: u64 = ${productId};
493
- const SERVICE: &str = "${service}";
494
- const ACCOUNT_LICENSE: &str = "license-state";
495
- const ACCOUNT_DEVICE: &str = "device-id";
496
-
497
- /// Tolerance (seconds) for legitimate clock drift between checks. Anything
498
- /// larger than this means the machine's clock was moved, so the cached
499
- /// entitlement is no longer trustworthy.
500
- const CLOCK_TOLERANCE_SECS: i64 = 300;
501
-
502
- #[derive(Serialize, Deserialize, Debug, Clone, Default)]
503
- pub struct LicenseState {
504
- pub license_key: String,
505
- pub device_id: String,
506
- pub status: String,
507
- pub variation_title: String,
508
- pub expires: String,
509
- /// Server clock at the moment of this check — the only time source we trust.
510
- pub server_time_unix: i64,
511
- /// Local clock at that same moment, used to detect a clock that moved back.
512
- pub checked_at_local: i64,
513
- /// Pre-computed by the server so the client never does date math.
514
- pub expires_in_days: Option<i64>,
515
- pub activation_hash: String,
516
- }
517
-
518
- #[derive(Deserialize)]
519
- struct RawResponse {
520
- status: Option<String>,
521
- license_key: Option<String>,
522
- variation_title: Option<String>,
523
- expires: Option<String>,
524
- activation_hash: Option<String>,
525
- server_time_unix: Option<i64>,
526
- expires_in_days: Option<i64>,
527
- message: Option<String>,
528
- }
529
-
530
- fn now_unix() -> i64 {
531
- SystemTime::now()
532
- .duration_since(UNIX_EPOCH)
533
- .map(|d| d.as_secs() as i64)
534
- .unwrap_or(0)
535
- }
536
-
537
- /// A stable per-install identifier, kept in the OS keychain. The UUID is what
538
- /// FluentCart stores as device://<uuid>, so it must survive app restarts.
539
- pub fn device_id() -> Result<String, String> {
540
- let entry = keyring::Entry::new(SERVICE, ACCOUNT_DEVICE).map_err(|e| e.to_string())?;
541
- if let Ok(existing) = entry.get_password() {
542
- if !existing.is_empty() {
543
- return Ok(existing);
544
- }
545
- }
546
- let fresh = format!("device://{}", uuid::Uuid::new_v4());
547
- entry.set_password(&fresh).map_err(|e| e.to_string())?;
548
- Ok(fresh)
549
- }
550
-
551
- pub fn load_state() -> Option<LicenseState> {
552
- let entry = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE).ok()?;
553
- let raw = entry.get_password().ok()?;
554
- serde_json::from_str(&raw).ok()
555
- }
556
-
557
- fn store_state(state: &LicenseState) -> Result<(), String> {
558
- let entry = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE).map_err(|e| e.to_string())?;
559
- entry
560
- .set_password(&serde_json::to_string(state).map_err(|e| e.to_string())?)
561
- .map_err(|e| e.to_string())
562
- }
563
-
564
- fn post(endpoint: &str, params: &[(&str, String)]) -> Result<RawResponse, String> {
565
- let url = format!("{}?fluent-cart={}", STORE_URL, endpoint);
566
- let body: HashMap<&str, String> = params.iter().cloned().collect();
567
-
568
- let client = reqwest::blocking::Client::builder()
569
- .timeout(std::time::Duration::from_secs(15))
570
- .build()
571
- .map_err(|e| e.to_string())?;
572
-
573
- let res = client.post(&url).form(&body).send().map_err(|e| e.to_string())?;
574
- res.json::<RawResponse>().map_err(|e| e.to_string())
575
- }
576
-
577
- pub fn activate(license_key: &str) -> Result<LicenseState, String> {
578
- let device = device_id()?;
579
- let raw = post(
580
- "activate_license",
581
- &[
582
- ("license_key", license_key.trim().to_string()),
583
- ("item_id", ITEM_ID.to_string()),
584
- ("site_url", device.clone()),
585
- // os and arch, not platform: the store folds them into the site's
586
- // platform_version column. A bare platform field is ignored, which
587
- // is how activations end up listed with no operating system at all.
588
- ("os", std::env::consts::OS.to_string()),
589
- ("arch", std::env::consts::ARCH.to_string()),
590
- ("device_type", "Desktop (Tauri)".to_string()),
591
- ("server_version", env!("CARGO_PKG_VERSION").to_string()),
592
- ],
593
- )?;
594
-
595
- let status = raw.status.unwrap_or_default();
596
- if status != "valid" && status != "active" {
597
- return Err(raw.message.unwrap_or_else(|| format!("Activation failed: {}", status)));
598
- }
599
-
600
- let state = LicenseState {
601
- license_key: license_key.trim().to_string(),
602
- device_id: device,
603
- status,
604
- variation_title: raw.variation_title.unwrap_or_default(),
605
- expires: raw.expires.unwrap_or_else(|| "lifetime".into()),
606
- server_time_unix: raw.server_time_unix.unwrap_or_else(now_unix),
607
- checked_at_local: now_unix(),
608
- expires_in_days: raw.expires_in_days,
609
- activation_hash: raw.activation_hash.unwrap_or_default(),
610
- };
611
- store_state(&state)?;
612
- Ok(state)
613
- }
614
-
615
- /// Re-validates against the store. Returns Ok(false) when the license is no
616
- /// longer valid but the call itself worked.
617
- pub fn validate() -> Result<bool, String> {
618
- let mut state = load_state().ok_or("No license stored on this device")?;
619
-
620
- let raw = post(
621
- "check_license",
622
- &[
623
- ("license_key", state.license_key.clone()),
624
- ("item_id", ITEM_ID.to_string()),
625
- ("site_url", state.device_id.clone()),
626
- ],
627
- )?;
628
-
629
- let status = raw.status.unwrap_or_default();
630
- let valid = status == "valid" || status == "active";
631
-
632
- state.status = status;
633
- state.expires = raw.expires.unwrap_or(state.expires);
634
- state.expires_in_days = raw.expires_in_days.or(state.expires_in_days);
635
- state.server_time_unix = raw.server_time_unix.unwrap_or_else(now_unix);
636
- state.checked_at_local = now_unix();
637
- store_state(&state)?;
638
-
639
- Ok(valid)
640
- }
641
-
642
- /// True when the machine's clock has not been moved backwards since the last
643
- /// successful check. A backwards jump is how users try to outlive an expiry.
644
- pub fn clock_is_sane() -> bool {
645
- match load_state() {
646
- Some(state) if state.checked_at_local > 0 => {
647
- let elapsed = now_unix() - state.checked_at_local;
648
- elapsed >= -CLOCK_TOLERANCE_SECS
649
- }
650
- _ => true,
651
- }
652
- }
653
-
654
- /// The entitlement decision the app should gate on. Offline is tolerated for a
655
- /// short grace window, but a tampered clock is not.
656
- pub fn is_licensed() -> bool {
657
- let Some(state) = load_state() else { return false };
658
- if state.status != "valid" && state.status != "active" {
659
- return false;
660
- }
661
- if !clock_is_sane() {
662
- return false;
663
- }
664
- match state.expires_in_days {
665
- // Server-computed remaining days — never derived from the local clock.
666
- Some(days) => days >= 0,
667
- None => true, // lifetime
668
- }
669
- }
670
-
671
- pub fn deactivate() -> Result<(), String> {
672
- let state = load_state().ok_or("No license stored on this device")?;
673
- let _ = post(
674
- "deactivate_license",
675
- &[
676
- ("license_key", state.license_key),
677
- ("item_id", ITEM_ID.to_string()),
678
- ("site_url", state.device_id),
679
- ],
680
- );
681
- if let Ok(entry) = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE) {
682
- let _ = entry.delete_credential();
683
- }
684
- Ok(())
685
- }
686
-
687
- // Tauri wiring (src/main.rs):
688
- // #[tauri::command]
689
- // async fn license_activate(key: String) -> Result<bool, String> {
690
- // tauri::async_runtime::spawn_blocking(move || licensing::activate(&key).map(|_| true))
691
- // .await.map_err(|e| e.to_string())?
692
- // }
517
+ code = `${header('Tauri / Rust', 'src/licensing.rs')}
518
+ //
519
+ // Cargo.toml
520
+ // reqwest = { version = "0.12", features = ["blocking", "json"] }
521
+ // serde = { version = "1", features = ["derive"] }
522
+ // serde_json = "1"
523
+ // uuid = { version = "1", features = ["v4"] }
524
+ //
525
+ // # keyring 3 enables no backend by default. A bare keyring = "3" compiles
526
+ // # and even returns Ok from set_password(), but get_password() always
527
+ // # answers NoEntry. The device id and the stored licence then never
528
+ // # survive a restart: every launch registers a NEW device, which costs a
529
+ // # seat, and deactivate() cannot find its own state to give the seat back.
530
+ // # Declare the store for each platform you ship.
531
+ // [target.'cfg(target_os = "windows")'.dependencies]
532
+ // keyring = { version = "3", features = ["windows-native"] }
533
+ //
534
+ // [target.'cfg(target_os = "macos")'.dependencies]
535
+ // keyring = { version = "3", features = ["apple-native"] }
536
+ //
537
+ // [target.'cfg(target_os = "linux")'.dependencies]
538
+ // keyring = { version = "3", features = ["sync-secret-service"] }
539
+ //
540
+ // All functions are blocking: call them from tauri::async_runtime::spawn_blocking.
541
+
542
+ use serde::{Deserialize, Serialize};
543
+ use std::collections::HashMap;
544
+ use std::time::{SystemTime, UNIX_EPOCH};
545
+
546
+ const STORE_URL: &str = "${base}";
547
+ const ITEM_ID: u64 = ${productId};
548
+ const SERVICE: &str = "${service}";
549
+ const ACCOUNT_LICENSE: &str = "license-state";
550
+ const ACCOUNT_DEVICE: &str = "device-id";
551
+
552
+ /// Tolerance (seconds) for legitimate clock drift between checks. Anything
553
+ /// larger than this means the machine's clock was moved, so the cached
554
+ /// entitlement is no longer trustworthy.
555
+ const CLOCK_TOLERANCE_SECS: i64 = 300;
556
+
557
+ #[derive(Serialize, Deserialize, Debug, Clone, Default)]
558
+ pub struct LicenseState {
559
+ pub license_key: String,
560
+ pub device_id: String,
561
+ pub status: String,
562
+ pub variation_title: String,
563
+ pub expires: String,
564
+ /// Server clock at the moment of this check — the only time source we trust.
565
+ pub server_time_unix: i64,
566
+ /// Local clock at that same moment, used to detect a clock that moved back.
567
+ pub checked_at_local: i64,
568
+ /// Pre-computed by the server so the client never does date math.
569
+ pub expires_in_days: Option<i64>,
570
+ pub activation_hash: String,
571
+ }
572
+
573
+ #[derive(Deserialize)]
574
+ struct RawResponse {
575
+ status: Option<String>,
576
+ license_key: Option<String>,
577
+ variation_title: Option<String>,
578
+ expires: Option<String>,
579
+ activation_hash: Option<String>,
580
+ server_time_unix: Option<i64>,
581
+ expires_in_days: Option<i64>,
582
+ message: Option<String>,
583
+ }
584
+
585
+ fn now_unix() -> i64 {
586
+ SystemTime::now()
587
+ .duration_since(UNIX_EPOCH)
588
+ .map(|d| d.as_secs() as i64)
589
+ .unwrap_or(0)
590
+ }
591
+
592
+ /// A stable per-install identifier, kept in the OS keychain. The UUID is what
593
+ /// FluentCart stores as device://<uuid>, so it must survive app restarts.
594
+ pub fn device_id() -> Result<String, String> {
595
+ let entry = keyring::Entry::new(SERVICE, ACCOUNT_DEVICE).map_err(|e| e.to_string())?;
596
+ if let Ok(existing) = entry.get_password() {
597
+ if !existing.is_empty() {
598
+ return Ok(existing);
599
+ }
600
+ }
601
+ let fresh = format!("device://{}", uuid::Uuid::new_v4());
602
+ entry.set_password(&fresh).map_err(|e| e.to_string())?;
603
+ Ok(fresh)
604
+ }
605
+
606
+ pub fn load_state() -> Option<LicenseState> {
607
+ let entry = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE).ok()?;
608
+ let raw = entry.get_password().ok()?;
609
+ serde_json::from_str(&raw).ok()
610
+ }
611
+
612
+ fn store_state(state: &LicenseState) -> Result<(), String> {
613
+ let entry = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE).map_err(|e| e.to_string())?;
614
+ entry
615
+ .set_password(&serde_json::to_string(state).map_err(|e| e.to_string())?)
616
+ .map_err(|e| e.to_string())
617
+ }
618
+
619
+ fn post(endpoint: &str, params: &[(&str, String)]) -> Result<RawResponse, String> {
620
+ let url = format!("{}?fluent-cart={}", STORE_URL, endpoint);
621
+ let body: HashMap<&str, String> = params.iter().cloned().collect();
622
+
623
+ let client = reqwest::blocking::Client::builder()
624
+ .timeout(std::time::Duration::from_secs(15))
625
+ .build()
626
+ .map_err(|e| e.to_string())?;
627
+
628
+ let res = client.post(&url).form(&body).send().map_err(|e| e.to_string())?;
629
+ res.json::<RawResponse>().map_err(|e| e.to_string())
630
+ }
631
+
632
+ pub fn activate(license_key: &str) -> Result<LicenseState, String> {
633
+ let device = device_id()?;
634
+ let raw = post(
635
+ "activate_license",
636
+ &[
637
+ ("license_key", license_key.trim().to_string()),
638
+ ("item_id", ITEM_ID.to_string()),
639
+ ("site_url", device.clone()),
640
+ ("platform", std::env::consts::OS.to_string()),
641
+ ("server_version", env!("CARGO_PKG_VERSION").to_string()),
642
+ ],
643
+ )?;
644
+
645
+ let status = raw.status.unwrap_or_default();
646
+ if status != "valid" && status != "active" {
647
+ return Err(raw.message.unwrap_or_else(|| format!("Activation failed: {}", status)));
648
+ }
649
+
650
+ let state = LicenseState {
651
+ license_key: license_key.trim().to_string(),
652
+ device_id: device,
653
+ status,
654
+ variation_title: raw.variation_title.unwrap_or_default(),
655
+ expires: raw.expires.unwrap_or_else(|| "lifetime".into()),
656
+ server_time_unix: raw.server_time_unix.unwrap_or_else(now_unix),
657
+ checked_at_local: now_unix(),
658
+ expires_in_days: raw.expires_in_days,
659
+ activation_hash: raw.activation_hash.unwrap_or_default(),
660
+ };
661
+ store_state(&state)?;
662
+ Ok(state)
663
+ }
664
+
665
+ /// Re-validates against the store. Returns Ok(false) when the license is no
666
+ /// longer valid but the call itself worked.
667
+ pub fn validate() -> Result<bool, String> {
668
+ let mut state = load_state().ok_or("No license stored on this device")?;
669
+
670
+ let raw = post(
671
+ "check_license",
672
+ &[
673
+ ("license_key", state.license_key.clone()),
674
+ ("item_id", ITEM_ID.to_string()),
675
+ ("site_url", state.device_id.clone()),
676
+ ],
677
+ )?;
678
+
679
+ let status = raw.status.unwrap_or_default();
680
+ let valid = status == "valid" || status == "active";
681
+
682
+ state.status = status;
683
+ state.expires = raw.expires.unwrap_or(state.expires);
684
+ state.expires_in_days = raw.expires_in_days.or(state.expires_in_days);
685
+ state.server_time_unix = raw.server_time_unix.unwrap_or_else(now_unix);
686
+ state.checked_at_local = now_unix();
687
+ store_state(&state)?;
688
+
689
+ Ok(valid)
690
+ }
691
+
692
+ /// True when the machine's clock has not been moved backwards since the last
693
+ /// successful check. A backwards jump is how users try to outlive an expiry.
694
+ pub fn clock_is_sane() -> bool {
695
+ match load_state() {
696
+ Some(state) if state.checked_at_local > 0 => {
697
+ let elapsed = now_unix() - state.checked_at_local;
698
+ elapsed >= -CLOCK_TOLERANCE_SECS
699
+ }
700
+ _ => true,
701
+ }
702
+ }
703
+
704
+ /// The entitlement decision the app should gate on. Offline is tolerated for a
705
+ /// short grace window, but a tampered clock is not.
706
+ pub fn is_licensed() -> bool {
707
+ let Some(state) = load_state() else { return false };
708
+ if state.status != "valid" && state.status != "active" {
709
+ return false;
710
+ }
711
+ if !clock_is_sane() {
712
+ return false;
713
+ }
714
+ match state.expires_in_days {
715
+ // Server-computed remaining days — never derived from the local clock.
716
+ Some(days) => days >= 0,
717
+ None => true, // lifetime
718
+ }
719
+ }
720
+
721
+ pub fn deactivate() -> Result<(), String> {
722
+ let state = load_state().ok_or("No license stored on this device")?;
723
+ let _ = post(
724
+ "deactivate_license",
725
+ &[
726
+ ("license_key", state.license_key),
727
+ ("item_id", ITEM_ID.to_string()),
728
+ ("site_url", state.device_id),
729
+ ],
730
+ );
731
+ if let Ok(entry) = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE) {
732
+ let _ = entry.delete_credential();
733
+ }
734
+ Ok(())
735
+ }
736
+
737
+ // Tauri wiring (src/main.rs):
738
+ // #[tauri::command]
739
+ // async fn license_activate(key: String) -> Result<bool, String> {
740
+ // tauri::async_runtime::spawn_blocking(move || licensing::activate(&key).map(|_| true))
741
+ // .await.map_err(|e| e.to_string())?
742
+ // }
693
743
  `;
694
744
  }
695
745
  if (platform === 'chrome_extension') {
696
- code = `${header('Chrome MV3 extension', 'background.js')}
697
- //
698
- // manifest.json needs:
699
- // "permissions": ["storage", "alarms"],
700
- // "host_permissions": ["${base}*"],
701
- // "background": { "service_worker": "background.js", "type": "module" }
702
- //
703
- // A service worker is killed after ~30s idle, so nothing may live in a module
704
- // variable. Device id, license state and the last check all live in
705
- // chrome.storage.local, and the 12-hour alarm is what re-checks while asleep.
706
-
707
- const STORE_URL = '${base}';
708
- const ITEM_ID = ${productId};
709
- const KEYS = { device: 'fc_device_id', state: 'fc_license_state' };
710
- const CLOCK_TOLERANCE_MS = 5 * 60 * 1000;
711
- const CHECK_ALARM = 'fc-license-check';
712
-
713
- async function getDeviceId() {
714
- const stored = await chrome.storage.local.get(KEYS.device);
715
- if (stored[KEYS.device]) return stored[KEYS.device];
716
- // randomUUID is available in the MV3 service worker context.
717
- const deviceId = 'device://' + crypto.randomUUID();
718
- await chrome.storage.local.set({ [KEYS.device]: deviceId });
719
- return deviceId;
720
- }
721
-
722
- async function post(endpoint, params) {
723
- const body = new URLSearchParams(params);
724
- const res = await fetch(STORE_URL + '?fluent-cart=' + endpoint, {
725
- method: 'POST',
726
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
727
- body: body.toString(),
728
- });
729
- if (!res.ok) throw new Error('HTTP ' + res.status);
730
- return res.json();
731
- }
732
-
733
- async function saveState(patch) {
734
- const prev = (await chrome.storage.local.get(KEYS.state))[KEYS.state] || {};
735
- const next = Object.assign({}, prev, patch);
736
- await chrome.storage.local.set({ [KEYS.state]: next });
737
- return next;
738
- }
739
-
740
- export async function activate(licenseKey) {
741
- const deviceId = await getDeviceId();
742
- const data = await post('activate_license', {
743
- license_key: licenseKey.trim(),
744
- item_id: String(ITEM_ID),
745
- site_url: deviceId,
746
- platform: 'chrome-extension',
747
- server_version: chrome.runtime.getManifest().version,
748
- });
749
-
750
- const status = data.status || '';
751
- const valid = status === 'valid' || status === 'active';
752
- const state = await saveState({
753
- license_key: licenseKey.trim(),
754
- device_id: deviceId,
755
- status: status,
756
- expires: data.expires || 'lifetime',
757
- expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : null,
758
- server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
759
- checked_at_local: Date.now(),
760
- variation_title: data.variation_title || '',
761
- });
762
-
763
- if (!valid) throw new Error(data.message || 'Activation failed: ' + status);
764
- return state;
765
- }
766
-
767
- export async function validate() {
768
- const stored = await chrome.storage.local.get(KEYS.state);
769
- const state = stored[KEYS.state];
770
- if (!state || !state.license_key) return { valid: false, reason: 'no-license' };
771
-
772
- const data = await post('check_license', {
773
- license_key: state.license_key,
774
- item_id: String(ITEM_ID),
775
- site_url: state.device_id,
776
- });
777
-
778
- const status = data.status || '';
779
- const valid = status === 'valid' || status === 'active';
780
- await saveState({
781
- status: status,
782
- expires: data.expires || state.expires,
783
- expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : state.expires_in_days,
784
- server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
785
- checked_at_local: Date.now(),
786
- });
787
-
788
- return { valid: valid, reason: status };
789
- }
790
-
791
- // The server's clock is the only one that counts. If the machine's clock is
792
- // now behind the moment of the last check by more than the tolerance, it moved.
793
- function clockIsSane(state) {
794
- if (!state || !state.checked_at_local) return true;
795
- return Date.now() - state.checked_at_local >= -CLOCK_TOLERANCE_MS;
796
- }
797
-
798
- export async function isLicensed() {
799
- const stored = await chrome.storage.local.get(KEYS.state);
800
- const state = stored[KEYS.state];
801
- if (!state) return false;
802
- if (state.status !== 'valid' && state.status !== 'active') return false;
803
- if (!clockIsSane(state)) return false;
804
- if (typeof state.expires_in_days === 'number' && state.expires_in_days < 0) return false;
805
- return true;
806
- }
807
-
808
- export async function deactivate() {
809
- const stored = await chrome.storage.local.get(KEYS.state);
810
- const state = stored[KEYS.state];
811
- if (state && state.license_key) {
812
- try {
813
- await post('deactivate_license', {
814
- license_key: state.license_key,
815
- item_id: String(ITEM_ID),
816
- site_url: state.device_id,
817
- });
818
- } catch (e) {
819
- // Deactivation is best-effort: the device is forgotten locally anyway.
820
- }
821
- }
822
- await chrome.storage.local.remove(KEYS.state);
823
- }
824
-
825
- // Re-check every 12 hours, and once whenever the browser starts.
826
- chrome.alarms.create(CHECK_ALARM, { periodInMinutes: 720 });
827
- chrome.alarms.onAlarm.addListener(async (alarm) => {
828
- if (alarm.name !== CHECK_ALARM) return;
829
- try {
830
- await validate();
831
- } catch (e) {
832
- // Offline: keep the cached verdict until the next alarm.
833
- }
834
- });
835
- chrome.runtime.onStartup.addListener(() => { validate().catch(() => {}); });
836
- chrome.runtime.onInstalled.addListener(() => { validate().catch(() => {}); });
837
-
838
- // Popup / options page usage:
839
- // const licensed = await chrome.runtime.sendMessage({ type: 'fc:is-licensed' });
840
- chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
841
- if (msg && msg.type === 'fc:is-licensed') {
842
- isLicensed().then((v) => sendResponse(v));
843
- return true; // keep the channel open for the async reply
844
- }
845
- });
746
+ code = `${header('Chrome MV3 extension', 'background.js')}
747
+ //
748
+ // manifest.json needs:
749
+ // "permissions": ["storage", "alarms"],
750
+ // "host_permissions": ["${base}*"],
751
+ // "background": { "service_worker": "background.js", "type": "module" }
752
+ //
753
+ // A service worker is killed after ~30s idle, so nothing may live in a module
754
+ // variable. Device id, license state and the last check all live in
755
+ // chrome.storage.local, and the 12-hour alarm is what re-checks while asleep.
756
+
757
+ const STORE_URL = '${base}';
758
+ const ITEM_ID = ${productId};
759
+ const KEYS = { device: 'fc_device_id', state: 'fc_license_state' };
760
+ const CLOCK_TOLERANCE_MS = 5 * 60 * 1000;
761
+ const CHECK_ALARM = 'fc-license-check';
762
+
763
+ async function getDeviceId() {
764
+ const stored = await chrome.storage.local.get(KEYS.device);
765
+ if (stored[KEYS.device]) return stored[KEYS.device];
766
+ // randomUUID is available in the MV3 service worker context.
767
+ const deviceId = 'device://' + crypto.randomUUID();
768
+ await chrome.storage.local.set({ [KEYS.device]: deviceId });
769
+ return deviceId;
770
+ }
771
+
772
+ async function post(endpoint, params) {
773
+ const body = new URLSearchParams(params);
774
+ const res = await fetch(STORE_URL + '?fluent-cart=' + endpoint, {
775
+ method: 'POST',
776
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
777
+ body: body.toString(),
778
+ });
779
+ if (!res.ok) throw new Error('HTTP ' + res.status);
780
+ return res.json();
781
+ }
782
+
783
+ async function saveState(patch) {
784
+ const prev = (await chrome.storage.local.get(KEYS.state))[KEYS.state] || {};
785
+ const next = Object.assign({}, prev, patch);
786
+ await chrome.storage.local.set({ [KEYS.state]: next });
787
+ return next;
788
+ }
789
+
790
+ export async function activate(licenseKey) {
791
+ const deviceId = await getDeviceId();
792
+ const data = await post('activate_license', {
793
+ license_key: licenseKey.trim(),
794
+ item_id: String(ITEM_ID),
795
+ site_url: deviceId,
796
+ platform: 'chrome-extension',
797
+ server_version: chrome.runtime.getManifest().version,
798
+ });
799
+
800
+ const status = data.status || '';
801
+ const valid = status === 'valid' || status === 'active';
802
+ const state = await saveState({
803
+ license_key: licenseKey.trim(),
804
+ device_id: deviceId,
805
+ status: status,
806
+ expires: data.expires || 'lifetime',
807
+ expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : null,
808
+ server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
809
+ checked_at_local: Date.now(),
810
+ variation_title: data.variation_title || '',
811
+ });
812
+
813
+ if (!valid) throw new Error(data.message || 'Activation failed: ' + status);
814
+ return state;
815
+ }
816
+
817
+ export async function validate() {
818
+ const stored = await chrome.storage.local.get(KEYS.state);
819
+ const state = stored[KEYS.state];
820
+ if (!state || !state.license_key) return { valid: false, reason: 'no-license' };
821
+
822
+ const data = await post('check_license', {
823
+ license_key: state.license_key,
824
+ item_id: String(ITEM_ID),
825
+ site_url: state.device_id,
826
+ });
827
+
828
+ const status = data.status || '';
829
+ const valid = status === 'valid' || status === 'active';
830
+ await saveState({
831
+ status: status,
832
+ expires: data.expires || state.expires,
833
+ expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : state.expires_in_days,
834
+ server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
835
+ checked_at_local: Date.now(),
836
+ });
837
+
838
+ return { valid: valid, reason: status };
839
+ }
840
+
841
+ // The server's clock is the only one that counts. If the machine's clock is
842
+ // now behind the moment of the last check by more than the tolerance, it moved.
843
+ function clockIsSane(state) {
844
+ if (!state || !state.checked_at_local) return true;
845
+ return Date.now() - state.checked_at_local >= -CLOCK_TOLERANCE_MS;
846
+ }
847
+
848
+ export async function isLicensed() {
849
+ const stored = await chrome.storage.local.get(KEYS.state);
850
+ const state = stored[KEYS.state];
851
+ if (!state) return false;
852
+ if (state.status !== 'valid' && state.status !== 'active') return false;
853
+ if (!clockIsSane(state)) return false;
854
+ if (typeof state.expires_in_days === 'number' && state.expires_in_days < 0) return false;
855
+ return true;
856
+ }
857
+
858
+ export async function deactivate() {
859
+ const stored = await chrome.storage.local.get(KEYS.state);
860
+ const state = stored[KEYS.state];
861
+ if (state && state.license_key) {
862
+ try {
863
+ await post('deactivate_license', {
864
+ license_key: state.license_key,
865
+ item_id: String(ITEM_ID),
866
+ site_url: state.device_id,
867
+ });
868
+ } catch (e) {
869
+ // Deactivation is best-effort: the device is forgotten locally anyway.
870
+ }
871
+ }
872
+ await chrome.storage.local.remove(KEYS.state);
873
+ }
874
+
875
+ // Re-check every 12 hours, and once whenever the browser starts.
876
+ chrome.alarms.create(CHECK_ALARM, { periodInMinutes: 720 });
877
+ chrome.alarms.onAlarm.addListener(async (alarm) => {
878
+ if (alarm.name !== CHECK_ALARM) return;
879
+ try {
880
+ await validate();
881
+ } catch (e) {
882
+ // Offline: keep the cached verdict until the next alarm.
883
+ }
884
+ });
885
+ chrome.runtime.onStartup.addListener(() => { validate().catch(() => {}); });
886
+ chrome.runtime.onInstalled.addListener(() => { validate().catch(() => {}); });
887
+
888
+ // Popup / options page usage:
889
+ // const licensed = await chrome.runtime.sendMessage({ type: 'fc:is-licensed' });
890
+ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
891
+ if (msg && msg.type === 'fc:is-licensed') {
892
+ isLicensed().then((v) => sendResponse(v));
893
+ return true; // keep the channel open for the async reply
894
+ }
895
+ });
846
896
  `;
847
897
  }
848
898
  if (platform === 'python') {
849
- code = `${header('Python (CLI / desktop)', 'licensing.py')}
850
- #
851
- # pip install httpx keyring
852
- #
853
- # Usage:
854
- # python licensing.py activate ABCD-1234-EFGH-5678
855
- # python licensing.py status
856
- # python licensing.py deactivate
857
-
858
- from __future__ import annotations
859
-
860
- import json
861
- import sys
862
- import time
863
- import uuid
864
- from pathlib import Path
865
- from typing import Any, Optional
866
-
867
- import httpx
868
- import keyring
869
-
870
- STORE_URL = "${base}"
871
- ITEM_ID = ${productId}
872
- APP_NAME = "${appName}"
873
- SERVICE = "${service}"
874
- CLOCK_TOLERANCE_SECS = 300
875
- STATE_FILE = Path.home() / ".config" / SERVICE.replace("-", "_") / "license.json"
876
-
877
-
878
- def now_unix() -> int:
879
- return int(time.time())
880
-
881
-
882
- def device_id() -> str:
883
- """Stable per-install id; FluentCart stores it as device://<uuid>."""
884
- existing = keyring.get_password(SERVICE, "device-id")
885
- if existing:
886
- return existing
887
- fresh = f"device://{uuid.uuid4()}"
888
- keyring.set_password(SERVICE, "device-id", fresh)
889
- return fresh
890
-
891
-
892
- def load_state() -> Optional[dict[str, Any]]:
893
- try:
894
- return json.loads(STATE_FILE.read_text(encoding="utf-8"))
895
- except (OSError, ValueError):
896
- return None
897
-
898
-
899
- def save_state(state: dict[str, Any]) -> None:
900
- STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
901
- STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
902
-
903
-
904
- def _post(endpoint: str, params: dict[str, str]) -> dict[str, Any]:
905
- with httpx.Client(timeout=15.0) as client:
906
- res = client.post(f"{STORE_URL}?fluent-cart={endpoint}", data=params)
907
- res.raise_for_status()
908
- return res.json()
909
-
910
-
911
- def activate(license_key: str) -> dict[str, Any]:
912
- data = _post(
913
- "activate_license",
914
- {
915
- "license_key": license_key.strip(),
916
- "item_id": str(ITEM_ID),
917
- "site_url": device_id(),
918
- # os and device_type are what the store persists; a bare platform
919
- # field leaves the device listed without an operating system.
920
- "os": sys.platform,
921
- "device_type": "Python Desktop / CLI",
922
- "server_version": "1.0.0",
923
- },
924
- )
925
- status = str(data.get("status", ""))
926
- if status not in ("valid", "active"):
927
- raise RuntimeError(data.get("message") or f"Activation failed: {status}")
928
-
929
- state = {
930
- "license_key": license_key.strip(),
931
- "device_id": device_id(),
932
- "status": status,
933
- "expires": data.get("expires", "lifetime"),
934
- "expires_in_days": data.get("expires_in_days"),
935
- "server_time_unix": int(data.get("server_time_unix") or now_unix()),
936
- "checked_at_local": now_unix(),
937
- "variation_title": data.get("variation_title", ""),
938
- "activation_hash": data.get("activation_hash", ""),
939
- }
940
- save_state(state)
941
- return state
942
-
943
-
944
- def validate() -> bool:
945
- state = load_state()
946
- if not state:
947
- return False
948
-
949
- data = _post(
950
- "check_license",
951
- {
952
- "license_key": state["license_key"],
953
- "item_id": str(ITEM_ID),
954
- "site_url": state["device_id"],
955
- },
956
- )
957
- status = str(data.get("status", ""))
958
- state.update(
959
- {
960
- "status": status,
961
- "expires": data.get("expires", state.get("expires", "lifetime")),
962
- "expires_in_days": data.get("expires_in_days", state.get("expires_in_days")),
963
- "server_time_unix": int(data.get("server_time_unix") or now_unix()),
964
- "checked_at_local": now_unix(),
965
- }
966
- )
967
- save_state(state)
968
- return status in ("valid", "active")
969
-
970
-
971
- def clock_is_sane(state: Optional[dict[str, Any]]) -> bool:
972
- """Reject a machine whose clock was moved backwards since the last check."""
973
- if not state or not state.get("checked_at_local"):
974
- return True
975
- return now_unix() - int(state["checked_at_local"]) >= -CLOCK_TOLERANCE_SECS
976
-
977
-
978
- def is_licensed() -> bool:
979
- state = load_state()
980
- if not state:
981
- return False
982
- if state.get("status") not in ("valid", "active"):
983
- return False
984
- if not clock_is_sane(state):
985
- return False
986
- days = state.get("expires_in_days")
987
- if isinstance(days, int) and days < 0:
988
- return False
989
- return True
990
-
991
-
992
- def deactivate() -> None:
993
- state = load_state()
994
- if state:
995
- try:
996
- _post(
997
- "deactivate_license",
998
- {
999
- "license_key": state.get("license_key", ""),
1000
- "item_id": str(ITEM_ID),
1001
- "site_url": state.get("device_id", ""),
1002
- },
1003
- )
1004
- except httpx.HTTPError:
1005
- pass # best effort; the device forgets the key regardless
1006
- try:
1007
- STATE_FILE.unlink()
1008
- except OSError:
1009
- pass
1010
-
1011
-
1012
- if __name__ == "__main__":
1013
- cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
1014
- if cmd == "activate":
1015
- if len(sys.argv) < 3:
1016
- sys.exit("usage: python licensing.py activate <license-key>")
1017
- print(json.dumps(activate(sys.argv[2]), indent=2))
1018
- elif cmd == "deactivate":
1019
- deactivate()
1020
- print("deactivated")
1021
- elif cmd == "status":
1022
- print("licensed" if is_licensed() else "not licensed")
1023
- else:
1024
- sys.exit(f"unknown command: {cmd}")
899
+ code = `${header('Python (CLI / desktop)', 'licensing.py')}
900
+ #
901
+ # pip install httpx keyring
902
+ #
903
+ # Usage:
904
+ # python licensing.py activate ABCD-1234-EFGH-5678
905
+ # python licensing.py status
906
+ # python licensing.py deactivate
907
+
908
+ from __future__ import annotations
909
+
910
+ import json
911
+ import sys
912
+ import time
913
+ import uuid
914
+ from pathlib import Path
915
+ from typing import Any, Optional
916
+
917
+ import httpx
918
+ import keyring
919
+
920
+ STORE_URL = "${base}"
921
+ ITEM_ID = ${productId}
922
+ APP_NAME = "${appName}"
923
+ SERVICE = "${service}"
924
+ CLOCK_TOLERANCE_SECS = 300
925
+ STATE_FILE = Path.home() / ".config" / SERVICE.replace("-", "_") / "license.json"
926
+
927
+
928
+ def now_unix() -> int:
929
+ return int(time.time())
930
+
931
+
932
+ def device_id() -> str:
933
+ """Stable per-install id; FluentCart stores it as device://<uuid>."""
934
+ existing = keyring.get_password(SERVICE, "device-id")
935
+ if existing:
936
+ return existing
937
+ fresh = f"device://{uuid.uuid4()}"
938
+ keyring.set_password(SERVICE, "device-id", fresh)
939
+ return fresh
940
+
941
+
942
+ def load_state() -> Optional[dict[str, Any]]:
943
+ try:
944
+ return json.loads(STATE_FILE.read_text(encoding="utf-8"))
945
+ except (OSError, ValueError):
946
+ return None
947
+
948
+
949
+ def save_state(state: dict[str, Any]) -> None:
950
+ STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
951
+ STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
952
+
953
+
954
+ def _post(endpoint: str, params: dict[str, str]) -> dict[str, Any]:
955
+ with httpx.Client(timeout=15.0) as client:
956
+ res = client.post(f"{STORE_URL}?fluent-cart={endpoint}", data=params)
957
+ res.raise_for_status()
958
+ return res.json()
959
+
960
+
961
+ def activate(license_key: str) -> dict[str, Any]:
962
+ data = _post(
963
+ "activate_license",
964
+ {
965
+ "license_key": license_key.strip(),
966
+ "item_id": str(ITEM_ID),
967
+ "site_url": device_id(),
968
+ "platform": sys.platform,
969
+ "server_version": "1.0.0",
970
+ },
971
+ )
972
+ status = str(data.get("status", ""))
973
+ if status not in ("valid", "active"):
974
+ raise RuntimeError(data.get("message") or f"Activation failed: {status}")
975
+
976
+ state = {
977
+ "license_key": license_key.strip(),
978
+ "device_id": device_id(),
979
+ "status": status,
980
+ "expires": data.get("expires", "lifetime"),
981
+ "expires_in_days": data.get("expires_in_days"),
982
+ "server_time_unix": int(data.get("server_time_unix") or now_unix()),
983
+ "checked_at_local": now_unix(),
984
+ "variation_title": data.get("variation_title", ""),
985
+ "activation_hash": data.get("activation_hash", ""),
986
+ }
987
+ save_state(state)
988
+ return state
989
+
990
+
991
+ def validate() -> bool:
992
+ state = load_state()
993
+ if not state:
994
+ return False
995
+
996
+ data = _post(
997
+ "check_license",
998
+ {
999
+ "license_key": state["license_key"],
1000
+ "item_id": str(ITEM_ID),
1001
+ "site_url": state["device_id"],
1002
+ },
1003
+ )
1004
+ status = str(data.get("status", ""))
1005
+ state.update(
1006
+ {
1007
+ "status": status,
1008
+ "expires": data.get("expires", state.get("expires", "lifetime")),
1009
+ "expires_in_days": data.get("expires_in_days", state.get("expires_in_days")),
1010
+ "server_time_unix": int(data.get("server_time_unix") or now_unix()),
1011
+ "checked_at_local": now_unix(),
1012
+ }
1013
+ )
1014
+ save_state(state)
1015
+ return status in ("valid", "active")
1016
+
1017
+
1018
+ def clock_is_sane(state: Optional[dict[str, Any]]) -> bool:
1019
+ """Reject a machine whose clock was moved backwards since the last check."""
1020
+ if not state or not state.get("checked_at_local"):
1021
+ return True
1022
+ return now_unix() - int(state["checked_at_local"]) >= -CLOCK_TOLERANCE_SECS
1023
+
1024
+
1025
+ def is_licensed() -> bool:
1026
+ state = load_state()
1027
+ if not state:
1028
+ return False
1029
+ if state.get("status") not in ("valid", "active"):
1030
+ return False
1031
+ if not clock_is_sane(state):
1032
+ return False
1033
+ days = state.get("expires_in_days")
1034
+ if isinstance(days, int) and days < 0:
1035
+ return False
1036
+ return True
1037
+
1038
+
1039
+ def deactivate() -> None:
1040
+ state = load_state()
1041
+ if state:
1042
+ try:
1043
+ _post(
1044
+ "deactivate_license",
1045
+ {
1046
+ "license_key": state.get("license_key", ""),
1047
+ "item_id": str(ITEM_ID),
1048
+ "site_url": state.get("device_id", ""),
1049
+ },
1050
+ )
1051
+ except httpx.HTTPError:
1052
+ pass # best effort; the device forgets the key regardless
1053
+ try:
1054
+ STATE_FILE.unlink()
1055
+ except OSError:
1056
+ pass
1057
+
1058
+
1059
+ if __name__ == "__main__":
1060
+ cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
1061
+ if cmd == "activate":
1062
+ if len(sys.argv) < 3:
1063
+ sys.exit("usage: python licensing.py activate <license-key>")
1064
+ print(json.dumps(activate(sys.argv[2]), indent=2))
1065
+ elif cmd == "deactivate":
1066
+ deactivate()
1067
+ print("deactivated")
1068
+ elif cmd == "status":
1069
+ print("licensed" if is_licensed() else "not licensed")
1070
+ else:
1071
+ sys.exit(f"unknown command: {cmd}")
1025
1072
  `;
1026
1073
  }
1027
1074
  if (platform === 'cpp_vst') {
1028
- code = `${header('C++ / JUCE (VST3, AU, AAX)', 'LicensingManager.h + .cpp')}
1029
- //
1030
- // Add to your juce_module dependencies: juce_core, juce_data_structures.
1031
- // Enable JUCE_WEB_BROWSER=0 is fine — juce::URL handles the POST itself.
1032
- //
1033
- // ── LicensingManager.h ─────────────────────────────────────────────────────
1034
- #pragma once
1035
-
1036
- #include <JuceHeader.h>
1037
-
1038
- class LicensingManager : public juce::Thread
1039
- {
1040
- public:
1041
- LicensingManager();
1042
- ~LicensingManager() override;
1043
-
1044
- /** Kicks off a background check. Never blocks the audio thread. */
1045
- void refreshAsync();
1046
-
1047
- /** Cached verdict, safe to read from the message/audio thread. */
1048
- bool isLicensed() const;
1049
-
1050
- juce::String getStatusText() const;
1051
- juce::String getExpiryText() const;
1052
-
1053
- void activate (const juce::String& licenseKey);
1054
- void deactivate();
1055
-
1056
- /** Fired on the message thread whenever the verdict changes. */
1057
- std::function<void (bool licensed)> onLicenseChanged;
1058
-
1059
- private:
1060
- void run() override;
1061
- void setState (const juce::var& json);
1062
- juce::var post (const juce::String& endpoint,
1063
- const juce::StringPairArray& params);
1064
-
1065
- static juce::String deviceId();
1066
-
1067
- juce::CriticalSection lock;
1068
- bool licensed = false;
1069
- juce::String statusText { "unlicensed" };
1070
- juce::String expiryText;
1071
- std::unique_ptr<juce::PropertiesFile> props;
1072
- };
1073
-
1074
- // ── LicensingManager.cpp ───────────────────────────────────────────────────
1075
- #include "LicensingManager.h"
1076
-
1077
- namespace
1078
- {
1079
- constexpr const char* kStoreUrl = "${base}";
1080
- constexpr int kItemId = ${productId};
1081
- constexpr juce::int64 kClockToleranceMs = 5 * 60 * 1000;
1082
-
1083
- juce::PropertiesFile::Options optionsFor (const juce::String& appName)
1084
- {
1085
- juce::PropertiesFile::Options o;
1086
- o.applicationName = appName;
1087
- o.filenameSuffix = ".licence";
1088
- o.osxLibrarySubFolder = "Application Support";
1089
- return o;
1090
- }
1091
- }
1092
-
1093
- LicensingManager::LicensingManager()
1094
- : juce::Thread ("FluentCart licensing"),
1095
- props (new juce::PropertiesFile (
1096
- optionsFor ("${service}"),
1097
- juce::PropertiesFile::storeAsXML))
1098
- {
1099
- }
1100
-
1101
- LicensingManager::~LicensingManager() { stopThread (3000); }
1102
-
1103
- juce::String LicensingManager::deviceId()
1104
- {
1105
- auto& p = *juce::PropertiesFile::createDefaultAppPropertiesFile (
1106
- "${service}", ".licence", "Application Support", true);
1107
- auto existing = p.getValue ("fc_device_id");
1108
- if (existing.isNotEmpty())
1109
- return existing;
1110
-
1111
- auto fresh = "device://" + juce::Uuid().toString();
1112
- p.setValue ("fc_device_id", fresh);
1113
- p.saveIfNeeded();
1114
- return fresh;
1115
- }
1116
-
1117
- juce::var LicensingManager::post (const juce::String& endpoint,
1118
- const juce::StringPairArray& params)
1119
- {
1120
- juce::String body;
1121
- for (int i = 0; i < params.size(); ++i)
1122
- body << (i ? "&" : "")
1123
- << juce::URL::addEscapeChars (params.getAllKeys()[i], false) << "="
1124
- << juce::URL::addEscapeChars (params.getAllValues()[i], false);
1125
-
1126
- juce::URL url (juce::String (kStoreUrl) + "?fluent-cart=" + endpoint);
1127
- url = url.withPOSTData (body);
1128
-
1129
- int statusCode = 0;
1130
- auto stream = url.createInputStream (
1131
- juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
1132
- .withConnectionTimeoutMs (15000)
1133
- .withExtraHeaders ("Content-Type: application/x-www-form-urlencoded")
1134
- .withStatusCode (&statusCode));
1135
-
1136
- if (stream == nullptr)
1137
- return {};
1138
-
1139
- return juce::JSON::parse (stream->readEntireStreamAsString());
1140
- }
1141
-
1142
- void LicensingManager::setState (const juce::var& json)
1143
- {
1144
- auto* obj = json.getDynamicObject();
1145
- if (obj == nullptr)
1146
- return;
1147
-
1148
- auto status = obj->getProperty ("status").toString();
1149
- auto valid = (status == "valid" || status == "active");
1150
-
1151
- // The server's clock is authoritative. Remember the matching local time so
1152
- // a clock moved backwards between checks can be detected.
1153
- auto serverTime = (juce::int64) (double) obj->getProperty ("server_time_unix");
1154
-
1155
- {
1156
- const juce::ScopedLock sl (lock);
1157
- licensed = valid;
1158
- statusText = status.isNotEmpty() ? status : "unknown";
1159
- expiryText = obj->getProperty ("expires").toString();
1160
- }
1161
-
1162
- if (serverTime > 0)
1163
- props->setValue ("fc_server_time", juce::String (serverTime));
1164
- props->setValue ("fc_checked_at_local", juce::String (juce::Time::currentTimeMillis()));
1165
- props->saveIfNeeded();
1166
-
1167
- auto changed = onLicenseChanged;
1168
- if (changed != nullptr)
1169
- juce::MessageManager::callAsync ([changed, valid] { changed (valid); });
1170
- }
1171
-
1172
- bool LicensingManager::isLicensed() const
1173
- {
1174
- const juce::ScopedLock sl (lock);
1175
- if (! licensed)
1176
- return false;
1177
-
1178
- // Pre-computed by the server; the client never does date math.
1179
- auto days = props->getIntValue ("fc_expires_in_days", -1);
1180
- if (days >= 0 && days == 0)
1181
- return false;
1182
-
1183
- auto checkedAt = props->getValue ("fc_checked_at_local").getLargeIntValue();
1184
- if (checkedAt > 0 && juce::Time::currentTimeMillis() - checkedAt < -kClockToleranceMs)
1185
- return false; // clock moved backwards — treat as tampered
1186
-
1187
- return true;
1188
- }
1189
-
1190
- juce::String LicensingManager::getStatusText() const
1191
- {
1192
- const juce::ScopedLock sl (lock);
1193
- return statusText;
1194
- }
1195
-
1196
- juce::String LicensingManager::getExpiryText() const
1197
- {
1198
- const juce::ScopedLock sl (lock);
1199
- return expiryText;
1200
- }
1201
-
1202
- void LicensingManager::refreshAsync()
1203
- {
1204
- if (! isThreadRunning())
1205
- startThread();
1206
- }
1207
-
1208
- void LicensingManager::run()
1209
- {
1210
- auto& p = *props;
1211
- auto key = p.getValue ("fc_license_key");
1212
- if (key.isEmpty())
1213
- return;
1214
-
1215
- juce::StringPairArray params;
1216
- params.set ("license_key", key);
1217
- params.set ("item_id", juce::String (kItemId));
1218
- params.set ("site_url", p.getValue ("fc_device_id"));
1219
-
1220
- setState (post ("check_license", params));
1221
- }
1222
-
1223
- void LicensingManager::activate (const juce::String& licenseKey)
1224
- {
1225
- juce::StringPairArray params;
1226
- params.set ("license_key", licenseKey.trim());
1227
- params.set ("item_id", juce::String (kItemId));
1228
- params.set ("site_url", deviceId());
1229
- // os, not platform: the store reads os/arch to fill platform_version.
1230
- params.set ("os", juce::SystemStats::getOperatingSystemName());
1231
- params.set ("device_type", "Audio Plugin (JUCE)");
1232
-
1233
- auto json = post ("activate_license", params);
1234
- auto* obj = json.getDynamicObject();
1235
- if (obj != nullptr)
1236
- {
1237
- props->setValue ("fc_license_key", licenseKey.trim());
1238
- props->setValue ("fc_expires_in_days",
1239
- juce::String ((int) (double) obj->getProperty ("expires_in_days")));
1240
- }
1241
- setState (json);
1242
- props->saveIfNeeded();
1243
- }
1244
-
1245
- void LicensingManager::deactivate()
1246
- {
1247
- juce::StringPairArray params;
1248
- params.set ("license_key", props->getValue ("fc_license_key"));
1249
- params.set ("item_id", juce::String (kItemId));
1250
- params.set ("site_url", props->getValue ("fc_device_id"));
1251
- post ("deactivate_license", params);
1252
-
1253
- props->removeValue ("fc_license_key");
1254
- props->saveIfNeeded();
1255
-
1256
- const juce::ScopedLock sl (lock);
1257
- licensed = false;
1258
- statusText = "unlicensed";
1259
- }
1260
-
1261
- // In your AudioProcessor constructor:
1262
- // licensing.refreshAsync(); // background thread, no UI stall
1263
- // Never call isLicensed() from the audio callback — cache it on the message
1264
- // thread and read an atomic in processBlock().
1075
+ code = `${header('C++ / JUCE (VST3, AU, AAX)', 'LicensingManager.h + .cpp')}
1076
+ //
1077
+ // Add to your juce_module dependencies: juce_core, juce_data_structures.
1078
+ // Enable JUCE_WEB_BROWSER=0 is fine — juce::URL handles the POST itself.
1079
+ //
1080
+ // ── LicensingManager.h ─────────────────────────────────────────────────────
1081
+ #pragma once
1082
+
1083
+ #include <JuceHeader.h>
1084
+
1085
+ class LicensingManager : public juce::Thread
1086
+ {
1087
+ public:
1088
+ LicensingManager();
1089
+ ~LicensingManager() override;
1090
+
1091
+ /** Kicks off a background check. Never blocks the audio thread. */
1092
+ void refreshAsync();
1093
+
1094
+ /** Cached verdict, safe to read from the message/audio thread. */
1095
+ bool isLicensed() const;
1096
+
1097
+ juce::String getStatusText() const;
1098
+ juce::String getExpiryText() const;
1099
+
1100
+ void activate (const juce::String& licenseKey);
1101
+ void deactivate();
1102
+
1103
+ /** Fired on the message thread whenever the verdict changes. */
1104
+ std::function<void (bool licensed)> onLicenseChanged;
1105
+
1106
+ private:
1107
+ void run() override;
1108
+ void setState (const juce::var& json);
1109
+ juce::var post (const juce::String& endpoint,
1110
+ const juce::StringPairArray& params);
1111
+
1112
+ static juce::String deviceId();
1113
+
1114
+ juce::CriticalSection lock;
1115
+ bool licensed = false;
1116
+ juce::String statusText { "unlicensed" };
1117
+ juce::String expiryText;
1118
+ std::unique_ptr<juce::PropertiesFile> props;
1119
+ };
1120
+
1121
+ // ── LicensingManager.cpp ───────────────────────────────────────────────────
1122
+ #include "LicensingManager.h"
1123
+
1124
+ namespace
1125
+ {
1126
+ constexpr const char* kStoreUrl = "${base}";
1127
+ constexpr int kItemId = ${productId};
1128
+ constexpr juce::int64 kClockToleranceMs = 5 * 60 * 1000;
1129
+
1130
+ juce::PropertiesFile::Options optionsFor (const juce::String& appName)
1131
+ {
1132
+ juce::PropertiesFile::Options o;
1133
+ o.applicationName = appName;
1134
+ o.filenameSuffix = ".licence";
1135
+ o.osxLibrarySubFolder = "Application Support";
1136
+ return o;
1137
+ }
1138
+ }
1139
+
1140
+ LicensingManager::LicensingManager()
1141
+ : juce::Thread ("FluentCart licensing"),
1142
+ props (new juce::PropertiesFile (
1143
+ optionsFor ("${service}"),
1144
+ juce::PropertiesFile::storeAsXML))
1145
+ {
1146
+ }
1147
+
1148
+ LicensingManager::~LicensingManager() { stopThread (3000); }
1149
+
1150
+ juce::String LicensingManager::deviceId()
1151
+ {
1152
+ auto& p = *juce::PropertiesFile::createDefaultAppPropertiesFile (
1153
+ "${service}", ".licence", "Application Support", true);
1154
+ auto existing = p.getValue ("fc_device_id");
1155
+ if (existing.isNotEmpty())
1156
+ return existing;
1157
+
1158
+ auto fresh = "device://" + juce::Uuid().toString();
1159
+ p.setValue ("fc_device_id", fresh);
1160
+ p.saveIfNeeded();
1161
+ return fresh;
1162
+ }
1163
+
1164
+ juce::var LicensingManager::post (const juce::String& endpoint,
1165
+ const juce::StringPairArray& params)
1166
+ {
1167
+ juce::String body;
1168
+ for (int i = 0; i < params.size(); ++i)
1169
+ body << (i ? "&" : "")
1170
+ << juce::URL::addEscapeChars (params.getAllKeys()[i], false) << "="
1171
+ << juce::URL::addEscapeChars (params.getAllValues()[i], false);
1172
+
1173
+ juce::URL url (juce::String (kStoreUrl) + "?fluent-cart=" + endpoint);
1174
+ url = url.withPOSTData (body);
1175
+
1176
+ int statusCode = 0;
1177
+ auto stream = url.createInputStream (
1178
+ juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
1179
+ .withConnectionTimeoutMs (15000)
1180
+ .withExtraHeaders ("Content-Type: application/x-www-form-urlencoded")
1181
+ .withStatusCode (&statusCode));
1182
+
1183
+ if (stream == nullptr)
1184
+ return {};
1185
+
1186
+ return juce::JSON::parse (stream->readEntireStreamAsString());
1187
+ }
1188
+
1189
+ void LicensingManager::setState (const juce::var& json)
1190
+ {
1191
+ auto* obj = json.getDynamicObject();
1192
+ if (obj == nullptr)
1193
+ return;
1194
+
1195
+ auto status = obj->getProperty ("status").toString();
1196
+ auto valid = (status == "valid" || status == "active");
1197
+
1198
+ // The server's clock is authoritative. Remember the matching local time so
1199
+ // a clock moved backwards between checks can be detected.
1200
+ auto serverTime = (juce::int64) (double) obj->getProperty ("server_time_unix");
1201
+
1202
+ {
1203
+ const juce::ScopedLock sl (lock);
1204
+ licensed = valid;
1205
+ statusText = status.isNotEmpty() ? status : "unknown";
1206
+ expiryText = obj->getProperty ("expires").toString();
1207
+ }
1208
+
1209
+ if (serverTime > 0)
1210
+ props->setValue ("fc_server_time", juce::String (serverTime));
1211
+ props->setValue ("fc_checked_at_local", juce::String (juce::Time::currentTimeMillis()));
1212
+ props->saveIfNeeded();
1213
+
1214
+ auto changed = onLicenseChanged;
1215
+ if (changed != nullptr)
1216
+ juce::MessageManager::callAsync ([changed, valid] { changed (valid); });
1217
+ }
1218
+
1219
+ bool LicensingManager::isLicensed() const
1220
+ {
1221
+ const juce::ScopedLock sl (lock);
1222
+ if (! licensed)
1223
+ return false;
1224
+
1225
+ // Pre-computed by the server; the client never does date math.
1226
+ auto days = props->getIntValue ("fc_expires_in_days", -1);
1227
+ if (days >= 0 && days == 0)
1228
+ return false;
1229
+
1230
+ auto checkedAt = props->getValue ("fc_checked_at_local").getLargeIntValue();
1231
+ if (checkedAt > 0 && juce::Time::currentTimeMillis() - checkedAt < -kClockToleranceMs)
1232
+ return false; // clock moved backwards — treat as tampered
1233
+
1234
+ return true;
1235
+ }
1236
+
1237
+ juce::String LicensingManager::getStatusText() const
1238
+ {
1239
+ const juce::ScopedLock sl (lock);
1240
+ return statusText;
1241
+ }
1242
+
1243
+ juce::String LicensingManager::getExpiryText() const
1244
+ {
1245
+ const juce::ScopedLock sl (lock);
1246
+ return expiryText;
1247
+ }
1248
+
1249
+ void LicensingManager::refreshAsync()
1250
+ {
1251
+ if (! isThreadRunning())
1252
+ startThread();
1253
+ }
1254
+
1255
+ void LicensingManager::run()
1256
+ {
1257
+ auto& p = *props;
1258
+ auto key = p.getValue ("fc_license_key");
1259
+ if (key.isEmpty())
1260
+ return;
1261
+
1262
+ juce::StringPairArray params;
1263
+ params.set ("license_key", key);
1264
+ params.set ("item_id", juce::String (kItemId));
1265
+ params.set ("site_url", p.getValue ("fc_device_id"));
1266
+
1267
+ setState (post ("check_license", params));
1268
+ }
1269
+
1270
+ void LicensingManager::activate (const juce::String& licenseKey)
1271
+ {
1272
+ juce::StringPairArray params;
1273
+ params.set ("license_key", licenseKey.trim());
1274
+ params.set ("item_id", juce::String (kItemId));
1275
+ params.set ("site_url", deviceId());
1276
+ params.set ("platform", juce::SystemStats::getOperatingSystemName());
1277
+
1278
+ auto json = post ("activate_license", params);
1279
+ auto* obj = json.getDynamicObject();
1280
+ if (obj != nullptr)
1281
+ {
1282
+ props->setValue ("fc_license_key", licenseKey.trim());
1283
+ props->setValue ("fc_expires_in_days",
1284
+ juce::String ((int) (double) obj->getProperty ("expires_in_days")));
1285
+ }
1286
+ setState (json);
1287
+ props->saveIfNeeded();
1288
+ }
1289
+
1290
+ void LicensingManager::deactivate()
1291
+ {
1292
+ juce::StringPairArray params;
1293
+ params.set ("license_key", props->getValue ("fc_license_key"));
1294
+ params.set ("item_id", juce::String (kItemId));
1295
+ params.set ("site_url", props->getValue ("fc_device_id"));
1296
+ post ("deactivate_license", params);
1297
+
1298
+ props->removeValue ("fc_license_key");
1299
+ props->saveIfNeeded();
1300
+
1301
+ const juce::ScopedLock sl (lock);
1302
+ licensed = false;
1303
+ statusText = "unlicensed";
1304
+ }
1305
+
1306
+ // In your AudioProcessor constructor:
1307
+ // licensing.refreshAsync(); // background thread, no UI stall
1308
+ // Never call isLicensed() from the audio callback — cache it on the message
1309
+ // thread and read an atomic in processBlock().
1265
1310
  `;
1266
1311
  }
1267
1312
  return {
@@ -1302,110 +1347,110 @@ void LicensingManager::deactivate()
1302
1347
  content: [
1303
1348
  {
1304
1349
  type: 'text',
1305
- text: `${header('Tauri / Rust', 'src/trial.rs')}
1306
- //
1307
- // Cargo.toml
1308
- // reqwest = { version = "0.12", features = ["json"] }
1309
- // serde = { version = "1", features = ["derive"] }
1310
- // serde_json = "1"
1311
- // machine-uid = "0.5"
1312
- // keyring = "2"
1313
- // whoami = "1"
1314
-
1315
- use serde::Deserialize;
1316
-
1317
- const STORE: &str = "${base}";
1318
- const PRODUCT_ID: i64 = ${productId};
1319
- const KEYRING_SERVICE: &str = "${slug}-trial";
1320
-
1321
- #[derive(Deserialize, Debug)]
1322
- pub struct Eligibility {
1323
- pub eligible: bool,
1324
- pub reason: String,
1325
- pub token: Option<String>,
1326
- pub risk_score: Option<i64>,
1327
- }
1328
-
1329
- /// Stable, versioned machine fingerprint. Survives app updates; changes on
1330
- /// OS reinstall or disk replacement, which is a support reset, not abuse.
1331
- pub fn fingerprint() -> String {
1332
- let uid = machine_uid::get().unwrap_or_else(|_| "unknown".to_string());
1333
- let host = whoami::fallible::hostname().unwrap_or_else(|_| "host".to_string());
1334
- format!(
1335
- "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}",
1336
- uid,
1337
- host,
1338
- std::env::consts::OS,
1339
- std::env::consts::ARCH
1340
- )
1341
- }
1342
-
1343
- /// One persisted device:// id, used as site_url. Separate from the fingerprint:
1344
- /// the id identifies the install, the fingerprint identifies the machine.
1345
- pub fn device_id() -> String {
1346
- if let Ok(entry) = keyring::Entry::new(KEYRING_SERVICE, "device_id") {
1347
- if let Ok(id) = entry.get_password() {
1348
- return id;
1349
- }
1350
- let id = format!("device://{}", uuid::Uuid::new_v4());
1351
- let _ = entry.set_password(&id);
1352
- return id;
1353
- }
1354
- "device://unknown".to_string()
1355
- }
1356
-
1357
- pub async fn check_trial(client: &reqwest::Client, email: &str) -> Result<Eligibility, String> {
1358
- let res = client
1359
- .post(format!("{}?fluent-cart=fastr_trial_eligibility", STORE))
1360
- .form(&[
1361
- ("product_id", PRODUCT_ID.to_string()),
1362
- ("device_fingerprint", fingerprint()),
1363
- ("email", email.to_string()),
1364
- ])
1365
- .send()
1366
- .await
1367
- .map_err(|e| e.to_string())?;
1368
-
1369
- res.json::<Eligibility>().await.map_err(|e| e.to_string())
1370
- }
1371
-
1372
- pub async fn activate(
1373
- client: &reqwest::Client,
1374
- license_key: &str,
1375
- email: &str,
1376
- ) -> Result<serde_json::Value, String> {
1377
- let res = client
1378
- .post(format!("{}?fluent-cart=activate_license", STORE))
1379
- .form(&[
1380
- ("item_id", PRODUCT_ID.to_string()),
1381
- ("license_key", license_key.to_string()),
1382
- ("site_url", device_id()),
1383
- ("device_fingerprint", fingerprint()),
1384
- ("device_name", whoami::fallible::hostname().unwrap_or_default()),
1385
- ("device_type", "Desktop (Tauri)".to_string()),
1386
- ("os", std::env::consts::OS.to_string()),
1387
- ("arch", std::env::consts::ARCH.to_string()),
1388
- ("email", email.to_string()),
1389
- ("server_version", env!("CARGO_PKG_VERSION").to_string()),
1390
- ])
1391
- .send()
1392
- .await
1393
- .map_err(|e| e.to_string())?;
1394
-
1395
- let body: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
1396
-
1397
- match body.get("error_type").and_then(|v| v.as_str()) {
1398
- Some("trial_already_used") => Err("trial_already_used".into()),
1399
- Some("trial_fingerprint_required") => Err("client_outdated".into()),
1400
- Some("trial_device_mismatch") => Err("trial_device_mismatch".into()),
1401
- Some("device_blocked") => Err("device_blocked".into()),
1402
- _ => Ok(body),
1403
- }
1404
- }
1405
-
1406
- // Flow: check_trial() before showing the trial button; hide or disable it when
1407
- // eligible=false. activate() on submit. Cache the server's server_time_unix and
1408
- // compare it on every launch instead of trusting the local clock.
1350
+ text: `${header('Tauri / Rust', 'src/trial.rs')}
1351
+ //
1352
+ // Cargo.toml
1353
+ // reqwest = { version = "0.12", features = ["json"] }
1354
+ // serde = { version = "1", features = ["derive"] }
1355
+ // serde_json = "1"
1356
+ // machine-uid = "0.5"
1357
+ // keyring = "2"
1358
+ // whoami = "1"
1359
+
1360
+ use serde::Deserialize;
1361
+
1362
+ const STORE: &str = "${base}";
1363
+ const PRODUCT_ID: i64 = ${productId};
1364
+ const KEYRING_SERVICE: &str = "${slug}-trial";
1365
+
1366
+ #[derive(Deserialize, Debug)]
1367
+ pub struct Eligibility {
1368
+ pub eligible: bool,
1369
+ pub reason: String,
1370
+ pub token: Option<String>,
1371
+ pub risk_score: Option<i64>,
1372
+ }
1373
+
1374
+ /// Stable, versioned machine fingerprint. Survives app updates; changes on
1375
+ /// OS reinstall or disk replacement, which is a support reset, not abuse.
1376
+ pub fn fingerprint() -> String {
1377
+ let uid = machine_uid::get().unwrap_or_else(|_| "unknown".to_string());
1378
+ let host = whoami::fallible::hostname().unwrap_or_else(|_| "host".to_string());
1379
+ format!(
1380
+ "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}",
1381
+ uid,
1382
+ host,
1383
+ std::env::consts::OS,
1384
+ std::env::consts::ARCH
1385
+ )
1386
+ }
1387
+
1388
+ /// One persisted device:// id, used as site_url. Separate from the fingerprint:
1389
+ /// the id identifies the install, the fingerprint identifies the machine.
1390
+ pub fn device_id() -> String {
1391
+ if let Ok(entry) = keyring::Entry::new(KEYRING_SERVICE, "device_id") {
1392
+ if let Ok(id) = entry.get_password() {
1393
+ return id;
1394
+ }
1395
+ let id = format!("device://{}", uuid::Uuid::new_v4());
1396
+ let _ = entry.set_password(&id);
1397
+ return id;
1398
+ }
1399
+ "device://unknown".to_string()
1400
+ }
1401
+
1402
+ pub async fn check_trial(client: &reqwest::Client, email: &str) -> Result<Eligibility, String> {
1403
+ let res = client
1404
+ .post(format!("{}?fluent-cart=fastr_trial_eligibility", STORE))
1405
+ .form(&[
1406
+ ("product_id", PRODUCT_ID.to_string()),
1407
+ ("device_fingerprint", fingerprint()),
1408
+ ("email", email.to_string()),
1409
+ ])
1410
+ .send()
1411
+ .await
1412
+ .map_err(|e| e.to_string())?;
1413
+
1414
+ res.json::<Eligibility>().await.map_err(|e| e.to_string())
1415
+ }
1416
+
1417
+ pub async fn activate(
1418
+ client: &reqwest::Client,
1419
+ license_key: &str,
1420
+ email: &str,
1421
+ ) -> Result<serde_json::Value, String> {
1422
+ let res = client
1423
+ .post(format!("{}?fluent-cart=activate_license", STORE))
1424
+ .form(&[
1425
+ ("item_id", PRODUCT_ID.to_string()),
1426
+ ("license_key", license_key.to_string()),
1427
+ ("site_url", device_id()),
1428
+ ("device_fingerprint", fingerprint()),
1429
+ ("device_name", whoami::fallible::hostname().unwrap_or_default()),
1430
+ ("device_type", "Desktop (Tauri)".to_string()),
1431
+ ("os", std::env::consts::OS.to_string()),
1432
+ ("arch", std::env::consts::ARCH.to_string()),
1433
+ ("email", email.to_string()),
1434
+ ("server_version", env!("CARGO_PKG_VERSION").to_string()),
1435
+ ])
1436
+ .send()
1437
+ .await
1438
+ .map_err(|e| e.to_string())?;
1439
+
1440
+ let body: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
1441
+
1442
+ match body.get("error_type").and_then(|v| v.as_str()) {
1443
+ Some("trial_already_used") => Err("trial_already_used".into()),
1444
+ Some("trial_fingerprint_required") => Err("client_outdated".into()),
1445
+ Some("trial_device_mismatch") => Err("trial_device_mismatch".into()),
1446
+ Some("device_blocked") => Err("device_blocked".into()),
1447
+ _ => Ok(body),
1448
+ }
1449
+ }
1450
+
1451
+ // Flow: check_trial() before showing the trial button; hide or disable it when
1452
+ // eligible=false. activate() on submit. Cache the server's server_time_unix and
1453
+ // compare it on every launch instead of trusting the local clock.
1409
1454
  `
1410
1455
  }
1411
1456
  ]
@@ -1416,125 +1461,125 @@ pub async fn activate(
1416
1461
  content: [
1417
1462
  {
1418
1463
  type: 'text',
1419
- text: `"""${appName} - FluentCart trial guard (Python)
1420
-
1421
- Store: ${base}
1422
- Product ID: ${productId}
1423
- Dependencies: httpx, keyring
1424
-
1425
- Flow: check_trial() before offering the trial, activate() on submit,
1426
- check() on every launch. Never trust the local clock for expiry.
1427
- """
1428
-
1429
- import platform
1430
- import socket
1431
- import subprocess
1432
- import sys
1433
- import time
1434
- import uuid
1435
-
1436
- import httpx
1437
- import keyring
1438
-
1439
- STORE = "${base}"
1440
- PRODUCT_ID = ${productId}
1441
- KEYRING_SERVICE = "${slug}-trial"
1442
-
1443
-
1444
- def machine_id() -> str:
1445
- """Stable machine identifier. Linux: /etc/machine-id, Windows: MachineGuid."""
1446
- if sys.platform.startswith("win"):
1447
- try:
1448
- import winreg
1449
-
1450
- key = winreg.OpenKey(
1451
- winreg.HKEY_LOCAL_MACHINE,
1452
- r"SOFTWARE\\Microsoft\\Cryptography",
1453
- )
1454
- value, _ = winreg.QueryValueEx(key, "MachineGuid")
1455
- return str(value)
1456
- except Exception:
1457
- return ""
1458
- if sys.platform == "darwin":
1459
- try:
1460
- out = subprocess.check_output(
1461
- ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
1462
- text=True,
1463
- )
1464
- for line in out.splitlines():
1465
- if "IOPlatformUUID" in line:
1466
- return line.split("=")[-1].strip().strip('"')
1467
- except Exception:
1468
- return ""
1469
- try:
1470
- with open("/etc/machine-id", "r", encoding="utf-8") as handle:
1471
- return handle.read().strip()
1472
- except OSError:
1473
- return ""
1474
-
1475
-
1476
- def fingerprint() -> str:
1477
- uname = platform.uname()
1478
- return "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}".format(
1479
- machine_id() or "unknown",
1480
- socket.gethostname(),
1481
- uname.system,
1482
- uname.machine,
1483
- )
1484
-
1485
-
1486
- def device_id() -> str:
1487
- stored = keyring.get_password(KEYRING_SERVICE, "device_id")
1488
- if stored:
1489
- return stored
1490
- new_id = "device://" + str(uuid.uuid4())
1491
- keyring.set_password(KEYRING_SERVICE, "device_id", new_id)
1492
- return new_id
1493
-
1494
-
1495
- def check_trial(email: str) -> dict:
1496
- payload = {
1497
- "product_id": PRODUCT_ID,
1498
- "device_fingerprint": fingerprint(),
1499
- "email": email,
1500
- }
1501
- with httpx.Client(timeout=10.0) as client:
1502
- response = client.post(STORE + "?fluent-cart=fastr_trial_eligibility", data=payload)
1503
- return response.json()
1504
-
1505
-
1506
- def activate(license_key: str, email: str) -> dict:
1507
- uname = platform.uname()
1508
- payload = {
1509
- "item_id": PRODUCT_ID,
1510
- "license_key": license_key,
1511
- "site_url": device_id(),
1512
- "device_fingerprint": fingerprint(),
1513
- "device_name": socket.gethostname(),
1514
- "device_type": "Python Desktop / CLI",
1515
- "os": uname.system,
1516
- "arch": uname.machine,
1517
- "email": email,
1518
- "server_version": "1.0.0",
1519
- }
1520
- with httpx.Client(timeout=10.0) as client:
1521
- response = client.post(STORE + "?fluent-cart=activate_license", data=payload)
1522
- body = response.json()
1523
-
1524
- error = body.get("error_type")
1525
- if error in {
1526
- "trial_already_used",
1527
- "trial_fingerprint_required",
1528
- "trial_device_mismatch",
1529
- "device_blocked",
1530
- }:
1531
- raise RuntimeError(error)
1532
-
1533
- if body.get("status") == "valid":
1534
- keyring.set_password(KEYRING_SERVICE, "license_key", license_key)
1535
- keyring.set_password(KEYRING_SERVICE, "last_server_time", str(body.get("server_time_unix", 0)))
1536
-
1537
- return body
1464
+ text: `"""${appName} - FluentCart trial guard (Python)
1465
+
1466
+ Store: ${base}
1467
+ Product ID: ${productId}
1468
+ Dependencies: httpx, keyring
1469
+
1470
+ Flow: check_trial() before offering the trial, activate() on submit,
1471
+ check() on every launch. Never trust the local clock for expiry.
1472
+ """
1473
+
1474
+ import platform
1475
+ import socket
1476
+ import subprocess
1477
+ import sys
1478
+ import time
1479
+ import uuid
1480
+
1481
+ import httpx
1482
+ import keyring
1483
+
1484
+ STORE = "${base}"
1485
+ PRODUCT_ID = ${productId}
1486
+ KEYRING_SERVICE = "${slug}-trial"
1487
+
1488
+
1489
+ def machine_id() -> str:
1490
+ """Stable machine identifier. Linux: /etc/machine-id, Windows: MachineGuid."""
1491
+ if sys.platform.startswith("win"):
1492
+ try:
1493
+ import winreg
1494
+
1495
+ key = winreg.OpenKey(
1496
+ winreg.HKEY_LOCAL_MACHINE,
1497
+ r"SOFTWARE\\Microsoft\\Cryptography",
1498
+ )
1499
+ value, _ = winreg.QueryValueEx(key, "MachineGuid")
1500
+ return str(value)
1501
+ except Exception:
1502
+ return ""
1503
+ if sys.platform == "darwin":
1504
+ try:
1505
+ out = subprocess.check_output(
1506
+ ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
1507
+ text=True,
1508
+ )
1509
+ for line in out.splitlines():
1510
+ if "IOPlatformUUID" in line:
1511
+ return line.split("=")[-1].strip().strip('"')
1512
+ except Exception:
1513
+ return ""
1514
+ try:
1515
+ with open("/etc/machine-id", "r", encoding="utf-8") as handle:
1516
+ return handle.read().strip()
1517
+ except OSError:
1518
+ return ""
1519
+
1520
+
1521
+ def fingerprint() -> str:
1522
+ uname = platform.uname()
1523
+ return "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}".format(
1524
+ machine_id() or "unknown",
1525
+ socket.gethostname(),
1526
+ uname.system,
1527
+ uname.machine,
1528
+ )
1529
+
1530
+
1531
+ def device_id() -> str:
1532
+ stored = keyring.get_password(KEYRING_SERVICE, "device_id")
1533
+ if stored:
1534
+ return stored
1535
+ new_id = "device://" + str(uuid.uuid4())
1536
+ keyring.set_password(KEYRING_SERVICE, "device_id", new_id)
1537
+ return new_id
1538
+
1539
+
1540
+ def check_trial(email: str) -> dict:
1541
+ payload = {
1542
+ "product_id": PRODUCT_ID,
1543
+ "device_fingerprint": fingerprint(),
1544
+ "email": email,
1545
+ }
1546
+ with httpx.Client(timeout=10.0) as client:
1547
+ response = client.post(STORE + "?fluent-cart=fastr_trial_eligibility", data=payload)
1548
+ return response.json()
1549
+
1550
+
1551
+ def activate(license_key: str, email: str) -> dict:
1552
+ uname = platform.uname()
1553
+ payload = {
1554
+ "item_id": PRODUCT_ID,
1555
+ "license_key": license_key,
1556
+ "site_url": device_id(),
1557
+ "device_fingerprint": fingerprint(),
1558
+ "device_name": socket.gethostname(),
1559
+ "device_type": "Python Desktop / CLI",
1560
+ "os": uname.system,
1561
+ "arch": uname.machine,
1562
+ "email": email,
1563
+ "server_version": "1.0.0",
1564
+ }
1565
+ with httpx.Client(timeout=10.0) as client:
1566
+ response = client.post(STORE + "?fluent-cart=activate_license", data=payload)
1567
+ body = response.json()
1568
+
1569
+ error = body.get("error_type")
1570
+ if error in {
1571
+ "trial_already_used",
1572
+ "trial_fingerprint_required",
1573
+ "trial_device_mismatch",
1574
+ "device_blocked",
1575
+ }:
1576
+ raise RuntimeError(error)
1577
+
1578
+ if body.get("status") == "valid":
1579
+ keyring.set_password(KEYRING_SERVICE, "license_key", license_key)
1580
+ keyring.set_password(KEYRING_SERVICE, "last_server_time", str(body.get("server_time_unix", 0)))
1581
+
1582
+ return body
1538
1583
  `
1539
1584
  }
1540
1585
  ]
@@ -1544,234 +1589,234 @@ def activate(license_key: str, email: str) -> dict:
1544
1589
  content: [
1545
1590
  {
1546
1591
  type: 'text',
1547
- text: `${header('Chrome Extension MV3', 'background.js')}
1548
- //
1549
- // manifest.json permissions: "storage", "alarms"
1550
- // Note: a user can clear chrome.storage in seconds, so browser trials are
1551
- // account-bound in practice. The fingerprint raises friction, it does not
1552
- // guarantee device identity.
1553
-
1554
- const STORE = "${base}";
1555
- const PRODUCT_ID = ${productId};
1556
- // Offline entitlement is bounded by the signed token's own exp, which the
1557
- // server issues. Nothing below trusts a timestamp this extension wrote:
1558
- // chrome.storage is editable from DevTools in seconds.
1559
- const PUBLIC_KEY_URL = STORE + "?fluent-cart=fastr_license_public_key";
1560
-
1561
- async function getInstallId() {
1562
- const data = await chrome.storage.local.get("install_id");
1563
- if (data.install_id) return data.install_id;
1564
- const id = "device://" + crypto.randomUUID();
1565
- await chrome.storage.local.set({ install_id: id });
1566
- return id;
1567
- }
1568
-
1569
- async function fingerprint() {
1570
- const manifest = chrome.runtime.getManifest();
1571
- return [
1572
- "v1",
1573
- "INSTALL=" + (await getInstallId()),
1574
- "EXT=" + chrome.runtime.id,
1575
- "CORES=" + (navigator.hardwareConcurrency || 0),
1576
- "TZ=" + Intl.DateTimeFormat().resolvedOptions().timeZone,
1577
- "VER=" + manifest.version
1578
- ].join("|");
1579
- }
1580
-
1581
- export async function checkTrial(email) {
1582
- const body = new URLSearchParams({
1583
- product_id: String(PRODUCT_ID),
1584
- device_fingerprint: await fingerprint(),
1585
- email: email || ""
1586
- });
1587
-
1588
- const res = await fetch(STORE + "?fluent-cart=fastr_trial_eligibility", {
1589
- method: "POST",
1590
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1591
- body: body.toString()
1592
- });
1593
-
1594
- const json = await res.json();
1595
- await chrome.storage.local.set({ trial_risk: json.risk_score || 0 });
1596
- return json;
1597
- }
1598
-
1599
- export async function activateLicense(licenseKey, email) {
1600
- const installId = await getInstallId();
1601
- const body = new URLSearchParams({
1602
- item_id: String(PRODUCT_ID),
1603
- license_key: licenseKey,
1604
- site_url: installId,
1605
- device_fingerprint: await fingerprint(),
1606
- device_name: "Chrome Browser Profile",
1607
- device_type: "Chrome Extension",
1608
- os: navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
1609
- email: email || "",
1610
- server_version: chrome.runtime.getManifest().version
1611
- });
1612
-
1613
- const res = await fetch(STORE + "?fluent-cart=activate_license", {
1614
- method: "POST",
1615
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1616
- body: body.toString()
1617
- });
1618
-
1619
- const json = await res.json();
1620
-
1621
- if (json.error_type === "trial_already_used") throw new Error("trial_already_used");
1622
- if (json.error_type === "trial_fingerprint_required") throw new Error("client_outdated");
1623
- if (json.error_type === "trial_device_mismatch") throw new Error("trial_device_mismatch");
1624
-
1625
- if (json.status === "valid" && json.license_token) {
1626
- await chrome.storage.local.set({
1627
- license_key: licenseKey,
1628
- activation_hash: json.activation_hash,
1629
- license_token: json.license_token,
1630
- server_time_unix: json.server_time_unix,
1631
- local_at_check: Date.now()
1632
- });
1633
- }
1634
-
1635
- return json;
1636
- }
1637
-
1638
- function b64Bytes(input) {
1639
- const bin = atob(input.replace(/-/g, "+").replace(/_/g, "/"));
1640
- const out = new Uint8Array(bin.length);
1641
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1642
- return out;
1643
- }
1644
-
1645
- async function storePublicKey() {
1646
- const cached = await chrome.storage.local.get("fastr_public_key");
1647
- if (cached.fastr_public_key) return cached.fastr_public_key;
1648
-
1649
- const res = await fetch(PUBLIC_KEY_URL, { cache: "no-store" });
1650
- const json = await res.json();
1651
- // The store answers { kid, alg, public_key_pem, ... }. Guessing a shorter
1652
- // name here means the key is never found and every user is locked out.
1653
- const pem = String(json.public_key_pem || json.public_key || json.pem || "");
1654
-
1655
- if (pem) await chrome.storage.local.set({ fastr_public_key: pem });
1656
- return pem;
1657
- }
1658
-
1659
- // RS256 verification. A token the user forges fails here; a token the store
1660
- // signed cannot be edited without breaking the signature.
1661
- export async function verifyLicenseToken(token, pem) {
1662
- const parts = String(token || "").split(".");
1663
- if (parts.length !== 3 || !pem) return null;
1664
-
1665
- try {
1666
- const der = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
1667
-
1668
- const key = await crypto.subtle.importKey(
1669
- "spki",
1670
- b64Bytes(der),
1671
- { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
1672
- false,
1673
- ["verify"]
1674
- );
1675
-
1676
- const ok = await crypto.subtle.verify(
1677
- "RSASSA-PKCS1-v1_5",
1678
- key,
1679
- b64Bytes(parts[2]),
1680
- new TextEncoder().encode(parts[0] + "." + parts[1])
1681
- );
1682
-
1683
- if (!ok) return null;
1684
-
1685
- const claims = JSON.parse(new TextDecoder().decode(b64Bytes(parts[1])));
1686
-
1687
- if (typeof claims.exp === "number" && claims.exp <= Math.floor(Date.now() / 1000)) {
1688
- return null;
1689
- }
1690
-
1691
- return claims;
1692
- } catch (error) {
1693
- return null;
1694
- }
1695
- }
1696
-
1697
- // What the extension should gate on. Verified offline against the store's key,
1698
- // so the answer survives losing the network but not editing storage.
1699
- export async function hasAccess() {
1700
- const data = await chrome.storage.local.get([
1701
- "license_key",
1702
- "license_token",
1703
- "local_at_check"
1704
- ]);
1705
-
1706
- if (!data.license_key || !data.license_token) {
1707
- return { status: "unlicensed" };
1708
- }
1709
-
1710
- // A clock that now reads earlier than it did at the last successful check
1711
- // defeats the expiry check below, so refuse instead of guessing.
1712
- if (data.local_at_check && Date.now() < data.local_at_check) {
1713
- return { status: "invalid", reason: "clock_rollback" };
1714
- }
1715
-
1716
- const pem = await storePublicKey();
1717
- const claims = await verifyLicenseToken(data.license_token, pem);
1718
-
1719
- if (!claims) {
1720
- return { status: "expired", reason: "token_invalid_or_expired" };
1721
- }
1722
-
1723
- return { status: "valid", source: "offline_token", claims };
1724
- }
1725
-
1726
- export async function checkLicense() {
1727
- const data = await chrome.storage.local.get([
1728
- "license_key",
1729
- "install_id",
1730
- "license_token"
1731
- ]);
1732
-
1733
- if (!data.license_key || !data.install_id) return { status: "unlicensed" };
1734
-
1735
- const body = new URLSearchParams({
1736
- item_id: String(PRODUCT_ID),
1737
- license_key: data.license_key,
1738
- site_url: data.install_id,
1739
- device_fingerprint: await fingerprint()
1740
- });
1741
-
1742
- try {
1743
- const res = await fetch(STORE + "?fluent-cart=check_license", {
1744
- method: "POST",
1745
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1746
- body: body.toString()
1747
- });
1748
-
1749
- const json = await res.json();
1750
-
1751
- if (json.status !== "valid") {
1752
- // The store said no. Whatever is still on disk is now a lie.
1753
- await chrome.storage.local.remove(["license_token", "local_at_check"]);
1754
- return json;
1755
- }
1756
-
1757
- await chrome.storage.local.set({
1758
- license_token: json.license_token || data.license_token,
1759
- server_time_unix: json.server_time_unix,
1760
- local_at_check: Date.now()
1761
- });
1762
-
1763
- return json;
1764
- } catch (error) {
1765
- // No network. The signed token is the best evidence available, and it
1766
- // expires on the server's schedule rather than ours.
1767
- return await hasAccess();
1768
- }
1769
- }
1770
-
1771
- chrome.alarms.create("fastr_license_check", { periodInMinutes: 60 });
1772
- chrome.alarms.onAlarm.addListener((alarm) => {
1773
- if (alarm.name === "fastr_license_check") checkLicense();
1774
- });
1592
+ text: `${header('Chrome Extension MV3', 'background.js')}
1593
+ //
1594
+ // manifest.json permissions: "storage", "alarms"
1595
+ // Note: a user can clear chrome.storage in seconds, so browser trials are
1596
+ // account-bound in practice. The fingerprint raises friction, it does not
1597
+ // guarantee device identity.
1598
+
1599
+ const STORE = "${base}";
1600
+ const PRODUCT_ID = ${productId};
1601
+ // Offline entitlement is bounded by the signed token's own exp, which the
1602
+ // server issues. Nothing below trusts a timestamp this extension wrote:
1603
+ // chrome.storage is editable from DevTools in seconds.
1604
+ const PUBLIC_KEY_URL = STORE + "?fluent-cart=fastr_license_public_key";
1605
+
1606
+ async function getInstallId() {
1607
+ const data = await chrome.storage.local.get("install_id");
1608
+ if (data.install_id) return data.install_id;
1609
+ const id = "device://" + crypto.randomUUID();
1610
+ await chrome.storage.local.set({ install_id: id });
1611
+ return id;
1612
+ }
1613
+
1614
+ async function fingerprint() {
1615
+ const manifest = chrome.runtime.getManifest();
1616
+ return [
1617
+ "v1",
1618
+ "INSTALL=" + (await getInstallId()),
1619
+ "EXT=" + chrome.runtime.id,
1620
+ "CORES=" + (navigator.hardwareConcurrency || 0),
1621
+ "TZ=" + Intl.DateTimeFormat().resolvedOptions().timeZone,
1622
+ "VER=" + manifest.version
1623
+ ].join("|");
1624
+ }
1625
+
1626
+ export async function checkTrial(email) {
1627
+ const body = new URLSearchParams({
1628
+ product_id: String(PRODUCT_ID),
1629
+ device_fingerprint: await fingerprint(),
1630
+ email: email || ""
1631
+ });
1632
+
1633
+ const res = await fetch(STORE + "?fluent-cart=fastr_trial_eligibility", {
1634
+ method: "POST",
1635
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1636
+ body: body.toString()
1637
+ });
1638
+
1639
+ const json = await res.json();
1640
+ await chrome.storage.local.set({ trial_risk: json.risk_score || 0 });
1641
+ return json;
1642
+ }
1643
+
1644
+ export async function activateLicense(licenseKey, email) {
1645
+ const installId = await getInstallId();
1646
+ const body = new URLSearchParams({
1647
+ item_id: String(PRODUCT_ID),
1648
+ license_key: licenseKey,
1649
+ site_url: installId,
1650
+ device_fingerprint: await fingerprint(),
1651
+ device_name: "Chrome Browser Profile",
1652
+ device_type: "Chrome Extension",
1653
+ os: navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
1654
+ email: email || "",
1655
+ server_version: chrome.runtime.getManifest().version
1656
+ });
1657
+
1658
+ const res = await fetch(STORE + "?fluent-cart=activate_license", {
1659
+ method: "POST",
1660
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1661
+ body: body.toString()
1662
+ });
1663
+
1664
+ const json = await res.json();
1665
+
1666
+ if (json.error_type === "trial_already_used") throw new Error("trial_already_used");
1667
+ if (json.error_type === "trial_fingerprint_required") throw new Error("client_outdated");
1668
+ if (json.error_type === "trial_device_mismatch") throw new Error("trial_device_mismatch");
1669
+
1670
+ if (json.status === "valid" && json.license_token) {
1671
+ await chrome.storage.local.set({
1672
+ license_key: licenseKey,
1673
+ activation_hash: json.activation_hash,
1674
+ license_token: json.license_token,
1675
+ server_time_unix: json.server_time_unix,
1676
+ local_at_check: Date.now()
1677
+ });
1678
+ }
1679
+
1680
+ return json;
1681
+ }
1682
+
1683
+ function b64Bytes(input) {
1684
+ const bin = atob(input.replace(/-/g, "+").replace(/_/g, "/"));
1685
+ const out = new Uint8Array(bin.length);
1686
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1687
+ return out;
1688
+ }
1689
+
1690
+ async function storePublicKey() {
1691
+ const cached = await chrome.storage.local.get("fastr_public_key");
1692
+ if (cached.fastr_public_key) return cached.fastr_public_key;
1693
+
1694
+ const res = await fetch(PUBLIC_KEY_URL, { cache: "no-store" });
1695
+ const json = await res.json();
1696
+ // The store answers { kid, alg, public_key_pem, ... }. Guessing a shorter
1697
+ // name here means the key is never found and every user is locked out.
1698
+ const pem = String(json.public_key_pem || json.public_key || json.pem || "");
1699
+
1700
+ if (pem) await chrome.storage.local.set({ fastr_public_key: pem });
1701
+ return pem;
1702
+ }
1703
+
1704
+ // RS256 verification. A token the user forges fails here; a token the store
1705
+ // signed cannot be edited without breaking the signature.
1706
+ export async function verifyLicenseToken(token, pem) {
1707
+ const parts = String(token || "").split(".");
1708
+ if (parts.length !== 3 || !pem) return null;
1709
+
1710
+ try {
1711
+ const der = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
1712
+
1713
+ const key = await crypto.subtle.importKey(
1714
+ "spki",
1715
+ b64Bytes(der),
1716
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
1717
+ false,
1718
+ ["verify"]
1719
+ );
1720
+
1721
+ const ok = await crypto.subtle.verify(
1722
+ "RSASSA-PKCS1-v1_5",
1723
+ key,
1724
+ b64Bytes(parts[2]),
1725
+ new TextEncoder().encode(parts[0] + "." + parts[1])
1726
+ );
1727
+
1728
+ if (!ok) return null;
1729
+
1730
+ const claims = JSON.parse(new TextDecoder().decode(b64Bytes(parts[1])));
1731
+
1732
+ if (typeof claims.exp === "number" && claims.exp <= Math.floor(Date.now() / 1000)) {
1733
+ return null;
1734
+ }
1735
+
1736
+ return claims;
1737
+ } catch (error) {
1738
+ return null;
1739
+ }
1740
+ }
1741
+
1742
+ // What the extension should gate on. Verified offline against the store's key,
1743
+ // so the answer survives losing the network but not editing storage.
1744
+ export async function hasAccess() {
1745
+ const data = await chrome.storage.local.get([
1746
+ "license_key",
1747
+ "license_token",
1748
+ "local_at_check"
1749
+ ]);
1750
+
1751
+ if (!data.license_key || !data.license_token) {
1752
+ return { status: "unlicensed" };
1753
+ }
1754
+
1755
+ // A clock that now reads earlier than it did at the last successful check
1756
+ // defeats the expiry check below, so refuse instead of guessing.
1757
+ if (data.local_at_check && Date.now() < data.local_at_check) {
1758
+ return { status: "invalid", reason: "clock_rollback" };
1759
+ }
1760
+
1761
+ const pem = await storePublicKey();
1762
+ const claims = await verifyLicenseToken(data.license_token, pem);
1763
+
1764
+ if (!claims) {
1765
+ return { status: "expired", reason: "token_invalid_or_expired" };
1766
+ }
1767
+
1768
+ return { status: "valid", source: "offline_token", claims };
1769
+ }
1770
+
1771
+ export async function checkLicense() {
1772
+ const data = await chrome.storage.local.get([
1773
+ "license_key",
1774
+ "install_id",
1775
+ "license_token"
1776
+ ]);
1777
+
1778
+ if (!data.license_key || !data.install_id) return { status: "unlicensed" };
1779
+
1780
+ const body = new URLSearchParams({
1781
+ item_id: String(PRODUCT_ID),
1782
+ license_key: data.license_key,
1783
+ site_url: data.install_id,
1784
+ device_fingerprint: await fingerprint()
1785
+ });
1786
+
1787
+ try {
1788
+ const res = await fetch(STORE + "?fluent-cart=check_license", {
1789
+ method: "POST",
1790
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1791
+ body: body.toString()
1792
+ });
1793
+
1794
+ const json = await res.json();
1795
+
1796
+ if (json.status !== "valid") {
1797
+ // The store said no. Whatever is still on disk is now a lie.
1798
+ await chrome.storage.local.remove(["license_token", "local_at_check"]);
1799
+ return json;
1800
+ }
1801
+
1802
+ await chrome.storage.local.set({
1803
+ license_token: json.license_token || data.license_token,
1804
+ server_time_unix: json.server_time_unix,
1805
+ local_at_check: Date.now()
1806
+ });
1807
+
1808
+ return json;
1809
+ } catch (error) {
1810
+ // No network. The signed token is the best evidence available, and it
1811
+ // expires on the server's schedule rather than ours.
1812
+ return await hasAccess();
1813
+ }
1814
+ }
1815
+
1816
+ chrome.alarms.create("fastr_license_check", { periodInMinutes: 60 });
1817
+ chrome.alarms.onAlarm.addListener((alarm) => {
1818
+ if (alarm.name === "fastr_license_check") checkLicense();
1819
+ });
1775
1820
  `
1776
1821
  }
1777
1822
  ]
@@ -1802,270 +1847,270 @@ chrome.alarms.onAlarm.addListener((alarm) => {
1802
1847
  content: [
1803
1848
  {
1804
1849
  type: 'text',
1805
- text: `${header('Node / Electron', 'src/license.ts')}
1806
- import { createVerify, randomUUID } from "node:crypto";
1807
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1808
- import { homedir } from "node:os";
1809
- import { join } from "node:path";
1810
-
1811
- const STORE = "${base}";
1812
- const PRODUCT_ID = ${productId};
1813
-
1814
- /**
1815
- * Where the device id and the last verdict live. In Electron, point this at
1816
- * app.getPath("userData") before the first call.
1817
- */
1818
- const DATA_DIR = process.env.FASTR_DATA_DIR || join(homedir(), ".${slug}");
1819
- const DEVICE_FILE = join(DATA_DIR, "device-id");
1820
- const STATE_FILE = join(DATA_DIR, "license.json");
1821
-
1822
- /** A backwards clock jump larger than this means the machine was moved. */
1823
- const CLOCK_TOLERANCE_SECS = 300;
1824
- /** How long a cached verdict survives without reaching the store. */
1825
- const OFFLINE_GRACE_SECS = 7 * 24 * 60 * 60;
1826
-
1827
- export type LicenseState = {
1828
- status: string;
1829
- token?: string;
1830
- entitlements?: number[];
1831
- expiresInDays?: number | null;
1832
- errorType?: string;
1833
- };
1834
-
1835
- type StoredState = LicenseState & {
1836
- licenseKey: string;
1837
- deviceId: string;
1838
- variationTitle?: string;
1839
- expires?: string;
1840
- /** Server clock at the last successful call — the only time we trust. */
1841
- serverTimeUnix?: number;
1842
- /** Local clock at that same moment, used to detect a rollback. */
1843
- checkedAtLocal: number;
1844
- };
1845
-
1846
- /**
1847
- * device://<uuid>, created once and kept.
1848
- *
1849
- * Deriving this from hardware is wrong: MAC addresses change, serials are not
1850
- * readable on every platform, and both can be cloned. Persist it, never
1851
- * regenerate it on update, and never let a failed write invent a new one —
1852
- * a new id is a new seat.
1853
- */
1854
- export function deviceId(): string {
1855
- try {
1856
- const existing = readFileSync(DEVICE_FILE, "utf8").trim();
1857
- if (existing) return existing;
1858
- } catch {
1859
- /* first run */
1860
- }
1861
-
1862
- const fresh = "device://" + randomUUID();
1863
- mkdirSync(DATA_DIR, { recursive: true });
1864
- writeFileSync(DEVICE_FILE, fresh, { mode: 0o600 });
1865
- return fresh;
1866
- }
1867
-
1868
- export function loadState(): StoredState | null {
1869
- try {
1870
- return JSON.parse(readFileSync(STATE_FILE, "utf8")) as StoredState;
1871
- } catch {
1872
- return null;
1873
- }
1874
- }
1875
-
1876
- function saveState(state: StoredState): void {
1877
- mkdirSync(DATA_DIR, { recursive: true });
1878
- writeFileSync(STATE_FILE, JSON.stringify(state), { mode: 0o600 });
1879
- }
1880
-
1881
- /**
1882
- * False when the local clock sits more than CLOCK_TOLERANCE_SECS behind the
1883
- * moment of the last check — the signature of someone trying to outlive an
1884
- * expiry. Forward jumps are not flagged: they only cost the user.
1885
- */
1886
- export function clockIsSane(state: StoredState | null = loadState()): boolean {
1887
- if (!state || !state.checkedAtLocal) return true;
1888
- return Math.floor(Date.now() / 1000) - state.checkedAtLocal >= -CLOCK_TOLERANCE_SECS;
1889
- }
1890
-
1891
- /** The online verdict, using the server-computed remaining days. */
1892
- export function isLicensed(state: StoredState | null = loadState()): boolean {
1893
- if (!state) return false;
1894
- if (state.status !== "valid" && state.status !== "active") return false;
1895
- if (!clockIsSane(state)) return false;
1896
- // Server-computed: never do date math against the local clock.
1897
- if (typeof state.expiresInDays === "number") return state.expiresInDays >= 0;
1898
- return true; // lifetime
1899
- }
1900
-
1901
- /**
1902
- * The verdict to use when the store cannot be reached. A tampered clock is
1903
- * refused outright; an untouched clock is trusted for OFFLINE_GRACE_SECS.
1904
- */
1905
- export function isLicensedOffline(state: StoredState | null = loadState()): boolean {
1906
- if (!state) return false;
1907
- if (!clockIsSane(state)) return false;
1908
- const age = Math.floor(Date.now() / 1000) - state.checkedAtLocal;
1909
- if (age > OFFLINE_GRACE_SECS) return false;
1910
- return isLicensed(state);
1911
- }
1912
-
1913
- async function call(verb: string, body: Record<string, string>) {
1914
- const res = await fetch(STORE + "?fluent-cart=" + verb, {
1915
- method: "POST",
1916
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1917
- body: new URLSearchParams(body).toString()
1918
- });
1919
- return { http: res.status, json: await res.json() };
1920
- }
1921
-
1922
- // instanceId defaults to the persisted device id, so a restart reuses the same
1923
- // seat instead of registering a new device.
1924
- export async function activate(licenseKey: string, fingerprint: string, email = "", instanceId = deviceId()): Promise<LicenseState> {
1925
- const { json } = await call("activate_license", {
1926
- item_id: String(PRODUCT_ID),
1927
- license_key: licenseKey,
1928
- site_url: instanceId,
1929
- device_fingerprint: fingerprint,
1930
- device_name: process.env.COMPUTERNAME || "desktop",
1931
- device_type: "Desktop (Node)",
1932
- os: process.platform + " " + process.arch,
1933
- email,
1934
- server_version: "1.0.0"
1935
- });
1936
-
1937
- // A refused activation arrives as HTTP 200 with success:false, an error_type
1938
- // and NO status field at all. Reading json.status, seeing undefined and carrying
1939
- // on is how a client ships unlocked -- throw instead, and surface the store's
1940
- // own message so the user knows what to do.
1941
- const status = String(json.status ?? "");
1942
-
1943
- if (status !== "valid" && status !== "active") {
1944
- throw new Error(json.message || json.error_type || "Activation refused by the store.");
1945
- }
1946
-
1947
- const state: StoredState = {
1948
- licenseKey,
1949
- deviceId: instanceId,
1950
- status: json.status,
1951
- token: json.license_token,
1952
- entitlements: json.entitlements,
1953
- expiresInDays: json.expires_in_days ?? null,
1954
- errorType: json.error_type,
1955
- variationTitle: json.variation_title,
1956
- expires: json.expires,
1957
- serverTimeUnix: json.server_time_unix,
1958
- checkedAtLocal: Math.floor(Date.now() / 1000)
1959
- };
1960
- saveState(state);
1961
- return state;
1962
- }
1963
-
1964
- export async function check(licenseKey: string, fingerprint: string, instanceId = deviceId()): Promise<LicenseState> {
1965
- const { json } = await call("check_license", {
1966
- item_id: String(PRODUCT_ID),
1967
- license_key: licenseKey,
1968
- site_url: instanceId,
1969
- device_fingerprint: fingerprint
1970
- });
1971
-
1972
- const prev = loadState();
1973
- const state: StoredState = {
1974
- licenseKey,
1975
- deviceId: instanceId,
1976
- status: json.status ?? "unknown",
1977
- token: json.license_token ?? prev?.token,
1978
- entitlements: json.entitlements ?? prev?.entitlements,
1979
- expiresInDays: json.expires_in_days ?? prev?.expiresInDays ?? null,
1980
- variationTitle: json.variation_title ?? prev?.variationTitle,
1981
- expires: json.expires ?? prev?.expires,
1982
- serverTimeUnix: json.server_time_unix ?? prev?.serverTimeUnix,
1983
- checkedAtLocal: Math.floor(Date.now() / 1000)
1984
- };
1985
- saveState(state);
1986
- return state;
1987
- }
1988
-
1989
- export async function deactivate(licenseKey: string, instanceId = deviceId()): Promise<void> {
1990
- await call("deactivate_license", {
1991
- item_id: String(PRODUCT_ID),
1992
- license_key: licenseKey,
1993
- site_url: instanceId
1994
- });
1995
-
1996
- // The device id stays: it is this machine's identity, not the licence's.
1997
- try {
1998
- rmSync(STATE_FILE);
1999
- } catch {
2000
- /* nothing cached */
2001
- }
2002
- }
2003
-
2004
- export async function latestRelease(licenseKey: string, currentVersion: string, platform = "any") {
2005
- const query = new URLSearchParams({
2006
- product_id: String(PRODUCT_ID),
2007
- platform,
2008
- current_version: currentVersion,
2009
- license_key: licenseKey
2010
- });
2011
- const res = await fetch(STORE + "?fluent-cart=fastr_release_latest&" + query.toString());
2012
- return res.json();
2013
- }
2014
-
2015
- export async function reportUsage(licenseKey: string, metric: string, quantity: number, idempotencyKey: string) {
2016
- const { json } = await call("fastr_usage_report", {
2017
- license_key: licenseKey,
2018
- metric,
2019
- quantity: String(quantity),
2020
- idempotency_key: idempotencyKey
2021
- });
2022
- return json;
2023
- }
2024
-
2025
- // After verifying, compare claims.ins and claims.fp with this install and
2026
- // claims.prod / claims.ent with the product you are running.
2027
- export function verifyToken(token: string, publicKeyPem: string): Record<string, unknown> | null {
2028
- const parts = token.split(".");
2029
- if (parts.length !== 3) return null;
2030
- const verifier = createVerify("RSA-SHA256");
2031
- verifier.update(parts[0] + "." + parts[1]);
2032
- if (!verifier.verify(publicKeyPem, Buffer.from(parts[2], "base64url"))) return null;
2033
- const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2034
- if (typeof claims.exp === "number" && claims.exp < Math.floor(Date.now() / 1000)) return null;
2035
- return claims;
2036
- }
2037
-
2038
- /**
2039
- * Decide whether the app should run, binding the token to THIS installation.
2040
- *
2041
- * verifyToken proves the store signed the token and that it has not expired.
2042
- * It does not prove the token was issued for this machine or this product, so
2043
- * a token copied from another install passes it. Compare the claims before
2044
- * granting anything.
2045
- *
2046
- * claims.fp is a server-side HMAC of the device fingerprint and cannot be
2047
- * recomputed here, so claims.ins (the install id you sent as site_url) is the
2048
- * binding a client is able to check. That is friction against sharing, not a
2049
- * guarantee: the server's check() is what actually enforces seats.
2050
- */
2051
- export function entitlement(
2052
- token: string,
2053
- publicKeyPem: string,
2054
- expected: { installId?: string; productId?: number }
2055
- ): { ok: boolean; reason?: string; claims?: Record<string, unknown> } {
2056
- const claims = verifyToken(token, publicKeyPem);
2057
- if (!claims) return { ok: false, reason: "invalid_or_expired" };
2058
-
2059
- if (typeof expected.productId === "number" && Number(claims.prod) !== expected.productId) {
2060
- return { ok: false, reason: "wrong_product" };
2061
- }
2062
-
2063
- if (expected.installId && claims.ins && String(claims.ins) !== expected.installId) {
2064
- return { ok: false, reason: "wrong_install" };
2065
- }
2066
-
2067
- return { ok: true, claims };
2068
- }
1850
+ text: `${header('Node / Electron', 'src/license.ts')}
1851
+ import { createVerify, randomUUID } from "node:crypto";
1852
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1853
+ import { homedir } from "node:os";
1854
+ import { join } from "node:path";
1855
+
1856
+ const STORE = "${base}";
1857
+ const PRODUCT_ID = ${productId};
1858
+
1859
+ /**
1860
+ * Where the device id and the last verdict live. In Electron, point this at
1861
+ * app.getPath("userData") before the first call.
1862
+ */
1863
+ const DATA_DIR = process.env.FASTR_DATA_DIR || join(homedir(), ".${slug}");
1864
+ const DEVICE_FILE = join(DATA_DIR, "device-id");
1865
+ const STATE_FILE = join(DATA_DIR, "license.json");
1866
+
1867
+ /** A backwards clock jump larger than this means the machine was moved. */
1868
+ const CLOCK_TOLERANCE_SECS = 300;
1869
+ /** How long a cached verdict survives without reaching the store. */
1870
+ const OFFLINE_GRACE_SECS = 7 * 24 * 60 * 60;
1871
+
1872
+ export type LicenseState = {
1873
+ status: string;
1874
+ token?: string;
1875
+ entitlements?: number[];
1876
+ expiresInDays?: number | null;
1877
+ errorType?: string;
1878
+ };
1879
+
1880
+ type StoredState = LicenseState & {
1881
+ licenseKey: string;
1882
+ deviceId: string;
1883
+ variationTitle?: string;
1884
+ expires?: string;
1885
+ /** Server clock at the last successful call — the only time we trust. */
1886
+ serverTimeUnix?: number;
1887
+ /** Local clock at that same moment, used to detect a rollback. */
1888
+ checkedAtLocal: number;
1889
+ };
1890
+
1891
+ /**
1892
+ * device://<uuid>, created once and kept.
1893
+ *
1894
+ * Deriving this from hardware is wrong: MAC addresses change, serials are not
1895
+ * readable on every platform, and both can be cloned. Persist it, never
1896
+ * regenerate it on update, and never let a failed write invent a new one —
1897
+ * a new id is a new seat.
1898
+ */
1899
+ export function deviceId(): string {
1900
+ try {
1901
+ const existing = readFileSync(DEVICE_FILE, "utf8").trim();
1902
+ if (existing) return existing;
1903
+ } catch {
1904
+ /* first run */
1905
+ }
1906
+
1907
+ const fresh = "device://" + randomUUID();
1908
+ mkdirSync(DATA_DIR, { recursive: true });
1909
+ writeFileSync(DEVICE_FILE, fresh, { mode: 0o600 });
1910
+ return fresh;
1911
+ }
1912
+
1913
+ export function loadState(): StoredState | null {
1914
+ try {
1915
+ return JSON.parse(readFileSync(STATE_FILE, "utf8")) as StoredState;
1916
+ } catch {
1917
+ return null;
1918
+ }
1919
+ }
1920
+
1921
+ function saveState(state: StoredState): void {
1922
+ mkdirSync(DATA_DIR, { recursive: true });
1923
+ writeFileSync(STATE_FILE, JSON.stringify(state), { mode: 0o600 });
1924
+ }
1925
+
1926
+ /**
1927
+ * False when the local clock sits more than CLOCK_TOLERANCE_SECS behind the
1928
+ * moment of the last check — the signature of someone trying to outlive an
1929
+ * expiry. Forward jumps are not flagged: they only cost the user.
1930
+ */
1931
+ export function clockIsSane(state: StoredState | null = loadState()): boolean {
1932
+ if (!state || !state.checkedAtLocal) return true;
1933
+ return Math.floor(Date.now() / 1000) - state.checkedAtLocal >= -CLOCK_TOLERANCE_SECS;
1934
+ }
1935
+
1936
+ /** The online verdict, using the server-computed remaining days. */
1937
+ export function isLicensed(state: StoredState | null = loadState()): boolean {
1938
+ if (!state) return false;
1939
+ if (state.status !== "valid" && state.status !== "active") return false;
1940
+ if (!clockIsSane(state)) return false;
1941
+ // Server-computed: never do date math against the local clock.
1942
+ if (typeof state.expiresInDays === "number") return state.expiresInDays >= 0;
1943
+ return true; // lifetime
1944
+ }
1945
+
1946
+ /**
1947
+ * The verdict to use when the store cannot be reached. A tampered clock is
1948
+ * refused outright; an untouched clock is trusted for OFFLINE_GRACE_SECS.
1949
+ */
1950
+ export function isLicensedOffline(state: StoredState | null = loadState()): boolean {
1951
+ if (!state) return false;
1952
+ if (!clockIsSane(state)) return false;
1953
+ const age = Math.floor(Date.now() / 1000) - state.checkedAtLocal;
1954
+ if (age > OFFLINE_GRACE_SECS) return false;
1955
+ return isLicensed(state);
1956
+ }
1957
+
1958
+ async function call(verb: string, body: Record<string, string>) {
1959
+ const res = await fetch(STORE + "?fluent-cart=" + verb, {
1960
+ method: "POST",
1961
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1962
+ body: new URLSearchParams(body).toString()
1963
+ });
1964
+ return { http: res.status, json: await res.json() };
1965
+ }
1966
+
1967
+ // instanceId defaults to the persisted device id, so a restart reuses the same
1968
+ // seat instead of registering a new device.
1969
+ export async function activate(licenseKey: string, fingerprint: string, email = "", instanceId = deviceId()): Promise<LicenseState> {
1970
+ const { json } = await call("activate_license", {
1971
+ item_id: String(PRODUCT_ID),
1972
+ license_key: licenseKey,
1973
+ site_url: instanceId,
1974
+ device_fingerprint: fingerprint,
1975
+ device_name: process.env.COMPUTERNAME || "desktop",
1976
+ device_type: "Desktop (Node)",
1977
+ os: process.platform + " " + process.arch,
1978
+ email,
1979
+ server_version: "1.0.0"
1980
+ });
1981
+
1982
+ // A refused activation arrives as HTTP 200 with success:false, an error_type
1983
+ // and NO status field at all. Reading json.status, seeing undefined and carrying
1984
+ // on is how a client ships unlocked -- throw instead, and surface the store's
1985
+ // own message so the user knows what to do.
1986
+ const status = String(json.status ?? "");
1987
+
1988
+ if (status !== "valid" && status !== "active") {
1989
+ throw new Error(json.message || json.error_type || "Activation refused by the store.");
1990
+ }
1991
+
1992
+ const state: StoredState = {
1993
+ licenseKey,
1994
+ deviceId: instanceId,
1995
+ status: json.status,
1996
+ token: json.license_token,
1997
+ entitlements: json.entitlements,
1998
+ expiresInDays: json.expires_in_days ?? null,
1999
+ errorType: json.error_type,
2000
+ variationTitle: json.variation_title,
2001
+ expires: json.expires,
2002
+ serverTimeUnix: json.server_time_unix,
2003
+ checkedAtLocal: Math.floor(Date.now() / 1000)
2004
+ };
2005
+ saveState(state);
2006
+ return state;
2007
+ }
2008
+
2009
+ export async function check(licenseKey: string, fingerprint: string, instanceId = deviceId()): Promise<LicenseState> {
2010
+ const { json } = await call("check_license", {
2011
+ item_id: String(PRODUCT_ID),
2012
+ license_key: licenseKey,
2013
+ site_url: instanceId,
2014
+ device_fingerprint: fingerprint
2015
+ });
2016
+
2017
+ const prev = loadState();
2018
+ const state: StoredState = {
2019
+ licenseKey,
2020
+ deviceId: instanceId,
2021
+ status: json.status ?? "unknown",
2022
+ token: json.license_token ?? prev?.token,
2023
+ entitlements: json.entitlements ?? prev?.entitlements,
2024
+ expiresInDays: json.expires_in_days ?? prev?.expiresInDays ?? null,
2025
+ variationTitle: json.variation_title ?? prev?.variationTitle,
2026
+ expires: json.expires ?? prev?.expires,
2027
+ serverTimeUnix: json.server_time_unix ?? prev?.serverTimeUnix,
2028
+ checkedAtLocal: Math.floor(Date.now() / 1000)
2029
+ };
2030
+ saveState(state);
2031
+ return state;
2032
+ }
2033
+
2034
+ export async function deactivate(licenseKey: string, instanceId = deviceId()): Promise<void> {
2035
+ await call("deactivate_license", {
2036
+ item_id: String(PRODUCT_ID),
2037
+ license_key: licenseKey,
2038
+ site_url: instanceId
2039
+ });
2040
+
2041
+ // The device id stays: it is this machine's identity, not the licence's.
2042
+ try {
2043
+ rmSync(STATE_FILE);
2044
+ } catch {
2045
+ /* nothing cached */
2046
+ }
2047
+ }
2048
+
2049
+ export async function latestRelease(licenseKey: string, currentVersion: string, platform = "any") {
2050
+ const query = new URLSearchParams({
2051
+ product_id: String(PRODUCT_ID),
2052
+ platform,
2053
+ current_version: currentVersion,
2054
+ license_key: licenseKey
2055
+ });
2056
+ const res = await fetch(STORE + "?fluent-cart=fastr_release_latest&" + query.toString());
2057
+ return res.json();
2058
+ }
2059
+
2060
+ export async function reportUsage(licenseKey: string, metric: string, quantity: number, idempotencyKey: string) {
2061
+ const { json } = await call("fastr_usage_report", {
2062
+ license_key: licenseKey,
2063
+ metric,
2064
+ quantity: String(quantity),
2065
+ idempotency_key: idempotencyKey
2066
+ });
2067
+ return json;
2068
+ }
2069
+
2070
+ // After verifying, compare claims.ins and claims.fp with this install and
2071
+ // claims.prod / claims.ent with the product you are running.
2072
+ export function verifyToken(token: string, publicKeyPem: string): Record<string, unknown> | null {
2073
+ const parts = token.split(".");
2074
+ if (parts.length !== 3) return null;
2075
+ const verifier = createVerify("RSA-SHA256");
2076
+ verifier.update(parts[0] + "." + parts[1]);
2077
+ if (!verifier.verify(publicKeyPem, Buffer.from(parts[2], "base64url"))) return null;
2078
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2079
+ if (typeof claims.exp === "number" && claims.exp < Math.floor(Date.now() / 1000)) return null;
2080
+ return claims;
2081
+ }
2082
+
2083
+ /**
2084
+ * Decide whether the app should run, binding the token to THIS installation.
2085
+ *
2086
+ * verifyToken proves the store signed the token and that it has not expired.
2087
+ * It does not prove the token was issued for this machine or this product, so
2088
+ * a token copied from another install passes it. Compare the claims before
2089
+ * granting anything.
2090
+ *
2091
+ * claims.fp is a server-side HMAC of the device fingerprint and cannot be
2092
+ * recomputed here, so claims.ins (the install id you sent as site_url) is the
2093
+ * binding a client is able to check. That is friction against sharing, not a
2094
+ * guarantee: the server's check() is what actually enforces seats.
2095
+ */
2096
+ export function entitlement(
2097
+ token: string,
2098
+ publicKeyPem: string,
2099
+ expected: { installId?: string; productId?: number }
2100
+ ): { ok: boolean; reason?: string; claims?: Record<string, unknown> } {
2101
+ const claims = verifyToken(token, publicKeyPem);
2102
+ if (!claims) return { ok: false, reason: "invalid_or_expired" };
2103
+
2104
+ if (typeof expected.productId === "number" && Number(claims.prod) !== expected.productId) {
2105
+ return { ok: false, reason: "wrong_product" };
2106
+ }
2107
+
2108
+ if (expected.installId && claims.ins && String(claims.ins) !== expected.installId) {
2109
+ return { ok: false, reason: "wrong_install" };
2110
+ }
2111
+
2112
+ return { ok: true, claims };
2113
+ }
2069
2114
  `
2070
2115
  }
2071
2116
  ]
@@ -2076,200 +2121,200 @@ export function entitlement(
2076
2121
  content: [
2077
2122
  {
2078
2123
  type: 'text',
2079
- text: `${header('.NET (WPF / MAUI / console)', 'License.cs')}
2080
- using System;
2081
- using System.Collections.Generic;
2082
- using System.Net.Http;
2083
- using System.Security.Cryptography;
2084
- using System.Text;
2085
- using System.Text.Json;
2086
- using System.Threading.Tasks;
2087
-
2088
- public sealed class LicenseState
2089
- {
2090
- public string Status { get; set; } = "";
2091
- public string? Token { get; set; }
2092
- public List<int> Entitlements { get; set; } = new();
2093
- public string? ErrorType { get; set; }
2094
- }
2095
-
2096
- public static class FastrLicense
2097
- {
2098
- private const string Store = "${base}";
2099
- private const int ProductId = ${productId};
2100
- private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };
2101
-
2102
- private static async Task<JsonElement> CallAsync(string verb, Dictionary<string, string> body)
2103
- {
2104
- var res = await Http.PostAsync(Store + "?fluent-cart=" + verb, new FormUrlEncodedContent(body));
2105
- var text = await res.Content.ReadAsStringAsync();
2106
- using var doc = JsonDocument.Parse(text);
2107
- return doc.RootElement.Clone();
2108
- }
2109
-
2110
- public static async Task<LicenseState> ActivateAsync(string licenseKey, string instanceId, string fingerprint, string email)
2111
- {
2112
- var json = await CallAsync("activate_license", new Dictionary<string, string>
2113
- {
2114
- ["item_id"] = ProductId.ToString(),
2115
- ["license_key"] = licenseKey,
2116
- ["site_url"] = instanceId,
2117
- ["device_fingerprint"] = fingerprint,
2118
- ["device_name"] = Environment.MachineName,
2119
- ["device_type"] = "Desktop (.NET)",
2120
- ["os"] = Environment.OSVersion.ToString(),
2121
- ["email"] = email,
2122
- ["server_version"] = "1.0.0"
2123
- });
2124
-
2125
- // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2126
- var state = new LicenseState
2127
- {
2128
- Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
2129
- Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
2130
- ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
2131
- };
2132
-
2133
- if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2134
- {
2135
- foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2136
- }
2137
-
2138
- return state;
2139
- }
2140
-
2141
- public static async Task<LicenseState> CheckAsync(string licenseKey, string instanceId, string fingerprint)
2142
- {
2143
- var json = await CallAsync("check_license", new Dictionary<string, string>
2144
- {
2145
- ["item_id"] = ProductId.ToString(),
2146
- ["license_key"] = licenseKey,
2147
- ["site_url"] = instanceId,
2148
- ["device_fingerprint"] = fingerprint
2149
- });
2150
-
2151
- var state = new LicenseState
2152
- {
2153
- Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
2154
- Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
2155
- ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
2156
- };
2157
-
2158
- if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2159
- {
2160
- foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2161
- }
2162
-
2163
- return state;
2164
- }
2165
-
2166
- public static async Task DeactivateAsync(string licenseKey, string instanceId)
2167
- {
2168
- await CallAsync("deactivate_license", new Dictionary<string, string>
2169
- {
2170
- ["item_id"] = ProductId.ToString(),
2171
- ["license_key"] = licenseKey,
2172
- ["site_url"] = instanceId
2173
- });
2174
- }
2175
-
2176
- public static async Task<JsonElement> LatestReleaseAsync(string licenseKey, string currentVersion, string platform = "any")
2177
- {
2178
- var url = Store + "?fluent-cart=fastr_release_latest&product_id=" + ProductId
2179
- + "&platform=" + Uri.EscapeDataString(platform)
2180
- + "&current_version=" + Uri.EscapeDataString(currentVersion)
2181
- + "&license_key=" + Uri.EscapeDataString(licenseKey);
2182
-
2183
- var text = await Http.GetStringAsync(url);
2184
- using var doc = JsonDocument.Parse(text);
2185
- return doc.RootElement.Clone();
2186
- }
2187
-
2188
- public static Task<JsonElement> ReportUsageAsync(string licenseKey, string metric, int quantity, string idempotencyKey)
2189
- {
2190
- return CallAsync("fastr_usage_report", new Dictionary<string, string>
2191
- {
2192
- ["license_key"] = licenseKey,
2193
- ["metric"] = metric,
2194
- ["quantity"] = quantity.ToString(),
2195
- ["idempotency_key"] = idempotencyKey
2196
- });
2197
- }
2198
-
2199
- // After verifying, compare claims ins/fp with this install and prod/ent
2200
- // with the product you are running.
2201
- public static bool VerifyToken(string token, string publicKeyPem, out JsonElement claims)
2202
- {
2203
- claims = default;
2204
- var parts = token.Split('.');
2205
- if (parts.Length != 3) return false;
2206
-
2207
- using var rsa = RSA.Create();
2208
- rsa.ImportFromPem(publicKeyPem);
2209
-
2210
- var data = Encoding.ASCII.GetBytes(parts[0] + "." + parts[1]);
2211
- var signature = Base64UrlDecode(parts[2]);
2212
-
2213
- if (!rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) return false;
2214
-
2215
- using var doc = JsonDocument.Parse(Base64UrlDecode(parts[1]));
2216
- claims = doc.RootElement.Clone();
2217
- return true;
2218
- }
2219
-
2220
- /// <summary>
2221
- /// Bind the token to this installation. VerifyToken proves the store signed
2222
- /// it and that it has not expired; it does not prove the token was issued
2223
- /// for this machine or this product, so a token copied from another install
2224
- /// passes it. claims.fp is a server-side HMAC and cannot be recomputed
2225
- /// here, so claims.ins (the install id sent as site_url) is the binding a
2226
- /// client is able to check.
2227
- /// </summary>
2228
- public static bool Entitlement(
2229
- string token,
2230
- string publicKeyPem,
2231
- string installId,
2232
- int productId,
2233
- out JsonElement claims,
2234
- out string reason)
2235
- {
2236
- reason = "";
2237
-
2238
- if (!VerifyToken(token, publicKeyPem, out claims))
2239
- {
2240
- reason = "invalid_or_expired";
2241
- return false;
2242
- }
2243
-
2244
- if (productId > 0)
2245
- {
2246
- if (!claims.TryGetProperty("prod", out var prod)
2247
- || prod.ValueKind != JsonValueKind.Number
2248
- || prod.GetInt32() != productId)
2249
- {
2250
- reason = "wrong_product";
2251
- return false;
2252
- }
2253
- }
2254
-
2255
- if (!string.IsNullOrEmpty(installId)
2256
- && claims.TryGetProperty("ins", out var ins)
2257
- && ins.GetString() != installId)
2258
- {
2259
- reason = "wrong_install";
2260
- return false;
2261
- }
2262
-
2263
- return true;
2264
- }
2265
-
2266
- private static byte[] Base64UrlDecode(string value)
2267
- {
2268
- var padded = value.Replace('-', '+').Replace('_', '/');
2269
- padded += new string('=', (4 - padded.Length % 4) % 4);
2270
- return Convert.FromBase64String(padded);
2271
- }
2272
- }
2124
+ text: `${header('.NET (WPF / MAUI / console)', 'License.cs')}
2125
+ using System;
2126
+ using System.Collections.Generic;
2127
+ using System.Net.Http;
2128
+ using System.Security.Cryptography;
2129
+ using System.Text;
2130
+ using System.Text.Json;
2131
+ using System.Threading.Tasks;
2132
+
2133
+ public sealed class LicenseState
2134
+ {
2135
+ public string Status { get; set; } = "";
2136
+ public string? Token { get; set; }
2137
+ public List<int> Entitlements { get; set; } = new();
2138
+ public string? ErrorType { get; set; }
2139
+ }
2140
+
2141
+ public static class FastrLicense
2142
+ {
2143
+ private const string Store = "${base}";
2144
+ private const int ProductId = ${productId};
2145
+ private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };
2146
+
2147
+ private static async Task<JsonElement> CallAsync(string verb, Dictionary<string, string> body)
2148
+ {
2149
+ var res = await Http.PostAsync(Store + "?fluent-cart=" + verb, new FormUrlEncodedContent(body));
2150
+ var text = await res.Content.ReadAsStringAsync();
2151
+ using var doc = JsonDocument.Parse(text);
2152
+ return doc.RootElement.Clone();
2153
+ }
2154
+
2155
+ public static async Task<LicenseState> ActivateAsync(string licenseKey, string instanceId, string fingerprint, string email)
2156
+ {
2157
+ var json = await CallAsync("activate_license", new Dictionary<string, string>
2158
+ {
2159
+ ["item_id"] = ProductId.ToString(),
2160
+ ["license_key"] = licenseKey,
2161
+ ["site_url"] = instanceId,
2162
+ ["device_fingerprint"] = fingerprint,
2163
+ ["device_name"] = Environment.MachineName,
2164
+ ["device_type"] = "Desktop (.NET)",
2165
+ ["os"] = Environment.OSVersion.ToString(),
2166
+ ["email"] = email,
2167
+ ["server_version"] = "1.0.0"
2168
+ });
2169
+
2170
+ // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2171
+ var state = new LicenseState
2172
+ {
2173
+ Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
2174
+ Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
2175
+ ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
2176
+ };
2177
+
2178
+ if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2179
+ {
2180
+ foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2181
+ }
2182
+
2183
+ return state;
2184
+ }
2185
+
2186
+ public static async Task<LicenseState> CheckAsync(string licenseKey, string instanceId, string fingerprint)
2187
+ {
2188
+ var json = await CallAsync("check_license", new Dictionary<string, string>
2189
+ {
2190
+ ["item_id"] = ProductId.ToString(),
2191
+ ["license_key"] = licenseKey,
2192
+ ["site_url"] = instanceId,
2193
+ ["device_fingerprint"] = fingerprint
2194
+ });
2195
+
2196
+ var state = new LicenseState
2197
+ {
2198
+ Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
2199
+ Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
2200
+ ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
2201
+ };
2202
+
2203
+ if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2204
+ {
2205
+ foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2206
+ }
2207
+
2208
+ return state;
2209
+ }
2210
+
2211
+ public static async Task DeactivateAsync(string licenseKey, string instanceId)
2212
+ {
2213
+ await CallAsync("deactivate_license", new Dictionary<string, string>
2214
+ {
2215
+ ["item_id"] = ProductId.ToString(),
2216
+ ["license_key"] = licenseKey,
2217
+ ["site_url"] = instanceId
2218
+ });
2219
+ }
2220
+
2221
+ public static async Task<JsonElement> LatestReleaseAsync(string licenseKey, string currentVersion, string platform = "any")
2222
+ {
2223
+ var url = Store + "?fluent-cart=fastr_release_latest&product_id=" + ProductId
2224
+ + "&platform=" + Uri.EscapeDataString(platform)
2225
+ + "&current_version=" + Uri.EscapeDataString(currentVersion)
2226
+ + "&license_key=" + Uri.EscapeDataString(licenseKey);
2227
+
2228
+ var text = await Http.GetStringAsync(url);
2229
+ using var doc = JsonDocument.Parse(text);
2230
+ return doc.RootElement.Clone();
2231
+ }
2232
+
2233
+ public static Task<JsonElement> ReportUsageAsync(string licenseKey, string metric, int quantity, string idempotencyKey)
2234
+ {
2235
+ return CallAsync("fastr_usage_report", new Dictionary<string, string>
2236
+ {
2237
+ ["license_key"] = licenseKey,
2238
+ ["metric"] = metric,
2239
+ ["quantity"] = quantity.ToString(),
2240
+ ["idempotency_key"] = idempotencyKey
2241
+ });
2242
+ }
2243
+
2244
+ // After verifying, compare claims ins/fp with this install and prod/ent
2245
+ // with the product you are running.
2246
+ public static bool VerifyToken(string token, string publicKeyPem, out JsonElement claims)
2247
+ {
2248
+ claims = default;
2249
+ var parts = token.Split('.');
2250
+ if (parts.Length != 3) return false;
2251
+
2252
+ using var rsa = RSA.Create();
2253
+ rsa.ImportFromPem(publicKeyPem);
2254
+
2255
+ var data = Encoding.ASCII.GetBytes(parts[0] + "." + parts[1]);
2256
+ var signature = Base64UrlDecode(parts[2]);
2257
+
2258
+ if (!rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) return false;
2259
+
2260
+ using var doc = JsonDocument.Parse(Base64UrlDecode(parts[1]));
2261
+ claims = doc.RootElement.Clone();
2262
+ return true;
2263
+ }
2264
+
2265
+ /// <summary>
2266
+ /// Bind the token to this installation. VerifyToken proves the store signed
2267
+ /// it and that it has not expired; it does not prove the token was issued
2268
+ /// for this machine or this product, so a token copied from another install
2269
+ /// passes it. claims.fp is a server-side HMAC and cannot be recomputed
2270
+ /// here, so claims.ins (the install id sent as site_url) is the binding a
2271
+ /// client is able to check.
2272
+ /// </summary>
2273
+ public static bool Entitlement(
2274
+ string token,
2275
+ string publicKeyPem,
2276
+ string installId,
2277
+ int productId,
2278
+ out JsonElement claims,
2279
+ out string reason)
2280
+ {
2281
+ reason = "";
2282
+
2283
+ if (!VerifyToken(token, publicKeyPem, out claims))
2284
+ {
2285
+ reason = "invalid_or_expired";
2286
+ return false;
2287
+ }
2288
+
2289
+ if (productId > 0)
2290
+ {
2291
+ if (!claims.TryGetProperty("prod", out var prod)
2292
+ || prod.ValueKind != JsonValueKind.Number
2293
+ || prod.GetInt32() != productId)
2294
+ {
2295
+ reason = "wrong_product";
2296
+ return false;
2297
+ }
2298
+ }
2299
+
2300
+ if (!string.IsNullOrEmpty(installId)
2301
+ && claims.TryGetProperty("ins", out var ins)
2302
+ && ins.GetString() != installId)
2303
+ {
2304
+ reason = "wrong_install";
2305
+ return false;
2306
+ }
2307
+
2308
+ return true;
2309
+ }
2310
+
2311
+ private static byte[] Base64UrlDecode(string value)
2312
+ {
2313
+ var padded = value.Replace('-', '+').Replace('_', '/');
2314
+ padded += new string('=', (4 - padded.Length % 4) % 4);
2315
+ return Convert.FromBase64String(padded);
2316
+ }
2317
+ }
2273
2318
  `
2274
2319
  }
2275
2320
  ]
@@ -2280,257 +2325,257 @@ public static class FastrLicense
2280
2325
  content: [
2281
2326
  {
2282
2327
  type: 'text',
2283
- text: `${header('Go (CLI / service)', 'license/license.go')}
2284
- package license
2285
-
2286
- import (
2287
- "crypto"
2288
- "crypto/rsa"
2289
- "crypto/sha256"
2290
- "crypto/x509"
2291
- "encoding/base64"
2292
- "encoding/json"
2293
- "encoding/pem"
2294
- "errors"
2295
- "io"
2296
- "strconv"
2297
- "net/http"
2298
- "net/url"
2299
- "os"
2300
- "runtime"
2301
- "strings"
2302
- "time"
2303
- )
2304
-
2305
- const (
2306
- Store = "${base}"
2307
- ProductID = "${productId}"
2308
- )
2309
-
2310
- type State struct {
2311
- Status string
2312
- Token string
2313
- Entitlements []int
2314
- ErrorType string
2315
- }
2316
-
2317
- func call(verb string, body url.Values) (map[string]any, error) {
2318
- res, err := http.PostForm(Store+"?fluent-cart="+verb, body)
2319
- if err != nil {
2320
- return nil, err
2321
- }
2322
- defer res.Body.Close()
2323
-
2324
- raw, err := io.ReadAll(res.Body)
2325
- if err != nil {
2326
- return nil, err
2327
- }
2328
-
2329
- var out map[string]any
2330
- if err := json.Unmarshal(raw, &out); err != nil {
2331
- return nil, err
2332
- }
2333
- return out, nil
2334
- }
2335
-
2336
- func Activate(key, instanceID, fingerprint, email string) (State, error) {
2337
- host, _ := os.Hostname()
2338
-
2339
- out, err := call("activate_license", url.Values{
2340
- "item_id": {ProductID},
2341
- "license_key": {key},
2342
- "site_url": {instanceID},
2343
- "device_fingerprint": {fingerprint},
2344
- "device_name": {host},
2345
- "device_type": {"CLI (Go)"},
2346
- "os": {runtime.GOOS + " " + runtime.GOARCH},
2347
- "email": {email},
2348
- "server_version": {"1.0.0"},
2349
- })
2350
- if err != nil {
2351
- return State{}, err
2352
- }
2353
-
2354
- // key_mismatch and invalid_activation come back as HTTP 200 success=true.
2355
- state := State{
2356
- Status: asString(out["status"]),
2357
- Token: asString(out["license_token"]),
2358
- ErrorType: asString(out["error_type"]),
2359
- }
2360
-
2361
- if list, ok := out["entitlements"].([]any); ok {
2362
- for _, v := range list {
2363
- if f, ok := v.(float64); ok {
2364
- state.Entitlements = append(state.Entitlements, int(f))
2365
- }
2366
- }
2367
- }
2368
-
2369
- return state, nil
2370
- }
2371
-
2372
- func Check(key, instanceID, fingerprint string) (State, error) {
2373
- out, err := call("check_license", url.Values{
2374
- "item_id": {ProductID},
2375
- "license_key": {key},
2376
- "site_url": {instanceID},
2377
- "device_fingerprint": {fingerprint},
2378
- })
2379
- if err != nil {
2380
- return State{}, err
2381
- }
2382
-
2383
- state := State{
2384
- Status: asString(out["status"]),
2385
- Token: asString(out["license_token"]),
2386
- ErrorType: asString(out["error_type"]),
2387
- }
2388
-
2389
- if list, ok := out["entitlements"].([]any); ok {
2390
- for _, v := range list {
2391
- if f, ok := v.(float64); ok {
2392
- state.Entitlements = append(state.Entitlements, int(f))
2393
- }
2394
- }
2395
- }
2396
-
2397
- return state, nil
2398
- }
2399
-
2400
- func Deactivate(key, instanceID string) error {
2401
- _, err := call("deactivate_license", url.Values{
2402
- "item_id": {ProductID},
2403
- "license_key": {key},
2404
- "site_url": {instanceID},
2405
- })
2406
- return err
2407
- }
2408
-
2409
- func LatestRelease(key, currentVersion, platform string) (map[string]any, error) {
2410
- query := url.Values{
2411
- "product_id": {ProductID},
2412
- "platform": {platform},
2413
- "current_version": {currentVersion},
2414
- "license_key": {key},
2415
- }
2416
-
2417
- res, err := http.Get(Store + "?fluent-cart=fastr_release_latest&" + query.Encode())
2418
- if err != nil {
2419
- return nil, err
2420
- }
2421
- defer res.Body.Close()
2422
-
2423
- raw, err := io.ReadAll(res.Body)
2424
- if err != nil {
2425
- return nil, err
2426
- }
2427
-
2428
- var out map[string]any
2429
- if err := json.Unmarshal(raw, &out); err != nil {
2430
- return nil, err
2431
- }
2432
-
2433
- return out, nil
2434
- }
2435
-
2436
- func ReportUsage(key, metric string, quantity int, idempotencyKey string) (map[string]any, error) {
2437
- return call("fastr_usage_report", url.Values{
2438
- "license_key": {key},
2439
- "metric": {metric},
2440
- "quantity": {strconv.Itoa(quantity)},
2441
- "idempotency_key": {idempotencyKey},
2442
- })
2443
- }
2444
-
2445
- // After verifying, compare claims["ins"] and claims["fp"] with this install
2446
- // and claims["prod"] / claims["ent"] with the product you are running.
2447
- // VerifyToken checks an RS256 licence token against the store's public key.// VerifyToken checks an RS256 licence token against the store's public key.
2448
- func VerifyToken(token, publicKeyPEM string) (map[string]any, error) {
2449
- parts := strings.Split(token, ".")
2450
- if len(parts) != 3 {
2451
- return nil, errors.New("malformed token")
2452
- }
2453
-
2454
- block, _ := pem.Decode([]byte(publicKeyPEM))
2455
- if block == nil {
2456
- return nil, errors.New("bad public key")
2457
- }
2458
-
2459
- pub, err := x509.ParsePKIXPublicKey(block.Bytes)
2460
- if err != nil {
2461
- return nil, err
2462
- }
2463
-
2464
- rsaPub, ok := pub.(*rsa.PublicKey)
2465
- if !ok {
2466
- return nil, errors.New("not an RSA key")
2467
- }
2468
-
2469
- sig, err := base64.RawURLEncoding.DecodeString(parts[2])
2470
- if err != nil {
2471
- return nil, err
2472
- }
2473
-
2474
- digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
2475
- if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
2476
- return nil, err
2477
- }
2478
-
2479
- payload, err := base64.RawURLEncoding.DecodeString(parts[1])
2480
- if err != nil {
2481
- return nil, err
2482
- }
2483
-
2484
- var claims map[string]any
2485
- if err := json.Unmarshal(payload, &claims); err != nil {
2486
- return nil, err
2487
- }
2488
-
2489
- if exp, ok := claims["exp"].(float64); ok && int64(exp) < time.Now().Unix() {
2490
- return nil, errors.New("token expired")
2491
- }
2492
-
2493
- return claims, nil
2494
- }
2495
-
2496
- // Entitlement binds the token to THIS installation.
2497
- //
2498
- // VerifyToken proves the store signed the token and that it has not expired.
2499
- // It does not prove the token was issued for this machine or this product, so
2500
- // a token copied from another install passes it. Compare the claims before
2501
- // granting anything.
2502
- //
2503
- // claims["fp"] is a server-side HMAC of the device fingerprint and cannot be
2504
- // recomputed here, so claims["ins"] - the install id sent as site_url - is the
2505
- // binding a client is able to check.
2506
- func Entitlement(token, publicKeyPEM, installID string, productID int) (map[string]any, string) {
2507
- claims, err := VerifyToken(token, publicKeyPEM)
2508
- if err != nil {
2509
- return nil, "invalid_or_expired"
2510
- }
2511
-
2512
- if productID > 0 {
2513
- prod, ok := claims["prod"].(float64)
2514
- if !ok || int(prod) != productID {
2515
- return nil, "wrong_product"
2516
- }
2517
- }
2518
-
2519
- if installID != "" {
2520
- if ins, ok := claims["ins"].(string); ok && ins != installID {
2521
- return nil, "wrong_install"
2522
- }
2523
- }
2524
-
2525
- return claims, ""
2526
- }
2527
-
2528
- func asString(v any) string {
2529
- if s, ok := v.(string); ok {
2530
- return s
2531
- }
2532
- return ""
2533
- }
2328
+ text: `${header('Go (CLI / service)', 'license/license.go')}
2329
+ package license
2330
+
2331
+ import (
2332
+ "crypto"
2333
+ "crypto/rsa"
2334
+ "crypto/sha256"
2335
+ "crypto/x509"
2336
+ "encoding/base64"
2337
+ "encoding/json"
2338
+ "encoding/pem"
2339
+ "errors"
2340
+ "io"
2341
+ "strconv"
2342
+ "net/http"
2343
+ "net/url"
2344
+ "os"
2345
+ "runtime"
2346
+ "strings"
2347
+ "time"
2348
+ )
2349
+
2350
+ const (
2351
+ Store = "${base}"
2352
+ ProductID = "${productId}"
2353
+ )
2354
+
2355
+ type State struct {
2356
+ Status string
2357
+ Token string
2358
+ Entitlements []int
2359
+ ErrorType string
2360
+ }
2361
+
2362
+ func call(verb string, body url.Values) (map[string]any, error) {
2363
+ res, err := http.PostForm(Store+"?fluent-cart="+verb, body)
2364
+ if err != nil {
2365
+ return nil, err
2366
+ }
2367
+ defer res.Body.Close()
2368
+
2369
+ raw, err := io.ReadAll(res.Body)
2370
+ if err != nil {
2371
+ return nil, err
2372
+ }
2373
+
2374
+ var out map[string]any
2375
+ if err := json.Unmarshal(raw, &out); err != nil {
2376
+ return nil, err
2377
+ }
2378
+ return out, nil
2379
+ }
2380
+
2381
+ func Activate(key, instanceID, fingerprint, email string) (State, error) {
2382
+ host, _ := os.Hostname()
2383
+
2384
+ out, err := call("activate_license", url.Values{
2385
+ "item_id": {ProductID},
2386
+ "license_key": {key},
2387
+ "site_url": {instanceID},
2388
+ "device_fingerprint": {fingerprint},
2389
+ "device_name": {host},
2390
+ "device_type": {"CLI (Go)"},
2391
+ "os": {runtime.GOOS + " " + runtime.GOARCH},
2392
+ "email": {email},
2393
+ "server_version": {"1.0.0"},
2394
+ })
2395
+ if err != nil {
2396
+ return State{}, err
2397
+ }
2398
+
2399
+ // key_mismatch and invalid_activation come back as HTTP 200 success=true.
2400
+ state := State{
2401
+ Status: asString(out["status"]),
2402
+ Token: asString(out["license_token"]),
2403
+ ErrorType: asString(out["error_type"]),
2404
+ }
2405
+
2406
+ if list, ok := out["entitlements"].([]any); ok {
2407
+ for _, v := range list {
2408
+ if f, ok := v.(float64); ok {
2409
+ state.Entitlements = append(state.Entitlements, int(f))
2410
+ }
2411
+ }
2412
+ }
2413
+
2414
+ return state, nil
2415
+ }
2416
+
2417
+ func Check(key, instanceID, fingerprint string) (State, error) {
2418
+ out, err := call("check_license", url.Values{
2419
+ "item_id": {ProductID},
2420
+ "license_key": {key},
2421
+ "site_url": {instanceID},
2422
+ "device_fingerprint": {fingerprint},
2423
+ })
2424
+ if err != nil {
2425
+ return State{}, err
2426
+ }
2427
+
2428
+ state := State{
2429
+ Status: asString(out["status"]),
2430
+ Token: asString(out["license_token"]),
2431
+ ErrorType: asString(out["error_type"]),
2432
+ }
2433
+
2434
+ if list, ok := out["entitlements"].([]any); ok {
2435
+ for _, v := range list {
2436
+ if f, ok := v.(float64); ok {
2437
+ state.Entitlements = append(state.Entitlements, int(f))
2438
+ }
2439
+ }
2440
+ }
2441
+
2442
+ return state, nil
2443
+ }
2444
+
2445
+ func Deactivate(key, instanceID string) error {
2446
+ _, err := call("deactivate_license", url.Values{
2447
+ "item_id": {ProductID},
2448
+ "license_key": {key},
2449
+ "site_url": {instanceID},
2450
+ })
2451
+ return err
2452
+ }
2453
+
2454
+ func LatestRelease(key, currentVersion, platform string) (map[string]any, error) {
2455
+ query := url.Values{
2456
+ "product_id": {ProductID},
2457
+ "platform": {platform},
2458
+ "current_version": {currentVersion},
2459
+ "license_key": {key},
2460
+ }
2461
+
2462
+ res, err := http.Get(Store + "?fluent-cart=fastr_release_latest&" + query.Encode())
2463
+ if err != nil {
2464
+ return nil, err
2465
+ }
2466
+ defer res.Body.Close()
2467
+
2468
+ raw, err := io.ReadAll(res.Body)
2469
+ if err != nil {
2470
+ return nil, err
2471
+ }
2472
+
2473
+ var out map[string]any
2474
+ if err := json.Unmarshal(raw, &out); err != nil {
2475
+ return nil, err
2476
+ }
2477
+
2478
+ return out, nil
2479
+ }
2480
+
2481
+ func ReportUsage(key, metric string, quantity int, idempotencyKey string) (map[string]any, error) {
2482
+ return call("fastr_usage_report", url.Values{
2483
+ "license_key": {key},
2484
+ "metric": {metric},
2485
+ "quantity": {strconv.Itoa(quantity)},
2486
+ "idempotency_key": {idempotencyKey},
2487
+ })
2488
+ }
2489
+
2490
+ // After verifying, compare claims["ins"] and claims["fp"] with this install
2491
+ // and claims["prod"] / claims["ent"] with the product you are running.
2492
+ // VerifyToken checks an RS256 licence token against the store's public key.// VerifyToken checks an RS256 licence token against the store's public key.
2493
+ func VerifyToken(token, publicKeyPEM string) (map[string]any, error) {
2494
+ parts := strings.Split(token, ".")
2495
+ if len(parts) != 3 {
2496
+ return nil, errors.New("malformed token")
2497
+ }
2498
+
2499
+ block, _ := pem.Decode([]byte(publicKeyPEM))
2500
+ if block == nil {
2501
+ return nil, errors.New("bad public key")
2502
+ }
2503
+
2504
+ pub, err := x509.ParsePKIXPublicKey(block.Bytes)
2505
+ if err != nil {
2506
+ return nil, err
2507
+ }
2508
+
2509
+ rsaPub, ok := pub.(*rsa.PublicKey)
2510
+ if !ok {
2511
+ return nil, errors.New("not an RSA key")
2512
+ }
2513
+
2514
+ sig, err := base64.RawURLEncoding.DecodeString(parts[2])
2515
+ if err != nil {
2516
+ return nil, err
2517
+ }
2518
+
2519
+ digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
2520
+ if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
2521
+ return nil, err
2522
+ }
2523
+
2524
+ payload, err := base64.RawURLEncoding.DecodeString(parts[1])
2525
+ if err != nil {
2526
+ return nil, err
2527
+ }
2528
+
2529
+ var claims map[string]any
2530
+ if err := json.Unmarshal(payload, &claims); err != nil {
2531
+ return nil, err
2532
+ }
2533
+
2534
+ if exp, ok := claims["exp"].(float64); ok && int64(exp) < time.Now().Unix() {
2535
+ return nil, errors.New("token expired")
2536
+ }
2537
+
2538
+ return claims, nil
2539
+ }
2540
+
2541
+ // Entitlement binds the token to THIS installation.
2542
+ //
2543
+ // VerifyToken proves the store signed the token and that it has not expired.
2544
+ // It does not prove the token was issued for this machine or this product, so
2545
+ // a token copied from another install passes it. Compare the claims before
2546
+ // granting anything.
2547
+ //
2548
+ // claims["fp"] is a server-side HMAC of the device fingerprint and cannot be
2549
+ // recomputed here, so claims["ins"] - the install id sent as site_url - is the
2550
+ // binding a client is able to check.
2551
+ func Entitlement(token, publicKeyPEM, installID string, productID int) (map[string]any, string) {
2552
+ claims, err := VerifyToken(token, publicKeyPEM)
2553
+ if err != nil {
2554
+ return nil, "invalid_or_expired"
2555
+ }
2556
+
2557
+ if productID > 0 {
2558
+ prod, ok := claims["prod"].(float64)
2559
+ if !ok || int(prod) != productID {
2560
+ return nil, "wrong_product"
2561
+ }
2562
+ }
2563
+
2564
+ if installID != "" {
2565
+ if ins, ok := claims["ins"].(string); ok && ins != installID {
2566
+ return nil, "wrong_install"
2567
+ }
2568
+ }
2569
+
2570
+ return claims, ""
2571
+ }
2572
+
2573
+ func asString(v any) string {
2574
+ if s, ok := v.(string); ok {
2575
+ return s
2576
+ }
2577
+ return ""
2578
+ }
2534
2579
  `
2535
2580
  }
2536
2581
  ]
@@ -2540,170 +2585,170 @@ func asString(v any) string {
2540
2585
  content: [
2541
2586
  {
2542
2587
  type: 'text',
2543
- text: `${header('Kotlin / JVM', 'LicenseClient.kt')}
2544
- import java.net.HttpURLConnection
2545
- import java.net.URL
2546
- import java.security.KeyFactory
2547
- import java.security.Signature
2548
- import java.security.spec.X509EncodedKeySpec
2549
- import java.util.Base64
2550
- import org.json.JSONObject
2551
-
2552
- const val STORE = "${base}"
2553
- const val PRODUCT_ID = ${productId}
2554
-
2555
- data class LicenseState(
2556
- val status: String,
2557
- val token: String?,
2558
- val entitlements: List<Int>,
2559
- val errorType: String?
2560
- )
2561
-
2562
- fun call(verb: String, body: Map<String, String>): JSONObject {
2563
- val url = URL(STORE + "?fluent-cart=" + verb)
2564
- val conn = url.openConnection() as HttpURLConnection
2565
- conn.requestMethod = "POST"
2566
- conn.doOutput = true
2567
- conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
2568
- val form = body.entries.joinToString("&") { e ->
2569
- java.net.URLEncoder.encode(e.key, "UTF-8") + "=" + java.net.URLEncoder.encode(e.value, "UTF-8")
2570
- }
2571
- conn.outputStream.use { it.write(form.toByteArray()) }
2572
- return JSONObject(conn.inputStream.bufferedReader().readText())
2573
- }
2574
-
2575
- fun activate(key: String, instanceId: String, fingerprint: String, email: String): LicenseState {
2576
- val json = call("activate_license", mapOf(
2577
- "item_id" to PRODUCT_ID.toString(),
2578
- "license_key" to key,
2579
- "site_url" to instanceId,
2580
- "device_fingerprint" to fingerprint,
2581
- "device_name" to (System.getenv("COMPUTERNAME") ?: "desktop"),
2582
- "device_type" to "Desktop (JVM)",
2583
- "os" to System.getProperty("os.name") + " " + System.getProperty("os.arch"),
2584
- "email" to email,
2585
- "server_version" to "1.0.0"
2586
- ))
2587
-
2588
- // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2589
- val ents = mutableListOf<Int>()
2590
- json.optJSONArray("entitlements")?.let { arr ->
2591
- for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2592
- }
2593
-
2594
- return LicenseState(
2595
- status = json.optString("status"),
2596
- token = json.optString("license_token").ifEmpty { null },
2597
- entitlements = ents,
2598
- errorType = json.optString("error_type").ifEmpty { null }
2599
- )
2600
- }
2601
-
2602
- fun check(key: String, instanceId: String, fingerprint: String): LicenseState {
2603
- val json = call("check_license", mapOf(
2604
- "item_id" to PRODUCT_ID.toString(),
2605
- "license_key" to key,
2606
- "site_url" to instanceId,
2607
- "device_fingerprint" to fingerprint
2608
- ))
2609
-
2610
- val ents = mutableListOf<Int>()
2611
- json.optJSONArray("entitlements")?.let { arr ->
2612
- for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2613
- }
2614
-
2615
- return LicenseState(
2616
- status = json.optString("status"),
2617
- token = json.optString("license_token").ifEmpty { null },
2618
- entitlements = ents,
2619
- errorType = json.optString("error_type").ifEmpty { null }
2620
- )
2621
- }
2622
-
2623
- fun deactivate(key: String, instanceId: String) {
2624
- call("deactivate_license", mapOf(
2625
- "item_id" to PRODUCT_ID.toString(),
2626
- "license_key" to key,
2627
- "site_url" to instanceId
2628
- ))
2629
- }
2630
-
2631
- fun latestRelease(key: String, currentVersion: String, platform: String = "any"): JSONObject {
2632
- val query = "product_id=" + PRODUCT_ID +
2633
- "&platform=" + java.net.URLEncoder.encode(platform, "UTF-8") +
2634
- "&current_version=" + java.net.URLEncoder.encode(currentVersion, "UTF-8") +
2635
- "&license_key=" + java.net.URLEncoder.encode(key, "UTF-8")
2636
-
2637
- val connection = java.net.URL(STORE + "?fluent-cart=fastr_release_latest&" + query)
2638
- .openConnection() as java.net.HttpURLConnection
2639
-
2640
- return JSONObject(connection.inputStream.bufferedReader().readText())
2641
- }
2642
-
2643
- fun reportUsage(key: String, metric: String, quantity: Int, idempotencyKey: String): JSONObject {
2644
- return call("fastr_usage_report", mapOf(
2645
- "license_key" to key,
2646
- "metric" to metric,
2647
- "quantity" to quantity.toString(),
2648
- "idempotency_key" to idempotencyKey
2649
- ))
2650
- }
2651
-
2652
- // After verifying, compare claims.ins / claims.fp with this install and
2653
- // claims.prod / claims.ent with the product you are running.
2654
- fun verifyToken(token: String, publicKeyPem: String): JSONObject? {
2655
- val parts = token.split(".")
2656
- if (parts.size != 3) return null
2657
-
2658
- val pem = publicKeyPem
2659
- .replace("-----BEGIN PUBLIC KEY-----", "")
2660
- .replace("-----END PUBLIC KEY-----", "")
2661
- .replace("\\\\s".toRegex(), "")
2662
-
2663
- val keySpec = X509EncodedKeySpec(Base64.getDecoder().decode(pem))
2664
- val publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec)
2665
-
2666
- val verifier = Signature.getInstance("SHA256withRSA")
2667
- verifier.initVerify(publicKey)
2668
- verifier.update((parts[0] + "." + parts[1]).toByteArray())
2669
-
2670
- val signature = Base64.getUrlDecoder().decode(parts[2])
2671
- if (!verifier.verify(signature)) return null
2672
-
2673
- val payload = String(Base64.getUrlDecoder().decode(parts[1]))
2674
- return JSONObject(payload)
2675
- }
2676
-
2677
- // Entitlement binds the token to THIS installation.
2678
- //
2679
- // verifyToken only proves the store signed it: it does not check expiry, this
2680
- // machine, or this product. Compare the claims before granting anything.
2681
- // claims.fp is a server-side HMAC and cannot be recomputed here, so claims.ins
2682
- // - the install id sent as site_url - is the binding a client can check.
2683
- // Returns the claims and a null reason on success, or null and a reason.
2684
- fun entitlement(
2685
- token: String,
2686
- publicKeyPem: String,
2687
- installId: String?,
2688
- productId: Int
2689
- ): Pair<JSONObject?, String?> {
2690
- val claims = verifyToken(token, publicKeyPem) ?: return Pair(null, "invalid_or_expired")
2691
-
2692
- val exp = if (claims.has("exp")) claims.optLong("exp", 0L) else 0L
2693
- if (exp > 0L && exp <= System.currentTimeMillis() / 1000L) {
2694
- return Pair(null, "invalid_or_expired")
2695
- }
2696
-
2697
- if (productId > 0 && claims.optInt("prod", -1) != productId) {
2698
- return Pair(null, "wrong_product")
2699
- }
2700
-
2701
- if (!installId.isNullOrEmpty() && claims.has("ins") && claims.optString("ins", "") != installId) {
2702
- return Pair(null, "wrong_install")
2703
- }
2704
-
2705
- return Pair(claims, null)
2706
- }
2588
+ text: `${header('Kotlin / JVM', 'LicenseClient.kt')}
2589
+ import java.net.HttpURLConnection
2590
+ import java.net.URL
2591
+ import java.security.KeyFactory
2592
+ import java.security.Signature
2593
+ import java.security.spec.X509EncodedKeySpec
2594
+ import java.util.Base64
2595
+ import org.json.JSONObject
2596
+
2597
+ const val STORE = "${base}"
2598
+ const val PRODUCT_ID = ${productId}
2599
+
2600
+ data class LicenseState(
2601
+ val status: String,
2602
+ val token: String?,
2603
+ val entitlements: List<Int>,
2604
+ val errorType: String?
2605
+ )
2606
+
2607
+ fun call(verb: String, body: Map<String, String>): JSONObject {
2608
+ val url = URL(STORE + "?fluent-cart=" + verb)
2609
+ val conn = url.openConnection() as HttpURLConnection
2610
+ conn.requestMethod = "POST"
2611
+ conn.doOutput = true
2612
+ conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
2613
+ val form = body.entries.joinToString("&") { e ->
2614
+ java.net.URLEncoder.encode(e.key, "UTF-8") + "=" + java.net.URLEncoder.encode(e.value, "UTF-8")
2615
+ }
2616
+ conn.outputStream.use { it.write(form.toByteArray()) }
2617
+ return JSONObject(conn.inputStream.bufferedReader().readText())
2618
+ }
2619
+
2620
+ fun activate(key: String, instanceId: String, fingerprint: String, email: String): LicenseState {
2621
+ val json = call("activate_license", mapOf(
2622
+ "item_id" to PRODUCT_ID.toString(),
2623
+ "license_key" to key,
2624
+ "site_url" to instanceId,
2625
+ "device_fingerprint" to fingerprint,
2626
+ "device_name" to (System.getenv("COMPUTERNAME") ?: "desktop"),
2627
+ "device_type" to "Desktop (JVM)",
2628
+ "os" to System.getProperty("os.name") + " " + System.getProperty("os.arch"),
2629
+ "email" to email,
2630
+ "server_version" to "1.0.0"
2631
+ ))
2632
+
2633
+ // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2634
+ val ents = mutableListOf<Int>()
2635
+ json.optJSONArray("entitlements")?.let { arr ->
2636
+ for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2637
+ }
2638
+
2639
+ return LicenseState(
2640
+ status = json.optString("status"),
2641
+ token = json.optString("license_token").ifEmpty { null },
2642
+ entitlements = ents,
2643
+ errorType = json.optString("error_type").ifEmpty { null }
2644
+ )
2645
+ }
2646
+
2647
+ fun check(key: String, instanceId: String, fingerprint: String): LicenseState {
2648
+ val json = call("check_license", mapOf(
2649
+ "item_id" to PRODUCT_ID.toString(),
2650
+ "license_key" to key,
2651
+ "site_url" to instanceId,
2652
+ "device_fingerprint" to fingerprint
2653
+ ))
2654
+
2655
+ val ents = mutableListOf<Int>()
2656
+ json.optJSONArray("entitlements")?.let { arr ->
2657
+ for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2658
+ }
2659
+
2660
+ return LicenseState(
2661
+ status = json.optString("status"),
2662
+ token = json.optString("license_token").ifEmpty { null },
2663
+ entitlements = ents,
2664
+ errorType = json.optString("error_type").ifEmpty { null }
2665
+ )
2666
+ }
2667
+
2668
+ fun deactivate(key: String, instanceId: String) {
2669
+ call("deactivate_license", mapOf(
2670
+ "item_id" to PRODUCT_ID.toString(),
2671
+ "license_key" to key,
2672
+ "site_url" to instanceId
2673
+ ))
2674
+ }
2675
+
2676
+ fun latestRelease(key: String, currentVersion: String, platform: String = "any"): JSONObject {
2677
+ val query = "product_id=" + PRODUCT_ID +
2678
+ "&platform=" + java.net.URLEncoder.encode(platform, "UTF-8") +
2679
+ "&current_version=" + java.net.URLEncoder.encode(currentVersion, "UTF-8") +
2680
+ "&license_key=" + java.net.URLEncoder.encode(key, "UTF-8")
2681
+
2682
+ val connection = java.net.URL(STORE + "?fluent-cart=fastr_release_latest&" + query)
2683
+ .openConnection() as java.net.HttpURLConnection
2684
+
2685
+ return JSONObject(connection.inputStream.bufferedReader().readText())
2686
+ }
2687
+
2688
+ fun reportUsage(key: String, metric: String, quantity: Int, idempotencyKey: String): JSONObject {
2689
+ return call("fastr_usage_report", mapOf(
2690
+ "license_key" to key,
2691
+ "metric" to metric,
2692
+ "quantity" to quantity.toString(),
2693
+ "idempotency_key" to idempotencyKey
2694
+ ))
2695
+ }
2696
+
2697
+ // After verifying, compare claims.ins / claims.fp with this install and
2698
+ // claims.prod / claims.ent with the product you are running.
2699
+ fun verifyToken(token: String, publicKeyPem: String): JSONObject? {
2700
+ val parts = token.split(".")
2701
+ if (parts.size != 3) return null
2702
+
2703
+ val pem = publicKeyPem
2704
+ .replace("-----BEGIN PUBLIC KEY-----", "")
2705
+ .replace("-----END PUBLIC KEY-----", "")
2706
+ .replace("\\\\s".toRegex(), "")
2707
+
2708
+ val keySpec = X509EncodedKeySpec(Base64.getDecoder().decode(pem))
2709
+ val publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec)
2710
+
2711
+ val verifier = Signature.getInstance("SHA256withRSA")
2712
+ verifier.initVerify(publicKey)
2713
+ verifier.update((parts[0] + "." + parts[1]).toByteArray())
2714
+
2715
+ val signature = Base64.getUrlDecoder().decode(parts[2])
2716
+ if (!verifier.verify(signature)) return null
2717
+
2718
+ val payload = String(Base64.getUrlDecoder().decode(parts[1]))
2719
+ return JSONObject(payload)
2720
+ }
2721
+
2722
+ // Entitlement binds the token to THIS installation.
2723
+ //
2724
+ // verifyToken only proves the store signed it: it does not check expiry, this
2725
+ // machine, or this product. Compare the claims before granting anything.
2726
+ // claims.fp is a server-side HMAC and cannot be recomputed here, so claims.ins
2727
+ // - the install id sent as site_url - is the binding a client can check.
2728
+ // Returns the claims and a null reason on success, or null and a reason.
2729
+ fun entitlement(
2730
+ token: String,
2731
+ publicKeyPem: String,
2732
+ installId: String?,
2733
+ productId: Int
2734
+ ): Pair<JSONObject?, String?> {
2735
+ val claims = verifyToken(token, publicKeyPem) ?: return Pair(null, "invalid_or_expired")
2736
+
2737
+ val exp = if (claims.has("exp")) claims.optLong("exp", 0L) else 0L
2738
+ if (exp > 0L && exp <= System.currentTimeMillis() / 1000L) {
2739
+ return Pair(null, "invalid_or_expired")
2740
+ }
2741
+
2742
+ if (productId > 0 && claims.optInt("prod", -1) != productId) {
2743
+ return Pair(null, "wrong_product")
2744
+ }
2745
+
2746
+ if (!installId.isNullOrEmpty() && claims.has("ins") && claims.optString("ins", "") != installId) {
2747
+ return Pair(null, "wrong_install")
2748
+ }
2749
+
2750
+ return Pair(claims, null)
2751
+ }
2707
2752
  `
2708
2753
  }
2709
2754
  ]