@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.js 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
  (function (global, factory) {
8
8
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
@@ -52,6 +52,8 @@
52
52
  * none — never had it
53
53
  */
54
54
  const PAY_ENTITLEMENT_STATUSES = ['active', 'grace', 'expired', 'none'];
55
+ // Outside the seller SKU grammar. Issued only in a signed projection, never in the sales ledger.
56
+ const PAY_REGIONAL_ACCESS_SKU = '@regional-free';
55
57
  /**
56
58
  * Version of the buyer-facing withdrawal waiver text the paywall shows (EU/EEA
57
59
  * digital content, Directive 2011/83/EU art. 16(m); UK CCR 2013 reg. 37). The
@@ -92,6 +94,14 @@
92
94
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
93
95
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
94
96
  }
97
+ /**
98
+ * `storage`: the buyer turns on the cloud copy of the extension's settings. The
99
+ * hosted page shows the storage disclosure; the claim records consent. Additive:
100
+ * a session without a purpose is a plain restore.
101
+ */
102
+ const PAY_RESTORE_PURPOSES = ['restore', 'storage'];
103
+ /** From `shared-types/storage.ts`: `est_` + 32 random bytes, base64url. */
104
+ const STORAGE_TOKEN_RE = /^est_[A-Za-z0-9_-]{43}$/;
95
105
 
96
106
  const ERROR_CODES = {
97
107
  INVALID_CONFIG: 'INVALID_CONFIG',
@@ -163,7 +173,7 @@
163
173
  * developed with no backend: offers and entitlements come from `mockData`, a
164
174
  * mock checkout completes after `claimAfterPolls` polls and grants the SKU.
165
175
  */
166
- const DAY_MS = 24 * 60 * 60 * 1000;
176
+ const DAY_MS$1 = 24 * 60 * 60 * 1000;
167
177
  /** Accepts the same optional `withdrawalWaiver` input as the BFF; anything else is no consent. */
168
178
  function mockConsent(value) {
169
179
  const consent = value;
@@ -181,6 +191,10 @@
181
191
  this.claimAfterPolls = data.claimAfterPolls ?? 1;
182
192
  this.withdrawalWaiver =
183
193
  data.withdrawalWaiver === undefined ? { version: PAY_WITHDRAWAL_WAIVER_VERSION } : data.withdrawalWaiver;
194
+ this.seller = data.seller;
195
+ this.trial = null;
196
+ if (data.trial)
197
+ this.setTrial(data.trial.days, data.trial.startedAt);
184
198
  }
185
199
  async call(procedure, _kind, input) {
186
200
  switch (procedure) {
@@ -202,6 +216,14 @@
202
216
  setEntitlements(items) {
203
217
  this.entitlements = [...items];
204
218
  }
219
+ /** Previews a server trial of `days` from `startedAt` (default now); `null` removes it. */
220
+ setTrial(days, startedAt = new Date().toISOString()) {
221
+ const start = Date.parse(startedAt);
222
+ this.trial =
223
+ days === null || !Number.isFinite(start)
224
+ ? null
225
+ : { startedAt: new Date(start).toISOString(), endsAt: new Date(start + days * DAY_MS$1).toISOString() };
226
+ }
205
227
  cancelSession(sessionId) {
206
228
  const session = this.sessions.get(sessionId);
207
229
  if (session)
@@ -221,6 +243,7 @@
221
243
  offers: [...this.offers],
222
244
  entitlementPublicKey: null,
223
245
  withdrawalWaiver: this.withdrawalWaiver ? { ...this.withdrawalWaiver } : null,
246
+ ...(this.seller !== undefined && { seller: this.seller ? { ...this.seller } : null }),
224
247
  };
225
248
  }
226
249
  createCheckout(sku, withdrawalWaiver) {
@@ -258,7 +281,7 @@
258
281
  grant(sku) {
259
282
  const offer = this.offers.find((o) => o.sku === sku);
260
283
  const expiresAt = offer?.kind === 'subscription'
261
- ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS).toISOString()
284
+ ? new Date(Date.now() + (offer.interval === 'year' ? 365 : 30) * DAY_MS$1).toISOString()
262
285
  : null;
263
286
  this.entitlements = [
264
287
  ...this.entitlements.filter((item) => item.sku !== sku),
@@ -280,6 +303,7 @@
280
303
  endUserRef,
281
304
  entitlements: [...this.entitlements],
282
305
  issuedAt: new Date().toISOString(),
306
+ ...(this.trial ? { trial: { ...this.trial } } : {}),
283
307
  },
284
308
  signature: null,
285
309
  alg: null,
@@ -293,12 +317,17 @@
293
317
  this.transport = transport;
294
318
  this.publishableKey = publishableKey;
295
319
  }
296
- /** `locale` opens the hosted recovery page (and its email) in the user's language. */
297
- createRestoreSession(claimChallenge, locale) {
320
+ /**
321
+ * `locale` opens the hosted recovery page (and its email) in the user's language.
322
+ * `purpose` is sent only for `storage`: a plain restore keeps the request older
323
+ * BFFs know, and their non-strict zod input strips the key anyway.
324
+ */
325
+ createRestoreSession(claimChallenge, locale, purpose) {
298
326
  return this.transport.call('pay.createRestoreSession', 'mutation', {
299
327
  publishableKey: this.publishableKey,
300
328
  claimChallenge,
301
329
  ...(locale ? { locale } : {}),
330
+ ...(purpose === 'storage' ? { purpose } : {}),
302
331
  });
303
332
  }
304
333
  claimRestoreSession(sessionId, claimSecret) {
@@ -337,10 +366,12 @@
337
366
  endUserRef,
338
367
  });
339
368
  }
340
- getEntitlement(endUserRef) {
369
+ /** `trialStartedHint`: the trial start kept in storage.sync; the server only lets it move a start earlier. */
370
+ getEntitlement(endUserRef, trialStartedHint) {
341
371
  return this.transport.call('pay.getEntitlement', 'query', {
342
372
  publishableKey: this.publishableKey,
343
373
  endUserRef,
374
+ ...(trialStartedHint ? { trialStartedHint } : {}),
344
375
  });
345
376
  }
346
377
  getPortalUrl(endUserRef, customerId, locale) {
@@ -738,6 +769,118 @@
738
769
  openInNewTab: openInNewTab
739
770
  });
740
771
 
772
+ /**
773
+ * Cloud copy of the extension's settings (`@extenshi/storage`). Pay owns the
774
+ * token: only a verified restore claim issues it; this module keeps it in the
775
+ * SDK's storage (`storage.local`) and revokes it. `@extenshi/storage` reads it
776
+ * through `cloudBackupToken()`. The token is never logged and never answered to
777
+ * a content script: route those calls to the background.
778
+ */
779
+ const REQUEST_TIMEOUT_MS = 10000;
780
+ /** True in a content script, where the token must not be handed out. */
781
+ function inContentScript() {
782
+ const g = globalThis;
783
+ return !!(g.chrome?.runtime?.id || g.browser?.runtime?.id) && !(g.chrome?.tabs || g.browser?.tabs);
784
+ }
785
+ class CloudBackup {
786
+ constructor(options) {
787
+ this.options = options;
788
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
789
+ }
790
+ get storageKey() {
791
+ return `extenshi-pay:${this.options.publishableKey}:storageToken`;
792
+ }
793
+ /** Stores or clears the token from a verified claim. Never throws: the licence is already restored. */
794
+ async accept(grant) {
795
+ if (!grant || typeof grant !== 'object')
796
+ return undefined;
797
+ try {
798
+ if (grant.state === 'granted') {
799
+ if (typeof grant.token !== 'string' || !STORAGE_TOKEN_RE.test(grant.token))
800
+ return undefined;
801
+ await this.options.storage.set(this.storageKey, grant.token);
802
+ return 'on';
803
+ }
804
+ if (grant.state === 'unavailable') {
805
+ await this.options.storage.remove(this.storageKey);
806
+ return grant.reason === 'LICENSE_REQUIRED' ? 'license_required' : 'no_consent';
807
+ }
808
+ }
809
+ catch {
810
+ logger.warn('cloud backup state could not be saved');
811
+ }
812
+ return undefined;
813
+ }
814
+ async token() {
815
+ this.assertTrustedContext();
816
+ const value = await this.options.storage.get(this.storageKey);
817
+ return typeof value === 'string' && STORAGE_TOKEN_RE.test(value) ? value : null;
818
+ }
819
+ /** Revokes this installation's token. A token the server no longer knows (401) is forgotten too. */
820
+ async disable() {
821
+ const token = await this.token();
822
+ if (!token)
823
+ return;
824
+ if (!this.options.mock) {
825
+ const status = await this.request('/v1/storage/grant', token);
826
+ if (status !== 401)
827
+ this.throwUnlessOk(status);
828
+ }
829
+ await this.options.storage.remove(this.storageKey);
830
+ }
831
+ /** Deletes the buyer's cloud copy and turns the backup off on every device. */
832
+ async delete() {
833
+ const token = await this.token();
834
+ if (!token)
835
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Cloud backup is off on this installation; turn it on to delete the cloud copy');
836
+ if (!this.options.mock) {
837
+ const status = await this.request('/v1/storage/data', token);
838
+ if (status === 401) {
839
+ // The server no longer accepts this token, so it is useless here; the copy was not deleted.
840
+ await this.options.storage.remove(this.storageKey);
841
+ 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 });
842
+ }
843
+ this.throwUnlessOk(status);
844
+ }
845
+ await this.options.storage.remove(this.storageKey);
846
+ }
847
+ assertTrustedContext() {
848
+ if (inContentScript())
849
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_REQUEST, 'Use cloud backup from an extension page or background context');
850
+ }
851
+ throwUnlessOk(status) {
852
+ if (status >= 200 && status < 300)
853
+ return;
854
+ if (status === 429)
855
+ throw new ExtenshiPayError(ERROR_CODES.RATE_LIMITED, 'Too many requests', { httpStatus: status });
856
+ if (status >= 500)
857
+ throw new ExtenshiPayError(ERROR_CODES.GATEWAY_UNAVAILABLE, `HTTP ${status}`, { httpStatus: status });
858
+ throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, `HTTP ${status}`, { httpStatus: status });
859
+ }
860
+ async request(path, token) {
861
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
862
+ const timer = controller ? setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) : null;
863
+ try {
864
+ const response = await this.fetchImpl(`${this.options.apiUrl}${path}`, {
865
+ method: 'DELETE',
866
+ headers: { Authorization: `Bearer ${token}` },
867
+ credentials: 'omit',
868
+ signal: controller?.signal,
869
+ });
870
+ return response.status;
871
+ }
872
+ catch (error) {
873
+ if (controller?.signal.aborted)
874
+ throw new ExtenshiPayError(ERROR_CODES.TIMEOUT, `Request timed out after ${REQUEST_TIMEOUT_MS}ms`);
875
+ throw new ExtenshiPayError(ERROR_CODES.NETWORK_ERROR, 'Network request failed', { cause: error });
876
+ }
877
+ finally {
878
+ if (timer !== null)
879
+ clearTimeout(timer);
880
+ }
881
+ }
882
+ }
883
+
741
884
  /** Pure helpers over the entitlement projection. Features come from the items' `features[]`. */
