@extenshi/pay 0.9.0 → 0.11.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 +128 -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 +268 -26
  14. package/dist/core.d.ts +268 -26
  15. package/dist/core.js +566 -44
  16. package/dist/core.js.map +1 -1
  17. package/dist/core.mjs +562 -45
  18. package/dist/core.mjs.map +1 -1
  19. package/dist/extenshi-pay-lite.js +555 -44
  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 +555 -44
  24. package/dist/extenshi-pay-lite.mjs.map +1 -1
  25. package/dist/extenshi-pay.cjs.js +670 -57
  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 +670 -57
  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 +666 -58
  36. package/dist/extenshi-pay.mjs.map +1 -1
  37. package/dist/index.d.mts +285 -26
  38. package/dist/index.d.ts +285 -26
  39. package/dist/lite.d.mts +212 -13
  40. package/dist/lite.d.ts +212 -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 +35 -0
  65. package/dist/types/contract.d.ts.map +1 -1
  66. package/dist/types/entitlement.d.ts +37 -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.11.0
3
3
  * (c) 2026 Extenshi.io
4
4
  * Released under the MIT License.
5
- * commit bd166bf9b687f60e965d03acec7a648b42226652 · built by `rollup -c`
5
+ * commit ed0f776ae9ab7ce6b2c614dbdfe696e9007b0d05 · built by `rollup -c`
6
6
  */
7
7
  /**
8
8
  * Wire contract between the SDK and catalog-bff `pay.*`.
@@ -86,6 +86,14 @@ function canonicalJson(value) {
86
86
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
87
87
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
88
88
  }
89
+ /**
90
+ * `storage`: the buyer turns on the cloud copy of the extension's settings. The
91
+ * hosted page shows the storage disclosure; the claim records consent. Additive:
92
+ * a session without a purpose is a plain restore.
93
+ */
94
+ const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
95
+ /** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
96
+ const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
89
97
 
90
98
  const ERROR_CODES = {
91
99
  INVALID_CONFIG: 'INVALID_CONFIG',
@@ -157,7 +165,7 @@ async function getOrCreateEndUserRef(storage) {
157
165
  * developed with no backend: offers and entitlements come from `mockData`, a
158
166
  * mock checkout completes after `claimAfterPolls` polls and grants the SKU.
159
167
  */
160
- const DAY_MS = 24 * 60 * 60 * 1000;
168
+ const DAY_MS$1 = 24 * 60 * 60 * 1000;
161
169
  /** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
162
170
  function mockConsent(value) {
163
171
  const consent = value;
@@ -175,6 +183,10 @@ class MockTransport {
175
183
  this.claimAfterPolls = data.claimAfterPolls ?? 1;
176
184
  this.withdrawalWaiver =
177
185
  data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
186
+ this.seller = data.seller;
187
+ this.trial = null;
188
+ if (data.trial)
189
+ this.setTrial(data.trial.days, data.trial.startedAt);
178
190
  }
179
191
  async call(procedure, _kind, input) {
180
192
  switch (procedure) {
@@ -196,6 +208,14 @@ class MockTransport {
196
208
  setEntitlements(items) {
197
209
  this.entitlements = [...items];
198
210
  }
211
+ /** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
212
+ setTrial(days, startedAt = new Date().toISOString()) {
213
+ const start = Date.parse(startedAt);
214
+ this.trial =
215
+ days === null || !Number.isFinite(start)
216
+ ? null
217
+ : { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
218
+ }
199
219
  cancelSession(sessionId) {
200
220
  const session = this.sessions.get(sessionId);
201
221
  if (session)
@@ -215,6 +235,7 @@ class MockTransport {
215
235
  offers: [...this.offers],
216
236
  entitlementPublicKey: null,
217
237
  withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
238
+ ...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
218
239
  };
219
240
  }
220
241
  createCheckout(sku, withdrawalWaiver) {
@@ -252,7 +273,7 @@ class MockTransport {
252
273
  grant(sku) {
253
274
  const offer = this.offers.find((o) => o.sku === sku);
254
275
  const expiresAt = offer?.kind === 'subscription'
255
- ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
276
+ ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
256
277
  : null;
257
278
  this.entitlements = [
258
279
  ...this.entitlements.filter((item) => item.sku !== sku),
@@ -274,6 +295,7 @@ class MockTransport {
274
295
  endUserRef,
275
296
  entitlements: [...this.entitlements],
276
297
  issuedAt: new Date().toISOString(),
298
+ ...(this.trial ? { trial: { ...this.trial } } : {}),
277
299
  },
278
300
  signature: null,
279
301
  alg: null,
@@ -287,12 +309,17 @@ class PayApi {
287
309
  this.transport = transport;
288
310
  this.publishableKey = publishableKey;
289
311
  }
290
- /** `locale` opens the hosted recovery page (and its email) in the user's language. */
291
- createRestoreSession(claimChallenge, locale) {
312
+ /**
313
+ * `locale` opens the hosted recovery page (and its email) in the user's language.
314
+ * `purpose` is sent only for `storage`: a plain restore keeps the request older
315
+ * BFFs know, and their non-strict zod input strips the key anyway.
316
+ */
317
+ createRestoreSession(claimChallenge, locale, purpose) {
292
318
  return this.transport.call('pay.createRestoreSession', 'mutation', {
293
319
  publishableKey: this.publishableKey,
294
320
  claimChallenge,
295
321
  ...(locale ? { locale } : {}),
322
+ ...(purpose === 'storage' ? { purpose } : {}),
296
323
  });
297
324
  }
298
325
  claimRestoreSession(sessionId, claimSecret) {
@@ -331,10 +358,12 @@ class PayApi {
331
358
  endUserRef,
332
359
  });
333
360
  }
