@extenshi/pay 0.9.0 → 0.12.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 (74) hide show
  1. package/README.md +138 -17
  2. package/dist/api/mock.d.ts +4 -0
  3. package/dist/api/mock.d.ts.map +1 -1
  4. package/dist/api/pay-api.d.ts +9 -4
  5. package/dist/api/pay-api.d.ts.map +1 -1
  6. package/dist/core/config.d.ts.map +1 -1
  7. package/dist/core/extenshi-pay.d.ts +60 -5
  8. package/dist/core/extenshi-pay.d.ts.map +1 -1
  9. package/dist/core/index.d.ts +3 -1
  10. package/dist/core/index.d.ts.map +1 -1
  11. package/dist/core/storage.d.ts +6 -0
  12. package/dist/core/storage.d.ts.map +1 -1
  13. package/dist/core.d.mts +271 -26
  14. package/dist/core.d.ts +271 -26
  15. package/dist/core.js +589 -49
  16. package/dist/core.js.map +1 -1
  17. package/dist/core.mjs +584 -50
  18. package/dist/core.mjs.map +1 -1
  19. package/dist/extenshi-pay-lite.js +577 -49
  20. package/dist/extenshi-pay-lite.js.map +1 -1
  21. package/dist/extenshi-pay-lite.min.js +3 -3
  22. package/dist/extenshi-pay-lite.min.js.map +1 -1
  23. package/dist/extenshi-pay-lite.mjs +577 -49
  24. package/dist/extenshi-pay-lite.mjs.map +1 -1
  25. package/dist/extenshi-pay.cjs.js +694 -61
  26. package/dist/extenshi-pay.cjs.js.map +1 -1
  27. package/dist/extenshi-pay.d.ts +11 -1
  28. package/dist/extenshi-pay.d.ts.map +1 -1
  29. package/dist/extenshi-pay.js +694 -61
  30. package/dist/extenshi-pay.js.map +1 -1
  31. package/dist/extenshi-pay.min.js +3 -3
  32. package/dist/extenshi-pay.min.js.map +1 -1
  33. package/dist/extenshi-pay.min.mjs +3 -3
  34. package/dist/extenshi-pay.min.mjs.map +1 -1
  35. package/dist/extenshi-pay.mjs +689 -62
  36. package/dist/extenshi-pay.mjs.map +1 -1
  37. package/dist/index.d.mts +288 -26
  38. package/dist/index.d.ts +288 -26
  39. package/dist/lite.d.mts +214 -13
  40. package/dist/lite.d.ts +214 -13
  41. package/dist/lite.d.ts.map +1 -1
  42. package/dist/payment/cloud-backup.d.ts +35 -0
  43. package/dist/payment/cloud-backup.d.ts.map +1 -0
  44. package/dist/payment/entitlement.d.ts +21 -5
  45. package/dist/payment/entitlement.d.ts.map +1 -1
  46. package/dist/payment/recovery.d.ts +4 -2
  47. package/dist/payment/recovery.d.ts.map +1 -1
  48. package/dist/payment/signature.d.ts +29 -3
  49. package/dist/payment/signature.d.ts.map +1 -1
  50. package/dist/payment/trial.d.ts +55 -0
  51. package/dist/payment/trial.d.ts.map +1 -0
  52. package/dist/paywall/i18n.d.ts +3 -0
  53. package/dist/paywall/i18n.d.ts.map +1 -1
  54. package/dist/paywall/renderer.d.ts +7 -0
  55. package/dist/paywall/renderer.d.ts.map +1 -1
  56. package/dist/paywall.d.mts +7 -0
  57. package/dist/paywall.d.ts +7 -0
  58. package/dist/paywall.js +54 -14
  59. package/dist/paywall.js.map +1 -1
  60. package/dist/paywall.mjs +54 -14
  61. package/dist/paywall.mjs.map +1 -1
  62. package/dist/types/config.d.ts +27 -1
  63. package/dist/types/config.d.ts.map +1 -1
  64. package/dist/types/contract.d.ts +36 -0
  65. package/dist/types/contract.d.ts.map +1 -1
  66. package/dist/types/entitlement.d.ts +39 -1
  67. package/dist/types/entitlement.d.ts.map +1 -1
  68. package/dist/types/events.d.ts +5 -1
  69. package/dist/types/events.d.ts.map +1 -1
  70. package/dist/types/paywall.d.ts +10 -0
  71. package/dist/types/paywall.d.ts.map +1 -1
  72. package/dist/version.d.ts +1 -1
  73. package/dist/version.d.ts.map +1 -1
  74. package/package.json +3 -2
package/dist/core.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * ExtenshiPay SDK v0.9.0
2
+ * ExtenshiPay SDK v0.12.0
3
3
  * (c) 2026 Extenshi.io
4
4
  * Released under the MIT License.
5
- * commit bd166bf9b687f60e965d03acec7a648b42226652 · built by `rollup -c`
5
+ * commit 7f4b4e98165b3c8eb11e100b3855fee1ade7aaab · built by `rollup -c`
6
6
  */
7
7
  /**
8
8
  * Wire contract between the SDK and catalog-bff `pay.*`.
@@ -46,6 +46,8 @@ const PAY_SKU_RE = /^[a-z0-9][a-z0-9_-]{1,39}$/;
46
46
  * none — never had it
47
47
  */
48
48
  const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'];
49
+ // Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.
50
+ const PAY_REGIONAL_ACCESS_SKU = '@regional-free';
49
51
  /**
50
52
  * Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA
51
53
  * digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The
@@ -86,6 +88,14 @@ function canonicalJson(value) {
86
88
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
87
89
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
88
90
  }
91
+ /**
92
+ * `storage`: the buyer turns on the cloud copy of the extension's settings. The
93
+ * hosted page shows the storage disclosure; the claim records consent. Additive:
94
+ * a session without a purpose is a plain restore.
95
+ */
96
+ const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
97
+ /** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
98
+ const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
89
99
 
90
100
  const ERROR_CODES = {
91
101
  INVALID_CONFIG: 'INVALID_CONFIG',
@@ -157,7 +167,7 @@ async function getOrCreateEndUserRef(storage) {
157
167
  * developed with no backend: offers and entitlements come from `mockData`, a
158
168
  * mock checkout completes after `claimAfterPolls` polls and grants the SKU.
159
169
  */