742
885
  const LIVE_STATUSES = new Set(['active', 'grace']);
743
886
  function isLive(item) {
@@ -792,9 +935,17 @@
792
935
  /**
793
936
  * Ed25519 verification of the entitlement projection.
794
937
  *
795
- * Tamper resistance, not DRM. Trust comes from the developer's bundled key or
796
- * a key fetched over HTTPS, never from editable extension storage. Callers must
797
- * deny access for both invalid and unverified envelopes outside explicit mocks.
938
+ * Tamper resistance, not DRM. Callers must deny access for both invalid and
939
+ * unverified envelopes outside explicit mocks.
940
+ *
941
+ * Which keys are trusted, in order (`PublicKeySource`, built in core/extenshi-pay.ts):
942
+ * 1. the key the server returned over HTTPS in this session;
943
+ * 2. the bundled `entitlementPublicKey`, when the developer configured one. It pins
944
+ * verification without a round-trip: a key read from extension storage is then never used;
945
+ * 3. without a bundled key, the server key saved in `storage.local` next to the
946
+ * license cache, so a restart with no network can still verify the cache.
947
+ * When none of them verifies an envelope the server is asked for its current key once
948
+ * (a rotated key), and that answer decides.
798
949
  */
799
950
  function base64ToBytes(base64) {
800
951
  const binary = atob(base64);
@@ -829,6 +980,140 @@
829
980
  return 'invalid';
830
981
  }
831
982
  }
