fluentcart-developer 2.3.0 → 2.3.1

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 (49) hide show
  1. package/README.md +59 -59
  2. package/dist/cards/fluentcart/tools.d.ts.map +1 -1
  3. package/dist/cards/fluentcart/tools.js +2301 -2161
  4. package/dist/cards/fluentcart/tools.js.map +1 -1
  5. package/dist/skills/fluentcart-developer/.claude-plugin/plugin.json +12 -12
  6. package/dist/skills/fluentcart-developer/.mcp.json +11 -11
  7. package/dist/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/fluent-cart/checkout.php +32 -32
  8. package/dist/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/functions.php +40 -40
  9. package/dist/skills/fluentcart-developer/examples/sample-fee-surcharge-plugin/fluentcart-fee-surcharge.php +38 -38
  10. package/dist/skills/fluentcart-developer/references/action-hooks-cart-checkout.md +1355 -1355
  11. package/dist/skills/fluentcart-developer/references/action-hooks-customers-users.md +266 -266
  12. package/dist/skills/fluentcart-developer/references/action-hooks-licenses.md +855 -855
  13. package/dist/skills/fluentcart-developer/references/action-hooks-orders.md +631 -631
  14. package/dist/skills/fluentcart-developer/references/action-hooks-payments-integrations.md +963 -963
  15. package/dist/skills/fluentcart-developer/references/action-hooks-products-coupons.md +585 -585
  16. package/dist/skills/fluentcart-developer/references/action-hooks-subscriptions.md +661 -661
  17. package/dist/skills/fluentcart-developer/references/database-models-query-builder.md +194 -194
  18. package/dist/skills/fluentcart-developer/references/database-models-reference.md +604 -604
  19. package/dist/skills/fluentcart-developer/references/engineering-notes.md +154 -154
  20. package/dist/skills/fluentcart-developer/references/fee-system-guide.md +449 -449
  21. package/dist/skills/fluentcart-developer/references/filter-hooks-cart-checkout.md +1202 -1202
  22. package/dist/skills/fluentcart-developer/references/filter-hooks-integrations-advanced.md +1598 -1598
  23. package/dist/skills/fluentcart-developer/references/filter-hooks-products-pricing.md +628 -628
  24. package/dist/skills/fluentcart-developer/references/filter-hooks-settings-configuration.md +1177 -1177
  25. package/dist/skills/fluentcart-developer/references/fluentcart-developer-guide.md +154 -154
  26. package/dist/skills/fluentcart-developer/references/ghost-product-selling.md +458 -458
  27. package/dist/skills/fluentcart-developer/references/modules-and-extensions-reference.md +224 -224
  28. package/dist/skills/fluentcart-developer/references/payment-gateway-integration.md +761 -761
  29. package/dist/skills/fluentcart-developer/references/rest-api-customer-profile.md +190 -190
  30. package/dist/skills/fluentcart-developer/references/rest-api-customers.md +1121 -1121
  31. package/dist/skills/fluentcart-developer/references/rest-api-dashboard-utilities.md +219 -219
  32. package/dist/skills/fluentcart-developer/references/rest-api-email-notifications.md +619 -619
  33. package/dist/skills/fluentcart-developer/references/rest-api-files.md +290 -290
  34. package/dist/skills/fluentcart-developer/references/rest-api-integrations.md +324 -324
  35. package/dist/skills/fluentcart-developer/references/rest-api-labels-attributes.md +321 -321
  36. package/dist/skills/fluentcart-developer/references/rest-api-order-bumps.md +200 -200
  37. package/dist/skills/fluentcart-developer/references/rest-api-overview.md +131 -131
  38. package/dist/skills/fluentcart-developer/references/rest-api-public-shop.md +172 -172
  39. package/dist/skills/fluentcart-developer/references/rest-api-reference.md +552 -552
  40. package/dist/skills/fluentcart-developer/references/rest-api-reports.md +377 -377
  41. package/dist/skills/fluentcart-developer/references/rest-api-roles-permissions.md +147 -147
  42. package/dist/skills/fluentcart-developer/references/rest-api-settings.md +528 -528
  43. package/dist/skills/fluentcart-developer/references/rest-api-shipping.md +799 -799
  44. package/dist/skills/fluentcart-developer/references/rest-api-tax.md +356 -356
  45. package/dist/skills/fluentcart-developer/references/subscription-customization.md +197 -197
  46. package/dist/skills/fluentcart-developer/scripts/cli.js +1 -1
  47. package/dist/version.d.ts +1 -1
  48. package/dist/version.js +1 -1
  49. package/package.json +65 -65
@@ -181,48 +181,48 @@ export function registerFluentCartTools(server) {
181
181
  }
182
182
  }, async ({ gatewaySlug, gatewayTitle, supportsSubscriptions }) => {
183
183
  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
- }
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
+ }
226
226
  `;
227
227
  return {
228
228
  content: [{ type: 'text', text: code }]
@@ -242,80 +242,80 @@ class ${className} extends AbstractPaymentGateway
242
242
  const slug = pluginTitle.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
243
243
  const constPrefix = slug.toUpperCase().replace(/-/g, '_');
244
244
  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
- ]);
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
+ ]);
266
266
  }`
267
267
  : '';
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
- }
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
+ }
319
319
  `;
320
320
  return {
321
321
  content: [{ type: 'text', text: code }]
@@ -335,95 +335,95 @@ function ${slug.replace(/-/g, '_')}_is_license_active(): bool
335
335
  const defaultSvg = iconSvg ||
336
336
  `<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
337
  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>';
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>';
343
343
  break;`)
344
344
  .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
- }
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
+ }
427
427
  `;
428
428
  return {
429
429
  content: [{ type: 'text', text: code }]
@@ -459,785 +459,799 @@ ${subRouteCases}
459
459
  .join('\n')}\n`;
460
460
  let code = '';
461
461
  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
- // keyring = "3"
469
- // uuid = { version = "1", features = ["v4"] }
470
- //
471
- // All functions are blocking: call them from tauri::async_runtime::spawn_blocking.
472
-
473
- use serde::{Deserialize, Serialize};
474
- use std::collections::HashMap;
475
- use std::time::{SystemTime, UNIX_EPOCH};
476
-
477
- const STORE_URL: &str = "${base}";
478
- const ITEM_ID: u64 = ${productId};
479
- const SERVICE: &str = "${service}";
480
- const ACCOUNT_LICENSE: &str = "license-state";
481
- const ACCOUNT_DEVICE: &str = "device-id";
482
-
483
- /// Tolerance (seconds) for legitimate clock drift between checks. Anything
484
- /// larger than this means the machine's clock was moved, so the cached
485
- /// entitlement is no longer trustworthy.
486
- const CLOCK_TOLERANCE_SECS: i64 = 300;
487
-
488
- #[derive(Serialize, Deserialize, Debug, Clone, Default)]
489
- pub struct LicenseState {
490
- pub license_key: String,
491
- pub device_id: String,
492
- pub status: String,
493
- pub variation_title: String,
494
- pub expires: String,
495
- /// Server clock at the moment of this check — the only time source we trust.
496
- pub server_time_unix: i64,
497
- /// Local clock at that same moment, used to detect a clock that moved back.
498
- pub checked_at_local: i64,
499
- /// Pre-computed by the server so the client never does date math.
500
- pub expires_in_days: Option<i64>,
501
- pub activation_hash: String,
502
- }
503
-
504
- #[derive(Deserialize)]
505
- struct RawResponse {
506
- status: Option<String>,
507
- license_key: Option<String>,
508
- variation_title: Option<String>,
509
- expires: Option<String>,
510
- activation_hash: Option<String>,
511
- server_time_unix: Option<i64>,
512
- expires_in_days: Option<i64>,
513
- message: Option<String>,
514
- }
515
-
516
- fn now_unix() -> i64 {
517
- SystemTime::now()
518
- .duration_since(UNIX_EPOCH)
519
- .map(|d| d.as_secs() as i64)
520
- .unwrap_or(0)
521
- }
522
-
523
- /// A stable per-install identifier, kept in the OS keychain. The UUID is what
524
- /// FluentCart stores as device://<uuid>, so it must survive app restarts.
525
- pub fn device_id() -> Result<String, String> {
526
- let entry = keyring::Entry::new(SERVICE, ACCOUNT_DEVICE).map_err(|e| e.to_string())?;
527
- if let Ok(existing) = entry.get_password() {
528
- if !existing.is_empty() {
529
- return Ok(existing);
530
- }
531
- }
532
- let fresh = format!("device://{}", uuid::Uuid::new_v4());
533
- entry.set_password(&fresh).map_err(|e| e.to_string())?;
534
- Ok(fresh)
535
- }
536
-
537
- pub fn load_state() -> Option<LicenseState> {
538
- let entry = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE).ok()?;
539
- let raw = entry.get_password().ok()?;
540
- serde_json::from_str(&raw).ok()
541
- }
542
-
543
- fn store_state(state: &LicenseState) -> Result<(), String> {
544
- let entry = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE).map_err(|e| e.to_string())?;
545
- entry
546
- .set_password(&serde_json::to_string(state).map_err(|e| e.to_string())?)
547
- .map_err(|e| e.to_string())
548
- }
549
-
550
- fn post(endpoint: &str, params: &[(&str, String)]) -> Result<RawResponse, String> {
551
- let url = format!("{}?fluent-cart={}", STORE_URL, endpoint);
552
- let body: HashMap<&str, String> = params.iter().cloned().collect();
553
-
554
- let client = reqwest::blocking::Client::builder()
555
- .timeout(std::time::Duration::from_secs(15))
556
- .build()
557
- .map_err(|e| e.to_string())?;
558
-
559
- let res = client.post(&url).form(&body).send().map_err(|e| e.to_string())?;
560
- res.json::<RawResponse>().map_err(|e| e.to_string())
561
- }
562
-
563
- pub fn activate(license_key: &str) -> Result<LicenseState, String> {
564
- let device = device_id()?;
565
- let raw = post(
566
- "activate_license",
567
- &[
568
- ("license_key", license_key.trim().to_string()),
569
- ("item_id", ITEM_ID.to_string()),
570
- ("site_url", device.clone()),
571
- ("platform", std::env::consts::OS.to_string()),
572
- ("server_version", env!("CARGO_PKG_VERSION").to_string()),
573
- ],
574
- )?;
575
-
576
- let status = raw.status.unwrap_or_default();
577
- if status != "valid" && status != "active" {
578
- return Err(raw.message.unwrap_or_else(|| format!("Activation failed: {}", status)));
579
- }
580
-
581
- let state = LicenseState {
582
- license_key: license_key.trim().to_string(),
583
- device_id: device,
584
- status,
585
- variation_title: raw.variation_title.unwrap_or_default(),
586
- expires: raw.expires.unwrap_or_else(|| "lifetime".into()),
587
- server_time_unix: raw.server_time_unix.unwrap_or_else(now_unix),
588
- checked_at_local: now_unix(),
589
- expires_in_days: raw.expires_in_days,
590
- activation_hash: raw.activation_hash.unwrap_or_default(),
591
- };
592
- store_state(&state)?;
593
- Ok(state)
594
- }
595
-
596
- /// Re-validates against the store. Returns Ok(false) when the license is no
597
- /// longer valid but the call itself worked.
598
- pub fn validate() -> Result<bool, String> {
599
- let mut state = load_state().ok_or("No license stored on this device")?;
600
-
601
- let raw = post(
602
- "check_license",
603
- &[
604
- ("license_key", state.license_key.clone()),
605
- ("item_id", ITEM_ID.to_string()),
606
- ("site_url", state.device_id.clone()),
607
- ],
608
- )?;
609
-
610
- let status = raw.status.unwrap_or_default();
611
- let valid = status == "valid" || status == "active";
612
-
613
- state.status = status;
614
- state.expires = raw.expires.unwrap_or(state.expires);
615
- state.expires_in_days = raw.expires_in_days.or(state.expires_in_days);
616
- state.server_time_unix = raw.server_time_unix.unwrap_or_else(now_unix);
617
- state.checked_at_local = now_unix();
618
- store_state(&state)?;
619
-
620
- Ok(valid)
621
- }
622
-
623
- /// True when the machine's clock has not been moved backwards since the last
624
- /// successful check. A backwards jump is how users try to outlive an expiry.
625
- pub fn clock_is_sane() -> bool {
626
- match load_state() {
627
- Some(state) if state.checked_at_local > 0 => {
628
- let elapsed = now_unix() - state.checked_at_local;
629
- elapsed >= -CLOCK_TOLERANCE_SECS
630
- }
631
- _ => true,
632
- }
633
- }
634
-
635
- /// The entitlement decision the app should gate on. Offline is tolerated for a
636
- /// short grace window, but a tampered clock is not.
637
- pub fn is_licensed() -> bool {
638
- let Some(state) = load_state() else { return false };
639
- if state.status != "valid" && state.status != "active" {
640
- return false;
641
- }
642
- if !clock_is_sane() {
643
- return false;
644
- }
645
- match state.expires_in_days {
646
- // Server-computed remaining days — never derived from the local clock.
647
- Some(days) => days >= 0,
648
- None => true, // lifetime
649
- }
650
- }
651
-
652
- pub fn deactivate() -> Result<(), String> {
653
- let state = load_state().ok_or("No license stored on this device")?;
654
- let _ = post(
655
- "deactivate_license",
656
- &[
657
- ("license_key", state.license_key),
658
- ("item_id", ITEM_ID.to_string()),
659
- ("site_url", state.device_id),
660
- ],
661
- );
662
- if let Ok(entry) = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE) {
663
- let _ = entry.delete_credential();
664
- }
665
- Ok(())
666
- }
667
-
668
- // Tauri wiring (src/main.rs):
669
- // #[tauri::command]
670
- // async fn license_activate(key: String) -> Result<bool, String> {
671
- // tauri::async_runtime::spawn_blocking(move || licensing::activate(&key).map(|_| true))
672
- // .await.map_err(|e| e.to_string())?
673
- // }
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
+ ("platform", std::env::consts::OS.to_string()),
586
+ ("server_version", env!("CARGO_PKG_VERSION").to_string()),
587
+ ],
588
+ )?;
589
+
590
+ let status = raw.status.unwrap_or_default();
591
+ if status != "valid" && status != "active" {
592
+ return Err(raw.message.unwrap_or_else(|| format!("Activation failed: {}", status)));
593
+ }
594
+
595
+ let state = LicenseState {
596
+ license_key: license_key.trim().to_string(),
597
+ device_id: device,
598
+ status,
599
+ variation_title: raw.variation_title.unwrap_or_default(),
600
+ expires: raw.expires.unwrap_or_else(|| "lifetime".into()),
601
+ server_time_unix: raw.server_time_unix.unwrap_or_else(now_unix),
602
+ checked_at_local: now_unix(),
603
+ expires_in_days: raw.expires_in_days,
604
+ activation_hash: raw.activation_hash.unwrap_or_default(),
605
+ };
606
+ store_state(&state)?;
607
+ Ok(state)
608
+ }
609
+
610
+ /// Re-validates against the store. Returns Ok(false) when the license is no
611
+ /// longer valid but the call itself worked.
612
+ pub fn validate() -> Result<bool, String> {
613
+ let mut state = load_state().ok_or("No license stored on this device")?;
614
+
615
+ let raw = post(
616
+ "check_license",
617
+ &[
618
+ ("license_key", state.license_key.clone()),
619
+ ("item_id", ITEM_ID.to_string()),
620
+ ("site_url", state.device_id.clone()),
621
+ ],
622
+ )?;
623
+
624
+ let status = raw.status.unwrap_or_default();
625
+ let valid = status == "valid" || status == "active";
626
+
627
+ state.status = status;
628
+ state.expires = raw.expires.unwrap_or(state.expires);
629
+ state.expires_in_days = raw.expires_in_days.or(state.expires_in_days);
630
+ state.server_time_unix = raw.server_time_unix.unwrap_or_else(now_unix);
631
+ state.checked_at_local = now_unix();
632
+ store_state(&state)?;
633
+
634
+ Ok(valid)
635
+ }
636
+
637
+ /// True when the machine's clock has not been moved backwards since the last
638
+ /// successful check. A backwards jump is how users try to outlive an expiry.
639
+ pub fn clock_is_sane() -> bool {
640
+ match load_state() {
641
+ Some(state) if state.checked_at_local > 0 => {
642
+ let elapsed = now_unix() - state.checked_at_local;
643
+ elapsed >= -CLOCK_TOLERANCE_SECS
644
+ }
645
+ _ => true,
646
+ }
647
+ }
648
+
649
+ /// The entitlement decision the app should gate on. Offline is tolerated for a
650
+ /// short grace window, but a tampered clock is not.
651
+ pub fn is_licensed() -> bool {
652
+ let Some(state) = load_state() else { return false };
653
+ if state.status != "valid" && state.status != "active" {
654
+ return false;
655
+ }
656
+ if !clock_is_sane() {
657
+ return false;
658
+ }
659
+ match state.expires_in_days {
660
+ // Server-computed remaining days — never derived from the local clock.
661
+ Some(days) => days >= 0,
662
+ None => true, // lifetime
663
+ }
664
+ }
665
+
666
+ pub fn deactivate() -> Result<(), String> {
667
+ let state = load_state().ok_or("No license stored on this device")?;
668
+ let _ = post(
669
+ "deactivate_license",
670
+ &[
671
+ ("license_key", state.license_key),
672
+ ("item_id", ITEM_ID.to_string()),
673
+ ("site_url", state.device_id),
674
+ ],
675
+ );
676
+ if let Ok(entry) = keyring::Entry::new(SERVICE, ACCOUNT_LICENSE) {
677
+ let _ = entry.delete_credential();
678
+ }
679
+ Ok(())
680
+ }
681
+
682
+ // Tauri wiring (src/main.rs):
683
+ // #[tauri::command]
684
+ // async fn license_activate(key: String) -> Result<bool, String> {
685
+ // tauri::async_runtime::spawn_blocking(move || licensing::activate(&key).map(|_| true))
686
+ // .await.map_err(|e| e.to_string())?
687
+ // }
674
688
  `;
675
689
  }
