fluentcart-developer 2.3.1 → 2.3.3

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