983
+ const PUBLIC_KEY_RE = /^[A-Za-z0-9+/]{43}=$/;
984
+ /**
985
+ * `invalid` only when the server's current key was checked too (or the envelope carries no
986
+ * signature at all). A mismatch against known keys while the server is unreachable is
987
+ * `unverified`: it may be a rotated key, and no paid access is granted either way.
988
+ */
989
+ async function verifyWithKeys(envelope, source) {
990
+ if (!envelope.signature || envelope.alg !== 'ed25519')
991
+ return { verdict: 'invalid', key: null };
992
+ let known = [];
993
+ try {
994
+ known = await source.known();
995
+ }
996
+ catch {
997
+ known = [];
998
+ }
999
+ let mismatch = false;
1000
+ for (const key of known) {
1001
+ const verdict = await verifyEntitlementSignature(envelope, key);
1002
+ if (verdict === 'valid')
1003
+ return { verdict, key };
1004
+ if (verdict === 'invalid')
1005
+ mismatch = true;
1006
+ }
1007
+ let current;
1008
+ try {
1009
+ current = await source.fetchCurrent();
1010
+ }
1011
+ catch {
1012
+ return { verdict: 'unverified', key: null };
1013
+ }
1014
+ if (current && !known.includes(current)) {
1015
+ const verdict = await verifyEntitlementSignature(envelope, current);
1016
+ return { verdict, key: verdict === 'valid' ? current : null };
1017
+ }
1018
+ return { verdict: mismatch ? 'invalid' : 'unverified', key: null };
1019
+ }
1020
+
1021
+ /**
1022
+ * The free trial an application configures on the server (`trialDays`).
1023
+ *
1024
+ * The server starts one clock per installation at its first license read and
1025
+ * signs `{ startedAt, endsAt }` into the entitlement, so the trial comes from
1026
+ * the verified license like paid access does: no start date in extension
1027
+ * storage, nothing a device clock or a storage edit can move. Offline, the
1028
+ * cached license answers for up to 48 hours.
1029
+ *
1030
+ * `trial:ending` / `trial:ended` fire once per installation and trial (the
1031
+ * marker is kept in the SDK's storage), and not while the user has paid
1032
+ * access. Render state from `getTrial()`; the events are one-time notices.
1033
+ */
1034
+ const DAY_MS = 24 * 60 * 60 * 1000;
1035
+ /** Re-check at least daily: long timers are clamped by browsers and lost when a service worker sleeps. */
1036
+ const MAX_TIMER_MS$1 = DAY_MS;
1037
+ /** The trial as of `clock`, or null when the license carries none (or a malformed one). */
1038
+ function trialState(trial, clock) {
1039
+ if (!trial)
1040
+ return null;
1041
+ const startedAt = Date.parse(trial.startedAt);
1042
+ const endsAt = Date.parse(trial.endsAt);
1043
+ if (!Number.isFinite(startedAt) || !Number.isFinite(endsAt))
1044
+ return null;
1045
+ // The server's signed time is a floor: a clock turned back cannot reopen an ended trial.
1046
+ const now = Number.isFinite(clock.issuedAt) ? Math.max(clock.now, clock.issuedAt) : clock.now;
1047
+ const left = endsAt - now;
1048
+ return {
1049
+ active: left > 0 && clock.checked,
1050
+ startedAt: trial.startedAt,
1051
+ endsAt: trial.endsAt,
1052
+ daysLeft: left > 0 ? Math.ceil(left / DAY_MS) : 0,
1053
+ requiresOnlineCheck: left > 0 && !clock.checked,
1054
+ };
1055
+ }
1056
+ class TrialNotifier {
1057
+ constructor(options) {
1058
+ this.options = options;
1059
+ this.timer = null;
1060
+ this.running = false;
1061
+ this.pending = Promise.resolve();
1062
+ }
1063
+ start() {
1064
+ this.running = true;
1065
+ void this.evaluate();
1066
+ }
1067
+ stop() {
1068
+ this.running = false;
1069
+ this.clearTimer();
1070
+ }
1071
+ /** Checks the held license; serialized, so two refreshes never send one event twice. */
1072
+ evaluate() {
1073
+ this.pending = this.pending.then(() => this.check()).catch((error) => logger.debug('trial check', error));
1074
+ return this.pending;
1075
+ }
1076
+ async check() {
1077
+ if (!this.running)
1078
+ return;
1079
+ this.clearTimer();
1080
+ const trial = this.options.getTrial();
1081
+ if (!trial)
1082
+ return;
1083
+ const now = this.options.now();
1084
+ const endsAt = Date.parse(trial.endsAt);
1085
+ const endingAt = endsAt - this.options.endingDays * DAY_MS;
1086
+ const event = trial.daysLeft === 0
1087
+ ? 'trial:ended'
1088
+ : trial.active && this.options.endingDays > 0 && now >= endingAt
1089
+ ? 'trial:ending'
1090
+ : null;
1091
+ if (event && !this.options.hasPaidAccess())
1092
+ await this.send(event, trial);
1093
+ if (!this.running || trial.daysLeft === 0)
1094
+ return;
1095
+ const next = [endingAt, endsAt].find((at) => at > now) ?? endsAt;
1096
+ this.timer = setTimeout(() => {
1097
+ this.timer = null;
1098
+ void this.evaluate();
1099
+ }, Math.max(1000, Math.min(next - now, MAX_TIMER_MS$1)));
1100
+ }
1101
+ async send(event, trial) {
1102
+ const id = `${trial.startedAt}|${trial.endsAt}`;
1103
+ const field = event === 'trial:ended' ? 'ended' : 'ending';
1104
+ const stored = (await this.options.storage.get(this.options.storageKey));
1105
+ const sent = stored && typeof stored === 'object' ? stored : {};
1106
+ if (sent[field] === id || !this.running)
1107
+ return;
1108
+ await this.options.storage.set(this.options.storageKey, { ...sent, [field]: id });
1109
+ this.options.emit(event, trial);
1110
+ }
1111
+ clearTimer() {
1112
+ if (this.timer !== null)
1113
+ clearTimeout(this.timer);
1114
+ this.timer = null;
1115
+ }
1116
+ }
832
1117
 
833
1118
  /**
834
1119
  * Entitlement cache + refresh.
@@ -836,13 +1121,18 @@
836
1121
  * The cached envelope is a cache OF the server projection, never a second
837
1122
  * source of truth: it is verified when stored and re-verified on load (once
838
1123
  * the project's public key is known), served without a round-trip while the
839
- * TTL holds, served for up to 48 hours after signed issuance when the network is down, and expired
1124
+ * TTL holds, served after signed issuance for the signed `offlineSeconds` (48 hours when absent) when the network is down, and expired
840
1125
  * locally by `expiresAt`. Background refresh polls at most every 15 minutes
841
1126
  * and backs off exponentially on errors.
842
1127
  */
843
1128
  const MIN_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
844
1129
  const MAX_REFRESH_BACKOFF_MS = 6 * 60 * 60 * 1000;
1130
+ /** Offline allowance when the signed license names none (older servers and caches). */
845
1131
  const MAX_OFFLINE_AGE_MS = 48 * 60 * 60 * 1000;
1132
+ /** Ceiling for a signed `offlineSeconds`. */
1133
+ const MAX_SIGNED_OFFLINE_AGE_MS = 366 * 24 * 60 * 60 * 1000;
1134
+ /** `setTimeout` fires at once past this delay. */
1135
+ const MAX_TIMER_MS = 2 ** 31 - 1;
846
1136
  // Allow small server/client clock skew without granting more than the signed age limit.
