@extenshi/pay 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +260 -0
  3. package/dist/api/mock.d.ts +35 -0
  4. package/dist/api/mock.d.ts.map +1 -0
  5. package/dist/api/pay-api.d.ts +16 -0
  6. package/dist/api/pay-api.d.ts.map +1 -0
  7. package/dist/api/transport.d.ts +52 -0
  8. package/dist/api/transport.d.ts.map +1 -0
  9. package/dist/core/config.d.ts +5 -0
  10. package/dist/core/config.d.ts.map +1 -0
  11. package/dist/core/event-emitter.d.ts +10 -0
  12. package/dist/core/event-emitter.d.ts.map +1 -0
  13. package/dist/core/extenshi-pay.d.ts +90 -0
  14. package/dist/core/extenshi-pay.d.ts.map +1 -0
  15. package/dist/core/identity.d.ts +13 -0
  16. package/dist/core/identity.d.ts.map +1 -0
  17. package/dist/core/index.d.ts +25 -0
  18. package/dist/core/index.d.ts.map +1 -0
  19. package/dist/core/storage.d.ts +42 -0
  20. package/dist/core/storage.d.ts.map +1 -0
  21. package/dist/core.d.mts +821 -0
  22. package/dist/core.d.ts +821 -0
  23. package/dist/core.esm.js +1681 -0
  24. package/dist/core.esm.js.map +1 -0
  25. package/dist/core.js +1806 -0
  26. package/dist/core.js.map +1 -0
  27. package/dist/core.mjs +1744 -0
  28. package/dist/core.mjs.map +1 -0
  29. package/dist/extenshi-pay-lite.esm.js +1664 -0
  30. package/dist/extenshi-pay-lite.esm.js.map +1 -0
  31. package/dist/extenshi-pay-lite.js +1743 -0
  32. package/dist/extenshi-pay-lite.js.map +1 -0
  33. package/dist/extenshi-pay-lite.min.js +7 -0
  34. package/dist/extenshi-pay-lite.min.js.map +1 -0
  35. package/dist/extenshi-pay-lite.mjs +1727 -0
  36. package/dist/extenshi-pay-lite.mjs.map +1 -0
  37. package/dist/extenshi-pay.cjs.js +2632 -0
  38. package/dist/extenshi-pay.cjs.js.map +1 -0
  39. package/dist/extenshi-pay.d.ts +32 -0
  40. package/dist/extenshi-pay.d.ts.map +1 -0
  41. package/dist/extenshi-pay.esm.js +2496 -0
  42. package/dist/extenshi-pay.esm.js.map +1 -0
  43. package/dist/extenshi-pay.esm.min.js +7 -0
  44. package/dist/extenshi-pay.esm.min.js.map +1 -0
  45. package/dist/extenshi-pay.js +2638 -0
  46. package/dist/extenshi-pay.js.map +1 -0
  47. package/dist/extenshi-pay.min.js +7 -0
  48. package/dist/extenshi-pay.min.js.map +1 -0
  49. package/dist/extenshi-pay.min.mjs +7 -0
  50. package/dist/extenshi-pay.min.mjs.map +1 -0
  51. package/dist/extenshi-pay.mjs +2559 -0
  52. package/dist/extenshi-pay.mjs.map +1 -0
  53. package/dist/index.d.mts +937 -0
  54. package/dist/index.d.ts +937 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/lite.d.mts +659 -0
  57. package/dist/lite.d.ts +659 -0
  58. package/dist/lite.d.ts.map +1 -0
  59. package/dist/payment/checkout.d.ts +47 -0
  60. package/dist/payment/checkout.d.ts.map +1 -0
  61. package/dist/payment/entitlement.d.ts +76 -0
  62. package/dist/payment/entitlement.d.ts.map +1 -0
  63. package/dist/payment/features.d.ts +12 -0
  64. package/dist/payment/features.d.ts.map +1 -0
  65. package/dist/payment/recovery.d.ts +29 -0
  66. package/dist/payment/recovery.d.ts.map +1 -0
  67. package/dist/payment/signature.d.ts +12 -0
  68. package/dist/payment/signature.d.ts.map +1 -0
  69. package/dist/paywall/billing-profile-picker.d.ts +8 -0
  70. package/dist/paywall/billing-profile-picker.d.ts.map +1 -0
  71. package/dist/paywall/format.d.ts +13 -0
  72. package/dist/paywall/format.d.ts.map +1 -0
  73. package/dist/paywall/index.d.ts +9 -0
  74. package/dist/paywall/index.d.ts.map +1 -0
  75. package/dist/paywall/license-panel.d.ts +10 -0
  76. package/dist/paywall/license-panel.d.ts.map +1 -0
  77. package/dist/paywall/renderer.d.ts +55 -0
  78. package/dist/paywall/renderer.d.ts.map +1 -0
  79. package/dist/paywall/seller-details.d.ts +5 -0
  80. package/dist/paywall/seller-details.d.ts.map +1 -0
  81. package/dist/paywall/strings.d.ts +10 -0
  82. package/dist/paywall/strings.d.ts.map +1 -0
  83. package/dist/paywall/templates.d.ts +14 -0
  84. package/dist/paywall/templates.d.ts.map +1 -0
  85. package/dist/paywall.d.mts +160 -0
  86. package/dist/paywall.d.ts +160 -0
  87. package/dist/paywall.esm.js +442 -0
  88. package/dist/paywall.esm.js.map +1 -0
  89. package/dist/paywall.js +462 -0
  90. package/dist/paywall.js.map +1 -0
  91. package/dist/paywall.mjs +442 -0
  92. package/dist/paywall.mjs.map +1 -0
  93. package/dist/types/config.d.ts +62 -0
  94. package/dist/types/config.d.ts.map +1 -0
  95. package/dist/types/contract.d.ts +172 -0
  96. package/dist/types/contract.d.ts.map +1 -0
  97. package/dist/types/entitlement.d.ts +71 -0
  98. package/dist/types/entitlement.d.ts.map +1 -0
  99. package/dist/types/errors.d.ts +31 -0
  100. package/dist/types/errors.d.ts.map +1 -0
  101. package/dist/types/events.d.ts +29 -0
  102. package/dist/types/events.d.ts.map +1 -0
  103. package/dist/types/index.d.ts +7 -0
  104. package/dist/types/index.d.ts.map +1 -0
  105. package/dist/types/paywall.d.ts +37 -0
  106. package/dist/types/paywall.d.ts.map +1 -0
  107. package/dist/utils/logger.d.ts +16 -0
  108. package/dist/utils/logger.d.ts.map +1 -0
  109. package/dist/version.d.ts +3 -0
  110. package/dist/version.d.ts.map +1 -0
  111. package/package.json +115 -0