334
- getEntitlement(endUserRef) {
361
+ /** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
362
+ getEntitlement(endUserRef, trialStartedHint) {
335
363
  return this.transport.call('pay.getEntitlement', 'query', {
336
364
  publishableKey: this.publishableKey,
337
365
  endUserRef,
366
+ ...(trialStartedHint ? { trialStartedHint } : {}),
338
367
  });
339
368
  }
340
369
  getPortalUrl(endUserRef, customerId, locale) {
@@ -732,6 +761,118 @@ var checkout = /*#__PURE__*/Object.freeze({
732
761
  openInNewTab: openInNewTab
733
762
  });
734
763
 
764
+ /**
765
+ * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
766
+ * token: only a verified restore claim issues it; this module keeps it in the
767
+ * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
768
+ * through `cloudBackupToken()`. The token is never logged and never answered to
769
+ * a content script: route those calls to the background.
770
+ */
771
+ const REQUEST_TIMEOUT_MS = 10000;
772
+ /** True in a content script, where the token must not be handed out. */
773
+ function inContentScript() {
774
+ const g = globalThis;
775
+ return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
776
+ }
777
+ class CloudBackup {
778
+ constructor(options) {
779
+ this.options = options;
780
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
781
+ }
782
+ get storageKey() {
783
+ return `extenshi-pay:${this.options.publishableKey}:storageToken`;
784
+ }
785
+ /** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
786
+ async accept(grant) {
787
+ if (!grant || typeof grant !== 'object')
788
+ return undefined;
789
+ try {
790
+ if (grant.state === 'granted') {
791
+ if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
792
+ return undefined;
793
+ await this.options.storage.set(this.storageKey, grant.token);
794
+ return 'on';
795
+ }
796
+ if (grant.state === 'unavailable') {
797
+ await this.options.storage.remove(this.storageKey);
798
+ return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
799
+ }
800
+ }
801
+ catch {
802
+ logger.warn('cloud backup state could not be saved');
803
+ }
804
+ return undefined;
805
+ }
806
+ async token() {
807
+ this.assertTrustedContext();
808
+ const value = await this.options.storage.get(this.storageKey);
809
+ return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
810
+ }
811
+ /** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
812
+ async disable() {
813
+ const token = await this.token();
814
+ if (!token)
815
+ return;
816
+ if (!this.options.mock) {
817
+ const status = await this.request('/v1/storage/grant', token);
818
+ if (status !== 401)
819
+ this.throwUnlessOk(status);
820
+ }
821
+ await this.options.storage.remove(this.storageKey);
822
+ }
823
+ /** Deletes the buyer's cloud copy and turns the backup off on every device. */
824
+ async delete() {
825
+ const token = await this.token();
826
+ if (!token)
827
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
828
+ if (!this.options.mock) {
829
+ const status = await this.request('/v1/storage/data', token);
830
+ if (status === 401) {
831
+ // The server no longer accepts this token, so it is useless here; the copy was not deleted.
832
+ await this.options.storage.remove(this.storageKey);
833
+ 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 });
834
+ }
835
+ this.throwUnlessOk(status);
836
+ }
837
+ await this.options.storage.remove(this.storageKey);
838
+ }
839
+ assertTrustedContext() {
840
+ if (inContentScript())
841
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
842
+ }
843
+ throwUnlessOk(status) {
844
+ if (status >= 200 && status < 300)
845
+ return;
846
+ if (status === 429)
847
+ throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
848
+ if (status >= 500)
849
+ throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
850
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
851
+ }
852
+ async request(path, token) {
853
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
854
+ const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
855
+ try {
856
+ const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
857
+ method: 'DELETE',
858
+ headers: { Authorization: `Bearer ${token}` },
859
+ credentials: 'omit',
860
+ signal: controller?.signal,
861
+ });
862
+ return response.status;
863
+ }
864
+ catch (error) {
865
+ if (controller?.signal.aborted)
866
+ throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
867
+ throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
868
+ }
869
+ finally {
870
+ if (timer !== null)
871
+ clearTimeout(timer);
872
+ }
873
+ }
874
+ }
875
+
735
876
  /** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
736
877
  const LIVE_STATUSES = new Set(['active', 'grace']);
737
878
  function isLive(item) {
@@ -786,9 +927,17 @@ Object.freeze(EMPTY_ENTITLEMENT.features);
786
927
  /**
787
928
  * Ed25519 verification of the entitlement projection.
788
929
  *
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.
930
+ * Tamper resistance, not DRM. Callers must deny access for both invalid and
931
+ * unverified envelopes outside explicit mocks.
932
+ *
933
+ * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
934
+ * 1. the key the server returned over HTTPS in this session;
935
+ * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
936
+ * verification without a round-trip: a key read from extension storage is then never used;
937
+ * 3. without a bundled key, the server key saved in `storage.local` next to the
938
+ * license cache, so a restart with no network can still verify the cache.
939
+ * When none of them verifies an envelope the server is asked for its current key once
940
+ * (a rotated key), and that answer decides.
792
941
  */