847
1137
  const MAX_CLOCK_SKEW_MS = 5 * 60 * 1000;
848
1138
  const CACHE_VERSION = 1;
@@ -861,6 +1151,8 @@
861
1151
  this.options = options;
862
1152
  this.held = null;
863
1153
  this.inflight = null;
1154
+ /** Device clock against the server's at the last license check; null within 5 minutes. */
1155
+ this.clockSkew = null;
864
1156
  this.timer = null;
865
1157
  this.refreshGeneration = 0;
866
1158
  this.deadlineTimer = null;
@@ -902,8 +1194,10 @@
902
1194
  envelope: JSON.parse(JSON.stringify(record.envelope)),
903
1195
  fetchedAt: record.fetchedAt,
904
1196
  verified: false,
1197
+ key: null,
905
1198
  source: this.source === 'mock' ? 'mock' : 'cache',
906
1199
  };
1200
+ this.measureClockSkew(record.fetchedAt, Date.parse(record.envelope.payload.issuedAt));
907
1201
  this.lastFingerprint = this.fingerprint();
908
1202
  return this.snapshot();
909
1203
  }
@@ -914,8 +1208,7 @@
914
1208
  if (this.source === 'mock')
915
1209
  return;
916
1210
  const held = this.held;
917
- const key = await this.safePublicKey();
918
- const verdict = await verifyEntitlementSignature(held.envelope, key);
1211
+ const { verdict, key } = await verifyWithKeys(held.envelope, this.options.keys);
919
1212
  if (held !== this.held)
920
1213
  return;
921
1214
  if (verdict === 'invalid') {
@@ -924,19 +1217,39 @@
924
1217
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Cached entitlement signature is invalid');
925
1218
  }
926
1219
  held.verified = verdict === 'valid';
1220
+ held.key = key;
927
1221
  if (!held.verified) {
928
1222
  throw new ExtenshiPayError(ERROR_CODES.VERIFICATION_UNAVAILABLE, 'Entitlement verification requires a trusted key and Ed25519 WebCrypto support');
929
1223
  }
930
1224
  this.scheduleDeadline();
931
1225
  }
1226
+ /** The key the held license was verified with; null when there is none or it is unverified. */
1227
+ get verifiedKey() {
1228
+ return this.held?.verified ? this.held.key : null;
1229
+ }
932
1230
  getCached() {
933
1231
  return this.held ? this.snapshot() : null;
934
1232
  }
1233
+ /** The server trial in the held license; null without one, or while the license is unverified. */
1234
+ getTrial() {
1235
+ const held = this.held;
1236
+ if (!held || (this.source !== 'mock' && !held.verified))
1237
+ return null;
1238
+ const now = this.now();
1239
+ const issuedAt = Date.parse(held.envelope.payload.issuedAt);
1240
+ return trialState(held.envelope.payload.trial, {
1241
+ now,
1242
+ issuedAt,
1243
+ // The same offline rule as paid access (snapshot): the allowance from the signed issue, no clock turned back.
1244
+ checked: this.source === 'mock' ||
1245
+ (now >= held.fetchedAt && now < this.offlineDeadline() && now + MAX_CLOCK_SKEW_MS >= issuedAt),
1246
+ });
1247
+ }
935
1248
  isFresh() {
936
1249
  return (this.held !== null &&
937
1250
  (this.source === 'mock' || (this.held.verified && !this.snapshot().requiresOnlineCheck)) &&
938
1251
  this.now() >= this.held.fetchedAt &&
939
- this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, MAX_OFFLINE_AGE_MS));
1252
+ this.now() - this.held.fetchedAt < Math.min(this.options.cacheTtlMs, this.offlineAgeMs()));
940
1253
  }
941
1254
  async get(options = {}) {
942
1255
  if (!options.force && this.isFresh())
@@ -951,7 +1264,7 @@
951
1264
  logger.debug('serving cached entitlement after refresh failure', err.code);
952
1265
  return this.snapshot();
953
1266
  }
954
- return EMPTY_ENTITLEMENT;
1267
+ return this.snapshot();
955
1268
  }
956
1269
  }
957
1270
  /** Fetches the projection from the backend, verifies and stores it. */
@@ -959,7 +1272,8 @@
959
1272
  if (!this.inflight) {
960
1273
  this.inflight = (async () => {
961
1274
  const endUserRef = await this.options.getEndUserRef();
962
- const envelope = await this.options.api.getEntitlement(endUserRef);
1275
+ const hint = this.options.getTrialStartHint ? await this.options.getTrialStartHint() : null;
1276
+ const envelope = await this.options.api.getEntitlement(endUserRef, hint);
963
1277
  return this.accept(envelope, this.source);
964
1278
  })().finally(() => {
965
1279
  this.inflight = null;
@@ -981,9 +1295,9 @@
981
1295
  if (envelope.payload.endUserRef !== endUserRef) {
982
1296
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issued for a different endUserRef');
983
1297
  }
984
- const verdict = this.source === 'mock'
985
- ? 'unverified'
986
- : await verifyEntitlementSignature(envelope, await this.safePublicKey());
1298
+ const { verdict, key } = this.source === 'mock'
1299
+ ? { verdict: 'unverified', key: null }
1300
+ : await verifyWithKeys(envelope, this.options.keys);
987
1301
  if (verdict === 'invalid') {
988
1302
  await this.discard();
989
1303
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement signature is invalid');
@@ -993,15 +1307,19 @@
993
1307
  }
994
1308
  const fetchedAt = this.now();
995
1309
  const issuedAt = Date.parse(envelope.payload.issuedAt);
1310
+ // A verified envelope was signed moments ago: its `issuedAt` is the server's clock.
1311
+ if (this.source !== 'mock')
1312
+ this.measureClockSkew(fetchedAt, issuedAt);
996
1313
  if (this.source !== 'mock' && (!Number.isFinite(issuedAt) || issuedAt > fetchedAt + MAX_CLOCK_SKEW_MS)) {
997
1314
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Entitlement issuedAt is invalid or in the future');
998
1315
  }
999
- this.held = { envelope, fetchedAt, verified: verdict === 'valid', source };
1316
+ this.held = { envelope, fetchedAt, verified: verdict === 'valid', key, source };
1000
1317
  const record = { v: CACHE_VERSION, envelope, fetchedAt };
1001
1318
  await this.options.storage.set(this.storageKey, JSON.parse(JSON.stringify(record)));
1002
1319
  this.backoffMs = 0;
1003
1320
  this.scheduleDeadline();
1004
1321
  this.notifyIfChanged();
1322
+ this.options.onAccepted?.();
1005
1323
  return this.snapshot();
1006
1324
  }
1007
1325
  /** Drain an older installation refresh before changing identity. */
@@ -1055,7 +1373,7 @@
1055
1373
  this.deadlineTimer = null;
1056
1374
  this.notifyIfChanged();
1057
1375
  this.scheduleDeadline();
1058
- }, remaining);
1376
+ }, Math.min(remaining, MAX_TIMER_MS));
1059
1377
  }