160
- const DAY_MS = 24 * 60 * 60 * 1000;
170
+ const DAY_MS$1 = 24 * 60 * 60 * 1000;
161
171
  /** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
162
172
  function mockConsent(value) {
163
173
  const consent = value;
@@ -175,6 +185,10 @@ class MockTransport {
175
185
  this.claimAfterPolls = data.claimAfterPolls ?? 1;
176
186
  this.withdrawalWaiver =
177
187
  data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
188
+ this.seller = data.seller;
189
+ this.trial = null;
190
+ if (data.trial)
191
+ this.setTrial(data.trial.days, data.trial.startedAt);
178
192
  }
179
193
  async call(procedure, _kind, input) {
180
194
  switch (procedure) {
@@ -196,6 +210,14 @@ class MockTransport {
196
210
  setEntitlements(items) {
197
211
  this.entitlements = [...items];
198
212
  }
213
+ /** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
214
+ setTrial(days, startedAt = new Date().toISOString()) {
215
+ const start = Date.parse(startedAt);
216
+ this.trial =
217
+ days === null || !Number.isFinite(start)
218
+ ? null
219
+ : { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
220
+ }
199
221
  cancelSession(sessionId) {
200
222
  const session = this.sessions.get(sessionId);
201
223
  if (session)
@@ -215,6 +237,7 @@ class MockTransport {
215
237
  offers: [...this.offers],
216
238
  entitlementPublicKey: null,
217
239
  withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
240
+ ...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
218
241
  };
219
242
  }
220
243
  createCheckout(sku, withdrawalWaiver) {
@@ -252,7 +275,7 @@ class MockTransport {
252
275
  grant(sku) {
253
276
  const offer = this.offers.find((o) => o.sku === sku);
254
277
  const expiresAt = offer?.kind === 'subscription'
255
- ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
278
+ ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
256
279
  : null;
257
280
  this.entitlements = [
258
281
  ...this.entitlements.filter((item) => item.sku !== sku),
@@ -274,6 +297,7 @@ class MockTransport {
274
297
  endUserRef,
275
298
  entitlements: [...this.entitlements],
276
299
  issuedAt: new Date().toISOString(),
300
+ ...(this.trial ? { trial: { ...this.trial } } : {}),
277
301
  },
278
302
  signature: null,
279
303
  alg: null,
@@ -287,12 +311,17 @@ class PayApi {
287
311
  this.transport = transport;
288
312
  this.publishableKey = publishableKey;
289
313
  }
290
- /** `locale` opens the hosted recovery page (and its email) in the user's language. */
291
- createRestoreSession(claimChallenge, locale) {
314
+ /**
315
+ * `locale` opens the hosted recovery page (and its email) in the user's language.
316
+ * `purpose` is sent only for `storage`: a plain restore keeps the request older
317
+ * BFFs know, and their non-strict zod input strips the key anyway.
318
+ */
319
+ createRestoreSession(claimChallenge, locale, purpose) {
292
320
  return this.transport.call('pay.createRestoreSession', 'mutation', {
293
321
  publishableKey: this.publishableKey,
294
322
  claimChallenge,
295
323
  ...(locale ? { locale } : {}),
324
+ ...(purpose === 'storage' ? { purpose } : {}),
296
325
  });
297
326
  }
298
327
  claimRestoreSession(sessionId, claimSecret) {
@@ -331,10 +360,12 @@ class PayApi {
331
360
  endUserRef,
332
361
  });
333
362
  }
334
- getEntitlement(endUserRef) {
363
+ /** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
364
+ getEntitlement(endUserRef, trialStartedHint) {
335
365
  return this.transport.call('pay.getEntitlement', 'query', {
336
366
  publishableKey: this.publishableKey,
337
367
  endUserRef,
368
+ ...(trialStartedHint ? { trialStartedHint } : {}),
338
369
  });
339
370
  }
340
371
  getPortalUrl(endUserRef, customerId, locale) {
@@ -732,6 +763,118 @@ var checkout = /*#__PURE__*/Object.freeze({
732
763
  openInNewTab: openInNewTab
733
764
  });
734
765
 
766
+ /**
767
+ * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
768
+ * token: only a verified restore claim issues it; this module keeps it in the
769
+ * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
770
+ * through `cloudBackupToken()`. The token is never logged and never answered to
771
+ * a content script: route those calls to the background.
772
+ */
773
+ const REQUEST_TIMEOUT_MS = 10000;
774
+ /** True in a content script, where the token must not be handed out. */
775
+ function inContentScript() {
776
+ const g = globalThis;
777
+ return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
778
+ }
779
+ class CloudBackup {
780
+ constructor(options) {
781
+ this.options = options;
782
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
783
+ }
784
+ get storageKey() {
785
+ return `extenshi-pay:${this.options.publishableKey}:storageToken`;
786
+ }
787
+ /** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
788
+ async accept(grant) {
789
+ if (!grant || typeof grant !== 'object')
790
+ return undefined;
791
+ try {
792
+ if (grant.state === 'granted') {
793
+ if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
794
+ return undefined;
795
+ await this.options.storage.set(this.storageKey, grant.token);
796
+ return 'on';
797
+ }
798
+ if (grant.state === 'unavailable') {
799
+ await this.options.storage.remove(this.storageKey);
800
+ return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
801
+ }
802
+ }
803
+ catch {
804
+ logger.warn('cloud backup state could not be saved');
805
+ }
806
+ return undefined;
807
+ }
808
+ async token() {
809
+ this.assertTrustedContext();
810
+ const value = await this.options.storage.get(this.storageKey);
811
+ return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
812
+ }
813
+ /** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
814
+ async disable() {
815
+ const token = await this.token();
816
+ if (!token)
817
+ return;
818
+ if (!this.options.mock) {
819
+ const status = await this.request('/v1/storage/grant', token);
820
+ if (status !== 401)
821
+ this.throwUnlessOk(status);
822
+ }
823
+ await this.options.storage.remove(this.storageKey);
824
+ }
825
+ /** Deletes the buyer's cloud copy and turns the backup off on every device. */
826
+ async delete() {
827
+ const token = await this.token();
828
+ if (!token)
829
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
830
+ if (!this.options.mock) {
831
+ const status = await this.request('/v1/storage/data', token);
832
+ if (status === 401) {
833
+ // The server no longer accepts this token, so it is useless here; the copy was not deleted.
834
+ await this.options.storage.remove(this.storageKey);
835
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on the server; turn it on again to delete the cloud copy', { httpStatus: 401 });
836
+ }
837
+ this.throwUnlessOk(status);
838
+ }
839
+ await this.options.storage.remove(this.storageKey);
840
+ }
841
+ assertTrustedContext() {
842
+ if (inContentScript())
843
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
844
+ }
845
+ throwUnlessOk(status) {
846
+ if (status >= 200 && status < 300)
847
+ return;
848
+ if (status === 429)
849
+ throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
850
+ if (status >= 500)
851
+ throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
852
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
853
+ }
854
+ async request(path, token) {
855
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
856
+ const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
857
+ try {
858
+ const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
859
+ method: 'DELETE',
860
+ headers: { Authorization: `Bearer ${token}` },
861
+ credentials: 'omit',
862
+ signal: controller?.signal,
863
+ });
864
+ return response.status;
865
+ }
866
+ catch (error) {
867
+ if (controller?.signal.aborted)
868
+ throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
869
+ throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
870
+ }
871
+ finally {
872
+ if (timer !== null)
873
+ clearTimeout(timer);
874
+ }
875
+ }
876
+ }
877
+
735
878
  /** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
736
879
  const LIVE_STATUSES = new Set(['active', 'grace']);
737
880
  function isLive(item) {
@@ -786,9 +929,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
786
929
  /**
787
930
  * Ed25519 verification of the entitlement projection.
788
931
  *
789
- * Tamper resistance, not DRM. Trust comes from the developer's bundled key or
790
- * a key fetched over HTTPS, never from editable extension storage. Callers must
791
- * deny access for both invalid and unverified envelopes outside explicit mocks.
932
+ * Tamper resistance, not DRM. Callers must deny access for both invalid and
933
+ * unverified envelopes outside explicit mocks.
934
+ *
935
+ * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
936
+ * 1. the key the server returned over HTTPS in this session;
937
+ * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
938
+ * verification without a round-trip: a key read from extension storage is then never used;
939
+ * 3. without a bundled key, the server key saved in `storage.local` next to the
940
+ * license cache, so a restart with no network can still verify the cache.
941
+ * When none of them verifies an envelope the server is asked for its current key once
942
+ * (a rotated key), and that answer decides.
792
943
  */