676
690
  if (platform === 'chrome_extension') {
677
- code = `${header('Chrome MV3 extension', 'background.js')}
678
- //
679
- // manifest.json needs:
680
- // "permissions": ["storage", "alarms"],
681
- // "host_permissions": ["${base}*"],
682
- // "background": { "service_worker": "background.js", "type": "module" }
683
- //
684
- // A service worker is killed after ~30s idle, so nothing may live in a module
685
- // variable. Device id, license state and the last check all live in
686
- // chrome.storage.local, and the 12-hour alarm is what re-checks while asleep.
687
-
688
- const STORE_URL = '${base}';
689
- const ITEM_ID = ${productId};
690
- const KEYS = { device: 'fc_device_id', state: 'fc_license_state' };
691
- const CLOCK_TOLERANCE_MS = 5 * 60 * 1000;
692
- const CHECK_ALARM = 'fc-license-check';
693
-
694
- async function getDeviceId() {
695
- const stored = await chrome.storage.local.get(KEYS.device);
696
- if (stored[KEYS.device]) return stored[KEYS.device];
697
- // randomUUID is available in the MV3 service worker context.
698
- const deviceId = 'device://' + crypto.randomUUID();
699
- await chrome.storage.local.set({ [KEYS.device]: deviceId });
700
- return deviceId;
701
- }
702
-
703
- async function post(endpoint, params) {
704
- const body = new URLSearchParams(params);
705
- const res = await fetch(STORE_URL + '?fluent-cart=' + endpoint, {
706
- method: 'POST',
707
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
708
- body: body.toString(),
709
- });
710
- if (!res.ok) throw new Error('HTTP ' + res.status);
711
- return res.json();
712
- }
713
-
714
- async function saveState(patch) {
715
- const prev = (await chrome.storage.local.get(KEYS.state))[KEYS.state] || {};
716
- const next = Object.assign({}, prev, patch);
717
- await chrome.storage.local.set({ [KEYS.state]: next });
718
- return next;
719
- }
720
-
721
- export async function activate(licenseKey) {
722
- const deviceId = await getDeviceId();
723
- const data = await post('activate_license', {
724
- license_key: licenseKey.trim(),
725
- item_id: String(ITEM_ID),
726
- site_url: deviceId,
727
- platform: 'chrome-extension',
728
- server_version: chrome.runtime.getManifest().version,
729
- });
730
-
731
- const status = data.status || '';
732
- const valid = status === 'valid' || status === 'active';
733
- const state = await saveState({
734
- license_key: licenseKey.trim(),
735
- device_id: deviceId,
736
- status: status,
737
- expires: data.expires || 'lifetime',
738
- expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : null,
739
- server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
740
- checked_at_local: Date.now(),
741
- variation_title: data.variation_title || '',
742
- });
743
-
744
- if (!valid) throw new Error(data.message || 'Activation failed: ' + status);
745
- return state;
746
- }
747
-
748
- export async function validate() {
749
- const stored = await chrome.storage.local.get(KEYS.state);
750
- const state = stored[KEYS.state];
751
- if (!state || !state.license_key) return { valid: false, reason: 'no-license' };
752
-
753
- const data = await post('check_license', {
754
- license_key: state.license_key,
755
- item_id: String(ITEM_ID),
756
- site_url: state.device_id,
757
- });
758
-
759
- const status = data.status || '';
760
- const valid = status === 'valid' || status === 'active';
761
- await saveState({
762
- status: status,
763
- expires: data.expires || state.expires,
764
- expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : state.expires_in_days,
765
- server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
766
- checked_at_local: Date.now(),
767
- });
768
-
769
- return { valid: valid, reason: status };
770
- }
771
-
772
- // The server's clock is the only one that counts. If the machine's clock is
773
- // now behind the moment of the last check by more than the tolerance, it moved.
774
- function clockIsSane(state) {
775
- if (!state || !state.checked_at_local) return true;
776
- return Date.now() - state.checked_at_local >= -CLOCK_TOLERANCE_MS;
777
- }
778
-
779
- export async function isLicensed() {
780
- const stored = await chrome.storage.local.get(KEYS.state);
781
- const state = stored[KEYS.state];
782
- if (!state) return false;
783
- if (state.status !== 'valid' && state.status !== 'active') return false;
784
- if (!clockIsSane(state)) return false;
785
- if (typeof state.expires_in_days === 'number' && state.expires_in_days < 0) return false;
786
- return true;
787
- }
788
-
789
- export async function deactivate() {
790
- const stored = await chrome.storage.local.get(KEYS.state);
791
- const state = stored[KEYS.state];
792
- if (state && state.license_key) {
793
- try {
794
- await post('deactivate_license', {
795
- license_key: state.license_key,
796
- item_id: String(ITEM_ID),
797
- site_url: state.device_id,
798
- });
799
- } catch (e) {
800
- // Deactivation is best-effort: the device is forgotten locally anyway.
801
- }
802
- }
803
- await chrome.storage.local.remove(KEYS.state);
804
- }
805
-
806
- // Re-check every 12 hours, and once whenever the browser starts.
807
- chrome.alarms.create(CHECK_ALARM, { periodInMinutes: 720 });
808
- chrome.alarms.onAlarm.addListener(async (alarm) => {
809
- if (alarm.name !== CHECK_ALARM) return;
810
- try {
811
- await validate();
812
- } catch (e) {
813
- // Offline: keep the cached verdict until the next alarm.
814
- }
815
- });
816
- chrome.runtime.onStartup.addListener(() => { validate().catch(() => {}); });
817
- chrome.runtime.onInstalled.addListener(() => { validate().catch(() => {}); });
818
-
819
- // Popup / options page usage:
820
- // const licensed = await chrome.runtime.sendMessage({ type: 'fc:is-licensed' });
821
- chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
822
- if (msg && msg.type === 'fc:is-licensed') {
823
- isLicensed().then((v) => sendResponse(v));
824
- return true; // keep the channel open for the async reply
825
- }
826
- });
691
+ code = `${header('Chrome MV3 extension', 'background.js')}
692
+ //
693
+ // manifest.json needs:
694
+ // "permissions": ["storage", "alarms"],
695
+ // "host_permissions": ["${base}*"],
696
+ // "background": { "service_worker": "background.js", "type": "module" }
697
+ //
698
+ // A service worker is killed after ~30s idle, so nothing may live in a module
699
+ // variable. Device id, license state and the last check all live in
700
+ // chrome.storage.local, and the 12-hour alarm is what re-checks while asleep.
701
+
702
+ const STORE_URL = '${base}';
703
+ const ITEM_ID = ${productId};
704
+ const KEYS = { device: 'fc_device_id', state: 'fc_license_state' };
705
+ const CLOCK_TOLERANCE_MS = 5 * 60 * 1000;
706
+ const CHECK_ALARM = 'fc-license-check';
707
+
708
+ async function getDeviceId() {
709
+ const stored = await chrome.storage.local.get(KEYS.device);
710
+ if (stored[KEYS.device]) return stored[KEYS.device];
711
+ // randomUUID is available in the MV3 service worker context.
712
+ const deviceId = 'device://' + crypto.randomUUID();
713
+ await chrome.storage.local.set({ [KEYS.device]: deviceId });
714
+ return deviceId;
715
+ }
716
+
717
+ async function post(endpoint, params) {
718
+ const body = new URLSearchParams(params);
719
+ const res = await fetch(STORE_URL + '?fluent-cart=' + endpoint, {
720
+ method: 'POST',
721
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
722
+ body: body.toString(),
723
+ });
724
+ if (!res.ok) throw new Error('HTTP ' + res.status);
725
+ return res.json();
726
+ }
727
+
728
+ async function saveState(patch) {
729
+ const prev = (await chrome.storage.local.get(KEYS.state))[KEYS.state] || {};
730
+ const next = Object.assign({}, prev, patch);
731
+ await chrome.storage.local.set({ [KEYS.state]: next });
732
+ return next;
733
+ }
734
+
735
+ export async function activate(licenseKey) {
736
+ const deviceId = await getDeviceId();
737
+ const data = await post('activate_license', {
738
+ license_key: licenseKey.trim(),
739
+ item_id: String(ITEM_ID),
740
+ site_url: deviceId,
741
+ platform: 'chrome-extension',
742
+ server_version: chrome.runtime.getManifest().version,
743
+ });
744
+
745
+ const status = data.status || '';
746
+ const valid = status === 'valid' || status === 'active';
747
+ const state = await saveState({
748
+ license_key: licenseKey.trim(),
749
+ device_id: deviceId,
750
+ status: status,
751
+ expires: data.expires || 'lifetime',
752
+ expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : null,
753
+ server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
754
+ checked_at_local: Date.now(),
755
+ variation_title: data.variation_title || '',
756
+ });
757
+
758
+ if (!valid) throw new Error(data.message || 'Activation failed: ' + status);
759
+ return state;
760
+ }
761
+
762
+ export async function validate() {
763
+ const stored = await chrome.storage.local.get(KEYS.state);
764
+ const state = stored[KEYS.state];
765
+ if (!state || !state.license_key) return { valid: false, reason: 'no-license' };
766
+
767
+ const data = await post('check_license', {
768
+ license_key: state.license_key,
769
+ item_id: String(ITEM_ID),
770
+ site_url: state.device_id,
771
+ });
772
+
773
+ const status = data.status || '';
774
+ const valid = status === 'valid' || status === 'active';
775
+ await saveState({
776
+ status: status,
777
+ expires: data.expires || state.expires,
778
+ expires_in_days: typeof data.expires_in_days === 'number' ? data.expires_in_days : state.expires_in_days,
779
+ server_time_unix: data.server_time_unix || Math.floor(Date.now() / 1000),
780
+ checked_at_local: Date.now(),
781
+ });
782
+
783
+ return { valid: valid, reason: status };
784
+ }
785
+
786
+ // The server's clock is the only one that counts. If the machine's clock is
787
+ // now behind the moment of the last check by more than the tolerance, it moved.
788
+ function clockIsSane(state) {
789
+ if (!state || !state.checked_at_local) return true;
790
+ return Date.now() - state.checked_at_local >= -CLOCK_TOLERANCE_MS;
791
+ }
792
+
793
+ export async function isLicensed() {
794
+ const stored = await chrome.storage.local.get(KEYS.state);
795
+ const state = stored[KEYS.state];
796
+ if (!state) return false;
797
+ if (state.status !== 'valid' && state.status !== 'active') return false;
798
+ if (!clockIsSane(state)) return false;
799
+ if (typeof state.expires_in_days === 'number' && state.expires_in_days < 0) return false;
800
+ return true;
801
+ }
802
+
803
+ export async function deactivate() {
804
+ const stored = await chrome.storage.local.get(KEYS.state);
805
+ const state = stored[KEYS.state];
806
+ if (state && state.license_key) {
807
+ try {
808
+ await post('deactivate_license', {
809
+ license_key: state.license_key,
810
+ item_id: String(ITEM_ID),
811
+ site_url: state.device_id,
812
+ });
813
+ } catch (e) {
814
+ // Deactivation is best-effort: the device is forgotten locally anyway.
815
+ }
816
+ }
817
+ await chrome.storage.local.remove(KEYS.state);
818
+ }
819
+
820
+ // Re-check every 12 hours, and once whenever the browser starts.
821
+ chrome.alarms.create(CHECK_ALARM, { periodInMinutes: 720 });
822
+ chrome.alarms.onAlarm.addListener(async (alarm) => {
823
+ if (alarm.name !== CHECK_ALARM) return;
824
+ try {
825
+ await validate();
826
+ } catch (e) {
827
+ // Offline: keep the cached verdict until the next alarm.
828
+ }
829
+ });
830
+ chrome.runtime.onStartup.addListener(() => { validate().catch(() => {}); });
831
+ chrome.runtime.onInstalled.addListener(() => { validate().catch(() => {}); });
832
+
833
+ // Popup / options page usage:
834
+ // const licensed = await chrome.runtime.sendMessage({ type: 'fc:is-licensed' });
835
+ chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
836
+ if (msg && msg.type === 'fc:is-licensed') {
837
+ isLicensed().then((v) => sendResponse(v));
838
+ return true; // keep the channel open for the async reply
839
+ }
840
+ });
827
841
  `;
828
842
  }
829
843
  if (platform === 'python') {
830
- code = `${header('Python (CLI / desktop)', 'licensing.py')}
831
- #
832
- # pip install httpx keyring
833
- #
834
- # Usage:
835
- # python licensing.py activate ABCD-1234-EFGH-5678
836
- # python licensing.py status
837
- # python licensing.py deactivate
838
-
839
- from __future__ import annotations
840
-
841
- import json
842
- import sys
843
- import time
844
- import uuid
845
- from pathlib import Path
846
- from typing import Any, Optional
847
-
848
- import httpx
849
- import keyring
850
-
851
- STORE_URL = "${base}"
852
- ITEM_ID = ${productId}
853
- APP_NAME = "${appName}"
854
- SERVICE = "${service}"
855
- CLOCK_TOLERANCE_SECS = 300
856
- STATE_FILE = Path.home() / ".config" / SERVICE.replace("-", "_") / "license.json"
857
-
858
-
859
- def now_unix() -> int:
860
- return int(time.time())
861
-
862
-
863
- def device_id() -> str:
864
- """Stable per-install id; FluentCart stores it as device://<uuid>."""
865
- existing = keyring.get_password(SERVICE, "device-id")
866
- if existing:
867
- return existing
868
- fresh = f"device://{uuid.uuid4()}"
869
- keyring.set_password(SERVICE, "device-id", fresh)
870
- return fresh
871
-
872
-
873
- def load_state() -> Optional[dict[str, Any]]:
874
- try:
875
- return json.loads(STATE_FILE.read_text(encoding="utf-8"))
876
- except (OSError, ValueError):
877
- return None
878
-
879
-
880
- def save_state(state: dict[str, Any]) -> None:
881
- STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
882
- STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
883
-
884
-
885
- def _post(endpoint: str, params: dict[str, str]) -> dict[str, Any]:
886
- with httpx.Client(timeout=15.0) as client:
887
- res = client.post(f"{STORE_URL}?fluent-cart={endpoint}", data=params)
888
- res.raise_for_status()
889
- return res.json()
890
-
891
-
892
- def activate(license_key: str) -> dict[str, Any]:
893
- data = _post(
894
- "activate_license",
895
- {
896
- "license_key": license_key.strip(),
897
- "item_id": str(ITEM_ID),
898
- "site_url": device_id(),
899
- "platform": sys.platform,
900
- "server_version": "1.0.0",
901
- },
902
- )
903
- status = str(data.get("status", ""))
904
- if status not in ("valid", "active"):
905
- raise RuntimeError(data.get("message") or f"Activation failed: {status}")
906
-
907
- state = {
908
- "license_key": license_key.strip(),
909
- "device_id": device_id(),
910
- "status": status,
911
- "expires": data.get("expires", "lifetime"),
912
- "expires_in_days": data.get("expires_in_days"),
913
- "server_time_unix": int(data.get("server_time_unix") or now_unix()),
914
- "checked_at_local": now_unix(),
915
- "variation_title": data.get("variation_title", ""),
916
- "activation_hash": data.get("activation_hash", ""),
917
- }
918
- save_state(state)
919
- return state
920
-
921
-
922
- def validate() -> bool:
923
- state = load_state()
924
- if not state:
925
- return False
926
-
927
- data = _post(
928
- "check_license",
929
- {
930
- "license_key": state["license_key"],
931
- "item_id": str(ITEM_ID),
932
- "site_url": state["device_id"],
933
- },
934
- )
935
- status = str(data.get("status", ""))
936
- state.update(
937
- {
938
- "status": status,
939
- "expires": data.get("expires", state.get("expires", "lifetime")),
940
- "expires_in_days": data.get("expires_in_days", state.get("expires_in_days")),
941
- "server_time_unix": int(data.get("server_time_unix") or now_unix()),
942
- "checked_at_local": now_unix(),
943
- }
944
- )
945
- save_state(state)
946
- return status in ("valid", "active")
947
-
948
-
949
- def clock_is_sane(state: Optional[dict[str, Any]]) -> bool:
950
- """Reject a machine whose clock was moved backwards since the last check."""
951
- if not state or not state.get("checked_at_local"):
952
- return True
953
- return now_unix() - int(state["checked_at_local"]) >= -CLOCK_TOLERANCE_SECS
954
-
955
-
956
- def is_licensed() -> bool:
957
- state = load_state()
958
- if not state:
959
- return False
960
- if state.get("status") not in ("valid", "active"):
961
- return False
962
- if not clock_is_sane(state):
963
- return False
964
- days = state.get("expires_in_days")
965
- if isinstance(days, int) and days < 0:
966
- return False
967
- return True
968
-
969
-
970
- def deactivate() -> None:
971
- state = load_state()
972
- if state:
973
- try:
974
- _post(
975
- "deactivate_license",
976
- {
977
- "license_key": state.get("license_key", ""),
978
- "item_id": str(ITEM_ID),
979
- "site_url": state.get("device_id", ""),
980
- },
981
- )
982
- except httpx.HTTPError:
983
- pass # best effort; the device forgets the key regardless
984
- try:
985
- STATE_FILE.unlink()
986
- except OSError:
987
- pass
988
-
989
-
990
- if __name__ == "__main__":
991
- cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
992
- if cmd == "activate":
993
- if len(sys.argv) < 3:
994
- sys.exit("usage: python licensing.py activate <license-key>")
995
- print(json.dumps(activate(sys.argv[2]), indent=2))
996
- elif cmd == "deactivate":
997
- deactivate()
998
- print("deactivated")
999
- elif cmd == "status":
1000
- print("licensed" if is_licensed() else "not licensed")
1001
- else:
1002
- sys.exit(f"unknown command: {cmd}")
844
+ code = `${header('Python (CLI / desktop)', 'licensing.py')}
845
+ #
846
+ # pip install httpx keyring
847
+ #
848
+ # Usage:
849
+ # python licensing.py activate ABCD-1234-EFGH-5678
850
+ # python licensing.py status
851
+ # python licensing.py deactivate
852
+
853
+ from __future__ import annotations
854
+
855
+ import json
856
+ import sys
857
+ import time
858
+ import uuid
859
+ from pathlib import Path
860
+ from typing import Any, Optional
861
+
862
+ import httpx
863
+ import keyring
864
+
865
+ STORE_URL = "${base}"
866
+ ITEM_ID = ${productId}
867
+ APP_NAME = "${appName}"
868
+ SERVICE = "${service}"
869
+ CLOCK_TOLERANCE_SECS = 300
870
+ STATE_FILE = Path.home() / ".config" / SERVICE.replace("-", "_") / "license.json"
871
+
872
+
873
+ def now_unix() -> int:
874
+ return int(time.time())
875
+
876
+
877
+ def device_id() -> str:
878
+ """Stable per-install id; FluentCart stores it as device://<uuid>."""
879
+ existing = keyring.get_password(SERVICE, "device-id")
880
+ if existing:
881
+ return existing
882
+ fresh = f"device://{uuid.uuid4()}"
883
+ keyring.set_password(SERVICE, "device-id", fresh)
884
+ return fresh
885
+
886
+
887
+ def load_state() -> Optional[dict[str, Any]]:
888
+ try:
889
+ return json.loads(STATE_FILE.read_text(encoding="utf-8"))
890
+ except (OSError, ValueError):
891
+ return None
892
+
893
+
894
+ def save_state(state: dict[str, Any]) -> None:
895
+ STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
896
+ STATE_FILE.write_text(json.dumps(state, indent=2), encoding="utf-8")
897
+
898
+
899
+ def _post(endpoint: str, params: dict[str, str]) -> dict[str, Any]:
900
+ with httpx.Client(timeout=15.0) as client:
901
+ res = client.post(f"{STORE_URL}?fluent-cart={endpoint}", data=params)
902
+ res.raise_for_status()
903
+ return res.json()
904
+
905
+
906
+ def activate(license_key: str) -> dict[str, Any]:
907
+ data = _post(
908
+ "activate_license",
909
+ {
910
+ "license_key": license_key.strip(),
911
+ "item_id": str(ITEM_ID),
912
+ "site_url": device_id(),
913
+ "platform": sys.platform,
914
+ "server_version": "1.0.0",
915
+ },
916
+ )
917
+ status = str(data.get("status", ""))
918
+ if status not in ("valid", "active"):
919
+ raise RuntimeError(data.get("message") or f"Activation failed: {status}")
920
+
921
+ state = {
922
+ "license_key": license_key.strip(),
923
+ "device_id": device_id(),
924
+ "status": status,
925
+ "expires": data.get("expires", "lifetime"),
926
+ "expires_in_days": data.get("expires_in_days"),
927
+ "server_time_unix": int(data.get("server_time_unix") or now_unix()),
928
+ "checked_at_local": now_unix(),
929
+ "variation_title": data.get("variation_title", ""),
930
+ "activation_hash": data.get("activation_hash", ""),
931
+ }
932
+ save_state(state)
933
+ return state
934
+
935
+
936
+ def validate() -> bool:
937
+ state = load_state()
938
+ if not state:
939
+ return False
940
+
941
+ data = _post(
942
+ "check_license",
943
+ {
944
+ "license_key": state["license_key"],
945
+ "item_id": str(ITEM_ID),
946
+ "site_url": state["device_id"],
947
+ },
948
+ )
949
+ status = str(data.get("status", ""))
950
+ state.update(
951
+ {
952
+ "status": status,
953
+ "expires": data.get("expires", state.get("expires", "lifetime")),
954
+ "expires_in_days": data.get("expires_in_days", state.get("expires_in_days")),
955
+ "server_time_unix": int(data.get("server_time_unix") or now_unix()),
956
+ "checked_at_local": now_unix(),
957
+ }
958
+ )
959
+ save_state(state)
960
+ return status in ("valid", "active")
961
+
962
+
963
+ def clock_is_sane(state: Optional[dict[str, Any]]) -> bool:
964
+ """Reject a machine whose clock was moved backwards since the last check."""
965
+ if not state or not state.get("checked_at_local"):
966
+ return True
967
+ return now_unix() - int(state["checked_at_local"]) >= -CLOCK_TOLERANCE_SECS
968
+
969
+
970
+ def is_licensed() -> bool:
971
+ state = load_state()
972
+ if not state:
973
+ return False
974
+ if state.get("status") not in ("valid", "active"):
975
+ return False
976
+ if not clock_is_sane(state):
977
+ return False
978
+ days = state.get("expires_in_days")
979
+ if isinstance(days, int) and days < 0:
980
+ return False
981
+ return True
982
+
983
+
984
+ def deactivate() -> None:
985
+ state = load_state()
986
+ if state:
987
+ try:
988
+ _post(
989
+ "deactivate_license",
990
+ {
991
+ "license_key": state.get("license_key", ""),
992
+ "item_id": str(ITEM_ID),
993
+ "site_url": state.get("device_id", ""),
994
+ },
995
+ )
996
+ except httpx.HTTPError:
997
+ pass # best effort; the device forgets the key regardless
998
+ try:
999
+ STATE_FILE.unlink()
1000
+ except OSError:
1001
+ pass
1002
+
1003
+
1004
+ if __name__ == "__main__":
1005
+ cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
1006
+ if cmd == "activate":
1007
+ if len(sys.argv) < 3:
1008
+ sys.exit("usage: python licensing.py activate <license-key>")
1009
+ print(json.dumps(activate(sys.argv[2]), indent=2))
1010
+ elif cmd == "deactivate":
1011
+ deactivate()
1012
+ print("deactivated")
1013
+ elif cmd == "status":
1014
+ print("licensed" if is_licensed() else "not licensed")
1015
+ else:
1016
+ sys.exit(f"unknown command: {cmd}")
1003
1017
  `;