1060
1378
  schedule(delayMs) {
1061
1379
  const generation = this.refreshGeneration;
@@ -1076,14 +1394,12 @@
1076
1394
  }
1077
1395
  }, delayMs);
1078
1396
  }
1079
- async safePublicKey() {
1080
- try {
1081
- return await this.options.getPublicKey();
1082
- }
1083
- catch (error) {
1084
- logger.debug('public key unavailable; entitlement stays unverified', error);
1085
- return null;
1086
- }
1397
+ measureClockSkew(local, server) {
1398
+ const ms = local - server;
1399
+ this.clockSkew =
1400
+ Number.isFinite(ms) && Math.abs(ms) > MAX_CLOCK_SKEW_MS
1401
+ ? { direction: ms > 0 ? 'ahead' : 'behind', ms: Math.abs(ms) }
1402
+ : null;
1087
1403
  }
1088
1404
  async discard() {
1089
1405
  this.held = null;
@@ -1093,7 +1409,13 @@
1093
1409
  }
1094
1410
  fingerprint() {
1095
1411
  const state = this.snapshot();
1096
- return canonicalJson({ items: state.items, requiresOnlineCheck: state.requiresOnlineCheck });
1412
+ return canonicalJson({
1413
+ items: state.items,
1414
+ requiresOnlineCheck: state.requiresOnlineCheck,
1415
+ ...(state.regionalFreeUntil
1416
+ ? { regionalFreeUntil: state.regionalFreeUntil, features: state.features }
1417
+ : {}),
1418
+ });
1097
1419
  }
1098
1420
  notifyIfChanged() {
1099
1421
  const fingerprint = this.fingerprint();
@@ -1106,16 +1428,31 @@
1106
1428
  if (!this.held)
1107
1429
  return NaN;
1108
1430
  // fetchedAt is untrusted bookkeeping; it may shorten, never extend, a grant.
1109
- return Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + MAX_OFFLINE_AGE_MS;
1431
+ return (Math.min(this.held.fetchedAt, Date.parse(this.held.envelope.payload.issuedAt)) + this.offlineAgeMs());
1432
+ }
1433
+ /** The signed allowance of the held license, or 48 hours when it names none. */
1434
+ offlineAgeMs() {
1435
+ const seconds = this.held?.envelope.payload.offlineSeconds;
1436
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0)
1437
+ return MAX_OFFLINE_AGE_MS;
1438
+ return Math.min(seconds * 1000, MAX_SIGNED_OFFLINE_AGE_MS);
1110
1439
  }
1111
1440
  snapshot() {
1112
1441
  if (!this.held)
1113
- return EMPTY_ENTITLEMENT;
1442
+ return this.clockSkew ? { ...EMPTY_ENTITLEMENT, clockSkew: this.clockSkew } : EMPTY_ENTITLEMENT;
1114
1443
  if (this.source !== 'mock' && !this.held.verified) {
1115
- return { ...EMPTY_ENTITLEMENT, requiresOnlineCheck: true, source: this.held.source };
1116
- }
1117
- const items = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1118
- const hasPaidAccess = collectFeatures(items).length > 0 ||
1444
+ return {
1445
+ ...EMPTY_ENTITLEMENT,
1446
+ requiresOnlineCheck: true,
1447
+ clockSkew: this.clockSkew,
1448
+ source: this.held.source,
1449
+ };
1450
+ }
1451
+ const grants = applyLocalExpiry(JSON.parse(JSON.stringify(this.held.envelope.payload.entitlements)), this.now());
1452
+ const regional = grants.find((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU && grant.status === 'active');
1453
+ const items = grants.filter((grant) => grant.sku !== PAY_REGIONAL_ACCESS_SKU);
1454
+ const hasPaidAccess = grants.some((grant) => grant.sku === PAY_REGIONAL_ACCESS_SKU) ||
1455
+ collectFeatures(items).length > 0 ||
1119
1456
  items.some((item) => item.status === 'active' || item.status === 'grace');
1120
1457
  const offlineUntil = this.source === 'mock' || !hasPaidAccess ? null : this.offlineDeadline();
1121
1458
  const requiresOnlineCheck = offlineUntil !== null &&
@@ -1125,9 +1462,13 @@
1125
1462
  this.now() + MAX_CLOCK_SKEW_MS < Date.parse(this.held.envelope.payload.issuedAt));
1126
1463
  return {
1127
1464
  items,
1128
- features: requiresOnlineCheck ? [] : collectFeatures(items),
1465
+ features: requiresOnlineCheck ? [] : collectFeatures(grants),
1466
+ ...(regional?.expiresAt && !requiresOnlineCheck
1467
+ ? { regionalFreeUntil: Date.parse(regional.expiresAt) }
1468
+ : {}),
1129
1469
  requiresOnlineCheck,
1130
1470
  offlineUntil,
1471
+ clockSkew: this.clockSkew,
1131
1472
  verified: this.held.verified,
1132
1473
  issuedAt: this.held.envelope.payload.issuedAt,
1133
1474
  fetchedAt: this.held.fetchedAt,
@@ -1216,6 +1557,16 @@
1216
1557
  this.map.delete(key);
1217
1558
  }
1218
1559
  }
1560
+ /**
1561
+ * The browser's synced storage (`storage.sync`), or null outside an extension. The SDK keeps
1562
+ * only the trial start there (never `endUserRef`), so devices on one synced account share the
1563
+ * trial. Uninstalling clears it from the account, so it does not survive a reinstall.
1564
+ */
1565
+ function createSyncStorage() {
1566
+ const g = extensionGlobals();
1567
+ const area = g.chrome?.storage?.sync ?? g.browser?.storage?.sync;
1568
+ return area ? new ExtensionStorage(area) : null;
1569
+ }
1219
1570
  function createStorage() {
1220
1571
  const g = extensionGlobals();
1221
1572
  const area = g.chrome?.storage?.local ?? g.browser?.storage?.local;
@@ -1272,7 +1623,7 @@
1272
1623
  const secret = Array.from(cryptoApi.getRandomValues(new Uint8Array(32)), (b) => b.toString(16).padStart(2, '0')).join('');
1273
1624
  const hash = await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(secret));
1274
1625
  const challenge = Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');
1275
- const created = await this.options.api.createRestoreSession(challenge, this.options.locale);
1626
+ const created = await this.options.api.createRestoreSession(challenge, this.options.locale, options.purpose);
1276
1627
  if (!Number.isFinite(Date.parse(created.expiresAt)))