793
942
  function base64ToBytes(base64) {
794
943
  const binary = atob(base64);
@@ -823,6 +972,140 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
823
972
  return 'invalid';
824
973
  }
825
974
  }
975
+ const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
976
+ /**
977
+ * `invalid` only when the server's current key was checked too (or the envelope carries no
978
+ * signature at all). A mismatch against known keys while the server is unreachable is
979
+ * `unverified`: it may be a rotated key, and no paid access is granted either way.
980
+ */
981
+ async function verifyWithKeys(envelope, source) {
982
+ if (!envelope.signature || envelope.alg !== 'ed25519')
983
+ return { verdict: 'invalid', key: null };
984
+ let known = [];
985
+ try {
986
+ known = await source.known();
987
+ }
988
+ catch {
989
+ known = [];
990
+ }
991
+ let mismatch = false;
992
+ for (const key of known) {
993
+ const verdict = await verifyEntitlementSignature(envelope, key);
994
+ if (verdict === 'valid')
995
+ return { verdict, key };
996
+ if (verdict === 'invalid')
997
+ mismatch = true;
998
+ }
999
+ let current;
1000
+ try {
1001
+ current = await source.fetchCurrent();
1002
+ }
1003
+ catch {
1004
+ return { verdict: 'unverified', key: null };
1005
+ }
1006
+ if (current && !known.includes(current)) {
1007
+ const verdict = await verifyEntitlementSignature(envelope, current);
1008
+ return { verdict, key: verdict === 'valid' ? current : null };
1009
+ }
1010
+ return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
1011
+ }
1012
+
1013
+ /**
1014
+ * The free trial an application configures on the server (`trialDays`).
1015
+ *
1016
+ * The server starts one clock per installation at its first license read and
1017
+ * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
1018
+ * the verified license like paid access does: no start date in extension
1019
+ * storage, nothing a device clock or a storage edit can move. Offline, the
1020
+ * cached license answers for up to 48 hours.
1021
+ *
1022
+ * `trial:ending` / `trial:ended` fire once per installation and trial (the
1023
+ * marker is kept in the SDK's storage), and not while the user has paid
1024
+ * access. Render state from `getTrial()`; the events are one-time notices.
1025
+ */
1026
+ const DAY_MS = 24 * 60 * 60 * 1000;
1027
+ /** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
1028
+ const MAX_TIMER_MS$1 = DAY_MS;
1029
+ /** The trial as of `clock`, or null when the license carries none (or a malformed one). */
1030
+ function trialState(trial, clock) {
1031
+ if (!trial)
1032
+ return null;
1033
+ const startedAt = Date.parse(trial.startedAt);
1034
+ const endsAt = Date.parse(trial.endsAt);
1035
+ if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
1036
+ return null;
1037
+ // The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
1038
+ const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
1039
+ const left = endsAt - now;
1040
+ return {
1041
+ active: left > 0 && clock.checked,
1042
+ startedAt: trial.startedAt,
1043
+ endsAt: trial.endsAt,
1044
+ daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
1045
+ requiresOnlineCheck: left > 0 && !clock.checked,
1046
+ };
1047
+ }
1048
+ class TrialNotifier {
1049
+ constructor(options) {
1050
+ this.options = options;
1051
+ this.timer = null;
1052
+ this.running = false;
1053
+ this.pending = Promise.resolve();
1054
+ }
1055
+ start() {
1056
+ this.running = true;
1057
+ void this.evaluate();
1058
+ }
1059
+ stop() {
1060
+ this.running = false;
1061
+ this.clearTimer();
1062
+ }
1063
+ /** Checks the held license; serialized, so two refreshes never send one event twice. */
1064
+ evaluate() {
1065
+ this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
1066
+ return this.pending;
1067
+ }
1068
+ async check() {
1069
+ if (!this.running)
1070
+ return;
1071
+ this.clearTimer();
1072
+ const trial = this.options.getTrial();
1073
+ if (!trial)
1074
+ return;
1075
+ const now = this.options.now();
1076
+ const endsAt = Date.parse(trial.endsAt);
1077
+ const endingAt = endsAt - this.options.endingDays * DAY_MS;
1078
+ const event = trial.daysLeft === 0
1079
+ ? 'trial:ended'
1080
+ : trial.active && this.options.endingDays > 0 && now >= endingAt
1081
+ ? 'trial:ending'
1082
+ : null;
1083
+ if (event && !this.options.hasPaidAccess())
1084
+ await this.send(event, trial);
1085
+ if (!this.running || trial.daysLeft === 0)
1086
+ return;
1087
+ const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
1088
+ this.timer = setTimeout(() => {
1089
+ this.timer = null;
1090
+ void this.evaluate();
1091
+ }, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
1092
+ }
1093
+ async send(event, trial) {
1094
+ const id = `${trial.startedAt}|${trial.endsAt}`;
1095
+ const field = event === 'trial:ended' ? 'ended' : 'ending';
1096
+ const stored = (await this.options.storage.get(this.options.storageKey));
1097
+ const sent = stored && typeof stored === 'object' ? stored : {};
1098
+ if (sent[field] === id || !this.running)
1099
+ return;
1100
+ await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
1101
+ this.options.emit(event, trial);
1102
+ }
1103
+ clearTimer() {
1104
+ if (this.timer !== null)
1105
+ clearTimeout(this.timer);
1106
+ this.timer = null;
1107
+ }
1108
+ }
826
1109
 
827
1110
  /**
828
1111
  * Entitlement cache + refresh.
@@ -830,13 +1113,18 @@ async function verifyEntitlementSignature(envelope, publicKeyBase64) {
830
1113
  * The cached envelope is a cache OF the server projection, never a second
831
1114
  * source of truth: it is verified when stored and re-verified on load (once
832
1115
  * 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
1116
+ * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
834
1117
  * locally by `expiresAt`. Background refresh polls at most every 15 minutes
835
1118
  * and backs off exponentially on errors.
836
1119
  */
837
1120
  const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
838
1121
  const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
1122
+ /** Offline allowance when the signed license names none (older servers and caches). */
839
1123
  const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
1124
+ /** Ceiling for a signed `offlineSeconds`. */
1125
+ const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
1126
+ /** `setTimeout` fires at once past this delay. */
1127
+ const MAX_TIMER_MS = 2 ** 31 - 1;
840
1128
  // Allow small server/client clock skew without granting more than the signed age limit.
841
1129
  const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
842
1130
  const CACHE_VERSION = 1;
@@ -855,6 +1143,8 @@ class EntitlementManager {
855
1143
  this.options = options;
856
1144
  this.held = null;
857
1145
  this.inflight = null;
1146
+ /** Device clock against the server's at the last license check; null within 5 minutes. */
1147
+ this.clockSkew = null;
858
1148
  this.timer = null;
859
1149
  this.refreshGeneration = 0;
860
1150
  this.deadlineTimer = null;
@@ -896,8 +1186,10 @@ class EntitlementManager {
896
1186
  envelope: JSON.parse(JSON.stringify(record.envelope)),
897
1187
  fetchedAt: record.fetchedAt,
898
1188
  verified: false,
1189
+ key: null,
899
1190
  source: this.source === 'mock' ? 'mock' : 'cache',
900
1191
  };
1192
+ this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
901
1193
  this.lastFingerprint = this.fingerprint();
902
1194
  return this.snapshot();
903
1195
  }
@@ -908,8 +1200,7 @@ class EntitlementManager {
908
1200
  if (this.source === 'mock')
909
1201
  return;
910
1202
  const held = this.held;
911
- const key = await this.safePublicKey();
912
- const verdict = await verifyEntitlementSignature(held.envelope, key);
1203
+ const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
913
1204
  if (held !== this.held)
914
1205
  return;
915
1206
  if (verdict === 'invalid') {
@@ -918,19 +1209,39 @@ class EntitlementManager {
918
1209
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
919
1210
  }
920
1211
  held.verified = verdict === 'valid';
1212
+ held.key = key;
921
1213
  if (!held.verified) {
922
1214
  throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
923
1215
  }
924
1216
  this.scheduleDeadline();
925
1217
  }
1218
+ /** The key the held license was verified with; null when there is none or it is unverified. */
1219
+ get verifiedKey() {
1220
+ return this.held?.verified ? this.held.key : null;
1221
+ }
926
1222
  getCached() {
927
1223
  return this.held ? this.snapshot() : null;
928
1224
  }
1225
+ /** The server trial in the held license; null without one, or while the license is unverified. */
1226
+ getTrial() {
1227
+ const held = this.held;
1228
+ if (!held || (this.source !== 'mock' && !held.verified))
1229
+ return null;
1230
+ const now = this.now();
1231
+ const issuedAt = Date.parse(held.envelope.payload.issuedAt);
1232
+ return trialState(held.envelope.payload.trial, {
1233
+ now,
1234
+ issuedAt,
1235
+ // The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
1236
+ checked: this.source === 'mock' ||
1237
+ (now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
1238
+ });
1239
+ }
929
1240
  isFresh() {
930
1241
  return (this.held !== null &&
931
1242
  (this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
932
1243
  this.now() >= this.held.fetchedAt &&
933
- this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS));
1244
+ this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
934
1245
  }
935
1246
  async get(options = {}) {
936
1247
  if (!options.force && this.isFresh())
@@ -945,7 +1256,7 @@ class EntitlementManager {
945
1256
  logger.debug('serving cached entitlement after refresh failure', err.code);
946
1257
  return this.snapshot();
947
1258
  }
948
- return EMPTY_ENTITLEMENT;
1259
+ return this.snapshot();
949
1260
  }
950
1261
  }
951
1262
  /** Fetches the projection from the backend, verifies and stores it. */
@@ -953,7 +1264,8 @@ class EntitlementManager {
953
1264
  if (!this.inflight) {
954
1265
  this.inflight = (async () => {
955
1266
  const endUserRef = await this.options.getEndUserRef();
956
- const envelope = await this.options.api.getEntitlement(endUserRef);
1267
+ const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
1268
+ const envelope = await this.options.api.getEntitlement(endUserRef, hint);
957
1269
  return this.accept(envelope, this.source);
958
1270
  })().finally(() => {
959
1271
  this.inflight = null;
@@ -975,9 +1287,9 @@ class EntitlementManager {
975
1287
  if (envelope.payload.endUserRef !== endUserRef) {
976
1288
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
977
1289
  }
978
- const verdict = this.source === 'mock'
979
- ? 'unverified'
980
- : await verifyEntitlementSignature(envelope, await this.safePublicKey());
1290
+ const { verdict, key } = this.source === 'mock'
1291
+ ? { verdict: 'unverified', key: null }
1292
+ : await verifyWithKeys(envelope, this.options.keys);
981
1293
  if (verdict === 'invalid') {
982
1294
  await this.discard();
983
1295
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
@@ -987,15 +1299,19 @@ class EntitlementManager {
987
1299
  }
988
1300
  const fetchedAt = this.now();
989
1301
  const issuedAt = Date.parse(envelope.payload.issuedAt);
1302
+ // A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
1303
+ if (this.source !== 'mock')
1304
+ this.measureClockSkew(fetchedAt, issuedAt);
990
1305
  if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
991
1306
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
992
1307
  }
993
- this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
1308
+ this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
994
1309
  const record = { v: CACHE_VERSION, envelope, fetchedAt };
995
1310
  await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
996
1311
  this.backoffMs = 0;
997
1312
  this.scheduleDeadline();
998
1313
  this.notifyIfChanged();
1314
+ this.options.onAccepted?.();
999
1315
  return this.snapshot();
1000
1316
  }
1001
1317
  /** Drain an older installation refresh before changing identity. */
@@ -1049,7 +1365,7 @@ class EntitlementManager {
1049
1365
  this.deadlineTimer = null;
1050
1366
  this.notifyIfChanged();
1051
1367
  this.scheduleDeadline();
1052
- }, remaining);
1368
+ }, Math.min(remaining, MAX_TIMER_MS));
1053
1369
  }
1054
1370
  schedule(delayMs) {
1055
1371
  const generation = this.refreshGeneration;
@@ -1070,14 +1386,12 @@ class EntitlementManager {
1070
1386
  }
1071
1387
  }, delayMs);
1072
1388
  }
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
- }
1389
+ measureClockSkew(local, server) {
1390
+ const ms = local - server;
1391
+ this.clockSkew =
1392
+ Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
1393
+ ? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
1394
+ : null;
1081
1395
  }