1004
1018
  }
1005
1019
  if (platform === 'cpp_vst') {
1006
- code = `${header('C++ / JUCE (VST3, AU, AAX)', 'LicensingManager.h + .cpp')}
1007
- //
1008
- // Add to your juce_module dependencies: juce_core, juce_data_structures.
1009
- // Enable JUCE_WEB_BROWSER=0 is fine — juce::URL handles the POST itself.
1010
- //
1011
- // ── LicensingManager.h ─────────────────────────────────────────────────────
1012
- #pragma once
1013
-
1014
- #include <JuceHeader.h>
1015
-
1016
- class LicensingManager : public juce::Thread
1017
- {
1018
- public:
1019
- LicensingManager();
1020
- ~LicensingManager() override;
1021
-
1022
- /** Kicks off a background check. Never blocks the audio thread. */
1023
- void refreshAsync();
1024
-
1025
- /** Cached verdict, safe to read from the message/audio thread. */
1026
- bool isLicensed() const;
1027
-
1028
- juce::String getStatusText() const;
1029
- juce::String getExpiryText() const;
1030
-
1031
- void activate (const juce::String& licenseKey);
1032
- void deactivate();
1033
-
1034
- /** Fired on the message thread whenever the verdict changes. */
1035
- std::function<void (bool licensed)> onLicenseChanged;
1036
-
1037
- private:
1038
- void run() override;
1039
- void setState (const juce::var& json);
1040
- juce::var post (const juce::String& endpoint,
1041
- const juce::StringPairArray& params);
1042
-
1043
- static juce::String deviceId();
1044
-
1045
- juce::CriticalSection lock;
1046
- bool licensed = false;
1047
- juce::String statusText { "unlicensed" };
1048
- juce::String expiryText;
1049
- std::unique_ptr<juce::PropertiesFile> props;
1050
- };
1051
-
1052
- // ── LicensingManager.cpp ───────────────────────────────────────────────────
1053
- #include "LicensingManager.h"
1054
-
1055
- namespace
1056
- {
1057
- constexpr const char* kStoreUrl = "${base}";
1058
- constexpr int kItemId = ${productId};
1059
- constexpr juce::int64 kClockToleranceMs = 5 * 60 * 1000;
1060
-
1061
- juce::PropertiesFile::Options optionsFor (const juce::String& appName)
1062
- {
1063
- juce::PropertiesFile::Options o;
1064
- o.applicationName = appName;
1065
- o.filenameSuffix = ".licence";
1066
- o.osxLibrarySubFolder = "Application Support";
1067
- return o;
1068
- }
1069
- }
1070
-
1071
- LicensingManager::LicensingManager()
1072
- : juce::Thread ("FluentCart licensing"),
1073
- props (new juce::PropertiesFile (
1074
- optionsFor ("${service}"),
1075
- juce::PropertiesFile::storeAsXML))
1076
- {
1077
- }
1078
-
1079
- LicensingManager::~LicensingManager() { stopThread (3000); }
1080
-
1081
- juce::String LicensingManager::deviceId()
1082
- {
1083
- auto& p = *juce::PropertiesFile::createDefaultAppPropertiesFile (
1084
- "${service}", ".licence", "Application Support", true);
1085
- auto existing = p.getValue ("fc_device_id");
1086
- if (existing.isNotEmpty())
1087
- return existing;
1088
-
1089
- auto fresh = "device://" + juce::Uuid().toString();
1090
- p.setValue ("fc_device_id", fresh);
1091
- p.saveIfNeeded();
1092
- return fresh;
1093
- }
1094
-
1095
- juce::var LicensingManager::post (const juce::String& endpoint,
1096
- const juce::StringPairArray& params)
1097
- {
1098
- juce::String body;
1099
- for (int i = 0; i < params.size(); ++i)
1100
- body << (i ? "&" : "")
1101
- << juce::URL::addEscapeChars (params.getAllKeys()[i], false) << "="
1102
- << juce::URL::addEscapeChars (params.getAllValues()[i], false);
1103
-
1104
- juce::URL url (juce::String (kStoreUrl) + "?fluent-cart=" + endpoint);
1105
- url = url.withPOSTData (body);
1106
-
1107
- int statusCode = 0;
1108
- auto stream = url.createInputStream (
1109
- juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
1110
- .withConnectionTimeoutMs (15000)
1111
- .withExtraHeaders ("Content-Type: application/x-www-form-urlencoded")
1112
- .withStatusCode (&statusCode));
1113
-
1114
- if (stream == nullptr)
1115
- return {};
1116
-
1117
- return juce::JSON::parse (stream->readEntireStreamAsString());
1118
- }
1119
-
1120
- void LicensingManager::setState (const juce::var& json)
1121
- {
1122
- auto* obj = json.getDynamicObject();
1123
- if (obj == nullptr)
1124
- return;
1125
-
1126
- auto status = obj->getProperty ("status").toString();
1127
- auto valid = (status == "valid" || status == "active");
1128
-
1129
- // The server's clock is authoritative. Remember the matching local time so
1130
- // a clock moved backwards between checks can be detected.
1131
- auto serverTime = (juce::int64) (double) obj->getProperty ("server_time_unix");
1132
-
1133
- {
1134
- const juce::ScopedLock sl (lock);
1135
- licensed = valid;
1136
- statusText = status.isNotEmpty() ? status : "unknown";
1137
- expiryText = obj->getProperty ("expires").toString();
1138
- }
1139
-
1140
- if (serverTime > 0)
1141
- props->setValue ("fc_server_time", juce::String (serverTime));
1142
- props->setValue ("fc_checked_at_local", juce::String (juce::Time::currentTimeMillis()));
1143
- props->saveIfNeeded();
1144
-
1145
- auto changed = onLicenseChanged;
1146
- if (changed != nullptr)
1147
- juce::MessageManager::callAsync ([changed, valid] { changed (valid); });
1148
- }
1149
-
1150
- bool LicensingManager::isLicensed() const
1151
- {
1152
- const juce::ScopedLock sl (lock);
1153
- if (! licensed)
1154
- return false;
1155
-
1156
- // Pre-computed by the server; the client never does date math.
1157
- auto days = props->getIntValue ("fc_expires_in_days", -1);
1158
- if (days >= 0 && days == 0)
1159
- return false;
1160
-
1161
- auto checkedAt = props->getValue ("fc_checked_at_local").getLargeIntValue();
1162
- if (checkedAt > 0 && juce::Time::currentTimeMillis() - checkedAt < -kClockToleranceMs)
1163
- return false; // clock moved backwards — treat as tampered
1164
-
1165
- return true;
1166
- }
1167
-
1168
- juce::String LicensingManager::getStatusText() const
1169
- {
1170
- const juce::ScopedLock sl (lock);
1171
- return statusText;
1172
- }
1173
-
1174
- juce::String LicensingManager::getExpiryText() const
1175
- {
1176
- const juce::ScopedLock sl (lock);
1177
- return expiryText;
1178
- }
1179
-
1180
- void LicensingManager::refreshAsync()
1181
- {
1182
- if (! isThreadRunning())
1183
- startThread();
1184
- }
1185
-
1186
- void LicensingManager::run()
1187
- {
1188
- auto& p = *props;
1189
- auto key = p.getValue ("fc_license_key");
1190
- if (key.isEmpty())
1191
- return;
1192
-
1193
- juce::StringPairArray params;
1194
- params.set ("license_key", key);
1195
- params.set ("item_id", juce::String (kItemId));
1196
- params.set ("site_url", p.getValue ("fc_device_id"));
1197
-
1198
- setState (post ("check_license", params));
1199
- }
1200
-
1201
- void LicensingManager::activate (const juce::String& licenseKey)
1202
- {
1203
- juce::StringPairArray params;
1204
- params.set ("license_key", licenseKey.trim());
1205
- params.set ("item_id", juce::String (kItemId));
1206
- params.set ("site_url", deviceId());
1207
- params.set ("platform", juce::SystemStats::getOperatingSystemName());
1208
-
1209
- auto json = post ("activate_license", params);
1210
- auto* obj = json.getDynamicObject();
1211
- if (obj != nullptr)
1212
- {
1213
- props->setValue ("fc_license_key", licenseKey.trim());
1214
- props->setValue ("fc_expires_in_days",
1215
- juce::String ((int) (double) obj->getProperty ("expires_in_days")));
1216
- }
1217
- setState (json);
1218
- props->saveIfNeeded();
1219
- }
1220
-
1221
- void LicensingManager::deactivate()
1222
- {
1223
- juce::StringPairArray params;
1224
- params.set ("license_key", props->getValue ("fc_license_key"));
1225
- params.set ("item_id", juce::String (kItemId));
1226
- params.set ("site_url", props->getValue ("fc_device_id"));
1227
- post ("deactivate_license", params);
1228
-
1229
- props->removeValue ("fc_license_key");
1230
- props->saveIfNeeded();
1231
-
1232
- const juce::ScopedLock sl (lock);
1233
- licensed = false;
1234
- statusText = "unlicensed";
1235
- }
1236
-
1237
- // In your AudioProcessor constructor:
1238
- // licensing.refreshAsync(); // background thread, no UI stall
1239
- // Never call isLicensed() from the audio callback — cache it on the message
1240
- // thread and read an atomic in processBlock().
1020
+ code = `${header('C++ / JUCE (VST3, AU, AAX)', 'LicensingManager.h + .cpp')}
1021
+ //
1022
+ // Add to your juce_module dependencies: juce_core, juce_data_structures.
1023
+ // Enable JUCE_WEB_BROWSER=0 is fine — juce::URL handles the POST itself.
1024
+ //
1025
+ // ── LicensingManager.h ─────────────────────────────────────────────────────
1026
+ #pragma once
1027
+
1028
+ #include <JuceHeader.h>
1029
+
1030
+ class LicensingManager : public juce::Thread
1031
+ {
1032
+ public:
1033
+ LicensingManager();
1034
+ ~LicensingManager() override;
1035
+
1036
+ /** Kicks off a background check. Never blocks the audio thread. */
1037
+ void refreshAsync();
1038
+
1039
+ /** Cached verdict, safe to read from the message/audio thread. */
1040
+ bool isLicensed() const;
1041
+
1042
+ juce::String getStatusText() const;
1043
+ juce::String getExpiryText() const;
1044
+
1045
+ void activate (const juce::String& licenseKey);
1046
+ void deactivate();
1047
+
1048
+ /** Fired on the message thread whenever the verdict changes. */
1049
+ std::function<void (bool licensed)> onLicenseChanged;
1050
+
1051
+ private:
1052
+ void run() override;
1053
+ void setState (const juce::var& json);
1054
+ juce::var post (const juce::String& endpoint,
1055
+ const juce::StringPairArray& params);
1056
+
1057
+ static juce::String deviceId();
1058
+
1059
+ juce::CriticalSection lock;
1060
+ bool licensed = false;
1061
+ juce::String statusText { "unlicensed" };
1062
+ juce::String expiryText;
1063
+ std::unique_ptr<juce::PropertiesFile> props;
1064
+ };
1065
+
1066
+ // ── LicensingManager.cpp ───────────────────────────────────────────────────
1067
+ #include "LicensingManager.h"
1068
+
1069
+ namespace
1070
+ {
1071
+ constexpr const char* kStoreUrl = "${base}";
1072
+ constexpr int kItemId = ${productId};
1073
+ constexpr juce::int64 kClockToleranceMs = 5 * 60 * 1000;
1074
+
1075
+ juce::PropertiesFile::Options optionsFor (const juce::String& appName)
1076
+ {
1077
+ juce::PropertiesFile::Options o;
1078
+ o.applicationName = appName;
1079
+ o.filenameSuffix = ".licence";
1080
+ o.osxLibrarySubFolder = "Application Support";
1081
+ return o;
1082
+ }
1083
+ }
1084
+
1085
+ LicensingManager::LicensingManager()
1086
+ : juce::Thread ("FluentCart licensing"),
1087
+ props (new juce::PropertiesFile (
1088
+ optionsFor ("${service}"),
1089
+ juce::PropertiesFile::storeAsXML))
1090
+ {
1091
+ }
1092
+
1093
+ LicensingManager::~LicensingManager() { stopThread (3000); }
1094
+
1095
+ juce::String LicensingManager::deviceId()
1096
+ {
1097
+ auto& p = *juce::PropertiesFile::createDefaultAppPropertiesFile (
1098
+ "${service}", ".licence", "Application Support", true);
1099
+ auto existing = p.getValue ("fc_device_id");
1100
+ if (existing.isNotEmpty())
1101
+ return existing;
1102
+
1103
+ auto fresh = "device://" + juce::Uuid().toString();
1104
+ p.setValue ("fc_device_id", fresh);
1105
+ p.saveIfNeeded();
1106
+ return fresh;
1107
+ }
1108
+
1109
+ juce::var LicensingManager::post (const juce::String& endpoint,
1110
+ const juce::StringPairArray& params)
1111
+ {
1112
+ juce::String body;
1113
+ for (int i = 0; i < params.size(); ++i)
1114
+ body << (i ? "&" : "")
1115
+ << juce::URL::addEscapeChars (params.getAllKeys()[i], false) << "="
1116
+ << juce::URL::addEscapeChars (params.getAllValues()[i], false);
1117
+
1118
+ juce::URL url (juce::String (kStoreUrl) + "?fluent-cart=" + endpoint);
1119
+ url = url.withPOSTData (body);
1120
+
1121
+ int statusCode = 0;
1122
+ auto stream = url.createInputStream (
1123
+ juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
1124
+ .withConnectionTimeoutMs (15000)
1125
+ .withExtraHeaders ("Content-Type: application/x-www-form-urlencoded")
1126
+ .withStatusCode (&statusCode));
1127
+
1128
+ if (stream == nullptr)
1129
+ return {};
1130
+
1131
+ return juce::JSON::parse (stream->readEntireStreamAsString());
1132
+ }
1133
+
1134
+ void LicensingManager::setState (const juce::var& json)
1135
+ {
1136
+ auto* obj = json.getDynamicObject();
1137
+ if (obj == nullptr)
1138
+ return;
1139
+
1140
+ auto status = obj->getProperty ("status").toString();
1141
+ auto valid = (status == "valid" || status == "active");
1142
+
1143
+ // The server's clock is authoritative. Remember the matching local time so
1144
+ // a clock moved backwards between checks can be detected.
1145
+ auto serverTime = (juce::int64) (double) obj->getProperty ("server_time_unix");
1146
+
1147
+ {
1148
+ const juce::ScopedLock sl (lock);
1149
+ licensed = valid;
1150
+ statusText = status.isNotEmpty() ? status : "unknown";
1151
+ expiryText = obj->getProperty ("expires").toString();
1152
+ }
1153
+
1154
+ if (serverTime > 0)
1155
+ props->setValue ("fc_server_time", juce::String (serverTime));
1156
+ props->setValue ("fc_checked_at_local", juce::String (juce::Time::currentTimeMillis()));
1157
+ props->saveIfNeeded();
1158
+
1159
+ auto changed = onLicenseChanged;
1160
+ if (changed != nullptr)
1161
+ juce::MessageManager::callAsync ([changed, valid] { changed (valid); });
1162
+ }
1163
+
1164
+ bool LicensingManager::isLicensed() const
1165
+ {
1166
+ const juce::ScopedLock sl (lock);
1167
+ if (! licensed)
1168
+ return false;
1169
+
1170
+ // Pre-computed by the server; the client never does date math.
1171
+ auto days = props->getIntValue ("fc_expires_in_days", -1);
1172
+ if (days >= 0 && days == 0)
1173
+ return false;
1174
+
1175
+ auto checkedAt = props->getValue ("fc_checked_at_local").getLargeIntValue();
1176
+ if (checkedAt > 0 && juce::Time::currentTimeMillis() - checkedAt < -kClockToleranceMs)
1177
+ return false; // clock moved backwards — treat as tampered
1178
+
1179
+ return true;
1180
+ }
1181
+
1182
+ juce::String LicensingManager::getStatusText() const
1183
+ {
1184
+ const juce::ScopedLock sl (lock);
1185
+ return statusText;
1186
+ }
1187
+
1188
+ juce::String LicensingManager::getExpiryText() const
1189
+ {
1190
+ const juce::ScopedLock sl (lock);
1191
+ return expiryText;
1192
+ }
1193
+
1194
+ void LicensingManager::refreshAsync()
1195
+ {
1196
+ if (! isThreadRunning())
1197
+ startThread();
1198
+ }
1199
+
1200
+ void LicensingManager::run()
1201
+ {
1202
+ auto& p = *props;
1203
+ auto key = p.getValue ("fc_license_key");
1204
+ if (key.isEmpty())
1205
+ return;
1206
+
1207
+ juce::StringPairArray params;
1208
+ params.set ("license_key", key);
1209
+ params.set ("item_id", juce::String (kItemId));
1210
+ params.set ("site_url", p.getValue ("fc_device_id"));
1211
+
1212
+ setState (post ("check_license", params));
1213
+ }
1214
+
1215
+ void LicensingManager::activate (const juce::String& licenseKey)
1216
+ {
1217
+ juce::StringPairArray params;
1218
+ params.set ("license_key", licenseKey.trim());
1219
+ params.set ("item_id", juce::String (kItemId));
1220
+ params.set ("site_url", deviceId());
1221
+ params.set ("platform", juce::SystemStats::getOperatingSystemName());
1222
+
1223
+ auto json = post ("activate_license", params);
1224
+ auto* obj = json.getDynamicObject();
1225
+ if (obj != nullptr)
1226
+ {
1227
+ props->setValue ("fc_license_key", licenseKey.trim());
1228
+ props->setValue ("fc_expires_in_days",
1229
+ juce::String ((int) (double) obj->getProperty ("expires_in_days")));
1230
+ }
1231
+ setState (json);
1232
+ props->saveIfNeeded();
1233
+ }
1234
+
1235
+ void LicensingManager::deactivate()
1236
+ {
1237
+ juce::StringPairArray params;
1238
+ params.set ("license_key", props->getValue ("fc_license_key"));
1239
+ params.set ("item_id", juce::String (kItemId));
1240
+ params.set ("site_url", props->getValue ("fc_device_id"));
1241
+ post ("deactivate_license", params);
1242
+
1243
+ props->removeValue ("fc_license_key");
1244
+ props->saveIfNeeded();
1245
+
1246
+ const juce::ScopedLock sl (lock);
1247
+ licensed = false;
1248
+ statusText = "unlicensed";
1249
+ }
1250
+
1251
+ // In your AudioProcessor constructor:
1252
+ // licensing.refreshAsync(); // background thread, no UI stall
1253
+ // Never call isLicensed() from the audio callback — cache it on the message
1254
+ // thread and read an atomic in processBlock().
1241
1255
  `;
1242
1256
  }
1243
1257
  return {
@@ -1278,110 +1292,110 @@ void LicensingManager::deactivate()
1278
1292
  content: [
1279
1293
  {
1280
1294
  type: 'text',
1281
- text: `${header('Tauri / Rust', 'src/trial.rs')}
1282
- //
1283
- // Cargo.toml
1284
- // reqwest = { version = "0.12", features = ["json"] }
1285
- // serde = { version = "1", features = ["derive"] }
1286
- // serde_json = "1"
1287
- // machine-uid = "0.5"
1288
- // keyring = "2"
1289
- // whoami = "1"
1290
-
1291
- use serde::Deserialize;
1292
-
1293
- const STORE: &str = "${base}";
1294
- const PRODUCT_ID: i64 = ${productId};
1295
- const KEYRING_SERVICE: &str = "${slug}-trial";
1296
-
1297
- #[derive(Deserialize, Debug)]
1298
- pub struct Eligibility {
1299
- pub eligible: bool,
1300
- pub reason: String,
1301
- pub token: Option<String>,
1302
- pub risk_score: Option<i64>,
1303
- }
1304
-
1305
- /// Stable, versioned machine fingerprint. Survives app updates; changes on
1306
- /// OS reinstall or disk replacement, which is a support reset, not abuse.
1307
- pub fn fingerprint() -> String {
1308
- let uid = machine_uid::get().unwrap_or_else(|_| "unknown".to_string());
1309
- let host = whoami::fallible::hostname().unwrap_or_else(|_| "host".to_string());
1310
- format!(
1311
- "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}",
1312
- uid,
1313
- host,
1314
- std::env::consts::OS,
1315
- std::env::consts::ARCH
1316
- )
1317
- }
1318
-
1319
- /// One persisted device:// id, used as site_url. Separate from the fingerprint:
1320
- /// the id identifies the install, the fingerprint identifies the machine.
1321
- pub fn device_id() -> String {
1322
- if let Ok(entry) = keyring::Entry::new(KEYRING_SERVICE, "device_id") {
1323
- if let Ok(id) = entry.get_password() {
1324
- return id;
1325
- }
1326
- let id = format!("device://{}", uuid::Uuid::new_v4());
1327
- let _ = entry.set_password(&id);
1328
- return id;
1329
- }
1330
- "device://unknown".to_string()
1331
- }
1332
-
1333
- pub async fn check_trial(client: &reqwest::Client, email: &str) -> Result<Eligibility, String> {
1334
- let res = client
1335
- .post(format!("{}?fluent-cart=fastr_trial_eligibility", STORE))
1336
- .form(&[
1337
- ("product_id", PRODUCT_ID.to_string()),
1338
- ("device_fingerprint", fingerprint()),
1339
- ("email", email.to_string()),
1340
- ])
1341
- .send()
1342
- .await
1343
- .map_err(|e| e.to_string())?;
1344
-
1345
- res.json::<Eligibility>().await.map_err(|e| e.to_string())
1346
- }
1347
-
1348
- pub async fn activate(
1349
- client: &reqwest::Client,
1350
- license_key: &str,
1351
- email: &str,
1352
- ) -> Result<serde_json::Value, String> {
1353
- let res = client
1354
- .post(format!("{}?fluent-cart=activate_license", STORE))
1355
- .form(&[
1356
- ("item_id", PRODUCT_ID.to_string()),
1357
- ("license_key", license_key.to_string()),
1358
- ("site_url", device_id()),
1359
- ("device_fingerprint", fingerprint()),
1360
- ("device_name", whoami::fallible::hostname().unwrap_or_default()),
1361
- ("device_type", "Desktop (Tauri)".to_string()),
1362
- ("os", std::env::consts::OS.to_string()),
1363
- ("arch", std::env::consts::ARCH.to_string()),
1364
- ("email", email.to_string()),
1365
- ("server_version", env!("CARGO_PKG_VERSION").to_string()),
1366
- ])
1367
- .send()
1368
- .await
1369
- .map_err(|e| e.to_string())?;
1370
-
1371
- let body: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
1372
-
1373
- match body.get("error_type").and_then(|v| v.as_str()) {
1374
- Some("trial_already_used") => Err("trial_already_used".into()),
1375
- Some("trial_fingerprint_required") => Err("client_outdated".into()),
1376
- Some("trial_device_mismatch") => Err("trial_device_mismatch".into()),
1377
- Some("device_blocked") => Err("device_blocked".into()),
1378
- _ => Ok(body),
1379
- }
1380
- }
1381
-
1382
- // Flow: check_trial() before showing the trial button; hide or disable it when
1383
- // eligible=false. activate() on submit. Cache the server's server_time_unix and
1384
- // compare it on every launch instead of trusting the local clock.
1295
+ text: `${header('Tauri / Rust', 'src/trial.rs')}
1296
+ //
1297
+ // Cargo.toml
1298
+ // reqwest = { version = "0.12", features = ["json"] }
1299
+ // serde = { version = "1", features = ["derive"] }
1300
+ // serde_json = "1"
1301
+ // machine-uid = "0.5"
1302
+ // keyring = "2"
1303
+ // whoami = "1"
1304
+
1305
+ use serde::Deserialize;
1306
+
1307
+ const STORE: &str = "${base}";
1308
+ const PRODUCT_ID: i64 = ${productId};
1309
+ const KEYRING_SERVICE: &str = "${slug}-trial";
1310
+
1311
+ #[derive(Deserialize, Debug)]
1312
+ pub struct Eligibility {
1313
+ pub eligible: bool,
1314
+ pub reason: String,
1315
+ pub token: Option<String>,
1316
+ pub risk_score: Option<i64>,
1317
+ }
1318
+
1319
+ /// Stable, versioned machine fingerprint. Survives app updates; changes on
1320
+ /// OS reinstall or disk replacement, which is a support reset, not abuse.
1321
+ pub fn fingerprint() -> String {
1322
+ let uid = machine_uid::get().unwrap_or_else(|_| "unknown".to_string());
1323
+ let host = whoami::fallible::hostname().unwrap_or_else(|_| "host".to_string());
1324
+ format!(
1325
+ "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}",
1326
+ uid,
1327
+ host,
1328
+ std::env::consts::OS,
1329
+ std::env::consts::ARCH
1330
+ )
1331
+ }
1332
+
1333
+ /// One persisted device:// id, used as site_url. Separate from the fingerprint:
1334
+ /// the id identifies the install, the fingerprint identifies the machine.
1335
+ pub fn device_id() -> String {
1336
+ if let Ok(entry) = keyring::Entry::new(KEYRING_SERVICE, "device_id") {
1337
+ if let Ok(id) = entry.get_password() {
1338
+ return id;
1339
+ }
1340
+ let id = format!("device://{}", uuid::Uuid::new_v4());
1341
+ let _ = entry.set_password(&id);
1342
+ return id;
1343
+ }
1344
+ "device://unknown".to_string()
1345
+ }
1346
+
1347
+ pub async fn check_trial(client: &reqwest::Client, email: &str) -> Result<Eligibility, String> {
1348
+ let res = client
1349
+ .post(format!("{}?fluent-cart=fastr_trial_eligibility", STORE))
1350
+ .form(&[
1351
+ ("product_id", PRODUCT_ID.to_string()),
1352
+ ("device_fingerprint", fingerprint()),
1353
+ ("email", email.to_string()),
1354
+ ])
1355
+ .send()
1356
+ .await
1357
+ .map_err(|e| e.to_string())?;
1358
+
1359
+ res.json::<Eligibility>().await.map_err(|e| e.to_string())
1360
+ }
1361
+
1362
+ pub async fn activate(
1363
+ client: &reqwest::Client,
1364
+ license_key: &str,
1365
+ email: &str,
1366
+ ) -> Result<serde_json::Value, String> {
1367
+ let res = client
1368
+ .post(format!("{}?fluent-cart=activate_license", STORE))
1369
+ .form(&[
1370
+ ("item_id", PRODUCT_ID.to_string()),
1371
+ ("license_key", license_key.to_string()),
1372
+ ("site_url", device_id()),
1373
+ ("device_fingerprint", fingerprint()),
1374
+ ("device_name", whoami::fallible::hostname().unwrap_or_default()),
1375
+ ("device_type", "Desktop (Tauri)".to_string()),
1376
+ ("os", std::env::consts::OS.to_string()),
1377
+ ("arch", std::env::consts::ARCH.to_string()),
1378
+ ("email", email.to_string()),
1379
+ ("server_version", env!("CARGO_PKG_VERSION").to_string()),
1380
+ ])
1381
+ .send()
1382
+ .await
1383
+ .map_err(|e| e.to_string())?;
1384
+
1385
+ let body: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
1386
+
1387
+ match body.get("error_type").and_then(|v| v.as_str()) {
1388
+ Some("trial_already_used") => Err("trial_already_used".into()),
1389
+ Some("trial_fingerprint_required") => Err("client_outdated".into()),
1390
+ Some("trial_device_mismatch") => Err("trial_device_mismatch".into()),
1391
+ Some("device_blocked") => Err("device_blocked".into()),
1392
+ _ => Ok(body),
1393
+ }
1394
+ }
1395
+
1396
+ // Flow: check_trial() before showing the trial button; hide or disable it when
1397
+ // eligible=false. activate() on submit. Cache the server's server_time_unix and
1398
+ // compare it on every launch instead of trusting the local clock.
1385
1399
  `
1386
1400
  }