1277
1628
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery expiry');
1278
1629
  const pending = { sessionId: created.sessionId, expiresAt: created.expiresAt, claimSecret: secret };
@@ -1332,8 +1683,9 @@
1332
1683
  break;
1333
1684
  if (claim.state === 'complete') {
1334
1685
  const entitlement = await this.options.onComplete(claim.endUserRef, claim.entitlement);
1686
+ const cloudBackup = await this.options.onStorageGrant?.(claim.storage);
1335
1687
  await this.options.storage.remove(this.pendingKey);
1336
- return { state: 'complete', entitlement };
1688
+ return { state: 'complete', entitlement, ...(cloudBackup ? { cloudBackup } : {}) };
1337
1689
  }
1338
1690
  if (claim.state !== 'pending')
1339
1691
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Invalid recovery response');
@@ -1362,9 +1714,10 @@
1362
1714
  const DEFAULT_API_URL = 'https://bff.extenshi.io';
1363
1715
  const DEFAULT_CACHE_TTL_MS = 60 * 60 * 1000;
1364
1716
  const MAX_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1717
+ const DEFAULT_TRIAL_ENDING_DAYS = 2;
1365
1718
 
1366
1719
  /** Kept in sync with package.json by tests/unit/version.test.ts. */
1367
- const VERSION = '0.9.0';
1720
+ const VERSION = '0.12.0';
1368
1721
 
1369
1722
  /**
1370
1723
  * The user's language as the SDK sends it. Kept apart from the paywall
@@ -1434,7 +1787,7 @@
1434
1787
  if (!isHttpUrl(apiUrl))
1435
1788
  errors.push('apiUrl must be an http(s) URL');
1436
1789
  const entitlementPublicKey = input.entitlementPublicKey ?? null;
1437
- if (entitlementPublicKey !== null && !/^[A-Za-z0-9+/]{43}=$/.test(entitlementPublicKey)) {
1790
+ if (entitlementPublicKey !== null && !PUBLIC_KEY_RE.test(entitlementPublicKey)) {
1438
1791
  errors.push('entitlementPublicKey must be a base64-encoded 32-byte Ed25519 public key');
1439
1792
  }
1440
1793
  const environment = input.environment ?? 'production';
@@ -1456,6 +1809,9 @@
1456
1809
  const theme = input.theme ?? {};
1457
1810
  if (theme.mode !== undefined && !THEME_MODES.has(theme.mode))
1458
1811
  errors.push('theme.mode must be light, dark or auto');
1812
+ const trialEndingDays = input.trialEndingDays ?? DEFAULT_TRIAL_ENDING_DAYS;
1813
+ if (!Number.isInteger(trialEndingDays) || trialEndingDays < 0 || trialEndingDays > 365)
1814
+ errors.push('trialEndingDays must be a whole number of days between 0 and 365');
1459
1815
  if (input.mock &&
1460
1816
  input.mockData !== undefined &&
1461
1817
  (typeof input.mockData !== 'object' || input.mockData === null)) {
@@ -1476,6 +1832,8 @@
1476
1832
  mock: input.mock === true,
1477
1833
  mockData: input.mock ? (input.mockData ?? {}) : null,
1478
1834
  theme,
1835
+ trialEndingDays,
1836
+ syncTrialStart: input.syncTrialStart !== false,
1479
1837
  };
1480
1838
  }
1481
1839
 
@@ -1604,8 +1962,10 @@
1604
1962
  * extends it with `getOffer()` / `showPaywall()`.
1605
1963
  *
1606
1964
  * Data that leaves the extension: `publishableKey`, `endUserRef`, `sku`,
1607
- * `locale` and checkout session IDs. Explicit recovery also sends its session ID,
1608
- * challenge and claim secret (POST body). Email stays on the hosted page.
1965
+ * `locale`, checkout session IDs and, with a server trial, the trial start date
1966
+ * the server issued (`trialStartedHint`, kept in storage.sync). Explicit recovery also sends its session ID,
1967
+ * challenge and claim secret (POST body). Email stays on the hosted page. With cloud backup, the
1968
+ * storage token goes only to `/v1/storage` (as a bearer), never in a message to a content script.
1609
1969
  */
1610
1970
  /** Server-side offer cache is 5 min; mirror it in memory. */
1611
1971
  const OFFER_TTL_MS = 5 * 60 * 1000;
@@ -1616,12 +1976,30 @@
1616
1976
  this.endUserRefPromise = null;
1617
1977
  this.offer = null;
1618
1978
  this.offerInflight = null;
1979
+ /** The signing key the server returned in this session; never one read from storage. */
1980
+ this.serverKey = null;
1981
+ /** Trust order for license signatures; see payment/signature.ts. */
1982
+ this.keys = {
1983
+ known: async () => {
1984
+ const pinned = this.config.entitlementPublicKey;
1985
+ const offline = pinned ?? (await this.readSavedServerKey());
1986
+ return [...new Set([this.serverKey, offline].filter((key) => !!key))];
1987
+ },
1988
+ fetchCurrent: async () => (await this.fetchOffer(true)).entitlementPublicKey,
1989
+ };
1619
1990
  this.readyPromise = null;
1620
1991
  this.destroyed = false;
1621
1992
  this.config = resolveConfig(config);
1622
1993
  logger.configure({ logLevel: this.config.logLevel, debug: this.config.debug });
1623
1994
  this.now = deps.now ?? (() => Date.now());
1624
1995
  this.storage = deps.storage ?? createStorage();
1996
+ this.openUrl = deps.openUrl;
1997
+ this.syncStorage =
1998
+ !this.config.syncTrialStart || this.config.mock
1999
+ ? null
2000
+ : deps.syncStorage === undefined
2001
+ ? createSyncStorage()
2002
+ : deps.syncStorage;
1625
2003
  const transport = deps.transport ??
1626
2004
  (this.config.mock
1627
2005
  ? new MockTransport(this.config.mockData ?? {})
@@ -1634,11 +2012,29 @@
1634
2012
  cacheTtlMs: this.config.cacheTtlMs,
1635
2013
  source: this.config.mock ? 'mock' : 'network',
1636
2014
  getEndUserRef: () => this.getEndUserRef(),
1637
- getPublicKey: () => this.getPublicKey(),
2015
+ keys: this.keys,
1638
2016
  onChange: (entitlement) => this.emitter.emit('entitlement:changed', entitlement),
2017
+ onAccepted: () => {
2018
+ void this.trial.evaluate();
2019
+ void this.rememberTrialStart();
2020
+ },
2021
+ getTrialStartHint: () => this.readTrialStartHint(),
1639
2022
  onError: (error) => this.reportError(error),
1640
2023
  now: this.now,
1641
2024
  });
