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