793
944
  function base64ToBytes(base64) {
794
945
  const binary = atob(base64);
@@ -823,6 +974,140 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
823
974
  return 'invalid';
824
975
  }
825
976
  }
977
+ const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
978
+ /**
979
+ * `invalid` only when the server's current key was checked too (or the envelope carries no
980
+ * signature at all). A mismatch against known keys while the server is unreachable is
981
+ * `unverified`: it may be a rotated key, and no paid access is granted either way.
982
+ */
983
+ async function verifyWithKeys(envelope, source) {
984
+ if (!envelope.signature || envelope.alg !== 'ed25519')
985
+ return { verdict: 'invalid', key: null };
986
+ let known = [];
987
+ try {
988
+ known = await source.known();
989
+ }
990
+ catch {
991
+ known = [];
992
+ }
993
+ let mismatch = false;
994
+ for (const key of known) {
995
+ const verdict = await verifyEntitlementSignature(envelope, key);
996
+ if (verdict === 'valid')
997
+ return { verdict, key };
998
+ if (verdict === 'invalid')
999
+ mismatch = true;
1000
+ }
1001
+ let current;
1002
+ try {
1003
+ current = await source.fetchCurrent();
1004
+ }
1005
+ catch {
1006
+ return { verdict: 'unverified', key: null };
1007
+ }
1008
+ if (current && !known.includes(current)) {
1009
+ const verdict = await verifyEntitlementSignature(envelope, current);
1010
+ return { verdict, key: verdict === 'valid' ? current : null };
1011
+ }
1012
+ return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
1013
+ }
1014
+
1015
+ /**
1016
+ * The free trial an application configures on the server (`trialDays`).
1017
+ *
1018
+ * The server starts one clock per installation at its first license read and
1019
+ * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
1020
+ * the verified license like paid access does: no start date in extension
1021
+ * storage, nothing a device clock or a storage edit can move. Offline, the
1022
+ * cached license answers for up to 48 hours.
1023
+ *
1024
+ * `trial:ending` / `trial:ended` fire once per installation and trial (the
1025
+ * marker is kept in the SDK's storage), and not while the user has paid
1026
+ * access. Render state from `getTrial()`; the events are one-time notices.
1027
+ */
1028
+ const DAY_MS = 24 * 60 * 60 * 1000;
1029
+ /** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
1030
+ const MAX_TIMER_MS$1 = DAY_MS;
1031
+ /** The trial as of `clock`, or null when the license carries none (or a malformed one). */
1032
+ function trialState(trial, clock) {
1033
+ if (!trial)
1034
+ return null;
1035
+ const startedAt = Date.parse(trial.startedAt);
1036
+ const endsAt = Date.parse(trial.endsAt);
1037
+ if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
1038
+ return null;
1039
+ // The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
1040
+ const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
1041
+ const left = endsAt - now;
1042
+ return {
1043
+ active: left > 0 && clock.checked,
1044
+ startedAt: trial.startedAt,
1045
+ endsAt: trial.endsAt,
1046
+ daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
1047
+ requiresOnlineCheck: left > 0 && !clock.checked,
1048
+ };
1049
+ }
1050
+ class TrialNotifier {
1051
+ constructor(options) {
1052
+ this.options = options;
1053
+ this.timer = null;
1054
+ this.running = false;
1055
+ this.pending = Promise.resolve();
1056
+ }
1057
+ start() {
1058
+ this.running = true;
1059
+ void this.evaluate();
1060
+ }
1061
+ stop() {
1062
+ this.running = false;
1063
+ this.clearTimer();
1064
+ }
1065
+ /** Checks the held license; serialized, so two refreshes never send one event twice. */
1066
+ evaluate() {
1067
+ this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
1068
+ return this.pending;
1069
+ }
1070
+ async check() {
1071
+ if (!this.running)
1072
+ return;
1073
+ this.clearTimer();
1074
+ const trial = this.options.getTrial();
1075
+ if (!trial)
1076
+ return;
1077
+ const now = this.options.now();
1078
+ const endsAt = Date.parse(trial.endsAt);
1079
+ const endingAt = endsAt - this.options.endingDays * DAY_MS;
1080
+ const event = trial.daysLeft === 0
1081
+ ? 'trial:ended'
1082
+ : trial.active && this.options.endingDays > 0 && now >= endingAt
1083
+ ? 'trial:ending'
1084
+ : null;
1085
+ if (event && !this.options.hasPaidAccess())
1086
+ await this.send(event, trial);
1087
+ if (!this.running || trial.daysLeft === 0)
1088
+ return;
1089
+ const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
1090
+ this.timer = setTimeout(() => {
1091
+ this.timer = null;
1092
+ void this.evaluate();
1093
+ }, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
1094
+ }
1095
+ async send(event, trial) {
1096
+ const id = `${trial.startedAt}|${trial.endsAt}`;
1097
+ const field = event === 'trial:ended' ? 'ended' : 'ending';
1098
+ const stored = (await this.options.storage.get(this.options.storageKey));
1099
+ const sent = stored && typeof stored === 'object' ? stored : {};
1100
+ if (sent[field] === id || !this.running)
1101
+ return;
1102
+ await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
1103
+ this.options.emit(event, trial);
1104
+ }
1105
+ clearTimer() {
1106
+ if (this.timer !== null)
1107
+ clearTimeout(this.timer);
1108
+ this.timer = null;
1109
+ }
1110
+ }
826
1111
 
827
1112
  /**
828
1113
  * Entitlement cache + refresh.
@@ -830,13 +1115,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
830
1115
  * The cached envelope is a cache OF the server projection, never a second
831
1116
  * source of truth: it is verified when stored and re-verified on load (once
832
1117
  * the project's public key is known), served without a round-trip while the
833
- * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired
1118
+ * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
834
1119
  * locally by `expiresAt`. Background refresh polls at most every 15 minutes
835
1120
  * and backs off exponentially on errors.
836
1121
  */
837
1122
  const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
838
1123
  const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
1124
+ /** Offline allowance when the signed license names none (older servers and caches). */
839
1125
  const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
1126
+ /** Ceiling for a signed `offlineSeconds`. */
1127
+ const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
1128
+ /** `setTimeout` fires at once past this delay. */
1129
+ const MAX_TIMER_MS = 2 ** 31 - 1;
840
1130
  // Allow small server/client clock skew without granting more than the signed age limit.
841
1131
  const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
842
1132
  const CACHE_VERSION = 1;
@@ -855,6 +1145,8 @@ class EntitlementManager {
855
1145
  this.options = options;
856
1146
  this.held = null;
857
1147
  this.inflight = null;
1148
+ /** Device clock against the server's at the last license check; null within 5 minutes. */
1149
+ this.clockSkew = null;
858
1150
  this.timer = null;
859
1151
  this.refreshGeneration = 0;
860
1152
  this.deadlineTimer = null;
@@ -896,8 +1188,10 @@ class EntitlementManager {
896
1188
  envelope: JSON.parse(JSON.stringify(record.envelope)),
897
1189
  fetchedAt: record.fetchedAt,
898
1190
  verified: false,
1191
+ key: null,
899
1192
  source: this.source === 'mock' ? 'mock' : 'cache',
900
1193
  };
1194
+ this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
901
1195
  this.lastFingerprint = this.fingerprint();
902
1196
  return this.snapshot();
903
1197
  }
@@ -908,8 +1202,7 @@ class EntitlementManager {
908
1202
  if (this.source === 'mock')
909
1203
  return;
910
1204
  const held = this.held;
911
- const key = await this.safePublicKey();
912
- const verdict = await verifyEntitlementSignature(held.envelope, key);
1205
+ const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
913
1206
  if (held !== this.held)
914
1207
  return;
915
1208
  if (verdict === 'invalid') {
@@ -918,19 +1211,39 @@ class EntitlementManager {
918
1211
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
919
1212
  }
920
1213
  held.verified = verdict === 'valid';
1214
+ held.key = key;
921
1215
  if (!held.verified) {
922
1216
  throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
923
1217
  }
924
1218
  this.scheduleDeadline();
925
1219
  }
1220
+ /** The key the held license was verified with; null when there is none or it is unverified. */
1221
+ get verifiedKey() {
1222
+ return this.held?.verified ? this.held.key : null;
1223
+ }
926
1224
  getCached() {
927
1225
  return this.held ? this.snapshot() : null;
928
1226
  }
1227
+ /** The server trial in the held license; null without one, or while the license is unverified. */
1228
+ getTrial() {
1229
+ const held = this.held;
1230
+ if (!held || (this.source !== 'mock' && !held.verified))
1231
+ return null;
1232
+ const now = this.now();
1233
+ const issuedAt = Date.parse(held.envelope.payload.issuedAt);
1234
+ return trialState(held.envelope.payload.trial, {
1235
+ now,
1236
+ issuedAt,
1237
+ // The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
1238
+ checked: this.source === 'mock' ||
1239
+ (now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
1240
+ });
1241
+ }
929
1242
  isFresh() {
930
1243
  return (this.held !== null &&
931
1244
  (this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
932
1245
  this.now() >= this.held.fetchedAt &&
933
- this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS));
1246
+ this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
934
1247
  }
935
1248
  async get(options = {}) {
936
1249
  if (!options.force && this.isFresh())
@@ -945,7 +1258,7 @@ class EntitlementManager {
945
1258
  logger.debug('serving cached entitlement after refresh failure', err.code);
946
1259
  return this.snapshot();
947
1260
  }
948
- return EMPTY_ENTITLEMENT;
1261
+ return this.snapshot();
949
1262
  }
950
1263
  }
951
1264
  /** Fetches the projection from the backend, verifies and stores it. */
@@ -953,7 +1266,8 @@ class EntitlementManager {
953
1266
  if (!this.inflight) {
954
1267
  this.inflight = (async () => {
955
1268
  const endUserRef = await this.options.getEndUserRef();
956
- const envelope = await this.options.api.getEntitlement(endUserRef);
1269
+ const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
1270
+ const envelope = await this.options.api.getEntitlement(endUserRef, hint);
957
1271
  return this.accept(envelope, this.source);
958
1272
  })().finally(() => {
959
1273
  this.inflight = null;
@@ -975,9 +1289,9 @@ class EntitlementManager {
975
1289
  if (envelope.payload.endUserRef !== endUserRef) {
976
1290
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
977
1291
  }
978
- const verdict = this.source === 'mock'
979
- ? 'unverified'
980
- : await verifyEntitlementSignature(envelope, await this.safePublicKey());
1292
+ const { verdict, key } = this.source === 'mock'
1293
+ ? { verdict: 'unverified', key: null }
1294
+ : await verifyWithKeys(envelope, this.options.keys);
981
1295
  if (verdict === 'invalid') {
982
1296
  await this.discard();
983
1297
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
@@ -987,15 +1301,19 @@ class EntitlementManager {
987
1301
  }
988
1302
  const fetchedAt = this.now();
989
1303
  const issuedAt = Date.parse(envelope.payload.issuedAt);
1304
+ // A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
1305
+ if (this.source !== 'mock')
1306
+ this.measureClockSkew(fetchedAt, issuedAt);
990
1307
  if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
991
1308
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
992
1309
  }
993
- this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
1310
+ this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
994
1311
  const record = { v: CACHE_VERSION, envelope, fetchedAt };
995
1312
  await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
996
1313
  this.backoffMs = 0;
997
1314
  this.scheduleDeadline();
998
1315
  this.notifyIfChanged();
1316
+ this.options.onAccepted?.();
999
1317
  return this.snapshot();
1000
1318
  }
1001
1319
  /** Drain an older installation refresh before changing identity. */
@@ -1049,7 +1367,7 @@ class EntitlementManager {
1049
1367
  this.deadlineTimer = null;
1050
1368
  this.notifyIfChanged();
1051
1369
  this.scheduleDeadline();
1052
- }, remaining);
1370
+ }, Math.min(remaining, MAX_TIMER_MS));
1053
1371
  }
1054
1372
  schedule(delayMs) {
1055
1373
  const generation = this.refreshGeneration;
@@ -1070,14 +1388,12 @@ class EntitlementManager {
1070
1388
  }
1071
1389
  }, delayMs);
1072
1390
  }