1387
1401
  ]
@@ -1392,125 +1406,125 @@ pub async fn activate(
1392
1406
  content: [
1393
1407
  {
1394
1408
  type: 'text',
1395
- text: `"""${appName} - FluentCart trial guard (Python)
1396
-
1397
- Store: ${base}
1398
- Product ID: ${productId}
1399
- Dependencies: httpx, keyring
1400
-
1401
- Flow: check_trial() before offering the trial, activate() on submit,
1402
- check() on every launch. Never trust the local clock for expiry.
1403
- """
1404
-
1405
- import platform
1406
- import socket
1407
- import subprocess
1408
- import sys
1409
- import time
1410
- import uuid
1411
-
1412
- import httpx
1413
- import keyring
1414
-
1415
- STORE = "${base}"
1416
- PRODUCT_ID = ${productId}
1417
- KEYRING_SERVICE = "${slug}-trial"
1418
-
1419
-
1420
- def machine_id() -> str:
1421
- """Stable machine identifier. Linux: /etc/machine-id, Windows: MachineGuid."""
1422
- if sys.platform.startswith("win"):
1423
- try:
1424
- import winreg
1425
-
1426
- key = winreg.OpenKey(
1427
- winreg.HKEY_LOCAL_MACHINE,
1428
- r"SOFTWARE\\Microsoft\\Cryptography",
1429
- )
1430
- value, _ = winreg.QueryValueEx(key, "MachineGuid")
1431
- return str(value)
1432
- except Exception:
1433
- return ""
1434
- if sys.platform == "darwin":
1435
- try:
1436
- out = subprocess.check_output(
1437
- ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
1438
- text=True,
1439
- )
1440
- for line in out.splitlines():
1441
- if "IOPlatformUUID" in line:
1442
- return line.split("=")[-1].strip().strip('"')
1443
- except Exception:
1444
- return ""
1445
- try:
1446
- with open("/etc/machine-id", "r", encoding="utf-8") as handle:
1447
- return handle.read().strip()
1448
- except OSError:
1449
- return ""
1450
-
1451
-
1452
- def fingerprint() -> str:
1453
- uname = platform.uname()
1454
- return "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}".format(
1455
- machine_id() or "unknown",
1456
- socket.gethostname(),
1457
- uname.system,
1458
- uname.machine,
1459
- )
1460
-
1461
-
1462
- def device_id() -> str:
1463
- stored = keyring.get_password(KEYRING_SERVICE, "device_id")
1464
- if stored:
1465
- return stored
1466
- new_id = "device://" + str(uuid.uuid4())
1467
- keyring.set_password(KEYRING_SERVICE, "device_id", new_id)
1468
- return new_id
1469
-
1470
-
1471
- def check_trial(email: str) -> dict:
1472
- payload = {
1473
- "product_id": PRODUCT_ID,
1474
- "device_fingerprint": fingerprint(),
1475
- "email": email,
1476
- }
1477
- with httpx.Client(timeout=10.0) as client:
1478
- response = client.post(STORE + "?fluent-cart=fastr_trial_eligibility", data=payload)
1479
- return response.json()
1480
-
1481
-
1482
- def activate(license_key: str, email: str) -> dict:
1483
- uname = platform.uname()
1484
- payload = {
1485
- "item_id": PRODUCT_ID,
1486
- "license_key": license_key,
1487
- "site_url": device_id(),
1488
- "device_fingerprint": fingerprint(),
1489
- "device_name": socket.gethostname(),
1490
- "device_type": "Python Desktop / CLI",
1491
- "os": uname.system,
1492
- "arch": uname.machine,
1493
- "email": email,
1494
- "server_version": "1.0.0",
1495
- }
1496
- with httpx.Client(timeout=10.0) as client:
1497
- response = client.post(STORE + "?fluent-cart=activate_license", data=payload)
1498
- body = response.json()
1499
-
1500
- error = body.get("error_type")
1501
- if error in {
1502
- "trial_already_used",
1503
- "trial_fingerprint_required",
1504
- "trial_device_mismatch",
1505
- "device_blocked",
1506
- }:
1507
- raise RuntimeError(error)
1508
-
1509
- if body.get("status") == "valid":
1510
- keyring.set_password(KEYRING_SERVICE, "license_key", license_key)
1511
- keyring.set_password(KEYRING_SERVICE, "last_server_time", str(body.get("server_time_unix", 0)))
1512
-
1513
- return body
1409
+ text: `"""${appName} - FluentCart trial guard (Python)
1410
+
1411
+ Store: ${base}
1412
+ Product ID: ${productId}
1413
+ Dependencies: httpx, keyring
1414
+
1415
+ Flow: check_trial() before offering the trial, activate() on submit,
1416
+ check() on every launch. Never trust the local clock for expiry.
1417
+ """
1418
+
1419
+ import platform
1420
+ import socket
1421
+ import subprocess
1422
+ import sys
1423
+ import time
1424
+ import uuid
1425
+
1426
+ import httpx
1427
+ import keyring
1428
+
1429
+ STORE = "${base}"
1430
+ PRODUCT_ID = ${productId}
1431
+ KEYRING_SERVICE = "${slug}-trial"
1432
+
1433
+
1434
+ def machine_id() -> str:
1435
+ """Stable machine identifier. Linux: /etc/machine-id, Windows: MachineGuid."""
1436
+ if sys.platform.startswith("win"):
1437
+ try:
1438
+ import winreg
1439
+
1440
+ key = winreg.OpenKey(
1441
+ winreg.HKEY_LOCAL_MACHINE,
1442
+ r"SOFTWARE\\Microsoft\\Cryptography",
1443
+ )
1444
+ value, _ = winreg.QueryValueEx(key, "MachineGuid")
1445
+ return str(value)
1446
+ except Exception:
1447
+ return ""
1448
+ if sys.platform == "darwin":
1449
+ try:
1450
+ out = subprocess.check_output(
1451
+ ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
1452
+ text=True,
1453
+ )
1454
+ for line in out.splitlines():
1455
+ if "IOPlatformUUID" in line:
1456
+ return line.split("=")[-1].strip().strip('"')
1457
+ except Exception:
1458
+ return ""
1459
+ try:
1460
+ with open("/etc/machine-id", "r", encoding="utf-8") as handle:
1461
+ return handle.read().strip()
1462
+ except OSError:
1463
+ return ""
1464
+
1465
+
1466
+ def fingerprint() -> str:
1467
+ uname = platform.uname()
1468
+ return "v1|MACHINEID={}|HOST={}|OS={}|ARCH={}".format(
1469
+ machine_id() or "unknown",
1470
+ socket.gethostname(),
1471
+ uname.system,
1472
+ uname.machine,
1473
+ )
1474
+
1475
+
1476
+ def device_id() -> str:
1477
+ stored = keyring.get_password(KEYRING_SERVICE, "device_id")
1478
+ if stored:
1479
+ return stored
1480
+ new_id = "device://" + str(uuid.uuid4())
1481
+ keyring.set_password(KEYRING_SERVICE, "device_id", new_id)
1482
+ return new_id
1483
+
1484
+
1485
+ def check_trial(email: str) -> dict:
1486
+ payload = {
1487
+ "product_id": PRODUCT_ID,
1488
+ "device_fingerprint": fingerprint(),
1489
+ "email": email,
1490
+ }
1491
+ with httpx.Client(timeout=10.0) as client:
1492
+ response = client.post(STORE + "?fluent-cart=fastr_trial_eligibility", data=payload)
1493
+ return response.json()
1494
+
1495
+
1496
+ def activate(license_key: str, email: str) -> dict:
1497
+ uname = platform.uname()
1498
+ payload = {
1499
+ "item_id": PRODUCT_ID,
1500
+ "license_key": license_key,
1501
+ "site_url": device_id(),
1502
+ "device_fingerprint": fingerprint(),
1503
+ "device_name": socket.gethostname(),
1504
+ "device_type": "Python Desktop / CLI",
1505
+ "os": uname.system,
1506
+ "arch": uname.machine,
1507
+ "email": email,
1508
+ "server_version": "1.0.0",
1509
+ }
1510
+ with httpx.Client(timeout=10.0) as client:
1511
+ response = client.post(STORE + "?fluent-cart=activate_license", data=payload)
1512
+ body = response.json()
1513
+
1514
+ error = body.get("error_type")
1515
+ if error in {
1516
+ "trial_already_used",
1517
+ "trial_fingerprint_required",
1518
+ "trial_device_mismatch",
1519
+ "device_blocked",
1520
+ }:
1521
+ raise RuntimeError(error)
1522
+
1523
+ if body.get("status") == "valid":
1524
+ keyring.set_password(KEYRING_SERVICE, "license_key", license_key)
1525
+ keyring.set_password(KEYRING_SERVICE, "last_server_time", str(body.get("server_time_unix", 0)))
1526
+
1527
+ return body
1514
1528
  `
1515
1529
  }
1516
1530
  ]
@@ -1520,234 +1534,234 @@ def activate(license_key: str, email: str) -> dict:
1520
1534
  content: [
1521
1535
  {
1522
1536
  type: 'text',
1523
- text: `${header('Chrome Extension MV3', 'background.js')}
1524
- //
1525
- // manifest.json permissions: "storage", "alarms"
1526
- // Note: a user can clear chrome.storage in seconds, so browser trials are
1527
- // account-bound in practice. The fingerprint raises friction, it does not
1528
- // guarantee device identity.
1529
-
1530
- const STORE = "${base}";
1531
- const PRODUCT_ID = ${productId};
1532
- // Offline entitlement is bounded by the signed token's own exp, which the
1533
- // server issues. Nothing below trusts a timestamp this extension wrote:
1534
- // chrome.storage is editable from DevTools in seconds.
1535
- const PUBLIC_KEY_URL = STORE + "?fluent-cart=fastr_license_public_key";
1536
-
1537
- async function getInstallId() {
1538
- const data = await chrome.storage.local.get("install_id");
1539
- if (data.install_id) return data.install_id;
1540
- const id = "device://" + crypto.randomUUID();
1541
- await chrome.storage.local.set({ install_id: id });
1542
- return id;
1543
- }
1544
-
1545
- async function fingerprint() {
1546
- const manifest = chrome.runtime.getManifest();
1547
- return [
1548
- "v1",
1549
- "INSTALL=" + (await getInstallId()),
1550
- "EXT=" + chrome.runtime.id,
1551
- "CORES=" + (navigator.hardwareConcurrency || 0),
1552
- "TZ=" + Intl.DateTimeFormat().resolvedOptions().timeZone,
1553
- "VER=" + manifest.version
1554
- ].join("|");
1555
- }
1556
-
1557
- export async function checkTrial(email) {
1558
- const body = new URLSearchParams({
1559
- product_id: String(PRODUCT_ID),
1560
- device_fingerprint: await fingerprint(),
1561
- email: email || ""
1562
- });
1563
-
1564
- const res = await fetch(STORE + "?fluent-cart=fastr_trial_eligibility", {
1565
- method: "POST",
1566
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1567
- body: body.toString()
1568
- });
1569
-
1570
- const json = await res.json();
1571
- await chrome.storage.local.set({ trial_risk: json.risk_score || 0 });
1572
- return json;
1573
- }
1574
-
1575
- export async function activateLicense(licenseKey, email) {
1576
- const installId = await getInstallId();
1577
- const body = new URLSearchParams({
1578
- item_id: String(PRODUCT_ID),
1579
- license_key: licenseKey,
1580
- site_url: installId,
1581
- device_fingerprint: await fingerprint(),
1582
- device_name: "Chrome Browser Profile",
1583
- device_type: "Chrome Extension",
1584
- os: navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
1585
- email: email || "",
1586
- server_version: chrome.runtime.getManifest().version
1587
- });
1588
-
1589
- const res = await fetch(STORE + "?fluent-cart=activate_license", {
1590
- method: "POST",
1591
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1592
- body: body.toString()
1593
- });
1594
-
1595
- const json = await res.json();
1596
-
1597
- if (json.error_type === "trial_already_used") throw new Error("trial_already_used");
1598
- if (json.error_type === "trial_fingerprint_required") throw new Error("client_outdated");
1599
- if (json.error_type === "trial_device_mismatch") throw new Error("trial_device_mismatch");
1600
-
1601
- if (json.status === "valid" && json.license_token) {
1602
- await chrome.storage.local.set({
1603
- license_key: licenseKey,
1604
- activation_hash: json.activation_hash,
1605
- license_token: json.license_token,
1606
- server_time_unix: json.server_time_unix,
1607
- local_at_check: Date.now()
1608
- });
1609
- }
1610
-
1611
- return json;
1612
- }
1613
-
1614
- function b64Bytes(input) {
1615
- const bin = atob(input.replace(/-/g, "+").replace(/_/g, "/"));
1616
- const out = new Uint8Array(bin.length);
1617
- for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1618
- return out;
1619
- }
1620
-
1621
- async function storePublicKey() {
1622
- const cached = await chrome.storage.local.get("fastr_public_key");
1623
- if (cached.fastr_public_key) return cached.fastr_public_key;
1624
-
1625
- const res = await fetch(PUBLIC_KEY_URL, { cache: "no-store" });
1626
- const json = await res.json();
1627
- // The store answers { kid, alg, public_key_pem, ... }. Guessing a shorter
1628
- // name here means the key is never found and every user is locked out.
1629
- const pem = String(json.public_key_pem || json.public_key || json.pem || "");
1630
-
1631
- if (pem) await chrome.storage.local.set({ fastr_public_key: pem });
1632
- return pem;
1633
- }
1634
-
1635
- // RS256 verification. A token the user forges fails here; a token the store
1636
- // signed cannot be edited without breaking the signature.
1637
- export async function verifyLicenseToken(token, pem) {
1638
- const parts = String(token || "").split(".");
1639
- if (parts.length !== 3 || !pem) return null;
1640
-
1641
- try {
1642
- const der = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
1643
-
1644
- const key = await crypto.subtle.importKey(
1645
- "spki",
1646
- b64Bytes(der),
1647
- { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
1648
- false,
1649
- ["verify"]
1650
- );
1651
-
1652
- const ok = await crypto.subtle.verify(
1653
- "RSASSA-PKCS1-v1_5",
1654
- key,
1655
- b64Bytes(parts[2]),
1656
- new TextEncoder().encode(parts[0] + "." + parts[1])
1657
- );
1658
-
1659
- if (!ok) return null;
1660
-
1661
- const claims = JSON.parse(new TextDecoder().decode(b64Bytes(parts[1])));
1662
-
1663
- if (typeof claims.exp === "number" && claims.exp <= Math.floor(Date.now() / 1000)) {
1664
- return null;
1665
- }
1666
-
1667
- return claims;
1668
- } catch (error) {
1669
- return null;
1670
- }
1671
- }
1672
-
1673
- // What the extension should gate on. Verified offline against the store's key,
1674
- // so the answer survives losing the network but not editing storage.
1675
- export async function hasAccess() {
1676
- const data = await chrome.storage.local.get([
1677
- "license_key",
1678
- "license_token",
1679
- "local_at_check"
1680
- ]);
1681
-
1682
- if (!data.license_key || !data.license_token) {
1683
- return { status: "unlicensed" };
1684
- }
1685
-
1686
- // A clock that now reads earlier than it did at the last successful check
1687
- // defeats the expiry check below, so refuse instead of guessing.
1688
- if (data.local_at_check && Date.now() < data.local_at_check) {
1689
- return { status: "invalid", reason: "clock_rollback" };
1690
- }
1691
-
1692
- const pem = await storePublicKey();
1693
- const claims = await verifyLicenseToken(data.license_token, pem);
1694
-
1695
- if (!claims) {
1696
- return { status: "expired", reason: "token_invalid_or_expired" };
1697
- }
1698
-
1699
- return { status: "valid", source: "offline_token", claims };
1700
- }
1701
-
1702
- export async function checkLicense() {
1703
- const data = await chrome.storage.local.get([
1704
- "license_key",
1705
- "install_id",
1706
- "license_token"
1707
- ]);
1708
-
1709
- if (!data.license_key || !data.install_id) return { status: "unlicensed" };
1710
-
1711
- const body = new URLSearchParams({
1712
- item_id: String(PRODUCT_ID),
1713
- license_key: data.license_key,
1714
- site_url: data.install_id,
1715
- device_fingerprint: await fingerprint()
1716
- });
1717
-
1718
- try {
1719
- const res = await fetch(STORE + "?fluent-cart=check_license", {
1720
- method: "POST",
1721
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1722
- body: body.toString()
1723
- });
1724
-
1725
- const json = await res.json();
1726
-
1727
- if (json.status !== "valid") {
1728
- // The store said no. Whatever is still on disk is now a lie.
1729
- await chrome.storage.local.remove(["license_token", "local_at_check"]);
1730
- return json;
1731
- }
1732
-
1733
- await chrome.storage.local.set({
1734
- license_token: json.license_token || data.license_token,
1735
- server_time_unix: json.server_time_unix,
1736
- local_at_check: Date.now()
1737
- });
1738
-
1739
- return json;
1740
- } catch (error) {
1741
- // No network. The signed token is the best evidence available, and it
1742
- // expires on the server's schedule rather than ours.
1743
- return await hasAccess();
1744
- }
1745
- }
1746
-
1747
- chrome.alarms.create("fastr_license_check", { periodInMinutes: 60 });
1748
- chrome.alarms.onAlarm.addListener((alarm) => {
1749
- if (alarm.name === "fastr_license_check") checkLicense();
1750
- });
1537
+ text: `${header('Chrome Extension MV3', 'background.js')}
1538
+ //
1539
+ // manifest.json permissions: "storage", "alarms"
1540
+ // Note: a user can clear chrome.storage in seconds, so browser trials are
1541
+ // account-bound in practice. The fingerprint raises friction, it does not
1542
+ // guarantee device identity.
1543
+
1544
+ const STORE = "${base}";
1545
+ const PRODUCT_ID = ${productId};
1546
+ // Offline entitlement is bounded by the signed token's own exp, which the
1547
+ // server issues. Nothing below trusts a timestamp this extension wrote:
1548
+ // chrome.storage is editable from DevTools in seconds.
1549
+ const PUBLIC_KEY_URL = STORE + "?fluent-cart=fastr_license_public_key";
1550
+
1551
+ async function getInstallId() {
1552
+ const data = await chrome.storage.local.get("install_id");
1553
+ if (data.install_id) return data.install_id;
1554
+ const id = "device://" + crypto.randomUUID();
1555
+ await chrome.storage.local.set({ install_id: id });
1556
+ return id;
1557
+ }
1558
+
1559
+ async function fingerprint() {
1560
+ const manifest = chrome.runtime.getManifest();
1561
+ return [
1562
+ "v1",
1563
+ "INSTALL=" + (await getInstallId()),
1564
+ "EXT=" + chrome.runtime.id,
1565
+ "CORES=" + (navigator.hardwareConcurrency || 0),
1566
+ "TZ=" + Intl.DateTimeFormat().resolvedOptions().timeZone,
1567
+ "VER=" + manifest.version
1568
+ ].join("|");
1569
+ }
1570
+
1571
+ export async function checkTrial(email) {
1572
+ const body = new URLSearchParams({
1573
+ product_id: String(PRODUCT_ID),
1574
+ device_fingerprint: await fingerprint(),
1575
+ email: email || ""
1576
+ });
1577
+
1578
+ const res = await fetch(STORE + "?fluent-cart=fastr_trial_eligibility", {
1579
+ method: "POST",
1580
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1581
+ body: body.toString()
1582
+ });
1583
+
1584
+ const json = await res.json();
1585
+ await chrome.storage.local.set({ trial_risk: json.risk_score || 0 });
1586
+ return json;
1587
+ }
1588
+
1589
+ export async function activateLicense(licenseKey, email) {
1590
+ const installId = await getInstallId();
1591
+ const body = new URLSearchParams({
1592
+ item_id: String(PRODUCT_ID),
1593
+ license_key: licenseKey,
1594
+ site_url: installId,
1595
+ device_fingerprint: await fingerprint(),
1596
+ device_name: "Chrome Browser Profile",
1597
+ device_type: "Chrome Extension",
1598
+ os: navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
1599
+ email: email || "",
1600
+ server_version: chrome.runtime.getManifest().version
1601
+ });
1602
+
1603
+ const res = await fetch(STORE + "?fluent-cart=activate_license", {
1604
+ method: "POST",
1605
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1606
+ body: body.toString()
1607
+ });
1608
+
1609
+ const json = await res.json();
1610
+
1611
+ if (json.error_type === "trial_already_used") throw new Error("trial_already_used");
1612
+ if (json.error_type === "trial_fingerprint_required") throw new Error("client_outdated");
1613
+ if (json.error_type === "trial_device_mismatch") throw new Error("trial_device_mismatch");
1614
+
1615
+ if (json.status === "valid" && json.license_token) {
1616
+ await chrome.storage.local.set({
1617
+ license_key: licenseKey,
1618
+ activation_hash: json.activation_hash,
1619
+ license_token: json.license_token,
1620
+ server_time_unix: json.server_time_unix,
1621
+ local_at_check: Date.now()
1622
+ });
1623
+ }
1624
+
1625
+ return json;
1626
+ }
1627
+
1628
+ function b64Bytes(input) {
1629
+ const bin = atob(input.replace(/-/g, "+").replace(/_/g, "/"));
1630
+ const out = new Uint8Array(bin.length);
1631
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
1632
+ return out;
1633
+ }
1634
+
1635
+ async function storePublicKey() {
1636
+ const cached = await chrome.storage.local.get("fastr_public_key");
1637
+ if (cached.fastr_public_key) return cached.fastr_public_key;
1638
+
1639
+ const res = await fetch(PUBLIC_KEY_URL, { cache: "no-store" });
1640
+ const json = await res.json();
1641
+ // The store answers { kid, alg, public_key_pem, ... }. Guessing a shorter
1642
+ // name here means the key is never found and every user is locked out.
1643
+ const pem = String(json.public_key_pem || json.public_key || json.pem || "");
1644
+
1645
+ if (pem) await chrome.storage.local.set({ fastr_public_key: pem });
1646
+ return pem;
1647
+ }
1648
+
1649
+ // RS256 verification. A token the user forges fails here; a token the store
1650
+ // signed cannot be edited without breaking the signature.
1651
+ export async function verifyLicenseToken(token, pem) {
1652
+ const parts = String(token || "").split(".");
1653
+ if (parts.length !== 3 || !pem) return null;
1654
+
1655
+ try {
1656
+ const der = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
1657
+
1658
+ const key = await crypto.subtle.importKey(
1659
+ "spki",
1660
+ b64Bytes(der),
1661
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
1662
+ false,
1663
+ ["verify"]
1664
+ );
1665
+
1666
+ const ok = await crypto.subtle.verify(
1667
+ "RSASSA-PKCS1-v1_5",
1668
+ key,
1669
+ b64Bytes(parts[2]),
1670
+ new TextEncoder().encode(parts[0] + "." + parts[1])
1671
+ );
1672
+
1673
+ if (!ok) return null;
1674
+
1675
+ const claims = JSON.parse(new TextDecoder().decode(b64Bytes(parts[1])));
1676
+
1677
+ if (typeof claims.exp === "number" && claims.exp <= Math.floor(Date.now() / 1000)) {
1678
+ return null;
1679
+ }
1680
+
1681
+ return claims;
1682
+ } catch (error) {
1683
+ return null;
1684
+ }
1685
+ }
1686
+
1687
+ // What the extension should gate on. Verified offline against the store's key,
1688
+ // so the answer survives losing the network but not editing storage.
1689
+ export async function hasAccess() {
1690
+ const data = await chrome.storage.local.get([
1691
+ "license_key",
1692
+ "license_token",
1693
+ "local_at_check"
1694
+ ]);
1695
+
1696
+ if (!data.license_key || !data.license_token) {
1697
+ return { status: "unlicensed" };
1698
+ }
1699
+
1700
+ // A clock that now reads earlier than it did at the last successful check
1701
+ // defeats the expiry check below, so refuse instead of guessing.
1702
+ if (data.local_at_check && Date.now() < data.local_at_check) {
1703
+ return { status: "invalid", reason: "clock_rollback" };
1704
+ }
1705
+
1706
+ const pem = await storePublicKey();
1707
+ const claims = await verifyLicenseToken(data.license_token, pem);
1708
+
1709
+ if (!claims) {
1710
+ return { status: "expired", reason: "token_invalid_or_expired" };
1711
+ }
1712
+
1713
+ return { status: "valid", source: "offline_token", claims };
1714
+ }
1715
+
1716
+ export async function checkLicense() {
1717
+ const data = await chrome.storage.local.get([
1718
+ "license_key",
1719
+ "install_id",
1720
+ "license_token"
1721
+ ]);
1722
+
1723
+ if (!data.license_key || !data.install_id) return { status: "unlicensed" };
1724
+
1725
+ const body = new URLSearchParams({
1726
+ item_id: String(PRODUCT_ID),
1727
+ license_key: data.license_key,
1728
+ site_url: data.install_id,
1729
+ device_fingerprint: await fingerprint()
1730
+ });
1731
+
1732
+ try {
1733
+ const res = await fetch(STORE + "?fluent-cart=check_license", {
1734
+ method: "POST",
1735
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1736
+ body: body.toString()
1737
+ });
1738
+
1739
+ const json = await res.json();
1740
+
1741
+ if (json.status !== "valid") {
1742
+ // The store said no. Whatever is still on disk is now a lie.
1743
+ await chrome.storage.local.remove(["license_token", "local_at_check"]);
1744
+ return json;
1745
+ }
1746
+
1747
+ await chrome.storage.local.set({
1748
+ license_token: json.license_token || data.license_token,
1749
+ server_time_unix: json.server_time_unix,
1750
+ local_at_check: Date.now()
1751
+ });
1752
+
1753
+ return json;
1754
+ } catch (error) {
1755
+ // No network. The signed token is the best evidence available, and it
1756
+ // expires on the server's schedule rather than ours.
1757
+ return await hasAccess();
1758
+ }
1759
+ }
1760
+
1761
+ chrome.alarms.create("fastr_license_check", { periodInMinutes: 60 });
1762
+ chrome.alarms.onAlarm.addListener((alarm) => {
1763
+ if (alarm.name === "fastr_license_check") checkLicense();
1764
+ });
1751
1765
  `
1752
1766
  }
1753
1767
  ]
@@ -1778,136 +1792,262 @@ chrome.alarms.onAlarm.addListener((alarm) => {
1778
1792
  content: [
1779
1793
  {
1780
1794
  type: 'text',
1781
- text: `${header('Node / Electron', 'src/license.ts')}
1782
- import { createVerify } from "node:crypto";
1783
-
1784
- const STORE = "${base}";
1785
- const PRODUCT_ID = ${productId};
1786
-
1787
- export type LicenseState = {
1788
- status: string;
1789
- token?: string;
1790
- entitlements?: number[];
1791
- expiresInDays?: number;
1792
- errorType?: string;
1793
- };
1794
-
1795
- async function call(verb: string, body: Record<string, string>) {
1796
- const res = await fetch(STORE + "?fluent-cart=" + verb, {
1797
- method: "POST",
1798
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1799
- body: new URLSearchParams(body).toString()
1800
- });
1801
- return { http: res.status, json: await res.json() };
1802
- }
1803
-
1804
- export async function activate(licenseKey: string, instanceId: string, fingerprint: string, email: string): Promise<LicenseState> {
1805
- const { json } = await call("activate_license", {
1806
- item_id: String(PRODUCT_ID),
1807
- license_key: licenseKey,
1808
- site_url: instanceId,
1809
- device_fingerprint: fingerprint,
1810
- device_name: process.env.COMPUTERNAME || "desktop",
1811
- device_type: "Desktop (Node)",
1812
- os: process.platform + " " + process.arch,
1813
- email,
1814
- server_version: "1.0.0"
1815
- });
1816
-
1817
- // FluentCart returns key_mismatch / invalid_activation as HTTP 200 with
1818
- // success=true. Only status === "valid" means licensed.
1819
- return {
1820
- status: json.status,
1821
- token: json.license_token,
1822
- entitlements: json.entitlements,
1823
- expiresInDays: json.expires_in_days,
1824
- errorType: json.error_type
1825
- };
1826
- }
1827
-
1828
- export async function check(licenseKey: string, instanceId: string, fingerprint: string): Promise<LicenseState> {
1829
- const { json } = await call("check_license", {
1830
- item_id: String(PRODUCT_ID),
1831
- license_key: licenseKey,
1832
- site_url: instanceId,
1833
- device_fingerprint: fingerprint
1834
- });
1835
- return { status: json.status, token: json.license_token, entitlements: json.entitlements };
1836
- }
1837
-
1838
- export async function deactivate(licenseKey: string, instanceId: string): Promise<void> {
1839
- await call("deactivate_license", {
1840
- item_id: String(PRODUCT_ID),
1841
- license_key: licenseKey,
1842
- site_url: instanceId
1843
- });
1844
- }
1845
-
1846
- export async function latestRelease(licenseKey: string, currentVersion: string, platform = "any") {
1847
- const query = new URLSearchParams({
1848
- product_id: String(PRODUCT_ID),
1849
- platform,
1850
- current_version: currentVersion,
1851
- license_key: licenseKey
1852
- });
1853
- const res = await fetch(STORE + "?fluent-cart=fastr_release_latest&" + query.toString());
1854
- return res.json();
1855
- }
1856
-
1857
- export async function reportUsage(licenseKey: string, metric: string, quantity: number, idempotencyKey: string) {
1858
- const { json } = await call("fastr_usage_report", {
1859
- license_key: licenseKey,
1860
- metric,
1861
- quantity: String(quantity),
1862
- idempotency_key: idempotencyKey
1863
- });
1864
- return json;
1865
- }
1866
-
1867
- // After verifying, compare claims.ins and claims.fp with this install and
1868
- // claims.prod / claims.ent with the product you are running.
1869
- export function verifyToken(token: string, publicKeyPem: string): Record<string, unknown> | null {
1870
- const parts = token.split(".");
1871
- if (parts.length !== 3) return null;
1872
- const verifier = createVerify("RSA-SHA256");
1873
- verifier.update(parts[0] + "." + parts[1]);
1874
- if (!verifier.verify(publicKeyPem, Buffer.from(parts[2], "base64url"))) return null;
1875
- const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
1876
- if (typeof claims.exp === "number" && claims.exp < Math.floor(Date.now() / 1000)) return null;
1877
- return claims;
1878
- }
1879
-
1880
- /**
1881
- * Decide whether the app should run, binding the token to THIS installation.
1882
- *
1883
- * verifyToken proves the store signed the token and that it has not expired.
1884
- * It does not prove the token was issued for this machine or this product, so
1885
- * a token copied from another install passes it. Compare the claims before
1886
- * granting anything.
1887
- *
1888
- * claims.fp is a server-side HMAC of the device fingerprint and cannot be
1889
- * recomputed here, so claims.ins (the install id you sent as site_url) is the
1890
- * binding a client is able to check. That is friction against sharing, not a
1891
- * guarantee: the server's check() is what actually enforces seats.
1892
- */
1893
- export function entitlement(
1894
- token: string,
1895
- publicKeyPem: string,
1896
- expected: { installId?: string; productId?: number }
1897
- ): { ok: boolean; reason?: string; claims?: Record<string, unknown> } {
1898
- const claims = verifyToken(token, publicKeyPem);
1899
- if (!claims) return { ok: false, reason: "invalid_or_expired" };
1900
-
1901
- if (typeof expected.productId === "number" && Number(claims.prod) !== expected.productId) {
1902
- return { ok: false, reason: "wrong_product" };
1903
- }
1904
-
1905
- if (expected.installId && claims.ins && String(claims.ins) !== expected.installId) {
1906
- return { ok: false, reason: "wrong_install" };
1907
- }
1908
-
1909
- return { ok: true, claims };
1910
- }
1795
+ text: `${header('Node / Electron', 'src/license.ts')}
1796
+ import { createVerify, randomUUID } from "node:crypto";
1797
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1798
+ import { homedir } from "node:os";
1799
+ import { join } from "node:path";
1800
+
1801
+ const STORE = "${base}";
1802
+ const PRODUCT_ID = ${productId};
1803
+
1804
+ /**
1805
+ * Where the device id and the last verdict live. In Electron, point this at
1806
+ * app.getPath("userData") before the first call.
1807
+ */
1808
+ const DATA_DIR = process.env.FASTR_DATA_DIR || join(homedir(), ".${slug}");
1809
+ const DEVICE_FILE = join(DATA_DIR, "device-id");
1810
+ const STATE_FILE = join(DATA_DIR, "license.json");
1811
+
1812
+ /** A backwards clock jump larger than this means the machine was moved. */
1813
+ const CLOCK_TOLERANCE_SECS = 300;
1814
+ /** How long a cached verdict survives without reaching the store. */
1815
+ const OFFLINE_GRACE_SECS = 7 * 24 * 60 * 60;
1816
+
1817
+ export type LicenseState = {
1818
+ status: string;
1819
+ token?: string;
1820
+ entitlements?: number[];
1821
+ expiresInDays?: number | null;
1822
+ errorType?: string;
1823
+ };
1824
+
1825
+ type StoredState = LicenseState & {
1826
+ licenseKey: string;
1827
+ deviceId: string;
1828
+ variationTitle?: string;
1829
+ expires?: string;
1830
+ /** Server clock at the last successful call — the only time we trust. */
1831
+ serverTimeUnix?: number;
1832
+ /** Local clock at that same moment, used to detect a rollback. */
1833
+ checkedAtLocal: number;
1834
+ };
1835
+
1836
+ /**
1837
+ * device://<uuid>, created once and kept.
1838
+ *
1839
+ * Deriving this from hardware is wrong: MAC addresses change, serials are not
1840
+ * readable on every platform, and both can be cloned. Persist it, never
1841
+ * regenerate it on update, and never let a failed write invent a new one —
1842
+ * a new id is a new seat.
1843
+ */
1844
+ export function deviceId(): string {
1845
+ try {
1846
+ const existing = readFileSync(DEVICE_FILE, "utf8").trim();
1847
+ if (existing) return existing;
1848
+ } catch {
1849
+ /* first run */
1850
+ }
1851
+
1852
+ const fresh = "device://" + randomUUID();
1853
+ mkdirSync(DATA_DIR, { recursive: true });
1854
+ writeFileSync(DEVICE_FILE, fresh, { mode: 0o600 });
1855
+ return fresh;
1856
+ }
1857
+
1858
+ export function loadState(): StoredState | null {
1859
+ try {
1860
+ return JSON.parse(readFileSync(STATE_FILE, "utf8")) as StoredState;
1861
+ } catch {
1862
+ return null;
1863
+ }
1864
+ }
1865
+
1866
+ function saveState(state: StoredState): void {
1867
+ mkdirSync(DATA_DIR, { recursive: true });
1868
+ writeFileSync(STATE_FILE, JSON.stringify(state), { mode: 0o600 });
1869
+ }
1870
+
1871
+ /**
1872
+ * False when the local clock sits more than CLOCK_TOLERANCE_SECS behind the
1873
+ * moment of the last check — the signature of someone trying to outlive an
1874
+ * expiry. Forward jumps are not flagged: they only cost the user.
1875
+ */
1876
+ export function clockIsSane(state: StoredState | null = loadState()): boolean {
1877
+ if (!state || !state.checkedAtLocal) return true;
1878
+ return Math.floor(Date.now() / 1000) - state.checkedAtLocal >= -CLOCK_TOLERANCE_SECS;
1879
+ }
1880
+
1881
+ /** The online verdict, using the server-computed remaining days. */
1882
+ export function isLicensed(state: StoredState | null = loadState()): boolean {
1883
+ if (!state) return false;
1884
+ if (state.status !== "valid" && state.status !== "active") return false;
1885
+ if (!clockIsSane(state)) return false;
1886
+ // Server-computed: never do date math against the local clock.
1887
+ if (typeof state.expiresInDays === "number") return state.expiresInDays >= 0;
1888
+ return true; // lifetime
1889
+ }
1890
+
1891
+ /**
1892
+ * The verdict to use when the store cannot be reached. A tampered clock is
1893
+ * refused outright; an untouched clock is trusted for OFFLINE_GRACE_SECS.
1894
+ */
1895
+ export function isLicensedOffline(state: StoredState | null = loadState()): boolean {
1896
+ if (!state) return false;
1897
+ if (!clockIsSane(state)) return false;
1898
+ const age = Math.floor(Date.now() / 1000) - state.checkedAtLocal;
1899
+ if (age > OFFLINE_GRACE_SECS) return false;
1900
+ return isLicensed(state);
1901
+ }
1902
+
1903
+ async function call(verb: string, body: Record<string, string>) {
1904
+ const res = await fetch(STORE + "?fluent-cart=" + verb, {
1905
+ method: "POST",
1906
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
1907
+ body: new URLSearchParams(body).toString()
1908
+ });
1909
+ return { http: res.status, json: await res.json() };
1910
+ }
1911
+
1912
+ // instanceId defaults to the persisted device id, so a restart reuses the same
1913
+ // seat instead of registering a new device.
1914
+ export async function activate(licenseKey: string, fingerprint: string, email = "", instanceId = deviceId()): Promise<LicenseState> {
1915
+ const { json } = await call("activate_license", {
1916
+ item_id: String(PRODUCT_ID),
1917
+ license_key: licenseKey,
1918
+ site_url: instanceId,
1919
+ device_fingerprint: fingerprint,
1920
+ device_name: process.env.COMPUTERNAME || "desktop",
1921
+ device_type: "Desktop (Node)",
1922
+ os: process.platform + " " + process.arch,
1923
+ email,
1924
+ server_version: "1.0.0"
1925
+ });
1926
+
1927
+ // FluentCart returns key_mismatch / invalid_activation as HTTP 200 with
1928
+ // success=true. Only status === "valid" means licensed.
1929
+ const state: StoredState = {
1930
+ licenseKey,
1931
+ deviceId: instanceId,
1932
+ status: json.status,
1933
+ token: json.license_token,
1934
+ entitlements: json.entitlements,
1935
+ expiresInDays: json.expires_in_days ?? null,
1936
+ errorType: json.error_type,
1937
+ variationTitle: json.variation_title,
1938
+ expires: json.expires,
1939
+ serverTimeUnix: json.server_time_unix,
1940
+ checkedAtLocal: Math.floor(Date.now() / 1000)
1941
+ };
1942
+ saveState(state);
1943
+ return state;
1944
+ }
1945
+
1946
+ export async function check(licenseKey: string, fingerprint: string, instanceId = deviceId()): Promise<LicenseState> {
1947
+ const { json } = await call("check_license", {
1948
+ item_id: String(PRODUCT_ID),
1949
+ license_key: licenseKey,
1950
+ site_url: instanceId,
1951
+ device_fingerprint: fingerprint
1952
+ });
1953
+
1954
+ const prev = loadState();
1955
+ const state: StoredState = {
1956
+ licenseKey,
1957
+ deviceId: instanceId,
1958
+ status: json.status ?? "unknown",
1959
+ token: json.license_token ?? prev?.token,
1960
+ entitlements: json.entitlements ?? prev?.entitlements,
1961
+ expiresInDays: json.expires_in_days ?? prev?.expiresInDays ?? null,
1962
+ variationTitle: json.variation_title ?? prev?.variationTitle,
1963
+ expires: json.expires ?? prev?.expires,
1964
+ serverTimeUnix: json.server_time_unix ?? prev?.serverTimeUnix,
1965
+ checkedAtLocal: Math.floor(Date.now() / 1000)
1966
+ };
1967
+ saveState(state);
1968
+ return state;
1969
+ }
1970
+
1971
+ export async function deactivate(licenseKey: string, instanceId = deviceId()): Promise<void> {
1972
+ await call("deactivate_license", {
1973
+ item_id: String(PRODUCT_ID),
1974
+ license_key: licenseKey,
1975
+ site_url: instanceId
1976
+ });
1977
+
1978
+ // The device id stays: it is this machine's identity, not the licence's.
1979
+ try {
1980
+ rmSync(STATE_FILE);
1981
+ } catch {
1982
+ /* nothing cached */
1983
+ }
1984
+ }
1985
+
1986
+ export async function latestRelease(licenseKey: string, currentVersion: string, platform = "any") {
1987
+ const query = new URLSearchParams({
1988
+ product_id: String(PRODUCT_ID),
1989
+ platform,
1990
+ current_version: currentVersion,
1991
+ license_key: licenseKey
1992
+ });
1993
+ const res = await fetch(STORE + "?fluent-cart=fastr_release_latest&" + query.toString());
1994
+ return res.json();
1995
+ }
1996
+
1997
+ export async function reportUsage(licenseKey: string, metric: string, quantity: number, idempotencyKey: string) {
1998
+ const { json } = await call("fastr_usage_report", {
1999
+ license_key: licenseKey,
2000
+ metric,
2001
+ quantity: String(quantity),
2002
+ idempotency_key: idempotencyKey
2003
+ });
2004
+ return json;
2005
+ }
2006
+
2007
+ // After verifying, compare claims.ins and claims.fp with this install and
2008
+ // claims.prod / claims.ent with the product you are running.
2009
+ export function verifyToken(token: string, publicKeyPem: string): Record<string, unknown> | null {
2010
+ const parts = token.split(".");
2011
+ if (parts.length !== 3) return null;
2012
+ const verifier = createVerify("RSA-SHA256");
2013
+ verifier.update(parts[0] + "." + parts[1]);
2014
+ if (!verifier.verify(publicKeyPem, Buffer.from(parts[2], "base64url"))) return null;
2015
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2016
+ if (typeof claims.exp === "number" && claims.exp < Math.floor(Date.now() / 1000)) return null;
2017
+ return claims;
2018
+ }
2019
+
2020
+ /**
2021
+ * Decide whether the app should run, binding the token to THIS installation.
2022
+ *
2023
+ * verifyToken proves the store signed the token and that it has not expired.
2024
+ * It does not prove the token was issued for this machine or this product, so
2025
+ * a token copied from another install passes it. Compare the claims before
2026
+ * granting anything.
2027
+ *
2028
+ * claims.fp is a server-side HMAC of the device fingerprint and cannot be
2029
+ * recomputed here, so claims.ins (the install id you sent as site_url) is the
2030
+ * binding a client is able to check. That is friction against sharing, not a
2031
+ * guarantee: the server's check() is what actually enforces seats.
2032
+ */
2033
+ export function entitlement(
2034
+ token: string,
2035
+ publicKeyPem: string,
2036
+ expected: { installId?: string; productId?: number }
2037
+ ): { ok: boolean; reason?: string; claims?: Record<string, unknown> } {
2038
+ const claims = verifyToken(token, publicKeyPem);
2039
+ if (!claims) return { ok: false, reason: "invalid_or_expired" };
2040
+
2041
+ if (typeof expected.productId === "number" && Number(claims.prod) !== expected.productId) {
2042
+ return { ok: false, reason: "wrong_product" };
2043
+ }
2044
+
2045
+ if (expected.installId && claims.ins && String(claims.ins) !== expected.installId) {
2046
+ return { ok: false, reason: "wrong_install" };
2047
+ }
2048
+
2049
+ return { ok: true, claims };
2050
+ }
1911
2051
  `
1912
2052
  }
1913
2053
  ]
@@ -1918,200 +2058,200 @@ export function entitlement(
1918
2058
  content: [
1919
2059
  {
1920
2060
  type: 'text',
1921
- text: `${header('.NET (WPF / MAUI / console)', 'License.cs')}
1922
- using System;
1923
- using System.Collections.Generic;
1924
- using System.Net.Http;
1925
- using System.Security.Cryptography;
1926
- using System.Text;
1927
- using System.Text.Json;
1928
- using System.Threading.Tasks;
1929
-
1930
- public sealed class LicenseState
1931
- {
1932
- public string Status { get; set; } = "";
1933
- public string? Token { get; set; }
1934
- public List<int> Entitlements { get; set; } = new();
1935
- public string? ErrorType { get; set; }
1936
- }
1937
-
1938
- public static class FastrLicense
1939
- {
1940
- private const string Store = "${base}";
1941
- private const int ProductId = ${productId};
1942
- private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };
1943
-
1944
- private static async Task<JsonElement> CallAsync(string verb, Dictionary<string, string> body)
1945
- {
1946
- var res = await Http.PostAsync(Store + "?fluent-cart=" + verb, new FormUrlEncodedContent(body));
1947
- var text = await res.Content.ReadAsStringAsync();
1948
- using var doc = JsonDocument.Parse(text);
1949
- return doc.RootElement.Clone();
1950
- }
1951
-
1952
- public static async Task<LicenseState> ActivateAsync(string licenseKey, string instanceId, string fingerprint, string email)
1953
- {
1954
- var json = await CallAsync("activate_license", new Dictionary<string, string>
1955
- {
1956
- ["item_id"] = ProductId.ToString(),
1957
- ["license_key"] = licenseKey,
1958
- ["site_url"] = instanceId,
1959
- ["device_fingerprint"] = fingerprint,
1960
- ["device_name"] = Environment.MachineName,
1961
- ["device_type"] = "Desktop (.NET)",
1962
- ["os"] = Environment.OSVersion.ToString(),
1963
- ["email"] = email,
1964
- ["server_version"] = "1.0.0"
1965
- });
1966
-
1967
- // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
1968
- var state = new LicenseState
1969
- {
1970
- Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
1971
- Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
1972
- ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
1973
- };
1974
-
1975
- if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
1976
- {
1977
- foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
1978
- }
1979
-
1980
- return state;
1981
- }
1982
-
1983
- public static async Task<LicenseState> CheckAsync(string licenseKey, string instanceId, string fingerprint)
1984
- {
1985
- var json = await CallAsync("check_license", new Dictionary<string, string>
1986
- {
1987
- ["item_id"] = ProductId.ToString(),
1988
- ["license_key"] = licenseKey,
1989
- ["site_url"] = instanceId,
1990
- ["device_fingerprint"] = fingerprint
1991
- });
1992
-
1993
- var state = new LicenseState
1994
- {
1995
- Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
1996
- Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
1997
- ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
1998
- };
1999
-
2000
- if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2001
- {
2002
- foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2003
- }
2004
-
2005
- return state;
2006
- }
2007
-
2008
- public static async Task DeactivateAsync(string licenseKey, string instanceId)
2009
- {
2010
- await CallAsync("deactivate_license", new Dictionary<string, string>
2011
- {
2012
- ["item_id"] = ProductId.ToString(),
2013
- ["license_key"] = licenseKey,
2014
- ["site_url"] = instanceId
2015
- });
2016
- }
2017
-
2018
- public static async Task<JsonElement> LatestReleaseAsync(string licenseKey, string currentVersion, string platform = "any")
2019
- {
2020
- var url = Store + "?fluent-cart=fastr_release_latest&product_id=" + ProductId
2021
- + "&platform=" + Uri.EscapeDataString(platform)
2022
- + "&current_version=" + Uri.EscapeDataString(currentVersion)
2023
- + "&license_key=" + Uri.EscapeDataString(licenseKey);
2024
-
2025
- var text = await Http.GetStringAsync(url);
2026
- using var doc = JsonDocument.Parse(text);
2027
- return doc.RootElement.Clone();
2028
- }
2029
-
2030
- public static Task<JsonElement> ReportUsageAsync(string licenseKey, string metric, int quantity, string idempotencyKey)
2031
- {
2032
- return CallAsync("fastr_usage_report", new Dictionary<string, string>
2033
- {
2034
- ["license_key"] = licenseKey,
2035
- ["metric"] = metric,
2036
- ["quantity"] = quantity.ToString(),
2037
- ["idempotency_key"] = idempotencyKey
2038
- });
2039
- }
2040
-
2041
- // After verifying, compare claims ins/fp with this install and prod/ent
2042
- // with the product you are running.
2043
- public static bool VerifyToken(string token, string publicKeyPem, out JsonElement claims)
2044
- {
2045
- claims = default;
2046
- var parts = token.Split('.');
2047
- if (parts.Length != 3) return false;
2048
-
2049
- using var rsa = RSA.Create();
2050
- rsa.ImportFromPem(publicKeyPem);
2051
-
2052
- var data = Encoding.ASCII.GetBytes(parts[0] + "." + parts[1]);
2053
- var signature = Base64UrlDecode(parts[2]);
2054
-
2055
- if (!rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) return false;
2056
-
2057
- using var doc = JsonDocument.Parse(Base64UrlDecode(parts[1]));
2058
- claims = doc.RootElement.Clone();
2059
- return true;
2060
- }
2061
-
2062
- /// <summary>
2063
- /// Bind the token to this installation. VerifyToken proves the store signed
2064
- /// it and that it has not expired; it does not prove the token was issued
2065
- /// for this machine or this product, so a token copied from another install
2066
- /// passes it. claims.fp is a server-side HMAC and cannot be recomputed
2067
- /// here, so claims.ins (the install id sent as site_url) is the binding a
2068
- /// client is able to check.
2069
- /// </summary>
2070
- public static bool Entitlement(
2071
- string token,
2072
- string publicKeyPem,
2073
- string installId,
2074
- int productId,
2075
- out JsonElement claims,
2076
- out string reason)
2077
- {
2078
- reason = "";
2079
-
2080
- if (!VerifyToken(token, publicKeyPem, out claims))
2081
- {
2082
- reason = "invalid_or_expired";
2083
- return false;
2084
- }
2085
-
2086
- if (productId > 0)
2087
- {
2088
- if (!claims.TryGetProperty("prod", out var prod)
2089
- || prod.ValueKind != JsonValueKind.Number
2090
- || prod.GetInt32() != productId)
2091
- {
2092
- reason = "wrong_product";
2093
- return false;
2094
- }
2095
- }
2096
-
2097
- if (!string.IsNullOrEmpty(installId)
2098
- && claims.TryGetProperty("ins", out var ins)
2099
- && ins.GetString() != installId)
2100
- {
2101
- reason = "wrong_install";
2102
- return false;
2103
- }
2104
-
2105
- return true;
2106
- }
2107
-
2108
- private static byte[] Base64UrlDecode(string value)
2109
- {
2110
- var padded = value.Replace('-', '+').Replace('_', '/');
2111
- padded += new string('=', (4 - padded.Length % 4) % 4);
2112
- return Convert.FromBase64String(padded);
2113
- }
2114
- }
2061
+ text: `${header('.NET (WPF / MAUI / console)', 'License.cs')}
2062
+ using System;
2063
+ using System.Collections.Generic;
2064
+ using System.Net.Http;
2065
+ using System.Security.Cryptography;
2066
+ using System.Text;
2067
+ using System.Text.Json;
2068
+ using System.Threading.Tasks;
2069
+
2070
+ public sealed class LicenseState
2071
+ {
2072
+ public string Status { get; set; } = "";
2073
+ public string? Token { get; set; }
2074
+ public List<int> Entitlements { get; set; } = new();
2075
+ public string? ErrorType { get; set; }
2076
+ }
2077
+
2078
+ public static class FastrLicense
2079
+ {
2080
+ private const string Store = "${base}";
2081
+ private const int ProductId = ${productId};
2082
+ private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(10) };
2083
+
2084
+ private static async Task<JsonElement> CallAsync(string verb, Dictionary<string, string> body)
2085
+ {
2086
+ var res = await Http.PostAsync(Store + "?fluent-cart=" + verb, new FormUrlEncodedContent(body));
2087
+ var text = await res.Content.ReadAsStringAsync();
2088
+ using var doc = JsonDocument.Parse(text);
2089
+ return doc.RootElement.Clone();
2090
+ }
2091
+
2092
+ public static async Task<LicenseState> ActivateAsync(string licenseKey, string instanceId, string fingerprint, string email)
2093
+ {
2094
+ var json = await CallAsync("activate_license", new Dictionary<string, string>
2095
+ {
2096
+ ["item_id"] = ProductId.ToString(),
2097
+ ["license_key"] = licenseKey,
2098
+ ["site_url"] = instanceId,
2099
+ ["device_fingerprint"] = fingerprint,
2100
+ ["device_name"] = Environment.MachineName,
2101
+ ["device_type"] = "Desktop (.NET)",
2102
+ ["os"] = Environment.OSVersion.ToString(),
2103
+ ["email"] = email,
2104
+ ["server_version"] = "1.0.0"
2105
+ });
2106
+
2107
+ // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2108
+ var state = new LicenseState
2109
+ {
2110
+ Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
2111
+ Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
2112
+ ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
2113
+ };
2114
+
2115
+ if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2116
+ {
2117
+ foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2118
+ }
2119
+
2120
+ return state;
2121
+ }
2122
+
2123
+ public static async Task<LicenseState> CheckAsync(string licenseKey, string instanceId, string fingerprint)
2124
+ {
2125
+ var json = await CallAsync("check_license", new Dictionary<string, string>
2126
+ {
2127
+ ["item_id"] = ProductId.ToString(),
2128
+ ["license_key"] = licenseKey,
2129
+ ["site_url"] = instanceId,
2130
+ ["device_fingerprint"] = fingerprint
2131
+ });
2132
+
2133
+ var state = new LicenseState
2134
+ {
2135
+ Status = json.TryGetProperty("status", out var s) ? s.GetString() ?? "" : "",
2136
+ Token = json.TryGetProperty("license_token", out var t) ? t.GetString() : null,
2137
+ ErrorType = json.TryGetProperty("error_type", out var e) ? e.GetString() : null
2138
+ };
2139
+
2140
+ if (json.TryGetProperty("entitlements", out var ent) && ent.ValueKind == JsonValueKind.Array)
2141
+ {
2142
+ foreach (var id in ent.EnumerateArray()) state.Entitlements.Add(id.GetInt32());
2143
+ }
2144
+
2145
+ return state;
2146
+ }
2147
+
2148
+ public static async Task DeactivateAsync(string licenseKey, string instanceId)
2149
+ {
2150
+ await CallAsync("deactivate_license", new Dictionary<string, string>
2151
+ {
2152
+ ["item_id"] = ProductId.ToString(),
2153
+ ["license_key"] = licenseKey,
2154
+ ["site_url"] = instanceId
2155
+ });
2156
+ }
2157
+
2158
+ public static async Task<JsonElement> LatestReleaseAsync(string licenseKey, string currentVersion, string platform = "any")
2159
+ {
2160
+ var url = Store + "?fluent-cart=fastr_release_latest&product_id=" + ProductId
2161
+ + "&platform=" + Uri.EscapeDataString(platform)
2162
+ + "&current_version=" + Uri.EscapeDataString(currentVersion)
2163
+ + "&license_key=" + Uri.EscapeDataString(licenseKey);
2164
+
2165
+ var text = await Http.GetStringAsync(url);
2166
+ using var doc = JsonDocument.Parse(text);
2167
+ return doc.RootElement.Clone();
2168
+ }
2169
+
2170
+ public static Task<JsonElement> ReportUsageAsync(string licenseKey, string metric, int quantity, string idempotencyKey)
2171
+ {
2172
+ return CallAsync("fastr_usage_report", new Dictionary<string, string>
2173
+ {
2174
+ ["license_key"] = licenseKey,
2175
+ ["metric"] = metric,
2176
+ ["quantity"] = quantity.ToString(),
2177
+ ["idempotency_key"] = idempotencyKey
2178
+ });
2179
+ }
2180
+
2181
+ // After verifying, compare claims ins/fp with this install and prod/ent
2182
+ // with the product you are running.
2183
+ public static bool VerifyToken(string token, string publicKeyPem, out JsonElement claims)
2184
+ {
2185
+ claims = default;
2186
+ var parts = token.Split('.');
2187
+ if (parts.Length != 3) return false;
2188
+
2189
+ using var rsa = RSA.Create();
2190
+ rsa.ImportFromPem(publicKeyPem);
2191
+
2192
+ var data = Encoding.ASCII.GetBytes(parts[0] + "." + parts[1]);
2193
+ var signature = Base64UrlDecode(parts[2]);
2194
+
2195
+ if (!rsa.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) return false;
2196
+
2197
+ using var doc = JsonDocument.Parse(Base64UrlDecode(parts[1]));
2198
+ claims = doc.RootElement.Clone();
2199
+ return true;
2200
+ }
2201
+
2202
+ /// <summary>
2203
+ /// Bind the token to this installation. VerifyToken proves the store signed
2204
+ /// it and that it has not expired; it does not prove the token was issued
2205
+ /// for this machine or this product, so a token copied from another install
2206
+ /// passes it. claims.fp is a server-side HMAC and cannot be recomputed
2207
+ /// here, so claims.ins (the install id sent as site_url) is the binding a
2208
+ /// client is able to check.
2209
+ /// </summary>
2210
+ public static bool Entitlement(
2211
+ string token,
2212
+ string publicKeyPem,
2213
+ string installId,
2214
+ int productId,
2215
+ out JsonElement claims,
2216
+ out string reason)
2217
+ {
2218
+ reason = "";
2219
+
2220
+ if (!VerifyToken(token, publicKeyPem, out claims))
2221
+ {
2222
+ reason = "invalid_or_expired";
2223
+ return false;
2224
+ }
2225
+
2226
+ if (productId > 0)
2227
+ {
2228
+ if (!claims.TryGetProperty("prod", out var prod)
2229
+ || prod.ValueKind != JsonValueKind.Number
2230
+ || prod.GetInt32() != productId)
2231
+ {
2232
+ reason = "wrong_product";
2233
+ return false;
2234
+ }
2235
+ }
2236
+
2237
+ if (!string.IsNullOrEmpty(installId)
2238
+ && claims.TryGetProperty("ins", out var ins)
2239
+ && ins.GetString() != installId)
2240
+ {
2241
+ reason = "wrong_install";
2242
+ return false;
2243
+ }
2244
+
2245
+ return true;
2246
+ }
2247
+
2248
+ private static byte[] Base64UrlDecode(string value)
2249
+ {
2250
+ var padded = value.Replace('-', '+').Replace('_', '/');
2251
+ padded += new string('=', (4 - padded.Length % 4) % 4);
2252
+ return Convert.FromBase64String(padded);
2253
+ }
2254
+ }
2115
2255
  `
2116
2256
  }
2117
2257
  ]
@@ -2122,257 +2262,257 @@ public static class FastrLicense
2122
2262
  content: [
2123
2263
  {
2124
2264
  type: 'text',
2125
- text: `${header('Go (CLI / service)', 'license/license.go')}
2126
- package license
2127
-
2128
- import (
2129
- "crypto"
2130
- "crypto/rsa"
2131
- "crypto/sha256"
2132
- "crypto/x509"
2133
- "encoding/base64"
2134
- "encoding/json"
2135
- "encoding/pem"
2136
- "errors"
2137
- "io"
2138
- "strconv"
2139
- "net/http"
2140
- "net/url"
2141
- "os"
2142
- "runtime"
2143
- "strings"
2144
- "time"
2145
- )
2146
-
2147
- const (
2148
- Store = "${base}"
2149
- ProductID = "${productId}"
2150
- )
2151
-
2152
- type State struct {
2153
- Status string
2154
- Token string
2155
- Entitlements []int
2156
- ErrorType string
2157
- }
2158
-
2159
- func call(verb string, body url.Values) (map[string]any, error) {
2160
- res, err := http.PostForm(Store+"?fluent-cart="+verb, body)
2161
- if err != nil {
2162
- return nil, err
2163
- }
2164
- defer res.Body.Close()
2165
-
2166
- raw, err := io.ReadAll(res.Body)
2167
- if err != nil {
2168
- return nil, err
2169
- }
2170
-
2171
- var out map[string]any
2172
- if err := json.Unmarshal(raw, &out); err != nil {
2173
- return nil, err
2174
- }
2175
- return out, nil
2176
- }
2177
-
2178
- func Activate(key, instanceID, fingerprint, email string) (State, error) {
2179
- host, _ := os.Hostname()
2180
-
2181
- out, err := call("activate_license", url.Values{
2182
- "item_id": {ProductID},
2183
- "license_key": {key},
2184
- "site_url": {instanceID},
2185
- "device_fingerprint": {fingerprint},
2186
- "device_name": {host},
2187
- "device_type": {"CLI (Go)"},
2188
- "os": {runtime.GOOS + " " + runtime.GOARCH},
2189
- "email": {email},
2190
- "server_version": {"1.0.0"},
2191
- })
2192
- if err != nil {
2193
- return State{}, err
2194
- }
2195
-
2196
- // key_mismatch and invalid_activation come back as HTTP 200 success=true.
2197
- state := State{
2198
- Status: asString(out["status"]),
2199
- Token: asString(out["license_token"]),
2200
- ErrorType: asString(out["error_type"]),
2201
- }
2202
-
2203
- if list, ok := out["entitlements"].([]any); ok {
2204
- for _, v := range list {
2205
- if f, ok := v.(float64); ok {
2206
- state.Entitlements = append(state.Entitlements, int(f))
2207
- }
2208
- }
2209
- }
2210
-
2211
- return state, nil
2212
- }
2213
-
2214
- func Check(key, instanceID, fingerprint string) (State, error) {
2215
- out, err := call("check_license", url.Values{
2216
- "item_id": {ProductID},
2217
- "license_key": {key},
2218
- "site_url": {instanceID},
2219
- "device_fingerprint": {fingerprint},
2220
- })
2221
- if err != nil {
2222
- return State{}, err
2223
- }
2224
-
2225
- state := State{
2226
- Status: asString(out["status"]),
2227
- Token: asString(out["license_token"]),
2228
- ErrorType: asString(out["error_type"]),
2229
- }
2230
-
2231
- if list, ok := out["entitlements"].([]any); ok {
2232
- for _, v := range list {
2233
- if f, ok := v.(float64); ok {
2234
- state.Entitlements = append(state.Entitlements, int(f))
2235
- }
2236
- }
2237
- }
2238
-
2239
- return state, nil
2240
- }
2241
-
2242
- func Deactivate(key, instanceID string) error {
2243
- _, err := call("deactivate_license", url.Values{
2244
- "item_id": {ProductID},
2245
- "license_key": {key},
2246
- "site_url": {instanceID},
2247
- })
2248
- return err
2249
- }
2250
-
2251
- func LatestRelease(key, currentVersion, platform string) (map[string]any, error) {
2252
- query := url.Values{
2253
- "product_id": {ProductID},
2254
- "platform": {platform},
2255
- "current_version": {currentVersion},
2256
- "license_key": {key},
2257
- }
2258
-
2259
- res, err := http.Get(Store + "?fluent-cart=fastr_release_latest&" + query.Encode())
2260
- if err != nil {
2261
- return nil, err
2262
- }
2263
- defer res.Body.Close()
2264
-
2265
- raw, err := io.ReadAll(res.Body)
2266
- if err != nil {
2267
- return nil, err
2268
- }
2269
-
2270
- var out map[string]any
2271
- if err := json.Unmarshal(raw, &out); err != nil {
2272
- return nil, err
2273
- }
2274
-
2275
- return out, nil
2276
- }
2277
-
2278
- func ReportUsage(key, metric string, quantity int, idempotencyKey string) (map[string]any, error) {
2279
- return call("fastr_usage_report", url.Values{
2280
- "license_key": {key},
2281
- "metric": {metric},
2282
- "quantity": {strconv.Itoa(quantity)},
2283
- "idempotency_key": {idempotencyKey},
2284
- })
2285
- }
2286
-
2287
- // After verifying, compare claims["ins"] and claims["fp"] with this install
2288
- // and claims["prod"] / claims["ent"] with the product you are running.
2289
- // VerifyToken checks an RS256 licence token against the store's public key.// VerifyToken checks an RS256 licence token against the store's public key.
2290
- func VerifyToken(token, publicKeyPEM string) (map[string]any, error) {
2291
- parts := strings.Split(token, ".")
2292
- if len(parts) != 3 {
2293
- return nil, errors.New("malformed token")
2294
- }
2295
-
2296
- block, _ := pem.Decode([]byte(publicKeyPEM))
2297
- if block == nil {
2298
- return nil, errors.New("bad public key")
2299
- }
2300
-
2301
- pub, err := x509.ParsePKIXPublicKey(block.Bytes)
2302
- if err != nil {
2303
- return nil, err
2304
- }
2305
-
2306
- rsaPub, ok := pub.(*rsa.PublicKey)
2307
- if !ok {
2308
- return nil, errors.New("not an RSA key")
2309
- }
2310
-
2311
- sig, err := base64.RawURLEncoding.DecodeString(parts[2])
2312
- if err != nil {
2313
- return nil, err
2314
- }
2315
-
2316
- digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
2317
- if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
2318
- return nil, err
2319
- }
2320
-
2321
- payload, err := base64.RawURLEncoding.DecodeString(parts[1])
2322
- if err != nil {
2323
- return nil, err
2324
- }
2325
-
2326
- var claims map[string]any
2327
- if err := json.Unmarshal(payload, &claims); err != nil {
2328
- return nil, err
2329
- }
2330
-
2331
- if exp, ok := claims["exp"].(float64); ok && int64(exp) < time.Now().Unix() {
2332
- return nil, errors.New("token expired")
2333
- }
2334
-
2335
- return claims, nil
2336
- }
2337
-
2338
- // Entitlement binds the token to THIS installation.
2339
- //
2340
- // VerifyToken proves the store signed the token and that it has not expired.
2341
- // It does not prove the token was issued for this machine or this product, so
2342
- // a token copied from another install passes it. Compare the claims before
2343
- // granting anything.
2344
- //
2345
- // claims["fp"] is a server-side HMAC of the device fingerprint and cannot be
2346
- // recomputed here, so claims["ins"] - the install id sent as site_url - is the
2347
- // binding a client is able to check.
2348
- func Entitlement(token, publicKeyPEM, installID string, productID int) (map[string]any, string) {
2349
- claims, err := VerifyToken(token, publicKeyPEM)
2350
- if err != nil {
2351
- return nil, "invalid_or_expired"
2352
- }
2353
-
2354
- if productID > 0 {
2355
- prod, ok := claims["prod"].(float64)
2356
- if !ok || int(prod) != productID {
2357
- return nil, "wrong_product"
2358
- }
2359
- }
2360
-
2361
- if installID != "" {
2362
- if ins, ok := claims["ins"].(string); ok && ins != installID {
2363
- return nil, "wrong_install"
2364
- }
2365
- }
2366
-
2367
- return claims, ""
2368
- }
2369
-
2370
- func asString(v any) string {
2371
- if s, ok := v.(string); ok {
2372
- return s
2373
- }
2374
- return ""
2375
- }
2265
+ text: `${header('Go (CLI / service)', 'license/license.go')}
2266
+ package license
2267
+
2268
+ import (
2269
+ "crypto"
2270
+ "crypto/rsa"
2271
+ "crypto/sha256"
2272
+ "crypto/x509"
2273
+ "encoding/base64"
2274
+ "encoding/json"
2275
+ "encoding/pem"
2276
+ "errors"
2277
+ "io"
2278
+ "strconv"
2279
+ "net/http"
2280
+ "net/url"
2281
+ "os"
2282
+ "runtime"
2283
+ "strings"
2284
+ "time"
2285
+ )
2286
+
2287
+ const (
2288
+ Store = "${base}"
2289
+ ProductID = "${productId}"
2290
+ )
2291
+
2292
+ type State struct {
2293
+ Status string
2294
+ Token string
2295
+ Entitlements []int
2296
+ ErrorType string
2297
+ }
2298
+
2299
+ func call(verb string, body url.Values) (map[string]any, error) {
2300
+ res, err := http.PostForm(Store+"?fluent-cart="+verb, body)
2301
+ if err != nil {
2302
+ return nil, err
2303
+ }
2304
+ defer res.Body.Close()
2305
+
2306
+ raw, err := io.ReadAll(res.Body)
2307
+ if err != nil {
2308
+ return nil, err
2309
+ }
2310
+
2311
+ var out map[string]any
2312
+ if err := json.Unmarshal(raw, &out); err != nil {
2313
+ return nil, err
2314
+ }
2315
+ return out, nil
2316
+ }
2317
+
2318
+ func Activate(key, instanceID, fingerprint, email string) (State, error) {
2319
+ host, _ := os.Hostname()
2320
+
2321
+ out, err := call("activate_license", url.Values{
2322
+ "item_id": {ProductID},
2323
+ "license_key": {key},
2324
+ "site_url": {instanceID},
2325
+ "device_fingerprint": {fingerprint},
2326
+ "device_name": {host},
2327
+ "device_type": {"CLI (Go)"},
2328
+ "os": {runtime.GOOS + " " + runtime.GOARCH},
2329
+ "email": {email},
2330
+ "server_version": {"1.0.0"},
2331
+ })
2332
+ if err != nil {
2333
+ return State{}, err
2334
+ }
2335
+
2336
+ // key_mismatch and invalid_activation come back as HTTP 200 success=true.
2337
+ state := State{
2338
+ Status: asString(out["status"]),
2339
+ Token: asString(out["license_token"]),
2340
+ ErrorType: asString(out["error_type"]),
2341
+ }
2342
+
2343
+ if list, ok := out["entitlements"].([]any); ok {
2344
+ for _, v := range list {
2345
+ if f, ok := v.(float64); ok {
2346
+ state.Entitlements = append(state.Entitlements, int(f))
2347
+ }
2348
+ }
2349
+ }
2350
+
2351
+ return state, nil
2352
+ }
2353
+
2354
+ func Check(key, instanceID, fingerprint string) (State, error) {
2355
+ out, err := call("check_license", url.Values{
2356
+ "item_id": {ProductID},
2357
+ "license_key": {key},
2358
+ "site_url": {instanceID},
2359
+ "device_fingerprint": {fingerprint},
2360
+ })
2361
+ if err != nil {
2362
+ return State{}, err
2363
+ }
2364
+
2365
+ state := State{
2366
+ Status: asString(out["status"]),
2367
+ Token: asString(out["license_token"]),
2368
+ ErrorType: asString(out["error_type"]),
2369
+ }
2370
+
2371
+ if list, ok := out["entitlements"].([]any); ok {
2372
+ for _, v := range list {
2373
+ if f, ok := v.(float64); ok {
2374
+ state.Entitlements = append(state.Entitlements, int(f))
2375
+ }
2376
+ }
2377
+ }
2378
+
2379
+ return state, nil
2380
+ }
2381
+
2382
+ func Deactivate(key, instanceID string) error {
2383
+ _, err := call("deactivate_license", url.Values{
2384
+ "item_id": {ProductID},
2385
+ "license_key": {key},
2386
+ "site_url": {instanceID},
2387
+ })
2388
+ return err
2389
+ }
2390
+
2391
+ func LatestRelease(key, currentVersion, platform string) (map[string]any, error) {
2392
+ query := url.Values{
2393
+ "product_id": {ProductID},
2394
+ "platform": {platform},
2395
+ "current_version": {currentVersion},
2396
+ "license_key": {key},
2397
+ }
2398
+
2399
+ res, err := http.Get(Store + "?fluent-cart=fastr_release_latest&" + query.Encode())
2400
+ if err != nil {
2401
+ return nil, err
2402
+ }
2403
+ defer res.Body.Close()
2404
+
2405
+ raw, err := io.ReadAll(res.Body)
2406
+ if err != nil {
2407
+ return nil, err
2408
+ }
2409
+
2410
+ var out map[string]any
2411
+ if err := json.Unmarshal(raw, &out); err != nil {
2412
+ return nil, err
2413
+ }
2414
+
2415
+ return out, nil
2416
+ }
2417
+
2418
+ func ReportUsage(key, metric string, quantity int, idempotencyKey string) (map[string]any, error) {
2419
+ return call("fastr_usage_report", url.Values{
2420
+ "license_key": {key},
2421
+ "metric": {metric},
2422
+ "quantity": {strconv.Itoa(quantity)},
2423
+ "idempotency_key": {idempotencyKey},
2424
+ })
2425
+ }
2426
+
2427
+ // After verifying, compare claims["ins"] and claims["fp"] with this install
2428
+ // and claims["prod"] / claims["ent"] with the product you are running.
2429
+ // VerifyToken checks an RS256 licence token against the store's public key.// VerifyToken checks an RS256 licence token against the store's public key.
2430
+ func VerifyToken(token, publicKeyPEM string) (map[string]any, error) {
2431
+ parts := strings.Split(token, ".")
2432
+ if len(parts) != 3 {
2433
+ return nil, errors.New("malformed token")
2434
+ }
2435
+
2436
+ block, _ := pem.Decode([]byte(publicKeyPEM))
2437
+ if block == nil {
2438
+ return nil, errors.New("bad public key")
2439
+ }
2440
+
2441
+ pub, err := x509.ParsePKIXPublicKey(block.Bytes)
2442
+ if err != nil {
2443
+ return nil, err
2444
+ }
2445
+
2446
+ rsaPub, ok := pub.(*rsa.PublicKey)
2447
+ if !ok {
2448
+ return nil, errors.New("not an RSA key")
2449
+ }
2450
+
2451
+ sig, err := base64.RawURLEncoding.DecodeString(parts[2])
2452
+ if err != nil {
2453
+ return nil, err
2454
+ }
2455
+
2456
+ digest := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
2457
+ if err := rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, digest[:], sig); err != nil {
2458
+ return nil, err
2459
+ }
2460
+
2461
+ payload, err := base64.RawURLEncoding.DecodeString(parts[1])
2462
+ if err != nil {
2463
+ return nil, err
2464
+ }
2465
+
2466
+ var claims map[string]any
2467
+ if err := json.Unmarshal(payload, &claims); err != nil {
2468
+ return nil, err
2469
+ }
2470
+
2471
+ if exp, ok := claims["exp"].(float64); ok && int64(exp) < time.Now().Unix() {
2472
+ return nil, errors.New("token expired")
2473
+ }
2474
+
2475
+ return claims, nil
2476
+ }
2477
+
2478
+ // Entitlement binds the token to THIS installation.
2479
+ //
2480
+ // VerifyToken proves the store signed the token and that it has not expired.
2481
+ // It does not prove the token was issued for this machine or this product, so
2482
+ // a token copied from another install passes it. Compare the claims before
2483
+ // granting anything.
2484
+ //
2485
+ // claims["fp"] is a server-side HMAC of the device fingerprint and cannot be
2486
+ // recomputed here, so claims["ins"] - the install id sent as site_url - is the
2487
+ // binding a client is able to check.
2488
+ func Entitlement(token, publicKeyPEM, installID string, productID int) (map[string]any, string) {
2489
+ claims, err := VerifyToken(token, publicKeyPEM)
2490
+ if err != nil {
2491
+ return nil, "invalid_or_expired"
2492
+ }
2493
+
2494
+ if productID > 0 {
2495
+ prod, ok := claims["prod"].(float64)
2496
+ if !ok || int(prod) != productID {
2497
+ return nil, "wrong_product"
2498
+ }
2499
+ }
2500
+
2501
+ if installID != "" {
2502
+ if ins, ok := claims["ins"].(string); ok && ins != installID {
2503
+ return nil, "wrong_install"
2504
+ }
2505
+ }
2506
+
2507
+ return claims, ""
2508
+ }
2509
+
2510
+ func asString(v any) string {
2511
+ if s, ok := v.(string); ok {
2512
+ return s
2513
+ }
2514
+ return ""
2515
+ }
2376
2516
  `
2377
2517
  }
2378
2518
  ]
@@ -2382,170 +2522,170 @@ func asString(v any) string {
2382
2522
  content: [
2383
2523
  {
2384
2524
  type: 'text',
2385
- text: `${header('Kotlin / JVM', 'LicenseClient.kt')}
2386
- import java.net.HttpURLConnection
2387
- import java.net.URL
2388
- import java.security.KeyFactory
2389
- import java.security.Signature
2390
- import java.security.spec.X509EncodedKeySpec
2391
- import java.util.Base64
2392
- import org.json.JSONObject
2393
-
2394
- const val STORE = "${base}"
2395
- const val PRODUCT_ID = ${productId}
2396
-
2397
- data class LicenseState(
2398
- val status: String,
2399
- val token: String?,
2400
- val entitlements: List<Int>,
2401
- val errorType: String?
2402
- )
2403
-
2404
- fun call(verb: String, body: Map<String, String>): JSONObject {
2405
- val url = URL(STORE + "?fluent-cart=" + verb)
2406
- val conn = url.openConnection() as HttpURLConnection
2407
- conn.requestMethod = "POST"
2408
- conn.doOutput = true
2409
- conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
2410
- val form = body.entries.joinToString("&") { e ->
2411
- java.net.URLEncoder.encode(e.key, "UTF-8") + "=" + java.net.URLEncoder.encode(e.value, "UTF-8")
2412
- }
2413
- conn.outputStream.use { it.write(form.toByteArray()) }
2414
- return JSONObject(conn.inputStream.bufferedReader().readText())
2415
- }
2416
-
2417
- fun activate(key: String, instanceId: String, fingerprint: String, email: String): LicenseState {
2418
- val json = call("activate_license", mapOf(
2419
- "item_id" to PRODUCT_ID.toString(),
2420
- "license_key" to key,
2421
- "site_url" to instanceId,
2422
- "device_fingerprint" to fingerprint,
2423
- "device_name" to (System.getenv("COMPUTERNAME") ?: "desktop"),
2424
- "device_type" to "Desktop (JVM)",
2425
- "os" to System.getProperty("os.name") + " " + System.getProperty("os.arch"),
2426
- "email" to email,
2427
- "server_version" to "1.0.0"
2428
- ))
2429
-
2430
- // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2431
- val ents = mutableListOf<Int>()
2432
- json.optJSONArray("entitlements")?.let { arr ->
2433
- for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2434
- }
2435
-
2436
- return LicenseState(
2437
- status = json.optString("status"),
2438
- token = json.optString("license_token").ifEmpty { null },
2439
- entitlements = ents,
2440
- errorType = json.optString("error_type").ifEmpty { null }
2441
- )
2442
- }
2443
-
2444
- fun check(key: String, instanceId: String, fingerprint: String): LicenseState {
2445
- val json = call("check_license", mapOf(
2446
- "item_id" to PRODUCT_ID.toString(),
2447
- "license_key" to key,
2448
- "site_url" to instanceId,
2449
- "device_fingerprint" to fingerprint
2450
- ))
2451
-
2452
- val ents = mutableListOf<Int>()
2453
- json.optJSONArray("entitlements")?.let { arr ->
2454
- for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2455
- }
2456
-
2457
- return LicenseState(
2458
- status = json.optString("status"),
2459
- token = json.optString("license_token").ifEmpty { null },
2460
- entitlements = ents,
2461
- errorType = json.optString("error_type").ifEmpty { null }
2462
- )
2463
- }
2464
-
2465
- fun deactivate(key: String, instanceId: String) {
2466
- call("deactivate_license", mapOf(
2467
- "item_id" to PRODUCT_ID.toString(),
2468
- "license_key" to key,
2469
- "site_url" to instanceId
2470
- ))
2471
- }
2472
-
2473
- fun latestRelease(key: String, currentVersion: String, platform: String = "any"): JSONObject {
2474
- val query = "product_id=" + PRODUCT_ID +
2475
- "&platform=" + java.net.URLEncoder.encode(platform, "UTF-8") +
2476
- "&current_version=" + java.net.URLEncoder.encode(currentVersion, "UTF-8") +
2477
- "&license_key=" + java.net.URLEncoder.encode(key, "UTF-8")
2478
-
2479
- val connection = java.net.URL(STORE + "?fluent-cart=fastr_release_latest&" + query)
2480
- .openConnection() as java.net.HttpURLConnection
2481
-
2482
- return JSONObject(connection.inputStream.bufferedReader().readText())
2483
- }
2484
-
2485
- fun reportUsage(key: String, metric: String, quantity: Int, idempotencyKey: String): JSONObject {
2486
- return call("fastr_usage_report", mapOf(
2487
- "license_key" to key,
2488
- "metric" to metric,
2489
- "quantity" to quantity.toString(),
2490
- "idempotency_key" to idempotencyKey
2491
- ))
2492
- }
2493
-
2494
- // After verifying, compare claims.ins / claims.fp with this install and
2495
- // claims.prod / claims.ent with the product you are running.
2496
- fun verifyToken(token: String, publicKeyPem: String): JSONObject? {
2497
- val parts = token.split(".")
2498
- if (parts.size != 3) return null
2499
-
2500
- val pem = publicKeyPem
2501
- .replace("-----BEGIN PUBLIC KEY-----", "")
2502
- .replace("-----END PUBLIC KEY-----", "")
2503
- .replace("\\\\s".toRegex(), "")
2504
-
2505
- val keySpec = X509EncodedKeySpec(Base64.getDecoder().decode(pem))
2506
- val publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec)
2507
-
2508
- val verifier = Signature.getInstance("SHA256withRSA")
2509
- verifier.initVerify(publicKey)
2510
- verifier.update((parts[0] + "." + parts[1]).toByteArray())
2511
-
2512
- val signature = Base64.getUrlDecoder().decode(parts[2])
2513
- if (!verifier.verify(signature)) return null
2514
-
2515
- val payload = String(Base64.getUrlDecoder().decode(parts[1]))
2516
- return JSONObject(payload)
2517
- }
2518
-
2519
- // Entitlement binds the token to THIS installation.
2520
- //
2521
- // verifyToken only proves the store signed it: it does not check expiry, this
2522
- // machine, or this product. Compare the claims before granting anything.
2523
- // claims.fp is a server-side HMAC and cannot be recomputed here, so claims.ins
2524
- // - the install id sent as site_url - is the binding a client can check.
2525
- // Returns the claims and a null reason on success, or null and a reason.
2526
- fun entitlement(
2527
- token: String,
2528
- publicKeyPem: String,
2529
- installId: String?,
2530
- productId: Int
2531
- ): Pair<JSONObject?, String?> {
2532
- val claims = verifyToken(token, publicKeyPem) ?: return Pair(null, "invalid_or_expired")
2533
-
2534
- val exp = if (claims.has("exp")) claims.optLong("exp", 0L) else 0L
2535
- if (exp > 0L && exp <= System.currentTimeMillis() / 1000L) {
2536
- return Pair(null, "invalid_or_expired")
2537
- }
2538
-
2539
- if (productId > 0 && claims.optInt("prod", -1) != productId) {
2540
- return Pair(null, "wrong_product")
2541
- }
2542
-
2543
- if (!installId.isNullOrEmpty() && claims.has("ins") && claims.optString("ins", "") != installId) {
2544
- return Pair(null, "wrong_install")
2545
- }
2546
-
2547
- return Pair(claims, null)
2548
- }
2525
+ text: `${header('Kotlin / JVM', 'LicenseClient.kt')}
2526
+ import java.net.HttpURLConnection
2527
+ import java.net.URL
2528
+ import java.security.KeyFactory
2529
+ import java.security.Signature
2530
+ import java.security.spec.X509EncodedKeySpec
2531
+ import java.util.Base64
2532
+ import org.json.JSONObject
2533
+
2534
+ const val STORE = "${base}"
2535
+ const val PRODUCT_ID = ${productId}
2536
+
2537
+ data class LicenseState(
2538
+ val status: String,
2539
+ val token: String?,
2540
+ val entitlements: List<Int>,
2541
+ val errorType: String?
2542
+ )
2543
+
2544
+ fun call(verb: String, body: Map<String, String>): JSONObject {
2545
+ val url = URL(STORE + "?fluent-cart=" + verb)
2546
+ val conn = url.openConnection() as HttpURLConnection
2547
+ conn.requestMethod = "POST"
2548
+ conn.doOutput = true
2549
+ conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
2550
+ val form = body.entries.joinToString("&") { e ->
2551
+ java.net.URLEncoder.encode(e.key, "UTF-8") + "=" + java.net.URLEncoder.encode(e.value, "UTF-8")
2552
+ }
2553
+ conn.outputStream.use { it.write(form.toByteArray()) }
2554
+ return JSONObject(conn.inputStream.bufferedReader().readText())
2555
+ }
2556
+
2557
+ fun activate(key: String, instanceId: String, fingerprint: String, email: String): LicenseState {
2558
+ val json = call("activate_license", mapOf(
2559
+ "item_id" to PRODUCT_ID.toString(),
2560
+ "license_key" to key,
2561
+ "site_url" to instanceId,
2562
+ "device_fingerprint" to fingerprint,
2563
+ "device_name" to (System.getenv("COMPUTERNAME") ?: "desktop"),
2564
+ "device_type" to "Desktop (JVM)",
2565
+ "os" to System.getProperty("os.name") + " " + System.getProperty("os.arch"),
2566
+ "email" to email,
2567
+ "server_version" to "1.0.0"
2568
+ ))
2569
+
2570
+ // key_mismatch and invalid_activation arrive as HTTP 200 with success=true.
2571
+ val ents = mutableListOf<Int>()
2572
+ json.optJSONArray("entitlements")?.let { arr ->
2573
+ for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2574
+ }
2575
+
2576
+ return LicenseState(
2577
+ status = json.optString("status"),
2578
+ token = json.optString("license_token").ifEmpty { null },
2579
+ entitlements = ents,
2580
+ errorType = json.optString("error_type").ifEmpty { null }
2581
+ )
2582
+ }
2583
+
2584
+ fun check(key: String, instanceId: String, fingerprint: String): LicenseState {
2585
+ val json = call("check_license", mapOf(
2586
+ "item_id" to PRODUCT_ID.toString(),
2587
+ "license_key" to key,
2588
+ "site_url" to instanceId,
2589
+ "device_fingerprint" to fingerprint
2590
+ ))
2591
+
2592
+ val ents = mutableListOf<Int>()
2593
+ json.optJSONArray("entitlements")?.let { arr ->
2594
+ for (i in 0 until arr.length()) ents.add(arr.getInt(i))
2595
+ }
2596
+
2597
+ return LicenseState(
2598
+ status = json.optString("status"),
2599
+ token = json.optString("license_token").ifEmpty { null },
2600
+ entitlements = ents,
2601
+ errorType = json.optString("error_type").ifEmpty { null }
2602
+ )
2603
+ }
2604
+
2605
+ fun deactivate(key: String, instanceId: String) {
2606
+ call("deactivate_license", mapOf(
2607
+ "item_id" to PRODUCT_ID.toString(),
2608
+ "license_key" to key,
2609
+ "site_url" to instanceId
2610
+ ))
2611
+ }
2612
+
2613
+ fun latestRelease(key: String, currentVersion: String, platform: String = "any"): JSONObject {
2614
+ val query = "product_id=" + PRODUCT_ID +
2615
+ "&platform=" + java.net.URLEncoder.encode(platform, "UTF-8") +
2616
+ "&current_version=" + java.net.URLEncoder.encode(currentVersion, "UTF-8") +
2617
+ "&license_key=" + java.net.URLEncoder.encode(key, "UTF-8")
2618
+
2619
+ val connection = java.net.URL(STORE + "?fluent-cart=fastr_release_latest&" + query)
2620
+ .openConnection() as java.net.HttpURLConnection
2621
+
2622
+ return JSONObject(connection.inputStream.bufferedReader().readText())
2623
+ }
2624
+
2625
+ fun reportUsage(key: String, metric: String, quantity: Int, idempotencyKey: String): JSONObject {
2626
+ return call("fastr_usage_report", mapOf(
2627
+ "license_key" to key,
2628
+ "metric" to metric,
2629
+ "quantity" to quantity.toString(),
2630
+ "idempotency_key" to idempotencyKey
2631
+ ))
2632
+ }
2633
+
2634
+ // After verifying, compare claims.ins / claims.fp with this install and
2635
+ // claims.prod / claims.ent with the product you are running.
2636
+ fun verifyToken(token: String, publicKeyPem: String): JSONObject? {
2637
+ val parts = token.split(".")
2638
+ if (parts.size != 3) return null
2639
+
2640
+ val pem = publicKeyPem
2641
+ .replace("-----BEGIN PUBLIC KEY-----", "")
2642
+ .replace("-----END PUBLIC KEY-----", "")
2643
+ .replace("\\\\s".toRegex(), "")
2644
+
2645
+ val keySpec = X509EncodedKeySpec(Base64.getDecoder().decode(pem))
2646
+ val publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec)
2647
+
2648
+ val verifier = Signature.getInstance("SHA256withRSA")
2649
+ verifier.initVerify(publicKey)
2650
+ verifier.update((parts[0] + "." + parts[1]).toByteArray())
2651
+
2652
+ val signature = Base64.getUrlDecoder().decode(parts[2])
2653
+ if (!verifier.verify(signature)) return null
2654
+
2655
+ val payload = String(Base64.getUrlDecoder().decode(parts[1]))
2656
+ return JSONObject(payload)
2657
+ }
2658
+
2659
+ // Entitlement binds the token to THIS installation.
2660
+ //
2661
+ // verifyToken only proves the store signed it: it does not check expiry, this
2662
+ // machine, or this product. Compare the claims before granting anything.
2663
+ // claims.fp is a server-side HMAC and cannot be recomputed here, so claims.ins
2664
+ // - the install id sent as site_url - is the binding a client can check.
2665
+ // Returns the claims and a null reason on success, or null and a reason.
2666
+ fun entitlement(
2667
+ token: String,
2668
+ publicKeyPem: String,
2669
+ installId: String?,
2670
+ productId: Int
2671
+ ): Pair<JSONObject?, String?> {
2672
+ val claims = verifyToken(token, publicKeyPem) ?: return Pair(null, "invalid_or_expired")
2673
+
2674
+ val exp = if (claims.has("exp")) claims.optLong("exp", 0L) else 0L
2675
+ if (exp > 0L && exp <= System.currentTimeMillis() / 1000L) {
2676
+ return Pair(null, "invalid_or_expired")
2677
+ }
2678
+
2679
+ if (productId > 0 && claims.optInt("prod", -1) != productId) {
2680
+ return Pair(null, "wrong_product")
2681
+ }
2682
+
2683
+ if (!installId.isNullOrEmpty() && claims.has("ins") && claims.optString("ins", "") != installId) {
2684
+ return Pair(null, "wrong_install")
2685
+ }
2686
+
2687
+ return Pair(claims, null)
2688
+ }
2549
2689
  `
2550
2690
  }
2551
2691
  ]