@@ -0,0 +1,1743 @@
1
+ /*!
2
+ * ExtenshiPay SDK v0.7.0
3
+ * (c) 2026 Extenshi.io
4
+ * Released under the MIT License.
5
+ */
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
8
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ExtenshiPayLite = {}));
10
+ })(this, (function (exports) { 'use strict';
11
+
12
+ /**
13
+ * Wire contract between the SDK and catalog-bff `pay.*`.
14
+ *
15
+ * SOURCE OF TRUTH: `shared-types/pay.ts` in the extenshi.io monorepo. The SDK
16
+ * ships with zero runtime dependencies and must not import that workspace, so
17
+ * the types and constants it needs are copied here under identical names.
18
+ * `canonicalJson` is copied VERBATIM: the BFF signs its output and the SDK
19
+ * verifies it, so both sides must produce byte-identical strings
20
+ * (pinned by tests/unit/canonical-json.test.ts). When `shared-types/pay.ts`
21
+ * changes, mirror the change here.
22
+ */
23
+ /** Bumped only when an older SDK could misread the response. */
24
+ const PAY_CONTRACT_VERSION = 1;
25
+ // ─── Publishable key ────────────────────────────────────────────────────────
26
+ /**
27
+ * The only credential an extension bundle carries. It is public by
28
+ * construction (anyone can unzip the .crx), so it must grant nothing beyond
29
+ * "read this project's offer" and "start a checkout for this project".
30
+ */
31
+ const PAY_PUBLISHABLE_KEY_PREFIX = 'pk_ext_';
32
+ const PAY_PUBLISHABLE_KEY_HEX_LENGTH = 32;
33
+ const PUBLISHABLE_KEY_RE = new RegExp(`^${PAY_PUBLISHABLE_KEY_PREFIX}[0-9a-f]{${PAY_PUBLISHABLE_KEY_HEX_LENGTH}}$`);
34
+ function isPayPublishableKey(value) {
35
+ return typeof value === 'string' && PUBLISHABLE_KEY_RE.test(value);
36
+ }
37
+ /**
38
+ * The `endUserRef` an SDK mints on first run and keeps in `chrome.storage`.
39
+ * Opaque, random, never derived from anything identifying.
40
+ */
41
+ const PAY_END_USER_REF_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
42
+ /** Typed error codes the BFF throws; dojo and the SDK match on `cause.code`. */
43
+ const PAY_ERRORS = {
44
+ SELLER_NOT_CONNECTED: 'PAY_SELLER_NOT_CONNECTED',
45
+ SELLER_NOT_ACTIVE: 'PAY_SELLER_NOT_ACTIVE',
46
+ AGREEMENT_REQUIRED: 'PAY_AGREEMENT_REQUIRED',
47
+ OFFER_NOT_FOUND: 'PAY_OFFER_NOT_FOUND',
48
+ GATEWAY_UNAVAILABLE: 'PAY_GATEWAY_UNAVAILABLE',
49
+ RATE_LIMITED: 'PAY_RATE_LIMITED',
50
+ INVALID_KEY: 'PAY_INVALID_KEY',
51
+ };
52
+ /**
53
+ * Canonical JSON for signing: keys sorted recursively, no whitespace. Both
54
+ * the BFF (sign) and the SDK (verify) must produce byte-identical output for
55
+ * the same payload, so the rule lives in the shared contract.
56
+ */
57
+ function canonicalJson(value) {
58
+ if (value === null || typeof value !== 'object')
59
+ return JSON.stringify(value);
60
+ if (Array.isArray(value))
61
+ return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
62
+ const entries = Object.entries(value)
63
+ .filter(([, v]) => v !== undefined)
64
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
65
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
66
+ }
67
+
68
+ const ERROR_CODES = {
69
+ INVALID_CONFIG: 'INVALID_CONFIG',
70
+ INVALID_REQUEST: 'INVALID_REQUEST',
71
+ NETWORK_ERROR: 'NETWORK_ERROR',
72
+ TIMEOUT: 'TIMEOUT',
73
+ VERIFICATION_UNAVAILABLE: 'VERIFICATION_UNAVAILABLE',
74
+ INVALID_RESPONSE: 'INVALID_RESPONSE',
75
+ RATE_LIMITED: 'RATE_LIMITED',
76
+ INVALID_KEY: 'INVALID_KEY',
77
+ SELLER_NOT_ACTIVE: 'SELLER_NOT_ACTIVE',
78
+ OFFER_NOT_FOUND: 'OFFER_NOT_FOUND',
79
+ GATEWAY_UNAVAILABLE: 'GATEWAY_UNAVAILABLE',
80
+ CHECKOUT_UNAVAILABLE: 'CHECKOUT_UNAVAILABLE',
81
+ PAYWALL_UNAVAILABLE: 'PAYWALL_UNAVAILABLE',
82
+ UNKNOWN: 'UNKNOWN',
83
+ };
84
+ class ExtenshiPayError extends Error {
85
+ constructor(code, message, options = {}) {
86
+ super(message);
87
+ this.name = 'ExtenshiPayError';
88
+ this.code = code;
89
+ this.retryAfterSec = options.retryAfterSec;
90
+ this.httpStatus = options.httpStatus;
91
+ this.cause = options.cause;
92
+ }
93
+ static from(error, fallback = ERROR_CODES.UNKNOWN) {
94
+ if (error instanceof ExtenshiPayError)
95
+ return error;
96
+ const message = error instanceof Error ? error.message : String(error);
97
+ return new ExtenshiPayError(fallback, message, { cause: error });
98
+ }
99
+ }
100
+
101
+ /**
102
+ * `endUserRef` — the only identity the SDK has.
103
+ *
104
+ * A random UUID minted on first run and kept in the SDK's storage namespace.
105
+ * It is never derived from anything identifying (no fingerprint, no e-mail,
106
+ * no extension-supplied user id) and remains the installation identifier. Explicit recovery also sends a
107
+ * random session ID and proof; it never derives identity from an email locally.
108
+ */
109
+ const END_USER_REF_STORAGE_KEY = 'extenshi-pay:endUserRef';
110
+ function mintEndUserRef() {
111
+ const cryptoApi = globalThis.crypto;
112
+ if (!cryptoApi) {
113
+ throw new ExtenshiPayError(ERROR_CODES.UNKNOWN, 'Web Crypto is not available in this context');
114
+ }
115
+ if (typeof cryptoApi.randomUUID === 'function')
116
+ return cryptoApi.randomUUID();
117
+ const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
118
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
119
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
120
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
121
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
122
+ }
123
+ async function getOrCreateEndUserRef(storage) {
124
+ const existing = await storage.get(END_USER_REF_STORAGE_KEY);
125
+ if (typeof existing === 'string' && PAY_END_USER_REF_RE.test(existing))
126
+ return existing;
127
+ const ref = mintEndUserRef();
128
+ await storage.set(END_USER_REF_STORAGE_KEY, ref);
129
+ return ref;
130
+ }
131
+
132
+ /**
133
+ * In-memory stand-in for the BFF, used when `mock: true`. Lets an extension be
134
+ * developed with no backend: offers and entitlements come from `mockData`, a
135
+ * mock checkout completes after `claimAfterPolls` polls and grants the SKU.
136
+ */
137
+ const DAY_MS = 24 * 60 * 60 * 1000;
138
+ class MockTransport {
139
+ constructor(data = {}) {
140
+ this.sessions = new Map();
141
+ this.entitlements = [...(data.entitlements ?? [])];
142
+ this.offers = [...(data.offers ?? [])];
143
+ this.projectName = data.projectName ?? 'Mock project';
144
+ this.checkoutEnabled = data.checkoutEnabled ?? true;
145
+ this.claimAfterPolls = data.claimAfterPolls ?? 1;
146
+ }
147
+ async call(procedure, _kind, input) {
148
+ switch (procedure) {
149
+ case 'pay.getOffer':
150
+ return this.offerResponse();
151
+ case 'pay.createCheckout':
152
+ return this.createCheckout(String(input.sku));
153
+ case 'pay.claimSession':
154
+ return this.claim(String(input.sessionId), String(input.endUserRef), String(input.publishableKey));
155
+ case 'pay.getEntitlement':
156
+ return this.envelope(String(input.endUserRef), String(input.publishableKey));
157
+ case 'pay.getPortalUrl':
158
+ return { url: this.entitlements.length > 0 ? 'https://mock.extenshi.io/portal' : null };
159
+ default:
160
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, `Unknown procedure ${procedure}`);
161
+ }
162
+ }
163
+ /** Test/dev helpers. */
164
+ setEntitlements(items) {
165
+ this.entitlements = [...items];
166
+ }
167
+ cancelSession(sessionId) {
168
+ const session = this.sessions.get(sessionId);
169
+ if (session)
170
+ session.state = 'canceled';
171
+ }
172
+ expireSession(sessionId) {
173
+ const session = this.sessions.get(sessionId);
174
+ if (session)
175
+ session.state = 'expired';
176
+ }
177
+ offerResponse() {
178
+ return {
179
+ v: PAY_CONTRACT_VERSION,
180
+ projectName: this.projectName,
181
+ provider: 'stripe',
182
+ checkoutEnabled: this.checkoutEnabled && this.offers.length > 0,
183
+ offers: [...this.offers],
184
+ entitlementPublicKey: null,
185
+ };
186
+ }
187
+ createCheckout(sku) {
188
+ if (!this.checkoutEnabled) {
189
+ throw new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, 'Mock seller cannot take payments');
190
+ }
191
+ if (!this.offers.some((offer) => offer.sku === sku)) {
192
+ throw new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, `Unknown mock offer ${sku}`);
193
+ }
194
+ const sessionId = mintEndUserRef();
195
+ this.sessions.set(sessionId, { sku, polls: 0, state: 'open' });
196
+ return {
197
+ url: `https://mock.extenshi.io/checkout/${sessionId}`,
198
+ sessionId,
199
+ expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
200
+ };
201
+ }
202
+ claim(sessionId, endUserRef, publishableKey) {
203
+ const session = this.sessions.get(sessionId);
204
+ if (!session)
205
+ throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Unknown checkout session');
206
+ if (session.state === 'canceled')
207
+ return { state: 'canceled' };
208
+ if (session.state === 'expired')
209
+ return { state: 'expired' };
210
+ if (session.state === 'open') {
211
+ session.polls += 1;
212
+ if (session.polls <= this.claimAfterPolls)
213
+ return { state: 'pending' };
214
+ session.state = 'complete';
215
+ this.grant(session.sku);
216
+ }
217
+ return { state: 'complete', entitlement: this.envelope(endUserRef, publishableKey) };
218
+ }
219
+ grant(sku) {
220
+ const offer = this.offers.find((o) => o.sku === sku);
221
+ const expiresAt = offer?.kind === 'subscription'
222
+ ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
223
+ : null;
224
+ this.entitlements = [
225
+ ...this.entitlements.filter((item) => item.sku !== sku),
226
+ {
227
+ sku,
228
+ title: offer?.title,
229
+ kind: offer?.kind,
230
+ status: 'active',
231
+ expiresAt,
232
+ features: offer?.features ?? [],
233
+ },
234
+ ];
235
+ }
236
+ envelope(endUserRef, publishableKey) {
237
+ return {
238
+ payload: {
239
+ v: PAY_CONTRACT_VERSION,
240
+ publishableKey,
241
+ endUserRef,
242
+ entitlements: [...this.entitlements],
243
+ issuedAt: new Date().toISOString(),
244
+ },
245
+ signature: null,
246
+ alg: null,
247
+ };
248
+ }
249
+ }
250
+
251
+ /** Typed wrapper over the SDK-facing `pay.*` procedures. Nothing else is ever called. */
252
+ class PayApi {
253
+ constructor(transport, publishableKey) {
254
+ this.transport = transport;
255
+ this.publishableKey = publishableKey;
256
+ }
257
+ createRestoreSession(claimChallenge) {
258
+ return this.transport.call('pay.createRestoreSession', 'mutation', {
259
+ publishableKey: this.publishableKey,
260
+ claimChallenge,
261
+ });
262
+ }
263
+ claimRestoreSession(sessionId, claimSecret) {
264
+ return this.transport.call('pay.claimRestoreSession', 'mutation', {
265
+ publishableKey: this.publishableKey,
266
+ sessionId,
267
+ claimSecret,
268
+ });
269
+ }
270
+ getOffer(locale) {
271
+ return this.transport.call('pay.getOffer', 'query', {
272
+ publishableKey: this.publishableKey,
273
+ locale: locale ?? undefined,
274
+ });
275
+ }
276
+ createCheckout(sku, endUserRef, locale) {
277
+ return this.transport.call('pay.createCheckout', 'mutation', {
278
+ publishableKey: this.publishableKey,
279
+ sku,
280
+ endUserRef,
281
+ locale: locale ?? undefined,
282
+ });
283
+ }
284
+ claimSession(sessionId, endUserRef) {
285
+ return this.transport.call('pay.claimSession', 'query', {
286
+ publishableKey: this.publishableKey,
287
+ sessionId,
288
+ endUserRef,
289
+ });
290
+ }
291
+ getEntitlement(endUserRef) {
292
+ return this.transport.call('pay.getEntitlement', 'query', {
293
+ publishableKey: this.publishableKey,
294
+ endUserRef,
295
+ });
296
+ }
297
+ getPortalUrl(endUserRef, customerId) {
298
+ return this.transport.call('pay.getPortalUrl', 'mutation', {
299
+ publishableKey: this.publishableKey,
300
+ endUserRef,
301
+ ...(customerId ? { customerId } : {}),
302
+ });
303
+ }
304
+ }
305
+
306
+ const ORDER = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
307
+ class Logger {
308
+ constructor() {
309
+ this.level = 'warn';
310
+ this.prefix = '[ExtenshiPay]';
311
+ }
312
+ configure(options) {
313
+ if (options.logLevel)
314
+ this.level = options.logLevel;
315
+ if (options.debug)
316
+ this.level = 'debug';
317
+ }
318
+ error(message, ...args) {
319
+ if (this.enabled('error'))
320
+ console.error(this.prefix, message, ...args);
321
+ }
322
+ warn(message, ...args) {
323
+ if (this.enabled('warn'))
324
+ console.warn(this.prefix, message, ...args);
325
+ }
326
+ info(message, ...args) {
327
+ if (this.enabled('info'))
328
+ console.info(this.prefix, message, ...args);
329
+ }
330
+ debug(message, ...args) {
331
+ if (this.enabled('debug'))
332
+ console.debug(this.prefix, message, ...args);
333
+ }
334
+ enabled(level) {
335
+ return ORDER[level] <= ORDER[this.level];
336
+ }
337
+ }
338
+ const logger = new Logger();
339
+
340
+ /**
341
+ * HTTP transport for the BFF's tRPC endpoint (`/api/trpc/<procedure>`).
342
+ *
343
+ * Queries are header-less GETs with `?input=<json>` (a CORS "simple request",
344
+ * so no preflight); mutations POST a JSON body. The only things that leave the
345
+ * extension are payment inputs and optional recovery session/proof inputs
346
+ * and the browser's standard headers — `credentials: 'omit'` keeps cookies out.
347
+ * Queries are retried on network / 5xx errors; mutations never are.
348
+ */
349
+ const TRPC_PATH = '/api/trpc';
350
+ const DEFAULT_TIMEOUT_MS = 10000;
351
+ const DEFAULT_RETRIES = 1;
352
+ const RETRY_BASE_MS = 500;
353
+ const RETRYABLE = new Set([
354
+ ERROR_CODES.NETWORK_ERROR,
355
+ ERROR_CODES.TIMEOUT,
356
+ ERROR_CODES.GATEWAY_UNAVAILABLE,
357
+ ]);
358
+ /** `PAY_*` cause codes, when the BFF forwards them, map 1:1. */
359
+ const CAUSE_TO_CODE = {
360
+ [PAY_ERRORS.RATE_LIMITED]: ERROR_CODES.RATE_LIMITED,
361
+ [PAY_ERRORS.INVALID_KEY]: ERROR_CODES.INVALID_KEY,
362
+ [PAY_ERRORS.SELLER_NOT_CONNECTED]: ERROR_CODES.SELLER_NOT_ACTIVE,
363
+ [PAY_ERRORS.SELLER_NOT_ACTIVE]: ERROR_CODES.SELLER_NOT_ACTIVE,
364
+ [PAY_ERRORS.AGREEMENT_REQUIRED]: ERROR_CODES.SELLER_NOT_ACTIVE,
365
+ [PAY_ERRORS.OFFER_NOT_FOUND]: ERROR_CODES.OFFER_NOT_FOUND,
366
+ [PAY_ERRORS.GATEWAY_UNAVAILABLE]: ERROR_CODES.GATEWAY_UNAVAILABLE,
367
+ };
368
+ function parseRetryAfter(message) {
369
+ const match = /retry in (\d+)s/i.exec(message);
370
+ return match ? Number(match[1]) : undefined;
371
+ }
372
+ /**
373
+ * The BFF's error formatter does not forward `cause` for `pay.*` errors, so the
374
+ * tRPC code + message is the primary signal; `data.cause.code` is honoured when
375
+ * present so a future BFF that forwards it needs no SDK change.
376
+ */
377
+ function trpcErrorToPayError(error, httpStatus) {
378
+ const message = error.message ?? 'Request failed';
379
+ const trpcCode = error.data?.code ?? '';
380
+ const causeCode = error.data?.cause?.code;
381
+ const retryAfterSec = error.data?.cause?.retryAfterSec ?? parseRetryAfter(message);
382
+ const options = { retryAfterSec, httpStatus: error.data?.httpStatus ?? httpStatus };
383
+ const mapped = causeCode ? CAUSE_TO_CODE[causeCode] : undefined;
384
+ if (mapped)
385
+ return new ExtenshiPayError(mapped, message, options);
386
+ switch (trpcCode) {
387
+ case 'TOO_MANY_REQUESTS':
388
+ return new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, message, options);
389
+ case 'NOT_FOUND':
390
+ if (/publishable key/i.test(message))
391
+ return new ExtenshiPayError(ERROR_CODES.INVALID_KEY, message, options);
392
+ if (/session/i.test(message))
393
+ return new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, message, options);
394
+ return new ExtenshiPayError(ERROR_CODES.OFFER_NOT_FOUND, message, options);
395
+ case 'PRECONDITION_FAILED':
396
+ return new ExtenshiPayError(ERROR_CODES.SELLER_NOT_ACTIVE, message, options);
397
+ case 'BAD_REQUEST':
398
+ return new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, message, options);
399
+ case 'INTERNAL_SERVER_ERROR':
400
+ return new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, message, options);
401
+ default:
402
+ return new ExtenshiPayError(ERROR_CODES.UNKNOWN, message, options);
403
+ }
404
+ }
405
+ function sleep(ms) {
406
+ return new Promise((resolve) => setTimeout(resolve, ms));
407
+ }
408
+ class HttpTransport {
409
+ constructor(options) {
410
+ this.apiUrl = options.apiUrl.replace(/\/+$/, '');
411
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
412
+ this.retries = options.retries ?? DEFAULT_RETRIES;
413
+ this.fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
414
+ }
415
+ async call(procedure, kind, input) {
416
+ const base = `${this.apiUrl}${TRPC_PATH}/${procedure}`;
417
+ const url = kind === 'query' ? `${base}?input=${encodeURIComponent(JSON.stringify(input))}` : base;
418
+ const attempts = kind === 'query' ? this.retries + 1 : 1;
419
+ let lastError = null;
420
+ for (let attempt = 0; attempt < attempts; attempt++) {
421
+ try {
422
+ return await this.request(url, kind, input);
423
+ }
424
+ catch (error) {
425
+ const err = ExtenshiPayError.from(error);
426
+ if (!RETRYABLE.has(err.code) || attempt === attempts - 1)
427
+ throw err;
428
+ lastError = err;
429
+ logger.debug(`${procedure} failed (${err.code}), retrying`);
430
+ await sleep(RETRY_BASE_MS * 2 ** attempt);
431
+ }
432
+ }
433
+ throw lastError ?? new ExtenshiPayError(ERROR_CODES.UNKNOWN, `${procedure} failed`);
434
+ }
435
+ async request(url, kind, input) {
436
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
437
+ const timer = controller ? setTimeout(() => controller.abort(), this.timeoutMs) : null;
438
+ let response;
439
+ try {
440
+ response = await this.fetchImpl(url, {
441
+ method: kind === 'query' ? 'GET' : 'POST',
442
+ headers: kind === 'mutation' ? { 'Content-Type': 'application/json' } : undefined,
443
+ body: kind === 'mutation' ? JSON.stringify(input) : undefined,
444
+ signal: controller?.signal,
445
+ credentials: 'omit',
446
+ });
447
+ }
448
+ catch (error) {
449
+ if (controller?.signal.aborted) {
450
+ throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${this.timeoutMs}ms`);
451
+ }
452
+ throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
453
+ }
454
+ finally {
455
+ if (timer !== null)
456
+ clearTimeout(timer);
457
+ }
458
+ let body = null;
459
+ try {
460
+ body = (await response.json());
461
+ }
462
+ catch {
463
+ body = null;
464
+ }
465
+ if (body?.error)
466
+ throw trpcErrorToPayError(body.error, response.status);
467
+ if (!response.ok) {
468
+ const code = response.status >= 500 ? ERROR_CODES.GATEWAY_UNAVAILABLE : ERROR_CODES.INVALID_RESPONSE;
469
+ throw new ExtenshiPayError(code, `HTTP ${response.status}`, { httpStatus: response.status });
470
+ }
471
+ if (!body?.result || !('data' in body.result)) {
472
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed response from the payment backend');
473
+ }
474
+ return body.result.data;
475
+ }
476
+ }
477
+
478
+ /**
479
+ * Hosted checkout flow.
480
+ *
481
+ * `pay.createCheckout` returns a URL on the seller's provider; the SDK opens
482
+ * it in a new tab (`chrome.tabs.create`, falling back to `window.open`) and
483
+ * polls `pay.claimSession` every 2 s for up to 10 min — and immediately when
484
+ * the extension regains focus — until the webhook has landed. A pending
485
+ * session is persisted so a restarted service worker / reopened popup can
486
+ * finish the claim on the next `initialize()`.
487
+ */
488
+ const CHECKOUT_POLL_INTERVAL_MS = 2000;
489
+ const CHECKOUT_TIMEOUT_MS = 10 * 60 * 1000;
490
+ const MAX_ERROR_BACKOFF_MS = 30000;
491
+ /** How long after `expiresAt` a persisted session is still worth one claim (webhook lag). */
492
+ const PENDING_GRACE_MS = 60 * 60 * 1000;
493
+ async function openInNewTab(url) {
494
+ const g = globalThis;
495
+ const tabs = g.chrome?.tabs ?? g.browser?.tabs;
496
+ if (tabs && typeof tabs.create === 'function') {
497
+ const result = tabs.create({ url });
498
+ if (result && typeof result.then === 'function')
499
+ await result;
500
+ return;
501
+ }
502
+ if (typeof g.open === 'function') {
503
+ g.open(url, '_blank', 'noopener,noreferrer');
504
+ return;
505
+ }
506
+ throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'Cannot open a checkout tab from this context');
507
+ }
508
+ /** Calls `onFocus` whenever the extension window/tab regains focus; returns a disposer. */
509
+ function onFocusRegained(onFocus) {
510
+ const g = globalThis;
511
+ const disposers = [];
512
+ if (typeof g.addEventListener === 'function' && typeof g.removeEventListener === 'function') {
513
+ g.addEventListener('focus', onFocus);
514
+ disposers.push(() => g.removeEventListener?.('focus', onFocus));
515
+ }
516
+ const doc = g.document;
517
+ if (doc && typeof doc.addEventListener === 'function') {
518
+ const onVisible = () => {
519
+ if (doc.visibilityState === 'visible')
520
+ onFocus();
521
+ };
522
+ doc.addEventListener('visibilitychange', onVisible);
523
+ disposers.push(() => doc.removeEventListener('visibilitychange', onVisible));
524
+ }
525
+ const windows = g.chrome?.windows?.onFocusChanged;
526
+ if (windows && typeof windows.addListener === 'function') {
527
+ const onWindow = (windowId) => {
528
+ if (windowId !== -1)
529
+ onFocus();
530
+ };
531
+ windows.addListener(onWindow);
532
+ disposers.push(() => windows.removeListener(onWindow));
533
+ }
534
+ return () => {
535
+ for (const dispose of disposers)
536
+ dispose();
537
+ };
538
+ }
539
+ /** A sleep that can be cut short by `wake()`. */
540
+ function interruptibleSleep() {
541
+ let wake = null;
542
+ return {
543
+ sleep(ms) {
544
+ return new Promise((resolve) => {
545
+ const timer = setTimeout(() => {
546
+ wake = null;
547
+ resolve();
548
+ }, ms);
549
+ wake = () => {
550
+ clearTimeout(timer);
551
+ wake = null;
552
+ resolve();
553
+ };
554
+ });
555
+ },
556
+ wake() {
557
+ wake?.();
558
+ },
559
+ };
560
+ }
561
+ class CheckoutManager {
562
+ constructor(options) {
563
+ this.options = options;
564
+ this.active = null;
565
+ this.now = options.now ?? (() => Date.now());
566
+ }
567
+ get pendingKey() {
568
+ return `extenshi-pay:${this.options.publishableKey}:pendingCheckout`;
569
+ }
570
+ isActive() {
571
+ return this.active !== null;
572
+ }
573
+ async open(sku, options = {}) {
574
+ if (this.active) {
575
+ throw new ExtenshiPayError(ERROR_CODES.CHECKOUT_UNAVAILABLE, 'A checkout is already in progress');
576
+ }
577
+ const endUserRef = await this.options.getEndUserRef();
578
+ const session = await this.options.api.createCheckout(sku, endUserRef, options.locale ?? this.options.locale);
579
+ this.active = session.sessionId;
580
+ try {
581
+ const pending = { sessionId: session.sessionId, sku, expiresAt: session.expiresAt };
582
+ await this.options.storage.set(this.pendingKey, pending);
583
+ this.options.emit('checkout:started', { sku, sessionId: session.sessionId, url: session.url });
584
+ await (options.openUrl ?? this.options.openUrl ?? openInNewTab)(session.url);
585
+ return await this.poll(sku, session.sessionId, endUserRef, options);
586
+ }
587
+ finally {
588
+ this.active = null;
589
+ }
590
+ }
591
+ /** Finishes a checkout that was started before a restart; null when there is nothing to resume. */
592
+ async resumePending() {
593
+ const raw = (await this.options.storage.get(this.pendingKey));
594
+ if (!raw || typeof raw.sessionId !== 'string' || typeof raw.sku !== 'string')
595
+ return null;
596
+ const expires = Date.parse(raw.expiresAt ?? '');
597
+ if (!Number.isFinite(expires) || expires + PENDING_GRACE_MS < this.now()) {
598
+ await this.options.storage.remove(this.pendingKey);
599
+ return null;
600
+ }
601
+ const endUserRef = await this.options.getEndUserRef();
602
+ let claim;
603
+ try {
604
+ claim = await this.options.api.claimSession(raw.sessionId, endUserRef);
605
+ }
606
+ catch (error) {
607
+ logger.debug('could not resume pending checkout', error);
608
+ return null;
609
+ }
610
+ return this.settle(claim, raw.sku, raw.sessionId);
611
+ }
612
+ async poll(sku, sessionId, endUserRef, options) {
613
+ const interval = options.pollIntervalMs ?? CHECKOUT_POLL_INTERVAL_MS;
614
+ const deadline = this.now() + (options.timeoutMs ?? CHECKOUT_TIMEOUT_MS);
615
+ const sleeper = interruptibleSleep();
616
+ const stopFocus = onFocusRegained(() => sleeper.wake());
617
+ let delay = interval;
618
+ let errorBackoff = 0;
619
+ try {
620
+ for (;;) {
621
+ await sleeper.sleep(delay);
622
+ if (this.now() >= deadline)
623
+ return { state: 'timeout', sku, sessionId };
624
+ let claim;
625
+ try {
626
+ claim = await this.options.api.claimSession(sessionId, endUserRef);
627
+ }
628
+ catch (error) {
629
+ const err = ExtenshiPayError.from(error);
630
+ if (err.code === ERROR_CODES.RATE_LIMITED) {
631
+ delay = (err.retryAfterSec ?? 5) * 1000;
632
+ }
633
+ else if (err.code === ERROR_CODES.NETWORK_ERROR ||
634
+ err.code === ERROR_CODES.TIMEOUT ||
635
+ err.code === ERROR_CODES.GATEWAY_UNAVAILABLE) {
636
+ errorBackoff = Math.min(errorBackoff ? errorBackoff * 2 : interval, MAX_ERROR_BACKOFF_MS);
637
+ delay = errorBackoff;
638
+ }
639
+ else {
640
+ await this.options.storage.remove(this.pendingKey);
641
+ throw err;
642
+ }
643
+ continue;
644
+ }
645
+ errorBackoff = 0;
646
+ delay = interval;
647
+ const result = await this.settle(claim, sku, sessionId);
648
+ if (result)
649
+ return result;
650
+ }
651
+ }
652
+ finally {
653
+ stopFocus();
654
+ }
655
+ }
656
+ async settle(claim, sku, sessionId) {
657
+ switch (claim.state) {
658
+ case 'pending':
659
+ return null;
660
+ case 'complete': {
661
+ const entitlement = await this.options.onComplete(claim.entitlement);
662
+ await this.options.storage.remove(this.pendingKey);
663
+ this.options.emit('checkout:completed', { sku, sessionId, entitlement });
664
+ return { state: 'complete', sku, sessionId, entitlement };
665
+ }
666
+ case 'canceled':
667
+ await this.options.storage.remove(this.pendingKey);
668
+ this.options.emit('checkout:canceled', { sku, sessionId });
669
+ return { state: 'canceled', sku, sessionId };
670
+ case 'expired':
671
+ await this.options.storage.remove(this.pendingKey);
672
+ this.options.emit('checkout:expired', { sku, sessionId });
673
+ return { state: 'expired', sku, sessionId };
674
+ default:
675
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Unknown checkout claim state');
676
+ }
677
+ }
678
+ }
679
+
680
+ var checkout = /*#__PURE__*/Object.freeze({
681
+ __proto__: null,
682
+ CHECKOUT_POLL_INTERVAL_MS: CHECKOUT_POLL_INTERVAL_MS,
683
+ CHECKOUT_TIMEOUT_MS: CHECKOUT_TIMEOUT_MS,
684
+ CheckoutManager: CheckoutManager,
685
+ openInNewTab: openInNewTab
686
+ });
687
+
688
+ /** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
689
+ const LIVE_STATUSES = new Set(['active', 'grace']);
690
+ function isLive(item) {
691
+ return LIVE_STATUSES.has(item.status);
692
+ }
693
+ /** An item past its `expiresAt` reads as expired without a network round-trip. */
694
+ function applyLocalExpiry(items, now = Date.now()) {
695
+ return items.map((item) => {
696
+ if (!isLive(item) || !item.expiresAt)
697
+ return item;
698
+ const expires = Date.parse(item.expiresAt);
699
+ return Number.isFinite(expires) && expires <= now ? { ...item, status: 'expired' } : item;
700
+ });
701
+ }
702
+ function collectFeatures(items) {
703
+ const features = new Set();
704
+ for (const item of items) {
705
+ if (!isLive(item))
706
+ continue;
707
+ for (const feature of item.features)
708
+ features.add(feature);
709
+ }
710
+ return [...features];
711
+ }
712
+ function isEntitled(entitlement, sku) {
713
+ return (!entitlement.requiresOnlineCheck &&
714
+ entitlement.items.some((item) => isLive(item) && (sku === undefined || item.sku === sku)));
715
+ }
716
+ function hasFeature(entitlement, feature) {
717
+ return entitlement.features.includes(feature);
718
+ }
719
+ function checkFeatures(entitlement, features) {
720
+ const result = {};
721
+ for (const feature of features)
722
+ result[feature] = hasFeature(entitlement, feature);
723
+ return result;
724
+ }
725
+ const EMPTY_ENTITLEMENT = Object.freeze({
726
+ items: [],
727
+ features: [],
728
+ verified: false,
729
+ issuedAt: null,
730
+ fetchedAt: null,
731
+ source: 'none',
732
+ requiresOnlineCheck: false,
733
+ offlineUntil: null,
734
+ });
735
+ // Frozen empty arrays prevent consumers from changing the shared denied state.
736
+ Object.freeze(EMPTY_ENTITLEMENT.items);
737
+ Object.freeze(EMPTY_ENTITLEMENT.features);
738
+
739
+ /**
740
+ * Ed25519 verification of the entitlement projection.
741
+ *
742
+ * Tamper resistance, not DRM. Trust comes from the developer's bundled key or
743
+ * a key fetched over HTTPS, never from editable extension storage. Callers must
744
+ * deny access for both invalid and unverified envelopes outside explicit mocks.
745
+ */
746
+ function base64ToBytes(base64) {
747
+ const binary = atob(base64);
748
+ const bytes = new Uint8Array(binary.length);
749
+ for (let i = 0; i < binary.length; i++)
750
+ bytes[i] = binary.charCodeAt(i);
751
+ return bytes;
752
+ }
753
+ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
754
+ if (!envelope.signature || envelope.alg !== 'ed25519')
755
+ return 'invalid';
756
+ if (!publicKeyBase64)
757
+ return 'unverified';
758
+ const subtle = globalThis.crypto?.subtle;
759
+ if (!subtle)
760
+ return 'unverified';
761
+ let key;
762
+ try {
763
+ key = await subtle.importKey('raw', base64ToBytes(publicKeyBase64), { name: 'Ed25519' }, false, [
764
+ 'verify',
765
+ ]);
766
+ }
767
+ catch {
768
+ return 'unverified';
769
+ }
770
+ try {
771
+ const data = new TextEncoder().encode(canonicalJson(envelope.payload));
772
+ const ok = await subtle.verify('Ed25519', key, base64ToBytes(envelope.signature), data);
773
+ return ok ? 'valid' : 'invalid';
774
+ }
775
+ catch {
776
+ return 'invalid';
777
+ }
778
+ }
779
+
780
+ /**
781
+ * Entitlement cache + refresh.
782
+ *
783
+ * The cached envelope is a cache OF the server projection, never a second
784
+ * source of truth: it is verified when stored and re-verified on load (once
785
+ * the project's public key is known), served without a round-trip while the
786
+ * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired
787
+ * locally by `expiresAt`. Background refresh polls at most every 15 minutes
788
+ * and backs off exponentially on errors.
789
+ */
790
+ const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
791
+ const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
792
+ const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
793
+ // Allow small server/client clock skew without granting more than the signed age limit.
794
+ const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
795
+ const CACHE_VERSION = 1;
796
+ function isEnvelope(value) {
797
+ if (!value || typeof value !== 'object')
798
+ return false;
799
+ const env = value;
800
+ return (!!env.payload &&
801
+ typeof env.payload === 'object' &&
802
+ typeof env.payload.endUserRef === 'string' &&
803
+ Array.isArray(env.payload.entitlements) &&
804
+ typeof env.payload.issuedAt === 'string');
805
+ }
806
+ class EntitlementManager {
807
+ constructor(options) {
808
+ this.options = options;
809
+ this.held = null;
810
+ this.inflight = null;
811
+ this.timer = null;
812
+ this.refreshGeneration = 0;
813
+ this.deadlineTimer = null;
814
+ this.refreshIntervalMs = MIN_REFRESH_INTERVAL_MS;
815
+ this.backoffMs = 0;
816
+ this.autoRefresh = false;
817
+ this.online = () => {
818
+ void this.get({ force: true }).then(() => this.notifyIfChanged());
819
+ };
820
+ // Starts at the empty projection: a first load that finds nothing is not a
821
+ // change, a first load that finds a paid entitlement is.
822
+ this.lastFingerprint = canonicalJson({ items: [], requiresOnlineCheck: false });
823
+ this.now = options.now ?? (() => Date.now());
824
+ this.source = options.source ?? 'network';
825
+ }
826
+ get storageKey() {
827
+ // Keep the real cache key stable for upgrades. Simulated grants must
828
+ // neither consume nor overwrite that cache when developers switch modes.
829
+ return `extenshi-pay:${this.options.publishableKey}:entitlement${this.source === 'mock' ? ':mock' : ''}`;
830
+ }
831
+ /** Loads the persisted envelope (unverified until `reverify()`); no network. */
832
+ async load() {
833
+ const raw = await this.options.storage.get(this.storageKey);
834
+ const record = raw;
835
+ if (!record ||
836
+ record.v !== CACHE_VERSION ||
837
+ !isEnvelope(record.envelope) ||
838
+ typeof record.fetchedAt !== 'number' ||
839
+ !Number.isFinite(record.fetchedAt)) {
840
+ return null;
841
+ }
842
+ const endUserRef = await this.options.getEndUserRef();
843
+ if (record.envelope.payload.endUserRef !== endUserRef ||
844
+ (this.source !== 'mock' && record.envelope.payload.publishableKey !== this.options.publishableKey)) {
845
+ await this.options.storage.remove(this.storageKey);
846
+ return null;
847
+ }
848
+ this.held = {
849
+ envelope: JSON.parse(JSON.stringify(record.envelope)),
850
+ fetchedAt: record.fetchedAt,
851
+ verified: false,
852
+ source: this.source === 'mock' ? 'mock' : 'cache',
853
+ };
854
+ this.lastFingerprint = this.fingerprint();
855
+ return this.snapshot();
856
+ }
857
+ /** Re-checks the loaded envelope against the project's key; discards it when the signature is invalid. */
858
+ async reverify() {
859
+ if (!this.held)
860
+ return;
861
+ if (this.source === 'mock')
862
+ return;
863
+ const held = this.held;
864
+ const key = await this.safePublicKey();
865
+ const verdict = await verifyEntitlementSignature(held.envelope, key);
866
+ if (held !== this.held)
867
+ return;
868
+ if (verdict === 'invalid') {
869
+ logger.warn('cached entitlement failed signature verification; discarding');
870
+ await this.discard();
871
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
872
+ }
873
+ held.verified = verdict === 'valid';
874
+ if (!held.verified) {
875
+ throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
876
+ }
877
+ this.scheduleDeadline();
878
+ }
879
+ getCached() {
880
+ return this.held ? this.snapshot() : null;
881
+ }
882
+ isFresh() {
883
+ return (this.held !== null &&
884
+ (this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
885
+ this.now() >= this.held.fetchedAt &&
886
+ this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS));
887
+ }
888
+ async get(options = {}) {
889
+ if (!options.force && this.isFresh())
890
+ return this.snapshot();
891
+ try {
892
+ return await this.refresh();
893
+ }
894
+ catch (error) {
895
+ const err = ExtenshiPayError.from(error);
896
+ this.options.onError?.(err);
897
+ if (this.held) {
898
+ logger.debug('serving cached entitlement after refresh failure', err.code);
899
+ return this.snapshot();
900
+ }
901
+ return EMPTY_ENTITLEMENT;
902
+ }
903
+ }
904
+ /** Fetches the projection from the backend, verifies and stores it. */
905
+ refresh() {
906
+ if (!this.inflight) {
907
+ this.inflight = (async () => {
908
+ const endUserRef = await this.options.getEndUserRef();
909
+ const envelope = await this.options.api.getEntitlement(endUserRef);
910
+ return this.accept(envelope, this.source);
911
+ })().finally(() => {
912
+ this.inflight = null;
913
+ });
914
+ }
915
+ return this.inflight;
916
+ }
917
+ /** Verifies and stores an envelope obtained elsewhere (e.g. from `claimSession`). */
918
+ async accept(envelope, source = this.source) {
919
+ if (!isEnvelope(envelope)) {
920
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Malformed entitlement envelope');
921
+ }
922
+ // Detach from callers/storage: later mutation must not alter verified state.
923
+ envelope = JSON.parse(JSON.stringify(envelope));
924
+ if (this.source !== 'mock' && envelope.payload.publishableKey !== this.options.publishableKey) {
925
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement belongs to a different application or lacks a signed application scope');
926
+ }
927
+ const endUserRef = await this.options.getEndUserRef();
928
+ if (envelope.payload.endUserRef !== endUserRef) {
929
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
930
+ }
931
+ const verdict = this.source === 'mock'
932
+ ? 'unverified'
933
+ : await verifyEntitlementSignature(envelope, await this.safePublicKey());
934
+ if (verdict === 'invalid') {
935
+ await this.discard();
936
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
937
+ }
938
+ if (verdict !== 'valid' && this.source !== 'mock') {
939
+ throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
940
+ }
941
+ const fetchedAt = this.now();
942
+ const issuedAt = Date.parse(envelope.payload.issuedAt);
943
+ if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
944
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
945
+ }
946
+ this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
947
+ const record = { v: CACHE_VERSION, envelope, fetchedAt };
948
+ await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
949
+ this.backoffMs = 0;
950
+ this.scheduleDeadline();
951
+ this.notifyIfChanged();
952
+ return this.snapshot();
953
+ }
954
+ /** Drain an older installation refresh before changing identity. */
955
+ async settleRefresh() {
956
+ await this.inflight?.catch(() => undefined);
957
+ }
958
+ async clear() {
959
+ this.held = null;
960
+ this.scheduleDeadline();
961
+ this.lastFingerprint = null;
962
+ await this.options.storage.remove(this.storageKey);
963
+ }
964
+ startAutoRefresh(intervalMs = Math.max(this.options.cacheTtlMs, MIN_REFRESH_INTERVAL_MS)) {
965
+ this.stopAutoRefresh();
966
+ this.autoRefresh = true;
967
+ globalThis.addEventListener?.('online', this.online);
968
+ this.refreshIntervalMs = Math.max(intervalMs, MIN_REFRESH_INTERVAL_MS);
969
+ this.schedule(this.refreshIntervalMs);
970
+ this.scheduleDeadline();
971
+ }
972
+ stopAutoRefresh() {
973
+ this.autoRefresh = false;
974
+ globalThis.removeEventListener?.('online', this.online);
975
+ this.refreshGeneration++;
976
+ if (this.deadlineTimer !== null)
977
+ clearTimeout(this.deadlineTimer);
978
+ this.deadlineTimer = null;
979
+ if (this.timer !== null)
980
+ clearTimeout(this.timer);
981
+ this.timer = null;
982
+ }
983
+ scheduleDeadline() {
984
+ if (this.deadlineTimer !== null)
985
+ clearTimeout(this.deadlineTimer);
986
+ this.deadlineTimer = null;
987
+ if (!this.autoRefresh || !this.held || !this.held.verified || this.source === 'mock')
988
+ return;
989
+ const now = this.now();
990
+ if (now >= this.offlineDeadline())
991
+ return;
992
+ const deadlines = [
993
+ this.offlineDeadline(),
994
+ ...this.held.envelope.payload.entitlements
995
+ .filter((item) => item.status === 'active' || item.status === 'grace')
996
+ .map((item) => (item.expiresAt ? Date.parse(item.expiresAt) : NaN)),
997
+ ];
998
+ const remaining = Math.min(...deadlines.filter((deadline) => deadline > now)) - now;
999
+ if (!Number.isFinite(remaining) || remaining <= 0)
1000
+ return;
1001
+ this.deadlineTimer = setTimeout(() => {
1002
+ this.deadlineTimer = null;
1003
+ this.notifyIfChanged();
1004
+ this.scheduleDeadline();
1005
+ }, remaining);
1006
+ }
1007
+ schedule(delayMs) {
1008
+ const generation = this.refreshGeneration;
1009
+ this.timer = setTimeout(async () => {
1010
+ this.timer = null;
1011
+ try {
1012
+ await this.refresh();
1013
+ if (generation !== this.refreshGeneration)
1014
+ return;
1015
+ this.schedule(this.refreshIntervalMs);
1016
+ }
1017
+ catch (error) {
1018
+ if (generation !== this.refreshGeneration)
1019
+ return;
1020
+ this.options.onError?.(ExtenshiPayError.from(error));
1021
+ this.backoffMs = Math.min(this.backoffMs ? this.backoffMs * 2 : this.refreshIntervalMs, MAX_REFRESH_BACKOFF_MS);
1022
+ this.schedule(this.backoffMs);
1023
+ }
1024
+ }, delayMs);
1025
+ }
1026
+ async safePublicKey() {
1027
+ try {
1028
+ return await this.options.getPublicKey();
1029
+ }
1030
+ catch (error) {
1031
+ logger.debug('public key unavailable; entitlement stays unverified', error);
1032
+ return null;
1033
+ }
1034
+ }
1035
+ async discard() {
1036
+ this.held = null;
1037
+ this.scheduleDeadline();
1038
+ await this.options.storage.remove(this.storageKey);
1039
+ this.notifyIfChanged();
1040
+ }
1041
+ fingerprint() {
1042
+ const state = this.snapshot();
1043
+ return canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck });
1044
+ }
1045
+ notifyIfChanged() {
1046
+ const fingerprint = this.fingerprint();
1047
+ if (fingerprint === this.lastFingerprint)
1048
+ return;
1049
+ this.lastFingerprint = fingerprint;
1050
+ this.options.onChange?.(this.snapshot());
1051
+ }
1052
+ offlineDeadline() {
1053
+ if (!this.held)
1054
+ return NaN;
1055
+ // fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
1056
+ return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS;
1057
+ }
1058
+ snapshot() {
1059
+ if (!this.held)
1060
+ return EMPTY_ENTITLEMENT;
1061
+ if (this.source !== 'mock' && !this.held.verified) {
1062
+ return { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source };
1063
+ }
1064
+ const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1065
+ const hasPaidAccess = collectFeatures(items).length > 0 ||
1066
+ items.some((item) => item.status === 'active' || item.status === 'grace');
1067
+ const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
1068
+ const requiresOnlineCheck = offlineUntil !== null &&
1069
+ (!Number.isFinite(offlineUntil) ||
1070
+ this.now() >= offlineUntil ||
1071
+ this.now() < this.held.fetchedAt ||
1072
+ this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
1073
+ return {
1074
+ items,
1075
+ features: requiresOnlineCheck ? [] : collectFeatures(items),
1076
+ requiresOnlineCheck,
1077
+ offlineUntil,
1078
+ verified: this.held.verified,
1079
+ issuedAt: this.held.envelope.payload.issuedAt,
1080
+ fetchedAt: this.held.fetchedAt,
1081
+ source: this.held.source,
1082
+ };
1083
+ }
1084
+ }
1085
+
1086
+ /**
1087
+ * Persistent key/value storage for the SDK's own namespace.
1088
+ *
1089
+ * Preference order: `chrome.storage.local` (Chrome/Edge), `browser.storage.local`
1090
+ * (Firefox), `localStorage` (non-extension contexts such as a dev page), then
1091
+ * memory. Both promise-returning (MV3, Firefox) and callback-only (MV2) storage
1092
+ * APIs are supported.
1093
+ */
1094
+ function extensionGlobals() {
1095
+ return globalThis;
1096
+ }
1097
+ function isThenable(value) {
1098
+ return !!value && typeof value.then === 'function';
1099
+ }
1100
+ /** Runs a storage-area call that may either return a promise or expect a callback. */
1101
+ function areaCall(direct, withCallback) {
1102
+ const result = direct();
1103
+ if (isThenable(result))
1104
+ return result;
1105
+ return new Promise((resolve, reject) => {
1106
+ withCallback((value) => {
1107
+ const lastError = extensionGlobals().chrome?.runtime?.lastError;
1108
+ if (lastError)
1109
+ reject(new Error(lastError.message ?? 'storage error'));
1110
+ else
1111
+ resolve(value);
1112
+ });
1113
+ });
1114
+ }
1115
+ class ExtensionStorage {
1116
+ constructor(area) {
1117
+ this.area = area;
1118
+ }
1119
+ async get(key) {
1120
+ const items = await areaCall(() => this.area.get(key), (cb) => this.area.get(key, cb));
1121
+ return items?.[key];
1122
+ }
1123
+ async set(key, value) {
1124
+ await areaCall(() => this.area.set({ [key]: value }), (cb) => this.area.set({ [key]: value }, cb));
1125
+ }
1126
+ async remove(key) {
1127
+ await areaCall(() => this.area.remove(key), (cb) => this.area.remove(key, cb));
1128
+ }
1129
+ }
1130
+ class LocalStorageAdapter {
1131
+ constructor(store) {
1132
+ this.store = store;
1133
+ }
1134
+ async get(key) {
1135
+ const raw = this.store.getItem(key);
1136
+ if (raw === null)
1137
+ return undefined;
1138
+ try {
1139
+ return JSON.parse(raw);
1140
+ }
1141
+ catch {
1142
+ return undefined;
1143
+ }
1144
+ }
1145
+ async set(key, value) {
1146
+ this.store.setItem(key, JSON.stringify(value));
1147
+ }
1148
+ async remove(key) {
1149
+ this.store.removeItem(key);
1150
+ }
1151
+ }
1152
+ class MemoryStorage {
1153
+ constructor() {
1154
+ this.map = new Map();
1155
+ }
1156
+ async get(key) {
1157
+ return this.map.get(key);
1158
+ }
1159
+ async set(key, value) {
1160
+ this.map.set(key, value);
1161
+ }
1162
+ async remove(key) {
1163
+ this.map.delete(key);
1164
+ }
1165
+ }
1166
+ function createStorage() {
1167
+ const g = extensionGlobals();
1168
+ const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
1169
+ if (area)
1170
+ return new ExtensionStorage(area);
1171
+ try {
1172
+ const store = globalThis.localStorage;
1173
+ if (store && typeof store.getItem === 'function')
1174
+ return new LocalStorageAdapter(store);
1175
+ }
1176
+ catch {
1177
+ // Access to localStorage can throw in sandboxed frames.
1178
+ }
1179
+ return new MemoryStorage();
1180
+ }
1181
+
1182
+ /** storage.local is exposed to content scripts by default. Never put a recovery proof there. */
1183
+ function createRecoveryStorage() {
1184
+ const g = globalThis;
1185
+ const extension = g.chrome?.tabs ? g.chrome : g.browser?.tabs ? g.browser : null;
1186
+ return extension?.storage?.session ? new ExtensionStorage(extension.storage.session) : new MemoryStorage();
1187
+ }
1188
+ class RecoveryManager {
1189
+ constructor(options) {
1190
+ this.options = options;
1191
+ this.active = false;
1192
+ this.stopped = false;
1193
+ this.wake = null;
1194
+ }
1195
+ get pendingKey() {
1196
+ return `extenshi-pay:${this.options.publishableKey}:pendingRestore`;
1197
+ }
1198
+ isActive() {
1199
+ return this.active;
1200
+ }
1201
+ stop() {
1202
+ this.stopped = true;
1203
+ this.wake?.();
1204
+ }
1205
+ async open(options = {}) {
1206
+ if (this.active)
1207
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is already in progress');
1208
+ this.active = true;
1209
+ this.stopped = false;
1210
+ try {
1211
+ // A caller from a content script must route the action to its own background;
1212
+ // never return this manager's internal state through that message bridge.
1213
+ const g = globalThis;
1214
+ if ((g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs))
1215
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Start recovery in an extension page or background context');
1216
+ const cryptoApi = globalThis.crypto;
1217
+ if (!cryptoApi?.subtle)
1218
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Secure recovery is unavailable in this browser');
1219
+ const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
1220
+ const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
1221
+ const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
1222
+ const created = await this.options.api.createRestoreSession(challenge);
1223
+ if (!Number.isFinite(Date.parse(created.expiresAt)))
1224
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
1225
+ const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
1226
+ await this.options.storage.set(this.pendingKey, pending);
1227
+ await (options.openUrl ?? this.options.openUrl ?? openInNewTab)(created.url);
1228
+ return await this.poll(pending, options);
1229
+ }
1230
+ finally {
1231
+ this.active = false;
1232
+ }
1233
+ }
1234
+ async resumePending() {
1235
+ if (this.active || this.stopped)
1236
+ return null;
1237
+ const raw = (await this.options.storage.get(this.pendingKey));
1238
+ if (!raw || this.active || this.stopped)
1239
+ return null;
1240
+ if (typeof raw.sessionId !== 'string' ||
1241
+ typeof raw.claimSecret !== 'string' ||
1242
+ !/^[a-f0-9]{64}$/.test(raw.claimSecret) ||
1243
+ !Number.isFinite(Date.parse(raw.expiresAt ?? ''))) {
1244
+ await this.options.storage.remove(this.pendingKey);
1245
+ return null;
1246
+ }
1247
+ this.active = true;
1248
+ this.stopped = false;
1249
+ try {
1250
+ return await this.poll(raw, {});
1251
+ }
1252
+ finally {
1253
+ this.active = false;
1254
+ }
1255
+ }
1256
+ async poll(pending, options) {
1257
+ const now = this.options.now ?? Date.now;
1258
+ const expires = Date.parse(pending.expiresAt);
1259
+ const deadline = Math.min(expires, now() + (options.timeoutMs ?? 10 * 60 * 1000));
1260
+ let delay = 0;
1261
+ while (!this.stopped && !options.signal?.aborted && now() < deadline) {
1262
+ if (delay)
1263
+ await new Promise((resolve) => {
1264
+ const done = () => {
1265
+ clearTimeout(timer);
1266
+ options.signal?.removeEventListener('abort', done);
1267
+ this.wake = null;
1268
+ resolve();
1269
+ };
1270
+ const timer = setTimeout(done, Math.min(delay, Math.max(0, deadline - now())));
1271
+ this.wake = done;
1272
+ options.signal?.addEventListener('abort', done, { once: true });
1273
+ });
1274
+ if (this.stopped || options.signal?.aborted || now() >= deadline)
1275
+ break;
1276
+ try {
1277
+ const claim = await this.options.api.claimRestoreSession(pending.sessionId, pending.claimSecret);
1278
+ if (this.stopped || options.signal?.aborted)
1279
+ break;
1280
+ if (claim.state === 'complete') {
1281
+ const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
1282
+ await this.options.storage.remove(this.pendingKey);
1283
+ return { state: 'complete', entitlement };
1284
+ }
1285
+ if (claim.state !== 'pending')
1286
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
1287
+ delay = Math.max(100, options.pollIntervalMs ?? 2000);
1288
+ }
1289
+ catch (error) {
1290
+ const err = ExtenshiPayError.from(error);
1291
+ if (![
1292
+ ERROR_CODES.NETWORK_ERROR,
1293
+ ERROR_CODES.TIMEOUT,
1294
+ ERROR_CODES.GATEWAY_UNAVAILABLE,
1295
+ ERROR_CODES.RATE_LIMITED,
1296
+ ].some((code) => code === err.code))
1297
+ throw err;
1298
+ delay = Math.max(2000, (err.retryAfterSec ?? 5) * 1000);
1299
+ }
1300
+ }
1301
+ if (now() >= expires)
1302
+ await this.options.storage.remove(this.pendingKey);
1303
+ return {
1304
+ state: this.stopped || options.signal?.aborted ? 'canceled' : now() >= expires ? 'expired' : 'timeout',
1305
+ };
1306
+ }
1307
+ }
1308
+
1309
+ /** Kept in sync with package.json by tests/unit/version.test.ts. */
1310
+ const VERSION = '0.7.0';
1311
+
1312
+ const DEFAULT_API_URL = 'https://bff.extenshi.io';
1313
+ const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
1314
+ const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1315
+
1316
+ const ENVIRONMENTS = new Set(['production', 'sandbox', 'development']);
1317
+ const LOG_LEVELS = new Set(['silent', 'error', 'warn', 'info', 'debug']);
1318
+ const THEME_MODES = new Set(['light', 'dark', 'auto']);
1319
+ /** Same shape the BFF accepts (`en`, `de-DE`, `zh-Hant`). */
1320
+ const LOCALE_RE = /^[a-z]{2}(-[A-Za-z]{2,4})?$/;
1321
+ function isHttpUrl(value) {
1322
+ try {
1323
+ const url = new URL(value);
1324
+ return url.protocol === 'https:' || url.protocol === 'http:';
1325
+ }
1326
+ catch {
1327
+ return false;
1328
+ }
1329
+ }
1330
+ function resolveConfig(input) {
1331
+ const errors = [];
1332
+ if (!input || typeof input !== 'object') {
1333
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, 'ExtenshiPay config must be an object');
1334
+ }
1335
+ if (!isPayPublishableKey(input.publishableKey)) {
1336
+ errors.push('publishableKey must look like pk_ext_<32 hex characters>');
1337
+ }
1338
+ const apiUrl = (input.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
1339
+ if (!isHttpUrl(apiUrl))
1340
+ errors.push('apiUrl must be an http(s) URL');
1341
+ const entitlementPublicKey = input.entitlementPublicKey ?? null;
1342
+ if (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {
1343
+ errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
1344
+ }
1345
+ const environment = input.environment ?? 'production';
1346
+ if (!ENVIRONMENTS.has(environment))
1347
+ errors.push('environment must be production, sandbox or development');
1348
+ const logLevel = input.logLevel ?? 'warn';
1349
+ if (!LOG_LEVELS.has(logLevel))
1350
+ errors.push('logLevel must be silent, error, warn, info or debug');
1351
+ const cacheTtlMs = input.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
1352
+ if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_CACHE_TTL_MS) {
1353
+ errors.push(`cacheTtlMs must be between 0 and ${MAX_CACHE_TTL_MS}`);
1354
+ }
1355
+ const locale = input.locale ?? null;
1356
+ if (locale !== null && !LOCALE_RE.test(locale))
1357
+ errors.push('locale must be a BCP-47 tag such as en or de-DE');
1358
+ const theme = input.theme ?? {};
1359
+ if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
1360
+ errors.push('theme.mode must be light, dark or auto');
1361
+ if (input.mock &&
1362
+ input.mockData !== undefined &&
1363
+ (typeof input.mockData !== 'object' || input.mockData === null)) {
1364
+ errors.push('mockData must be an object');
1365
+ }
1366
+ if (errors.length > 0) {
1367
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_CONFIG, `Invalid ExtenshiPay config: ${errors.join('; ')}`);
1368
+ }
1369
+ return {
1370
+ publishableKey: input.publishableKey,
1371
+ apiUrl,
1372
+ entitlementPublicKey,
1373
+ environment,
1374
+ debug: input.debug === true,
1375
+ logLevel,
1376
+ cacheTtlMs,
1377
+ locale,
1378
+ mock: input.mock === true,
1379
+ mockData: input.mock ? (input.mockData ?? {}) : null,
1380
+ theme,
1381
+ };
1382
+ }
1383
+
1384
+ class EventEmitter {
1385
+ constructor() {
1386
+ this.listeners = new Map();
1387
+ }
1388
+ on(event, listener) {
1389
+ let set = this.listeners.get(event);
1390
+ if (!set) {
1391
+ set = new Set();
1392
+ this.listeners.set(event, set);
1393
+ }
1394
+ set.add(listener);
1395
+ return () => this.off(event, listener);
1396
+ }
1397
+ once(event, listener) {
1398
+ const off = this.on(event, (payload) => {
1399
+ off();
1400
+ listener(payload);
1401
+ });
1402
+ return off;
1403
+ }
1404
+ off(event, listener) {
1405
+ this.listeners.get(event)?.delete(listener);
1406
+ }
1407
+ emit(event, payload) {
1408
+ const set = this.listeners.get(event);
1409
+ if (!set)
1410
+ return;
1411
+ for (const listener of [...set]) {
1412
+ const fn = listener;
1413
+ try {
1414
+ fn(payload);
1415
+ }
1416
+ catch (error) {
1417
+ logger.error(`listener for "${String(event)}" threw`, error);
1418
+ }
1419
+ }
1420
+ }
1421
+ removeAll() {
1422
+ this.listeners.clear();
1423
+ }
1424
+ }
1425
+
1426
+ /**
1427
+ * `ExtenshiPayLite` — entitlement, feature gating and hosted checkout, without
1428
+ * the paywall UI. This is what the `lite` bundle exports; the full `ExtenshiPay`
1429
+ * extends it with `getOffer()` / `showPaywall()`.
1430
+ *
1431
+ * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
1432
+ * `locale` and checkout session IDs. Explicit recovery also sends its session ID,
1433
+ * challenge and claim secret (POST body). Email stays on the hosted page.
1434
+ */
1435
+ /** Server-side offer cache is 5 min; mirror it in memory. */
1436
+ const OFFER_TTL_MS = 5 * 60 * 1000;
1437
+ class ExtenshiPayLite {
1438
+ constructor(config, deps = {}) {
1439
+ this.emitter = new EventEmitter();
1440
+ this.endUserRef = null;
1441
+ this.endUserRefPromise = null;
1442
+ this.offer = null;
1443
+ this.offerInflight = null;
1444
+ this.readyPromise = null;
1445
+ this.destroyed = false;
1446
+ this.config = resolveConfig(config);
1447
+ logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
1448
+ this.now = deps.now ?? (() => Date.now());
1449
+ this.storage = deps.storage ?? createStorage();
1450
+ const transport = deps.transport ??
1451
+ (this.config.mock
1452
+ ? new MockTransport(this.config.mockData ?? {})
1453
+ : new HttpTransport({ apiUrl: this.config.apiUrl, fetchImpl: deps.fetch }));
1454
+ this.api = new PayApi(transport, this.config.publishableKey);
1455
+ this.entitlements = new EntitlementManager({
1456
+ api: this.api,
1457
+ storage: this.storage,
1458
+ publishableKey: this.config.publishableKey,
1459
+ cacheTtlMs: this.config.cacheTtlMs,
1460
+ source: this.config.mock ? 'mock' : 'network',
1461
+ getEndUserRef: () => this.getEndUserRef(),
1462
+ getPublicKey: () => this.getPublicKey(),
1463
+ onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
1464
+ onError: (error) => this.reportError(error),
1465
+ now: this.now,
1466
+ });
1467
+ this.checkout = new CheckoutManager({
1468
+ api: this.api,
1469
+ storage: this.storage,
1470
+ publishableKey: this.config.publishableKey,
1471
+ locale: this.config.locale,
1472
+ getEndUserRef: () => this.getEndUserRef(),
1473
+ onComplete: (envelope) => this.entitlements.accept(envelope),
1474
+ emit: (event, payload) => this.emitter.emit(event, payload),
1475
+ // Mock checkouts complete on their own; never open a tab to a mock URL.
1476
+ openUrl: deps.openUrl ??
1477
+ (this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
1478
+ now: this.now,
1479
+ });
1480
+ this.recovery = new RecoveryManager({
1481
+ api: this.api,
1482
+ publishableKey: this.config.publishableKey,
1483
+ storage: deps.recoveryStorage ?? createRecoveryStorage(),
1484
+ openUrl: deps.openUrl,
1485
+ now: this.now,
1486
+ onComplete: async (ref, envelope) => {
1487
+ if (!PAY_END_USER_REF_RE.test(ref) ||
1488
+ envelope?.payload?.endUserRef !== ref ||
1489
+ envelope.payload.publishableKey !== this.config.publishableKey ||
1490
+ !Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
1491
+ Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
1492
+ (await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid')
1493
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
1494
+ this.entitlements.stopAutoRefresh();
1495
+ try {
1496
+ await this.entitlements.settleRefresh();
1497
+ if (this.destroyed)
1498
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery was stopped');
1499
+ await this.storage.set(END_USER_REF_STORAGE_KEY, ref);
1500
+ this.endUserRef = ref;
1501
+ this.endUserRefPromise = null;
1502
+ await this.entitlements.clear();
1503
+ return await this.entitlements.accept(envelope);
1504
+ }
1505
+ finally {
1506
+ if (!this.destroyed)
1507
+ this.entitlements.startAutoRefresh();
1508
+ }
1509
+ },
1510
+ });
1511
+ if (config.onError)
1512
+ this.emitter.on('error', config.onError);
1513
+ if (config.onReady)
1514
+ this.emitter.once('ready', config.onReady);
1515
+ }
1516
+ get version() {
1517
+ return VERSION;
1518
+ }
1519
+ /**
1520
+ * Mints/loads `endUserRef`, loads the cached entitlement, re-verifies it and
1521
+ * refreshes it when stale. Resolves once `isPaid()` can answer; network
1522
+ * failures fall back to the cache and are reported through `error`.
1523
+ */
1524
+ initialize() {
1525
+ if (!this.readyPromise)
1526
+ this.readyPromise = this.doInitialize();
1527
+ return this.readyPromise;
1528
+ }
1529
+ async doInitialize() {
1530
+ const endUserRef = await this.getEndUserRef();
1531
+ await this.entitlements.load();
1532
+ try {
1533
+ await this.entitlements.reverify();
1534
+ }
1535
+ catch (error) {
1536
+ this.reportError(error);
1537
+ }
1538
+ if (!this.entitlements.isFresh())
1539
+ await this.entitlements.get({ force: true });
1540
+ this.emitter.emit('ready', { endUserRef });
1541
+ void this.afterReady();
1542
+ }
1543
+ async afterReady() {
1544
+ if (this.destroyed)
1545
+ return;
1546
+ try {
1547
+ await this.checkout.resumePending();
1548
+ if (this.destroyed)
1549
+ return;
1550
+ await this.recovery.resumePending();
1551
+ }
1552
+ catch (error) {
1553
+ this.reportError(error);
1554
+ }
1555
+ if (!this.destroyed)
1556
+ this.entitlements.startAutoRefresh();
1557
+ }
1558
+ /** The anonymous, random id this install is known by. */
1559
+ getEndUserRef() {
1560
+ if (this.endUserRef)
1561
+ return Promise.resolve(this.endUserRef);
1562
+ if (!this.endUserRefPromise) {
1563
+ this.endUserRefPromise = getOrCreateEndUserRef(this.storage).then((ref) => {
1564
+ this.endUserRef = ref;
1565
+ return ref;
1566
+ });
1567
+ }
1568
+ return this.endUserRefPromise;
1569
+ }
1570
+ getCachedEntitlement() {
1571
+ return this.entitlements.getCached();
1572
+ }
1573
+ async getEntitlement(options = {}) {
1574
+ await this.initialize();
1575
+ return this.entitlements.get(options);
1576
+ }
1577
+ /** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
1578
+ async isPaid(sku) {
1579
+ return isEntitled(await this.getEntitlement(), sku);
1580
+ }
1581
+ async hasFeature(feature) {
1582
+ return hasFeature(await this.getEntitlement(), feature);
1583
+ }
1584
+ async checkFeatures(features) {
1585
+ return checkFeatures(await this.getEntitlement(), features);
1586
+ }
1587
+ /** Resolves true when the feature is (or becomes) unlocked. */
1588
+ async requireFeature(feature, options = {}) {
1589
+ if (await this.hasFeature(feature)) {
1590
+ options.onUnlock?.();
1591
+ return true;
1592
+ }
1593
+ const unlocked = await this.onFeatureLocked(feature, options);
1594
+ if (unlocked)
1595
+ options.onUnlock?.();
1596
+ else
1597
+ options.onCancel?.();
1598
+ return unlocked;
1599
+ }
1600
+ /** Lite has no UI: a locked feature stays locked. The full SDK shows the paywall here. */
1601
+ async onFeatureLocked(_feature, _options) {
1602
+ return false;
1603
+ }
1604
+ /** Opens hosted checkout for `sku` in a new tab and resolves when the session settles. */
1605
+ async openCheckout(sku, options = {}) {
1606
+ await this.initialize();
1607
+ try {
1608
+ if (this.recovery.isActive())
1609
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Recovery is in progress');
1610
+ return await this.checkout.open(sku, options);
1611
+ }
1612
+ catch (error) {
1613
+ throw this.reportError(error);
1614
+ }
1615
+ }
1616
+ /** Opens email verification on the hosted page. No email is collected inside the extension. */
1617
+ async restorePurchase(options = {}) {
1618
+ await this.initialize();
1619
+ try {
1620
+ if (this.checkout.isActive())
1621
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Checkout is in progress');
1622
+ return await this.recovery.open(options);
1623
+ }
1624
+ catch (error) {
1625
+ throw this.reportError(error);
1626
+ }
1627
+ }
1628
+ /** Read-only license view. Entitlements retain cache/signature/offline semantics. */
1629
+ async getLicenseSummary(options = {}) {
1630
+ await this.initialize();
1631
+ let offer = null;
1632
+ try {
1633
+ offer = await this.fetchOffer(options.force);
1634
+ }
1635
+ catch {
1636
+ /* Offline: do not invent seller details. */
1637
+ }
1638
+ return {
1639
+ projectName: offer?.projectName ?? null,
1640
+ seller: offer?.seller ?? null,
1641
+ entitlement: await this.getEntitlement(options),
1642
+ recoveryEnabled: offer?.recoveryEnabled === true,
1643
+ };
1644
+ }
1645
+ /** Opens the provider's self-service portal; resolves null when the provider has none. */
1646
+ async openCustomerPortal(options = {}) {
1647
+ await this.initialize();
1648
+ try {
1649
+ const endUserRef = await this.getEndUserRef();
1650
+ let result = await this.api.getPortalUrl(endUserRef);
1651
+ if (this.destroyed)
1652
+ return null;
1653
+ if (result.accounts?.length) {
1654
+ if (!options.selectAccount)
1655
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Choose a billing profile using selectAccount');
1656
+ const customerId = await options.selectAccount(result.accounts);
1657
+ if (customerId === null || this.destroyed)
1658
+ return null;
1659
+ if (!result.accounts.some((a) => a.id === customerId))
1660
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Invalid billing profile');
1661
+ // Recovery may replace this installation while the selector is open.
1662
+ if (endUserRef !== (await this.getEndUserRef()))
1663
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Installation changed; open the portal again');
1664
+ result = await this.api.getPortalUrl(endUserRef, customerId);
1665
+ }
1666
+ if (this.destroyed)
1667
+ return null;
1668
+ const { url } = result;
1669
+ if (url)
1670
+ await (options.openUrl ?? (await Promise.resolve().then(function () { return checkout; })).openInNewTab)(url);
1671
+ return url;
1672
+ }
1673
+ catch (error) {
1674
+ throw this.reportError(error);
1675
+ }
1676
+ }
1677
+ on(event, listener) {
1678
+ return this.emitter.on(event, listener);
1679
+ }
1680
+ once(event, listener) {
1681
+ return this.emitter.once(event, listener);
1682
+ }
1683
+ off(event, listener) {
1684
+ this.emitter.off(event, listener);
1685
+ }
1686
+ onEntitlementChange(listener) {
1687
+ return this.emitter.on('entitlement:changed', listener);
1688
+ }
1689
+ async clearCache() {
1690
+ this.offer = null;
1691
+ await this.entitlements.clear();
1692
+ }
1693
+ /** Stops background refresh and drops listeners. */
1694
+ destroy() {
1695
+ this.destroyed = true;
1696
+ this.recovery.stop();
1697
+ this.entitlements.stopAutoRefresh();
1698
+ this.emitter.removeAll();
1699
+ }
1700
+ /** Offer + signing key. Public in the full SDK (`getOffer`), internal here. */
1701
+ fetchOffer(force = false) {
1702
+ if (!force && this.offer && this.now() - this.offer.fetchedAt < OFFER_TTL_MS) {
1703
+ return Promise.resolve(this.offer.value);
1704
+ }
1705
+ if (!this.offerInflight) {
1706
+ this.offerInflight = this.api
1707
+ .getOffer(this.config.locale)
1708
+ .then((value) => {
1709
+ this.offer = { value, fetchedAt: this.now() };
1710
+ return value;
1711
+ })
1712
+ .finally(() => {
1713
+ this.offerInflight = null;
1714
+ });
1715
+ }
1716
+ return this.offerInflight;
1717
+ }
1718
+ async getPublicKey() {
1719
+ return this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey;
1720
+ }
1721
+ reportError(error) {
1722
+ const err = ExtenshiPayError.from(error);
1723
+ logger.warn(`${err.code}: ${err.message}`);
1724
+ this.emitter.emit('error', err);
1725
+ return err;
1726
+ }
1727
+ }
1728
+ ExtenshiPayLite.version = VERSION;
1729
+
1730
+ // Lite entry point: entitlement + feature gating + hosted checkout, no paywall UI, no getOffer().
1731
+
1732
+ exports.ERROR_CODES = ERROR_CODES;
1733
+ exports.ExtenshiPay = ExtenshiPayLite;
1734
+ exports.ExtenshiPayError = ExtenshiPayError;
1735
+ exports.ExtenshiPayLite = ExtenshiPayLite;
1736
+ exports.MockTransport = MockTransport;
1737
+ exports.VERSION = VERSION;
1738
+ exports.default = ExtenshiPayLite;
1739
+
1740
+ Object.defineProperty(exports, '__esModule', { value: true });
1741
+
1742
+ }));
1743
+ //# sourceMappingURL=extenshi-pay-lite.js.map