1073
- async safePublicKey() {
1074
- try {
1075
- return await this.options.getPublicKey();
1076
- }
1077
- catch (error) {
1078
- logger.debug('public key unavailable; entitlement stays unverified', error);
1079
- return null;
1080
- }
1391
+ measureClockSkew(local, server) {
1392
+ const ms = local - server;
1393
+ this.clockSkew =
1394
+ Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
1395
+ ? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
1396
+ : null;
1081
1397
  }
1082
1398
  async discard() {
1083
1399
  this.held = null;
@@ -1087,7 +1403,13 @@ class EntitlementManager {
1087
1403
  }
1088
1404
  fingerprint() {
1089
1405
  const state = this.snapshot();
1090
- return canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck });
1406
+ return canonicalJson({
1407
+ items: state.items,
1408
+ requiresOnlineCheck: state.requiresOnlineCheck,
1409
+ ...(state.regionalFreeUntil
1410
+ ? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }
1411
+ : {}),
1412
+ });
1091
1413
  }
1092
1414
  notifyIfChanged() {
1093
1415
  const fingerprint = this.fingerprint();
@@ -1100,16 +1422,31 @@ class EntitlementManager {
1100
1422
  if (!this.held)
1101
1423
  return NaN;
1102
1424
  // fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
1103
- return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS;
1425
+ return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
1426
+ }
1427
+ /** The signed allowance of the held license, or 48 hours when it names none. */
1428
+ offlineAgeMs() {
1429
+ const seconds = this.held?.envelope.payload.offlineSeconds;
1430
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
1431
+ return MAX_OFFLINE_AGE_MS;
1432
+ return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
1104
1433
  }
1105
1434
  snapshot() {
1106
1435
  if (!this.held)
1107
- return EMPTY_ENTITLEMENT;
1436
+ return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
1108
1437
  if (this.source !== 'mock' && !this.held.verified) {
1109
- return { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source };
1110
- }
1111
- const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1112
- const hasPaidAccess = collectFeatures(items).length > 0 ||
1438
+ return {
1439
+ ...EMPTY_ENTITLEMENT,
1440
+ requiresOnlineCheck: true,
1441
+ clockSkew: this.clockSkew,
1442
+ source: this.held.source,
1443
+ };
1444
+ }
1445
+ const grants = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1446
+ const regional = grants.find((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active');
1447
+ const items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU);
1448
+ const hasPaidAccess = grants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||
1449
+ collectFeatures(items).length > 0 ||
1113
1450
  items.some((item) => item.status === 'active' || item.status === 'grace');
1114
1451
  const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
1115
1452
  const requiresOnlineCheck = offlineUntil !== null &&
@@ -1119,9 +1456,13 @@ class EntitlementManager {
1119
1456
  this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
1120
1457
  return {
1121
1458
  items,
1122
- features: requiresOnlineCheck ? [] : collectFeatures(items),
1459
+ features: requiresOnlineCheck ? [] : collectFeatures(grants),
1460
+ ...(regional?.expiresAt && !requiresOnlineCheck
1461
+ ? { regionalFreeUntil: Date.parse(regional.expiresAt) }
1462
+ : {}),
1123
1463
  requiresOnlineCheck,
1124
1464
  offlineUntil,
1465
+ clockSkew: this.clockSkew,
1125
1466
  verified: this.held.verified,
1126
1467
  issuedAt: this.held.envelope.payload.issuedAt,
1127
1468
  fetchedAt: this.held.fetchedAt,
@@ -1210,6 +1551,16 @@ class MemoryStorage {
1210
1551
  this.map.delete(key);
1211
1552
  }
1212
1553
  }
1554
+ /**
1555
+ * The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
1556
+ * only the trial start there (never `endUserRef`), so devices on one synced account share the
1557
+ * trial. Uninstalling clears it from the account, so it does not survive a reinstall.
1558
+ */
1559
+ function createSyncStorage() {
1560
+ const g = extensionGlobals();
1561
+ const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
1562
+ return area ? new ExtensionStorage(area) : null;
1563
+ }
1213
1564
  function createStorage() {
1214
1565
  const g = extensionGlobals();
1215
1566
  const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
@@ -1266,7 +1617,7 @@ class RecoveryManager {
1266
1617
  const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
1267
1618
  const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
1268
1619
  const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
1269
- const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
1620
+ const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
1270
1621
  if (!Number.isFinite(Date.parse(created.expiresAt)))
1271
1622
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
1272
1623
  const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
@@ -1326,8 +1677,9 @@ class RecoveryManager {
1326
1677
  break;
1327
1678
  if (claim.state === 'complete') {
1328
1679
  const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
1680
+ const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
1329
1681
  await this.options.storage.remove(this.pendingKey);
1330
- return { state: 'complete', entitlement };
1682
+ return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
1331
1683
  }
1332
1684
  if (claim.state !== 'pending')
1333
1685
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
@@ -1356,9 +1708,10 @@ class RecoveryManager {
1356
1708
  const DEFAULT_API_URL = 'https://bff.extenshi.io';
1357
1709
  const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
1358
1710
  const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1711
+ const DEFAULT_TRIAL_ENDING_DAYS = 2;
1359
1712
 
1360
1713
  /** Kept in sync with package.json by tests/unit/version.test.ts. */
1361
- const VERSION = '0.9.0';
1714
+ const VERSION = '0.12.0';
1362
1715
 
1363
1716
  /**
1364
1717
  * The user's language as the SDK sends it. Kept apart from the paywall
@@ -1428,7 +1781,7 @@ function resolveConfig(input) {
1428
1781
  if (!isHttpUrl(apiUrl))
1429
1782
  errors.push('apiUrl must be an http(s) URL');
1430
1783
  const entitlementPublicKey = input.entitlementPublicKey ?? null;
1431
- if (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {
1784
+ if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
1432
1785
  errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
1433
1786
  }
1434
1787
  const environment = input.environment ?? 'production';
@@ -1450,6 +1803,9 @@ function resolveConfig(input) {
1450
1803
  const theme = input.theme ?? {};
1451
1804
  if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
1452
1805
  errors.push('theme.mode must be light, dark or auto');
1806
+ const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
1807
+ if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
1808
+ errors.push('trialEndingDays must be a whole number of days between 0 and 365');
1453
1809
  if (input.mock &&
1454
1810
  input.mockData !== undefined &&
1455
1811
  (typeof input.mockData !== 'object' || input.mockData === null)) {
@@ -1470,6 +1826,8 @@ function resolveConfig(input) {
1470
1826
  mock: input.mock === true,
1471
1827
  mockData: input.mock ? (input.mockData ?? {}) : null,
1472
1828
  theme,
1829
+ trialEndingDays,
1830
+ syncTrialStart: input.syncTrialStart !== false,
1473
1831
  };
1474
1832
  }
1475
1833
 
@@ -1598,8 +1956,10 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
1598
1956
  * extends it with `getOffer()` / `showPaywall()`.
1599
1957
  *
1600
1958
  * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
1601
- * `locale` and checkout session IDs. Explicit recovery also sends its session ID,
1602
- * challenge and claim secret (POST body). Email stays on the hosted page.
1959
+ * `locale`, checkout session IDs and, with a server trial, the trial start date
1960
+ * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
1961
+ * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
1962
+ * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
1603
1963
  */
1604
1964
  /** Server-side offer cache is 5 min; mirror it in memory. */
1605
1965
  const OFFER_TTL_MS = 5 * 60 * 1000;
@@ -1610,12 +1970,30 @@ class ExtenshiPayLite {
1610
1970
  this.endUserRefPromise = null;
1611
1971
  this.offer = null;
1612
1972
  this.offerInflight = null;
1973
+ /** The signing key the server returned in this session; never one read from storage. */
1974
+ this.serverKey = null;
1975
+ /** Trust order for license signatures; see payment/signature.ts. */
1976
+ this.keys = {
1977
+ known: async () => {
1978
+ const pinned = this.config.entitlementPublicKey;
1979
+ const offline = pinned ?? (await this.readSavedServerKey());
1980
+ return [...new Set([this.serverKey, offline].filter((key) => !!key))];
1981
+ },
1982
+ fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
1983
+ };
1613
1984
  this.readyPromise = null;
1614
1985
  this.destroyed = false;
1615
1986
  this.config = resolveConfig(config);
1616
1987
  logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
1617
1988
  this.now = deps.now ?? (() => Date.now());
1618
1989
  this.storage = deps.storage ?? createStorage();
1990
+ this.openUrl = deps.openUrl;
1991
+ this.syncStorage =
1992
+ !this.config.syncTrialStart || this.config.mock
1993
+ ? null
1994
+ : deps.syncStorage === undefined
1995
+ ? createSyncStorage()
1996
+ : deps.syncStorage;
1619
1997
  const transport = deps.transport ??
1620
1998
  (this.config.mock
1621
1999
  ? new MockTransport(this.config.mockData ?? {})
@@ -1628,11 +2006,29 @@ class ExtenshiPayLite {
1628
2006
  cacheTtlMs: this.config.cacheTtlMs,
1629
2007
  source: this.config.mock ? 'mock' : 'network',
1630
2008
  getEndUserRef: () => this.getEndUserRef(),
1631
- getPublicKey: () => this.getPublicKey(),
2009
+ keys: this.keys,
1632
2010
  onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
2011
+ onAccepted: () => {
2012
+ void this.trial.evaluate();
2013
+ void this.rememberTrialStart();
2014
+ },
2015
+ getTrialStartHint: () => this.readTrialStartHint(),
1633
2016
  onError: (error) => this.reportError(error),
1634
2017
  now: this.now,
1635
2018
  });
2019
+ this.trial = new TrialNotifier({
2020
+ storage: this.storage,
2021
+ storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
2022
+ endingDays: this.config.trialEndingDays,
2023
+ getTrial: () => this.entitlements.getTrial(),
2024
+ // A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
2025
+ hasPaidAccess: () => {
2026
+ const license = this.entitlements.getCached();
2027
+ return Boolean(license?.regionalFreeUntil || license?.items.some(isLive));
2028
+ },
2029
+ emit: (event, trial) => this.emitter.emit(event, trial),
2030
+ now: this.now,
2031
+ });
1636
2032
  this.checkout = new CheckoutManager({
1637
2033
  api: this.api,
1638
2034
  storage: this.storage,
@@ -1646,6 +2042,13 @@ class ExtenshiPayLite {
1646
2042
  (this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
1647
2043
  now: this.now,
1648
2044
  });
2045
+ this.backup = new CloudBackup({
2046
+ storage: this.storage,
2047
+ publishableKey: this.config.publishableKey,
2048
+ apiUrl: this.config.apiUrl,
2049
+ fetch: deps.fetch,
2050
+ mock: this.config.mock,
2051
+ });
1649
2052
  this.recovery = new RecoveryManager({
1650
2053
  api: this.api,
1651
2054
  locale: this.config.locale,
@@ -1659,7 +2062,7 @@ class ExtenshiPayLite {
1659
2062
  envelope.payload.publishableKey !== this.config.publishableKey ||
1660
2063
  !Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
1661
2064
  Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
1662
- (await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid')
2065
+ (await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
1663
2066
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
1664
2067
  this.entitlements.stopAutoRefresh();
1665
2068
  try {
@@ -1677,6 +2080,7 @@ class ExtenshiPayLite {
1677
2080
  this.entitlements.startAutoRefresh();
1678
2081
  }
1679
2082
  },
2083
+ onStorageGrant: (grant) => this.backup.accept(grant),
1680
2084
  });
1681
2085
  if (config.onError)
1682
2086
  this.emitter.on('error', config.onError);
@@ -1722,8 +2126,11 @@ class ExtenshiPayLite {
1722
2126
  catch (error) {
1723
2127
  this.reportError(error);
1724
2128
  }
1725
- if (!this.destroyed)
2129
+ void this.confirmSavedServerKey();
2130
+ if (!this.destroyed) {
1726
2131
  this.entitlements.startAutoRefresh();
2132
+ this.trial.start();
2133
+ }
1727
2134
  }
1728
2135
  /** The anonymous, random id this install is known by. */
1729
2136
  getEndUserRef() {
@@ -1744,6 +2151,16 @@ class ExtenshiPayLite {
1744
2151
  await this.initialize();
1745
2152
  return this.entitlements.get(options);
1746
2153
  }
2154
+ /**
2155
+ * The free trial the application set on the server, from the verified license, or null when
2156
+ * there is none (or the license could not be verified yet). Answers offline from the cached
2157
+ * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
2158
+ * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
2159
+ */
2160
+ async getTrial(options = {}) {
2161
+ await this.getEntitlement(options);
2162
+ return this.entitlements.getTrial();
2163
+ }
1747
2164
  /** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
1748
2165
  async isPaid(sku) {
1749
2166
  return isEntitled(await this.getEntitlement(), sku);
@@ -1827,6 +2244,41 @@ class ExtenshiPayLite {
1827
2244
  throw this.reportError(error);
1828
2245
  }
1829
2246
  }
2247
+ /**
2248
+ * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
2249
+ * hosted restore page shows the storage disclosure and the buyer confirms with
2250
+ * the code from the purchase email. `cloudBackup` in the result says whether it is
2251
+ * on. Buyers only; consent is recorded by the server.
2252
+ */
2253
+ enableCloudBackup(options = {}) {
2254
+ return this.restorePurchase({ ...options, purpose: 'storage' });
2255
+ }
2256
+ /**
2257
+ * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
2258
+ * while cloud backup is off on this installation. Extension pages and background
2259
+ * only: it rejects in a content script, and must never be sent to one.
2260
+ */
2261
+ async cloudBackupToken() {
2262
+ return this.backup.token();
2263
+ }
2264
+ /** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
2265
+ async disableCloudBackup() {
2266
+ try {
2267
+ await this.backup.disable();
2268
+ }
2269
+ catch (error) {
2270
+ throw this.reportError(error);
2271
+ }
2272
+ }
2273
+ /** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
2274
+ async deleteCloudBackup() {
2275
+ try {
2276
+ await this.backup.delete();
2277
+ }
2278
+ catch (error) {
2279
+ throw this.reportError(error);
2280
+ }
2281
+ }
1830
2282
  /** Read-only license view. Entitlements retain cache/signature/offline semantics. */
1831
2283
  async getLicenseSummary(options = {}) {
1832
2284
  await this.initialize();
@@ -1896,6 +2348,7 @@ class ExtenshiPayLite {
1896
2348
  destroy() {
1897
2349
  this.destroyed = true;
1898
2350
  this.recovery.stop();
2351
+ this.trial.stop();
1899
2352
  this.entitlements.stopAutoRefresh();
1900
2353
  this.emitter.removeAll();
1901
2354
  }
@@ -1907,8 +2360,9 @@ class ExtenshiPayLite {
1907
2360
  if (!this.offerInflight) {
1908
2361
  this.offerInflight = this.api
1909
2362
  .getOffer(this.config.locale)
1910
- .then((value) => {
2363
+ .then(async (value) => {
1911
2364
  this.offer = { value, fetchedAt: this.now() };
2365
+ await this.rememberServerKey(value.entitlementPublicKey);
1912
2366
  return value;
1913
2367
  })
1914
2368
  .finally(() => {
@@ -1917,8 +2371,88 @@ class ExtenshiPayLite {
1917
2371
  }
1918
2372
  return this.offerInflight;
1919
2373
  }
1920
- async getPublicKey() {
1921
- return this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey;
2374
+ get serverKeyStorageKey() {
2375
+ return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
2376
+ }
2377
+ async readSavedServerKey() {
2378
+ try {
2379
+ const value = await this.storage.get(this.serverKeyStorageKey);
2380
+ return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
2381
+ }
2382
+ catch {
2383
+ return null;
2384
+ }
2385
+ }
2386
+ /**
2387
+ * Keeps the server's key next to the license cache so a restart with no network can verify it.
2388
+ * Not with a bundled key: that one already covers the restart, and storage stays untrusted.
2389
+ */
2390
+ async rememberServerKey(key) {
2391
+ if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
2392
+ return;
2393
+ this.serverKey = key;
2394
+ if (this.config.entitlementPublicKey || this.config.mock)
2395
+ return;
2396
+ try {
2397
+ if ((await this.readSavedServerKey()) !== key)
2398
+ await this.storage.set(this.serverKeyStorageKey, key);
2399
+ }
2400
+ catch (error) {
2401
+ logger.debug('signing key not saved', error);
2402
+ }
2403
+ }
2404
+ /**
2405
+ * A license verified with the saved key alone is checked against the server once per start:
2406
+ * when the server's key differs (rotation, or an edited storage) the license is fetched again,
2407
+ * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
2408
+ */
2409
+ async confirmSavedServerKey() {
2410
+ const used = this.entitlements.verifiedKey;
2411
+ if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
2412
+ return;
2413
+ try {
2414
+ if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
2415
+ return;
2416
+ }
2417
+ catch {
2418
+ return;
2419
+ }
2420
+ try {
2421
+ await this.entitlements.refresh();
2422
+ }
2423
+ catch {
2424
+ await this.entitlements.reverify().catch((error) => this.reportError(error));
2425
+ }
2426
+ }
2427
+ get trialStartKey() {
2428
+ return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
2429
+ }
2430
+ /** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
2431
+ async readTrialStartHint() {
2432
+ if (!this.syncStorage)
2433
+ return null;
2434
+ try {
2435
+ const value = await this.syncStorage.get(this.trialStartKey);
2436
+ return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
2437
+ }
2438
+ catch {
2439
+ return null;
2440
+ }
2441
+ }
2442
+ /** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
2443
+ async rememberTrialStart() {
2444
+ const trial = this.entitlements.getTrial();
2445
+ if (!this.syncStorage || !trial)
2446
+ return;
2447
+ try {
2448
+ const synced = await this.readTrialStartHint();
2449
+ if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
2450
+ return;
2451
+ await this.syncStorage.set(this.trialStartKey, trial.startedAt);
2452
+ }
2453
+ catch (error) {
2454
+ logger.debug('trial start not synced', error);
2455
+ }
1922
2456
  }
1923
2457
  reportError(error) {
1924
2458
  const err = ExtenshiPayError.from(error);
@@ -1929,5 +2463,5 @@ class ExtenshiPayLite {
1929
2463
  }
1930
2464
  ExtenshiPayLite.version = VERSION;
1931
2465
 
1932
- export { CHECKOUT_POLL_INTERVAL_MS, CHECKOUT_TIMEOUT_MS, CheckoutManager, DEFAULT_API_URL, DEFAULT_CACHE_TTL_MS, EMPTY_ENTITLEMENT, END_USER_REF_STORAGE_KEY, ERROR_CODES, EntitlementManager, EventEmitter, ExtenshiPayError, ExtenshiPayLite, ExtensionStorage, HttpTransport, LOCALE_RE, LocalStorageAdapter, Logger, MAX_CACHE_TTL_MS, MAX_REFRESH_BACKOFF_MS, MIN_REFRESH_INTERVAL_MS, MemoryStorage, MockTransport, PAY_CONTRACT_VERSION, PAY_CURRENCIES, PAY_END_USER_REF_RE, PAY_ENTITLEMENT_STATUSES, PAY_ERRORS, PAY_GATEWAYS, PAY_OFFER_INTERVALS, PAY_OFFER_KINDS, PAY_PUBLISHABLE_KEY_HEX_LENGTH, PAY_PUBLISHABLE_KEY_PREFIX, PAY_SKU_RE, PAY_WITHDRAWAL_WAIVER_VERSION, PayApi, RecoveryManager, TRPC_PATH, VERSION, applyLocalExpiry, base64ToBytes, canonicalJson, checkFeatures, collectFeatures, createRecoveryStorage, createStorage, getOrCreateEndUserRef, hasFeature, isEntitled, isLive, isPayPublishableKey, logger, mintEndUserRef, openInNewTab, resolveConfig, trpcErrorToPayError, verifyEntitlementSignature };
2466
+ export { CHECKOUT_POLL_INTERVAL_MS, CHECKOUT_TIMEOUT_MS, CheckoutManager, CloudBackup, DEFAULT_API_URL, DEFAULT_CACHE_TTL_MS, DEFAULT_TRIAL_ENDING_DAYS, EMPTY_ENTITLEMENT, END_USER_REF_STORAGE_KEY, ERROR_CODES, EntitlementManager, EventEmitter, ExtenshiPayError, ExtenshiPayLite, ExtensionStorage, HttpTransport, LOCALE_RE, LocalStorageAdapter, Logger, MAX_CACHE_TTL_MS, MAX_REFRESH_BACKOFF_MS, MIN_REFRESH_INTERVAL_MS, MemoryStorage, MockTransport, PAY_CONTRACT_VERSION, PAY_CURRENCIES, PAY_END_USER_REF_RE, PAY_ENTITLEMENT_STATUSES, PAY_ERRORS, PAY_GATEWAYS, PAY_OFFER_INTERVALS, PAY_OFFER_KINDS, PAY_PUBLISHABLE_KEY_HEX_LENGTH, PAY_PUBLISHABLE_KEY_PREFIX, PAY_REGIONAL_ACCESS_SKU, PAY_RESTORE_PURPOSES, PAY_SKU_RE, PAY_WITHDRAWAL_WAIVER_VERSION, PayApi, RecoveryManager, STORAGE_TOKEN_RE, TRPC_PATH, VERSION, applyLocalExpiry, base64ToBytes, canonicalJson, checkFeatures, collectFeatures, createRecoveryStorage, createStorage, createSyncStorage, getOrCreateEndUserRef, hasFeature, isEntitled, isLive, isPayPublishableKey, logger, mintEndUserRef, openInNewTab, resolveConfig, trpcErrorToPayError, verifyEntitlementSignature };
1933
2467
  //# sourceMappingURL=core.mjs.map