2025
+ this.trial = new TrialNotifier({
2026
+ storage: this.storage,
2027
+ storageKey: `extenshi-pay:${this.config.publishableKey}:trial-events${this.config.mock ? ':mock' : ''}`,
2028
+ endingDays: this.config.trialEndingDays,
2029
+ getTrial: () => this.entitlements.getTrial(),
2030
+ // A paid license still counts while it waits for an online check: no "trial ended" to a buyer.
2031
+ hasPaidAccess: () => {
2032
+ const license = this.entitlements.getCached();
2033
+ return Boolean(license?.regionalFreeUntil || license?.items.some(isLive));
2034
+ },
2035
+ emit: (event, trial) => this.emitter.emit(event, trial),
2036
+ now: this.now,
2037
+ });
1642
2038
  this.checkout = new CheckoutManager({
1643
2039
  api: this.api,
1644
2040
  storage: this.storage,
@@ -1652,6 +2048,13 @@
1652
2048
  (this.config.mock ? (url) => logger.info('mock checkout (no tab opened)', url) : undefined),
1653
2049
  now: this.now,
1654
2050
  });
2051
+ this.backup = new CloudBackup({
2052
+ storage: this.storage,
2053
+ publishableKey: this.config.publishableKey,
2054
+ apiUrl: this.config.apiUrl,
2055
+ fetch: deps.fetch,
2056
+ mock: this.config.mock,
2057
+ });
1655
2058
  this.recovery = new RecoveryManager({
1656
2059
  api: this.api,
1657
2060
  locale: this.config.locale,
@@ -1665,7 +2068,7 @@
1665
2068
  envelope.payload.publishableKey !== this.config.publishableKey ||
1666
2069
  !Number.isFinite(Date.parse(envelope.payload.issuedAt)) ||
1667
2070
  Date.parse(envelope.payload.issuedAt) > this.now() + MAX_CLOCK_SKEW_MS ||
1668
- (await verifyEntitlementSignature(envelope, await this.getPublicKey())) !== 'valid')
2071
+ (await verifyWithKeys(envelope, this.keys)).verdict !== 'valid')
1669
2072
  throw new ExtenshiPayError(ERROR_CODES.INVALID_RESPONSE, 'Recovery requires a verified entitlement for this installation');
1670
2073
  this.entitlements.stopAutoRefresh();
1671
2074
  try {
@@ -1683,6 +2086,7 @@
1683
2086
  this.entitlements.startAutoRefresh();
1684
2087
  }
1685
2088
  },
2089
+ onStorageGrant: (grant) => this.backup.accept(grant),
1686
2090
  });
1687
2091
  if (config.onError)
1688
2092
  this.emitter.on('error', config.onError);
@@ -1728,8 +2132,11 @@
1728
2132
  catch (error) {
1729
2133
  this.reportError(error);
1730
2134
  }
1731
- if (!this.destroyed)
2135
+ void this.confirmSavedServerKey();
2136
+ if (!this.destroyed) {
1732
2137
  this.entitlements.startAutoRefresh();
2138
+ this.trial.start();
2139
+ }
1733
2140
  }
1734
2141
  /** The anonymous, random id this install is known by. */
1735
2142
  getEndUserRef() {
@@ -1750,6 +2157,16 @@
1750
2157
  await this.initialize();
1751
2158
  return this.entitlements.get(options);
1752
2159
  }
2160
+ /**
2161
+ * The free trial the application set on the server, from the verified license, or null when
2162
+ * there is none (or the license could not be verified yet). Answers offline from the cached
2163
+ * license; like paid access, `active` needs a license check within 48 hours. `isPaid()` and
2164
+ * `hasFeature()` do not include the trial: grant trial access with `(await getTrial())?.active`.
2165
+ */
2166
+ async getTrial(options = {}) {
2167
+ await this.getEntitlement(options);
2168
+ return this.entitlements.getTrial();
2169
+ }
1753
2170
  /** True when any active/grace entitlement exists, or the given `sku` is active/grace. */
1754
2171
  async isPaid(sku) {
1755
2172
  return isEntitled(await this.getEntitlement(), sku);
@@ -1833,6 +2250,41 @@
1833
2250
  throw this.reportError(error);
1834
2251
  }
1835
2252
  }
2253
+ /**
2254
+ * Turns on the cloud copy of the extension's settings (`@extenshi/storage`): the
2255
+ * hosted restore page shows the storage disclosure and the buyer confirms with
2256
+ * the code from the purchase email. `cloudBackup` in the result says whether it is
2257
+ * on. Buyers only; consent is recorded by the server.
2258
+ */
2259
+ enableCloudBackup(options = {}) {
2260
+ return this.restorePurchase({ ...options, purpose: 'storage' });
2261
+ }
2262
+ /**
2263
+ * The storage token for `ExtenshiStorage.create({ cloud: { getToken } })`, or null
2264
+ * while cloud backup is off on this installation. Extension pages and background
2265
+ * only: it rejects in a content script, and must never be sent to one.
2266
+ */
2267
+ async cloudBackupToken() {
2268
+ return this.backup.token();
2269
+ }
2270
+ /** Turns cloud backup off on this installation: revokes its token. The cloud copy stays. */
2271
+ async disableCloudBackup() {
2272
+ try {
2273
+ await this.backup.disable();
2274
+ }
2275
+ catch (error) {
2276
+ throw this.reportError(error);
2277
+ }
2278
+ }
2279
+ /** Deletes the buyer's cloud copy and turns cloud backup off on every installation. */
2280
+ async deleteCloudBackup() {
2281
+ try {
2282
+ await this.backup.delete();
2283
+ }
2284
+ catch (error) {
2285
+ throw this.reportError(error);
2286
+ }
2287
+ }
1836
2288
  /** Read-only license view. Entitlements retain cache/signature/offline semantics. */
