feat: add client self-service purchases and integration kit
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
This commit is contained in:
142
client/purchase-sdk.mjs
Normal file
142
client/purchase-sdk.mjs
Normal file
@@ -0,0 +1,142 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { acceptLease, canRunOffline, verifyEnvelope } from './verify.mjs';
|
||||
|
||||
export class PurchaseError extends Error {
|
||||
constructor(code, status) { super(code); this.name = 'PurchaseError'; this.code = code; this.status = status; }
|
||||
}
|
||||
const valid = value => typeof value === 'string' && value.length > 0;
|
||||
const uuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
||||
const copy = value => structuredClone(value);
|
||||
const purchaseCodes = new Set(['invalid_purchase_credential', 'invalid_request', 'not_found', 'idempotency_conflict', 'plan_disabled', 'plan_version_conflict', 'purchase_not_paid', 'authorization_unavailable', 'instance_conflict', 'authorization_pending', 'channel_unavailable', 'credentials_unavailable']);
|
||||
|
||||
export class PurchaseClient {
|
||||
constructor({ baseUrl, token, productId, installationId, pinnedKeys, storage, fetchImpl = fetch, clock = () => Date.now(), timeoutMs = 15000 }) {
|
||||
let url;
|
||||
try { url = new URL(baseUrl); } catch { throw new PurchaseError('invalid_origin'); }
|
||||
if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash || url.username || url.password) throw new PurchaseError('invalid_origin');
|
||||
if (!valid(token) || !valid(installationId) || !Number.isSafeInteger(productId) || productId <= 0 || !Array.isArray(pinnedKeys) || !storage?.load || !storage?.saveAtomic || !Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new PurchaseError('invalid_config');
|
||||
this.origin = url; this.token = token; this.productId = productId; this.installationId = installationId;
|
||||
this.keys = pinnedKeys; this.storage = storage; this.fetch = fetchImpl; this.clock = clock; this.timeoutMs = timeoutMs;
|
||||
}
|
||||
async load() {
|
||||
let state;
|
||||
try { state = await this.storage.load(); } catch { throw new PurchaseError('storage_load_failed'); }
|
||||
if (state && (state.installation_id !== this.installationId || state.product_id !== this.productId)) throw new PurchaseError('storage_scope_mismatch');
|
||||
if (state?.credentials && !uuid(state.credentials.instance_id)) throw new PurchaseError('invalid_instance');
|
||||
return state ? copy(state) : { installation_id: this.installationId, product_id: this.productId };
|
||||
}
|
||||
async save(state) {
|
||||
try { await this.storage.saveAtomic(copy(state)); } catch { throw new PurchaseError('storage_save_failed'); }
|
||||
}
|
||||
async request(path, body, { bearer = false, key, signal } = {}) {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
const abort = () => controller.abort();
|
||||
if (signal) { if (signal.aborted) abort(); else signal.addEventListener('abort', abort, { once: true }); }
|
||||
try {
|
||||
if (controller.signal.aborted) throw new PurchaseError('request_aborted');
|
||||
const headers = { 'content-type': 'application/json' };
|
||||
if (bearer) headers.authorization = `Bearer ${this.token}`;
|
||||
if (key) headers['Idempotency-Key'] = key;
|
||||
const response = await this.fetch(new URL(path, this.origin), { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal, redirect: 'error' });
|
||||
if (!response.ok) {
|
||||
let code;
|
||||
if (bearer) {
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (typeof body?.error?.code === 'string' && purchaseCodes.has(body.error.code)) code = body.error.code;
|
||||
} catch { /* Malformed responses use the HTTP status fallback. */ }
|
||||
}
|
||||
throw new PurchaseError(code || `http_${response.status}`, response.status);
|
||||
}
|
||||
const json = await response.json();
|
||||
if (!json || typeof json.data !== 'object' || json.data === null) throw new PurchaseError('invalid_response');
|
||||
return json.data;
|
||||
} catch (error) {
|
||||
if (error instanceof PurchaseError) throw error;
|
||||
throw new PurchaseError(controller.signal.aborted ? 'request_aborted' : 'network_error');
|
||||
} finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
|
||||
}
|
||||
async plans(options = {}) {
|
||||
return this.request('api/v1/client/plans', { installation_id: this.installationId }, { bearer: true, signal: options.signal });
|
||||
}
|
||||
async purchase(planId, planVersion, channel, options = {}) {
|
||||
if (!valid(channel) || !(valid(planId) || Number.isSafeInteger(planId)) || !(valid(planVersion) || Number.isSafeInteger(planVersion))) throw new PurchaseError('invalid_purchase');
|
||||
const state = await this.load();
|
||||
const input = { plan_id: planId, plan_version: planVersion, installation_id: this.installationId, channel };
|
||||
if (state.purchase && JSON.stringify(state.purchase.input) !== JSON.stringify(input)) throw new PurchaseError('pending_purchase_conflict');
|
||||
if (!state.purchase) { state.purchase = { input, key: randomUUID() }; await this.save(state); }
|
||||
const data = await this.request('api/v1/client/purchases', state.purchase.input, { bearer: true, key: state.purchase.key, signal: options.signal });
|
||||
if (!valid(data.order_no)) throw new PurchaseError('invalid_response');
|
||||
if (state.purchase.order_no && state.purchase.order_no !== data.order_no) throw new PurchaseError('order_mismatch');
|
||||
state.purchase.order_no = data.order_no;
|
||||
await this.save(state);
|
||||
return data;
|
||||
}
|
||||
async status(options = {}) {
|
||||
const state = await this.load();
|
||||
if (!state.purchase) throw new PurchaseError('no_pending_purchase');
|
||||
const lookup = state.purchase.order_no ? { order_no: state.purchase.order_no } : { idempotency_key: state.purchase.key };
|
||||
const data = await this.request('api/v1/client/purchases/status', { ...lookup, installation_id: this.installationId }, { bearer: true, signal: options.signal });
|
||||
if (state.purchase.order_no && data.order_no !== state.purchase.order_no) throw new PurchaseError('order_mismatch');
|
||||
if (!state.purchase.order_no && valid(data.order_no)) { state.purchase.order_no = data.order_no; await this.save(state); }
|
||||
return data;
|
||||
}
|
||||
async claim(options = {}) {
|
||||
const state = await this.load();
|
||||
if (state.credentials && state.activation_key) return this.activate(options);
|
||||
if (!state.purchase?.order_no) await this.status(options);
|
||||
const current = await this.load();
|
||||
if (!current.purchase?.order_no) throw new PurchaseError('order_unresolved');
|
||||
const data = await this.request('api/v1/client/purchases/claim', { order_no: current.purchase.order_no, installation_id: this.installationId }, { bearer: true, signal: options.signal });
|
||||
if (!uuid(data.instance_id) || !valid(data.secret) || !valid(data.license_key) || !Number.isSafeInteger(data.license_id) || data.license_id <= 0) throw new PurchaseError('invalid_claim');
|
||||
if (current.credentials && (current.credentials.instance_id !== data.instance_id || current.credentials.secret !== data.secret || current.credentials.license_key !== data.license_key || current.credentials.license_id !== data.license_id)) throw new PurchaseError('claim_conflict');
|
||||
if (!current.credentials) {
|
||||
current.lease = null;
|
||||
current.certificate = null;
|
||||
current.customer_id = null;
|
||||
}
|
||||
current.credentials = { instance_id: data.instance_id, secret: data.secret, license_key: data.license_key, license_id: data.license_id };
|
||||
if (!current.activation_key) current.activation_key = randomUUID();
|
||||
await this.save(current);
|
||||
return this.activate(options);
|
||||
}
|
||||
async activate(options = {}) {
|
||||
const state = await this.load();
|
||||
if (!state.credentials || !state.activation_key) throw new PurchaseError('no_credentials');
|
||||
if (!uuid(state.credentials.instance_id)) throw new PurchaseError('invalid_instance');
|
||||
const data = await this.request(`api/v1/activation/instances/${encodeURIComponent(state.credentials.instance_id)}`, { secret: state.credentials.secret, license_key: state.credentials.license_key }, { key: state.activation_key, signal: options.signal });
|
||||
const p = verifyEnvelope(data.certificate, this.keys);
|
||||
if (p.version !== 'license-v2' || p.instance_id !== state.credentials.instance_id || p.product_id !== this.productId || p.license_id !== state.credentials.license_id || (state.customer_id && p.customer_id !== state.customer_id)) throw new PurchaseError('certificate_scope_mismatch');
|
||||
if (!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(p.starts_at) || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z$/.test(p.expires_at) || !Number.isFinite(Date.parse(p.starts_at)) || !Number.isFinite(Date.parse(p.expires_at)) || Date.parse(p.starts_at) > this.clock() || Date.parse(p.expires_at) <= this.clock()) throw new PurchaseError('certificate_not_active');
|
||||
if (state.certificate && (state.certificate.payload.customer_id !== p.customer_id || state.certificate.payload.license_id !== p.license_id)) throw new PurchaseError('certificate_mismatch');
|
||||
state.customer_id = p.customer_id; state.certificate = data.certificate;
|
||||
await this.save(state);
|
||||
return this.heartbeat(options);
|
||||
}
|
||||
async heartbeat(options = {}) {
|
||||
const state = await this.load();
|
||||
if (!state.credentials || !state.certificate) throw new PurchaseError('not_activated');
|
||||
const cert = verifyEnvelope(state.certificate, this.keys);
|
||||
if (cert.version !== 'license-v2' || cert.instance_id !== state.credentials.instance_id || cert.product_id !== this.productId || cert.customer_id !== state.customer_id || cert.license_id !== state.credentials.license_id || Date.parse(cert.expires_at) <= this.clock()) throw new PurchaseError('certificate_scope_mismatch');
|
||||
if (!state.heartbeat_request) { state.heartbeat_request = { key: randomUUID(), client_time: new Date(this.clock()).toISOString() }; await this.save(state); }
|
||||
let data;
|
||||
try {
|
||||
data = await this.request(`api/v1/instances/${encodeURIComponent(state.credentials.instance_id)}/heartbeat`, { secret: state.credentials.secret, client_time: state.heartbeat_request.client_time }, { key: state.heartbeat_request.key, signal: options.signal });
|
||||
} catch (error) {
|
||||
if (error.status === 409 && options.resetConflict === true) { state.heartbeat_request = null; await this.save(state); }
|
||||
throw error;
|
||||
}
|
||||
const lease = acceptLease(data, this.keys, state.credentials.instance_id, state.lease, this.clock());
|
||||
if (Date.parse(data.payload.entitlement_expires_at) !== Date.parse(cert.expires_at)) throw new PurchaseError('entitlement_mismatch');
|
||||
state.lease = lease; state.heartbeat_request = null;
|
||||
await this.save(state);
|
||||
return { enabled: lease.enabled, next_heartbeat_seconds: data.next_heartbeat_seconds };
|
||||
}
|
||||
async offlineEnabled() {
|
||||
const state = await this.load();
|
||||
if (!state.credentials || !state.certificate || !state.lease) return false;
|
||||
const p = verifyEnvelope(state.certificate, this.keys);
|
||||
return p.version === 'license-v2' && p.instance_id === state.credentials.instance_id && p.product_id === this.productId && p.customer_id === state.customer_id && Number.isFinite(Date.parse(p.starts_at)) && Number.isFinite(Date.parse(p.expires_at)) && this.clock() >= Date.parse(p.starts_at) && this.clock() < Date.parse(p.expires_at) && canRunOffline(state.lease, state.credentials.instance_id, this.clock());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user