1082
1396
  async discard() {
1083
1397
  this.held = null;
@@ -1100,13 +1414,25 @@ class EntitlementManager {
1100
1414
  if (!this.held)
1101
1415
  return NaN;
1102
1416
  // 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;
1417
+ return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
1418
+ }
1419
+ /** The signed allowance of the held license, or 48 hours when it names none. */
1420
+ offlineAgeMs() {
1421
+ const seconds = this.held?.envelope.payload.offlineSeconds;
1422
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
1423
+ return MAX_OFFLINE_AGE_MS;
1424
+ return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
1104
1425
  }
1105
1426
  snapshot() {
1106
1427
  if (!this.held)
1107
- return EMPTY_ENTITLEMENT;
1428
+ return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
1108
1429
  if (this.source !== 'mock' && !this.held.verified) {
1109
- return { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source };
1430
+ return {
1431
+ ...EMPTY_ENTITLEMENT,
1432
+ requiresOnlineCheck: true,
1433
+ clockSkew: this.clockSkew,
1434
+ source: this.held.source,
1435
+ };
1110
1436
  }
1111
1437
  const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1112
1438
  const hasPaidAccess = collectFeatures(items).length > 0 ||
@@ -1122,6 +1448,7 @@ class EntitlementManager {
1122
1448
  features: requiresOnlineCheck ? [] : collectFeatures(items),
1123
1449
  requiresOnlineCheck,
1124
1450
  offlineUntil,
1451
+ clockSkew: this.clockSkew,
1125
1452
  verified: this.held.verified,
1126
1453
  issuedAt: this.held.envelope.payload.issuedAt,
1127
1454
  fetchedAt: this.held.fetchedAt,
@@ -1210,6 +1537,16 @@ class MemoryStorage {
1210
1537
  this.map.delete(key);
1211
1538
  }
1212
1539
  }
1540
+ /**
1541
+ * The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
1542
+ * only the trial start there (never `endUserRef`), so devices on one synced account share the
1543
+ * trial. Uninstalling clears it from the account, so it does not survive a reinstall.
1544
+ */
1545
+ function createSyncStorage() {
1546
+ const g = extensionGlobals();
1547
+ const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
1548
+ return area ? new ExtensionStorage(area) : null;
1549
+ }
1213
1550
  function createStorage() {
1214
1551
  const g = extensionGlobals();
1215
1552
  const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
@@ -1266,7 +1603,7 @@ class RecoveryManager {
1266
1603
  const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
1267
1604
  const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
1268
1605
  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);
1606
+ const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
1270
1607
  if (!Number.isFinite(Date.parse(created.expiresAt)))
1271
1608
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
1272
1609
  const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
@@ -1326,8 +1663,9 @@ class RecoveryManager {
1326
1663
  break;
1327
1664
  if (claim.state === 'complete') {
1328
1665
  const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
1666
+ const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
1329
1667
  await this.options.storage.remove(this.pendingKey);
1330
- return { state: 'complete', entitlement };
1668
+ return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
1331
1669
  }
1332
1670
  if (claim.state !== 'pending')
1333
1671
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
@@ -1356,9 +1694,10 @@ class RecoveryManager {
1356
1694
  const DEFAULT_API_URL = 'https://bff.extenshi.io';
1357
1695
  const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
1358
1696
  const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1697
+ const DEFAULT_TRIAL_ENDING_DAYS = 2;
1359
1698
 
1360
1699
  /** Kept in sync with package.json by tests/unit/version.test.ts. */
1361
- const VERSION = '0.9.0';
1700
+ const VERSION = '0.11.0';
1362
1701
 
1363
1702
  /**
1364
1703
  * The user's language as the SDK sends it. Kept apart from the paywall
@@ -1428,7 +1767,7 @@ function resolveConfig(input) {
1428
1767
  if (!isHttpUrl(apiUrl))
1429
1768
  errors.push('apiUrl must be an http(s) URL');
1430
1769
  const entitlementPublicKey = input.entitlementPublicKey ?? null;
1431
- if (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {
1770
+ if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
1432
1771
  errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
1433
1772
  }
1434
1773
  const environment = input.environment ?? 'production';
@@ -1450,6 +1789,9 @@ function resolveConfig(input) {
1450
1789
  const theme = input.theme ?? {};
1451
1790
  if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
1452
1791
  errors.push('theme.mode must be light, dark or auto');
1792
+ const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
1793
+ if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
1794
+ errors.push('trialEndingDays must be a whole number of days between 0 and 365');
1453
1795
  if (input.mock &&
1454
1796
  input.mockData !== undefined &&
1455
1797
  (typeof input.mockData !== 'object' || input.mockData === null)) {
@@ -1470,6 +1812,8 @@ function resolveConfig(input) {
1470
1812
  mock: input.mock === true,
1471
1813
  mockData: input.mock ? (input.mockData ?? {}) : null,
1472
1814
  theme,
1815
+ trialEndingDays,
1816
+ syncTrialStart: input.syncTrialStart !== false,
1473
1817
  };
1474
1818
  }
1475
1819
 
@@ -1598,8 +1942,10 @@ function withdrawalWaiverText(serverVersion, locale, seller) {
1598
1942
  * extends it with `getOffer()` / `showPaywall()`.
1599
1943
  *
1600
1944
  * 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.
1945
+ * `locale`, checkout session IDs and, with a server trial, the trial start date
1946
+ * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
1947
+ * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
1948
+ * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
1603
1949
  */
1604
1950
  /** Server-side offer cache is 5 min; mirror it in memory. */
1605
1951
  const OFFER_TTL_MS = 5 * 60 * 1000;
@@ -1610,12 +1956,30 @@ class ExtenshiPayLite {
1610
1956
  this.endUserRefPromise = null;
1611
1957
  this.offer = null;
1612
1958
  this.offerInflight = null;
1959
+ /** The signing key the server returned in this session; never one read from storage. */
1960
+ this.serverKey = null;
1961
+ /** Trust order for license signatures; see payment/signature.ts. */
1962
+ this.keys = {
1963
+ known: async () => {
1964
+ const pinned = this.config.entitlementPublicKey;
1965
+ const offline = pinned ?? (await this.readSavedServerKey());
1966
+ return [...new Set([this.serverKey, offline].filter((key) => !!key))];
1967
+ },
1968
+ fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
1969
+ };
1613
1970
  this.readyPromise = null;
1614
1971
  this.destroyed = false;
1615
1972
  this.config = resolveConfig(config);
1616
1973
  logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
1617
1974
  this.now = deps.now ?? (() => Date.now());
1618
1975
  this.storage = deps.storage ?? createStorage();
1976
+ this.openUrl = deps.openUrl;
1977
+ this.syncStorage =
1978
+ !this.config.syncTrialStart || this.config.mock
1979
+ ? null
1980
+ : deps.syncStorage === undefined
1981
+ ? createSyncStorage()
1982
+ : deps.syncStorage;
1619
1983
  const transport = deps.transport ??
1620
1984
  (this.config.mock
1621
1985
  ? new MockTransport(this.config.mockData ?? {})
@@ -1628,11 +1992,26 @@ class ExtenshiPayLite {
1628
1992
  cacheTtlMs: this.config.cacheTtlMs,
1629
1993
  source: this.config.mock ? 'mock' : 'network',
1630
1994
  getEndUserRef: () => this.getEndUserRef(),
1631
- getPublicKey: () => this.getPublicKey(),
1995
+ keys: this.keys,
1632
1996
  onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
1997
+ onAccepted: () => {
1998
+ void this.trial.evaluate();
1999
+ void this.rememberTrialStart();
2000
+ },
2001
+ getTrialStartHint: () => this.readTrialStartHint(),
1633
2002
  onError: (error) => this.reportError(error),
1634
2003
  now: this.now,
1635
2004
  });
2005
+ this.trial = new TrialNotifier({
2006
+ storage: this.storage,
2007
+ storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
2008
+ endingDays: this.config.trialEndingDays,
2009
+ getTrial: () => this.entitlements.getTrial(),
2010
+ // A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
2011
+ hasPaidAccess: () => (this.entitlements.getCached()?.items ?? []).some(isLive),
2012
+ emit: (event, trial) => this.emitter.emit(event, trial),
2013
+ now: this.now,
2014
+ });
1636
2015
  this.checkout = new CheckoutManager({
1637
2016
  api: this.api,
1638
2017
  storage: this.storage,
@@ -1646,6 +2025,13 @@ class ExtenshiPayLite {
1646
2025
  (this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
1647
2026
  now: this.now,
1648
2027
  });
2028
+ this.backup = new CloudBackup({
2029
+ storage: this.storage,
2030
+ publishableKey: this.config.publishableKey,
2031
+ apiUrl: this.config.apiUrl,
2032
+ fetch: deps.fetch,
2033
+ mock: this.config.mock,
2034
+ });
1649
2035
  this.recovery = new RecoveryManager({
1650
2036
  api: this.api,
1651
2037
  locale: this.config.locale,
@@ -1659,7 +2045,7 @@ class ExtenshiPayLite {
1659
2045
  envelope.payload.publishableKey !== this.config.publishableKey ||
1660
2046
  !Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
1661
2047
  Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
1662
- (await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid')
2048
+ (await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
1663
2049
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
1664
2050
  this.entitlements.stopAutoRefresh();
1665
2051
  try {
@@ -1677,6 +2063,7 @@ class ExtenshiPayLite {
1677
2063
  this.entitlements.startAutoRefresh();
1678
2064
  }
1679
2065
  },
2066
+ onStorageGrant: (grant) => this.backup.accept(grant),
1680
2067
  });
1681
2068
  if (config.onError)
1682
2069
  this.emitter.on('error', config.onError);
@@ -1722,8 +2109,11 @@ class ExtenshiPayLite {
1722
2109
  catch (error) {
1723
2110
  this.reportError(error);
1724
2111
  }
1725
- if (!this.destroyed)
2112
+ void this.confirmSavedServerKey();
2113
+ if (!this.destroyed) {
1726
2114
  this.entitlements.startAutoRefresh();
2115
+ this.trial.start();
2116
+ }
1727
2117
  }
1728
2118
  /** The anonymous, random id this install is known by. */
1729
2119
  getEndUserRef() {
@@ -1744,6 +2134,16 @@ class ExtenshiPayLite {
1744
2134
  await this.initialize();
1745
2135
  return this.entitlements.get(options);
1746
2136
  }
2137
+ /**
2138
+ * The free trial the application set on the server, from the verified license, or null when
2139
+ * there is none (or the license could not be verified yet). Answers offline from the cached
2140
+ * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
2141
+ * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
2142
+ */
2143
+ async getTrial(options = {}) {
2144
+ await this.getEntitlement(options);
2145
+ return this.entitlements.getTrial();
2146
+ }
1747
2147
  /** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
1748
2148
  async isPaid(sku) {
1749
2149
  return isEntitled(await this.getEntitlement(), sku);
@@ -1827,6 +2227,41 @@ class ExtenshiPayLite {
1827
2227
  throw this.reportError(error);
1828
2228
  }
1829
2229
  }
2230
+ /**
2231
+ * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
2232
+ * hosted restore page shows the storage disclosure and the buyer confirms with
2233
+ * the code from the purchase email. `cloudBackup` in the result says whether it is
2234
+ * on. Buyers only; consent is recorded by the server.
2235
+ */
2236
+ enableCloudBackup(options = {}) {
2237
+ return this.restorePurchase({ ...options, purpose: 'storage' });
2238
+ }
2239
+ /**
2240
+ * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
2241
+ * while cloud backup is off on this installation. Extension pages and background
2242
+ * only: it rejects in a content script, and must never be sent to one.
2243
+ */
2244
+ async cloudBackupToken() {
2245
+ return this.backup.token();
2246
+ }
2247
+ /** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
2248
+ async disableCloudBackup() {
2249
+ try {
2250
+ await this.backup.disable();
2251
+ }
2252
+ catch (error) {
2253
+ throw this.reportError(error);
2254
+ }
2255
+ }
2256
+ /** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
2257
+ async deleteCloudBackup() {
2258
+ try {
2259
+ await this.backup.delete();
2260
+ }
2261
+ catch (error) {
2262
+ throw this.reportError(error);
2263
+ }
2264
+ }
1830
2265
  /** Read-only license view. Entitlements retain cache/signature/offline semantics. */
1831
2266
  async getLicenseSummary(options = {}) {
1832
2267
  await this.initialize();
@@ -1896,6 +2331,7 @@ class ExtenshiPayLite {
1896
2331
  destroy() {
1897
2332
  this.destroyed = true;
1898
2333
  this.recovery.stop();
2334
+ this.trial.stop();
1899
2335
  this.entitlements.stopAutoRefresh();
1900
2336
  this.emitter.removeAll();
1901
2337
  }
@@ -1907,8 +2343,9 @@ class ExtenshiPayLite {
1907
2343
  if (!this.offerInflight) {
1908
2344
  this.offerInflight = this.api
1909
2345
  .getOffer(this.config.locale)
1910
- .then((value) => {
2346
+ .then(async (value) => {
1911
2347
  this.offer = { value, fetchedAt: this.now() };
2348
+ await this.rememberServerKey(value.entitlementPublicKey);
1912
2349
  return value;
1913
2350
  })
1914
2351
  .finally(() => {
@@ -1917,8 +2354,88 @@ class ExtenshiPayLite {
1917
2354
  }
1918
2355
  return this.offerInflight;
1919
2356
  }
1920
- async getPublicKey() {
1921
- return this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey;
2357
+ get serverKeyStorageKey() {
2358
+ return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
2359
+ }
2360
+ async readSavedServerKey() {
2361
+ try {
2362
+ const value = await this.storage.get(this.serverKeyStorageKey);
2363
+ return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
2364
+ }
2365
+ catch {
2366
+ return null;
2367
+ }
2368
+ }
2369
+ /**
2370
+ * Keeps the server's key next to the license cache so a restart with no network can verify it.
2371
+ * Not with a bundled key: that one already covers the restart, and storage stays untrusted.
2372
+ */
2373
+ async rememberServerKey(key) {
2374
+ if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
2375
+ return;
2376
+ this.serverKey = key;
2377
+ if (this.config.entitlementPublicKey || this.config.mock)
2378
+ return;
2379
+ try {
2380
+ if ((await this.readSavedServerKey()) !== key)
2381
+ await this.storage.set(this.serverKeyStorageKey, key);
2382
+ }
2383
+ catch (error) {
2384
+ logger.debug('signing key not saved', error);
2385
+ }
2386
+ }
2387
+ /**
2388
+ * A license verified with the saved key alone is checked against the server once per start:
2389
+ * when the server's key differs (rotation, or an edited storage) the license is fetched again,
2390
+ * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
2391
+ */
2392
+ async confirmSavedServerKey() {
2393
+ const used = this.entitlements.verifiedKey;
2394
+ if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
2395
+ return;
2396
+ try {
2397
+ if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
2398
+ return;
2399
+ }
2400
+ catch {
2401
+ return;
2402
+ }
2403
+ try {
2404
+ await this.entitlements.refresh();
2405
+ }
2406
+ catch {
2407
+ await this.entitlements.reverify().catch((error) => this.reportError(error));
2408
+ }
2409
+ }
2410
+ get trialStartKey() {
2411
+ return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
2412
+ }
2413
+ /** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
2414
+ async readTrialStartHint() {
2415
+ if (!this.syncStorage)
2416
+ return null;
2417
+ try {
2418
+ const value = await this.syncStorage.get(this.trialStartKey);
2419
+ return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
2420
+ }
2421
+ catch {
2422
+ return null;
2423
+ }
2424
+ }
2425
+ /** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
2426
+ async rememberTrialStart() {
2427
+ const trial = this.entitlements.getTrial();
2428
+ if (!this.syncStorage || !trial)
2429
+ return;
2430
+ try {
2431
+ const synced = await this.readTrialStartHint();
2432
+ if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
2433
+ return;
2434
+ await this.syncStorage.set(this.trialStartKey, trial.startedAt);
2435
+ }
2436
+ catch (error) {
2437
+ logger.debug('trial start not synced', error);
2438
+ }
1922
2439
  }
1923
2440
  reportError(error) {
1924
2441
  const err = ExtenshiPayError.from(error);
@@ -1929,5 +2446,5 @@ class ExtenshiPayLite {
1929
2446
  }
1930
2447
  ExtenshiPayLite.version = VERSION;
1931
2448
 
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 };
2449
+ 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_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
2450
  //# sourceMappingURL=core.mjs.map