1837
2289
  async getLicenseSummary(options = {}) {
1838
2290
  await this.initialize();
@@ -1902,6 +2354,7 @@
1902
2354
  destroy() {
1903
2355
  this.destroyed = true;
1904
2356
  this.recovery.stop();
2357
+ this.trial.stop();
1905
2358
  this.entitlements.stopAutoRefresh();
1906
2359
  this.emitter.removeAll();
1907
2360
  }
@@ -1913,8 +2366,9 @@
1913
2366
  if (!this.offerInflight) {
1914
2367
  this.offerInflight = this.api
1915
2368
  .getOffer(this.config.locale)
1916
- .then((value) => {
2369
+ .then(async (value) => {
1917
2370
  this.offer = { value, fetchedAt: this.now() };
2371
+ await this.rememberServerKey(value.entitlementPublicKey);
1918
2372
  return value;
1919
2373
  })
1920
2374
  .finally(() => {
@@ -1923,8 +2377,88 @@
1923
2377
  }
1924
2378
  return this.offerInflight;
1925
2379
  }
1926
- async getPublicKey() {
1927
- return this.config.entitlementPublicKey ?? (await this.fetchOffer()).entitlementPublicKey;
2380
+ get serverKeyStorageKey() {
2381
+ return `extenshi-pay:${this.config.publishableKey}:entitlementPublicKey`;
2382
+ }
2383
+ async readSavedServerKey() {
2384
+ try {
2385
+ const value = await this.storage.get(this.serverKeyStorageKey);
2386
+ return typeof value === 'string' && PUBLIC_KEY_RE.test(value) ? value : null;
2387
+ }
2388
+ catch {
2389
+ return null;
2390
+ }
2391
+ }
2392
+ /**
2393
+ * Keeps the server's key next to the license cache so a restart with no network can verify it.
2394
+ * Not with a bundled key: that one already covers the restart, and storage stays untrusted.
2395
+ */
2396
+ async rememberServerKey(key) {
2397
+ if (typeof key !== 'string' || !PUBLIC_KEY_RE.test(key))
2398
+ return;
2399
+ this.serverKey = key;
2400
+ if (this.config.entitlementPublicKey || this.config.mock)
2401
+ return;
2402
+ try {
2403
+ if ((await this.readSavedServerKey()) !== key)
2404
+ await this.storage.set(this.serverKeyStorageKey, key);
2405
+ }
2406
+ catch (error) {
2407
+ logger.debug('signing key not saved', error);
2408
+ }
2409
+ }
2410
+ /**
2411
+ * A license verified with the saved key alone is checked against the server once per start:
2412
+ * when the server's key differs (rotation, or an edited storage) the license is fetched again,
2413
+ * and dropped if it does not verify. Offline, the saved key stands until `offlineUntil`.
2414
+ */
2415
+ async confirmSavedServerKey() {
2416
+ const used = this.entitlements.verifiedKey;
2417
+ if (this.destroyed || !used || used === this.serverKey || used === this.config.entitlementPublicKey)
2418
+ return;
2419
+ try {
2420
+ if ((await this.fetchOffer()).entitlementPublicKey === used || this.destroyed)
2421
+ return;
2422
+ }
2423
+ catch {
2424
+ return;
2425
+ }
2426
+ try {
2427
+ await this.entitlements.refresh();
2428
+ }
2429
+ catch {
2430
+ await this.entitlements.reverify().catch((error) => this.reportError(error));
2431
+ }
2432
+ }
2433
+ get trialStartKey() {
2434
+ return `extenshi-pay:${this.config.publishableKey}:trialStartedAt`;
2435
+ }
2436
+ /** The synced trial start, or null (none, malformed, or storage.sync unavailable). */
2437
+ async readTrialStartHint() {
2438
+ if (!this.syncStorage)
2439
+ return null;
2440
+ try {
2441
+ const value = await this.syncStorage.get(this.trialStartKey);
2442
+ return typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
2443
+ }
2444
+ catch {
2445
+ return null;
2446
+ }
2447
+ }
2448
+ /** Syncs the verified trial start, keeping the earliest one seen. Never the installation id. */
2449
+ async rememberTrialStart() {
2450
+ const trial = this.entitlements.getTrial();
2451
+ if (!this.syncStorage || !trial)
2452
+ return;
2453
+ try {
2454
+ const synced = await this.readTrialStartHint();
2455
+ if (synced && Date.parse(synced) <= Date.parse(trial.startedAt))
2456
+ return;
2457
+ await this.syncStorage.set(this.trialStartKey, trial.startedAt);
2458
+ }
2459
+ catch (error) {
2460
+ logger.debug('trial start not synced', error);
2461
+ }
1928
2462
  }
1929
2463
  reportError(error) {
1930
2464
  const err = ExtenshiPayError.from(error);
@@ -1938,8 +2472,10 @@
1938
2472
  exports.CHECKOUT_POLL_INTERVAL_MS = CHECKOUT_POLL_INTERVAL_MS;
1939
2473
  exports.CHECKOUT_TIMEOUT_MS = CHECKOUT_TIMEOUT_MS;
1940
2474
  exports.CheckoutManager = CheckoutManager;
2475
+ exports.CloudBackup = CloudBackup;
1941
2476
  exports.DEFAULT_API_URL = DEFAULT_API_URL;
1942
2477
  exports.DEFAULT_CACHE_TTL_MS = DEFAULT_CACHE_TTL_MS;
2478
+ exports.DEFAULT_TRIAL_ENDING_DAYS = DEFAULT_TRIAL_ENDING_DAYS;
1943
2479
  exports.EMPTY_ENTITLEMENT = EMPTY_ENTITLEMENT;
1944
2480
  exports.END_USER_REF_STORAGE_KEY = END_USER_REF_STORAGE_KEY;
1945
2481
  exports.ERROR_CODES = ERROR_CODES;
@@ -1967,10 +2503,13 @@
1967
2503
  exports.PAY_OFFER_KINDS = PAY_OFFER_KINDS;
1968
2504
  exports.PAY_PUBLISHABLE_KEY_HEX_LENGTH = PAY_PUBLISHABLE_KEY_HEX_LENGTH;
1969
2505
  exports.PAY_PUBLISHABLE_KEY_PREFIX = PAY_PUBLISHABLE_KEY_PREFIX;
2506
+ exports.PAY_REGIONAL_ACCESS_SKU = PAY_REGIONAL_ACCESS_SKU;
2507
+ exports.PAY_RESTORE_PURPOSES = PAY_RESTORE_PURPOSES;
1970
2508
  exports.PAY_SKU_RE = PAY_SKU_RE;
1971
2509
  exports.PAY_WITHDRAWAL_WAIVER_VERSION = PAY_WITHDRAWAL_WAIVER_VERSION;
1972
2510
  exports.PayApi = PayApi;
1973
2511
  exports.RecoveryManager = RecoveryManager;
2512
+ exports.STORAGE_TOKEN_RE = STORAGE_TOKEN_RE;
1974
2513
  exports.TRPC_PATH = TRPC_PATH;
1975
2514
  exports.VERSION = VERSION;
1976
2515
  exports.applyLocalExpiry = applyLocalExpiry;
@@ -1980,6 +2519,7 @@
1980
2519
  exports.collectFeatures = collectFeatures;
1981
2520
  exports.createRecoveryStorage = createRecoveryStorage;
1982
2521
  exports.createStorage = createStorage;
2522
+ exports.createSyncStorage = createSyncStorage;
1983
2523
  exports.getOrCreateEndUserRef = getOrCreateEndUserRef;
1984
2524
  exports.hasFeature = hasFeature;
1985
2525
  exports.isEntitled = isEntitled;